RD_CONF für SVG zu bearbeiten

This commit is contained in:
2025-06-24 13:30:47 +02:00
parent 9783ab756b
commit 97807e3a34
28 changed files with 3380 additions and 257 deletions
@@ -23,6 +23,7 @@
The script is designed to process SVG measurement data, perform geometric validations, and produce an enhanced dataset while providing thorough feedback about the processing results. '''
import json
import math
import os
def safe_float(value, default=0.0):
"""Safely convert value to float, return default if conversion fails"""
@@ -145,7 +146,9 @@ def process_json_file(input_file, output_file):
# Example usage
if __name__ == "__main__":
input_filename = "1_SVGErfassung_updated_new_input.json" # Replace with your input filename
output_filename = "1_SVGErfassung_updated_new_output.json" # Replace with desired output filename
json_path=os.environ.get("JSON_PATH","JSON")
input_filename = os.path.join(json_path,"1_SVGErfassung_updated_new_input.json") # Replace with your input filename
output_filename = os.path.join(json_path,"1_SVGErfassung_updated_new_output.json") # Replace with desired output filename
process_json_file(input_filename, output_filename)
@@ -13,6 +13,7 @@
Maintains aspect ratio while standardizing dimensions '''
import json
import math
import os
def process_json_item(item):
# Ensure all numeric fields are floats
@@ -144,7 +145,7 @@ def process_json_file(input_file, output_file):
with open(output_file, 'w', encoding='utf-8') as f:
json.dump(processed_data, f, indent=4, ensure_ascii=False)
print(f"Processing complete. Results saved to {output_file}")
print(f"Processing for calculations to standardize the dimensions and add connection points completed. Results saved to {output_file}")
# Print error reports
if error_reports:
@@ -168,8 +169,9 @@ def process_json_file(input_file, output_file):
# Example usage
if __name__ == "__main__":
input_filename = "1_SVGErfassung_updated_new_output.json"
output_filename = "2_calculated_px_cps_output.json"
json_path=os.environ.get("JSON_PATH","JSON")
input_filename = os.path.join(json_path,"1_SVGErfassung_updated_new_output.json")
output_filename =os.path.join(json_path,"2_calculated_px_cps_output.json")
process_json_file(input_filename, output_filename)
process_json_file(input_filename, output_filename)
@@ -30,13 +30,21 @@ def process_files(json_file_path, txt_files_dir):
# Create Sivasnr to JSON data mapping
sivasnr_mapping = {item["Sivasnr"]: item for item in json_data}
# Initialize counters
total_files = 0
processed_files = 0
skipped_files = 0
# Prepare report content
report_content = []
report_content.append(f"Modification Report - {datetime.now().strftime('%Y-%m-%d %H:%M:%S')}")
report_content.append(f"JSON Reference File: {json_file_path}")
report_content.append(f"TXT Files Directory: {txt_files_dir}")
report_content.append("="*50 + "\n")
# Process all TXT files
for txt_file_path in glob.glob(os.path.join(txt_files_dir, '*.txt')):
total_files += 1
# Extract Sivasnr from filename
sivasnr = os.path.splitext(os.path.basename(txt_file_path))[0]
@@ -50,7 +58,7 @@ def process_files(json_file_path, txt_files_dir):
# Prepare entry for this file
file_entry = []
file_entry.append(f"\nProcessing file: {txt_file_path}")
file_entry.append(f"\nProcessing file: {os.path.basename(txt_file_path)}")
file_entry.append("="*50)
# Record old values
@@ -107,7 +115,8 @@ def process_files(json_file_path, txt_files_dir):
file_entry.append(f" y: {change['y'][0]}{change['y'][1]}")
file_entry.append(f" direction: {change['direction'][0]}{change['direction'][1]}")
file_entry.append(f"\nFile {txt_file_path} processed successfully")
processed_files += 1
file_entry.append(f"\nFile processed successfully")
file_entry.append("="*50)
# Add this file's entry to main report
@@ -116,19 +125,41 @@ def process_files(json_file_path, txt_files_dir):
# Also print to console
print("\n" + "\n".join(file_entry))
else:
print(f"\nSkipping file {txt_file_path} (no matching JSON data found)")
skipped_files += 1
# Write the report file if any changes were made
if len(report_content) > 2: # More than just the header
with open(log_file_path, 'w', encoding='utf-8') as f:
f.write("\n".join(report_content))
print(f"\nModification report saved to: {log_file_path}")
else:
print("\nNo files were modified - no report generated")
# Add processing statistics to report
report_content.append("\n" + "="*50)
report_content.append("Processing Statistics:")
report_content.append(f"Total TXT files found: {total_files}")
report_content.append(f"Total JSON records available: {len(json_data)}")
report_content.append(f"Successfully processed: {processed_files}")
report_content.append(f"Skipped files: {skipped_files}")
if total_files > 0:
success_rate = (processed_files / len(json_data)) * 100
report_content.append(f"Success rate: {success_rate:.2f}%")
report_content.append("="*50)
# Print statistics to console
print("\n" + "="*50)
print("Processing Statistics:")
print(f"Total TXT files found: {total_files}")
print(f"Total JSON records available: {len(json_data)}")
print(f"Successfully processed: {processed_files}")
print(f"Skipped files: {skipped_files}")
if total_files > 0:
success_rate = (processed_files / len(json_data)) * 100
print(f"Success rate: {success_rate:.2f}%")
print("="*50 + "\n")
# Write the report file
with open(log_file_path, 'w', encoding='utf-8') as f:
f.write("\n".join(report_content))
print(f"Modification report saved to: {log_file_path}")
# Example usage
if __name__ == "__main__":
json_file_path = "2_calculated_px_cps_output.json"
txt_files_dir = "C:/Program Files/RuleDesigner/RDConfigurator Fusion/WebApi/Editor2D/SSG/shapes/props"
json_path = os.environ.get("JSON_PATH", "JSON")
json_file_path = os.path.join(json_path, "2_calculated_px_cps_output.json")
txt_files_dir = os.environ.get("PROPS_PATH", "props")
process_files(json_file_path, txt_files_dir)
print("\nAll files processed!")
print("\nProcessing complete!")
@@ -84,9 +84,9 @@ def main():
"""
Main processing function
"""
# Configure paths
json_file_path = r"C:\Users\y.wang\Documents\SSG-Ruledesigner-Konfigurator\SVGs\Omniflo\python\OFBogen\1_SVGErfassung_updated_new_input.json"
svg_folder_path = r"C:\Program Files\RuleDesigner\RDConfigurator Fusion\WebApi\Editor2D\SSG\shapes\svg"
json_path=os.environ.get("JSON_PATH","JSON")
json_file_path = os.path.join(json_path,"1_SVGErfassung_updated_new_output.json")
svg_folder_path = os.environ.get("XML_PATH","svg")
try:
# Read and parse JSON file
@@ -0,0 +1,12 @@
@echo off
set OFBogen_PATH=%~dp0
set XML_PATH=C:\Program Files\RuleDesigner\RDConfigurator Fusion\WebApi\Editor2D\SSG\shapes\svg
set JSON_PATH=%OFBogen_PATH%JSON
python 4_OFBogen_SVG_XML_Modifier_Script.py
pause
@@ -0,0 +1,12 @@
@echo off
set OFBogen_PATH=%~dp0
set PROPS_PATH=C:\Program Files\RuleDesigner\RDConfigurator Fusion\WebApi\Editor2D\SSG\shapes\props
set JSON_PATH=%OFBogen_PATH%JSON
python 1_calculate_ture_width_and_height_dimensions_with_profile_width.py
python 2_calculations_to_standardize_the_dimensions_and_add_connection_points.py
python 3_update_dimensions_and_connection_points_in_props.py
pause
+17
View File
@@ -0,0 +1,17 @@
import json
# 1. 读取 JSON 文件
with open("omniflo_weichen.json", "r", encoding="utf-8") as f:
data = json.load(f) # data 是一个列表(数组)
# 2. 遍历并清理数据
for item in data:
if isinstance(item, dict) and item.get("SivasnrTEF") is None:
item.pop("TEFWeiche_center_line_width_mm", None) # 安全删除,键不存在时不报错
item.pop("TEFWeiche_center_line_height_mm", None)
item.pop("TEFWeiche_CP1_x_mm", None) # 安全删除,键不存在时不报错
item.pop("TEFWeiche_CP1_y_mm", None)
# 3. 保存修改后的 JSON
with open("omniflo_weichen.json", "w", encoding="utf-8") as f:
json.dump(data, f, indent=2, ensure_ascii=False) # 保持中文/特殊字符
@@ -0,0 +1,57 @@
import json
def check_null_fields_in_items_with_sivasnrtef_null(json_file_path):
try:
with open(json_file_path, 'r', encoding='utf-8') as file:
data = json.load(file)
except FileNotFoundError:
print(f"Error: The file '{json_file_path}' does not exist.")
return
except json.JSONDecodeError:
print(f"Error: The file '{json_file_path}' is not a valid JSON file.")
return
if not isinstance(data, list):
print("Error: The JSON file should contain an array of objects.")
return
items_with_sivasnrtef_null = [item for item in data if isinstance(item, dict) and item.get("SivasnrTEF") is None]
if not items_with_sivasnrtef_null:
print("No items with 'SivasnrTEF': null found in the JSON file.")
return
# 初始化统计计数器
count_only_sivasnrtef_null = 0
count_with_other_nulls = 0
print(f"Found {len(items_with_sivasnrtef_null)} item(s) with 'SivasnrTEF': null")
print("-" * 50)
for idx, item in enumerate(items_with_sivasnrtef_null, 1):
null_fields = [key for key, value in item.items() if value is None and key != "SivasnrTEF"]
# 打印关键识别信息
sivasnr = item.get("Sivasnr", "Not found")
profil_typ = item.get("ProfilTyp", "Not found")
print(f"\nItem {idx}: Sivasnr='{sivasnr}', ProfilTyp='{profil_typ}'")
if null_fields:
count_with_other_nulls += 1
print(f" → Other null fields: {null_fields}")
print(" → Full item:", item)
else:
count_only_sivasnrtef_null += 1
print(" → No other null fields found.")
# 打印统计结果
print("\n" + "="*50)
print("Statistics:")
print(f"- Items with ONLY 'SivasnrTEF' as null: {count_only_sivasnrtef_null}")
print(f"- Items with 'SivasnrTEF' AND other null fields: {count_with_other_nulls}")
print("="*50)
# Example usage:
json_file_path = "omniflo_weichen.json" # Replace with your JSON file path
check_null_fields_in_items_with_sivasnrtef_null(json_file_path)
File diff suppressed because it is too large Load Diff
@@ -0,0 +1,622 @@
import json
import math
def modify_json_values(json_file):
# 常量定义
BogenProfileWidth = 42.080
WeichenkProfileWidth = 42.000
WeichenGerade = 360.000
# 读取JSON文件
with open(json_file, 'r', encoding='utf-8') as f:
data = json.load(f)
process_einzelweiche_items(data, WeichenkProfileWidth,BogenProfileWidth, WeichenGerade)
process_doppelweiche_items(data, BogenProfileWidth, WeichenGerade)
process_dreifachweiche_items(data, WeichenkProfileWidth)
# 询问是否保存
save_choice = input("\n是否保存所有修改? (直接回车保存,输入n取消): ").lower()
if save_choice == 'n':
print("所有修改未保存")
else:
with open(json_file, 'w', encoding='utf-8') as f:
json.dump(data, f, indent=2, ensure_ascii=False)
print("所有修改已保存!")
def process_einzelweiche_items(data, WeichenkProfileWidth,BogenProfileWidth, WeichenGerade): # 筛选符合条件的项
filtered_items = [
item for item in data
if (item.get("SivasnrTEF") is None and
item.get("KurvenRichtung") == 1 and
item.get("Schaltungstyp") == "M")
]
print(f"共找到 {len(filtered_items)} 项符合条件的记录")
print("="*50)
# 遍历每一项
for idx, item in enumerate(filtered_items, 1):
print(f"\n{idx} 项:")
print(f"Sivasnr: {item['Sivasnr']}")
print(f"ProfilTyp: {item['ProfilTyp']}")
print(f"Schaltungstyp: {item['Schaltungstyp']}")
# 处理 OFWeiche_center_line_width_mm
current_value = item.get("OFWeiche_center_line_width_mm")
print(f"\n当前 OFWeiche_center_line_width_mm: {current_value}")
choice = input("是否修改? (y修改,直接回车跳过): ").lower()
if choice == 'y':
new_value = input(f"请输入新值 (当前: {current_value}): ")
try:
old_value = item["OFWeiche_center_line_width_mm"]
item["OFWeiche_center_line_width_mm"] = round(float(new_value), 3) if new_value.lower() != 'null' else None
print(f"值已更新: {old_value}{item['OFWeiche_center_line_width_mm']}")
except ValueError:
print("输入无效,保持原值")
else:
print("跳过修改")
# 处理 OFWeiche_center_line_height_mm
current_value = item.get("OFWeiche_center_line_height_mm")
print(f"\n当前 OFWeiche_center_line_height_mm: {current_value}")
choice = input("是否修改? (y修改,直接回车跳过): ").lower()
if choice == 'y':
new_value = input(f"请输入新值 (当前: {current_value}): ")
try:
old_value = item["OFWeiche_center_line_height_mm"]
item["OFWeiche_center_line_height_mm"] = round(float(new_value), 3) if new_value.lower() != 'null' else None
print(f"值已更新: {old_value}{item['OFWeiche_center_line_height_mm']}")
except ValueError:
print("输入无效,保持原值")
else:
print("跳过修改")
# 计算相关值
if (item["OFWeiche_center_line_width_mm"] is not None and
item["OFWeiche_center_line_height_mm"] is not None):
angle_rad = math.radians(item["KurvenWinkel"])
# 计算并打印基本值
old_width = item.get("Objekte_width_mm")
item["Objekte_width_mm"] = round(
(BogenProfileWidth/2 * math.cos(angle_rad)) +
item["OFWeiche_center_line_width_mm"] +
WeichenkProfileWidth/2, 3)
print(f"\nObjekte_width_mm 计算更新: {old_width}{item['Objekte_width_mm']}")
old_height = item.get("Objekte_height_mm")
if item["KurvenWinkel"] == 22.5:
item["Objekte_height_mm"] = round(
item["OFWeiche_center_line_height_mm"], 3)
else:
item["Objekte_height_mm"] = round(
(BogenProfileWidth/2 * math.sin(angle_rad)) +
item["OFWeiche_center_line_height_mm"], 3)
print(f"Objekte_height_mm 计算更新: {old_height}{item['Objekte_height_mm']}")
# 计算并打印CP点坐标
old_cp1x = item.get("OFWeiche_CP1_x_mm")
item["OFWeiche_CP1_x_mm"] = round(
(BogenProfileWidth/2 * math.sin(angle_rad)) +
item["OFWeiche_center_line_width_mm"], 3)
print(f"OFWeiche_CP1_x_mm 计算更新: {old_cp1x}{item['OFWeiche_CP1_x_mm']}")
old_cp1y = item.get("OFWeiche_CP1_y_mm")
item["OFWeiche_CP1_y_mm"] = round(
item["Objekte_height_mm"] - WeichenGerade, 3)
print(f"OFWeiche_CP1_y_mm 计算更新: {old_cp1y}{item['OFWeiche_CP1_y_mm']}")
item["OFWeiche_CP2_x_mm"] = round(item["OFWeiche_CP1_x_mm"], 3)
print(f"OFWeiche_CP2_x_mm 设置: {item['OFWeiche_CP2_x_mm']}")
item["OFWeiche_CP2_y_mm"] = round(item["Objekte_height_mm"], 3)
print(f"OFWeiche_CP2_y_mm 设置: {item['OFWeiche_CP2_y_mm']}")
item["OFWeiche_CP3_x_mm"] = round(
BogenProfileWidth/2 * math.cos(angle_rad), 3)
print(f"OFWeiche_CP3_x_mm 计算更新: {item['OFWeiche_CP3_x_mm']}")
item["OFWeiche_CP3_y_mm"] = round(
BogenProfileWidth/2 * math.sin(angle_rad), 3)
print(f"OFWeiche_CP3_y_mm 计算更新: {item['OFWeiche_CP3_y_mm']}")
# 1. 查找Schaltungstyp为P的相似项(更新所有CP点)
current_profil = item["ProfilTyp"]
if "S" in current_profil:
prefix = current_profil.rsplit(" ", 1)[0]
similar_items_p = [x for x in data
if x["ProfilTyp"].startswith(prefix) and
x["ProfilTyp"] != current_profil and
"WEICHE" in x["ProfilTyp"] and
x.get("SivasnrTEF") is None and
x.get("Schaltungstyp") == "P"]
if similar_items_p:
print(f"\n找到 {len(similar_items_p)} 个Schaltungstyp=P的相似项")
for similar in similar_items_p:
print(f"正在更新相似项: {similar['ProfilTyp']} (Sivasnr: {similar['Sivasnr']})")
# 更新所有字段包括CP点
fields_to_copy = [
"OFWeiche_center_line_width_mm",
"OFWeiche_center_line_height_mm",
"Objekte_width_mm",
"Objekte_height_mm",
"OFWeiche_CP1_x_mm",
"OFWeiche_CP1_y_mm",
"OFWeiche_CP2_x_mm",
"OFWeiche_CP2_y_mm",
"OFWeiche_CP3_x_mm",
"OFWeiche_CP3_y_mm"
]
for field in fields_to_copy:
old_val = similar.get(field)
similar[field] = item[field]
print(f" {field}: {old_val}{similar[field]}")
else:
print("没有找到Schaltungstyp=P的相似项")
# 2. 查找L→R且KurvenRichtung=2的相似项
if "S" in current_profil and "-L-" in current_profil:
r_profil = current_profil.replace("-L-", "-R-")
similar_items_r = [x for x in data
if x["ProfilTyp"] == r_profil and
x.get("SivasnrTEF") is None and
x.get("KurvenRichtung") == 2 and
x.get("Schaltungstyp") == "M"]
if similar_items_r:
print(f"\n找到 {len(similar_items_r)} 个L→R的相似项(KurvenRichtung=2)")
for similar in similar_items_r:
print(f"正在更新R型相似项: {similar['ProfilTyp']} (Sivasnr: {similar['Sivasnr']})")
# 复制基础值
base_fields = [
"OFWeiche_center_line_width_mm",
"OFWeiche_center_line_height_mm",
"Objekte_width_mm",
"Objekte_height_mm"
]
for field in base_fields:
old_val = similar.get(field)
similar[field] = item[field]
print(f" {field}: {old_val}{similar[field]}")
# 计算并打印R型特有的CP点
old_cp1x = similar.get("OFWeiche_CP1_x_mm")
similar["OFWeiche_CP1_x_mm"] = round(WeichenkProfileWidth/2, 3)
print(f" OFWeiche_CP1_x_mm (R型): {old_cp1x}{similar['OFWeiche_CP1_x_mm']}")
old_cp1y = similar.get("OFWeiche_CP1_y_mm")
similar["OFWeiche_CP1_y_mm"] = round(item["Objekte_height_mm"] - WeichenGerade, 3)
print(f" OFWeiche_CP1_y_mm (R型): {old_cp1y}{similar['OFWeiche_CP1_y_mm']}")
similar["OFWeiche_CP2_x_mm"] = similar["OFWeiche_CP1_x_mm"]
print(f" OFWeiche_CP2_x_mm (R型): 设置为 {similar['OFWeiche_CP2_x_mm']}")
old_cp2y = similar.get("OFWeiche_CP2_y_mm")
similar["OFWeiche_CP2_y_mm"] = round(item["Objekte_height_mm"], 3)
print(f" OFWeiche_CP2_y_mm (R型): {old_cp2y}{similar['OFWeiche_CP2_y_mm']}")
old_cp3x = similar.get("OFWeiche_CP3_x_mm")
similar["OFWeiche_CP3_x_mm"] = round(
similar["OFWeiche_CP1_x_mm"] + item["OFWeiche_center_line_width_mm"], 3)
print(f" OFWeiche_CP3_x_mm (R型): {old_cp3x}{similar['OFWeiche_CP3_x_mm']}")
old_cp3y = similar.get("OFWeiche_CP3_y_mm")
similar["OFWeiche_CP3_y_mm"] = round(
BogenProfileWidth/2 * math.sin(angle_rad), 3)
print(f" OFWeiche_CP3_y_mm (R型): {old_cp3y}{similar['OFWeiche_CP3_y_mm']}")
# 3. 查找该R型项的P型对应项
r_p_profil = r_profil.replace("MIT M", "MIT P")
similar_items_r_p = [x for x in data
if x["ProfilTyp"] == r_p_profil and
x.get("SivasnrTEF") is None and
x.get("Schaltungstyp") == "P"]
if similar_items_r_p:
print(f"\n找到 {len(similar_items_r_p)} 个R型P型对应项")
for similar_r_p in similar_items_r_p:
print(f"正在更新R型P型对应项: {similar_r_p['ProfilTyp']} (Sivasnr: {similar_r_p['Sivasnr']})")
fields_to_copy_r_p = [
"OFWeiche_center_line_width_mm",
"OFWeiche_center_line_height_mm",
"Objekte_width_mm",
"Objekte_height_mm",
"OFWeiche_CP1_x_mm",
"OFWeiche_CP1_y_mm",
"OFWeiche_CP2_x_mm",
"OFWeiche_CP2_y_mm",
"OFWeiche_CP3_x_mm",
"OFWeiche_CP3_y_mm"
]
for field in fields_to_copy_r_p:
old_val = similar_r_p.get(field)
similar_r_p[field] = similar[field]
print(f" {field}: {old_val}{similar_r_p[field]}")
save_choice = input(f"是否确认更新此项? (直接回车确认,输入n取消): ").lower()
if save_choice == 'n':
print("此项更新已取消")
# 恢复原值
for field in fields_to_copy_r_p:
if field in similar_r_p:
similar_r_p[field] = old_val
else:
print("没有找到R型P型对应项")
else:
print("没有找到L→R的相似项")
def process_doppelweiche_items(data,BogenProfileWidth, WeichenGerade):
# 筛选Doppelweiche类型的项
filtered_items = [
item for item in data
if (item.get("WeichenTyp") == "Doppelweiche" and
item.get("Schaltungstyp") == "M" and
item.get("SivasnrTEF") is None)
]
print(f"\n\n共找到 {len(filtered_items)} 项Doppelweiche类型记录")
print("="*50)
# 遍历每一项Doppelweiche
for idx, item in enumerate(filtered_items, 1):
print(f"\n{idx} 项Doppelweiche:")
print(f"Sivasnr: {item['Sivasnr']}")
print(f"ProfilTyp: {item['ProfilTyp']}")
print(f"Schaltungstyp: {item['Schaltungstyp']}")
print(f"KurvenWinkel: {item['KurvenWinkel']}")
# 处理 OFWeiche_center_line_width_mm
current_value = item.get("OFWeiche_center_line_width_mm")
print(f"\n当前 OFWeiche_center_line_width_mm: {current_value}")
choice = input("是否修改? (y修改,直接回车跳过): ").lower()
if choice == 'y':
new_value = input(f"请输入新值 (当前: {current_value}): ")
try:
old_value = item["OFWeiche_center_line_width_mm"]
item["OFWeiche_center_line_width_mm"] = round(float(new_value), 3) if new_value.lower() != 'null' else None
print(f"值已更新: {old_value}{item['OFWeiche_center_line_width_mm']}")
except ValueError:
print("输入无效,保持原值")
else:
print("跳过修改")
# 处理 OFWeiche_center_line_height_mm
current_value = item.get("OFWeiche_center_line_height_mm")
print(f"\n当前 OFWeiche_center_line_height_mm: {current_value}")
choice = input("是否修改? (y修改,直接回车跳过): ").lower()
if choice == 'y':
new_value = input(f"请输入新值 (当前: {current_value}): ")
try:
old_value = item["OFWeiche_center_line_height_mm"]
item["OFWeiche_center_line_height_mm"] = round(float(new_value), 3) if new_value.lower() != 'null' else None
print(f"值已更新: {old_value}{item['OFWeiche_center_line_height_mm']}")
except ValueError:
print("输入无效,保持原值")
else:
print("跳过修改")
# 计算相关值
if (item["OFWeiche_center_line_width_mm"] is not None and
item["OFWeiche_center_line_height_mm"] is not None):
angle_rad = math.radians(item["KurvenWinkel"])
# 计算并打印基本值(Doppelweiche特有公式)
old_width = item.get("Objekte_width_mm")
item["Objekte_width_mm"] = round(
(BogenProfileWidth/2 * math.cos(angle_rad)) +
item["OFWeiche_center_line_width_mm"] +
BogenProfileWidth/2 * math.cos(angle_rad), 3)
print(f"\nObjekte_width_mm 计算更新: {old_width}{item['Objekte_width_mm']}")
old_height = item.get("Objekte_height_mm")
item["Objekte_height_mm"] = round(
(BogenProfileWidth/2 * math.sin(angle_rad)) +
item["OFWeiche_center_line_height_mm"], 3)
print(f"Objekte_height_mm 计算更新: {old_height}{item['Objekte_height_mm']}")
# 计算并打印CP点坐标(Doppelweiche特有公式)
item["OFWeiche_CP1_x_mm"] = round(item["Objekte_width_mm"]/2, 3)
print(f"OFWeiche_CP1_x_mm 计算更新: {item['OFWeiche_CP1_x_mm']}")
item["OFWeiche_CP1_y_mm"] = round(item["Objekte_height_mm"], 3)
print(f"OFWeiche_CP1_y_mm 计算更新: {item['OFWeiche_CP1_y_mm']}")
item["OFWeiche_CP2_x_mm"] = round(BogenProfileWidth/2 * math.cos(angle_rad), 3)
print(f"OFWeiche_CP2_x_mm 计算更新: {item['OFWeiche_CP2_x_mm']}")
item["OFWeiche_CP2_y_mm"] = round(BogenProfileWidth/2 * math.sin(angle_rad), 3)
print(f"OFWeiche_CP2_y_mm 计算更新: {item['OFWeiche_CP2_y_mm']}")
item["OFWeiche_CP3_x_mm"] = round(
BogenProfileWidth/2 * math.cos(angle_rad) +
item["OFWeiche_center_line_width_mm"], 3)
print(f"OFWeiche_CP3_x_mm 计算更新: {item['OFWeiche_CP3_x_mm']}")
item["OFWeiche_CP3_y_mm"] = item["OFWeiche_CP2_y_mm"]
print(f"OFWeiche_CP3_y_mm 设置: {item['OFWeiche_CP3_y_mm']}")
# 1. 查找类似项1D型P型)
current_profil = item["ProfilTyp"]
if "S D" in current_profil:
d_p_profil = current_profil.replace("MIT M", "MIT P")
similar_items_d_p = [x for x in data
if x["ProfilTyp"] == d_p_profil and
x.get("SivasnrTEF") is None]
if similar_items_d_p:
print(f"\n找到 {len(similar_items_d_p)} 个D型P型相似项")
for similar in similar_items_d_p:
print(f"正在更新D型P型相似项: {similar['ProfilTyp']} (Sivasnr: {similar['Sivasnr']})")
# 更新所有字段
fields_to_copy = [
"OFWeiche_center_line_width_mm",
"OFWeiche_center_line_height_mm",
"Objekte_width_mm",
"Objekte_height_mm",
"OFWeiche_CP1_x_mm",
"OFWeiche_CP1_y_mm",
"OFWeiche_CP2_x_mm",
"OFWeiche_CP2_y_mm",
"OFWeiche_CP3_x_mm",
"OFWeiche_CP3_y_mm"
]
for field in fields_to_copy:
old_val = similar.get(field)
similar[field] = item[field]
print(f" {field}: {old_val}{similar[field]}")
else:
print("没有找到D型P型相似项")
# 2. 查找类似项2T型M型)
if "S D" in current_profil:
t_m_profil = current_profil.replace("S D", "S T")
similar_items_t_m = [x for x in data
if x["ProfilTyp"] == t_m_profil and
x.get("SivasnrTEF") is None and
x.get("Schaltungstyp") == "M"]
if similar_items_t_m:
print(f"\n找到 {len(similar_items_t_m)} 个T型M型相似项")
for similar in similar_items_t_m:
print(f"正在更新T型M型相似项: {similar['ProfilTyp']} (Sivasnr: {similar['Sivasnr']})")
if similar["KurvenWinkel"] == 22.5:
print("检测到KurvenWinkel=22.5,采用特殊处理方式")
# 特殊处理逻辑
similar["OFWeiche_center_line_width_mm"] = item["OFWeiche_center_line_width_mm"]
print(f" OFWeiche_center_line_width_mm: → {similar['OFWeiche_center_line_width_mm']}")
similar["OFWeiche_center_line_height_mm"] = WeichenGerade
print(f" OFWeiche_center_line_height_mm: → {WeichenGerade}")
similar["Objekte_width_mm"] = item["Objekte_width_mm"]
print(f" Objekte_width_mm: → {similar['Objekte_width_mm']}")
similar["Objekte_height_mm"] = WeichenGerade
print(f" Objekte_height_mm: → {WeichenGerade}")
similar["OFWeiche_CP1_x_mm"] = item["OFWeiche_CP1_x_mm"]
print(f" OFWeiche_CP1_x_mm: → {similar['OFWeiche_CP1_x_mm']}")
similar["OFWeiche_CP1_y_mm"] = similar["Objekte_height_mm"]
print(f" OFWeiche_CP1_y_mm: → {similar['OFWeiche_CP1_y_mm']}")
similar["OFWeiche_CP2_x_mm"] = item["OFWeiche_CP2_x_mm"]
print(f" OFWeiche_CP2_x_mm: → {similar['OFWeiche_CP2_x_mm']}")
similar["OFWeiche_CP2_y_mm"] = 20
print(f" OFWeiche_CP2_y_mm: → 20")
similar["OFWeiche_CP3_x_mm"] = item["OFWeiche_CP3_x_mm"]
print(f" OFWeiche_CP3_x_mm: → {similar['OFWeiche_CP3_x_mm']}")
similar["OFWeiche_CP3_y_mm"] = 20
print(f" OFWeiche_CP3_y_mm: → 20")
else:
# 更新基本字段
base_fields = [
"OFWeiche_center_line_width_mm",
"OFWeiche_center_line_height_mm",
"Objekte_width_mm",
"Objekte_height_mm",
"OFWeiche_CP1_x_mm",
"OFWeiche_CP1_y_mm",
"OFWeiche_CP2_x_mm",
"OFWeiche_CP2_y_mm",
"OFWeiche_CP3_x_mm",
"OFWeiche_CP3_y_mm"
]
for field in base_fields:
old_val = similar.get(field)
similar[field] = item[field]
print(f" {field}: {old_val}{similar[field]}")
# 添加CP4点(T型特有)
similar["OFWeiche_CP4_x_mm"] = round(item["Objekte_width_mm"]/2, 3)
print(f" OFWeiche_CP4_x_mm 添加: {similar['OFWeiche_CP4_x_mm']}")
similar["OFWeiche_CP4_y_mm"] = round(item["Objekte_height_mm"] - WeichenGerade, 3)
print(f" OFWeiche_CP4_y_mm 添加: {similar['OFWeiche_CP4_y_mm']}")
# 3. 查找T型P型对应项
t_p_profil = t_m_profil.replace("MIT M", "MIT P")
similar_items_t_p = [x for x in data
if x["ProfilTyp"] == t_p_profil and
x.get("SivasnrTEF") is None and
x.get("Schaltungstyp") == "P"]
if similar_items_t_p:
print(f"\n找到 {len(similar_items_t_p)} 个T型P型对应项")
for similar_t_p in similar_items_t_p:
print(f"正在更新T型P型对应项: {similar_t_p['ProfilTyp']} (Sivasnr: {similar_t_p['Sivasnr']})")
# 更新所有字段包括CP4点
fields_to_copy_t_p = [
"OFWeiche_center_line_width_mm",
"OFWeiche_center_line_height_mm",
"Objekte_width_mm",
"Objekte_height_mm",
"OFWeiche_CP1_x_mm",
"OFWeiche_CP1_y_mm",
"OFWeiche_CP2_x_mm",
"OFWeiche_CP2_y_mm",
"OFWeiche_CP3_x_mm",
"OFWeiche_CP3_y_mm",
"OFWeiche_CP4_x_mm",
"OFWeiche_CP4_y_mm"
]
for field in fields_to_copy_t_p:
old_val = similar_t_p.get(field)
similar_t_p[field] = similar[field]
print(f" {field}: {old_val}{similar_t_p[field]}")
# 添加保存确认提示
save_choice = input(f"是否确认更新此项? (直接回车确认,输入n取消): ").lower()
if save_choice == 'n':
print("此项更新已取消")
# 恢复原值
for field in fields_to_copy_t_p:
similar_t_p[field] = old_val
else:
print("没有找到T型P型对应项")
else:
print("没有找到T型M型相似项")
def process_dreifachweiche_items(data, WeichenkProfileWidth):
# 筛选Dreifachweiche类型的项
filtered_items = [
item for item in data
if (item.get("WeichenTyp") == "Dreifachweiche" and
item.get("Schaltungstyp") == "M" and
item.get("SivasnrTEF") is None)
]
print(f"\n\n共找到 {len(filtered_items)} 项Dreifachweiche类型记录")
print("="*50)
for idx, item in enumerate(filtered_items, 1):
print(f"\n{idx} 项Dreifachweiche:")
print(f"Sivasnr: {item['Sivasnr']}")
print(f"ProfilTyp: {item['ProfilTyp']}")
# 交互修改OFWeiche_center_line_width_mm
current_value = item.get("OFWeiche_center_line_width_mm")
print(f"\n当前 OFWeiche_center_line_width_mm: {current_value}")
choice = input("是否修改? (y修改,直接回车跳过): ").lower()
if choice == 'y':
new_value = input(f"请输入新值 (当前: {current_value}): ")
try:
old_value = item["OFWeiche_center_line_width_mm"]
item["OFWeiche_center_line_width_mm"] = round(float(new_value), 3) if new_value.lower() != 'null' else None
print(f"值已更新: {old_value}{item['OFWeiche_center_line_width_mm']}")
except ValueError:
print("输入无效,保持原值")
# 交互修改OFWeiche_center_line_height_mm
current_value = item.get("OFWeiche_center_line_height_mm")
print(f"\n当前 OFWeiche_center_line_height_mm: {current_value}")
choice = input("是否修改? (y修改,直接回车跳过): ").lower()
if choice == 'y':
new_value = input(f"请输入新值 (当前: {current_value}): ")
try:
old_value = item["OFWeiche_center_line_height_mm"]
item["OFWeiche_center_line_height_mm"] = round(float(new_value), 3) if new_value.lower() != 'null' else None
print(f"值已更新: {old_value}{item['OFWeiche_center_line_height_mm']}")
except ValueError:
print("输入无效,保持原值")
# 计算相关值
if (item["OFWeiche_center_line_width_mm"] is not None and
item["OFWeiche_center_line_height_mm"] is not None):
# 计算基本尺寸
item["Objekte_width_mm"] = round(item["OFWeiche_center_line_width_mm"], 3)
print(f"\nObjekte_width_mm 计算更新: {item['Objekte_width_mm']}")
item["Objekte_height_mm"] = round(WeichenkProfileWidth/2 + item["OFWeiche_center_line_height_mm"], 3)
print(f"Objekte_height_mm 计算更新: {item['Objekte_height_mm']}")
# 计算控制点
item["OFWeiche_CP1_x_mm"] = round(item["Objekte_width_mm"]/2, 3)
item["OFWeiche_CP1_y_mm"] = 0
item["OFWeiche_CP2_x_mm"] = 0
item["OFWeiche_CP2_y_mm"] = round(item["OFWeiche_center_line_height_mm"], 3)
item["OFWeiche_CP3_x_mm"] = round(item["OFWeiche_center_line_width_mm"], 3)
item["OFWeiche_CP3_y_mm"] = item["OFWeiche_CP2_y_mm"]
print(f"OFWeiche_CP1_x_mm: {item['OFWeiche_CP1_x_mm']}")
print(f"OFWeiche_CP1_y_mm: {item['OFWeiche_CP1_y_mm']}")
print(f"OFWeiche_CP2_x_mm: {item['OFWeiche_CP2_x_mm']}")
print(f"OFWeiche_CP2_y_mm: {item['OFWeiche_CP2_y_mm']}")
print(f"OFWeiche_CP3_x_mm: {item['OFWeiche_CP3_x_mm']}")
print(f"OFWeiche_CP3_y_mm: {item['OFWeiche_CP3_y_mm']}")
# 查找相似项(P型)
if "WEICHE S C DELTA" in item["ProfilTyp"]:
similar_profil = item["ProfilTyp"].replace("KPL. M", "KPL. P")
similar_items = [x for x in data
if x["ProfilTyp"] == similar_profil and
x.get("SivasnrTEF") is None]
if similar_items:
print(f"\n找到 {len(similar_items)} 个相似P型项")
for similar in similar_items:
print(f"\n正在更新: {similar['ProfilTyp']} (Sivasnr: {similar['Sivasnr']})")
fields_to_copy = [
"OFWeiche_center_line_width_mm",
"OFWeiche_center_line_height_mm",
"Objekte_width_mm",
"Objekte_height_mm",
"OFWeiche_CP1_x_mm",
"OFWeiche_CP1_y_mm",
"OFWeiche_CP2_x_mm",
"OFWeiche_CP2_y_mm",
"OFWeiche_CP3_x_mm",
"OFWeiche_CP3_y_mm"
]
print("\n更新中:")
for field in fields_to_copy:
print(f" {field}: {similar.get(field)}{item[field]}")
similar[field] = item[field]# 实际更新相似项的值
choice = input("\n确认更新此项? (回车确认/n取消): ").lower()
if choice == 'n':
print("取消此项更新")
for field in fields_to_copy:
similar[field] = similar[field]
else:
print("此项更新已确认")
else:
print("没有找到相似P型项")
if __name__ == "__main__":
json_file_path = "omniflo_weichen.json" # 替换为你的JSON文件路径
modify_json_values(json_file_path)
-16
View File
@@ -1,16 +0,0 @@
{
// Use IntelliSense to learn about possible attributes.
// Hover to view descriptions of existing attributes.
// For more information, visit: https://go.microsoft.com/fwlink/?linkid=830387
"version": "0.2.0",
"configurations": [
{
"name": "Python Debugger: Current File",
"type": "debugpy",
"request": "launch",
"program": "${file}",
"args": ["1_TEF_Boegen_input.json"],
"console": "integratedTerminal"
}
]
}
@@ -1,189 +0,0 @@
import json
import sys
import os
from datetime import datetime
def convert_to_float(value):
"""Safely convert value to float, return original if conversion fails"""
try:
return float(value)
except (ValueError, TypeError):
return value
def process_json_file(input_file):
# Validate and prepare file paths
input_path = os.path.abspath(input_file)
if not os.path.isfile(input_path):
print(f"Error: Input file not found - {input_path}")
sys.exit(1)
print(f"Reading file: {input_path}")
# Read JSON file
try:
with open(input_path, 'r', encoding='utf-8') as f:
data = json.load(f)
except json.JSONDecodeError as e:
print(f"Error: Invalid JSON format in {input_path}")
print(f"Details: {str(e)}")
sys.exit(1)
except Exception as e:
print(f"Error reading file {input_path}: {str(e)}")
sys.exit(1)
# Process each item in the JSON array
for i, item in enumerate(data):
print(f"\nProcessing item {i+1}: {item.get('Sivasnr', 'Unknown')}")
# Convert numerical values to float
for key in item:
if isinstance(item[key], (int, float, str)) and any(x in key.lower() for x in ['mm', 'width', 'height', 'radius', 'winkel']):
item[key] = convert_to_float(item[key])
# 1. Add four new attributes and calculate their values
print("\nStep 1: Adding four new attributes with calculations")
# OFBogen_CP2_x_mm
of_cp2_x = float(item["OFBogen_CP1_x_mm"]) + float(item["OFBogen_center_line_width_mm"])
item["OFBogen_CP2_x_mm"] = round(of_cp2_x, 3)
print(f"Added OFBogen_CP2_x_mm: {item['OFBogen_CP2_x_mm']}")
# TEFBogen_CP2_x_mm
tef_cp2_x = float(item["TEFBogen_CP1_x_mm"]) + float(item["TEFBogen_center_line_width_mm"])
item["TEFBogen_CP2_x_mm"] = round(tef_cp2_x, 3)
print(f"Added TEFBogen_CP2_x_mm: {item['TEFBogen_CP2_x_mm']}")
# OFBogen_CP2_y_mm
of_cp2_y = float(item["OFBogen_CP1_y_mm"]) + float(item["OFBogen_center_line_height_mm"])
item["OFBogen_CP2_y_mm"] = round(of_cp2_y, 3)
print(f"Added OFBogen_CP2_y_mm: {item['OFBogen_CP2_y_mm']}")
# TEFBogen_CP2_y_mm
tef_cp2_y = float(item["TEFBogen_CP1_y_mm"]) + float(item["TEFBogen_center_line_height_mm"])
item["TEFBogen_CP2_y_mm"] = round(tef_cp2_y, 3)
print(f"Added TEFBogen_CP2_y_mm: {item['TEFBogen_CP2_y_mm']}")
# 2. Calculate pixel dimensions and SVG dimensions
print("\nStep 2: Calculating pixel and SVG dimensions")
# Calculate Gruppe_width_px and Gruppe_height_px
item["Gruppe_width_px"] = round(float(item["Gruppe_width_mm"]) * 3.7795, 3)
item["Gruppe_height_px"] = round(float(item["Gruppe_height_mm"]) * 3.7795, 3)
print(f"Calculated Gruppe_width_px: {item['Gruppe_width_px']}")
print(f"Calculated Gruppe_height_px: {item['Gruppe_height_px']}")
# Compare width and height to determine scaling
if float(item["Gruppe_width_mm"]) > float(item["Gruppe_height_mm"]):
print("Width is larger, setting calculated_SVG_width to 1000px")
scale = round(1000 / float(item["Gruppe_width_mm"]), 6)
item["calculated_SVG_width_px"] = 1000
item["calculated_SVG_height_px"] = round(float(item["Gruppe_height_mm"]) * scale+3.7795/2, 3)
scale_RD_H = round(1000 / float(item["calculated_SVG_height_px"]), 6)
scale_RD_W = 1
elif float(item["Gruppe_width_mm"]) == float(item["Gruppe_height_mm"]):
print("Width =Height")
scale = round(1000 / float(item["Gruppe_width_mm"]), 6)
item["calculated_SVG_width_px"] = 1000
item["calculated_SVG_height_px"] = round(float(item["Gruppe_height_mm"]) * scale, 3)
scale_RD_H = round(1000 / float(item["calculated_SVG_height_px"]), 6)
scale_RD_W = 1
else:
print("Height is larger, setting calculated_SVG_height to 1000px")
scale = round(1000 / float(item["Gruppe_height_mm"]), 6)
item["calculated_SVG_height_px"] = 1000
item["calculated_SVG_width_px"] = round(float(item["Gruppe_width_mm"]) * scale+3.7795/2, 3)
scale_RD_W = round(1000 / float(item["calculated_SVG_width_px"]), 6)
scale_RD_H = 1
print(f"Calculated scale: {scale}")
print(f"Calculated calculated_SVG_width_px: {item['calculated_SVG_width_px']}")
print(f"Calculated calculated_SVG_height_px: {item['calculated_SVG_height_px']}")
print(f"Calculated scale_RD_W: {scale_RD_W}")
print(f"Calculated scale_RD_H: {scale_RD_H}")
# 3. Create connectionPoints array
print("\nStep 3: Creating connectionPoints array")
connection_points = []
# CP1
cp1_x = round(float(item["OFBogen_CP1_x_mm"]) * scale * scale_RD_W, 3)
cp1_y = round(float(item["OFBogen_CP1_y_mm"]) * scale * scale_RD_H, 3)
cp1 = {
"id": "cp1",
"x": cp1_x,
"y": cp1_y,
"direction": 270.0,
"linkClass": "Omniflo"
}
connection_points.append(cp1)
print(f"Created CP1: x={cp1_x}, y={cp1_y}, direction=270.0, linkClass=Omniflo")
# CP2
cp2_x = round(float(item["OFBogen_CP2_x_mm"]) * scale * scale_RD_W, 3)
cp2_y = round(float(item["OFBogen_CP2_y_mm"]) * scale * scale_RD_H, 3)
cp2_direction = round(90 + float(item["KurvenWinkel"]), 1)
cp2 = {
"id": "cp2",
"x": cp2_x,
"y": cp2_y,
"direction": cp2_direction,
"linkClass": "Omniflo"
}
connection_points.append(cp2)
print(f"Created CP2: x={cp2_x}, y={cp2_y}, direction={cp2_direction}, linkClass=Omniflo")
# CP3
cp3_x = round(float(item["TEFBogen_CP1_x_mm"]) * scale * scale_RD_W, 3)
cp3_y = round(float(item["TEFBogen_CP1_y_mm"]) * scale * scale_RD_H, 3)
cp3 = {
"id": "cp3",
"x": cp3_x,
"y": cp3_y,
"direction": 270.0,
"linkClass": "OmnifloTEF"
}
connection_points.append(cp3)
print(f"Created CP3: x={cp3_x}, y={cp3_y}, direction=270.0, linkClass=OmnifloTEF")
# CP4
cp4_x = round(float(item["TEFBogen_CP2_x_mm"]) * scale * scale_RD_W, 3)
cp4_y = round(float(item["TEFBogen_CP2_y_mm"]) * scale * scale_RD_H, 3)
cp4_direction = round(90 + float(item["KurvenWinkel"]), 1)
cp4 = {
"id": "cp4",
"x": cp4_x,
"y": cp4_y,
"direction": cp4_direction,
"linkClass": "OmnifloTEF"
}
connection_points.append(cp4)
print(f"Created CP4: x={cp4_x}, y={cp4_y}, direction={cp4_direction}, linkClass=OmnifloTEF")
item["connectionPoints"] = connection_points
# Prepare output path
output_dir = os.path.dirname(input_path) or '.' # Handle case when no directory in path
base_name = os.path.splitext(os.path.basename(input_path))[0]
timestamp = datetime.now().strftime("%Y%m%d_%H%M%S")
output_path = os.path.join(output_dir, f"{base_name}_processed_output.json")
# Save processed JSON file
try:
with open(output_path, 'w', encoding='utf-8') as f:
json.dump(data, f, indent=2, ensure_ascii=False)
print(f"\nProcessing complete! Results saved to new file: {output_path}")
print(f"Original file remains unchanged: {input_path}")
except Exception as e:
print(f"\nError saving processed file: {str(e)}")
sys.exit(1)
if __name__ == "__main__":
try:
if len(sys.argv) != 2:
raise ValueError("请提供输入文件路径")
input_file = sys.argv[1]
process_json_file(input_file)
except Exception as e:
print(f"错误详情: {str(e)}", file=sys.stderr)
sys.exit(1)
@@ -0,0 +1,259 @@
import json
import sys
import os
from datetime import datetime
def convert_to_float(value):
"""Convert value to float safely, return original if conversion fails"""
try:
return float(value)
except (ValueError, TypeError):
return value
def process_json_file(input_filename, output_filename=None):
"""
Process JSON file and generate output
Args:
input_filename: Input file path (can be relative or absolute)
output_filename: Optional output file path. Auto-generated if not provided
"""
# Get base path from environment variable
json_base_path = os.environ.get("JSON_PATH","JSON")
if not json_base_path:
print("Error: JSON_PATH environment variable not set")
print("Please set JSON_PATH in your .bat file")
sys.exit(1)
# Normalize path (handle path separator issues)
json_base_path = os.path.normpath(json_base_path)
# Build full input path
if os.path.isabs(input_filename):
input_path = input_filename
else:
input_path = os.path.join(json_base_path, input_filename)
# Convert to absolute path and normalize
input_path = os.path.abspath(os.path.normpath(input_path))
# Validate input file
if not os.path.isfile(input_path):
print(f"Error: Input file not found - {input_path}")
print(f"Current working directory: {os.getcwd()}")
sys.exit(1)
print(f"\nReading file: {input_path}")
# Read JSON file
try:
with open(input_path, 'r', encoding='utf-8') as f:
data = json.load(f)
except json.JSONDecodeError as e:
print(f"Error: Invalid JSON format in {input_path}")
print(f"Details: {str(e)}")
sys.exit(1)
except Exception as e:
print(f"Error reading file {input_path}: {str(e)}")
sys.exit(1)
# Print found item count
total_items = len(data)
processed_items = 0
print(f"\nFound {total_items} JSON records")
print("="*50) # Separator line
# 处理JSON数据 (保持原有处理逻辑不变)
for i, item in enumerate(data):
print(f"\nProcessing item {i+1}: {item.get('Sivasnr', 'Unknown')}")
try:
# 转换数值为float
for key in item:
if isinstance(item[key], (int, float, str)) and any(x in key.lower() for x in ['mm', 'width', 'height', 'radius', 'winkel']):
item[key] = convert_to_float(item[key])
# 1. 添加四个新属性并计算它们的值
print("\nStep 1: Adding four new attributes with calculations")
# OFBogen_CP2_x_mm
of_cp2_x = float(item["OFBogen_CP1_x_mm"]) + float(item["OFBogen_center_line_width_mm"])
item["OFBogen_CP2_x_mm"] = round(of_cp2_x, 3)
print(f"Added OFBogen_CP2_x_mm: {item['OFBogen_CP2_x_mm']}")
# TEFBogen_CP2_x_mm
tef_cp2_x = float(item["TEFBogen_CP1_x_mm"]) + float(item["TEFBogen_center_line_width_mm"])
item["TEFBogen_CP2_x_mm"] = round(tef_cp2_x, 3)
print(f"Added TEFBogen_CP2_x_mm: {item['TEFBogen_CP2_x_mm']}")
# OFBogen_CP2_y_mm
of_cp2_y = float(item["OFBogen_CP1_y_mm"]) + float(item["OFBogen_center_line_height_mm"])
item["OFBogen_CP2_y_mm"] = round(of_cp2_y, 3)
print(f"Added OFBogen_CP2_y_mm: {item['OFBogen_CP2_y_mm']}")
# TEFBogen_CP2_y_mm
tef_cp2_y = float(item["TEFBogen_CP1_y_mm"]) + float(item["TEFBogen_center_line_height_mm"])
item["TEFBogen_CP2_y_mm"] = round(tef_cp2_y, 3)
print(f"Added TEFBogen_CP2_y_mm: {item['TEFBogen_CP2_y_mm']}")
# 2. 计算像素尺寸和SVG尺寸
print("\nStep 2: Calculating pixel and SVG dimensions")
# 计算 Gruppe_width_px 和 Gruppe_height_px
item["Gruppe_width_px"] = round(float(item["Gruppe_width_mm"]) * 3.7795, 3)
item["Gruppe_height_px"] = round(float(item["Gruppe_height_mm"]) * 3.7795, 3)
print(f"Calculated Gruppe_width_px: {item['Gruppe_width_px']}")
print(f"Calculated Gruppe_height_px: {item['Gruppe_height_px']}")
# 比较宽度和高度以确定缩放比例
if float(item["Gruppe_width_mm"]) > float(item["Gruppe_height_mm"]):
print("Width is larger, setting calculated_SVG_width to 1000px")
scale = round(1000 / float(item["Gruppe_width_mm"]), 6)
item["calculated_SVG_width_px"] = 1000
item["calculated_SVG_height_px"] = round(float(item["Gruppe_height_mm"]) * scale+3.7795/2, 3)
scale_RD_H = round(1000 / float(item["calculated_SVG_height_px"]), 6)
scale_RD_W = 1
elif float(item["Gruppe_width_mm"]) == float(item["Gruppe_height_mm"]):
print("Width = Height")
scale = round(1000 / float(item["Gruppe_width_mm"]), 6)
item["calculated_SVG_width_px"] = 1000
item["calculated_SVG_height_px"] = round(float(item["Gruppe_height_mm"]) * scale, 3)
scale_RD_H = round(1000 / float(item["calculated_SVG_height_px"]), 6)
scale_RD_W = 1
else:
print("Height is larger, setting calculated_SVG_height to 1000px")
scale = round(1000 / float(item["Gruppe_height_mm"]), 6)
item["calculated_SVG_height_px"] = 1000
item["calculated_SVG_width_px"] = round(float(item["Gruppe_width_mm"]) * scale+3.7795/2, 3)
scale_RD_W = round(1000 / float(item["calculated_SVG_width_px"]), 6)
scale_RD_H = 1
print(f"Calculated scale: {scale}")
print(f"Calculated calculated_SVG_width_px: {item['calculated_SVG_width_px']}")
print(f"Calculated calculated_SVG_height_px: {item['calculated_SVG_height_px']}")
print(f"Calculated scale_RD_W: {scale_RD_W}")
print(f"Calculated scale_RD_H: {scale_RD_H}")
# 3. 创建connectionPoints数组
print("\nStep 3: Creating connectionPoints array")
connection_points = []
# CP1
cp1_x = round(float(item["OFBogen_CP1_x_mm"]) * scale * scale_RD_W, 3)
cp1_y = round(float(item["OFBogen_CP1_y_mm"]) * scale * scale_RD_H, 3)
cp1 = {
"id": "cp1",
"x": cp1_x,
"y": cp1_y,
"direction": 270.0,
"linkClass": "Omniflo"
}
connection_points.append(cp1)
print(f"Created CP1: x={cp1_x}, y={cp1_y}, direction=270.0, linkClass=Omniflo")
# CP2
cp2_x = round(float(item["OFBogen_CP2_x_mm"]) * scale * scale_RD_W, 3)
cp2_y = round(float(item["OFBogen_CP2_y_mm"]) * scale * scale_RD_H, 3)
cp2_direction = round(90 + float(item["KurvenWinkel"]), 1)
cp2 = {
"id": "cp2",
"x": cp2_x,
"y": cp2_y,
"direction": cp2_direction,
"linkClass": "Omniflo"
}
connection_points.append(cp2)
print(f"Created CP2: x={cp2_x}, y={cp2_y}, direction={cp2_direction}, linkClass=Omniflo")
# CP3
cp3_x = round(float(item["TEFBogen_CP1_x_mm"]) * scale * scale_RD_W, 3)
cp3_y = round(float(item["TEFBogen_CP1_y_mm"]) * scale * scale_RD_H, 3)
cp3 = {
"id": "cp3",
"x": cp3_x,
"y": cp3_y,
"direction": 270.0,
"linkClass": "OmnifloTEF"
}
connection_points.append(cp3)
print(f"Created CP3: x={cp3_x}, y={cp3_y}, direction=270.0, linkClass=OmnifloTEF")
# CP4
cp4_x = round(float(item["TEFBogen_CP2_x_mm"]) * scale * scale_RD_W, 3)
cp4_y = round(float(item["TEFBogen_CP2_y_mm"]) * scale * scale_RD_H, 3)
cp4_direction = round(90 + float(item["KurvenWinkel"]), 1)
cp4 = {
"id": "cp4",
"x": cp4_x,
"y": cp4_y,
"direction": cp4_direction,
"linkClass": "OmnifloTEF"
}
connection_points.append(cp4)
print(f"Created CP4: x={cp4_x}, y={cp4_y}, direction={cp4_direction}, linkClass=OmnifloTEF")
item["connectionPoints"] = connection_points
# Increment success counter
processed_items += 1
print(f"Item {i} processed successfully")
except Exception as e:
print(f"Error processing item {i}: {str(e)}")
continue
# Print processing statistics
print("\n" + "="*50)
print("Processing Statistics:")
print(f"Total records found: {total_items}")
print(f"Successfully processed: {processed_items}")
if total_items > 0:
success_rate = (processed_items / total_items) * 100
print(f"Success rate: {success_rate:.2f}%")
print("="*50 + "\n")
# Handle output file path
if output_filename is None:
base_name = os.path.splitext(os.path.basename(input_path))[0]
timestamp = datetime.now().strftime("%Y%m%d_%H%M%S")
output_filename = f"{base_name}_processed_{timestamp}.json"
# Build output path
if os.path.isabs(output_filename):
output_path = output_filename
else:
output_path = os.path.join(json_base_path, output_filename)
# Ensure output directory exists
os.makedirs(os.path.dirname(output_path) or '.', exist_ok=True)
# Save processed JSON file
try:
with open(output_path, 'w', encoding='utf-8') as f:
json.dump(data, f, indent=2, ensure_ascii=False)
print(f"Processing complete! Results saved to: {output_path}")
print(f"Original file remains unchanged: {input_path}")
except Exception as e:
print(f"\nError saving processed file: {str(e)}")
sys.exit(1)
if __name__ == "__main__":
try:
# Get JSON_PATH from environment
json_path = os.environ.get("JSON_PATH","JSON")
# Default filenames
input_filename = "1_TEF_Boegen_input.json"
output_filename = "1_TEF_Boegen_output.json"
# Use command line arguments if provided
if len(sys.argv) > 1:
input_filename = sys.argv[1]
if len(sys.argv) > 2:
output_filename = sys.argv[2]
process_json_file(input_filename, output_filename)
except Exception as e:
print(f"Error: {str(e)}", file=sys.stderr)
sys.exit(1)
@@ -1,18 +1,3 @@
''' Script Analysis
This Python script processes JSON and TXT files to update dimensions and connection points in SVG-related data. Here's the main logic:
Input Handling:
Reads a JSON file containing reference data
Processes all TXT files in a specified directory
Data Processing:
Creates a mapping between Sivasnr (from filenames) and JSON data
For each matching TXT file:
Updates width and height based on JSON data (converting mm to px)
Updates connection points (x, y, direction) from JSON data
Preserves the original file structure while updating specific values
Reporting:
Prints detailed change reports to console
Skips files without matching JSON data '''
import json
import os
import glob
@@ -30,13 +15,21 @@ def process_files(json_file_path, txt_files_dir):
# Create Sivasnr to JSON data mapping
sivasnr_mapping = {item["Sivasnr"]: item for item in json_data}
# Initialize counters
total_files = 0
processed_files = 0
skipped_files = 0
# Prepare report content
report_content = []
report_content.append(f"Modification Report - {datetime.now().strftime('%Y-%m-%d %H:%M:%S')}")
report_content.append(f"JSON Reference File: {json_file_path}")
report_content.append(f"TXT Files Directory: {txt_files_dir}")
report_content.append("="*50 + "\n")
# Process all TXT files
for txt_file_path in glob.glob(os.path.join(txt_files_dir, '*.txt')):
total_files += 1
# Extract Sivasnr from filename
sivasnr = os.path.splitext(os.path.basename(txt_file_path))[0]
@@ -50,7 +43,7 @@ def process_files(json_file_path, txt_files_dir):
# Prepare entry for this file
file_entry = []
file_entry.append(f"\nProcessing file: {txt_file_path}")
file_entry.append(f"\nProcessing file: {os.path.basename(txt_file_path)}")
file_entry.append("="*50)
# Record old values
@@ -108,7 +101,9 @@ def process_files(json_file_path, txt_files_dir):
file_entry.append(f" y: {change['y'][0]}{change['y'][1]}")
file_entry.append(f" direction: {change['direction'][0]}{change['direction'][1]}")
file_entry.append(f" linkClass: {change['linkClass'][0]}{change['linkClass'][1]}")
file_entry.append(f"\nFile {txt_file_path} processed successfully")
processed_files += 1
file_entry.append(f"\nFile processed successfully")
file_entry.append("="*50)
# Add this file's entry to main report
@@ -117,19 +112,41 @@ def process_files(json_file_path, txt_files_dir):
# Also print to console
print("\n" + "\n".join(file_entry))
else:
print(f"\nSkipping file {txt_file_path} (no matching JSON data found)")
skipped_files += 1
# Write the report file if any changes were made
if len(report_content) > 2: # More than just the header
with open(log_file_path, 'w', encoding='utf-8') as f:
f.write("\n".join(report_content))
print(f"\nModification report saved to: {log_file_path}")
else:
print("\nNo files were modified - no report generated")
# Add processing statistics to report
report_content.append("\n" + "="*50)
report_content.append("Processing Statistics:")
report_content.append(f"Total TXT files found: {total_files}")
report_content.append(f"Total JSON records available: {len(json_data)}")
report_content.append(f"Successfully processed: {processed_files}")
report_content.append(f"Skipped files: {skipped_files}")
if total_files > 0:
success_rate = (processed_files / len(json_data)) * 100
report_content.append(f"Success rate: {success_rate:.2f}%")
report_content.append("="*50)
# Print statistics to console
print("\n" + "="*50)
print("Processing Statistics:")
print(f"Total TXT files found: {total_files}")
print(f"Total JSON records available: {len(json_data)}")
print(f"Successfully processed: {processed_files}")
print(f"Skipped files: {skipped_files}")
if total_files > 0:
success_rate = (processed_files / len(json_data)) * 100
print(f"Success rate: {success_rate:.2f}%")
print("="*50 + "\n")
# Write the report file
with open(log_file_path, 'w', encoding='utf-8') as f:
f.write("\n".join(report_content))
print(f"Modification report saved to: {log_file_path}")
# Example usage
if __name__ == "__main__":
json_file_path = "1_TEF_Boegen_input_processed_output.json"
txt_files_dir = "C:/Program Files/RuleDesigner/RDConfigurator Fusion/WebApi/Editor2D/SSG/shapes/props"
json_path = os.environ.get("JSON_PATH", "JSON")
json_file_path = os.path.join(json_path, "1_TEF_Boegen_output.json")
txt_files_dir = os.environ.get("PROPS_PATH", "props")
process_files(json_file_path, txt_files_dir)
print("\nAll files processed!")
print("\nProcessing complete!")
@@ -107,8 +107,10 @@ def main():
Main processing function
"""
# Configure paths
json_file_path = "1_TEF_Boegen_input.json"
svg_folder_path = r"C:\Program Files\RuleDesigner\RDConfigurator Fusion\WebApi\Editor2D\SSG\shapes\svg"
json_path=os.environ.get("JSON_PATH","JSON")
json_file_path = os.path.join(json_path,"1_TEF_Boegen_input.json")
svg_folder_path = os.environ.get("XML_PATH","svg")
try:
# Read and parse JSON file
@@ -0,0 +1,12 @@
@echo off
set TEFBogen_PATH=%~dp0
set XML_PATH=C:\Program Files\RuleDesigner\RDConfigurator Fusion\WebApi\Editor2D\SSG\shapes\svg
set JSON_PATH=%TEFBogen_PATH%JSON
python 4_TEFBogen_SVG_XML_Modifier_Script.py
pause
@@ -0,0 +1,12 @@
@echo off
set TEFBogen_PATH=%~dp0
set PROPS_PATH=C:\Program Files\RuleDesigner\RDConfigurator Fusion\WebApi\Editor2D\SSG\shapes\props
set JSON_PATH=%TEFBogen_PATH%JSON
python 1_process_TEFBogen_json_1.py
python 2_update_props_TEF_Boegen_from_json_1.py
pause