Обновлён шаблон заземления шкафа операторской cross32-32

This commit is contained in:
Nail Sagitov 2026-08-03 23:39:58 +05:00
parent b544b6f6ec
commit 2db1cf3299
11 changed files with 352289 additions and 7839 deletions

View File

@ -22,5 +22,5 @@
Для каждого сгенерированного файла с помощью скриптов:
- выполнить печать печатных листов (сохраняя ctb, формат листа, high quality pdf plotter);
- на печатном листе под основной надписью выводить имя генерируемого файла, а не временное имя типа "01_source.dxf";
- на печатном листе под основной надписью выводить имя генерируемого файла, а не временное имя типа "01_source.dxf" и не имя шаблона DXF типа "Шаблон ...dxf");
- cформировать таблицы подключений.

View File

@ -22,6 +22,7 @@
| MZ11-R1 | MZ11 | MR200_102 | Электрощитовая (102) | Машинный зал №1.1 (MR200) |
| Шкаф ВОЛС | RTP3 | 60_бн | Помещение связи и телемеханики (бн) | РТП-3 (60) |
| ТШ_МФЦ-2 | MFC | 1704.70_057 | Серверная (057) | МФЦ "Лунная поляна" (1704.70) |
| 4 | ROM | 17_132 | Серверная (132) | п.Романтик. Административное здание (17) |
## Оптические линии - кроссы - волоконность

View File

@ -8,17 +8,16 @@ import shutil
import sys
import tempfile
import time
from collections import Counter, defaultdict
from collections import defaultdict
from dataclasses import dataclass
from pathlib import Path
import ezdxf
from openpyxl import Workbook, load_workbook
from ezdxf.addons.drawing import matplotlib
from ezdxf.addons.drawing.config import BackgroundPolicy, ColorPolicy, Configuration
from ezdxf.addons.drawing.frontend import Frontend
from ezdxf.addons.drawing.matplotlib import MatplotlibBackend
from ezdxf.addons.drawing.properties import LayoutProperties, RenderContext
from openpyxl import Workbook, load_workbook
class ProcessingError(RuntimeError):
@ -189,7 +188,9 @@ PRINCIPLE_TEMPLATE = TemplateSpec(
)
POWER_MACHINE_TEMPLATE = TemplateSpec(
template_path=Path("Шаблон Схема электропитания и заземления шкафа СПД - машзалы r11.dxf"),
template_path=Path(
"Шаблон Схема электропитания и заземления шкафа СПД - машзалы r11.dxf"
),
source_doc_code="01/B590.110900.1.6-СПД-050",
source_title="Схема электропитания и заземления MZ1-R1",
source_cabinet_label="Шкаф MZ1-R1",
@ -199,7 +200,9 @@ POWER_MACHINE_TEMPLATE = TemplateSpec(
)
POWER_OPERATOR_TEMPLATE = TemplateSpec(
template_path=Path("Шаблон Схема электропитания и заземления шкафа СПД - операторские r11.dxf"),
template_path=Path(
"Шаблон Схема электропитания и заземления шкафа СПД - операторские r11.dxf"
),
source_doc_code="01/B590.110900.1.6-СПД-018",
source_title="Схема электропитания и заземления MZ1-R1",
source_cabinet_label="Шкаф MZ1-R1",
@ -276,10 +279,14 @@ def update_text_entity(entity, replacements: dict[str, str]) -> int:
return 0
def apply_replacements(doc: ezdxf.document.Drawing, replacements: dict[str, str]) -> int:
def apply_replacements(
doc: ezdxf.document.Drawing, replacements: dict[str, str]
) -> int:
total = 0
spaces = [doc.modelspace()]
spaces.extend(doc.layouts.get(name) for name in doc.layout_names() if name != "Model")
spaces.extend(
doc.layouts.get(name) for name in doc.layout_names() if name != "Model"
)
spaces.extend(doc.blocks)
for space in spaces:
for entity in space:
@ -313,7 +320,9 @@ def persist_raw_dxf_replacements(path: Path, replacements: dict[str, str]) -> in
def extract_cabinet_name(document_title: str) -> str:
match = re.search(r"([A-Z0-9]+-R1)\s*$", document_title, re.IGNORECASE)
if not match:
raise ProcessingError(f"Cannot extract cabinet name from document title: {document_title}")
raise ProcessingError(
f"Cannot extract cabinet name from document title: {document_title}"
)
return match.group(1).upper()
@ -348,14 +357,22 @@ def load_mdr_entries(path: Path) -> list[MdrEntry]:
cabinet = ""
entries.append(
MdrEntry(
title_number=normalize_text(worksheet.cell(row_index, title_number_col).value),
title_name=normalize_text(worksheet.cell(row_index, title_name_col).value),
title_number=normalize_text(
worksheet.cell(row_index, title_number_col).value
),
title_name=normalize_text(
worksheet.cell(row_index, title_name_col).value
),
mark=normalize_text(worksheet.cell(row_index, mark_col).value),
doc_order=normalize_text(worksheet.cell(row_index, doc_order_col).value),
doc_order=normalize_text(
worksheet.cell(row_index, doc_order_col).value
),
doc_number=doc_number,
doc_name=doc_name,
revision=normalize_text(worksheet.cell(row_index, revision_col).value),
discipline=normalize_text(worksheet.cell(row_index, discipline_col).value),
discipline=normalize_text(
worksheet.cell(row_index, discipline_col).value
),
format_name=normalize_text(worksheet.cell(row_index, format_col).value),
cabinet=cabinet,
)
@ -374,7 +391,9 @@ def load_cabinet_lookup(path: Path) -> dict[str, CabinetInfo]:
for column in range(1, worksheet.max_column + 1)
if normalize_text(worksheet.cell(1, column).value)
}
cabinet_col = find_column(headers, "Наимнование_шкафа", "Наименование_шкафа", "Шкаф")
cabinet_col = find_column(
headers, "Наимнование_шкафа", "Наименование_шкафа", "Шкаф"
)
room_col = find_column(headers, "Наименование_помещения", "Помещение")
title_col = find_column(headers, "Титул", "Наименование_титула")
@ -469,7 +488,9 @@ def determine_remote_endpoint(designation: str, local_cabinet: str) -> str:
def iter_text_entities(doc: ezdxf.document.Drawing):
spaces = [doc.modelspace()]
spaces.extend(doc.layouts.get(name) for name in doc.layout_names() if name != "Model")
spaces.extend(
doc.layouts.get(name) for name in doc.layout_names() if name != "Model"
)
spaces.extend(doc.blocks)
for space in spaces:
for entity in space:
@ -494,7 +515,25 @@ def set_entity_raw_text(entity, value: str) -> None:
entity.text = value
def resolve_site_title(site_code: str, title_lookup: dict[str, str], structure_sites: dict[str, dict]) -> str:
def replace_template_footer_texts(
doc: ezdxf.document.Drawing, output_file_name: str
) -> int:
changed = 0
for entity in iter_text_entities(doc):
if entity.dxftype() not in {"TEXT", "MTEXT", "ATTRIB"}:
continue
raw_text = get_entity_raw_text(entity)
if not raw_text:
continue
if re.fullmatch(r"(?:01_)?Шаблон .*\.dxf", raw_text):
set_entity_raw_text(entity, output_file_name)
changed += 1
return changed
def resolve_site_title(
site_code: str, title_lookup: dict[str, str], structure_sites: dict[str, dict]
) -> str:
if not site_code:
return ""
normalized = site_code.upper()
@ -538,8 +577,12 @@ def build_rename_replacements(
source_parts = source_value.split("-")
target_parts = target_value.split("-")
if len(source_parts) >= 3 and len(target_parts) >= 3:
reversed_source = f"{source_parts[1]}-{source_parts[0]}-{'-'.join(source_parts[2:])}"
reversed_target = f"{target_parts[1]}-{target_parts[0]}-{'-'.join(target_parts[2:])}"
reversed_source = (
f"{source_parts[1]}-{source_parts[0]}-{'-'.join(source_parts[2:])}"
)
reversed_target = (
f"{target_parts[1]}-{target_parts[0]}-{'-'.join(target_parts[2:])}"
)
replacements[reversed_source] = reversed_target
replacements[reversed_source[:-1]] = reversed_target[:-1]
if row_index == 7:
@ -554,9 +597,14 @@ def lookup_vokrch_designation(
) -> str:
rows = vokrch_lookup.get(normalize_key(title_number), [])
if not rows:
raise ProcessingError(f"Title '{title_number}' was not found in sheet '{VOKRCH_SHEET}'.")
raise ProcessingError(
f"Title '{title_number}' was not found in sheet '{VOKRCH_SHEET}'."
)
for row in rows:
if TARGET_DISCIPLINE in normalize_text(row["systems"]) or normalize_text(row["suffix"]) == TARGET_DISCIPLINE:
if (
TARGET_DISCIPLINE in normalize_text(row["systems"])
or normalize_text(row["suffix"]) == TARGET_DISCIPLINE
):
return row["designation"]
return rows[0]["designation"]
@ -582,13 +630,17 @@ def find_input_power_reference(
return f"{reference.mark}{reference.doc_order}"
def classify_template(entry: MdrEntry, cabinet_info: CabinetInfo) -> TemplateSpec | None:
def classify_template(
entry: MdrEntry, cabinet_info: CabinetInfo
) -> TemplateSpec | None:
if entry.doc_name.startswith(LAYOUT_TITLE_PREFIX):
if is_operator_title(cabinet_info.title_name):
return LAYOUT_OPERATOR_TEMPLATE
if is_machine_title(cabinet_info.title_name):
return LAYOUT_MACHINE_TEMPLATE
raise ProcessingError(f"Unsupported cabinet title for layout document: {cabinet_info.title_name}")
raise ProcessingError(
f"Unsupported cabinet title for layout document: {cabinet_info.title_name}"
)
if entry.doc_name.startswith(PRINCIPLE_TITLE_PREFIX):
return PRINCIPLE_TEMPLATE
if entry.doc_name.startswith(POWER_TITLE_PREFIX):
@ -596,7 +648,9 @@ def classify_template(entry: MdrEntry, cabinet_info: CabinetInfo) -> TemplateSpe
return POWER_OPERATOR_TEMPLATE
if is_machine_title(cabinet_info.title_name):
return POWER_MACHINE_TEMPLATE
raise ProcessingError(f"Unsupported cabinet title for power document: {cabinet_info.title_name}")
raise ProcessingError(
f"Unsupported cabinet title for power document: {cabinet_info.title_name}"
)
return None
@ -606,7 +660,11 @@ def is_operator_title(title_name: str) -> bool:
def is_machine_title(title_name: str) -> bool:
normalized = normalize_text(title_name)
return any(normalized.startswith(prefix) for prefix in MACHINE_TITLE_PREFIXES) or normalized in MACHINE_TITLE_NAMES or normalized.startswith("Центр управления С")
return (
any(normalized.startswith(prefix) for prefix in MACHINE_TITLE_PREFIXES)
or normalized in MACHINE_TITLE_NAMES
or normalized.startswith("Центр управления С")
)
def is_ksb_title(entry: MdrEntry) -> bool:
@ -641,7 +699,9 @@ def build_output_folder(entry: MdrEntry, output_stem: str) -> Path:
return OUTPUT_ROOT / folder_prefix
def build_template_replacements(template_spec: TemplateSpec, output_file_name: str, output_doc_number: str) -> dict[str, str]:
def build_template_replacements(
template_spec: TemplateSpec, output_file_name: str, output_doc_number: str
) -> dict[str, str]:
replacements = {
template_spec.source_doc_code: output_doc_number,
GENERIC_DOC_CODE_PLACEHOLDER: output_doc_number,
@ -652,11 +712,15 @@ def build_template_replacements(template_spec: TemplateSpec, output_file_name: s
replacements[template_spec.template_path.name] = output_file_name
replacements[template_spec.template_path.stem] = Path(output_file_name).stem
replacements[f"01_{template_spec.template_path.name}"] = f"01_{output_file_name}"
replacements[f"01_{template_spec.template_path.stem}"] = f"01_{Path(output_file_name).stem}"
replacements[f"01_{template_spec.template_path.stem}"] = (
f"01_{Path(output_file_name).stem}"
)
return replacements
def build_caption_replacements(entry: MdrEntry, cabinet_info: CabinetInfo) -> dict[str, str]:
def build_caption_replacements(
entry: MdrEntry, cabinet_info: CabinetInfo
) -> dict[str, str]:
replacements: dict[str, str] = {}
for source_room in SOURCE_ROOM_TEXTS:
replacements[source_room] = cabinet_info.room_name
@ -666,7 +730,7 @@ def build_caption_replacements(entry: MdrEntry, cabinet_info: CabinetInfo) -> di
replacements[source_label] = f"Шкаф {entry.cabinet}"
for source_caption in SOURCE_CAPTION_TEXTS:
replacements[source_caption] = entry.doc_name
replacements[SOURCE_DISCIPLINE_TEXT] = SOURCE_DISCIPLINE_TEXT
# replacements[SOURCE_DISCIPLINE_TEXT] = SOURCE_DISCIPLINE_TEXT
return replacements
@ -691,11 +755,15 @@ def apply_structure_reference_updates(
designation_to_title: dict[str, str] = {}
fiber_count_by_designation: dict[str, int] = {}
for connection in structure_reference.get("connections", {}).get("optical_lines", []):
for connection in structure_reference.get("connections", {}).get(
"optical_lines", []
):
source_designation = normalize_text(connection.get("designation", ""))
if not source_designation:
continue
target_designation = normalize_text(rename_replacements.get(source_designation, source_designation))
target_designation = normalize_text(
rename_replacements.get(source_designation, source_designation)
)
if not target_designation:
continue
fiber_count = connection.get("fiber_count")
@ -706,7 +774,9 @@ def apply_structure_reference_updates(
source_designation = normalize_text(connection.get("designation", ""))
if not source_designation:
continue
target_designation = normalize_text(rename_replacements.get(source_designation, source_designation))
target_designation = normalize_text(
rename_replacements.get(source_designation, source_designation)
)
if not target_designation:
continue
remote_code = determine_remote_endpoint(target_designation, local_cabinet)
@ -729,7 +799,9 @@ def apply_structure_reference_updates(
except Exception:
continue
text_entities.append((entity, x, y, raw_text))
if raw_text in fiber_count_by_designation or re.fullmatch(r"[A-Z0-9]+(?:-[A-Z0-9]+)+-OL\d*", raw_text):
if raw_text in fiber_count_by_designation or re.fullmatch(
r"[A-Z0-9]+(?:-[A-Z0-9]+)+-OL\d*", raw_text
):
designation_entities.append((x, y, raw_text))
changed = 0
@ -789,11 +861,15 @@ def apply_structure_reference_updates_fixed(
designation_to_title: dict[str, str] = {}
fiber_count_by_designation: dict[str, int] = {}
for connection in structure_reference.get("connections", {}).get("optical_lines", []):
for connection in structure_reference.get("connections", {}).get(
"optical_lines", []
):
source_designation = normalize_text(connection.get("designation", ""))
if not source_designation:
continue
target_designation = normalize_text(rename_replacements.get(source_designation, source_designation))
target_designation = normalize_text(
rename_replacements.get(source_designation, source_designation)
)
if not target_designation:
continue
fiber_count = connection.get("fiber_count")
@ -804,7 +880,9 @@ def apply_structure_reference_updates_fixed(
source_designation = normalize_text(connection.get("designation", ""))
if not source_designation:
continue
target_designation = normalize_text(rename_replacements.get(source_designation, source_designation))
target_designation = normalize_text(
rename_replacements.get(source_designation, source_designation)
)
if not target_designation:
continue
remote_code = determine_remote_endpoint(target_designation, local_cabinet)
@ -827,7 +905,9 @@ def apply_structure_reference_updates_fixed(
except Exception:
continue
text_entities.append((entity, x, y, raw_text))
if raw_text in fiber_count_by_designation or re.fullmatch(r"[A-Z0-9]+(?:-[A-Z0-9]+)+-OL\d*", raw_text):
if raw_text in fiber_count_by_designation or re.fullmatch(
r"[A-Z0-9]+(?:-[A-Z0-9]+)+-OL\d*", raw_text
):
designation_entities.append((x, y, raw_text))
changed = 0
@ -877,7 +957,9 @@ def build_replacements(
output_stem = build_output_stem(entry)
output_file_name = f"{output_stem}.dxf"
replacements = dict(rename_replacements)
replacements.update(build_template_replacements(template_spec, output_file_name, entry.doc_number))
replacements.update(
build_template_replacements(template_spec, output_file_name, entry.doc_number)
)
replacements.update(build_caption_replacements(entry, cabinet_info))
replacements[entry.doc_name] = entry.doc_name
@ -887,34 +969,46 @@ def build_replacements(
replacements[template_spec.source_title_with_id] = cabinet_info.title_name
replacements[entry.doc_number] = entry.doc_number
replacements[entry.doc_number.replace("/", "_")] = entry.doc_number.replace("/", "_")
replacements["D"] = "07.2026"
replacements["{{ D }}"] = "07.2026"
replacements["{{D}}"] = "07.2026"
replacements[entry.doc_number.replace("/", "_")] = entry.doc_number.replace(
"/", "_"
)
replacements["D"] = "07.26"
replacements["{{ D }}"] = "07.26"
replacements["{{D}}"] = "07.26"
designation = lookup_vokrch_designation(vokrch_lookup, entry.title_number)
replacements["Оборудование СОПКД учтено в комплекте ___________________"] = (
f"Оборудование СОПКД учтено в комплекте {designation}"
)
replacements["Оборудование и кабели СОПКД учтено в комплекте ___________________"] = (
f"Оборудование и кабели СОПКД учтено в комплекте {designation}"
)
replacements[
"Оборудование и кабели СОПКД учтено в комплекте ___________________"
] = f"Оборудование и кабели СОПКД учтено в комплекте {designation}"
try:
input_power_ref = find_input_power_reference(entries_by_title, entry.title_number)
input_power_ref = find_input_power_reference(
entries_by_title, entry.title_number
)
except ProcessingError:
input_power_ref = ""
if input_power_ref:
replacements["Состав оборудования устройства ввода электропитания см. на листе __"] = (
"Состав оборудования устройства ввода электропитания см. на листе " + input_power_ref
replacements[
"Состав оборудования устройства ввода электропитания см. на листе __"
] = (
"Состав оборудования устройства ввода электропитания см. на листе "
+ input_power_ref
)
replacements["Состав оборудования устройства ввода электропитания \\P см. на листе __ ."] = (
replacements[
"Состав оборудования устройства ввода электропитания \\P см. на листе __ ."
] = (
"Состав оборудования устройства ввода электропитания \\P см. на листе "
+ input_power_ref
+ " ."
)
replacements["Состав оборудования устройства ввода электропитания\nсм. на листе __"] = (
"Состав оборудования устройства ввода электропитания\nсм. на листе " + input_power_ref
replacements[
"Состав оборудования устройства ввода электропитания\nсм. на листе __"
] = (
"Состав оборудования устройства ввода электропитания\nсм. на листе "
+ input_power_ref
)
if is_ksb_title(entry):
@ -926,7 +1020,9 @@ def build_replacements(
return replacements
def set_title_block_attributes(doc: ezdxf.document.Drawing, entry: MdrEntry, cabinet_info: CabinetInfo) -> None:
def set_title_block_attributes(
doc: ezdxf.document.Drawing, entry: MdrEntry, cabinet_info: CabinetInfo
) -> None:
for layout_name in doc.layout_names():
if layout_name == "Model":
continue
@ -969,7 +1065,9 @@ def layout_page_size_inches(layout) -> tuple[float, float]:
def layout_render_config(layout) -> Configuration:
config = Configuration.defaults()
style_sheet = str(getattr(layout.dxf, "current_style_sheet", "") or "").strip().casefold()
style_sheet = (
str(getattr(layout.dxf, "current_style_sheet", "") or "").strip().casefold()
)
if style_sheet in {"monochrome.ctb", "grayscale.ctb"}:
config = config.with_changes(
color_policy=ColorPolicy.BLACK,
@ -1035,41 +1133,55 @@ def export_layout_pdf(layout, pdf_path: Path, *, dpi: int = 150) -> Path:
class AutoCADPlotter:
def __init__(self) -> None:
self._app = None
self._owns_app = False
def _ensure_app(self):
if self._app is None:
import win32com.client
last_exc = None
try:
self._app = win32com.client.GetActiveObject("AutoCAD.Application")
self._owns_app = False
except Exception:
for _ in range(5):
try:
self._app = win32com.client.DispatchEx("AutoCAD.Application")
self._owns_app = True
break
except Exception as exc:
last_exc = exc
time.sleep(0.5)
for _ in range(10):
try:
self._app = win32com.client.DispatchEx("AutoCAD.Application")
if self._app is not None:
break
except Exception as exc:
last_exc = exc
time.sleep(1.0)
time.sleep(0.2)
if self._app is None:
raise last_exc
for _ in range(10):
try:
self._app.Visible = False
break
except Exception:
time.sleep(0.5)
time.sleep(2.0)
if self._owns_app:
for _ in range(5):
try:
self._app.Visible = False
break
except Exception:
time.sleep(0.2)
return self._app
def close(self) -> None:
if self._app is None:
return
try:
self._app.Quit()
except Exception:
pass
if self._owns_app:
try:
self._app.Quit()
except Exception:
pass
self._app = None
self._owns_app = False
def print_layouts(self, dxf_path: Path, layout_names: list[str], output_path: Path) -> tuple[Path, ...]:
def print_layouts(
self, dxf_path: Path, layout_names: list[str], output_path: Path
) -> tuple[Path, ...]:
def autocad_call(func, *args, **kwargs):
last_exc = None
for _ in range(10):
@ -1081,9 +1193,14 @@ class AutoCADPlotter:
raise last_exc
app = self._ensure_app()
temp_dir = Path(tempfile.mkdtemp(prefix="acad_plot_", dir=str(output_path.parent)))
temp_dir = Path(
tempfile.mkdtemp(prefix="acad_plot_", dir=str(output_path.parent))
)
ascii_copy = temp_dir / output_path.name
shutil.copy2(dxf_path, ascii_copy)
plot_doc = ezdxf.readfile(ascii_copy)
sanitize_plot_colors(plot_doc)
plot_doc.saveas(ascii_copy)
document = autocad_call(lambda: app.Documents.Open(str(ascii_copy.resolve())))
printed: list[Path] = []
@ -1094,6 +1211,7 @@ class AutoCADPlotter:
except Exception:
pass
for layout_name in layout_names:
print(f"AutoCAD plotting {layout_name} for {output_path.name}...", file=sys.stderr)
layout = autocad_call(lambda: document.Layouts.Item(layout_name))
document.ActiveLayout = layout
try:
@ -1102,20 +1220,29 @@ class AutoCADPlotter:
pass
temp_pdf = temp_dir / f"{safe_layout_suffix(layout_name)}.pdf"
pdf_path = output_path.with_name(f"{output_path.stem}_{safe_layout_suffix(layout_name)}.pdf")
pdf_path = output_path.with_name(
f"{output_path.stem}_{safe_layout_suffix(layout_name)}.pdf"
)
if pdf_path.exists():
pdf_path.unlink()
config_name = getattr(layout, "ConfigName", "") or ""
if config_name:
ok = autocad_call(lambda: document.Plot.PlotToFile(str(temp_pdf.resolve()), config_name))
ok = autocad_call(
lambda: document.Plot.PlotToFile(
str(temp_pdf.resolve()), config_name
)
)
else:
ok = autocad_call(lambda: document.Plot.PlotToFile(str(temp_pdf.resolve())))
ok = autocad_call(
lambda: document.Plot.PlotToFile(str(temp_pdf.resolve()))
)
if not ok or not temp_pdf.exists():
raise ProcessingError(
f"AutoCAD failed to plot layout '{layout_name}' for '{output_path.name}'."
)
shutil.move(str(temp_pdf), str(pdf_path))
print(f"AutoCAD finished {layout_name} for {output_path.name}.", file=sys.stderr)
printed.append(pdf_path)
finally:
try:
@ -1129,7 +1256,9 @@ class AutoCADPlotter:
def safe_layout_suffix(name: str) -> str:
cleaned = "".join(ch if ch.isalnum() or ch in ("-", "_") else "_" for ch in name.strip())
cleaned = "".join(
ch if ch.isalnum() or ch in ("-", "_") else "_" for ch in name.strip()
)
cleaned = cleaned.strip("_")
return cleaned or "layout"
@ -1152,9 +1281,26 @@ def sanitize_plot_entity_colors(entity) -> None:
entity.dxf.color = 7
def _copy_entity_plot_style(source, target) -> None:
if source.dxf.hasattr("layer"):
target.dxf.layer = source.dxf.layer
if source.dxf.hasattr("linetype"):
target.dxf.linetype = source.dxf.linetype
if source.dxf.hasattr("ltscale"):
target.dxf.ltscale = source.dxf.ltscale
if source.dxf.hasattr("color"):
target.dxf.color = source.dxf.color
if source.dxf.hasattr("true_color"):
target.dxf.true_color = source.dxf.true_color
if source.dxf.hasattr("transparency"):
target.dxf.transparency = source.dxf.transparency
def sanitize_plot_colors(doc: ezdxf.document.Drawing) -> None:
spaces = [doc.modelspace()]
spaces.extend(doc.layouts.get(name) for name in doc.layout_names() if name != "Model")
spaces.extend(
doc.layouts.get(name) for name in doc.layout_names() if name != "Model"
)
spaces.extend(doc.blocks)
for space in spaces:
for entity in space:
@ -1181,7 +1327,9 @@ def print_layouts(
printed: list[Path] = []
for layout_name in layout_names:
layout = doc.layouts.get(layout_name)
pdf_path = output_path.with_name(f"{output_path.stem}_{safe_layout_suffix(layout_name)}.pdf")
pdf_path = output_path.with_name(
f"{output_path.stem}_{safe_layout_suffix(layout_name)}.pdf"
)
printed.append(export_layout_pdf(layout, pdf_path, dpi=150))
return tuple(printed)
@ -1211,7 +1359,9 @@ def get_table_block(doc: ezdxf.document.Drawing, table_entity):
return doc.blocks.get(block_record.dxf.name)
def parse_component_table_rows(doc: ezdxf.document.Drawing) -> list[ExistingComponentRow]:
def parse_component_table_rows(
doc: ezdxf.document.Drawing,
) -> list[ExistingComponentRow]:
table_entity = locate_component_table(doc)
if table_entity is None:
return []
@ -1267,9 +1417,21 @@ def parse_component_table_rows(doc: ezdxf.document.Drawing) -> list[ExistingComp
mapping[column] = entity
logical_rows.append(
ExistingComponentRow(
designation=get_entity_text(mapping["designation"]) if "designation" in mapping else "",
description=get_entity_text(mapping["description"]) if "description" in mapping else "",
quantity=get_entity_text(mapping["quantity"]) if "quantity" in mapping else "",
designation=(
get_entity_text(mapping["designation"])
if "designation" in mapping
else ""
),
description=(
get_entity_text(mapping["description"])
if "description" in mapping
else ""
),
quantity=(
get_entity_text(mapping["quantity"])
if "quantity" in mapping
else ""
),
note=get_entity_text(mapping["note"]) if "note" in mapping else "",
)
)
@ -1325,7 +1487,9 @@ def parse_comma_designation(designation: str) -> list[str]:
return [part.strip() for part in designation.split(",") if part.strip()]
def find_devices(doc: ezdxf.document.Drawing, component_rows: list[ExistingComponentRow]) -> dict[str, Device]:
def find_devices(
doc: ezdxf.document.Drawing, component_rows: list[ExistingComponentRow]
) -> dict[str, Device]:
devices: dict[str, Device] = {}
for row in component_rows:
if not row.designation:
@ -1335,7 +1499,9 @@ def find_devices(doc: ezdxf.document.Drawing, component_rows: list[ExistingCompo
for token in parse_comma_designation(row.designation) or [row.designation]:
kind = normalize_device_kind(token)
if kind and token not in devices:
devices[token] = Device(name=token, kind=kind, location=extract_location(token))
devices[token] = Device(
name=token, kind=kind, location=extract_location(token)
)
for entity in doc.modelspace():
if entity.dxftype() not in {"MTEXT", "TEXT"}:
@ -1346,11 +1512,15 @@ def find_devices(doc: ezdxf.document.Drawing, component_rows: list[ExistingCompo
if kind == "odf":
continue
if kind and token not in devices:
devices[token] = Device(name=token, kind=kind, location=extract_location(token))
devices[token] = Device(
name=token, kind=kind, location=extract_location(token)
)
return devices
def find_connection_marks(doc: ezdxf.document.Drawing, devices: dict[str, Device]) -> list[ConnectionMark]:
def find_connection_marks(
doc: ezdxf.document.Drawing, devices: dict[str, Device]
) -> list[ConnectionMark]:
result: list[ConnectionMark] = []
skipped_unknown: list[str] = []
for insert in doc.modelspace().query('INSERT[name=="Cable_mark"]'):
@ -1381,14 +1551,17 @@ def find_connection_marks(doc: ezdxf.document.Drawing, devices: dict[str, Device
)
if skipped_unknown:
print(
"WARNING: skipped unclassified connection marks: " + ", ".join(sorted(set(skipped_unknown))),
"WARNING: skipped unclassified connection marks: "
+ ", ".join(sorted(set(skipped_unknown))),
file=sys.stderr,
)
result.sort(key=lambda item: item.mark)
return result
def build_cable_description_by_mark(component_rows: list[ExistingComponentRow]) -> dict[str, str]:
def build_cable_description_by_mark(
component_rows: list[ExistingComponentRow],
) -> dict[str, str]:
descriptions: dict[str, str] = {}
for row in component_rows:
if not row.designation or not row.description:
@ -1419,18 +1592,29 @@ def consecutive_groups(values: list[int]) -> list[list[int]]:
return groups
def ordered_odf_devices(component_rows: list[ExistingComponentRow], devices: dict[str, Device]) -> list[Device]:
def ordered_odf_devices(
component_rows: list[ExistingComponentRow], devices: dict[str, Device]
) -> list[Device]:
for row in component_rows:
if not row.designation:
continue
tokens = parse_comma_designation(row.designation)
odf_tokens = [token for token in tokens if normalize_device_kind(token) == "odf" and token in devices]
odf_tokens = [
token
for token in tokens
if normalize_device_kind(token) == "odf" and token in devices
]
if odf_tokens:
return [devices[token] for token in odf_tokens]
return sorted((device for device in devices.values() if device.kind == "odf"), key=lambda item: item.name)
return sorted(
(device for device in devices.values() if device.kind == "odf"),
key=lambda item: item.name,
)
def resolve_group_port(group: list[int], ordinal: int, target_port_count: int | None) -> int:
def resolve_group_port(
group: list[int], ordinal: int, target_port_count: int | None
) -> int:
if not group:
return ordinal
if target_port_count is None or target_port_count <= 0:
@ -1461,11 +1645,20 @@ def resolve_connection_rows(
sop_devices = sorted(by_kind.get("sop", []), key=lambda item: item.name)
odf_devices = ordered_odf_devices(component_rows, devices)
odf_port_counts = {
device.name: max((mark.port_number for mark in marks if mark.device_kind == "odf" and mark.device_name == device.name), default=0)
device.name: max(
(
mark.port_number
for mark in marks
if mark.device_kind == "odf" and mark.device_name == device.name
),
default=0,
)
for device in odf_devices
}
switch_ports = sorted(
mark.port_number for mark in marks if mark.device_kind == "switch" and mark.port_number not in {23, 24}
mark.port_number
for mark in marks
if mark.device_kind == "switch" and mark.port_number not in {23, 24}
)
switch_groups = consecutive_groups(switch_ports)
@ -1480,7 +1673,14 @@ def resolve_connection_rows(
if not switch_device_name:
unresolved.append(mark.mark)
continue
odf_index = next((idx for idx, device in enumerate(odf_devices) if device.name == mark.device_name), -1)
odf_index = next(
(
idx
for idx, device in enumerate(odf_devices)
if device.name == mark.device_name
),
-1,
)
if odf_index < 0:
unresolved.append(mark.mark)
continue
@ -1508,22 +1708,33 @@ def resolve_connection_rows(
dst_device = sop_devices[0].name
dst_port = "1"
else:
group_index = next((idx for idx, group in enumerate(switch_groups) if mark.port_number in group), -1)
group_index = next(
(
idx
for idx, group in enumerate(switch_groups)
if mark.port_number in group
),
-1,
)
if group_index < 0 or group_index >= len(odf_devices):
unresolved.append(mark.mark)
continue
target_device = odf_devices[group_index]
group = switch_groups[group_index]
dst_device = target_device.name
dst_port = str(resolve_group_port(group, group.index(mark.port_number) + 1, odf_port_counts.get(target_device.name)))
dst_port = str(
resolve_group_port(
group,
group.index(mark.port_number) + 1,
odf_port_counts.get(target_device.name),
)
)
else:
unresolved.append(mark.mark)
continue
cable_mark = cable_description_by_mark.get(mark.mark, "")
note = "" if cable_mark else (
"Марка кабеля не найдена в перечне элементов"
)
note = "" if cable_mark else ("Марка кабеля не найдена в перечне элементов")
rows.append(
ConnectionRow(
position=index,
@ -1539,7 +1750,9 @@ def resolve_connection_rows(
)
if unresolved:
raise ProcessingError("Cannot resolve destination devices for marks: " + ", ".join(unresolved))
raise ProcessingError(
"Cannot resolve destination devices for marks: " + ", ".join(unresolved)
)
return rows
@ -1582,17 +1795,23 @@ def write_connection_table(output_path: Path, rows: list[ConnectionRow]) -> Path
return output_path
def build_connection_table(doc: ezdxf.document.Drawing, output_path: Path) -> Path | None:
def build_connection_table(
doc: ezdxf.document.Drawing, output_path: Path
) -> Path | None:
component_rows = parse_component_table_rows(doc)
devices = find_devices(doc, component_rows)
marks = find_connection_marks(doc, devices)
if not marks:
return None
cable_description_by_mark = build_cable_description_by_mark(component_rows)
rows = resolve_connection_rows(marks, devices, cable_description_by_mark, component_rows)
rows = resolve_connection_rows(
marks, devices, cable_description_by_mark, component_rows
)
if not rows:
return None
return write_connection_table(output_path.with_name(f"{output_path.stem}_connection_table.xlsx"), rows)
return write_connection_table(
output_path.with_name(f"{output_path.stem}_connection_table.xlsx"), rows
)
MARK_TOKEN_RE = re.compile(r"\b(?:[A-Z0-9]+-)+(?:[A-Z0-9]+)\b")
@ -1607,7 +1826,19 @@ def extract_mark_tokens(doc: ezdxf.document.Drawing) -> dict[str, int]:
if not raw_text:
continue
for token in MARK_TOKEN_RE.findall(raw_text):
if any(marker in token for marker in ("-R1", "-ODF", "-ASW", "-DSW", "-OL", "-O-", "-T-", "-S-")):
if any(
marker in token
for marker in (
"-R1",
"-ODF",
"-ASW",
"-DSW",
"-OL",
"-O-",
"-T-",
"-S-",
)
):
counts[token] += 1
return dict(sorted(counts.items()))
@ -1640,7 +1871,9 @@ def build_job(
template_spec = classify_template(entry, cabinet_info)
if template_spec is None:
return None
rename_replacements = build_rename_replacements(rename_header, rename_rows, entry.cabinet)
rename_replacements = build_rename_replacements(
rename_header, rename_rows, entry.cabinet
)
replacements = build_replacements(
entry=entry,
cabinet_info=cabinet_info,
@ -1668,7 +1901,9 @@ def run_job(
output_folder.mkdir(parents=True, exist_ok=True)
output_path = output_folder / f"{output_stem}.dxf"
rename_replacements = build_rename_replacements(rename_header, rename_rows, job.entry.cabinet)
rename_replacements = build_rename_replacements(
rename_header, rename_rows, job.entry.cabinet
)
replacements = build_replacements(
entry=job.entry,
cabinet_info=job.cabinet_info,
@ -1681,6 +1916,7 @@ def run_job(
doc = ezdxf.readfile(job.template_spec.template_path)
replacements_count = apply_replacements(doc, replacements)
set_title_block_attributes(doc, job.entry, job.cabinet_info)
replacements_count += replace_template_footer_texts(doc, f"{output_stem}.dxf")
replacements_count += apply_structure_reference_updates_fixed(
doc,
job.entry,
@ -1695,12 +1931,19 @@ def run_job(
dxf_path_for_plot = output_path
try:
printed_files = print_layouts(doc, dxf_path_for_plot, output_path, autocad_plotter=autocad_plotter)
printed_files = print_layouts(
doc, dxf_path_for_plot, output_path, autocad_plotter=autocad_plotter
)
except Exception as exc:
if autocad_plotter is None:
raise
print(f"WARNING: AutoCAD plotting failed for {output_path.name}: {exc}", file=sys.stderr)
printed_files = print_layouts(doc, dxf_path_for_plot, output_path, autocad_plotter=None)
print(
f"WARNING: AutoCAD plotting failed for {output_path.name}: {exc}",
file=sys.stderr,
)
printed_files = print_layouts(
doc, dxf_path_for_plot, output_path, autocad_plotter=None
)
connection_table_path = build_connection_table(doc, output_path)
@ -1720,7 +1963,9 @@ def parse_args() -> argparse.Namespace:
"plot layouts to PDF and build connection tables."
)
)
parser.add_argument("--mdr", default=str(MDR_PATH), help="Path to the MDR workbook.")
parser.add_argument(
"--mdr", default=str(MDR_PATH), help="Path to the MDR workbook."
)
parser.add_argument(
"--rename-table",
default=str(RENAME_TABLE_PATH),
@ -1755,7 +2000,9 @@ def main() -> int:
vokrch_lookup = load_vokrch_lookup(mdr_path)
rename_header, rename_rows = load_rename_table(rename_table_path)
structure_reference = load_structure_reference(STRUCTURE_REFERENCE_PATH)
title_lookup = {cabinet: info.title_name for cabinet, info in cabinet_lookup.items()}
title_lookup = {
cabinet: info.title_name for cabinet, info in cabinet_lookup.items()
}
entries_by_title: dict[str, list[MdrEntry]] = defaultdict(list)
for entry in mdr_entries:
@ -1769,7 +2016,9 @@ def main() -> int:
template_spec = classify_template(entry, cabinet_info)
if template_spec is None:
continue
jobs.append(Job(entry=entry, cabinet_info=cabinet_info, template_spec=template_spec))
jobs.append(
Job(entry=entry, cabinet_info=cabinet_info, template_spec=template_spec)
)
if not jobs:
raise ProcessingError("No matching documents were found in MDR.xlsx.")

View File

@ -26,6 +26,7 @@ from generate_spd_dxfs import (
normalize_text,
persist_raw_dxf_replacements,
print_layouts,
replace_template_footer_texts,
safe_component,
set_title_block_attributes,
)
@ -223,8 +224,8 @@ def build_reference_replacements(
replacements["{{ DOC_NUM }}"] = doc_suffix(doc.doc_number)
replacements["{{DOC_NUM}}"] = doc_suffix(doc.doc_number)
# Legacy stamp placeholder in the templates.
replacements["{{ D }}"] = "07.2026"
replacements["{{D}}"] = "07.2026"
replacements["{{ D }}"] = "07.26"
replacements["{{D}}"] = "07.26"
return replacements
@ -401,6 +402,7 @@ def run_document(
doc = ezdxf.readfile(ref_doc.template_path)
apply_reference_replacements(doc, ref_doc.replacements)
set_title_block_attributes(doc, ref_doc.entry, ref_doc.cabinet)
replace_template_footer_texts(doc, f"{output_stem}.dxf")
remaining_placeholders = find_unreplaced_placeholders(doc)
if remaining_placeholders:
raise ProcessingError(