Добавлен экстрастор блоков
This commit is contained in:
parent
7a3d77546d
commit
0d8d92439f
32
README.md
32
README.md
|
|
@ -153,6 +153,38 @@ STAGE_TITUL = "*"
|
|||
- `STAGE_TITUL = "*"` (или не указан) → для места/документа генерируются **все** записи из MDR (все этапы); в каждом файле `{{STAGE_TITUL}}` заменяется на код этапа;
|
||||
- `STAGE_TITUL = "110900"` → обрабатывается только документ этого этапа.
|
||||
|
||||
## Библиотека блоков
|
||||
|
||||
Чтобы не дублировать блоки в каждом `templates/*.dxf`, можно держать их в отдельных библиотечных DXF. Практическая схема такая:
|
||||
|
||||
```text
|
||||
templates/
|
||||
library/
|
||||
common.dxf
|
||||
spd/
|
||||
principle.dxf
|
||||
power.dxf
|
||||
layout.dxf
|
||||
*.dxf
|
||||
archive/
|
||||
```
|
||||
|
||||
Утилита `src/sync_dxf_block_library.py` умеет:
|
||||
|
||||
- собрать библиотеку из текущих шаблонов;
|
||||
- синхронизировать определения блоков из библиотеки обратно в шаблоны;
|
||||
- пропускать `archive/` и саму библиотеку.
|
||||
- ограничивать обработку через `--include` и `--exclude`.
|
||||
|
||||
Примеры:
|
||||
|
||||
```powershell
|
||||
python src/sync_dxf_block_library.py extract --library templates/library/spd/principle.dxf --include "Шаблон Схема соединений принципиальная СПД*.dxf"
|
||||
python src/sync_dxf_block_library.py sync --library templates/library/spd/principle.dxf --include "Шаблон Схема соединений принципиальная СПД*.dxf"
|
||||
```
|
||||
|
||||
Если один и тот же `block name` в разных шаблонах отличается по геометрии, его нужно вынести в отдельную библиотеку или переименовать. Одна глобальная библиотека подходит только для реально идентичных блоков.
|
||||
|
||||
## Источники данных
|
||||
|
||||
Основные входные данные:
|
||||
|
|
|
|||
|
|
@ -0,0 +1,366 @@
|
|||
from __future__ import annotations
|
||||
|
||||
import argparse
|
||||
import hashlib
|
||||
import json
|
||||
from fnmatch import fnmatchcase
|
||||
from dataclasses import dataclass
|
||||
from pathlib import Path
|
||||
from typing import Iterable
|
||||
|
||||
import ezdxf
|
||||
from ezdxf.addons.importer import Importer
|
||||
|
||||
ROOT = Path(__file__).resolve().parent.parent
|
||||
|
||||
DEFAULT_TEMPLATE_ROOT = ROOT / "templates"
|
||||
DEFAULT_LIBRARY_PATH = ROOT / "templates" / "library" / "blocks.dxf"
|
||||
|
||||
|
||||
class ProcessingError(RuntimeError):
|
||||
pass
|
||||
|
||||
|
||||
@dataclass(frozen=True)
|
||||
class BlockRecord:
|
||||
name: str
|
||||
signature: str
|
||||
source: Path
|
||||
|
||||
|
||||
def normalize_text(value: object) -> str:
|
||||
if value is None:
|
||||
return ""
|
||||
return str(value).replace("\xa0", " ").replace("\n", " ").strip()
|
||||
|
||||
|
||||
def is_library_block(name: str) -> bool:
|
||||
normalized = normalize_text(name)
|
||||
if not normalized:
|
||||
return False
|
||||
if normalized.startswith("*"):
|
||||
return False
|
||||
if normalized.startswith("A$"):
|
||||
return False
|
||||
return True
|
||||
|
||||
|
||||
DEFAULT_INCLUDE_PATTERNS = ("*.dxf",)
|
||||
DEFAULT_EXCLUDE_PATTERNS = ("archive/**", "archive/*", "library/**", "library/*")
|
||||
|
||||
|
||||
def matches_patterns(path: Path, template_root: Path, patterns: Iterable[str]) -> bool:
|
||||
relative = path.relative_to(template_root).as_posix()
|
||||
name = path.name
|
||||
return any(fnmatchcase(relative, pattern) or fnmatchcase(name, pattern) for pattern in patterns)
|
||||
|
||||
|
||||
def iter_template_files(
|
||||
template_root: Path,
|
||||
library_path: Path,
|
||||
include_patterns: Iterable[str],
|
||||
exclude_patterns: Iterable[str],
|
||||
) -> list[Path]:
|
||||
files = []
|
||||
for path in sorted(template_root.rglob("*.dxf")):
|
||||
if path.resolve() == library_path.resolve():
|
||||
continue
|
||||
if matches_patterns(path, template_root, exclude_patterns):
|
||||
continue
|
||||
if include_patterns and not matches_patterns(path, template_root, include_patterns):
|
||||
continue
|
||||
files.append(path)
|
||||
return files
|
||||
|
||||
|
||||
def merge_patterns(default_patterns: Iterable[str], override_patterns: Iterable[str] | None) -> tuple[str, ...]:
|
||||
if override_patterns is None:
|
||||
return tuple(default_patterns)
|
||||
return tuple(default_patterns) + tuple(override_patterns)
|
||||
|
||||
|
||||
def json_ready(value: object) -> object:
|
||||
if value is None or isinstance(value, (str, int, float, bool)):
|
||||
return value
|
||||
if isinstance(value, dict):
|
||||
return {str(key): json_ready(item) for key, item in value.items()}
|
||||
if isinstance(value, (list, tuple, set, frozenset)):
|
||||
return [json_ready(item) for item in value]
|
||||
if hasattr(value, "x") and hasattr(value, "y"):
|
||||
coords = [value.x, value.y]
|
||||
if hasattr(value, "z"):
|
||||
coords.append(value.z)
|
||||
return coords
|
||||
return str(value)
|
||||
|
||||
|
||||
def entity_signature(entity) -> object:
|
||||
attribs = dict(entity.dxfattribs())
|
||||
for key in list(attribs):
|
||||
key_norm = key.casefold()
|
||||
if key_norm in {"handle", "owner"} or key_norm.endswith("handle") or key_norm.endswith("owner"):
|
||||
attribs.pop(key, None)
|
||||
return {
|
||||
"type": entity.dxftype(),
|
||||
"attribs": {key: json_ready(attribs[key]) for key in sorted(attribs)},
|
||||
}
|
||||
|
||||
|
||||
def block_signature(block) -> str:
|
||||
block_def = block.block
|
||||
payload = {
|
||||
"name": block.name,
|
||||
"base_point": json_ready(getattr(block_def.dxf, "base_point", None)) if block_def else None,
|
||||
"description": normalize_text(getattr(block_def.dxf, "description", "")) if block_def else "",
|
||||
"flags": int(getattr(block_def.dxf, "flags", 0) or 0) if block_def else 0,
|
||||
"entities": [
|
||||
entity_signature(entity)
|
||||
for entity in block
|
||||
if entity.dxftype() != "ENDBLK"
|
||||
],
|
||||
}
|
||||
encoded = json.dumps(payload, ensure_ascii=False, sort_keys=True, separators=(",", ":"))
|
||||
return hashlib.sha256(encoded.encode("utf-8")).hexdigest()
|
||||
|
||||
|
||||
def load_document(path: Path):
|
||||
if not path.exists():
|
||||
raise FileNotFoundError(f"DXF not found: {path}")
|
||||
return ezdxf.readfile(path)
|
||||
|
||||
|
||||
def collect_blocks(doc, source: Path) -> dict[str, BlockRecord]:
|
||||
records: dict[str, BlockRecord] = {}
|
||||
for block in doc.blocks:
|
||||
name = normalize_text(block.name)
|
||||
if not is_library_block(name):
|
||||
continue
|
||||
records[name] = BlockRecord(
|
||||
name=name,
|
||||
signature=block_signature(block),
|
||||
source=source,
|
||||
)
|
||||
return records
|
||||
|
||||
|
||||
def import_blocks_from_source(
|
||||
source_doc,
|
||||
target_doc,
|
||||
block_names: Iterable[str],
|
||||
) -> None:
|
||||
importer = Importer(source_doc, target_doc)
|
||||
importer.import_blocks(block_names, rename=False)
|
||||
importer.finalize()
|
||||
|
||||
|
||||
def extract_library(
|
||||
template_root: Path,
|
||||
library_path: Path,
|
||||
dry_run: bool,
|
||||
include_patterns: Iterable[str],
|
||||
exclude_patterns: Iterable[str],
|
||||
skip_conflicts: bool,
|
||||
) -> int:
|
||||
template_files = iter_template_files(
|
||||
template_root, library_path, include_patterns, exclude_patterns
|
||||
)
|
||||
if not template_files:
|
||||
raise ProcessingError(f"No template DXF files were found under {template_root}")
|
||||
|
||||
library_doc = ezdxf.new()
|
||||
seen: dict[str, BlockRecord] = {}
|
||||
conflicts = 0
|
||||
|
||||
for source_path in template_files:
|
||||
source_doc = load_document(source_path)
|
||||
source_records = collect_blocks(source_doc, source_path)
|
||||
to_import: list[str] = []
|
||||
|
||||
for name, record in source_records.items():
|
||||
existing = seen.get(name)
|
||||
if existing is not None:
|
||||
if existing.signature != record.signature:
|
||||
if skip_conflicts:
|
||||
conflicts += 1
|
||||
print(
|
||||
f'Skipping conflicting block "{name}" in {source_path}; '
|
||||
f"keeping the first definition from {existing.source}."
|
||||
)
|
||||
continue
|
||||
raise ProcessingError(
|
||||
f'Block "{name}" has conflicting definitions; '
|
||||
f"resolve it in {source_path}"
|
||||
)
|
||||
continue
|
||||
to_import.append(name)
|
||||
seen[name] = record
|
||||
|
||||
if to_import:
|
||||
import_blocks_from_source(source_doc, library_doc, to_import)
|
||||
seen = collect_blocks(library_doc, library_path)
|
||||
|
||||
if dry_run:
|
||||
print(f"Would write library with {len(seen)} blocks to {library_path}")
|
||||
if conflicts:
|
||||
print(f"Would skip {conflicts} conflicting block definitions.")
|
||||
return 0
|
||||
|
||||
library_path.parent.mkdir(parents=True, exist_ok=True)
|
||||
library_doc.saveas(library_path)
|
||||
print(f"Wrote {library_path} with {len(seen)} blocks.")
|
||||
if conflicts:
|
||||
print(f"Skipped {conflicts} conflicting block definitions.")
|
||||
return 0
|
||||
|
||||
|
||||
def sync_template(template_path: Path, library_doc, library_records: dict[str, BlockRecord], dry_run: bool) -> int:
|
||||
target_doc = load_document(template_path)
|
||||
target_records = collect_blocks(target_doc, template_path)
|
||||
names_to_update = sorted(
|
||||
name for name in library_records.keys() if name in target_records
|
||||
)
|
||||
|
||||
if not names_to_update:
|
||||
print(f"OK {template_path}")
|
||||
return 0
|
||||
|
||||
if dry_run:
|
||||
print(
|
||||
f"Would update {template_path} ({len(names_to_update)} blocks): "
|
||||
+ ", ".join(names_to_update)
|
||||
)
|
||||
return 1
|
||||
|
||||
for name in names_to_update:
|
||||
target_doc.blocks.delete_block(name, safe=False)
|
||||
|
||||
import_blocks_from_source(library_doc, target_doc, names_to_update)
|
||||
target_doc.saveas(template_path)
|
||||
print(f"Updated {template_path} ({len(names_to_update)} blocks).")
|
||||
return 1
|
||||
|
||||
|
||||
def sync_library_to_templates(
|
||||
template_root: Path,
|
||||
library_path: Path,
|
||||
dry_run: bool,
|
||||
include_patterns: Iterable[str],
|
||||
exclude_patterns: Iterable[str],
|
||||
) -> int:
|
||||
library_doc = load_document(library_path)
|
||||
library_records = collect_blocks(library_doc, library_path)
|
||||
if not library_records:
|
||||
raise ProcessingError(f"Library contains no reusable blocks: {library_path}")
|
||||
|
||||
template_files = iter_template_files(
|
||||
template_root, library_path, include_patterns, exclude_patterns
|
||||
)
|
||||
if not template_files:
|
||||
raise ProcessingError(f"No template DXF files were found under {template_root}")
|
||||
|
||||
updated = 0
|
||||
for template_path in template_files:
|
||||
updated += 1 if sync_template(template_path, library_doc, library_records, dry_run) else 0
|
||||
print(f"Processed {len(template_files)} template(s); updated {updated}.")
|
||||
return 0
|
||||
|
||||
|
||||
def parse_args() -> argparse.Namespace:
|
||||
parser = argparse.ArgumentParser(
|
||||
description="Extract reusable blocks into a shared DXF library and sync templates from it."
|
||||
)
|
||||
subparsers = parser.add_subparsers(dest="command", required=True)
|
||||
|
||||
extract = subparsers.add_parser(
|
||||
"extract",
|
||||
help="Build the block library from the current template DXF files.",
|
||||
)
|
||||
extract.add_argument(
|
||||
"--template-root",
|
||||
default=str(DEFAULT_TEMPLATE_ROOT),
|
||||
help="Root directory that contains template DXF files.",
|
||||
)
|
||||
extract.add_argument(
|
||||
"--library",
|
||||
default=str(DEFAULT_LIBRARY_PATH),
|
||||
help="Path to the block library DXF.",
|
||||
)
|
||||
extract.add_argument(
|
||||
"--dry-run",
|
||||
action="store_true",
|
||||
help="Print planned actions without writing files.",
|
||||
)
|
||||
extract.add_argument(
|
||||
"--include",
|
||||
action="append",
|
||||
help="Glob pattern for template DXF files to include. May be repeated.",
|
||||
)
|
||||
extract.add_argument(
|
||||
"--exclude",
|
||||
action="append",
|
||||
help="Glob pattern for template DXF files to exclude. May be repeated.",
|
||||
)
|
||||
extract.add_argument(
|
||||
"--skip-conflicts",
|
||||
action="store_true",
|
||||
help="Keep the first definition when block signatures differ and skip later ones.",
|
||||
)
|
||||
|
||||
sync = subparsers.add_parser(
|
||||
"sync",
|
||||
help="Replace template block definitions with the versions from the library.",
|
||||
)
|
||||
sync.add_argument(
|
||||
"--template-root",
|
||||
default=str(DEFAULT_TEMPLATE_ROOT),
|
||||
help="Root directory that contains template DXF files.",
|
||||
)
|
||||
sync.add_argument(
|
||||
"--library",
|
||||
default=str(DEFAULT_LIBRARY_PATH),
|
||||
help="Path to the block library DXF.",
|
||||
)
|
||||
sync.add_argument(
|
||||
"--dry-run",
|
||||
action="store_true",
|
||||
help="Print planned actions without writing files.",
|
||||
)
|
||||
sync.add_argument(
|
||||
"--include",
|
||||
action="append",
|
||||
help="Glob pattern for template DXF files to include. May be repeated.",
|
||||
)
|
||||
sync.add_argument(
|
||||
"--exclude",
|
||||
action="append",
|
||||
help="Glob pattern for template DXF files to exclude. May be repeated.",
|
||||
)
|
||||
|
||||
return parser.parse_args()
|
||||
|
||||
|
||||
def main() -> int:
|
||||
args = parse_args()
|
||||
template_root = Path(args.template_root)
|
||||
library_path = Path(args.library)
|
||||
include_patterns = merge_patterns(DEFAULT_INCLUDE_PATTERNS, args.include)
|
||||
exclude_patterns = merge_patterns(DEFAULT_EXCLUDE_PATTERNS, args.exclude)
|
||||
|
||||
if args.command == "extract":
|
||||
return extract_library(
|
||||
template_root,
|
||||
library_path,
|
||||
args.dry_run,
|
||||
include_patterns,
|
||||
exclude_patterns,
|
||||
args.skip_conflicts,
|
||||
)
|
||||
if args.command == "sync":
|
||||
return sync_library_to_templates(
|
||||
template_root, library_path, args.dry_run, include_patterns, exclude_patterns
|
||||
)
|
||||
raise ProcessingError(f"Unknown command: {args.command}")
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
raise SystemExit(main())
|
||||
File diff suppressed because it is too large
Load Diff
Loading…
Reference in New Issue