#!/usr/bin/env python3 """Shared schema and semantic validation for CAD showcase artifacts.""" from __future__ import annotations import argparse import copy import fnmatch import json from pathlib import Path from typing import Any SCHEMA_VERSION = 1 CONFIG_VERSION = 1 MANIFEST_VERSION = 1 REPORT_VERSION = 1 ROOT = Path(__file__).resolve().parent.parent SCHEMA_DIR = ROOT / "schemas" LEGACY_CATEGORY_STYLES = { "walls": {"label": "墙体", "color": "#d4cbb8"}, "glazing": {"label": "玻璃/幕墙", "color": "#79b8c9"}, "roof": {"label": "屋顶/屋盖", "color": "#b8ae98"}, "columns": {"label": "柱", "color": "#f58a1f"}, "beams": {"label": "梁/结构", "color": "#1f66c2"}, "railings": {"label": "栏杆/扶手", "color": "#6f746d"}, "doors": {"label": "门/开启线", "color": "#8a6a45"}, "detail_lines": {"label": "平面细节", "color": "#8c9088"}, "floor_lines": {"label": "楼面线", "color": "#18a058"}, "grid": {"label": "轴网", "color": "#20242a"}, "slab": {"label": "楼板", "color": "#c8ccc2"}, } class ValidationFailure(ValueError): """Raised when a config or generated artifact violates the contract.""" def _validator(schema_name: str): try: import jsonschema except ImportError: return None schema = json.loads((SCHEMA_DIR / schema_name).read_text(encoding="utf-8")) return jsonschema.Draft202012Validator(schema) def _format_errors(errors) -> list[str]: result = [] for error in sorted(errors, key=lambda item: list(item.absolute_path)): path = ".".join(str(part) for part in error.absolute_path) or "$" result.append(f"{path}: {error.message}") return result def schema_errors(data: dict[str, Any], schema_name: str) -> list[str]: validator = _validator(schema_name) if validator is not None: return _format_errors(validator.iter_errors(data)) # Blender ships an isolated Python without project dependencies. Keep a # small structural fallback so direct Blender runs still fail on broken # artifacts; normal CPython runs use the full Draft 2020-12 schemas. if schema_name == "building_spec.schema.json": required = {"schema_version", "project", "source", "units", "categories", "floors"} elif schema_name == "extraction_config.schema.json": required = {"config_version"} else: required = {"manifest_version", "name", "default_key", "variants"} return [f"$: missing required property {key!r}" for key in sorted(required - set(data))] def normalize_config(config: dict[str, Any]) -> dict[str, Any]: """Attach the current version while keeping legacy v0 configs readable.""" normalized = dict(config) normalized.setdefault("config_version", CONFIG_VERSION) if normalized.get("origin_strategy") == "min_corner": normalized["origin_strategy"] = "min" return normalized def normalize_spec(spec: dict[str, Any]) -> dict[str, Any]: """Read pre-versioning artifacts while emitting only the current contract.""" normalized = copy.deepcopy(spec) normalized.setdefault("schema_version", SCHEMA_VERSION) project = normalized.get("project", {}) if isinstance(project, str): project = {"name": project, "description": str(normalized.pop("description", ""))} else: project = dict(project) project.setdefault("name", "CAD Building Showcase") project.setdefault("description", str(normalized.pop("description", ""))) normalized["project"] = project source = dict(normalized.get("source", {})) source["config"] = normalize_config(dict(source.get("config", {}))) normalized["source"] = source raw_units = normalized.get("units", {}) units = {"source": raw_units} if isinstance(raw_units, str) else dict(raw_units) scale = float(units.pop("scale", units.get("scale_to_meters", 0.001))) units.setdefault("source", "millimeters" if scale == 0.001 else "unknown") units.setdefault("scale_to_meters", scale) units.setdefault("origin_source", [0.0, 0.0]) normalized["units"] = units raw_categories = normalized.get("categories", {}) categories = copy.deepcopy(raw_categories) if isinstance(raw_categories, dict) else {} configured_categories = source["config"].get("categories", {}) used_categories = { category for floor in normalized.get("floors", {}).values() for category, segments in floor.get("segments", {}).items() if segments } if source["config"].get("use_footprint_slabs"): used_categories.add("slab") for category in sorted(used_categories): if category in categories: continue style = dict(LEGACY_CATEGORY_STYLES.get(category, {"label": category, "color": "#8c9088"})) override = configured_categories.get(category, {}) if isinstance(configured_categories, dict) else {} if isinstance(override, dict): style.update({key: override[key] for key in ("label", "color") if key in override}) categories[category] = style normalized["categories"] = categories for floor in normalized.get("floors", {}).values(): floor.setdefault("source_file", "unknown") for category, segments in floor.get("segments", {}).items(): for segment in segments: segment.setdefault("width", 0.1) segment.setdefault("layer", "") segment.setdefault("source_type", "legacy") return normalized def floor_group(floor_key: str, config: dict[str, Any] | None = None) -> str: """Return the configured stack group used by caps and support checks.""" for pattern, group in (config or {}).get("cap_groups", []): if fnmatch.fnmatch(floor_key.upper(), str(pattern).upper()): return str(group) if floor_key.startswith("AUX_"): return "AUX" if floor_key in {"B1", "B1M"}: return "BASE" return "MAIN" def config_semantic_errors(config: dict[str, Any], dxf_dir: Path | None = None) -> list[str]: errors: list[str] = [] seen: dict[str, str] = {} drawings = config.get("drawings", []) or [] if not drawings: errors.append("drawings: extraction config contains no drawings") for drawing in drawings: file_name = str(drawing.get("file", "")) if dxf_dir is not None and file_name and not (dxf_dir / file_name).exists(): errors.append(f"drawings[{file_name}]: source DXF does not exist under {dxf_dir}") floors = drawing.get("floors") or [{"key": Path(file_name).stem}] for floor in floors: key = str(floor.get("key", "")) location = f"{file_name}:{floor.get('name', key)}" if key in seen: errors.append(f"duplicate floor key {key!r}: used by both {seen[key]} and {location}") else: seen[key] = location order = config.get("floor_order") or [] missing = sorted(set(seen) - set(order)) if order else [] ghosts = sorted(set(order) - set(seen)) if order else [] if missing: errors.append(f"floor_order omits configured floor keys: {missing}") if ghosts: errors.append(f"floor_order contains unknown floor keys: {ghosts}") return errors def validate_config(config: dict[str, Any], dxf_dir: Path | None = None) -> dict[str, Any]: normalized = normalize_config(config) errors = schema_errors(normalized, "extraction_config.schema.json") errors.extend(config_semantic_errors(normalized, dxf_dir)) if errors: raise ValidationFailure("Invalid extraction config:\n- " + "\n- ".join(errors)) return normalized def spec_semantic_errors(spec: dict[str, Any]) -> list[str]: errors: list[str] = [] floors = spec.get("floors", {}) categories = set(spec.get("categories", {})) if not floors: errors.append("floors: spec contains no floors") for key, floor in floors.items(): unknown_categories = sorted( category for category, items in floor.get("segments", {}).items() if items and category not in categories ) if unknown_categories: errors.append(f"floors.{key}.segments: categories missing from spec.categories: {unknown_categories}") segment_count = sum(len(items) for items in floor.get("segments", {}).values()) polygon_count = len((floor.get("footprint") or {}).get("polygons", [])) cap_count = sum(len(cap.get("polygons", [])) for cap in floor.get("caps", [])) if segment_count == 0 and polygon_count == 0 and cap_count == 0: errors.append(f"floors.{key}: floor has no segments, footprint polygons, or caps") for item in spec.get("extraction_report", []): if item.get("status") != "ok": errors.append(f"extraction_report: {item.get('file', '?')} status={item.get('status', '?')}") return errors def validate_spec(spec: dict[str, Any]) -> dict[str, Any]: errors = schema_errors(spec, "building_spec.schema.json") embedded_config = normalize_config(dict(spec.get("source", {}).get("config", {}))) errors.extend(f"source.config.{item}" for item in schema_errors(embedded_config, "extraction_config.schema.json")) errors.extend(spec_semantic_errors(spec)) if errors: raise ValidationFailure("Invalid building spec:\n- " + "\n- ".join(errors)) return spec def validate_manifest(manifest: dict[str, Any]) -> dict[str, Any]: errors = schema_errors(manifest, "variants_manifest.schema.json") keys = [item.get("key") for item in manifest.get("variants", [])] if len(keys) != len(set(keys)): errors.append("variants: duplicate variant keys") if manifest.get("default_key") not in keys: errors.append("default_key: does not reference a variant key") if errors: raise ValidationFailure("Invalid variants manifest:\n- " + "\n- ".join(errors)) return manifest def validate_source_report(report: dict[str, Any], expected_dxf_dir: Path | None = None) -> dict[str, Any]: if not isinstance(report, dict): raise ValidationFailure("Invalid CAD source report:\n- $: expected a JSON object") errors = [] if report.get("report_version") != REPORT_VERSION: errors.append(f"report_version: expected {REPORT_VERSION}, got {report.get('report_version')!r}") gate = report.get("gate") or {} if not isinstance(gate, dict): gate = {} gate_status = gate.get("status") if gate.get("name") != "all_sources_converted_and_readable" or gate_status not in {"PASS", "WARN"}: errors.append( f"gate: all_sources_converted_and_readable must be PASS or a reasoned partial WARN, got {gate_status!r}" ) if gate_status == "WARN" and not str(gate.get("partial_reason", "")).strip(): errors.append("gate.partial_reason: WARN source reports require a non-empty partial reason") files = report.get("files") if not isinstance(files, list) or not files: errors.append("files: report contains no inspected DXF files") else: readable = 0 for index, item in enumerate(files): if not isinstance(item, dict): errors.append(f"files[{index}]: expected an object") continue try: entity_count = int(item.get("modelspace_entities", 0) or 0) except (TypeError, ValueError): entity_count = 0 if item.get("status") == "ok" and entity_count > 0: readable += 1 elif gate_status == "PASS": errors.append( f"files[{index}]: {item.get('file', '?')} is not readable and nonempty " f"(status={item.get('status')!r}, entities={item.get('modelspace_entities')!r})" ) if readable == 0: errors.append("files: partial reports still require at least one readable nonempty DXF") if expected_dxf_dir is not None: reported = Path(str(report.get("dxf_sanitized", ""))) if not reported.is_absolute(): reported = ROOT / reported if reported.resolve() != expected_dxf_dir.resolve(): errors.append( f"dxf_sanitized: report points to {reported.resolve()}, expected {expected_dxf_dir.resolve()}" ) elif expected_dxf_dir.exists(): report_items = files if isinstance(files, list) else [] reported_files = {str(item.get("file")) for item in report_items if isinstance(item, dict)} actual_files = {path.name for path in expected_dxf_dir.glob("*.dxf")} if reported_files != actual_files: errors.append( "files: source report and sanitized directory differ " f"(missing={sorted(actual_files - reported_files)}, stale={sorted(reported_files - actual_files)})" ) if errors: raise ValidationFailure("Invalid CAD source report:\n- " + "\n- ".join(errors)) return report def main() -> int: parser = argparse.ArgumentParser(description=__doc__) parser.add_argument("kind", choices=("config", "spec", "manifest", "source-report")) parser.add_argument("path") parser.add_argument("--dxf-dir", help="Required for checking config source-file existence") args = parser.parse_args() try: data = json.loads(Path(args.path).read_text(encoding="utf-8")) if args.kind == "config": validate_config(data, Path(args.dxf_dir) if args.dxf_dir else None) elif args.kind == "spec": validate_spec(data) elif args.kind == "manifest": validate_manifest(data) else: validate_source_report(data, Path(args.dxf_dir) if args.dxf_dir else None) except (OSError, json.JSONDecodeError, ValidationFailure, TypeError, ValueError, AttributeError) as exc: print(str(exc)) return 3 print(json.dumps({"status": "PASS", "kind": args.kind, "path": args.path}, ensure_ascii=False)) return 0 if __name__ == "__main__": raise SystemExit(main())