Download scripts/spec_check.py from ysharma/klein-layout-plans: direct link, hf CLI and curl.
- Browser
- Download file 6.05 kB
-
https://huggingface.co/datasets/ysharma/klein-layout-plans/resolve/main/scripts/spec_check.py
- Command line
-
hf download hf://datasets/ysharma/klein-layout-plans/scripts/spec_check.py
-
curl -L -o spec_check.py https://huggingface.co/datasets/ysharma/klein-layout-plans/resolve/main/scripts/spec_check.py
6.05 kB
| """Spec checker: verify a plan's box table against a structured request spec, without eyes. | |
| Spec schema (stored with ~40% of generated requests): | |
| { | |
| "entities": [{"class": "person", "count": 3}, {"class": "bench", "count": 1}], | |
| "relations": [{"a": "person", "b": "bench", "rel": "left_of"}, ...], # rel in left_of/right_of/above/below | |
| "text": ["OPEN 24/7", ...] # strings that must appear verbatim | |
| } | |
| Relations compare box centres (ids are numbered left-to-right, top-to-bottom, so the first instance of a | |
| class is its leftmost/topmost one); counts accept separate rows per instance OR one collection row whose | |
| desc states the count as digits or a number word. | |
| """ | |
| import json | |
| import re | |
| from bbox import split, valid_box | |
| NUM_WORDS = {1: "one", 2: "two", 3: "three", 4: "four", 5: "five", 6: "six", 7: "seven", 8: "eight", | |
| 9: "nine", 10: "ten", 11: "eleven", 12: "twelve", 15: "fifteen", 20: "twenty"} | |
| RELS = {"left_of": lambda a, b: a[1] < b[1], "right_of": lambda a, b: a[1] > b[1], | |
| "above": lambda a, b: a[0] < b[0], "below": lambda a, b: a[0] > b[0]} | |
| def class_of(row_id: str) -> str: | |
| m = re.match(r"(.+?)_(\d+)$", row_id) | |
| return m.group(1) if m else row_id | |
| def instance_index(row_id: str) -> int: | |
| m = re.match(r"(.+?)_(\d+)$", row_id) | |
| return int(m.group(2)) if m else 0 | |
| def centre(box: list) -> tuple: | |
| return (box[0] + box[2]) / 2.0, (box[1] + box[3]) / 2.0 # (cy, cx) | |
| def parse_plan(output: str): | |
| """(rows, reasons) for a single-line plan output; rows is None when it does not parse cleanly.""" | |
| reasons = [] | |
| caption, rows = split(output) | |
| if rows is None: | |
| return None, ["no JSON table found"] | |
| for r in rows: | |
| if not isinstance(r, dict) or valid_box(r.get("bbox")) is None: | |
| reasons.append(f"invalid row {r!r}") | |
| if reasons: | |
| return None, reasons | |
| if not is_plan_finished(caption, rows): | |
| reasons.append("not every row id is cited as <id> in the caption") | |
| return rows, reasons | |
| def is_plan_finished(caption: str, rows: list) -> bool: | |
| from bbox import ID | |
| return all(isinstance(r.get("id"), str) and ID.fullmatch(r["id"]) and f"<{r['id']}>" in caption for r in rows) | |
| def normalize_class(name: str) -> str: | |
| """lowercase + simple singularization, so spec vocabulary can meet plan id nouns.""" | |
| n = name.strip().lower() | |
| if len(n) > 3 and n.endswith("s") and not n.endswith("ss"): | |
| n = n[:-1] | |
| return re.sub(r"\s+", " ", n) | |
| def check_count(rows: list, cls: str, count: int, known_classes=None) -> str | None: | |
| """None when satisfied, else a reason string. With known_classes (the plan's id-noun | |
| vocabulary), a class that matches nothing in the plan returns UNVERIFIABLE instead of a | |
| failure — the checker cannot judge counts for entities the plan named differently.""" | |
| c = normalize_class(cls) | |
| cls_rows = sorted((r for r in rows if normalize_class(class_of(r["id"])) == c), | |
| key=lambda r: instance_index(r["id"])) | |
| if len(cls_rows) == count: | |
| return None | |
| # collection row: one row of this class whose desc states the count as digits or a number word | |
| for r in cls_rows: | |
| d = r["desc"].lower() | |
| if re.search(rf"\b{count}\b", d) or (count in NUM_WORDS and re.search(rf"\b{NUM_WORDS[count]}\b", d)): | |
| return None | |
| if known_classes is not None and c not in {normalize_class(k) for k in known_classes}: | |
| return f"UNVERIFIABLE count: {cls!r} not in plan vocabulary" | |
| return f"{cls}: {len(cls_rows)} row(s) vs stated count {count}, no collection row stating it" | |
| def check_relation(rows: list, a: str, rel: str, b: str, known_classes=None) -> str | None: | |
| unres = known_classes is not None | |
| if rel not in RELS: | |
| return (f"UNVERIFIABLE relation: unsupported {rel!r}" if unres else f"unknown relation {rel!r}") | |
| cmp = RELS[rel] | |
| # resolve "person" (first instance) or "person_2" (that instance) | |
| def pick(name): | |
| if re.match(r"(.+?)_(\d+)$", name): | |
| hits = [r for r in rows if r["id"] == name] | |
| else: | |
| hits = sorted((r for r in rows if class_of(r["id"]) == name), | |
| key=lambda r: instance_index(r["id"])) | |
| if not hits: | |
| return None | |
| (cy, cx) = centre(hits[0]["bbox"]) | |
| return (cx, cy) | |
| pa, pb = pick(a), pick(b) | |
| if pa is None: | |
| return (f"UNVERIFIABLE relation: {a!r} not in plan vocabulary" if unres | |
| else f"relation {a!r} {rel} {b!r}: no row for {a!r}") | |
| if pb is None: | |
| return (f"UNVERIFIABLE relation: {b!r} not in plan vocabulary" if unres | |
| else f"relation {a!r} {rel} {b!r}: no row for {b!r}") | |
| # pick() returns (cx, cy); RELS compare cx for left/right, cy for above/below via tuples | |
| ax, ay = pa | |
| bx, by = pb | |
| ok = {"left_of": ax < bx, "right_of": ax > bx, "above": ay < by, "below": ay > by}[rel] | |
| return None if ok else f"relation violated: {a!r} ({ax:.0f},{ay:.0f}) {rel} {b!r} ({bx:.0f},{by:.0f})" | |
| def check_text(rows: list, strings: list) -> list: | |
| out = [] | |
| for s in strings: | |
| if not any(s in r["desc"] for r in rows): | |
| out.append(f"quoted string {s!r} not verbatim in any desc") | |
| return out | |
| def check_plan(output: str, spec: dict, known_classes=None) -> tuple[bool, list]: | |
| """(ok, reasons) for one teacher/student output against its spec. | |
| Reasons beginning with 'UNVERIFIABLE' are checker limitations, not plan errors.""" | |
| rows, reasons = parse_plan(output) | |
| if rows is None: | |
| return False, reasons | |
| for e in spec.get("entities", []): | |
| r = check_count(rows, e["class"], e["count"], known_classes) | |
| if r: | |
| reasons.append(r) | |
| for rel in spec.get("relations", []): | |
| r = check_relation(rows, rel["a"], rel["rel"], rel["b"], known_classes) | |
| if r: | |
| reasons.append(r) | |
| reasons.extend(check_text(rows, spec.get("text", []))) | |
| return not reasons, reasons | |