Download CODE/evaluation/eval/v5_sidecar.py from QLU-LLM/CAD: direct link, hf CLI and curl.
- Browser
- Download file 52.9 kB
-
https://huggingface.co/datasets/QLU-LLM/CAD/resolve/main/CODE/evaluation/eval/v5_sidecar.py
- Command line
-
hf download hf://datasets/QLU-LLM/CAD/CODE/evaluation/eval/v5_sidecar.py
-
curl -L -o v5_sidecar.py https://huggingface.co/datasets/QLU-LLM/CAD/resolve/main/CODE/evaluation/eval/v5_sidecar.py
52.9 kB
| #!/usr/bin/env python3 | |
| """Build an evaluator-only, auditable GT sidecar for the direct ezdxf task. | |
| The sidecar is deliberately *not* a model target or an intermediate DSL. It | |
| only freezes facts that can be recovered from an existing dataset row and its | |
| ground-truth DXF. In particular, view roles and physical feature bindings are | |
| never asserted when the DXF alone does not prove them: they are emitted as | |
| heuristic hints with explicit audit flags. | |
| Library API:: | |
| build_sidecar_row(row, dataset_path=None) -> dict | |
| build_sidecar_dataset(dataset_path, output_path, limit=None, strict=False) | |
| load_sidecar_jsonl(path) -> dict[id, row] | |
| CLI:: | |
| python eval/v5_sidecar.py \ | |
| --dataset code_datasets/physical_v1/eval_val.jsonl \ | |
| --out results/metric_v5/eval_val_sidecar.jsonl \ | |
| [--limit 32] [--strict] | |
| ``--strict`` applies to structural failures (missing/unreadable GT, malformed | |
| dataset rows, duplicate IDs). It intentionally does not fail merely because | |
| a conservative inference is marked ``needs_audit``. | |
| """ | |
| from __future__ import annotations | |
| import argparse | |
| import hashlib | |
| import json | |
| import math | |
| import os | |
| import re | |
| import statistics | |
| import tempfile | |
| from collections import Counter, defaultdict | |
| from pathlib import Path | |
| from typing import Any, Iterable, Mapping, Sequence | |
| import ezdxf | |
| from ezdxf import bbox as ezdxf_bbox | |
| SCHEMA_VERSION = "edp-evaluator-sidecar-v5.0" | |
| REQUIRED_TOP_LEVEL_FIELDS = ( | |
| "schema_version", | |
| "id", | |
| "category", | |
| "tier", | |
| "gt_dxf_sha256", | |
| "views", | |
| "dimensions", | |
| "fmfs", | |
| "parameters", | |
| "eligibility", | |
| "audit_flags", | |
| ) | |
| # These bounded entity types are sufficient for the current GT corpus and are | |
| # safe inputs to ezdxf.bbox.extents(). Unknown drawable types stay in the full | |
| # inventory but do not silently influence view detection. | |
| VIEW_GEOMETRY_TYPES = frozenset( | |
| { | |
| "LINE", | |
| "CIRCLE", | |
| "ARC", | |
| "LWPOLYLINE", | |
| "POLYLINE", | |
| "ELLIPSE", | |
| "SPLINE", | |
| "SOLID", | |
| "TRACE", | |
| "3DFACE", | |
| } | |
| ) | |
| ANNOTATION_ENTITY_TYPES = frozenset( | |
| {"DIMENSION", "TEXT", "MTEXT", "LEADER", "MLEADER", "TOLERANCE"} | |
| ) | |
| AUXILIARY_ENTITY_TYPES = frozenset( | |
| {"POINT", "XLINE", "RAY", "HATCH", "IMAGE", "WIPEOUT", "VIEWPORT"} | |
| ) | |
| PAIR_MEASUREMENT_RE = re.compile( | |
| r"(?<![\w.])" | |
| r"(?P<first>[+-]?(?:\d+(?:\.\d*)?|\.\d+))\s*" | |
| r"[x\u00d7]\s*" | |
| r"(?P<second>[+-]?(?:\d+(?:\.\d*)?|\.\d+))\s*" | |
| r"(?P<unit>mm|millimet(?:er|re)s?)\b", | |
| re.IGNORECASE, | |
| ) | |
| SINGLE_MEASUREMENT_RE = re.compile( | |
| r"(?<![\w.])" | |
| r"(?P<value>[+-]?(?:\d+(?:\.\d*)?|\.\d+))\s*" | |
| r"(?P<unit>mm|millimet(?:er|re)s?)\b", | |
| re.IGNORECASE, | |
| ) | |
| NUMBER_RE = re.compile(r"[-+]?(?:\d+(?:\.\d*)?|\.\d+)") | |
| class SidecarError(ValueError): | |
| """Raised for input failures that make a trustworthy sidecar impossible.""" | |
| def _rounded(value: Any, digits: int = 9) -> float | None: | |
| try: | |
| result = float(value) | |
| except (TypeError, ValueError): | |
| return None | |
| if not math.isfinite(result): | |
| return None | |
| result = round(result, digits) | |
| return 0.0 if abs(result) < 0.5 * (10.0 ** -digits) else result | |
| def _point2(value: Any) -> list[float] | None: | |
| try: | |
| x = _rounded(value.x) | |
| y = _rounded(value.y) | |
| except (AttributeError, TypeError): | |
| try: | |
| x = _rounded(value[0]) | |
| y = _rounded(value[1]) | |
| except (IndexError, TypeError): | |
| return None | |
| return [x, y] if x is not None and y is not None else None | |
| def _sha256(path: Path) -> str: | |
| digest = hashlib.sha256() | |
| with path.open("rb") as handle: | |
| for block in iter(lambda: handle.read(1024 * 1024), b""): | |
| digest.update(block) | |
| return digest.hexdigest() | |
| def _text_sha256(text: str) -> str: | |
| return hashlib.sha256(text.encode("utf-8")).hexdigest() | |
| def _audit( | |
| flags: list[dict[str, Any]], | |
| code: str, | |
| severity: str, | |
| scope: str, | |
| message: str, | |
| **details: Any, | |
| ) -> None: | |
| item: dict[str, Any] = { | |
| "code": code, | |
| "severity": severity, | |
| "scope": scope, | |
| "message": message, | |
| } | |
| if details: | |
| item["details"] = details | |
| flags.append(item) | |
| def _user_prompt(row: Mapping[str, Any]) -> str: | |
| messages = row.get("messages", []) | |
| if not isinstance(messages, list): | |
| return "" | |
| users = [ | |
| message.get("content", "") | |
| for message in messages | |
| if isinstance(message, Mapping) and message.get("role") == "user" | |
| ] | |
| if len(users) != 1 or not isinstance(users[0], str): | |
| return "" | |
| return users[0] | |
| def _feature_text(prompt: str) -> str: | |
| marker = "Feature description:" | |
| return prompt.split(marker, 1)[1].strip() if marker in prompt else prompt.strip() | |
| def _semantic_hint(text: str, start: int, end: int, *, pair: bool) -> str: | |
| before = text[max(0, start - 56) : start].lower() | |
| after = text[end : min(len(text), end + 28)].lower() | |
| context = before + " " + after | |
| if pair: | |
| if "bounding box" in before: | |
| return "bounding_box_extent_pair" | |
| if "cutout" in before: | |
| return "cutout_extent_pair" | |
| if "square" in before or "rectang" in before: | |
| return "planar_extent_pair" | |
| return "extent_pair" | |
| if "hole" in before[-48:] and re.search(r"diameter\s*$", before): | |
| return "hole_diameter" | |
| if re.search(r"diameter\s*$", before): | |
| return "diameter" | |
| if re.search(r"radius\s*$", before): | |
| return "radius" | |
| if re.search(r"thickness\s+of\s*$", before) or "thickness" in before[-28:]: | |
| return "extrusion_thickness" | |
| if re.match(r"\s*(?:mm\s+)?wide\b", after): | |
| return "width" | |
| if re.match(r"\s*(?:mm\s+)?tall\b", after): | |
| return "height" | |
| return "unknown" | |
| def extract_prompt_parameters(prompt: str) -> dict[str, Any]: | |
| """Return traceable numeric millimetre mentions, not feature truth. | |
| Counts such as "six straight edges" and the 2D/3D wording are intentionally | |
| excluded. ``A x B mm`` contributes two scalar candidates tied by one group | |
| ID. The original sign is retained; magnitude matching is reported later | |
| but never rewrites the prompt. | |
| """ | |
| text = _feature_text(prompt) | |
| occupied: list[tuple[int, int]] = [] | |
| raw: list[dict[str, Any]] = [] | |
| group_index = 0 | |
| for match in PAIR_MEASUREMENT_RE.finditer(text): | |
| occupied.append(match.span()) | |
| group_id = f"g{group_index:03d}" | |
| group_index += 1 | |
| hint = _semantic_hint(text, match.start(), match.end(), pair=True) | |
| for component, name in enumerate(("first", "second"), 1): | |
| raw.append( | |
| { | |
| "group_id": group_id, | |
| "component": component, | |
| "value": _rounded(match.group(name)), | |
| "unit": "mm", | |
| "semantic_hint": hint, | |
| "raw_group": match.group(0), | |
| "span": [match.start(), match.end()], | |
| "context": text[max(0, match.start() - 40) : match.end() + 40], | |
| } | |
| ) | |
| for match in SINGLE_MEASUREMENT_RE.finditer(text): | |
| if any(match.start() < end and match.end() > start for start, end in occupied): | |
| continue | |
| group_id = f"g{group_index:03d}" | |
| group_index += 1 | |
| raw.append( | |
| { | |
| "group_id": group_id, | |
| "component": 1, | |
| "value": _rounded(match.group("value")), | |
| "unit": "mm", | |
| "semantic_hint": _semantic_hint( | |
| text, match.start(), match.end(), pair=False | |
| ), | |
| "raw_group": match.group(0), | |
| "span": [match.start(), match.end()], | |
| "context": text[max(0, match.start() - 40) : match.end() + 40], | |
| } | |
| ) | |
| raw.sort(key=lambda item: (item["span"][0], item["component"])) | |
| for index, item in enumerate(raw): | |
| item["parameter_id"] = f"p{index:03d}" | |
| return { | |
| "status": "extracted" if raw else "unknown", | |
| "source": "user_prompt_numeric_mentions", | |
| "feature_text_sha256": _text_sha256(text), | |
| "candidate_count": len(raw), | |
| "prompt_numbers_mm": [item["value"] for item in raw], | |
| "candidates": raw, | |
| "semantic_binding": "needs_audit" if raw else "unknown", | |
| "notes": ( | |
| "Candidates are evaluator metadata only; semantic hints are not " | |
| "model targets and are not sufficient for a physical reward." | |
| ), | |
| } | |
| def _parse_dimension_text(text: str) -> tuple[str, float | None]: | |
| raw = text or "" | |
| compact = raw.strip().replace(" ", "") | |
| lower = compact.lower() | |
| family = "linear" | |
| if lower.startswith("%%c") or compact.startswith(("\u00d8", "\u2205")): | |
| family = "diameter" | |
| elif lower.startswith("r"): | |
| family = "radius" | |
| cleaned = re.sub(r"%%[a-zA-Z]", "", compact) | |
| cleaned = cleaned.replace("\u00d8", "").replace("\u2205", "") | |
| cleaned = re.sub(r"^[Rr]", "", cleaned) | |
| match = NUMBER_RE.search(cleaned) | |
| return family, _rounded(match.group(0)) if match else None | |
| def _dimension_family(dimtype: int, text: str) -> str: | |
| base = dimtype & 0x0F | |
| by_type = { | |
| 0: "linear", | |
| 1: "aligned", | |
| 2: "angular", | |
| 3: "diameter", | |
| 4: "radius", | |
| 5: "angular3", | |
| 6: "ordinate", | |
| } | |
| family = by_type.get(base, f"type{base}") | |
| text_family, _ = _parse_dimension_text(text) | |
| if family not in {"linear", "aligned", "diameter", "radius"}: | |
| return text_family if text_family != "linear" else family | |
| return family | |
| def _entity_bbox(entity: Any) -> tuple[dict[str, Any] | None, str]: | |
| try: | |
| bounds = ezdxf_bbox.extents([entity], fast=False) | |
| if not bounds.has_data: | |
| return None, "empty" | |
| minimum = _point2(bounds.extmin) | |
| maximum = _point2(bounds.extmax) | |
| if minimum is None or maximum is None: | |
| return None, "non_finite" | |
| return { | |
| "min": minimum, | |
| "max": maximum, | |
| "width": _rounded(maximum[0] - minimum[0]), | |
| "height": _rounded(maximum[1] - minimum[1]), | |
| }, "ok" | |
| except Exception as error: # retained in the inventory for auditability | |
| return None, f"{type(error).__name__}: {error}" | |
| def _dimension_record(entity: Any, index: int) -> dict[str, Any]: | |
| raw_dimtype = int(entity.dxf.dimtype) if entity.dxf.hasattr("dimtype") else 0 | |
| text = str(entity.dxf.text) if entity.dxf.hasattr("text") else "" | |
| reference_points: dict[str, list[float]] = {} | |
| for name in ("defpoint", "defpoint2", "defpoint3", "defpoint4", "defpoint5"): | |
| if entity.dxf.hasattr(name): | |
| point = _point2(getattr(entity.dxf, name)) | |
| if point is not None: | |
| reference_points[name] = point | |
| base = raw_dimtype & 0x0F | |
| if base in (0, 1) and {"defpoint2", "defpoint3"} <= reference_points.keys(): | |
| first = reference_points["defpoint2"] | |
| second = reference_points["defpoint3"] | |
| binding = [_rounded((first[0] + second[0]) / 2), _rounded((first[1] + second[1]) / 2)] | |
| elif base in (3, 4) and "defpoint4" in reference_points: | |
| binding = list(reference_points["defpoint4"]) | |
| else: | |
| binding = reference_points.get("defpoint") | |
| try: | |
| measurement_raw = entity.get_measurement() | |
| measurement = _rounded(measurement_raw) | |
| except Exception: | |
| measurement = None | |
| _, display_value = _parse_dimension_text(text) | |
| drawing_scale_ratio = ( | |
| _rounded(display_value / measurement) | |
| if display_value is not None | |
| and measurement is not None | |
| and abs(measurement) > 1e-12 | |
| else None | |
| ) | |
| return { | |
| "id": f"d{index:03d}", | |
| "index": index, | |
| "handle": str(entity.dxf.handle) if entity.dxf.hasattr("handle") else None, | |
| "layer": str(entity.dxf.layer) if entity.dxf.hasattr("layer") else "0", | |
| "dimtype": raw_dimtype, | |
| "family": _dimension_family(raw_dimtype, text), | |
| "text": text, | |
| "display_value": display_value, | |
| "measurement": measurement, | |
| "definition_point": reference_points.get("defpoint"), | |
| "drawing_scale_ratio": drawing_scale_ratio, | |
| "binding_point": binding, | |
| "reference_points": reference_points, | |
| "view_candidate_index": None, | |
| "nearest_view_role": None, | |
| "nearest_view_position": None, | |
| "scale_consistent": None, | |
| "reliable": False, | |
| "reliability_reasons": [], | |
| } | |
| def _layer_hint(name: str, linetype: str) -> str: | |
| token = f"{name} {linetype}".lower() | |
| if "hidden" in token or "dash" in token: | |
| return "hidden" | |
| if "center" in token or "centre" in token: | |
| return "center" | |
| if "dim" in token: | |
| return "dimension" | |
| return "visible_or_unknown" | |
| def _extract_dxf(doc: Any, flags: list[dict[str, Any]]) -> dict[str, Any]: | |
| modelspace = list(doc.modelspace()) | |
| type_counts: Counter[str] = Counter() | |
| layer_counts: Counter[str] = Counter() | |
| geometry_type_counts: Counter[str] = Counter() | |
| geometry_layer_counts: Counter[str] = Counter() | |
| entity_records: list[dict[str, Any]] = [] | |
| geometry_records: list[dict[str, Any]] = [] | |
| dimensions: list[dict[str, Any]] = [] | |
| unknown_types: Counter[str] = Counter() | |
| for index, entity in enumerate(modelspace): | |
| entity_type = entity.dxftype() | |
| layer = str(entity.dxf.layer) if entity.dxf.hasattr("layer") else "0" | |
| type_counts[entity_type] += 1 | |
| layer_counts[layer] += 1 | |
| record: dict[str, Any] = { | |
| "index": index, | |
| "handle": str(entity.dxf.handle) if entity.dxf.hasattr("handle") else None, | |
| "type": entity_type, | |
| "layer": layer, | |
| "view_candidate_index": None, | |
| } | |
| if entity_type in VIEW_GEOMETRY_TYPES: | |
| bounds, bbox_status = _entity_bbox(entity) | |
| record["bbox"] = bounds | |
| record["bbox_status"] = bbox_status | |
| geometry_type_counts[entity_type] += 1 | |
| geometry_layer_counts[layer] += 1 | |
| if bounds is not None: | |
| geometry_records.append(record) | |
| else: | |
| _audit( | |
| flags, | |
| "geometry_bbox_failed", | |
| "warning", | |
| "entities", | |
| "A supported geometry entity has no usable bounding box.", | |
| entity_index=index, | |
| entity_type=entity_type, | |
| bbox_status=bbox_status, | |
| ) | |
| elif entity_type == "DIMENSION": | |
| dimensions.append(_dimension_record(entity, len(dimensions))) | |
| elif entity_type not in ANNOTATION_ENTITY_TYPES | AUXILIARY_ENTITY_TYPES: | |
| unknown_types[entity_type] += 1 | |
| entity_records.append(record) | |
| if unknown_types: | |
| _audit( | |
| flags, | |
| "unsupported_modelspace_entity_types", | |
| "warning", | |
| "entities", | |
| "Entity types outside the conservative view extractor were retained in the inventory.", | |
| counts=dict(sorted(unknown_types.items())), | |
| ) | |
| layer_inventory: list[dict[str, Any]] = [] | |
| known_layer_names = {str(layer.dxf.name) for layer in doc.layers} | |
| for name in sorted(known_layer_names | set(layer_counts), key=str.casefold): | |
| try: | |
| layer = doc.layers.get(name) | |
| linetype = str(layer.dxf.linetype) | |
| color = int(layer.dxf.color) | |
| is_on = bool(layer.is_on()) | |
| is_frozen = bool(layer.is_frozen()) | |
| except Exception: | |
| linetype, color, is_on, is_frozen = "unknown", None, None, None | |
| layer_inventory.append( | |
| { | |
| "name": name, | |
| "linetype": linetype, | |
| "color": color, | |
| "is_on": is_on, | |
| "is_frozen": is_frozen, | |
| "visibility_hint": _layer_hint(name, linetype), | |
| "modelspace_entity_count": layer_counts.get(name, 0), | |
| "view_geometry_entity_count": geometry_layer_counts.get(name, 0), | |
| } | |
| ) | |
| return { | |
| "modelspace_entity_count": len(modelspace), | |
| "by_type": dict(sorted(type_counts.items())), | |
| "view_geometry_by_type": dict(sorted(geometry_type_counts.items())), | |
| "unsupported_by_type": dict(sorted(unknown_types.items())), | |
| "items": entity_records, | |
| "geometry_records": geometry_records, | |
| "layers": layer_inventory, | |
| "dimension_items": dimensions, | |
| } | |
| def _merge_intervals( | |
| intervals: Iterable[tuple[float, float]], tolerance: float | |
| ) -> list[tuple[float, float]]: | |
| ordered = sorted((min(a, b), max(a, b)) for a, b in intervals) | |
| if not ordered: | |
| return [] | |
| merged: list[list[float]] = [[ordered[0][0], ordered[0][1]]] | |
| for start, end in ordered[1:]: | |
| if start <= merged[-1][1] + tolerance: | |
| merged[-1][1] = max(merged[-1][1], end) | |
| else: | |
| merged.append([start, end]) | |
| return [(start, end) for start, end in merged] | |
| def _axis_gaps( | |
| records: Sequence[dict[str, Any]], axis: int, tolerance: float | |
| ) -> list[dict[str, float]]: | |
| merged = _merge_intervals( | |
| ( | |
| (record["bbox"]["min"][axis], record["bbox"]["max"][axis]) | |
| for record in records | |
| if record.get("bbox") is not None | |
| ), | |
| tolerance, | |
| ) | |
| return [ | |
| { | |
| "low": _rounded(left[1]), | |
| "high": _rounded(right[0]), | |
| "width": _rounded(right[0] - left[1]), | |
| "cut": _rounded((left[1] + right[0]) / 2), | |
| } | |
| for left, right in zip(merged, merged[1:]) | |
| if right[0] - left[1] > tolerance | |
| ] | |
| def _cell_for_bbox(bounds: Mapping[str, Any], x_cut: float, y_cut: float) -> str | None: | |
| minimum, maximum = bounds["min"], bounds["max"] | |
| if maximum[0] <= x_cut: | |
| horizontal = "left" | |
| elif minimum[0] >= x_cut: | |
| horizontal = "right" | |
| else: | |
| return None | |
| if maximum[1] <= y_cut: | |
| vertical = "lower" | |
| elif minimum[1] >= y_cut: | |
| vertical = "upper" | |
| else: | |
| return None | |
| return f"{vertical}_{horizontal}" | |
| def _cell_for_point(point: Sequence[float] | None, x_cut: float, y_cut: float) -> str | None: | |
| if point is None or len(point) < 2: | |
| return None | |
| horizontal = "left" if point[0] <= x_cut else "right" | |
| vertical = "lower" if point[1] <= y_cut else "upper" | |
| return f"{vertical}_{horizontal}" | |
| def _union_bbox(records: Sequence[dict[str, Any]]) -> dict[str, Any]: | |
| min_x = min(record["bbox"]["min"][0] for record in records) | |
| min_y = min(record["bbox"]["min"][1] for record in records) | |
| max_x = max(record["bbox"]["max"][0] for record in records) | |
| max_y = max(record["bbox"]["max"][1] for record in records) | |
| return { | |
| "min": [_rounded(min_x), _rounded(min_y)], | |
| "max": [_rounded(max_x), _rounded(max_y)], | |
| "width": _rounded(max_x - min_x), | |
| "height": _rounded(max_y - min_y), | |
| "centroid": [_rounded((min_x + max_x) / 2), _rounded((min_y + max_y) / 2)], | |
| } | |
| def _visibility_hint(layer: str) -> str: | |
| lower = layer.lower() | |
| if "hidden" in lower or "dash" in lower: | |
| return "hidden" | |
| if "center" in lower or "centre" in lower: | |
| return "center" | |
| return "visible_or_unknown" | |
| def detect_view_candidates( | |
| geometry_records: Sequence[dict[str, Any]], | |
| flags: list[dict[str, Any]], | |
| ) -> dict[str, Any]: | |
| """Detect three spatial regions via two empty projection gaps. | |
| This is deterministic and invariant to entity order. It does not use a | |
| learned classifier. A standard upper-left/lower-left/upper-right layout | |
| receives front/top/right *hints* only; the role assignment remains an audit | |
| item because position alone is not geometric proof. | |
| """ | |
| if not geometry_records: | |
| _audit( | |
| flags, | |
| "no_supported_view_geometry", | |
| "error", | |
| "views", | |
| "No bounded supported geometry is available for view detection.", | |
| ) | |
| return { | |
| "status": "unknown", | |
| "method": "orthogonal_empty_gap_v1", | |
| "candidate_count": 0, | |
| "candidates": [], | |
| "split": None, | |
| "role_assignment": {"status": "unknown", "basis": None}, | |
| } | |
| global_bbox = _union_bbox(geometry_records) | |
| diagonal = math.hypot(global_bbox["width"], global_bbox["height"]) | |
| tolerance = max(1e-7, 1e-7 * max(diagonal, 1.0)) | |
| x_gaps = _axis_gaps(geometry_records, 0, tolerance) | |
| y_gaps = _axis_gaps(geometry_records, 1, tolerance) | |
| expected_cells = {"upper_left", "lower_left", "upper_right"} | |
| proposals: list[dict[str, Any]] = [] | |
| for x_gap in x_gaps: | |
| for y_gap in y_gaps: | |
| grouped: dict[str, list[dict[str, Any]]] = defaultdict(list) | |
| crossed = False | |
| for record in geometry_records: | |
| cell = _cell_for_bbox(record["bbox"], x_gap["cut"], y_gap["cut"]) | |
| if cell is None: | |
| crossed = True | |
| break | |
| grouped[cell].append(record) | |
| occupied = set(grouped) | |
| if crossed or len(occupied) != 3: | |
| continue | |
| minimum_gap_ratio = min(x_gap["width"], y_gap["width"]) / max(diagonal, 1e-12) | |
| score = minimum_gap_ratio + ( | |
| 1.0 if occupied == expected_cells else 0.0 | |
| ) | |
| proposals.append( | |
| { | |
| "score": score, | |
| "x_gap": x_gap, | |
| "y_gap": y_gap, | |
| "grouped": grouped, | |
| "occupied": occupied, | |
| "minimum_gap_ratio": minimum_gap_ratio, | |
| } | |
| ) | |
| if not proposals: | |
| _audit( | |
| flags, | |
| "view_split_not_found", | |
| "warning", | |
| "views", | |
| "No pair of empty x/y gaps produced exactly three occupied regions.", | |
| x_gap_count=len(x_gaps), | |
| y_gap_count=len(y_gaps), | |
| ) | |
| return { | |
| "status": "unknown", | |
| "method": "orthogonal_empty_gap_v1", | |
| "global_geometry_bbox": global_bbox, | |
| "candidate_count": 0, | |
| "candidates": [], | |
| "split": None, | |
| "role_assignment": {"status": "unknown", "basis": None}, | |
| } | |
| selected = sorted( | |
| proposals, | |
| key=lambda proposal: ( | |
| -proposal["score"], | |
| proposal["x_gap"]["cut"], | |
| proposal["y_gap"]["cut"], | |
| ), | |
| )[0] | |
| conventional = selected["occupied"] == expected_cells | |
| status = ( | |
| "ok" | |
| if conventional and selected["minimum_gap_ratio"] >= 0.005 | |
| else "needs_audit" | |
| ) | |
| if not conventional: | |
| _audit( | |
| flags, | |
| "nonstandard_three_region_layout", | |
| "warning", | |
| "views", | |
| "Three regions were found, but not in the dataset's common L layout.", | |
| occupied_cells=sorted(selected["occupied"]), | |
| ) | |
| if selected["minimum_gap_ratio"] < 0.005: | |
| _audit( | |
| flags, | |
| "small_view_separation_gap", | |
| "warning", | |
| "views", | |
| "The smallest separating gap is below 0.5% of the drawing diagonal.", | |
| minimum_gap_ratio=_rounded(selected["minimum_gap_ratio"]), | |
| ) | |
| role_by_cell = { | |
| "upper_left": "front_candidate", | |
| "lower_left": "top_candidate", | |
| "upper_right": "right_candidate", | |
| } | |
| position_order = {"upper_left": 0, "lower_left": 1, "upper_right": 2, "lower_right": 3} | |
| candidates: list[dict[str, Any]] = [] | |
| record_to_candidate: dict[int, int] = {} | |
| for cell in sorted(selected["occupied"], key=lambda value: position_order[value]): | |
| records = selected["grouped"][cell] | |
| type_counts = Counter(record["type"] for record in records) | |
| layer_counts = Counter(record["layer"] for record in records) | |
| visibility_counts = Counter(_visibility_hint(record["layer"]) for record in records) | |
| candidate_index = len(candidates) | |
| for record in records: | |
| record_to_candidate[record["index"]] = candidate_index | |
| candidates.append( | |
| { | |
| "index": candidate_index, | |
| "position_hint": cell, | |
| "role_hint": role_by_cell.get(cell) if conventional else None, | |
| "name": ( | |
| role_by_cell[cell].removesuffix("_candidate") | |
| if conventional and cell in role_by_cell | |
| else f"view_{candidate_index}" | |
| ), | |
| "role_confidence": "heuristic" if conventional else "unknown", | |
| "geometry_bbox": _union_bbox(records), | |
| "bbox": [ | |
| *_union_bbox(records)["min"], | |
| *_union_bbox(records)["max"], | |
| ], | |
| "entity_count": len(records), | |
| "entity_indices": sorted(record["index"] for record in records), | |
| "entity_types": dict(sorted(type_counts.items())), | |
| "layer_counts": dict(sorted(layer_counts.items())), | |
| "visibility_counts": dict(sorted(visibility_counts.items())), | |
| "dimension_indices": [], | |
| } | |
| ) | |
| for record in geometry_records: | |
| record["view_candidate_index"] = record_to_candidate.get(record["index"]) | |
| if conventional: | |
| _audit( | |
| flags, | |
| "view_roles_are_heuristic", | |
| "info", | |
| "views", | |
| "Front/top/right labels are positional hints and require an audited convention.", | |
| ) | |
| return { | |
| "status": status, | |
| "method": "orthogonal_empty_gap_v1", | |
| "global_geometry_bbox": global_bbox, | |
| "candidate_count": len(candidates), | |
| "candidates": candidates, | |
| "split": { | |
| "x_cut": selected["x_gap"]["cut"], | |
| "y_cut": selected["y_gap"]["cut"], | |
| "x_gap": selected["x_gap"], | |
| "y_gap": selected["y_gap"], | |
| "minimum_gap_ratio": _rounded(selected["minimum_gap_ratio"]), | |
| "occupied_cells": sorted(selected["occupied"]), | |
| }, | |
| "role_assignment": { | |
| "status": "needs_audit" if conventional else "unknown", | |
| "basis": "dataset_position_convention" if conventional else None, | |
| "mapping": role_by_cell if conventional else {}, | |
| }, | |
| } | |
| def _attach_dimensions_to_views( | |
| dimensions: list[dict[str, Any]], views: dict[str, Any] | |
| ) -> None: | |
| split = views.get("split") | |
| if not split: | |
| return | |
| by_position = { | |
| candidate["position_hint"]: candidate | |
| for candidate in views.get("candidates", []) | |
| } | |
| for dimension in dimensions: | |
| cell = _cell_for_point( | |
| dimension.get("binding_point"), split["x_cut"], split["y_cut"] | |
| ) | |
| candidate = by_position.get(cell) | |
| if candidate is None: | |
| continue | |
| dimension["view_candidate_index"] = candidate["index"] | |
| dimension["nearest_view_role"] = candidate.get("role_hint") | |
| dimension["nearest_view_position"] = candidate.get("position_hint") | |
| candidate["dimension_indices"].append(dimension["index"]) | |
| def _dimension_manifest( | |
| items: list[dict[str, Any]], flags: list[dict[str, Any]] | |
| ) -> dict[str, Any]: | |
| family_counts = Counter(item["family"] for item in items) | |
| unparsed = [item["index"] for item in items if item["display_value"] is None] | |
| invalid_measurements = [item["index"] for item in items if item["measurement"] is None] | |
| zero_conflicts = [ | |
| item["index"] | |
| for item in items | |
| if item["measurement"] is not None | |
| and abs(item["measurement"]) <= 1e-12 | |
| and item["display_value"] not in (None, 0.0) | |
| ] | |
| signatures: defaultdict[tuple[Any, ...], list[int]] = defaultdict(list) | |
| for item in items: | |
| signature = ( | |
| item["family"], | |
| item["display_value"], | |
| tuple(item["binding_point"] or ()), | |
| tuple(item["definition_point"] or ()), | |
| ) | |
| signatures[signature].append(item["index"]) | |
| duplicate_groups = [indices for indices in signatures.values() if len(indices) > 1] | |
| ratios = [ | |
| float(item["drawing_scale_ratio"]) | |
| for item in items | |
| if isinstance(item.get("drawing_scale_ratio"), (int, float)) | |
| and float(item["drawing_scale_ratio"]) > 0 | |
| ] | |
| consensus_ratio = statistics.median(ratios) if ratios else None | |
| scale_qualities: list[float] = [] | |
| for item in items: | |
| ratio = item.get("drawing_scale_ratio") | |
| if consensus_ratio is not None and isinstance(ratio, (int, float)) and ratio > 0: | |
| relative_log_error = abs(math.log(float(ratio) / consensus_ratio)) | |
| item["scale_consistent"] = relative_log_error <= math.log1p(0.05) | |
| item["scale_quality"] = _rounded(math.exp(-relative_log_error / 0.05)) | |
| scale_qualities.append(float(item["scale_quality"])) | |
| else: | |
| item["scale_consistent"] = False | |
| item["scale_quality"] = 0.0 | |
| reasons: list[str] = [] | |
| if item.get("family") not in {"linear", "aligned", "diameter", "radius"}: | |
| reasons.append("unsupported_dimension_family") | |
| if item.get("display_value") is None: | |
| reasons.append("missing_display_value") | |
| if item.get("measurement") is None or abs(float(item.get("measurement") or 0.0)) <= 1e-12: | |
| reasons.append("missing_or_zero_measurement") | |
| if item.get("binding_point") is None: | |
| reasons.append("missing_binding_point") | |
| if item.get("view_candidate_index") is None: | |
| reasons.append("view_binding_unknown") | |
| if not item["scale_consistent"]: | |
| reasons.append("drawing_scale_outlier") | |
| item["reliability_reasons"] = reasons | |
| item["reliable"] = not reasons | |
| if not items: | |
| _audit( | |
| flags, | |
| "no_native_dimensions", | |
| "warning", | |
| "dimensions", | |
| "The GT modelspace contains no native DIMENSION entities.", | |
| ) | |
| if unparsed: | |
| _audit( | |
| flags, | |
| "unparsed_dimension_text", | |
| "warning", | |
| "dimensions", | |
| "Some DIMENSION text overrides do not expose a numeric value.", | |
| indices=unparsed, | |
| ) | |
| if invalid_measurements: | |
| _audit( | |
| flags, | |
| "invalid_dimension_measurement", | |
| "warning", | |
| "dimensions", | |
| "Some native DIMENSION measurements are unavailable or non-finite.", | |
| indices=invalid_measurements, | |
| ) | |
| if zero_conflicts: | |
| _audit( | |
| flags, | |
| "zero_measurement_nonzero_display", | |
| "warning", | |
| "dimensions", | |
| "A non-zero display value is attached to a zero geometric measurement.", | |
| indices=zero_conflicts, | |
| ) | |
| if duplicate_groups: | |
| _audit( | |
| flags, | |
| "duplicate_dimension_signatures", | |
| "warning", | |
| "dimensions", | |
| "Exact duplicate dimension signatures require review before coverage scoring.", | |
| groups=duplicate_groups, | |
| ) | |
| scale_outliers = [item["index"] for item in items if not item["scale_consistent"]] | |
| if scale_outliers: | |
| _audit( | |
| flags, | |
| "dimension_scale_outliers", | |
| "warning", | |
| "dimensions", | |
| "Some GT dimensions do not agree with the sheet drawing scale.", | |
| indices=scale_outliers, | |
| ) | |
| status = "ok" | |
| if not items: | |
| status = "unknown" | |
| elif unparsed or invalid_measurements or zero_conflicts or duplicate_groups: | |
| status = "needs_audit" | |
| return { | |
| "status": status, | |
| "count": len(items), | |
| "by_family": dict(sorted(family_counts.items())), | |
| "numeric_display_count": len(items) - len(unparsed), | |
| "valid_measurement_count": len(items) - len(invalid_measurements), | |
| "reliable_count": sum(bool(item["reliable"]) for item in items), | |
| "gt_dimension_values": [ | |
| item["display_value"] | |
| for item in items | |
| if item.get("display_value") is not None | |
| ], | |
| "physical_per_drawing_ratio": _rounded(consensus_ratio), | |
| "scale_consistency": _rounded(statistics.fmean(scale_qualities)) if scale_qualities else None, | |
| "duplicate_signature_groups": duplicate_groups, | |
| "items": items, | |
| } | |
| def _crosscheck_parameters( | |
| parameters: dict[str, Any], dimensions: Mapping[str, Any], flags: list[dict[str, Any]] | |
| ) -> None: | |
| dimension_items = dimensions.get("items", []) | |
| unmatched: list[str] = [] | |
| negative: list[str] = [] | |
| for candidate in parameters["candidates"]: | |
| value = candidate["value"] | |
| if value is None: | |
| candidate["signed_dimension_matches"] = [] | |
| candidate["magnitude_dimension_matches"] = [] | |
| unmatched.append(candidate["parameter_id"]) | |
| continue | |
| if value < 0: | |
| negative.append(candidate["parameter_id"]) | |
| tolerance = max(0.05, 0.001 * abs(value)) | |
| signed_matches: list[int] = [] | |
| magnitude_matches: list[int] = [] | |
| reliable_signed_matches: list[int] = [] | |
| for dimension in dimension_items: | |
| display = dimension.get("display_value") | |
| if display is None: | |
| continue | |
| if abs(display - value) <= tolerance: | |
| signed_matches.append(dimension["index"]) | |
| if dimension.get("reliable"): | |
| reliable_signed_matches.append(dimension["index"]) | |
| if abs(abs(display) - abs(value)) <= tolerance: | |
| magnitude_matches.append(dimension["index"]) | |
| candidate["match_tolerance_mm"] = _rounded(tolerance) | |
| candidate["signed_dimension_matches"] = signed_matches | |
| candidate["magnitude_dimension_matches"] = magnitude_matches | |
| candidate["reliable_signed_dimension_matches"] = reliable_signed_matches | |
| if not magnitude_matches: | |
| unmatched.append(candidate["parameter_id"]) | |
| parameters["matched_candidate_count"] = len(parameters["candidates"]) - len(unmatched) | |
| parameters["unmatched_candidate_ids"] = unmatched | |
| parameters["negative_candidate_ids"] = negative | |
| parameters["value_crosscheck_status"] = ( | |
| "ok" | |
| if parameters["candidates"] and not unmatched | |
| else "needs_audit" | |
| if parameters["candidates"] | |
| else "unknown" | |
| ) | |
| if negative: | |
| _audit( | |
| flags, | |
| "negative_prompt_parameters", | |
| "warning", | |
| "parameters", | |
| "Negative prompt values were preserved; magnitude matches do not authorize rewriting them.", | |
| parameter_ids=negative, | |
| ) | |
| if unmatched: | |
| _audit( | |
| flags, | |
| "prompt_parameters_without_dimension_value_match", | |
| "warning", | |
| "parameters", | |
| "Some prompt millimetre values have no matching GT DIMENSION display value.", | |
| parameter_ids=unmatched, | |
| ) | |
| if not parameters["candidates"]: | |
| _audit( | |
| flags, | |
| "no_prompt_parameter_candidates", | |
| "warning", | |
| "parameters", | |
| "No explicit millimetre-valued parameter candidates were extracted.", | |
| ) | |
| def _fmfs_manifest( | |
| parameters: Mapping[str, Any], | |
| dimensions: Mapping[str, Any], | |
| ) -> dict[str, Any]: | |
| """Build a conservative full-manufacturing-feature verifier manifest. | |
| Every explicit prompt millimetre value must have a signed match to a | |
| reliable, view-bound native GT dimension. Extra GT dimensions are retained | |
| as possible image/geometry-derived targets but do not by themselves make | |
| the prompt inconsistent. ``fully_derivable`` therefore remains a separate | |
| diagnostic instead of being silently assumed. | |
| """ | |
| candidates = list(parameters.get("candidates", [])) | |
| reliable_dimensions = [ | |
| item for item in dimensions.get("items", []) if item.get("reliable") | |
| ] | |
| by_index = {item["index"]: item for item in reliable_dimensions} | |
| matched_by_dimension: defaultdict[int, list[str]] = defaultdict(list) | |
| for candidate in candidates: | |
| for index in candidate.get("reliable_signed_dimension_matches", []): | |
| if index in by_index: | |
| matched_by_dimension[index].append(candidate["parameter_id"]) | |
| items: list[dict[str, Any]] = [] | |
| for dimension in reliable_dimensions: | |
| prompt_ids = sorted(matched_by_dimension.get(dimension["index"], [])) | |
| items.append( | |
| { | |
| "id": dimension["id"], | |
| "gt_dimension_index": dimension["index"], | |
| "family": dimension["family"], | |
| "value": dimension["display_value"], | |
| "measurement": dimension["measurement"], | |
| "physical_per_drawing_ratio": dimension["drawing_scale_ratio"], | |
| "view": dimension.get("nearest_view_role"), | |
| "position": dimension.get("nearest_view_position"), | |
| "binding_point": dimension.get("binding_point"), | |
| "prompt_parameter_ids": prompt_ids, | |
| "derivable": bool(prompt_ids), | |
| "consistent": bool(dimension.get("scale_consistent")), | |
| } | |
| ) | |
| reasons: list[str] = [] | |
| if not candidates: | |
| reasons.append("no_prompt_parameters") | |
| if parameters.get("negative_candidate_ids"): | |
| reasons.append("negative_prompt_parameters") | |
| unmatched_reliable = [ | |
| candidate["parameter_id"] | |
| for candidate in candidates | |
| if not candidate.get("reliable_signed_dimension_matches") | |
| ] | |
| if unmatched_reliable: | |
| reasons.append("prompt_gt_value_mismatch") | |
| gt_consistent = bool(dimensions.get("count")) and ( | |
| dimensions.get("reliable_count") == dimensions.get("count") | |
| ) | |
| if not reliable_dimensions: | |
| reasons.append("no_reliable_gt_dimensions") | |
| elif not gt_consistent: | |
| reasons.append("gt_dimension_manifest_needs_audit") | |
| prompt_consistent = bool(candidates) and not parameters.get( | |
| "negative_candidate_ids" | |
| ) and not unmatched_reliable | |
| eligible = bool(prompt_consistent and gt_consistent and items) | |
| return { | |
| "eligible": eligible, | |
| "reason": reasons or ["ok"], | |
| "prompt_consistent": prompt_consistent, | |
| "gt_consistent": gt_consistent, | |
| "fully_derivable": bool( | |
| prompt_consistent and items and all(item["derivable"] for item in items) | |
| ), | |
| "unmatched_prompt_parameter_ids": unmatched_reliable, | |
| "item_count": len(items), | |
| "items": items, | |
| "notes": ( | |
| "This evaluator-only manifest is not a model target. Extra reliable " | |
| "GT dimensions may be derivable from the ISO image or feature relations; " | |
| "that claim is reported separately by fully_derivable." | |
| ), | |
| } | |
| def _empty_row(row: Mapping[str, Any], gt_path: Path | None) -> dict[str, Any]: | |
| part_id = str(row.get("id", "")).strip() | |
| return { | |
| "schema_version": SCHEMA_VERSION, | |
| "id": part_id, | |
| "category": row.get("category"), | |
| "tier": row.get("tier"), | |
| "split": row.get("split"), | |
| "gt_dxf": str(gt_path) if gt_path is not None else None, | |
| "gt_dxf_sha256": None, | |
| "gt_dxf_bytes": None, | |
| "source": {}, | |
| "drawing": {}, | |
| "entities": { | |
| "modelspace_entity_count": 0, | |
| "by_type": {}, | |
| "view_geometry_by_type": {}, | |
| "unsupported_by_type": {}, | |
| "items": [], | |
| }, | |
| "layers": [], | |
| "views": { | |
| "status": "unknown", | |
| "method": "orthogonal_empty_gap_v1", | |
| "candidate_count": 0, | |
| "candidates": [], | |
| "split": None, | |
| "role_assignment": {"status": "unknown", "basis": None}, | |
| }, | |
| "dimensions": { | |
| "status": "unknown", | |
| "count": 0, | |
| "by_family": {}, | |
| "items": [], | |
| }, | |
| "fmfs": { | |
| "eligible": False, | |
| "reason": ["gt_unavailable"], | |
| "prompt_consistent": False, | |
| "gt_consistent": False, | |
| "fully_derivable": False, | |
| "item_count": 0, | |
| "items": [], | |
| }, | |
| "parameters": extract_prompt_parameters(_user_prompt(row)), | |
| "eligibility": {}, | |
| "audit_flags": [], | |
| } | |
| def _resolve_gt_path(row: Mapping[str, Any], dataset_path: Path | None) -> Path | None: | |
| raw = row.get("gt_dxf") | |
| if not raw: | |
| return None | |
| path = Path(str(raw)).expanduser() | |
| if not path.is_absolute() and dataset_path is not None: | |
| path = dataset_path.parent / path | |
| return path.resolve() | |
| def build_sidecar_row( | |
| row: Mapping[str, Any], dataset_path: str | Path | None = None | |
| ) -> dict[str, Any]: | |
| """Build one sidecar row without executing any generated model code.""" | |
| part_id = str(row.get("id", "")).strip() | |
| if not part_id: | |
| raise SidecarError("dataset row is missing a non-empty id") | |
| source_path = Path(dataset_path).resolve() if dataset_path is not None else None | |
| gt_path = _resolve_gt_path(row, source_path) | |
| output = _empty_row(row, gt_path) | |
| flags = output["audit_flags"] | |
| prompt = _user_prompt(row) | |
| output["source"] = { | |
| "dataset": str(source_path) if source_path is not None else None, | |
| "prompt_sha256": _text_sha256(prompt), | |
| "image_basenames": [ | |
| Path(str(image).replace("\\", "/")).name | |
| for image in ( | |
| [row.get("images")] | |
| if isinstance(row.get("images"), str) | |
| else row.get("images", []) | |
| ) | |
| ], | |
| } | |
| if output["category"] is None: | |
| _audit(flags, "missing_category", "warning", "sample", "Category is missing.") | |
| if output["tier"] is None: | |
| _audit(flags, "missing_tier", "warning", "sample", "Tier is missing.") | |
| if not prompt: | |
| _audit( | |
| flags, | |
| "missing_unique_user_prompt", | |
| "warning", | |
| "sample", | |
| "Expected exactly one string-valued user message.", | |
| ) | |
| if gt_path is None: | |
| _audit( | |
| flags, | |
| "missing_gt_dxf_path", | |
| "error", | |
| "dxf", | |
| "Dataset row has no GT DXF path.", | |
| ) | |
| output["eligibility"] = _eligibility(output) | |
| return output | |
| if not gt_path.is_file() or gt_path.stat().st_size <= 0: | |
| _audit( | |
| flags, | |
| "missing_or_empty_gt_dxf", | |
| "error", | |
| "dxf", | |
| "GT DXF is missing or empty.", | |
| path=str(gt_path), | |
| ) | |
| output["eligibility"] = _eligibility(output) | |
| return output | |
| output["gt_dxf_sha256"] = _sha256(gt_path) | |
| output["gt_dxf_bytes"] = gt_path.stat().st_size | |
| try: | |
| doc = ezdxf.readfile(str(gt_path)) | |
| except Exception as error: | |
| _audit( | |
| flags, | |
| "unreadable_gt_dxf", | |
| "error", | |
| "dxf", | |
| "ezdxf could not read the GT file.", | |
| error=f"{type(error).__name__}: {error}", | |
| ) | |
| output["eligibility"] = _eligibility(output) | |
| return output | |
| extracted = _extract_dxf(doc, flags) | |
| output["drawing"] = { | |
| "dxfversion": str(doc.dxfversion), | |
| "insertion_units_code": int(doc.header.get("$INSUNITS", 0) or 0), | |
| } | |
| output["entities"] = { | |
| key: extracted[key] | |
| for key in ( | |
| "modelspace_entity_count", | |
| "by_type", | |
| "view_geometry_by_type", | |
| "unsupported_by_type", | |
| "items", | |
| ) | |
| } | |
| output["layers"] = extracted["layers"] | |
| output["views"] = detect_view_candidates(extracted["geometry_records"], flags) | |
| _attach_dimensions_to_views(extracted["dimension_items"], output["views"]) | |
| output["dimensions"] = _dimension_manifest(extracted["dimension_items"], flags) | |
| _crosscheck_parameters(output["parameters"], output["dimensions"], flags) | |
| output["fmfs"] = _fmfs_manifest(output["parameters"], output["dimensions"]) | |
| output["eligibility"] = _eligibility(output) | |
| return output | |
| def _eligibility(row: Mapping[str, Any]) -> dict[str, Any]: | |
| flags = row.get("audit_flags", []) | |
| fatal_codes = sorted( | |
| flag["code"] for flag in flags if flag.get("severity") == "error" | |
| ) | |
| unsupported = bool(row.get("entities", {}).get("unsupported_by_type")) | |
| view_regions = row.get("views", {}).get("status") == "ok" | |
| dimensions = row.get("dimensions", {}) | |
| parameters = row.get("parameters", {}) | |
| fmfs = row.get("fmfs", {}) | |
| return { | |
| "inventory": not fatal_codes, | |
| "view_geometry": not fatal_codes and not unsupported, | |
| "view_regions": view_regions, | |
| # Roles and physical feature bindings are intentionally not certified by | |
| # this first sidecar version. Downstream code must not mistake hints for GT. | |
| "view_roles": False, | |
| "native_dimensions": bool(dimensions.get("count")) and not fatal_codes, | |
| "dimension_value_inventory": bool(dimensions.get("numeric_display_count")), | |
| "prompt_parameter_candidates": bool(parameters.get("candidate_count")), | |
| "parameter_value_crosscheck": parameters.get("value_crosscheck_status") == "ok", | |
| "fmfs": bool(fmfs.get("eligible")), | |
| "physical_parameter_binding": False, | |
| "automatic_v5_reward": False, | |
| "fatal_reason_codes": fatal_codes, | |
| "notes": ( | |
| "automatic_v5_reward stays false until view-role convention and " | |
| "feature/parameter bindings have been audited." | |
| ), | |
| } | |
| def _validate_loaded_row(row: Any, path: Path, line_number: int) -> dict[str, Any]: | |
| if not isinstance(row, dict): | |
| raise SidecarError(f"{path}:{line_number}: expected a JSON object") | |
| missing = [field for field in REQUIRED_TOP_LEVEL_FIELDS if field not in row] | |
| if missing: | |
| raise SidecarError(f"{path}:{line_number}: missing fields {missing}") | |
| if row["schema_version"] != SCHEMA_VERSION: | |
| raise SidecarError( | |
| f"{path}:{line_number}: unsupported schema {row['schema_version']!r}" | |
| ) | |
| part_id = str(row.get("id", "")).strip() | |
| if not part_id: | |
| raise SidecarError(f"{path}:{line_number}: missing id") | |
| fmfs = row.get("fmfs") | |
| eligibility = row.get("eligibility") | |
| if not isinstance(fmfs, dict) or not isinstance(eligibility, dict): | |
| raise SidecarError(f"{path}:{line_number}: missing fmfs/eligibility contract") | |
| items = fmfs.get("items") | |
| if not isinstance(items, list): | |
| raise SidecarError(f"{path}:{line_number}: fmfs.items must be a list") | |
| expected_derivable = bool( | |
| fmfs.get("prompt_consistent") | |
| and items | |
| and all(isinstance(item, dict) and item.get("derivable") for item in items) | |
| ) | |
| if fmfs.get("fully_derivable") is not expected_derivable: | |
| raise SidecarError( | |
| f"{path}:{line_number}: stale/inconsistent fmfs.fully_derivable" | |
| ) | |
| if bool(eligibility.get("fmfs")) != bool(fmfs.get("eligible")): | |
| raise SidecarError( | |
| f"{path}:{line_number}: eligibility.fmfs disagrees with fmfs.eligible" | |
| ) | |
| row["id"] = part_id | |
| return row | |
| def load_sidecar_jsonl(path: str | Path) -> dict[str, dict[str, Any]]: | |
| """Load a sidecar by ID, rejecting schema drift and duplicate identities.""" | |
| source = Path(path) | |
| rows: dict[str, dict[str, Any]] = {} | |
| with source.open(encoding="utf-8") as handle: | |
| for line_number, line in enumerate(handle, 1): | |
| if not line.strip(): | |
| continue | |
| try: | |
| decoded = json.loads(line) | |
| except json.JSONDecodeError as error: | |
| raise SidecarError(f"{source}:{line_number}: {error}") from error | |
| row = _validate_loaded_row(decoded, source, line_number) | |
| if row["id"] in rows: | |
| raise SidecarError(f"{source}:{line_number}: duplicate id {row['id']}") | |
| rows[row["id"]] = row | |
| return rows | |
| def _atomic_jsonl(path: Path, rows: Sequence[Mapping[str, Any]]) -> None: | |
| path.parent.mkdir(parents=True, exist_ok=True) | |
| descriptor, temporary = tempfile.mkstemp( | |
| prefix=path.name + ".", suffix=".tmp", dir=path.parent | |
| ) | |
| try: | |
| with os.fdopen(descriptor, "w", encoding="utf-8") as handle: | |
| for row in rows: | |
| handle.write( | |
| json.dumps( | |
| row, | |
| ensure_ascii=False, | |
| sort_keys=True, | |
| separators=(",", ":"), | |
| allow_nan=False, | |
| ) | |
| + "\n" | |
| ) | |
| handle.flush() | |
| os.fsync(handle.fileno()) | |
| os.replace(temporary, path) | |
| finally: | |
| if os.path.exists(temporary): | |
| os.remove(temporary) | |
| def build_sidecar_dataset( | |
| dataset_path: str | Path, | |
| output_path: str | Path, | |
| *, | |
| limit: int | None = None, | |
| strict: bool = False, | |
| ) -> dict[str, Any]: | |
| """Build and atomically write sidecars for a JSONL dataset.""" | |
| source = Path(dataset_path).resolve() | |
| destination = Path(output_path).resolve() | |
| if limit is not None and limit < 0: | |
| raise SidecarError("limit must be non-negative") | |
| outputs: list[dict[str, Any]] = [] | |
| seen: set[str] = set() | |
| with source.open(encoding="utf-8") as handle: | |
| for line_number, line in enumerate(handle, 1): | |
| if not line.strip(): | |
| continue | |
| if limit is not None and len(outputs) >= limit: | |
| break | |
| try: | |
| row = json.loads(line) | |
| except json.JSONDecodeError as error: | |
| raise SidecarError(f"{source}:{line_number}: {error}") from error | |
| if not isinstance(row, dict): | |
| raise SidecarError(f"{source}:{line_number}: expected a JSON object") | |
| part_id = str(row.get("id", "")).strip() | |
| if not part_id: | |
| raise SidecarError(f"{source}:{line_number}: missing id") | |
| if part_id in seen: | |
| raise SidecarError(f"{source}:{line_number}: duplicate id {part_id}") | |
| seen.add(part_id) | |
| sidecar = build_sidecar_row(row, source) | |
| if strict: | |
| fatal = sidecar["eligibility"]["fatal_reason_codes"] | |
| if fatal: | |
| raise SidecarError( | |
| f"{source}:{line_number}:{part_id}: structural failures {fatal}" | |
| ) | |
| outputs.append(sidecar) | |
| _atomic_jsonl(destination, outputs) | |
| status_counts = Counter(row["views"]["status"] for row in outputs) | |
| fmfs_counts = Counter( | |
| "eligible" if row.get("fmfs", {}).get("eligible") else "ineligible" | |
| for row in outputs | |
| ) | |
| flag_counts = Counter( | |
| flag["code"] for row in outputs for flag in row.get("audit_flags", []) | |
| ) | |
| summary = { | |
| "schema_version": SCHEMA_VERSION, | |
| "dataset": str(source), | |
| "dataset_sha256": _sha256(source), | |
| "output": str(destination), | |
| "output_sha256": _sha256(destination), | |
| "count": len(outputs), | |
| "strict": bool(strict), | |
| "limit": limit, | |
| "view_status_counts": dict(sorted(status_counts.items())), | |
| "fmfs_eligibility_counts": dict(sorted(fmfs_counts.items())), | |
| "audit_flag_counts": dict(sorted(flag_counts.items())), | |
| } | |
| return summary | |
| def main(argv: Sequence[str] | None = None) -> int: | |
| parser = argparse.ArgumentParser(description=__doc__) | |
| parser.add_argument("--dataset", type=Path, required=True) | |
| parser.add_argument("--out", type=Path, required=True) | |
| parser.add_argument("--limit", type=int) | |
| parser.add_argument( | |
| "--strict", | |
| action="store_true", | |
| help="abort on structural GT failures; needs_audit remains allowed", | |
| ) | |
| args = parser.parse_args(argv) | |
| summary = build_sidecar_dataset( | |
| args.dataset, args.out, limit=args.limit, strict=args.strict | |
| ) | |
| print(json.dumps(summary, ensure_ascii=False, indent=2, sort_keys=True)) | |
| return 0 | |
| if __name__ == "__main__": | |
| raise SystemExit(main()) | |