die SVGs für Weichenkörper und Parallelweischen sind updated
This commit is contained in:
@@ -1,125 +0,0 @@
|
||||
import os
|
||||
import json
|
||||
import re
|
||||
import shutil
|
||||
|
||||
def extract_sivasnr_from_svg(filename):
|
||||
"""
|
||||
Extracts the sivasnr (numeric ID) from the SVG filename.
|
||||
Example: "DeltaWeiche_1400_700_M_834372400.svg" → "834372400"
|
||||
"""
|
||||
match = re.search(r'_(\d+)\.svg$', filename)
|
||||
return match.group(1) if match else None
|
||||
|
||||
def convert_svg_to_xml(svg_path, output_folder):
|
||||
"""
|
||||
Converts an SVG file to an XML file (renames it) and saves it in `output_folder`.
|
||||
Returns the relative path in the format: "SSG/shapes/svg/{sivasnr}.xml"
|
||||
"""
|
||||
os.makedirs(output_folder, exist_ok=True)
|
||||
sivasnr = extract_sivasnr_from_svg(os.path.basename(svg_path))
|
||||
if not sivasnr:
|
||||
raise ValueError(f"Could not extract sivasnr from SVG: {svg_path}")
|
||||
|
||||
xml_filename = f"{sivasnr}.xml"
|
||||
xml_relative_path = f"SSG/shapes/svg/{xml_filename}" # Format: "SSG/shapes/svg/834372400.xml"
|
||||
xml_abs_path = os.path.join(output_folder, xml_filename)
|
||||
|
||||
# Copy SVG to XML (same content, just renamed)
|
||||
shutil.copy2(svg_path, xml_abs_path)
|
||||
return xml_relative_path # Return the relative path for TXT file
|
||||
|
||||
def update_txt_srcsvg(txt_path, new_srcsvg_value):
|
||||
"""
|
||||
Updates the "srcSVG" field in a TXT file with the relative path.
|
||||
Format: "SSG/shapes/svg/{sivasnr}.xml"
|
||||
"""
|
||||
try:
|
||||
with open(txt_path, 'r', encoding='utf-8') as f:
|
||||
data = json.load(f)
|
||||
|
||||
data["srcSVG"] = new_srcsvg_value # Write the relative path
|
||||
|
||||
with open(txt_path, 'w', encoding='utf-8') as f:
|
||||
json.dump(data, f, indent=4, ensure_ascii=False)
|
||||
|
||||
return True
|
||||
except Exception as e:
|
||||
print(f"❌ Failed to update {txt_path}: {str(e)}")
|
||||
return False
|
||||
|
||||
def process_svg_files(svg_folder, prorps_folder, output_folder="shapes/svg"):
|
||||
"""
|
||||
Processes all SVG files:
|
||||
1. Extracts sivasnr.
|
||||
2. Converts SVG to XML in `output_folder`.
|
||||
3. Updates the TXT file with "SSG/shapes/svg/{sivasnr}.xml".
|
||||
"""
|
||||
if not os.path.exists(svg_folder):
|
||||
print(f"❌ Error: SVG folder not found: {svg_folder}")
|
||||
return
|
||||
|
||||
if not os.path.exists(prorps_folder):
|
||||
print(f"❌ Error: Prorps folder not found: {prorps_folder}")
|
||||
return
|
||||
|
||||
os.makedirs(output_folder, exist_ok=True)
|
||||
svg_files = [f for f in os.listdir(svg_folder) if f.endswith('.svg')]
|
||||
total_files = len(svg_files)
|
||||
success_count = 0
|
||||
failed_count = 0
|
||||
|
||||
print(f"\n🔍 Found {total_files} SVG files in: {svg_folder}")
|
||||
print(f"📂 TXT files will be read from: {prorps_folder}")
|
||||
print(f"💾 XML files will be saved to: {output_folder}\n")
|
||||
|
||||
for svg_filename in svg_files:
|
||||
svg_path = os.path.join(svg_folder, svg_filename)
|
||||
sivasnr = extract_sivasnr_from_svg(svg_filename)
|
||||
|
||||
if not sivasnr:
|
||||
print(f"❌ Skipping {svg_filename}: Could not extract sivasnr.")
|
||||
failed_count += 1
|
||||
continue
|
||||
|
||||
print(f"🔄 Processing: {svg_filename} (sivasnr={sivasnr})")
|
||||
|
||||
try:
|
||||
# Step 1: Convert SVG to XML and get relative path
|
||||
xml_relative_path = convert_svg_to_xml(svg_path, output_folder)
|
||||
print(f" ✅ Converted to XML: {xml_relative_path}")
|
||||
|
||||
# Step 2: Update TXT file with relative path
|
||||
txt_path = os.path.join(prorps_folder, f"{sivasnr}.txt")
|
||||
if not os.path.exists(txt_path):
|
||||
print(f" ❌ TXT file not found: {os.path.basename(txt_path)}")
|
||||
failed_count += 1
|
||||
continue
|
||||
|
||||
if update_txt_srcsvg(txt_path, xml_relative_path):
|
||||
print(f" ✅ Updated TXT: {os.path.basename(txt_path)}")
|
||||
success_count += 1
|
||||
else:
|
||||
failed_count += 1
|
||||
|
||||
except Exception as e:
|
||||
print(f" ❌ Error processing {svg_filename}: {str(e)}")
|
||||
failed_count += 1
|
||||
|
||||
# Print summary
|
||||
print("\n📊 Processing Summary:")
|
||||
print(f" - Total SVG files: {total_files}")
|
||||
print(f" - Successfully processed: {success_count}")
|
||||
print(f" - Failed: {failed_count}")
|
||||
if total_files > 0:
|
||||
print(f" - Success rate: {(success_count / total_files) * 100:.2f}%")
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
# Configuration - modify these paths as needed
|
||||
SVG_FOLDER = r"C:\Users\y.wang\Documents\SSG-Ruledesigner-Konfigurator\SVGs\Omniflo\Weichen\outputdir" # Folder containing SVG files
|
||||
PRORPS_FOLDER = r"C:\Program Files\RuleDesigner\RDConfigurator Fusion\WebApi\Editor2D\SSG\shapes\props" # Folder containing txt files
|
||||
OUTPUT_FOLDER = r"C:\Program Files\RuleDesigner\RDConfigurator Fusion\WebApi\Editor2D\SSG\shapes\svg"
|
||||
# Start processing
|
||||
process_svg_files(SVG_FOLDER, PRORPS_FOLDER, OUTPUT_FOLDER)
|
||||
print("\nProcessing complete.")
|
||||
@@ -1,150 +0,0 @@
|
||||
"""
|
||||
SVG XML Batch Modifier Script
|
||||
|
||||
This script:
|
||||
1. Reads a JSON array of items
|
||||
2. For each item, extracts the "Sivasnr" value
|
||||
3. Locates and modifies the corresponding XML file
|
||||
4. Provides comprehensive reporting
|
||||
"""
|
||||
|
||||
import json
|
||||
import os
|
||||
import xml.etree.ElementTree as ET
|
||||
from xml.etree.ElementTree import Element, SubElement, tostring
|
||||
|
||||
def process_xml_file(xml_path):
|
||||
"""
|
||||
Process a single XML file with proper namespace handling
|
||||
Returns modification statistics
|
||||
"""
|
||||
try:
|
||||
tree = ET.parse(xml_path)
|
||||
root = tree.getroot()
|
||||
|
||||
# Register and handle SVG namespace
|
||||
ET.register_namespace('', 'http://www.w3.org/2000/svg')
|
||||
namespaces = {'svg': 'http://www.w3.org/2000/svg'}
|
||||
|
||||
stats = {
|
||||
'ffe31b_groups': 0,
|
||||
'ec2525_groups': 0,
|
||||
'elements_modified': 0,
|
||||
'modified': False
|
||||
}
|
||||
|
||||
# Process all group elements
|
||||
for g in root.findall('.//svg:g', namespaces):
|
||||
stroke = g.get('stroke')
|
||||
|
||||
if stroke == "#ffe31b":
|
||||
stats['ffe31b_groups'] += 1
|
||||
|
||||
if 'stroke-width' in g.attrib:
|
||||
del g.attrib['stroke-width']
|
||||
stats['modified'] = True
|
||||
if 'stroke-miterlimit' in g.attrib:
|
||||
del g.attrib['stroke-miterlimit']
|
||||
stats['modified'] = True
|
||||
|
||||
for child in g.findall('.//svg:path', namespaces):
|
||||
child.set('stroke-width', '1px')
|
||||
stats['elements_modified'] += 1
|
||||
stats['modified'] = True
|
||||
|
||||
elif stroke == "#ec2525":
|
||||
stats['ec2525_groups'] += 1
|
||||
|
||||
for attr in ['stroke', 'stroke-width', 'stroke-linejoin']:
|
||||
if attr in g.attrib:
|
||||
del g.attrib[attr]
|
||||
stats['modified'] = True
|
||||
|
||||
for child in g.findall('.//svg:path[@stroke-width="1px"]', namespaces):
|
||||
del child.attrib['stroke-width']
|
||||
child.set('style', 'stroke:#ec2525;stroke-width:2px')
|
||||
stats['elements_modified'] += 1
|
||||
stats['modified'] = True
|
||||
|
||||
# Save changes if modified
|
||||
if stats['modified']:
|
||||
xml_str = ET.tostring(root, encoding='unicode')
|
||||
xml_str = xml_str.replace('><', '>\n<').replace('</svg>', '\n</svg>')
|
||||
|
||||
with open(xml_path, 'w', encoding='utf-8') as f:
|
||||
f.write(xml_str)
|
||||
|
||||
return stats
|
||||
|
||||
except Exception as e:
|
||||
print(f" Error processing file: {str(e)}")
|
||||
return None
|
||||
|
||||
def main():
|
||||
"""
|
||||
Main processing function
|
||||
"""
|
||||
json_path=os.environ.get("JSON_PATH","JSON")
|
||||
json_file_path = os.path.join(json_path,"omniflo_weichen_output.json")
|
||||
svg_folder_path = os.environ.get("XML_PATH","svg")
|
||||
|
||||
try:
|
||||
# Read and parse JSON file
|
||||
with open(json_file_path, 'r', encoding='utf-8') as f:
|
||||
data = json.load(f)
|
||||
|
||||
# Verify we have a list of items
|
||||
if not isinstance(data, list):
|
||||
print("Error: JSON data should be an array of items")
|
||||
return
|
||||
|
||||
print(f"\nFound {len(data)} items in JSON file")
|
||||
|
||||
# Process each item in the JSON array
|
||||
for index, item in enumerate(data, 1):
|
||||
if not isinstance(item, dict):
|
||||
print(f"\nItem {index}: Not a dictionary, skipping")
|
||||
continue
|
||||
|
||||
sivasnr = item.get("Sivasnr")
|
||||
if not sivasnr:
|
||||
print(f"\nItem {index}: Missing 'Sivasnr' value, skipping")
|
||||
continue
|
||||
|
||||
print(f"\nProcessing item {index}: Sivasnr = {sivasnr}")
|
||||
|
||||
# Build XML filename and path
|
||||
xml_filename = f"{sivasnr}.xml"
|
||||
xml_path = os.path.join(svg_folder_path, xml_filename)
|
||||
|
||||
if not os.path.exists(xml_path):
|
||||
print(f" XML file not found: {xml_path}")
|
||||
continue
|
||||
|
||||
print(f" Found XML file: {xml_path}")
|
||||
|
||||
# Process the XML file
|
||||
stats = process_xml_file(xml_path)
|
||||
|
||||
if stats is None:
|
||||
print(" Processing failed")
|
||||
elif stats['modified']:
|
||||
print(" File successfully modified")
|
||||
print(f" - #ffe31b groups: {stats['ffe31b_groups']}")
|
||||
print(f" - #ec2525 groups: {stats['ec2525_groups']}")
|
||||
print(f" - Elements modified: {stats['elements_modified']}")
|
||||
else:
|
||||
print(" No modifications needed")
|
||||
|
||||
print("\nProcessing complete")
|
||||
|
||||
except FileNotFoundError:
|
||||
print("\nError: JSON file not found")
|
||||
except json.JSONDecodeError:
|
||||
print("\nError: Invalid JSON format")
|
||||
except Exception as e:
|
||||
print(f"\nUnexpected error: {str(e)}")
|
||||
|
||||
if __name__ == "__main__":
|
||||
print("SVG XML Batch Modifier - Starting execution")
|
||||
main()
|
||||
@@ -1,12 +0,0 @@
|
||||
@echo off
|
||||
|
||||
set OFWeiche_PATH=%~dp0
|
||||
|
||||
set XML_PATH=C:\Program Files\RuleDesigner\RDConfigurator Fusion\WebApi\Editor2D\SSG\shapes\svg
|
||||
|
||||
set JSON_PATH=%OFWeiche_PATH%JSON
|
||||
|
||||
python 5_OFWeiche_SVG_XML_Modifier_Script.py
|
||||
|
||||
|
||||
pause
|
||||
Reference in New Issue
Block a user