Datasets:
Download code/src/pvr_eval/visualization/structured_overlay.py from wenjieshu/solveedit_benchmark_2728: direct link, hf CLI and curl.
- Browser
- Download file 7.73 kB
-
https://huggingface.co/datasets/wenjieshu/solveedit_benchmark_2728/resolve/main/code/src/pvr_eval/visualization/structured_overlay.py
- Command line
-
hf download hf://datasets/wenjieshu/solveedit_benchmark_2728/code/src/pvr_eval/visualization/structured_overlay.py
-
curl -L -o structured_overlay.py https://huggingface.co/datasets/wenjieshu/solveedit_benchmark_2728/resolve/main/code/src/pvr_eval/visualization/structured_overlay.py
7.73 kB
| """Render inspectable geometry emitted by structured-contract checkers. | |
| The renderer deliberately consumes only evidence already used by the checker. | |
| It does not run another detector or alter the decision. This keeps review | |
| overlays faithful to the exact regions, instances, and lines behind a score. | |
| """ | |
| from __future__ import annotations | |
| import math | |
| from pathlib import Path | |
| from typing import Any, Iterable, Mapping | |
| from PIL import Image, ImageDraw, ImageFont | |
| BOX_TOKENS = ("bbox", "bboxes", "roi", "rois", "zone", "zones", "cell", "cells", "grid") | |
| POINT_TOKENS = ("pivot_xy", "centroid", "center_xy") | |
| MAX_PRIMITIVES = 48 | |
| def _numbers(value: Any, length: int) -> list[float] | None: | |
| if not isinstance(value, (list, tuple)) or len(value) != length: | |
| return None | |
| if not all(isinstance(item, (int, float)) for item in value): | |
| return None | |
| return [float(item) for item in value] | |
| def _polygon_numbers(value: Any) -> list[float] | None: | |
| if not isinstance(value, (list, tuple)) or len(value) < 3: | |
| return None | |
| points = [_numbers(point, 2) for point in value] | |
| if any(point is None for point in points): | |
| return None | |
| return [coordinate for point in points if point is not None for coordinate in point] | |
| def _label(path: tuple[str, ...]) -> str: | |
| return "/".join(path[-3:]) | |
| def extract_primitives(evidence: Mapping[str, Any], image_size: tuple[int, int]) -> list[dict[str, Any]]: | |
| """Extract pixel-space boxes, points, and line segments from evidence.""" | |
| width, height = image_size | |
| primitives: list[dict[str, Any]] = [] | |
| seen: set[tuple[Any, ...]] = set() | |
| def add(kind: str, values: Iterable[float], label: str) -> None: | |
| rounded = tuple(round(float(item), 2) for item in values) | |
| identity = (kind, rounded, label) | |
| if identity in seen: | |
| return | |
| seen.add(identity) | |
| primitives.append({"kind": kind, "values": list(rounded), "label": label}) | |
| def walk(value: Any, path: tuple[str, ...]) -> None: | |
| key_scope = "/".join(path).lower() | |
| polygon = _polygon_numbers(value) | |
| if polygon is not None and any(token in key_scope for token in ("polygon", "zone")): | |
| xs, ys = polygon[0::2], polygon[1::2] | |
| if min(xs) >= 0 and max(xs) <= width * 1.02 and min(ys) >= 0 and max(ys) <= height * 1.02: | |
| add("polygon", polygon, _label(path)) | |
| return | |
| box = _numbers(value, 4) | |
| if box is not None and any(token in key_scope for token in BOX_TOKENS): | |
| x0, y0, x1, y1 = box | |
| if 0 <= x0 < x1 <= width * 1.02 and 0 <= y0 < y1 <= height * 1.02: | |
| add("box", box, _label(path)) | |
| return | |
| point = _numbers(value, 2) | |
| if point is not None and any(token in key_scope for token in POINT_TOKENS): | |
| x, y = point | |
| if 0 <= x <= width and 0 <= y <= height: | |
| add("point", point, _label(path)) | |
| return | |
| if isinstance(value, Mapping): | |
| for child_key, child in value.items(): | |
| walk(child, (*path, str(child_key))) | |
| elif isinstance(value, list): | |
| for index, child in enumerate(value): | |
| walk(child, (*path, str(index))) | |
| walk(evidence, ()) | |
| parser = str(evidence.get("parser") or "") | |
| if parser.startswith("lower_gauge_radial_parser"): | |
| pivot = _numbers(evidence.get("pivot_xy"), 2) | |
| angle = evidence.get("output_angle_degrees") | |
| if pivot and isinstance(angle, (int, float)): | |
| radius = min(width, height) * 0.125 | |
| end = [ | |
| pivot[0] + math.cos(math.radians(float(angle))) * radius, | |
| pivot[1] + math.sin(math.radians(float(angle))) * radius, | |
| ] | |
| add("line", [*pivot, *end], "output needle") | |
| elif parser.startswith("watch_registered_hand_parser"): | |
| pivot = _numbers(evidence.get("output_pivot_xy"), 2) | |
| radius = min(width, height) * 0.22 | |
| for name, values, fraction in ( | |
| ("output hour hand", evidence.get("hour_angles"), 0.65), | |
| ("output minute hand", evidence.get("minute_angles"), 0.95), | |
| ): | |
| if pivot and isinstance(values, (list, tuple)) and len(values) >= 2 and isinstance(values[1], (int, float)): | |
| angle = math.radians(float(values[1])) | |
| end = [pivot[0] + math.cos(angle) * radius * fraction, pivot[1] + math.sin(angle) * radius * fraction] | |
| add("line", [*pivot, *end], name) | |
| overlay = evidence.get("overlay_geometry") | |
| if isinstance(overlay, Mapping) and isinstance(overlay.get("segments"), Mapping): | |
| for name, segment in overlay["segments"].items(): | |
| values = _numbers(segment, 4) | |
| if values is not None: | |
| add("line", values, str(name)) | |
| primitives.sort( | |
| key=lambda item: ( | |
| int("component" in item["label"] or "assignments/" in item["label"]), | |
| int("detection" in item["label"]), | |
| ) | |
| ) | |
| return primitives[:MAX_PRIMITIVES] | |
| def render_overlay( | |
| image_path: Path, | |
| evidence: Mapping[str, Any], | |
| output_path: Path, | |
| *, | |
| title: str, | |
| status: str, | |
| ) -> dict[str, Any]: | |
| """Draw evidence geometry and return a compact render manifest.""" | |
| with Image.open(image_path).convert("RGB") as source: | |
| image = source.copy() | |
| draw = ImageDraw.Draw(image) | |
| font = ImageFont.load_default() | |
| primitives = extract_primitives(evidence, image.size) | |
| status_color = { | |
| "pass": "#12B76A", "clean": "#12B76A", | |
| "partial": "#F79009", "partial_trigger": "#F79009", | |
| "fail": "#F04438", "triggered": "#F04438", | |
| "unknown": "#667085", "uncertain": "#667085", | |
| }.get(status, "#175CD3") | |
| palette = (status_color, "#2E90FA", "#7A5AF8", "#EE46BC", "#15B79E") | |
| for index, primitive in enumerate(primitives): | |
| label = primitive["label"] | |
| label_lower = label.lower() | |
| color = ( | |
| "#FEC84B" if "zone_polygons/yellow" in label_lower | |
| else "#06AED4" if "zone_polygons/cyan" in label_lower | |
| else palette[index % len(palette)] | |
| ) | |
| values = primitive["values"] | |
| if primitive["kind"] == "box": | |
| draw.rectangle(values, outline=color, width=max(2, min(image.size) // 320)) | |
| x, y = values[0], max(35, values[1] - 13) | |
| elif primitive["kind"] == "polygon": | |
| points = list(zip(values[0::2], values[1::2])) | |
| draw.line([*points, points[0]], fill=color, width=max(3, min(image.size) // 220), joint="curve") | |
| x, y = points[0] | |
| elif primitive["kind"] == "point": | |
| x, y = values | |
| radius = max(4, min(image.size) // 180) | |
| draw.ellipse((x - radius, y - radius, x + radius, y + radius), outline=color, width=2) | |
| else: | |
| draw.line(values, fill=color, width=max(3, min(image.size) // 220)) | |
| x, y = values[2], values[3] | |
| if index < 24 and "component" not in label and "assignments/" not in label: | |
| text_box = draw.textbbox((x, y), label, font=font) | |
| draw.rectangle(text_box, fill="#101828") | |
| draw.text((x, y), label, fill="white", font=font) | |
| draw.rectangle((0, 0, image.width, 34), fill="#101828") | |
| draw.text((8, 9), f"{status.upper()} | {title}", fill=status_color, font=font) | |
| output_path.parent.mkdir(parents=True, exist_ok=True) | |
| image.save(output_path, "JPEG", quality=90, optimize=True) | |
| return { | |
| "image": str(output_path), "source": str(image_path), "status": status, | |
| "primitive_count": len(primitives), "primitives": primitives, | |
| } | |