2025-05-16 18:15:31 +04:00
2025-05-16 18:15:31 +04:00
2025-05-16 18:15:31 +04:00
2025-05-16 18:15:31 +04:00
2025-05-16 18:15:31 +04:00
2025-05-16 18:15:31 +04:00
2025-05-16 18:15:31 +04:00
2025-05-16 18:15:31 +04:00
2025-05-16 18:15:31 +04:00
2025-05-16 18:15:31 +04:00
2025-05-16 18:15:31 +04:00
2025-05-16 18:15:31 +04:00
2025-05-16 18:15:31 +04:00

SVG Processor Tool

Overview

A desktop application built with Python and Tkinter for extracting elements from SVG files and converting them into a JSON format suitable for automation systems, specifically Ignition SCADA. It allows users to process SVGs, map elements based on types and labels, and export the configuration as a structured Ignition project (zip file).

Features

  • Graphical User Interface (GUI): Easy-to-use interface built with Tkinter.
  • SVG Parsing: Supports various SVG elements (rect, circle, ellipse, line, polyline, polygon, path, g).
  • Transformation Handling: Processes complex SVG transformations (translate, scale, rotate, matrix).
  • Element Mapping:
    • Configure mappings based on SVG element type (rect, path, etc.).
    • Use Label Prefixes for specific element configurations.
    • Define target Element Type and Props Path for Ignition components.
    • Specify Size (WxH) and Offset (X,Y) for positioning.
    • Add Final Prefix and Final Suffix for consistent naming.
  • Configuration Management: Saves and loads settings (SVG path, mappings, project details) to a config.json file.
  • SCADA Export:
    • Exports the processed configuration as an Ignition SCADA project.
    • Allows specifying Project Title, View Name, Ignition Base Directory, and optional View Path.
    • Supports setting a Background SVG URL for the view.
    • Provides an option to choose a Custom Export Location for the generated files.
    • Packages the output (view.json, resource.json, project.json) into a ZIP archive ready for Ignition import.
  • Logging: Displays processing logs and errors within the GUI.
  • Packaging: Includes a SVG_Processor.spec file for building a distributable executable using PyInstaller.

Dependencies

The SVG Processor Tool relies on several key Python libraries to function. These are listed in requirements.txt and should be installed in your Python environment (preferably a virtual environment) before running from source.

  • lxml (>=4.9.0): A powerful and Pythonic library for XML and HTML processing. It is used extensively for parsing SVG files, traversing the SVG DOM tree, and extracting element attributes. Role: Core SVG parsing and XML manipulation.

  • numpy (>=1.21.0): A fundamental package for scientific computing with Python. It provides support for large, multi-dimensional arrays and matrices, along with a collection of mathematical functions to operate on these arrays. Role: Handling matrix transformations (translation, rotation, scaling) of SVG elements efficiently.

  • Pillow (PIL Fork) (>=9.0.0): The Python Imaging Library (Fork). It adds image processing capabilities to your Python interpreter. *Role: Primarily used for loading and handling the application icon (.png format) to display in the Tkinter window's title bar and potentially for other image-related tasks if features are expanded.

  • pyinstaller (>=6.0.0): A tool used to package Python applications and all their dependencies into a single standalone executable. *Role: Not a runtime dependency for the source code, but a development dependency for creating distributable versions of the SVG Processor Tool.

  • svg.path (Implicit or to be added to requirements.txt): A library for parsing SVG path data strings (the d attribute of <path> elements). It can break down complex path definitions into individual segments like lines, arcs, and curves, making them easier to process and transform. Role: Parsing and interpreting complex SVG <path> element data for accurate geometric processing.

(Note: Ensure you install these using pip install -r requirements.txt when setting up to run from source.)

Installation

Prerequisites

  • Python 3.6+
  • Required Python packages (see requirements.txt):
    • lxml (for SVG parsing)
    • numpy (for matrix transformations)
    • Pillow (for icon handling, optional but recommended)
    • svg.path (for path parsing)

Running from Source

  1. Clone the repository:
    git clone <repository-url>
    cd svgprocessor
    
  2. Set up a virtual environment (recommended):
    python -m venv venv
    # Activate (Windows)
    .\venv\Scripts\activate
    # Activate (macOS/Linux)
    source venv/bin/activate
    
  3. Install dependencies:
    pip install -r requirements.txt
    
  4. Run the application:
    python app_runner.py
    

Building Executable with PyInstaller

  1. Ensure PyInstaller is installed (pip install pyinstaller).

  2. Run PyInstaller using the provided spec file:

    pyinstaller SVG_Processor.spec
    
  3. The executable will be located in the dist/SVG_Processor directory.

    (Note: The .spec file is configured for Windows. You may need adjustments for macOS or Linux, particularly regarding icon formats and library paths.)

Usage

  1. Launch the application (python app_runner.py or run the executable).
  2. Select SVG File: Click "Browse" to choose the SVG file you want to process.
  3. Configure Project Settings:
    • Enter Project Title and View Name.
    • Specify the Ignition Base Dir (path to your Ignition projects folder).
    • Optionally, set View Path (e.g., Folder/Subfolder) and Background SVG URL.
    • Adjust Image Width/Height and Default View Width/Height as needed.
  4. Configure Element Mappings (Element Mapping Tab):
    • Click "Add New Mapping" to create rules for converting SVG elements.
    • For each mapping:
      • SVG Type: The type of SVG element (e.g., rect, path).
      • Label Prefix: (Optional) A prefix found in the SVG element's ID or label to trigger this specific mapping.
      • Element Type: The target Ignition component type (e.g., ia.display.view, ia.display.label).
      • Props Path: The path to the Ignition component definition (e.g., Symbol-Views/Equipment-Views/Status).
      • Size (WxH): Default width and height for the created component.
      • Offset (X,Y): Adjust the component's position relative to the SVG element's calculated position.
      • Final Prefix/Suffix: Text added to the beginning/end of the generated component name.
    • Use the X button to remove mappings.
  5. Process SVG: Click the "Process SVG" button.
    • Check the Results and Logs tabs for output and any errors.
  6. Export SCADA Project: Click the "Export SCADA Project" button.
    • A file dialog will appear, allowing you to choose where to save the generated .zip file containing the Ignition project structure.

Configuration File (config.json)

The application saves user settings (last used SVG path, project details, element mappings) to config.json in the application's directory. This file is loaded automatically on startup.

Technical Details

Project Structure

  • app_runner.py: Main entry point, initializes the Tkinter application and handles setup.
  • gui/: Contains modules related to the graphical user interface.
    • svg_processor_gui.py: The main application window class.
    • element_mapping_frame.py: Manages the element mapping configuration grid.
    • notebook_manager.py: Handles the tabbed interface (Element Mapping, Results, Logs).
    • theme_manager.py: Manages basic application styling.
    • ... (other potential GUI components)
  • processing/: Contains modules for SVG parsing and transformation logic.
    • processor.py: Orchestrates the SVG processing workflow.
    • element_processor.py: Handles individual element extraction and mapping.
    • inkscape_transform.py: Parses SVG transform attributes and applies matrix math.
    • element_mapper.py: Finds the correct mapping rule for an element.
    • json_builder.py: Constructs the final JSON output for elements.
    • scada_exporter.py: Creates the Ignition project structure and zip file.
  • config_manager.py: Handles loading and saving the config.json file.
  • utils.py: Contains utility functions (e.g., resource path handling, stdout redirection, icon loading).
  • requirements.txt: Lists Python dependencies.
  • SVG_Processor.spec: Configuration file for PyInstaller.
  • README.md: This file.
  • USER_MANUAL.md: Detailed user guide.

SVG Processing Workflow

  1. Load SVG file using lxml.
  2. Traverse the SVG DOM tree.
  3. For each relevant element (rect, path, etc.):
    • Parse its attributes (ID, transform, position, size).
    • Calculate the final transformation matrix by accumulating transforms from parent groups (g elements).
    • Determine the element's bounding box or key points.
    • Apply the accumulated transformation matrix to find the final position and size in the view coordinate system.
    • Match the element (based on type and label prefix) to a rule in the element_mappings configuration.
    • Generate a JSON object representing the corresponding Ignition component using json_builder.py.
  4. Aggregate the JSON objects.

SCADA Export Process (scada_exporter.py)

  1. Takes the processed element data and configuration settings.
  2. Creates a temporary directory structure mimicking an Ignition project:
    <temp_dir>/
    ├── project.json
    └── com.inductiveautomation.perspective/
        └── views/
            └── [Optional View Path]/
                └── [View Name]/
                    ├── view.json
                    ├── resource.json
    
  3. Generates project.json (basic project metadata).
  4. Generates view.json containing the array of processed element JSON objects.
  5. Generates resource.json (metadata for the view resource).
  6. Packages the contents of the temporary directory into a .zip archive.
  7. Cleans up the temporary directory.

License

This project is open source.

[It is recommended to replace this placeholder with a specific open-source license. For example, the MIT License is a popular choice.]

If you choose to use a specific license like the MIT License, the text might look something like this:


MIT License

Copyright (c) [Year] [Your Name/Organization Name]

Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:

The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.


Please ensure you select and include the full text of the license you intend to use.

Acknowledgments

  • Built using Python and the Tkinter standard library.
  • Leverages libraries like lxml, numpy, Pillow, and svg.path.

Testing

Automated tests are crucial for maintaining code quality and ensuring new changes don't break existing functionality. This project uses pytest for its testing framework.

Setting Up for Testing

  1. Install Testing Dependencies: If you haven't already, install pytest and pytest-cov (for coverage reports). It's best to install them within your project's virtual environment:

    pip install pytest pytest-cov
    
  2. Test File Location and Naming:

    • Tests are typically located in a dedicated tests/ directory at the root of the project.
    • Test files should be named starting with test_ (e.g., test_element_processor.py).
    • Test functions within these files should also start with test_ (e.g., def test_specific_transformation():).

Running Tests

  1. Navigate to Project Root: Open your terminal or command prompt and ensure you are in the root directory of the SVG Processor Tool project (the directory containing app_runner.py and the tests/ folder).

  2. Activate Virtual Environment: If you are using a virtual environment, make sure it's activated.

  3. Execute Pytest:

    • To run all tests:
      pytest
      
      pytest will automatically discover and run test files and functions matching the naming conventions.
    • To run tests with a coverage report (shows which parts of your code are exercised by tests):
      pytest --cov=.
      
      This command tells pytest-cov to measure coverage for the current directory (.).
    • For a more detailed coverage report in the terminal, including missing line numbers:
      pytest --cov=. --cov-report=term-missing
      
    • To generate an HTML coverage report (which is often easier to navigate):
      pytest --cov=. --cov-report=html
      
      This will create an htmlcov/ directory. Open htmlcov/index.html in a web browser to view the interactive report.

Writing Tests

  • When adding new features or fixing bugs, try to accompany your code changes with corresponding tests.
  • Tests should be independent and not rely on the state left by previous tests.
  • Use assert statements to check for expected outcomes.
  • pytest offers powerful features like fixtures (for setting up test preconditions) and parameterization (for running a test with multiple inputs). Refer to the pytest documentation for more advanced usage.

Troubleshooting

If you encounter issues while using the SVG Processor Tool, this section provides guidance on common problems and how to resolve them.

  • Application Fails to Start or Crashes Immediately:

    • Check Python Installation: Ensure you have a compatible version of Python (3.6+) installed and correctly configured in your system's PATH.
    • Dependencies Not Installed: If running from source, make sure all dependencies listed in requirements.txt are installed in your active Python environment (preferably a virtual environment). Run pip install -r requirements.txt again.
    • Corrupted Configuration: A corrupted config.json file could sometimes prevent startup. Try renaming or deleting config.json (the application will create a new default one). You will lose your saved settings by doing this.
    • Console Logs: If running python app_runner.py from a terminal/command prompt, check the console output for any error messages or tracebacks. These are invaluable for diagnosing startup issues.
  • SVG File Not Loading or Parsing Errors:

    • Invalid SVG Format: Ensure your SVG file is well-formed XML and adheres to SVG standards. You can try opening it in a web browser (like Chrome or Firefox) or a dedicated SVG editor (like Inkscape or Adobe Illustrator) to check its validity. Some SVG features from advanced editors might not be fully supported if they use non-standard XML namespaces or structures.
    • File Path Issues: Double-check that the file path selected is correct and that the application has read permissions for the file and its directory.
    • Application Logs: The "Logs" tab within the application is the primary source for diagnosing SVG processing issues. It will often indicate which element caused a problem or if there were parsing errors.
  • Elements Not Appearing or Incorrectly Positioned/Sized in Export:

    • Transformation Complexity: Highly complex or unusual transform attributes in the SVG (e.g., deeply nested transforms, unsupported SVG 2.0 transform functions if any) might not be interpreted as expected by all parsers. Simplify transformations in your SVG source if possible.
    • Mapping Rules:
      • Verify that your "Element Mapping" rules are correctly configured for the SVG Type and any Label Prefix of the problematic elements.
      • Ensure the target Element Type and Props Path (if used) in the mapping are valid for your Ignition SCADA system.
      • Check the Offset (X,Y) and Size (WxH) values in your mappings, as these directly affect the output.
    • Application Logs: Again, the "Logs" tab may contain warnings or information about how specific elements were processed, including their calculated transformations and applied mappings.
    • Coordinate Systems: Be mindful of SVG's coordinate system (y-axis typically points downwards). While the tool handles this, complex SVG structures might have internal coordinate systems that could be tricky.
  • Issues with PyInstaller Executable (after building):

    • Missing DLLs/Libraries (Windows): If the executable fails to run with errors like "VCRUNTIME140.dll was not found," ensure the target machine has the latest Microsoft Visual C++ Redistributable installed for the version of Python used to build the executable.
    • macOS/Linux Specifics: On macOS, you might encounter permission issues or problems related to how libraries are bundled. Ensure the executable has execute permissions. Check for console output if running the executable from a terminal.
    • Data Files Not Bundled: If your application relies on external data files (e.g., custom icons not handled by utils.py's resource_path, default templates) that are not Python modules, ensure they are correctly specified in the SVG_Processor.spec file to be included in the bundle. The current setup with resource_path in utils.py should handle the provided automation_standard_logo.png.
    • Anti-virus Software: Occasionally, anti-virus software might incorrectly flag a newly built PyInstaller executable as suspicious. Try temporarily disabling it for testing or adding an exception.
    • Console Window (or lack thereof): The .spec file controls whether a console window appears when the executable runs (using the -w or --windowed flag for no console, or -c or --console for a console). If you need to see console output from the executable for debugging, ensure it's built with the console enabled.
  • General GUI Issues (e.g., distorted elements, unresponsiveness):

    • Tkinter/Tcl Version: While less common with modern Python, very old or mismatched Tk/Tcl versions (which Tkinter relies on) could theoretically cause display issues. Ensure your Python installation is standard.
    • Application Logs: Check for any Python tracebacks or error messages in the "Logs" tab that might indicate an internal GUI error.

General Troubleshooting Tip: When in doubt, always check the "Logs" tab within the application first. It is designed to provide detailed feedback on the application's operations and is the most valuable resource for understanding what went wrong.

Contributing

Contributions to the SVG Processor Tool are welcome! Whether you're looking to report a bug, suggest an enhancement, or contribute code, your input is valued.

How to Contribute

  1. Reporting Bugs:

    • If you encounter a bug, please check the existing issues on the project's issue tracker (if available) to see if it has already been reported.
    • If not, create a new issue, providing as much detail as possible:
      • Steps to reproduce the bug.
      • Expected behavior vs. actual behavior.
      • SVG Processor Tool version (if applicable), your OS, and Python version.
      • Relevant snippets from the "Logs" tab or console output.
      • A sample SVG file that triggers the bug (if possible and not proprietary).
  2. Suggesting Enhancements or Features:

    • If you have an idea for a new feature or an improvement to an existing one, feel free to open an issue to discuss it.
    • Clearly describe the proposed enhancement and its benefits.
  3. Submitting Code (Pull Requests):

    • If you'd like to contribute code, it's generally a good idea to first discuss your proposed changes by opening an issue, especially for larger contributions.
    • Fork the repository (if applicable), create a new branch for your feature or bugfix, and then submit a pull request.
    • Ensure your code is well-commented, particularly for complex logic.
    • If possible, add or update tests that cover your changes.
    • Follow the existing code style and architectural patterns (as outlined in project_config.md and observable in the codebase) to maintain consistency.

Coding Style and Conventions

  • While no strict style guide (like PEP 8 enforcement tool) is explicitly mandated by this document, aim for clear, readable, and maintainable Python code.
  • Follow the architectural principles of modular design with separation between GUI (gui/) and processing logic (processing/) as established in the project.
  • Use descriptive names for variables, functions, and classes.
  • Comment code where the logic is not immediately obvious.

We appreciate your help in making the SVG Processor Tool better!

Description
No description provided
Readme 106 KiB
Languages
Python 100%