SchemID / derived /Source /scripts /build_circuit_dataset.py
lsnu's picture
Add files using upload-large-folder tool
6ce7ee8 verified
#!/usr/bin/env python3
from __future__ import annotations
import argparse
import hashlib
import json
import math
import os
import re
import shutil
import subprocess
import tarfile
import urllib.parse
import urllib.request
import warnings
from collections import Counter, defaultdict
from concurrent.futures import ThreadPoolExecutor, as_completed
from dataclasses import dataclass
from pathlib import Path
from typing import Any
import numpy as np
import pyarrow as pa
import pyarrow.parquet as pq
from datasets import Dataset, Features, Image as HFImage, Value
from PIL import Image, ImageChops
PNG_DPI = 120
DEFAULT_LIII_PDF_URL = "https://www.ibiblio.org/kuphaldt/socratic/sinst/book/liii_2v16.pdf"
STRUCTURAL_VERSION = "schemid_source_structural_v1"
EXTRACTION_BRANCH = "xcircuit_eps_ir_v1"
SOURCE_DATASET_NAME = "schemid_source_available"
SOURCE_REPO_ID = "lsnu/SchemID"
SOURCE_SPLIT = "train"
SOURCE_ORIGIN = "xcircuit_eps"
SOURCE_GROUP = "non_cosyn"
PAGE_SCOPE_ID = "page_001"
COORD_SNAP = 0.75
PHASH_SIZE = 8
PHASH_HIGHFREQ = 32
GRAPH_WORD_COUNT_MAX = 50
GRAPH_TEXT_FRACTION_MAX = 0.18
GRAPH_RENDER_MAE_MAX = 3.0
GRAPH_RENDER_PHASH_MAX = 8
GRAPH_DECORATIVE_MAX = 12
PIN_INFER_BOUNDARY_MARGIN = 10.0
PIN_INFER_EXPAND_MARGIN = 12.0
MAX_INFERRED_COMPONENT_PINS = 12
NO_TEXT_PS_OVERRIDE = (
"\n"
"/show { pop } bind def\n"
"/ashow { pop pop } bind def\n"
"/widthshow { pop pop pop } bind def\n"
"/awidthshow { pop pop pop pop pop } bind def\n"
"/kshow { pop pop } bind def\n"
)
# These procedure names are emitted by XCircuit for electrical symbols.
CIRCUIT_PROCEDURE_WHITELIST = {
"LED",
"acsource",
"and_gate",
"battery",
"breadboard",
"capacitor",
"capacitor1",
"diode",
"dip_8",
"gnd",
"indicator",
"inductor",
"invert",
"jumper",
"nand",
"njf",
"no_contact",
"npn",
"opamp",
"or_gate",
"pnp",
"potentiometer",
"potentiometer1",
"real_batt",
"resistor",
"resistor4",
"source",
"transistor2",
}
PRIMARY_SEED_PROCEDURES = {
"LED",
"acsource",
"battery",
"capacitor",
"diode",
"fuse_blown",
"inductor",
"npn",
"opamp",
"pnp",
"potentiometer",
"resistor",
"source",
}
PROC_BBOX_CATALOG: dict[str, tuple[int, int, int, int]] = {
"LED": (-16, -32, 32, 59),
"acsource": (-32, -64, 64, 128),
"battery": (-32, -64, 64, 128),
"capacitor": (-32, -64, 64, 128),
"diode": (-8, -48, 36, 96),
"fuse_blown": (-16, -32, 32, 62),
"gnd": (-32, -60, 64, 68),
"inductor": (-14, -64, 29, 112),
"npn": (-64, -64, 72, 128),
"opamp": (-80, -80, 160, 160),
"pnp": (-64, -64, 72, 128),
"potentiometer": (-46, -64, 78, 128),
"resistor": (-14, -64, 28, 128),
"source": (-32, -64, 64, 128),
}
PROCEDURE_KIND_MAP: dict[str, tuple[str, str]] = {
"LED": ("indicator", "led"),
"acsource": ("source", "ac_source"),
"and_gate": ("logic", "logic_gate"),
"arrow": ("decorative", "arrow"),
"arrowhead": ("decorative", "arrowhead"),
"battery": ("source", "voltage_source"),
"breadboard": ("block", "breadboard"),
"capacitor": ("passive", "capacitor"),
"capacitor1": ("passive", "capacitor"),
"circle": ("io", "terminal"),
"diode": ("semiconductor", "diode"),
"dip_8": ("logic", "integrated_circuit"),
"dot": ("junction", "junction"),
"fuse_blown": ("protection", "fuse"),
"gnd": ("ground", "ground"),
"indicator": ("indicator", "indicator"),
"inductor": ("passive", "inductor"),
"invert": ("logic", "logic_gate"),
"jumper": ("switch", "jumper"),
"nand": ("logic", "logic_gate"),
"njf": ("semiconductor", "transistor"),
"no_contact": ("io", "terminal"),
"npn": ("semiconductor", "transistor"),
"opamp": ("active", "op_amp"),
"or_gate": ("logic", "logic_gate"),
"pnp": ("semiconductor", "transistor"),
"potentiometer": ("passive", "potentiometer"),
"potentiometer1": ("passive", "potentiometer"),
"real_batt": ("source", "voltage_source"),
"resistor": ("passive", "resistor"),
"resistor4": ("passive", "resistor"),
"source": ("source", "voltage_source"),
"transistor2": ("semiconductor", "transistor"),
}
ELECTRICAL_FAMILIES = {
"active",
"passive",
"source",
"semiconductor",
"switch",
"indicator",
"protection",
"ground",
"io",
"junction",
"logic",
}
MIN_CONNECTED_PINS = {
"ac_source": 2,
"capacitor": 2,
"current_source": 2,
"diode": 2,
"fuse": 2,
"ground": 1,
"integrated_circuit": 2,
"inductor": 2,
"instrument": 2,
"junction": 1,
"led": 2,
"logic_gate": 2,
"op_amp": 3,
"potentiometer": 3,
"relay": 2,
"resistor": 2,
"switch": 2,
"terminal": 1,
"transformer": 2,
"transistor": 3,
"vacuum_tube": 2,
"voltage_source": 2,
}
DECORATIVE_PROCEDURES = {
"approx",
"car2",
"cart",
"candle",
"d_dx",
"elipse",
"flywheel",
"g2h",
"g2v",
"greenlight",
"infinity",
"jet",
"kmap_3",
"kmap_4",
"left_hand",
"left_parenthesis",
"log_grid",
"omega",
"pointer",
"radicand1",
"radicand2",
"right_parenthesis",
"spring",
"washer",
"wave",
"bird",
"degree",
"polygon",
"sadfsaf",
"signal_air",
"squarewave",
"sinewave",
"sinewave1",
"sinewave2",
"sinewave3",
"sinewave4",
"tree",
}
BLOCK_PROCEDURES = {
"actuator_junk",
"analog_input",
"analog_output",
"air_compressor",
"aux_behind",
"aux_computer_front",
"aux_computer_behind",
"aux_front",
"aux_shared_behind",
"bar2",
"box",
"breadboard_large",
"blower",
"body_nut",
"brick",
"burner_1",
"control_selector",
"controller_pid",
"dndevice",
"fault_analysis_box",
"fcv",
"field",
"fieldbus_brick",
"fieldbus_terminator",
"flange",
"keyboard",
"link_data",
"link_dcs",
"main_behind",
"main_computer_front",
"main_front",
"measuring",
"packing",
"pid_controller",
"pipe_elbow",
"pipe_female",
"pipe_male",
"pipe_tee",
"proportional",
"remote_seal",
"signal_electric_binary",
"spectrum_display",
"tube_tee",
"transfer",
"valve_3",
"valve_5",
"valve_6",
"valve_7",
"valve_solenoid_2way",
"valve_control1",
"valve_control2",
"valve_globe_air",
"valve_globe_hand",
"valve_small",
"wedge",
}
TERMINAL_PROCEDURES = {
"audioplug",
"binding_post_black",
"binding_post_red",
"bnc_end",
"cabletip",
"connect",
"ladder_start",
"ladder_start2",
"probe",
"term_block_1",
}
SOURCE_PROCEDURES = {
"ac_supply",
"acsource",
"acsource2",
"alternator1",
"cell",
"dcgen1",
"dcgen2",
"function_generator",
"pulse_voltage_source",
"real_batt2",
"real_batt3",
"squarewave_source",
"variable_voltage",
"voltage_source_ac_dependent",
}
CURRENT_SOURCE_PROCEDURES = {"ac_dependent_i_source"}
SWITCH_PROCEDURES = {
"dpdt_toggle",
"nctc",
"ncto",
"nc_contact",
"nc_electronic",
"nc_flow",
"nc_pressure",
"nc_pushbutton",
"no_electronic",
"no_flow",
"no_level",
"no_limit",
"no_pressure",
"no_pushbutton",
"notc",
"noto",
"relay_coil",
"selector",
"solenoid",
"spdt_toggle",
"switch1",
"switch_closed",
"toggle_nc",
}
LOGIC_PROCEDURES = {
"compare_eq",
"compare_ge",
"compare_gt",
"compare_le",
"compare_lt",
"compare_ne",
"counter_down",
"counter_up",
"counter_up_down",
"d_flipflop",
"d_latch",
"halfadder",
"invert2",
"jk_flipflop",
"jk_flipflop2",
"neg_and",
"neg_or",
"schmitt",
"sr_enabled_latch",
"timer_on_en",
"tristate_1",
"xnor",
}
INDICATOR_PROCEDURES = {
"dc_voltmeter",
"led2",
"dp_cell",
"fancy_scope",
"gauge",
"headphones",
"lamp_socket",
"meter_movement",
"multimeter",
"multimeter2",
"multimeter_tiny",
"nullmeter",
"scopemeter",
"speaker",
"speaker2",
"synchro",
}
PASSIVE_RESISTIVE_PROCEDURES = {
"cds_cell",
"heater_element",
"load_delta",
"load_y",
"resistor_delta",
}
PASSIVE_MAGNETIC_PROCEDURES = {
"coil_out",
"inductor_large",
"inductor_medium",
"saturable_reactor",
"variac",
}
SEMICONDUCTOR_DIODE_PROCEDURES = {
"diac",
"lascr",
"constant_i_diode",
"diode1",
"opto_triac",
"photodiode",
"shockley_diode",
"zener_diode",
}
SEMICONDUCTOR_TRANSISTOR_PROCEDURES = {
"gcs",
"gto",
"igbt_nchannel",
"igbt_npn",
"scr",
"scs",
"triac",
"ujt",
"bjt_bias",
"nmos",
"npnn",
"pnpp",
"transistor1",
"transistor3",
"transistor4",
"tr4",
}
ACTIVE_TUBE_PROCEDURES = {
"beam_tetrode",
"glow_tube",
"ignitron",
"phototube",
"reflex_klystron",
"tube_halftriode",
"tube_pentode_1",
"tube_pentode_2",
"tube_tetrode",
"tube_thyratron",
"tube_triode",
}
STRIP_INVOCATION_PROCEDURES = {"person", "person_shocked"}
NON_CIRCUIT_SOURCE_PATTERNS: tuple[tuple[re.Pattern[str], str], ...] = (
(
re.compile(r"\breservoir\b|\bpond\b|\bpump\b|water flow", re.I),
"hydraulic analogy illustration",
),
(
re.compile(
r"lead-acid|fuel cell|electrolyte|electrode|hydrogen|oxygen|membranes?\b",
re.I,
),
"chemical cell illustration",
),
(
re.compile(
r"meter movement|moving coil|electron gun|view-screen|vacuum|needle|magnet\b",
re.I,
),
"instrument or device illustration",
),
)
XCIRCUIT_CREATOR_RE = re.compile(r"^%%Creator:\s*(.+)$", re.M)
EPS_PROC_RE = re.compile(r"^/([A-Za-z][A-Za-z0-9_-]*)\s*\{", re.M)
PROC_BBOX_RE = re.compile(
r"^/(?P<name>[A-Za-z][A-Za-z0-9_-]*)\s*\{\n%\s*"
r"(?P<x>-?\d+)\s+(?P<y>-?\d+)\s+(?P<w>-?\d+)\s+(?P<h>-?\d+)\s+bbox",
re.M,
)
PAGE_BODY_RE = re.compile(
r"(?P<prefix>^%%Page:.*?^/pgsave save def bop\n)(?P<body>.*?)(?P<suffix>^pgsave restore showpage.*?\Z)",
re.S | re.M,
)
PROC_CALL_RE = re.compile(
r"(?P<scale>-?\d+(?:\.\d+)?)\s+(?P<rot>-?\d+(?:\.\d+)?)\s+"
r"(?P<x>-?\d+(?:\.\d+)?)\s+(?P<y>-?\d+(?:\.\d+)?)\s+"
r"(?P<name>[A-Za-z][A-Za-z0-9_]*)\b"
)
PAGE_SCALE_RE = re.compile(r"(?P<scale>[0-9.]+)\s+(?P<kind>inchscale|cmscale)")
PAGE_TRANSLATE_RE = re.compile(
r"(?P<x>-?\d+(?:\.\d+)?)\s+(?P<y>-?\d+(?:\.\d+)?)\s+translate"
)
INVOCATION_LINE_RE = re.compile(
r"^\s*-?\d+(?:\.\d+)?\s+-?\d+(?:\.\d+)?\s+-?\d+(?:\.\d+)?\s+-?\d+(?:\.\d+)?\s+(?P<name>[A-Za-z][A-Za-z0-9_]*)\s*$"
)
FULL_INVOCATION_LINE_RE = re.compile(
r"^\s*(?P<scale>-?\d+(?:\.\d+)?)\s+(?P<rot>-?\d+(?:\.\d+)?)\s+"
r"(?P<x>-?\d+(?:\.\d+)?)\s+(?P<y>-?\d+(?:\.\d+)?)\s+"
r"(?P<name>[A-Za-z][A-Za-z0-9_]*)\s*$"
, re.M)
SML_TOKEN_RE = re.compile(
r"(?P<chapter><chaptertitle>(?P<chapter_text>.*?)</chaptertitle>)"
r"|(?P<section><sectiontitle>(?P<section_text>.*?)</sectiontitle>)"
r"|(?P<image><image>(?P<image_name>[^<]+?)(?:<caption>(?P<caption>.*?)</caption>)?</image>)",
re.S,
)
LATEX_SECTION_RE = re.compile(
r"\\(?P<kind>chapter|section|subsection)\*?\{(?P<title>[^}]*)\}"
)
LATEX_INCLUDE_RE = re.compile(
r"\\includegraphics(?:\[[^]]*\])?\{(?P<name>[^}]+\.eps)\}"
)
LABEL_COMMAND_RE = re.compile(
r"(?P<raw>(?P<content>(?:\((?:\\.|[^\\)])*\)|\{[^{}]*\}|\s+)+?)\s+"
r"(?P<count>\d+)\s+(?P<just>-?\d+)\s+(?P<rot>-?\d+(?:\.\d+)?)\s+"
r"(?:(?P<scale>-?\d+(?:\.\d+)?)\s+)?"
r"(?P<x>-?\d+(?:\.\d+)?)\s+(?P<y>-?\d+(?:\.\d+)?)\s+"
r"(?P<kind>label|pinlabel|pinglobal|infolabel)\b)",
re.S,
)
PS_STRING_RE = re.compile(r"\((?:\\.|[^\\)])*\)")
warnings.filterwarnings(
"ignore",
message="Palette images with Transparency expressed in bytes should be converted to RGBA images",
category=UserWarning,
)
@dataclass(frozen=True)
class BookConfig:
slug: str
display_name: str
pdf_name: str
archive_name: str | None
extract_dir: str
source_kind: str
html_dir: str | None
source_glob: str | None
source_file: str | None
source_version: str | None
pdf_version_sync: bool
BOOKS: list[BookConfig] = [
BookConfig(
slug="DC",
display_name="Lessons In Electric Circuits, Volume I – DC",
pdf_name="DC.pdf",
archive_name="DCsrc.tar.gz",
extract_dir="DCsrc",
source_kind="sml",
html_dir="DC",
source_glob="*.sml",
source_file=None,
source_version=None,
pdf_version_sync=True,
),
BookConfig(
slug="AC",
display_name="Lessons In Electric Circuits, Volume II – AC",
pdf_name="AC.pdf",
archive_name="ACsrc.tar.gz",
extract_dir="ACsrc",
source_kind="sml",
html_dir="AC",
source_glob="*.sml",
source_file=None,
source_version=None,
pdf_version_sync=True,
),
BookConfig(
slug="SEMI",
display_name="Lessons In Electric Circuits, Volume III – Semiconductors",
pdf_name="SEMI.pdf",
archive_name="SEMIsrc.tar.gz",
extract_dir="SEMIsrc",
source_kind="sml",
html_dir="Semi",
source_glob="*.sml",
source_file=None,
source_version=None,
pdf_version_sync=True,
),
BookConfig(
slug="DIGI",
display_name="Lessons In Electric Circuits, Volume IV – Digital",
pdf_name="DIGI.pdf",
archive_name="DIGIsrc.tar.gz",
extract_dir="DIGIsrc",
source_kind="sml",
html_dir="Digital",
source_glob="*.sml",
source_file=None,
source_version=None,
pdf_version_sync=True,
),
BookConfig(
slug="REF",
display_name="Lessons In Electric Circuits, Volume V – Reference",
pdf_name="REF.pdf",
archive_name="REFsrc.tar.gz",
extract_dir="REFsrc",
source_kind="sml",
html_dir="Ref",
source_glob="*.sml",
source_file=None,
source_version=None,
pdf_version_sync=True,
),
BookConfig(
slug="EXP",
display_name="Lessons In Electric Circuits, Volume VI – Experiments",
pdf_name="EXP.pdf",
archive_name="EXPsrc.tar.gz",
extract_dir="EXPsrc",
source_kind="sml",
html_dir="Exper",
source_glob="*.sml",
source_file=None,
source_version=None,
pdf_version_sync=True,
),
BookConfig(
slug="LIII",
display_name="Lessons In Industrial Instrumentation",
pdf_name="LessonsInIndustrialInstrumentation.pdf",
archive_name="sinst.tar.gz",
extract_dir="sinst/sinst/book",
source_kind="latex",
html_dir=None,
source_glob=None,
source_file="liii_2v16.latex",
source_version="2.16",
pdf_version_sync=False,
),
]
def run(cmd: list[str], *, cwd: Path | None = None) -> subprocess.CompletedProcess[str]:
return subprocess.run(
cmd,
cwd=str(cwd) if cwd else None,
check=True,
text=True,
capture_output=True,
)
def normalize_space(text: str) -> str:
return " ".join(text.split())
def extract_tar(archive_path: Path, output_dir: Path) -> None:
output_dir.mkdir(parents=True, exist_ok=True)
with tarfile.open(archive_path) as tar:
tar.extractall(output_dir, filter="data")
def ensure_inputs(repo_root: Path, extracted_root: Path) -> None:
extractions: dict[str, str] = {
"DCsrc.tar.gz": "DCsrc",
"ACsrc.tar.gz": "ACsrc",
"SEMIsrc.tar.gz": "SEMIsrc",
"DIGIsrc.tar.gz": "DIGIsrc",
"REFsrc.tar.gz": "REFsrc",
"EXPsrc.tar.gz": "EXPsrc",
"liechtml.tar.gz": "liechtml",
"sinst.tar.gz": "sinst",
}
source_dir = repo_root / "SchemSourceAvailable"
for archive_name, out_name in extractions.items():
marker_dir = extracted_root / out_name
marker_file = marker_dir / ".extracted.ok"
if marker_file.exists():
continue
if marker_dir.exists():
shutil.rmtree(marker_dir)
extract_tar(source_dir / archive_name, marker_dir)
marker_file.write_text("ok\n")
def download_file(url: str, destination: Path) -> None:
destination.parent.mkdir(parents=True, exist_ok=True)
with urllib.request.urlopen(url) as response, destination.open("wb") as handle:
shutil.copyfileobj(response, handle)
def resolve_pdf_source(
book: BookConfig,
repo_root: Path,
cache_root: Path,
liii_pdf_url: str,
) -> dict[str, Any]:
bundled_pdf = repo_root / "SchemSourceAvailable" / book.pdf_name
pdf_details = {
"bundled_pdf_name": book.pdf_name,
"bundled_pdf_path": str(bundled_pdf),
"pdf_name_used": book.pdf_name,
"pdf_path_used": str(bundled_pdf),
"pdf_url_used": None,
"pdf_origin": "bundled",
"pdf_version_sync": book.pdf_version_sync,
"notes": [],
}
if book.slug != "LIII":
return pdf_details
if liii_pdf_url:
parsed = urllib.parse.urlparse(liii_pdf_url)
download_name = Path(parsed.path).name or "liii_2v16.pdf"
download_path = cache_root / "pdfs" / download_name
if not download_path.exists():
download_file(liii_pdf_url, download_path)
pdf_details.update(
{
"pdf_name_used": download_name,
"pdf_path_used": str(download_path),
"pdf_url_used": liii_pdf_url,
"pdf_origin": "downloaded",
"pdf_version_sync": True,
"notes": [
"Using the source-matched Lessons in Industrial Instrumentation version 2.16 PDF downloaded from ibiblio for verification."
],
}
)
else:
pdf_details["notes"].append(
"No external version-matched PDF URL was provided; verification falls back to the bundled PDF."
)
if not book.pdf_version_sync:
pdf_details["notes"].append(
"Bundled PDF is newer than the available source tree. Source is liii_2v16.latex (January 1, 2016) while the bundled PDF metadata reports version 2.33 created on October 9, 2024."
)
return pdf_details
def load_pdf_text_pages(pdf_path: Path, text_cache_path: Path) -> list[str]:
if not text_cache_path.exists():
result = run(["pdftotext", "-layout", str(pdf_path), "-"])
text_cache_path.write_text(result.stdout)
return text_cache_path.read_text(errors="ignore").split("\f")
def parse_sml_references(book: BookConfig, source_dir: Path) -> dict[str, list[dict[str, Any]]]:
refs: dict[str, list[dict[str, Any]]] = {}
for source_path in sorted(source_dir.glob(book.source_glob or "")):
text = source_path.read_text(errors="ignore")
chapter = None
section = None
for match in SML_TOKEN_RE.finditer(text):
line = text.count("\n", 0, match.start()) + 1
if match.group("chapter"):
chapter = normalize_space(match.group("chapter_text") or "")
continue
if match.group("section"):
section = normalize_space(match.group("section_text") or "")
continue
if not match.group("image"):
continue
image_name = (match.group("image_name") or "").strip()
caption = normalize_space(match.group("caption") or "")
stem = Path(image_name).stem
refs.setdefault(stem, []).append(
{
"reference_source": str(source_path.relative_to(source_dir)),
"line": line,
"chapter": chapter,
"section": section,
"caption": caption or None,
"raw_reference": image_name,
}
)
return refs
def parse_latex_references(book: BookConfig, source_dir: Path) -> dict[str, list[dict[str, Any]]]:
if not book.source_file:
return {}
source_path = source_dir / book.source_file
refs: dict[str, list[dict[str, Any]]] = {}
chapter = None
section = None
subsection = None
for line_number, line in enumerate(source_path.read_text(errors="ignore").splitlines(), start=1):
for sm in LATEX_SECTION_RE.finditer(line):
title = normalize_space(sm.group("title") or "")
kind = sm.group("kind")
if kind == "chapter":
chapter = title
section = None
subsection = None
elif kind == "section":
section = title
subsection = None
elif kind == "subsection":
subsection = title
for im in LATEX_INCLUDE_RE.finditer(line):
stem = Path(im.group("name")).stem
refs.setdefault(stem, []).append(
{
"reference_source": book.source_file,
"line": line_number,
"chapter": chapter,
"section": section,
"subsection": subsection,
"caption": None,
"line_excerpt": normalize_space(line),
}
)
return refs
def parse_eps_metadata(eps_path: Path) -> dict[str, Any]:
text = eps_path.read_text(errors="ignore")
creator_match = XCIRCUIT_CREATOR_RE.search(text)
creator = normalize_space(creator_match.group(1)) if creator_match else None
procedures = sorted(set(EPS_PROC_RE.findall(text)))
circuit_tokens = sorted(
procedure
for procedure in procedures
if component_family_kind(procedure)[0] in ELECTRICAL_FAMILIES
)
is_xcircuit = bool(creator and "circuit" in creator.lower())
return {
"creator": creator,
"procedures": procedures,
"circuit_tokens": circuit_tokens,
"is_circuit": bool(circuit_tokens),
"is_xcircuit": is_xcircuit,
"code": text,
}
def parse_eps_bounding_box(source_code: str) -> tuple[float, float, float, float]:
match = re.search(
r"^%%BoundingBox:\s*(\S+)\s+(\S+)\s+(\S+)\s+(\S+)", source_code, re.M
)
if not match:
raise ValueError("Missing EPS bounding box")
return tuple(float(value) for value in match.groups())
def split_page_body(source_code: str) -> tuple[str, str, str] | None:
match = PAGE_BODY_RE.search(source_code)
if not match:
return None
return match.group("prefix"), match.group("body"), match.group("suffix")
def replace_page_body(source_code: str, new_body: str) -> str:
page_parts = split_page_body(source_code)
if not page_parts:
return source_code
prefix, _, suffix = page_parts
return source_code[: PAGE_BODY_RE.search(source_code).start()] + prefix + new_body + suffix
def strip_forbidden_invocations(source_code: str) -> tuple[str, list[str]]:
page_parts = split_page_body(source_code)
if not page_parts:
return source_code, []
prefix, body, suffix = page_parts
kept_lines: list[str] = []
removed: list[str] = []
for line in body.splitlines():
match = INVOCATION_LINE_RE.match(line)
if match and match.group("name") in STRIP_INVOCATION_PROCEDURES:
removed.append(match.group("name"))
continue
kept_lines.append(line)
rewritten = source_code[: PAGE_BODY_RE.search(source_code).start()] + prefix
if kept_lines:
rewritten += "\n".join(kept_lines) + "\n"
rewritten += suffix
return rewritten, sorted(set(removed))
def strip_trailing_ground_invocations(source_code: str) -> tuple[str, int]:
page_parts = split_page_body(source_code)
if not page_parts:
return source_code, 0
prefix, body, suffix = page_parts
anchor_x: float | None = None
for line in body.splitlines():
match = FULL_INVOCATION_LINE_RE.match(line)
if not match:
continue
name = match.group("name")
if name in PRIMARY_SEED_PROCEDURES:
x = float(match.group("x"))
anchor_x = x if anchor_x is None else max(anchor_x, x)
if anchor_x is None:
return source_code, 0
kept_lines: list[str] = []
removed = 0
for line in body.splitlines():
match = FULL_INVOCATION_LINE_RE.match(line)
if match and match.group("name") == "gnd" and float(match.group("x")) > anchor_x + 64.0:
removed += 1
continue
kept_lines.append(line)
rewritten = source_code[: PAGE_BODY_RE.search(source_code).start()] + prefix
if kept_lines:
rewritten += "\n".join(kept_lines) + "\n"
rewritten += suffix
return rewritten, removed
def reject_reason_for_figure(
book: BookConfig,
refs: list[dict[str, Any]],
source_code: str,
) -> str | None:
chapter = normalize_space(refs[0].get("chapter") or "").lower() if refs else ""
section = normalize_space(refs[0].get("section") or "").lower() if refs else ""
if (
book.slug == "DC"
and chapter == "dc metering circuits"
and section == "what is a meter?"
):
return "meter illustration section"
for pattern, reason in NON_CIRCUIT_SOURCE_PATTERNS:
if pattern.search(source_code):
return reason
return None
def parse_page_transform(source_code: str) -> tuple[tuple[float, float, float, float], float, float, float]:
bbox = parse_eps_bounding_box(source_code)
page_parts = split_page_body(source_code)
if not page_parts:
return bbox, 1.0, 0.0, 0.0
_, body, _ = page_parts
scale_match = PAGE_SCALE_RE.search(body)
scale = 1.0
if scale_match:
unit_scale = 0.375 if scale_match.group("kind") == "inchscale" else 0.35433071
scale = float(scale_match.group("scale")) * unit_scale
translate_match = PAGE_TRANSLATE_RE.search(body)
tx = float(translate_match.group("x")) if translate_match else 0.0
ty = float(translate_match.group("y")) if translate_match else 0.0
return bbox, scale, tx, ty
def dumps_json(value: Any) -> str:
return json.dumps(value, ensure_ascii=True, sort_keys=True)
def sha256_text(text: str) -> str:
return hashlib.sha256(text.encode("utf-8")).hexdigest()
def sha256_bytes(data: bytes) -> str:
return hashlib.sha256(data).hexdigest()
def normalize_code_for_hash(source_code: str) -> str:
return "\n".join(line.rstrip() for line in source_code.strip().splitlines())
def normalize_body_for_hash(source_code: str) -> str:
page_parts = split_page_body(source_code)
if not page_parts:
return normalize_code_for_hash(source_code)
return normalize_code_for_hash(page_parts[1])
def image_pixel_sha256(path: Path) -> str:
with Image.open(path) as image:
rgba = image.convert("RGBA")
return sha256_bytes(rgba.tobytes())
def image_dimensions(path: Path) -> tuple[int, int]:
with Image.open(path) as image:
return image.size
def _dct_matrix(size: int) -> np.ndarray:
matrix = np.zeros((size, size), dtype=np.float64)
factor = math.pi / (2.0 * size)
scale0 = math.sqrt(1.0 / size)
scale = math.sqrt(2.0 / size)
for k in range(size):
alpha = scale0 if k == 0 else scale
for n in range(size):
matrix[k, n] = alpha * math.cos((2 * n + 1) * k * factor)
return matrix
_PHASH_DCT = _dct_matrix(PHASH_HIGHFREQ)
def compute_image_phash(path: Path) -> str:
with Image.open(path) as image:
gray = image.convert("L").resize((PHASH_HIGHFREQ, PHASH_HIGHFREQ))
pixels = np.asarray(gray, dtype=np.float64)
transformed = _PHASH_DCT @ pixels @ _PHASH_DCT.T
low_freq = transformed[:PHASH_SIZE, :PHASH_SIZE]
flat = low_freq.flatten()
median = float(np.median(flat[1:])) if flat.size > 1 else float(flat[0])
bits = "".join("1" if value > median else "0" for value in flat)
return f"{int(bits, 2):0{len(bits) // 4}x}"
def phash_distance(left: str | None, right: str | None) -> int | None:
if not left or not right:
return None
return (int(left, 16) ^ int(right, 16)).bit_count()
def compare_image_paths(rendered_path: Path, reference_path: Path | None) -> dict[str, Any]:
if not reference_path or not reference_path.exists():
return {"status": "not_run"}
with Image.open(rendered_path) as rendered_img, Image.open(reference_path) as reference_img:
rendered = rendered_img.convert("RGBA")
reference = reference_img.convert("RGBA")
stored_size = list(reference.size)
rendered_size = list(rendered.size)
if rendered.size != reference.size:
reference = reference.resize(rendered.size)
diff = ImageChops.difference(rendered, reference).convert("L")
histogram = diff.histogram()
total_pixels = max(1, rendered.width * rendered.height)
diff_sum = int(sum(index * value for index, value in enumerate(histogram)))
mae = round(diff_sum / float(total_pixels), 6)
match = diff.getbbox() is None
rendered_hash = compute_image_phash(rendered_path)
reference_hash = compute_image_phash(reference_path)
return {
"status": "ok",
"match": match,
"mae": mae,
"phash_distance": phash_distance(rendered_hash, reference_hash),
"rendered_size": rendered_size,
"stored_size": stored_size,
}
def decode_ps_string(raw: str) -> str:
if raw.startswith("(") and raw.endswith(")"):
raw = raw[1:-1]
out: list[str] = []
index = 0
while index < len(raw):
char = raw[index]
if char != "\\":
out.append(char)
index += 1
continue
index += 1
if index >= len(raw):
break
escaped = raw[index]
if escaped in "()\\":
out.append(escaped)
index += 1
continue
if escaped == "n":
out.append("\n")
index += 1
continue
if escaped == "r":
out.append("\r")
index += 1
continue
if escaped == "t":
out.append("\t")
index += 1
continue
if escaped.isdigit():
octal = escaped
for _ in range(2):
if index + 1 < len(raw) and raw[index + 1].isdigit():
index += 1
octal += raw[index]
else:
break
out.append(chr(int(octal, 8)))
index += 1
continue
out.append(escaped)
index += 1
return normalize_space("".join(out).replace("\n", " "))
def extract_label_strings(content: str) -> list[str]:
return [decode_ps_string(match.group(0)) for match in PS_STRING_RE.finditer(content)]
def parse_visible_labels(body: str) -> list[dict[str, Any]]:
labels: list[dict[str, Any]] = []
for match in LABEL_COMMAND_RE.finditer(body):
if match.group("kind") not in {"label", "pinlabel", "pinglobal"}:
continue
parts = [value for value in extract_label_strings(match.group("content")) if value]
labels.append(
{
"raw": normalize_space(match.group("raw")),
"kind": match.group("kind"),
"text": normalize_space(" ".join(parts)),
"x": float(match.group("x")),
"y": float(match.group("y")),
"scale": float(match.group("scale")) if match.group("scale") else 1.0,
"rotation": float(match.group("rot")),
}
)
return labels
def parse_symbol_procedures(source_code: str) -> dict[str, str]:
lines = source_code.splitlines()
procedures: dict[str, str] = {}
index = 0
while index < len(lines):
line = lines[index]
if line.startswith("/") and line.rstrip().endswith("{"):
name = line[1:].split("{", 1)[0].strip()
depth = line.count("{") - line.count("}")
body_lines: list[str] = []
index += 1
while index < len(lines):
current = lines[index]
depth += current.count("{") - current.count("}")
if depth <= 0 and current.strip().endswith("def"):
break
body_lines.append(current)
index += 1
procedures[name] = "\n".join(body_lines)
index += 1
return procedures
def parse_symbol_pin_catalog(source_code: str) -> dict[str, list[dict[str, Any]]]:
pin_catalog: dict[str, list[dict[str, Any]]] = {}
for proc_name, body in parse_symbol_procedures(source_code).items():
entries: list[dict[str, Any]] = []
for match in LABEL_COMMAND_RE.finditer(body):
kind = match.group("kind")
if kind not in {"pinlabel", "pinglobal"}:
continue
strings = extract_label_strings(match.group("content"))
label_text = normalize_space(" ".join(strings))
entries.append(
{
"label": label_text,
"kind": "terminal" if kind == "pinlabel" else "global",
"x": float(match.group("x")),
"y": float(match.group("y")),
"raw": normalize_space(match.group("raw")),
}
)
if entries:
pin_catalog[proc_name] = entries
return pin_catalog
def component_family_kind(name: str) -> tuple[str, str]:
if name in PROCEDURE_KIND_MAP:
return PROCEDURE_KIND_MAP[name]
lower = name.lower()
if lower in DECORATIVE_PROCEDURES or lower.startswith("truth_") or lower.startswith("die_"):
return "decorative", lower
if lower in BLOCK_PROCEDURES:
return "block", lower
if lower in TERMINAL_PROCEDURES or lower.startswith("binding_post"):
return "io", "terminal"
if lower in SOURCE_PROCEDURES or lower.startswith("real_batt") or lower.endswith("_source"):
return "source", "ac_source" if "ac" in lower else "voltage_source"
if lower in CURRENT_SOURCE_PROCEDURES:
return "source", "current_source"
if lower in SWITCH_PROCEDURES or lower.startswith("no_") or lower.startswith("nc_"):
return "switch", "relay" if "relay" in lower else "switch"
if lower in LOGIC_PROCEDURES or "flipflop" in lower or "latch" in lower or "adder" in lower:
return "logic", "integrated_circuit"
if lower in INDICATOR_PROCEDURES or "scope" in lower:
return "indicator", "instrument"
if lower in PASSIVE_RESISTIVE_PROCEDURES or lower == "strain_gauge":
return "passive", "resistor"
if lower in PASSIVE_MAGNETIC_PROCEDURES:
return "passive", "inductor" if "inductor" in lower or "coil" in lower else "transformer"
if lower in SEMICONDUCTOR_DIODE_PROCEDURES:
return "semiconductor", "diode"
if lower in SEMICONDUCTOR_TRANSISTOR_PROCEDURES:
return "semiconductor", "transistor"
if lower in ACTIVE_TUBE_PROCEDURES or (lower.startswith("tube_") and lower != "tube_tee"):
return "active", "vacuum_tube"
if lower in {"plc_powersupply"} or "powersupply" in lower:
return "source", "voltage_source"
if lower in {"plc_processor"} or "processor" in lower:
return "logic", "integrated_circuit"
if lower in {"clip", "label", "marks"} or lower.startswith("die_") or lower.startswith("truth_"):
return "decorative", lower
if "arrow" in lower:
return "decorative", lower
if "opamp" in lower or (lower.endswith("amp") and "lamp" not in lower):
return "active", "op_amp"
if name.endswith("_gate") or "gate" in lower or lower in {"nor", "buffer"} or "flipflop" in lower or lower.startswith("dip_"):
return "logic", "logic_gate"
if "flipflop" in lower or "latch" in lower or lower in {"xnor", "xor", "xnor", "schmitt"}:
return "logic", "integrated_circuit"
if "resistor" in lower or lower == "strain_gauge":
return "passive", "resistor"
if "capacitor" in lower or "polarized" in lower:
return "passive", "capacitor"
if "inductor" in lower or "coil" in lower:
return "passive", "inductor"
if "transformer" in lower or lower == "core":
return "passive", "transformer"
if "battery" in lower or lower in {"vsource", "cell", "vdd", "vss", "vcc", "vee"}:
return "source", "voltage_source"
if "isource" in lower or "current" in lower:
return "source", "current_source"
if "source" in lower:
return "source", "ac_source" if "ac" in lower else "voltage_source"
if "switch" in lower or "toggle" in lower or "pushbutton" in lower or "contact" in lower:
return "switch", "switch"
if (
"diode" in lower
or "mosfet" in lower
or "jfet" in lower
or lower in {"scr", "diode", "triac", "diac", "gto", "gcs", "scs", "ujt"}
or "fet" in lower
or lower.startswith("npn")
or lower.startswith("pnp")
or lower.startswith("transistor")
or lower == "nmos"
):
transistor_like = (
"fet" in lower
or lower in {"scr", "triac", "gto", "gcs", "scs", "ujt", "nmos"}
or lower.startswith("npn")
or lower.startswith("pnp")
or lower.startswith("transistor")
)
return "semiconductor", "transistor" if transistor_like else "diode"
if "lamp" in lower or "meter" in lower or "motor" in lower or "detector" in lower or "speaker" in lower:
return "indicator", "indicator"
if "connector" in lower or "terminal" in lower or lower in {"stud", "tap", "powerpole"}:
return "io", "terminal"
if lower in {"fuse", "thermal_overload"}:
return "protection", "fuse"
if "relay" in lower:
return "switch", "relay"
return "unknown", name.lower()
def classify_component(component: dict[str, Any]) -> str:
family = component.get("family", "unknown")
kind = component.get("kind", "unknown")
if family in {"ground", "io", "junction"}:
return "terminal"
if family in {"active", "passive", "source", "semiconductor", "switch", "indicator", "protection", "logic"}:
return "electrical"
if family in {"block", "decorative"}:
return "decorative"
if family == "unknown":
return "unknown_bad"
return "other_bad"
def min_connected_pins(component: dict[str, Any]) -> int:
family = component.get("family", "unknown")
kind = component.get("kind", "unknown")
if kind in MIN_CONNECTED_PINS:
return MIN_CONNECTED_PINS[kind]
if family in {"active", "passive", "source", "semiconductor", "switch", "indicator", "protection", "logic"}:
return 2
return 1
def transform_component_point(
x: float,
y: float,
*,
scale: float,
rotation_deg: float,
origin_x: float,
origin_y: float,
page_scale: float,
page_tx: float,
page_ty: float,
) -> tuple[float, float]:
effective_scale = abs(scale)
radians = math.radians(rotation_deg)
scaled_x = x * effective_scale
scaled_y = y * effective_scale
rotated_x = scaled_x * math.cos(radians) - scaled_y * math.sin(radians)
rotated_y = scaled_x * math.sin(radians) + scaled_y * math.cos(radians)
global_x = page_scale * (page_tx + origin_x + rotated_x)
global_y = page_scale * (page_ty + origin_y + rotated_y)
return global_x, global_y
def point_to_ref(x: float, y: float) -> str:
return f"coord:{PAGE_SCOPE_ID}:{x:.3f}:{y:.3f}"
def point_payload(x: float, y: float) -> dict[str, float]:
return {"x": round(x, 3), "y": round(y, 3)}
def bbox_from_points(points: list[tuple[float, float]]) -> tuple[float, float, float, float]:
xs = [point[0] for point in points]
ys = [point[1] for point in points]
return min(xs), min(ys), max(xs), max(ys)
def bbox_intersects(
outer: tuple[float, float, float, float],
inner: tuple[float, float, float, float],
*,
margin: float = 0.0,
) -> bool:
left, bottom, right, top = outer
in_left, in_bottom, in_right, in_top = inner
return not (
in_right < left - margin
or in_left > right + margin
or in_top < bottom - margin
or in_bottom > top + margin
)
def point_inside_bbox(
point: tuple[float, float],
bbox: tuple[float, float, float, float],
*,
margin: float = 0.0,
) -> bool:
x, y = point
left, bottom, right, top = bbox
return left - margin <= x <= right + margin and bottom - margin <= y <= top + margin
def distance_to_bbox_boundary(
point: tuple[float, float],
bbox: tuple[float, float, float, float],
) -> float:
x, y = point
left, bottom, right, top = bbox
if left <= x <= right and bottom <= y <= top:
return min(x - left, right - x, y - bottom, top - y)
dx = 0.0 if left <= x <= right else min(abs(x - left), abs(x - right))
dy = 0.0 if bottom <= y <= top else min(abs(y - bottom), abs(y - top))
if dx == 0.0:
return dy
if dy == 0.0:
return dx
return math.hypot(dx, dy)
def bbox_segments(
bbox: tuple[float, float, float, float]
) -> list[tuple[tuple[float, float], tuple[float, float]]]:
left, bottom, right, top = bbox
return [
((left, bottom), (right, bottom)),
((right, bottom), (right, top)),
((right, top), (left, top)),
((left, top), (left, bottom)),
]
def snap_key(point: tuple[float, float]) -> tuple[int, int]:
return (round(point[0] / COORD_SNAP), round(point[1] / COORD_SNAP))
def dedupe_points(points: list[tuple[float, float]]) -> list[tuple[float, float]]:
unique: dict[tuple[int, int], tuple[float, float]] = {}
for point in points:
key = snap_key(point)
unique.setdefault(key, (round(point[0], 3), round(point[1], 3)))
return list(unique.values())
def _projection_fraction(
point: tuple[float, float],
start: tuple[float, float],
end: tuple[float, float],
) -> float:
dx = end[0] - start[0]
dy = end[1] - start[1]
denom = dx * dx + dy * dy
if denom <= 1e-9:
return 0.0
return ((point[0] - start[0]) * dx + (point[1] - start[1]) * dy) / denom
def point_on_segment(
point: tuple[float, float],
start: tuple[float, float],
end: tuple[float, float],
*,
tolerance: float = COORD_SNAP,
) -> bool:
if start == end:
return math.dist(point, start) <= tolerance
t = _projection_fraction(point, start, end)
if t < -1e-6 or t > 1.0 + 1e-6:
return False
projected = (start[0] + t * (end[0] - start[0]), start[1] + t * (end[1] - start[1]))
return math.dist(projected, point) <= tolerance
def segment_intersection(
start_a: tuple[float, float],
end_a: tuple[float, float],
start_b: tuple[float, float],
end_b: tuple[float, float],
*,
tolerance: float = COORD_SNAP,
) -> tuple[float, float] | None:
ax1, ay1 = start_a
ax2, ay2 = end_a
bx1, by1 = start_b
bx2, by2 = end_b
denom = (ax1 - ax2) * (by1 - by2) - (ay1 - ay2) * (bx1 - bx2)
if abs(denom) <= 1e-9:
shared = [point for point in (start_a, end_a, start_b, end_b) if point_on_segment(point, start_a, end_a, tolerance=tolerance) and point_on_segment(point, start_b, end_b, tolerance=tolerance)]
if shared:
return min(shared)
return None
px = (
(ax1 * ay2 - ay1 * ax2) * (bx1 - bx2)
- (ax1 - ax2) * (bx1 * by2 - by1 * bx2)
) / denom
py = (
(ax1 * ay2 - ay1 * ax2) * (by1 - by2)
- (ay1 - ay2) * (bx1 * by2 - by1 * bx2)
) / denom
point = (px, py)
if point_on_segment(point, start_a, end_a, tolerance=tolerance) and point_on_segment(point, start_b, end_b, tolerance=tolerance):
return point
return None
def sort_points_on_segment(
points: set[tuple[float, float]],
start: tuple[float, float],
end: tuple[float, float],
) -> list[tuple[float, float]]:
return sorted(points, key=lambda point: _projection_fraction(point, start, end))
def fallback_bbox_pin_points(component: dict[str, Any]) -> list[tuple[float, float]]:
bbox_values = component.get("bbox")
if not bbox_values:
origin = component.get("point")
if origin:
return [(float(origin["x"]), float(origin["y"]))]
return []
bbox = tuple(float(value) for value in bbox_values)
left, bottom, right, top = bbox
center_x = (left + right) / 2.0
center_y = (bottom + top) / 2.0
family = component.get("family", "unknown")
expected = min_connected_pins(component)
if family in {"ground", "io", "junction"} or expected <= 1:
return [(center_x, center_y)]
if expected != 2:
return []
if (right - left) >= (top - bottom):
return [(left, center_y), (right, center_y)]
return [(center_x, bottom), (center_x, top)]
def infer_missing_component_pins(
components: list[dict[str, Any]],
pins: list[dict[str, Any]],
wire_polylines: list[dict[str, Any]],
*,
start_index: int,
) -> tuple[list[dict[str, Any]], int, list[str]]:
pins_by_component: dict[str, list[dict[str, Any]]] = defaultdict(list)
for pin in pins:
pins_by_component[pin["component_id"]].append(pin)
conductive_segments: list[tuple[tuple[float, float], tuple[float, float]]] = []
for wire in wire_polylines:
if not wire.get("conductive"):
continue
points = [(float(point["x"]), float(point["y"])) for point in wire["points"]]
for start, end in zip(points, points[1:]):
conductive_segments.append((start, end))
inferred_pins: list[dict[str, Any]] = []
missing_warnings: list[str] = []
pin_index = start_index
for component in components:
if pins_by_component.get(component["id"]):
continue
family = component.get("family", "unknown")
if family in {"decorative", "block"}:
continue
bbox_values = component.get("bbox")
candidate_points: list[tuple[float, float]] = []
if bbox_values:
bbox = tuple(float(value) for value in bbox_values)
for start, end in conductive_segments:
seg_bbox = (
min(start[0], end[0]),
min(start[1], end[1]),
max(start[0], end[0]),
max(start[1], end[1]),
)
if not bbox_intersects(bbox, seg_bbox, margin=PIN_INFER_EXPAND_MARGIN):
continue
for point in (start, end):
if point_inside_bbox(point, bbox, margin=PIN_INFER_EXPAND_MARGIN) and distance_to_bbox_boundary(point, bbox) <= PIN_INFER_BOUNDARY_MARGIN:
candidate_points.append(point)
for edge_start, edge_end in bbox_segments(bbox):
intersection = segment_intersection(start, end, edge_start, edge_end, tolerance=PIN_INFER_EXPAND_MARGIN)
if intersection is not None:
candidate_points.append(intersection)
candidate_points = sorted(
dedupe_points(candidate_points),
key=lambda point: (round(point[0], 3), round(point[1], 3)),
)
if not candidate_points:
candidate_points = fallback_bbox_pin_points(component)
if not candidate_points:
missing_warnings.append(f"missing_pins:{component['raw_kind']}:{component['id']}")
continue
for pin_position, point in enumerate(candidate_points[:MAX_INFERRED_COMPONENT_PINS], start=1):
pin_id = f"{component['id']}.pin_{pin_index:04d}"
pin_index += 1
inferred_pins.append(
{
"id": pin_id,
"component_id": component["id"],
"name": f"inferred_{pin_position}",
"kind": "terminal",
"point": point_payload(*point),
"point_ref": point_to_ref(*point),
"raw": "inferred_from_bbox_wire",
}
)
return inferred_pins, pin_index, missing_warnings
def count_words(text: str) -> int:
return len(re.findall(r"[A-Za-z0-9_]+", text))
def first_caption(refs: list[dict[str, Any]]) -> str | None:
for ref in refs:
caption = normalize_space(ref.get("caption") or "")
if caption:
return caption
return None
def build_description(book: BookConfig, figure_stem: str, refs: list[dict[str, Any]]) -> str:
parts = [book.display_name, f"Figure {figure_stem}"]
if refs:
ref = refs[0]
for key in ("chapter", "section", "subsection"):
value = normalize_space(ref.get(key) or "")
if value:
parts.append(value)
caption = first_caption(refs)
if caption:
parts.append(caption)
return " | ".join(parts)
def synthesize_component_spans(components: list[dict[str, Any]], pins: list[dict[str, Any]]) -> list[dict[str, Any]]:
pins_by_component: dict[str, list[dict[str, Any]]] = defaultdict(list)
for pin in pins:
pins_by_component[pin["component_id"]].append(pin)
spans: list[dict[str, Any]] = []
span_index = 1
for component in components:
component_pins = pins_by_component.get(component["id"], [])
if len(component_pins) != 2:
continue
ordered = sorted(component_pins, key=lambda item: item["id"])
spans.append(
{
"id": f"wire_cmp_{span_index:04d}",
"kind": "component_span",
"conductive": False,
"draw_options": [component["kind"]],
"points": [
{
"kind": "coord",
"raw": ordered[0]["point_ref"],
"ref": ordered[0]["point_ref"],
**ordered[0]["point"],
},
{
"kind": "coord",
"raw": ordered[1]["point_ref"],
"ref": ordered[1]["point_ref"],
**ordered[1]["point"],
},
],
"point_refs": [ordered[0]["point_ref"], ordered[1]["point_ref"]],
"raw": component["raw"],
"scope_id": PAGE_SCOPE_ID,
"component_id": component["id"],
}
)
span_index += 1
return spans
def build_eps_ir(source_code: str) -> dict[str, Any]:
page_parts = split_page_body(source_code)
if not page_parts:
return {
"parse_status": "failed",
"circuit_ir_json": dumps_json({}),
"parse_warnings_json": dumps_json(["missing_page_body"]),
"unsupported_constructs_json": dumps_json([]),
"component_count": 0,
"pin_count": 0,
"net_count": 0,
"wire_count": 0,
"label_count": 0,
}
bbox, page_scale, page_tx, page_ty = parse_page_transform(source_code)
_, body, _ = page_parts
proc_pin_catalog = parse_symbol_pin_catalog(source_code)
proc_bbox_catalog = {
match.group("name"): (
int(match.group("x")),
int(match.group("y")),
int(match.group("w")),
int(match.group("h")),
)
for match in PROC_BBOX_RE.finditer(source_code)
}
components: list[dict[str, Any]] = []
pins: list[dict[str, Any]] = []
transforms: list[dict[str, Any]] = [
{
"scope_id": PAGE_SCOPE_ID,
"parent_scope_id": None,
"raw": f"bbox={bbox}",
"options": {
"page_scale": round(page_scale, 6),
"translate_x": round(page_tx, 3),
"translate_y": round(page_ty, 3),
"bounding_box": [round(value, 3) for value in bbox],
},
}
]
warnings_list: list[str] = []
unsupported_constructs: list[str] = []
pin_index = 1
component_index = 1
for match in FULL_INVOCATION_LINE_RE.finditer(body):
proc_name = match.group("name")
family, kind = component_family_kind(proc_name)
origin_x = float(match.group("x"))
origin_y = float(match.group("y"))
rotation = float(match.group("rot"))
scale = float(match.group("scale"))
local_bbox = proc_bbox_catalog.get(proc_name) or PROC_BBOX_CATALOG.get(proc_name)
placed_bbox = None
if local_bbox:
bx, by, bw, bh = local_bbox
corners = [
transform_component_point(
corner_x,
corner_y,
scale=scale,
rotation_deg=rotation,
origin_x=origin_x,
origin_y=origin_y,
page_scale=page_scale,
page_tx=page_tx,
page_ty=page_ty,
)
for corner_x, corner_y in (
(bx, by),
(bx + bw, by),
(bx, by + bh),
(bx + bw, by + bh),
)
]
placed_bbox = bbox_from_points(corners)
if not bbox_intersects(bbox, placed_bbox, margin=COORD_SNAP):
continue
global_origin = transform_component_point(
0.0,
0.0,
scale=scale,
rotation_deg=rotation,
origin_x=origin_x,
origin_y=origin_y,
page_scale=page_scale,
page_tx=page_tx,
page_ty=page_ty,
)
if not point_inside_bbox(global_origin, bbox, margin=COORD_SNAP) and not placed_bbox:
continue
component_id = f"cmp_{component_index:04d}"
component_index += 1
component_payload = {
"id": component_id,
"family": family,
"kind": kind,
"raw_kind": proc_name,
"raw": normalize_space(match.group(0)),
"scope_id": PAGE_SCOPE_ID,
"point": point_payload(*global_origin),
"point_ref": point_to_ref(*global_origin),
"option_tokens": [proc_name],
"options_raw": proc_name,
"transform_id": f"xfm_{component_id}",
}
if placed_bbox:
component_payload["bbox"] = [round(value, 3) for value in placed_bbox]
components.append(component_payload)
transforms.append(
{
"scope_id": component_payload["transform_id"],
"parent_scope_id": PAGE_SCOPE_ID,
"raw": normalize_space(match.group(0)),
"options": {
"procedure": proc_name,
"scale": scale,
"rotation": rotation,
"origin_x": origin_x,
"origin_y": origin_y,
"bbox": component_payload.get("bbox"),
},
}
)
local_pins = proc_pin_catalog.get(proc_name, [])
if not local_pins and family in {"passive", "source", "indicator", "protection", "switch"} and local_bbox:
bx, by, bw, bh = local_bbox
if abs(bh) >= abs(bw):
local_pins = [
{"label": "start", "kind": "terminal", "x": 0.0, "y": by + bh, "raw": "inferred"},
{"label": "end", "kind": "terminal", "x": 0.0, "y": by, "raw": "inferred"},
]
else:
local_pins = [
{"label": "start", "kind": "terminal", "x": bx, "y": 0.0, "raw": "inferred"},
{"label": "end", "kind": "terminal", "x": bx + bw, "y": 0.0, "raw": "inferred"},
]
if not local_pins and family in {"junction", "io", "ground"}:
local_pins = [
{"label": kind, "kind": "terminal", "x": 0.0, "y": 0.0, "raw": "inferred"}
]
for pin_position, pin_info in enumerate(local_pins, start=1):
global_point = transform_component_point(
float(pin_info["x"]),
float(pin_info["y"]),
scale=scale,
rotation_deg=rotation,
origin_x=origin_x,
origin_y=origin_y,
page_scale=page_scale,
page_tx=page_tx,
page_ty=page_ty,
)
if not point_inside_bbox(global_point, bbox, margin=COORD_SNAP):
continue
name = pin_info["label"] or f"pin_{pin_position}"
pin_id = f"{component_id}.pin_{pin_index:04d}"
pin_index += 1
pins.append(
{
"id": pin_id,
"component_id": component_id,
"name": name,
"kind": pin_info.get("kind", "terminal"),
"point": point_payload(*global_point),
"point_ref": point_to_ref(*global_point),
"raw": pin_info.get("raw"),
}
)
labels: list[dict[str, Any]] = []
label_index = 1
for label_info in parse_visible_labels(body):
point = (
page_scale * (page_tx + label_info["x"]),
page_scale * (page_ty + label_info["y"]),
)
if not point_inside_bbox(point, bbox, margin=COORD_SNAP):
continue
labels.append(
{
"id": f"lbl_{label_index:04d}",
"scope_id": PAGE_SCOPE_ID,
"raw": label_info["raw"],
"text": label_info["text"],
"point": point_payload(*point),
"point_ref": point_to_ref(*point),
"kind": label_info["kind"],
}
)
label_index += 1
wire_polylines: list[dict[str, Any]] = []
wire_index = 1
conductive_wire_ids: set[str] = set()
for line in body.splitlines():
stripped = line.strip()
if not stripped.endswith("polygon"):
continue
tokens = stripped.split()
if len(tokens) < 8:
unsupported_constructs.append(f"polygon:{stripped}")
continue
try:
style = int(float(tokens[0]))
line_width = float(tokens[1])
point_count = int(tokens[-2])
coords = [float(value) for value in tokens[2:-2]]
except ValueError:
unsupported_constructs.append(f"polygon:{stripped}")
continue
if len(coords) != point_count * 2:
unsupported_constructs.append(f"polygon_coord_mismatch:{stripped}")
continue
points = [
(
page_scale * (page_tx + coords[index]),
page_scale * (page_ty + coords[index + 1]),
)
for index in range(0, len(coords), 2)
]
poly_bbox = bbox_from_points(points)
if not bbox_intersects(bbox, poly_bbox, margin=COORD_SNAP):
continue
conductive = bool(style & 1)
wire_id = f"wire_{wire_index:04d}"
wire_index += 1
if conductive:
conductive_wire_ids.add(wire_id)
wire_polylines.append(
{
"id": wire_id,
"kind": "wire" if conductive else "graphic_polyline",
"conductive": conductive,
"draw_options": [f"style:{style}", f"width:{line_width:g}"],
"points": [
{
"kind": "coord",
"raw": f"({coords[index]:g},{coords[index + 1]:g})",
"ref": point_to_ref(*point),
**point_payload(*point),
}
for index, point in zip(range(0, len(coords), 2), points)
],
"point_refs": [point_to_ref(*point) for point in points],
"raw": stripped,
"scope_id": PAGE_SCOPE_ID,
}
)
inferred_pins, pin_index, missing_pin_warnings = infer_missing_component_pins(
components,
pins,
wire_polylines,
start_index=pin_index,
)
pins.extend(inferred_pins)
warnings_list.extend(missing_pin_warnings)
wire_polylines.extend(synthesize_component_spans(components, pins))
node_points: dict[tuple[int, int], tuple[float, float]] = {}
node_labels: dict[tuple[int, int], str] = {}
node_sources: dict[str, set[str]] = defaultdict(set)
graph_adjacency: dict[str, set[str]] = defaultdict(set)
def register_point(point: tuple[float, float]) -> str:
key = snap_key(point)
if key not in node_points:
node_points[key] = (round(point[0], 3), round(point[1], 3))
node_labels[key] = point_to_ref(*node_points[key])
return node_labels[key]
segments: list[dict[str, Any]] = []
for wire in wire_polylines:
if not wire.get("conductive"):
continue
points = [(float(point["x"]), float(point["y"])) for point in wire["points"]]
for start, end in zip(points, points[1:]):
segments.append({"wire_id": wire["id"], "start": start, "end": end, "split_points": {start, end}})
for segment in segments:
for pin in pins:
point = (float(pin["point"]["x"]), float(pin["point"]["y"]))
if point_on_segment(point, segment["start"], segment["end"]):
segment["split_points"].add(point)
for index, left in enumerate(segments):
for right in segments[index + 1 :]:
intersection = segment_intersection(left["start"], left["end"], right["start"], right["end"])
if intersection is None:
continue
left["split_points"].add(intersection)
right["split_points"].add(intersection)
for segment in segments:
ordered = sort_points_on_segment(segment["split_points"], segment["start"], segment["end"])
if len(ordered) < 2:
continue
for start, end in zip(ordered, ordered[1:]):
left_ref = register_point(start)
right_ref = register_point(end)
graph_adjacency[left_ref].add(right_ref)
graph_adjacency[right_ref].add(left_ref)
node_sources[left_ref].add(segment["wire_id"])
node_sources[right_ref].add(segment["wire_id"])
pin_by_ref: dict[str, list[str]] = defaultdict(list)
for pin in pins:
point = (float(pin["point"]["x"]), float(pin["point"]["y"]))
attached_ref = register_point(point)
for existing_ref in list(graph_adjacency):
existing_key = next(key for key, value in node_labels.items() if value == existing_ref)
existing_point = node_points[existing_key]
if math.dist(existing_point, point) <= COORD_SNAP:
attached_ref = existing_ref
break
pin["point"] = point_payload(*next(node_points[key] for key, value in node_labels.items() if value == attached_ref))
pin["point_ref"] = attached_ref
pin_by_ref[attached_ref].append(pin["id"])
nets: list[dict[str, Any]] = []
seen_nodes: set[str] = set()
for node_ref in sorted(set(graph_adjacency) | set(pin_by_ref)):
if node_ref in seen_nodes:
continue
stack = [node_ref]
component_nodes: set[str] = set()
while stack:
current = stack.pop()
if current in seen_nodes:
continue
seen_nodes.add(current)
component_nodes.add(current)
for neighbor in graph_adjacency.get(current, ()):
if neighbor not in seen_nodes:
stack.append(neighbor)
net_pins = sorted({pin_id for ref in component_nodes for pin_id in pin_by_ref.get(ref, [])})
net_wires = sorted({wire_id for ref in component_nodes for wire_id in node_sources.get(ref, set())})
if not net_pins and not net_wires:
continue
nets.append(
{
"id": f"net_{len(nets) + 1:04d}",
"pins": net_pins,
"point_refs": sorted(component_nodes),
"wire_ids": net_wires,
}
)
ir = {
"components": components,
"pins": pins,
"nets": nets,
"wire_polylines": wire_polylines,
"transforms": transforms,
"labels": labels,
}
parse_status = "partial" if warnings_list or unsupported_constructs else "ok"
return {
"parse_status": parse_status,
"circuit_ir_json": dumps_json(ir),
"parse_warnings_json": dumps_json(sorted(set(warnings_list))),
"unsupported_constructs_json": dumps_json(sorted(set(unsupported_constructs))),
"component_count": len(components),
"pin_count": len(pins),
"net_count": len(nets),
"wire_count": len(wire_polylines),
"label_count": len(labels),
}
def overlay_metrics_from_pngs(original_path: Path, no_text_path: Path, word_count: int) -> dict[str, Any]:
with Image.open(original_path) as original_img, Image.open(no_text_path) as no_text_img:
original = original_img.convert("RGB")
no_text = no_text_img.convert("RGB")
if original.size != no_text.size:
no_text = no_text.resize(original.size)
diff = ImageChops.difference(original, no_text).convert("L")
histogram = diff.histogram()
nonzero = int(sum(histogram[1:]))
diff_sum = int(sum(index * value for index, value in enumerate(histogram)))
total_pixels = max(1, original.width * original.height)
return {
"status": "ok",
"width": original.width,
"height": original.height,
"outside_nonzero_pixels": 0,
"outside_sum": 0,
"outside_mean": 0.0,
"inside_nonzero_pixels": nonzero,
"inside_sum": diff_sum,
"inside_mean": round(diff_sum / float(total_pixels), 6),
"text_mask_pixels": nonzero,
"text_mask_fraction": round(nonzero / float(total_pixels), 6),
"word_count": word_count,
"pass": True,
"compiler": "ghostscript",
}
def classify_quality_row(
row: dict[str, Any],
original_render: dict[str, Any],
overlay: dict[str, Any],
no_label_render: dict[str, Any],
) -> tuple[str, bool, list[str]]:
reasons: list[str] = []
parse_warnings = json.loads(row.get("parse_warnings_json") or "[]")
unsupported_constructs = json.loads(row.get("unsupported_constructs_json") or "[]")
if row.get("component_count", 0) <= 0:
reasons.append("component_count_zero")
if row.get("wire_count", 0) <= 0:
reasons.append("wire_count_zero")
if row.get("net_count", 0) <= 0:
reasons.append("net_count_zero")
if row.get("parse_status") == "failed":
reasons.append("parse_failed")
if no_label_render.get("status") != "ok":
reasons.append(f"no_label_{no_label_render.get('status', 'error')}")
if overlay.get("status") != "ok":
reasons.append(f"overlay_{overlay.get('status', 'error')}")
elif not overlay.get("pass", False):
reasons.append("overlay_outside_text_changed")
if original_render.get("status") != "ok":
reasons.append(f"stored_compare_{original_render.get('status', 'error')}")
elif not original_render.get("match", False):
reasons.append("stored_compare_mismatch")
if parse_warnings:
reasons.append("parse_warnings_present")
if unsupported_constructs:
reasons.append("unsupported_constructs_present")
keep = not reasons
return ("well_generated" if keep else "jank", keep, reasons)
def graph_metrics_for_row(row: dict[str, Any], overlay: dict[str, Any], original_render: dict[str, Any]) -> dict[str, Any]:
ir = json.loads(row.get("circuit_ir_json") or "{}")
components = ir.get("components", [])
pins = ir.get("pins", [])
nets = ir.get("nets", [])
pin_to_component = {pin["id"]: pin["component_id"] for pin in pins}
component_by_id = {component["id"]: component for component in components}
component_classes = {component["id"]: classify_component(component) for component in components}
component_class_counts = Counter(component_classes.values())
connected_pin_counts: Counter[str] = Counter()
electrical_edges: set[tuple[str, str]] = set()
one_pin_active_net_count = 0
one_pin_terminal_only_net_count = 0
for net in nets:
active_components: list[str] = []
terminal_components: list[str] = []
for pin_id in net.get("pins", []):
component_id = pin_to_component.get(pin_id)
if not component_id:
continue
connected_pin_counts[component_id] += 1
classification = component_classes.get(component_id)
if classification == "electrical":
active_components.append(component_id)
elif classification == "terminal":
terminal_components.append(component_id)
active_components = sorted(set(active_components))
terminal_components = sorted(set(terminal_components))
if len(active_components) == 1 and not terminal_components:
one_pin_active_net_count += 1
if not active_components and len(terminal_components) == 1:
one_pin_terminal_only_net_count += 1
for index, left in enumerate(active_components):
for right in active_components[index + 1 :]:
electrical_edges.add(tuple(sorted((left, right))))
for right in terminal_components:
electrical_edges.add(tuple(sorted((left, right))))
active_component_ids = sorted(component_id for component_id, value in component_classes.items() if value == "electrical")
graph_component_ids = sorted(component_id for component_id, value in component_classes.items() if value in {"electrical", "terminal"})
adjacency = {component_id: set() for component_id in graph_component_ids}
for left, right in electrical_edges:
adjacency.setdefault(left, set()).add(right)
adjacency.setdefault(right, set()).add(left)
electrical_connected_components = 0
seen: set[str] = set()
for component_id in active_component_ids:
if component_id in seen:
continue
electrical_connected_components += 1
stack = [component_id]
seen.add(component_id)
while stack:
current = stack.pop()
for neighbor in adjacency.get(current, ()):
if neighbor not in seen:
seen.add(neighbor)
stack.append(neighbor)
underconnected_components: list[dict[str, Any]] = []
for component_id in active_component_ids:
component = component_by_id[component_id]
connected_pins = int(connected_pin_counts.get(component_id, 0))
required_pins = min_connected_pins(component)
if connected_pins < required_pins:
underconnected_components.append(
{
"component_id": component_id,
"family": component.get("family", "unknown"),
"kind": component.get("kind", "unknown"),
"connected_pins": connected_pins,
"required_pins": required_pins,
}
)
overlapping_active_components: list[dict[str, Any]] = []
span_map: dict[tuple[str, ...], list[dict[str, Any]]] = {}
for component_id in active_component_ids:
point_refs = tuple(sorted(set(pin.get("point_ref") for pin in pins if pin["component_id"] == component_id)))
if len(point_refs) < 2:
continue
component = component_by_id[component_id]
span_map.setdefault(point_refs, []).append(
{
"component_id": component_id,
"family": component.get("family", "unknown"),
"kind": component.get("kind", "unknown"),
}
)
for point_refs, components_for_span in sorted(span_map.items()):
if len(components_for_span) < 2:
continue
overlapping_active_components.append(
{"point_refs": list(point_refs), "components": components_for_span}
)
render_alignment_ok = (
float(original_render.get("mae", 999.0)) <= GRAPH_RENDER_MAE_MAX
or int(original_render.get("phash_distance", 999)) <= GRAPH_RENDER_PHASH_MAX
)
unknown_component_count = int(
component_class_counts.get("unknown_bad", 0) + component_class_counts.get("other_bad", 0)
)
decorative_component_count = int(component_class_counts.get("decorative", 0))
severe_underconnected = len(underconnected_components) >= max(
2,
math.ceil(len(active_component_ids) * 0.5),
)
symbol_plate_like = bool(
active_component_ids
and one_pin_active_net_count >= max(2, len(active_component_ids))
and electrical_connected_components >= max(1, len(active_component_ids) // 2)
)
heavily_fragmented = electrical_connected_components >= max(
3,
math.ceil(len(active_component_ids) * 0.5),
)
graph_core_reasons: list[str] = []
if row.get("parse_status") == "failed":
graph_core_reasons.append("parse_not_ok")
if len(active_component_ids) == 0:
graph_core_reasons.append("electrical_component_count_zero")
if severe_underconnected and not symbol_plate_like:
graph_core_reasons.append("electrical_component_underconnected")
if heavily_fragmented and severe_underconnected and not symbol_plate_like:
graph_core_reasons.append("electrical_graph_fragmented")
if unknown_component_count > 0:
graph_core_reasons.append("unrecognized_component_present")
if overlapping_active_components:
graph_core_reasons.append("active_component_span_overlap")
pretty_reasons = list(graph_core_reasons)
if electrical_connected_components > 1:
pretty_reasons.append("electrical_graph_components_gt_1")
if underconnected_components and "electrical_component_underconnected" not in pretty_reasons:
pretty_reasons.append("electrical_component_underconnected")
if one_pin_active_net_count > 0:
pretty_reasons.append("one_pin_active_net_present")
if decorative_component_count > GRAPH_DECORATIVE_MAX:
pretty_reasons.append("decorative_component_count_gt_12")
if int(overlay.get("word_count", 0)) > GRAPH_WORD_COUNT_MAX:
pretty_reasons.append("word_count_gt_50")
if float(overlay.get("text_mask_fraction", 0.0)) > GRAPH_TEXT_FRACTION_MAX:
pretty_reasons.append("text_mask_fraction_gt_0_18")
pretty_render_reasons = list(pretty_reasons)
if not render_alignment_ok:
pretty_render_reasons.append("render_alignment_weak")
keep_graph_sane = not graph_core_reasons
keep_graph_sane_pretty = not pretty_reasons
keep_graph_sane_pretty_render = not pretty_render_reasons
if keep_graph_sane_pretty_render:
bucket = "graph_sane_pretty_render_keep"
elif keep_graph_sane_pretty:
bucket = "graph_sane_pretty_keep"
elif keep_graph_sane:
bucket = "graph_sane_keep"
else:
bucket = "graph_reject"
metrics = {
"active_component_count": len(active_component_ids),
"graph_component_count": len(graph_component_ids),
"electrical_connected_components": electrical_connected_components,
"underconnected_component_count": len(underconnected_components),
"overlapping_active_component_group_count": len(overlapping_active_components),
"one_pin_active_net_count": one_pin_active_net_count,
"one_pin_terminal_only_net_count": one_pin_terminal_only_net_count,
"unknown_component_count": unknown_component_count,
"decorative_component_count": decorative_component_count,
"severe_underconnected": severe_underconnected,
"heavily_fragmented": heavily_fragmented,
"symbol_plate_like": symbol_plate_like,
"component_class_counts": dict(component_class_counts),
"word_count": int(overlay.get("word_count", 0)),
"text_mask_fraction": float(overlay.get("text_mask_fraction", 0.0)),
"render_mae": float(original_render.get("mae", 999.0)),
"render_phash_distance": int(original_render.get("phash_distance", 999) or 999),
}
return {
"graph_metrics_json": dumps_json(metrics),
"graph_underconnected_components_json": dumps_json(underconnected_components),
"graph_overlapping_active_components_json": dumps_json(overlapping_active_components),
"graph_reasons_core_json": dumps_json(graph_core_reasons),
"graph_reasons_pretty_json": dumps_json(pretty_reasons),
"graph_reasons_pretty_render_json": dumps_json(pretty_render_reasons),
"graph_keep_graph_sane": keep_graph_sane,
"graph_keep_graph_sane_pretty": keep_graph_sane_pretty,
"graph_keep_graph_sane_pretty_render": keep_graph_sane_pretty_render,
"graph_quality_bucket": bucket,
}
def placed_seed_boxes(source_code: str, image_size: tuple[int, int]) -> list[tuple[str, int, int, int, int]]:
bbox, page_scale, tx, ty = parse_page_transform(source_code)
page_parts = split_page_body(source_code)
if not page_parts:
return []
definitions = {
match.group("name"): (
int(match.group("x")),
int(match.group("y")),
int(match.group("w")),
int(match.group("h")),
)
for match in PROC_BBOX_RE.finditer(source_code)
}
_, body, _ = page_parts
llx, lly, urx, ury = bbox
width, height = image_size
seeds: list[tuple[str, int, int, int, int]] = []
for match in PROC_CALL_RE.finditer(body):
name = match.group("name")
if name not in PRIMARY_SEED_PROCEDURES:
continue
local_bbox = definitions.get(name) or PROC_BBOX_CATALOG.get(name)
if not local_bbox:
continue
scale = abs(float(match.group("scale")))
rotation = math.radians(float(match.group("rot")))
x = float(match.group("x"))
y = float(match.group("y"))
bx, by, bw, bh = local_bbox
corners = [
(bx, by),
(bx + bw, by),
(bx, by + bh),
(bx + bw, by + bh),
]
page_points: list[tuple[float, float]] = []
for cx, cy in corners:
sx = cx * scale
sy = cy * scale
rx = sx * math.cos(rotation) - sy * math.sin(rotation)
ry = sx * math.sin(rotation) + sy * math.cos(rotation)
page_points.append((page_scale * (tx + x + rx), page_scale * (ty + y + ry)))
xs = [point[0] for point in page_points]
ys = [point[1] for point in page_points]
left = max(0, int((min(xs) - llx) / (urx - llx) * width))
right = min(width - 1, int((max(xs) - llx) / (urx - llx) * width))
top = max(0, int((ury - max(ys)) / (ury - lly) * height))
bottom = min(height - 1, int((ury - min(ys)) / (ury - lly) * height))
seeds.append((name, left, top, right, bottom))
return seeds
def widest_low_ink_run(values: np.ndarray, max_dark: int) -> tuple[int, int] | None:
best: tuple[int, int] | None = None
run_start: int | None = None
for index, value in enumerate(values):
if int(value) <= max_dark:
if run_start is None:
run_start = index
continue
if run_start is not None:
candidate = (run_start, index - 1)
if not best or (candidate[1] - candidate[0]) > (best[1] - best[0]):
best = candidate
run_start = None
if run_start is not None:
candidate = (run_start, len(values) - 1)
if not best or (candidate[1] - candidate[0]) > (best[1] - best[0]):
best = candidate
return best
def pixel_bbox_from_mask(mask: np.ndarray) -> tuple[int, int, int, int] | None:
ys, xs = np.where(mask)
if xs.size == 0 or ys.size == 0:
return None
return int(xs.min()), int(ys.min()), int(xs.max()), int(ys.max())
def connected_components(mask: np.ndarray) -> tuple[np.ndarray, list[tuple[int, int, int, int, int, int]]]:
height, width = mask.shape
seen = np.zeros((height, width), dtype=np.uint8)
labels = np.full((height, width), -1, dtype=np.int32)
components: list[tuple[int, int, int, int, int, int]] = []
label = 0
for y in range(height):
for x in range(width):
if not mask[y, x] or seen[y, x]:
continue
stack = [(x, y)]
seen[y, x] = 1
area = 0
min_x = max_x = x
min_y = max_y = y
while stack:
cx, cy = stack.pop()
labels[cy, cx] = label
area += 1
min_x = min(min_x, cx)
max_x = max(max_x, cx)
min_y = min(min_y, cy)
max_y = max(max_y, cy)
for ny in range(max(0, cy - 1), min(height, cy + 2)):
for nx in range(max(0, cx - 1), min(width, cx + 2)):
if mask[ny, nx] and not seen[ny, nx]:
seen[ny, nx] = 1
stack.append((nx, ny))
components.append((label, area, min_x, min_y, max_x, max_y))
label += 1
return labels, components
def crop_pixels_to_eps_points(
pixel_bbox: tuple[int, int, int, int],
image_size: tuple[int, int],
eps_bbox: tuple[float, float, float, float],
) -> tuple[float, float, float, float]:
left, top, right, bottom = pixel_bbox
width, height = image_size
llx, lly, urx, ury = eps_bbox
eps_left = llx + (left / width) * (urx - llx)
eps_right = llx + ((right + 1) / width) * (urx - llx)
eps_top = ury - (top / height) * (ury - lly)
eps_bottom = ury - ((bottom + 1) / height) * (ury - lly)
return eps_left, eps_bottom, eps_right, eps_top
def crop_eps_points_to_pixels(
crop_bbox: tuple[float, float, float, float],
image_size: tuple[int, int],
eps_bbox: tuple[float, float, float, float],
) -> tuple[int, int, int, int]:
crop_llx, crop_lly, crop_urx, crop_ury = crop_bbox
llx, lly, urx, ury = eps_bbox
width, height = image_size
left = max(0, math.floor((crop_llx - llx) / (urx - llx) * width))
right = min(width, math.ceil((crop_urx - llx) / (urx - llx) * width))
top = max(0, math.floor((ury - crop_ury) / (ury - lly) * height))
bottom = min(height, math.ceil((ury - crop_lly) / (ury - lly) * height))
return left, top, right, bottom
def apply_clip_bbox(
source_code: str, crop_bbox: tuple[float, float, float, float]
) -> str:
page_parts = split_page_body(source_code)
if not page_parts:
return source_code
clip_llx, clip_lly, clip_urx, clip_ury = crop_bbox
prefix, body, suffix = page_parts
clip_ps = (
f"newpath {clip_llx:.3f} {clip_lly:.3f} moveto "
f"{clip_urx:.3f} {clip_lly:.3f} lineto "
f"{clip_urx:.3f} {clip_ury:.3f} lineto "
f"{clip_llx:.3f} {clip_ury:.3f} lineto closepath clip newpath\n"
)
rewritten = source_code[: PAGE_BODY_RE.search(source_code).start()] + prefix + clip_ps + body + suffix
bbox_line = "%%BoundingBox: {} {} {} {}".format(
math.floor(clip_llx),
math.floor(clip_lly),
math.ceil(clip_urx),
math.ceil(clip_ury),
)
rewritten = re.sub(r"^%%BoundingBox:.*$", bbox_line, rewritten, count=1, flags=re.M)
return rewritten
def render_source_code_to_png(
source_code: str,
eps_path: Path,
png_path: Path,
*,
device: str,
) -> None:
eps_path.parent.mkdir(parents=True, exist_ok=True)
eps_path.write_text(source_code)
render_eps_to_png(eps_path, png_path, device=device)
def derive_crop_bbox(
source_code: str,
analysis_png_path: Path,
) -> tuple[int, int, int, int] | None:
if not analysis_png_path.exists():
return None
with Image.open(analysis_png_path) as image:
gray = np.array(image.convert("L"))
mask = gray < 220
full_bbox = pixel_bbox_from_mask(mask)
if not full_bbox:
return None
seeds = placed_seed_boxes(source_code, (gray.shape[1], gray.shape[0]))
if not seeds:
return None
seed_left = min(seed[1] for seed in seeds)
seed_top = min(seed[2] for seed in seeds)
seed_right = max(seed[3] for seed in seeds)
seed_bottom = max(seed[4] for seed in seeds)
full_left, _, full_right, _ = full_bbox
column_sums = mask.sum(axis=0)
gap_dark_max = 1
gap_min_width = max(24, int(gray.shape[1] * 0.08))
left_gap_abs: tuple[int, int] | None = None
right_gap_abs: tuple[int, int] | None = None
if seed_left - full_left >= gap_min_width:
left_gap = widest_low_ink_run(column_sums[full_left:seed_left], gap_dark_max)
if left_gap and (left_gap[1] - left_gap[0] + 1) >= gap_min_width:
left_gap_abs = (full_left + left_gap[0], full_left + left_gap[1])
if full_right - seed_right >= gap_min_width:
right_gap = widest_low_ink_run(column_sums[seed_right + 1 : full_right + 1], gap_dark_max)
if right_gap and (right_gap[1] - right_gap[0] + 1) >= gap_min_width:
right_gap_abs = (seed_right + 1 + right_gap[0], seed_right + 1 + right_gap[1])
if not left_gap_abs and not right_gap_abs:
return None
labels, components = connected_components(mask)
component_ids: set[int] = set()
for _, left, top, right, bottom in seeds:
if right < left or bottom < top:
continue
sub = labels[top : bottom + 1, left : right + 1]
component_ids.update(int(value) for value in np.unique(sub) if value >= 0)
picked = [component for component in components if component[0] in component_ids]
if not picked:
return None
margin_x = max(8, int(gray.shape[1] * 0.02))
margin_y = max(8, int(gray.shape[0] * 0.05))
left = max(0, min(component[2] for component in picked) - margin_x)
top = max(0, min(component[3] for component in picked) - margin_y)
right = min(gray.shape[1] - 1, max(component[4] for component in picked) + margin_x)
bottom = min(gray.shape[0] - 1, max(component[5] for component in picked) + margin_y)
if left_gap_abs:
left = max(left, left_gap_abs[1] + 1)
if right_gap_abs:
right = min(right, right_gap_abs[0] - 1)
if right <= left or bottom <= top:
return None
cropped_area = (right - left + 1) * (bottom - top + 1)
full_area = gray.shape[0] * gray.shape[1]
if cropped_area >= full_area * 0.94:
return None
return left, top, right, bottom
def crop_image_to_bbox(
source_path: Path,
output_path: Path,
crop_bbox: tuple[float, float, float, float],
eps_bbox: tuple[float, float, float, float],
) -> None:
with Image.open(source_path) as image:
left, top, right, bottom = crop_eps_points_to_pixels(crop_bbox, image.size, eps_bbox)
output_path.parent.mkdir(parents=True, exist_ok=True)
image.crop((left, top, right, bottom)).save(output_path)
def prepare_figure_artifact(
book: BookConfig,
figure_stem: str,
refs: list[dict[str, Any]],
source_code: str,
temp_root: Path,
) -> dict[str, Any]:
reject_reason = reject_reason_for_figure(book, refs, source_code)
if reject_reason:
return {"keep": False, "reject_reason": reject_reason}
sanitized_code, removed_procedures = strip_forbidden_invocations(source_code)
removed_grounds = 0
if removed_procedures:
sanitized_code, removed_grounds = strip_trailing_ground_invocations(sanitized_code)
original_bbox = parse_eps_bounding_box(sanitized_code)
analysis_eps = temp_root / "analysis_eps" / book.slug / f"{figure_stem}.eps"
analysis_png = temp_root / "analysis_png" / book.slug / f"{figure_stem}.png"
analysis_eps.parent.mkdir(parents=True, exist_ok=True)
analysis_png.parent.mkdir(parents=True, exist_ok=True)
write_no_text_eps(sanitized_code, analysis_eps)
render_eps_to_png(analysis_eps, analysis_png, device="pnggray")
crop_bbox_px = None if removed_procedures else derive_crop_bbox(sanitized_code, analysis_png)
crop_bbox_eps = None
if crop_bbox_px and analysis_png.exists():
with Image.open(analysis_png) as analysis_image:
crop_bbox_eps = crop_pixels_to_eps_points(
crop_bbox_px,
analysis_image.size,
original_bbox,
)
derived_code = apply_clip_bbox(sanitized_code, crop_bbox_eps) if crop_bbox_eps else sanitized_code
extraction_mode = "whole"
if crop_bbox_eps:
extraction_mode = "cropped"
elif removed_procedures:
extraction_mode = "sanitized"
return {
"keep": True,
"source_code": derived_code,
"original_eps_bbox": original_bbox,
"crop_bbox_eps": crop_bbox_eps,
"crop_bbox_px": crop_bbox_px,
"removed_procedures": removed_procedures,
"removed_auxiliary_grounds": removed_grounds,
"extraction_mode": extraction_mode,
}
def write_no_text_eps(source_code: str, output_path: Path) -> None:
needle = "%%EndComments\n"
if needle in source_code:
patched = source_code.replace(needle, needle + NO_TEXT_PS_OVERRIDE, 1)
else:
patched = NO_TEXT_PS_OVERRIDE + source_code
output_path.write_text(patched)
def render_eps_to_png(eps_path: Path, png_path: Path, *, device: str) -> None:
png_path.parent.mkdir(parents=True, exist_ok=True)
cmd = [
"gs",
"-dSAFER",
"-dBATCH",
"-dNOPAUSE",
"-dEPSCrop",
f"-sDEVICE={device}",
f"-r{PNG_DPI}",
f"-sOutputFile={png_path}",
str(eps_path),
]
run(cmd)
if not png_path.exists():
run(cmd)
def images_equal_rgba(path_a: Path, path_b: Path) -> bool:
if not path_a.exists() or not path_b.exists():
return False
with Image.open(path_a) as a, Image.open(path_b) as b:
a_rgba = a.convert("RGBA")
b_rgba = b.convert("RGBA")
if a_rgba.size != b_rgba.size:
return False
return ImageChops.difference(a_rgba, b_rgba).getbbox() is None
def make_payload_copy(source_root: Path, payload_root: Path) -> None:
if payload_root.exists():
shutil.rmtree(payload_root)
target = payload_root / "derived" / "Source"
target.parent.mkdir(parents=True, exist_ok=True)
shutil.copytree(source_root, target)
def render_task(task: dict[str, Any]) -> dict[str, Any]:
eps_path = Path(task["eps_path"])
output_png = Path(task["output_png"])
no_text_png = Path(task["no_text_png"])
temp_no_text_eps = Path(task["temp_no_text_eps"])
temp_reference_png = Path(task["temp_reference_png"]) if task["temp_reference_png"] else None
temp_html_png = Path(task["temp_html_png"]) if task["temp_html_png"] else None
reference_png = Path(task["reference_png"]) if task["reference_png"] else None
html_png = Path(task["html_png"]) if task["html_png"] else None
pdf_text_path = Path(task["pdf_text_path"]) if task["pdf_text_path"] else None
captions = task["captions"]
source_code = task["source_code"]
word_count = int(task.get("word_count", 0))
label_count = int(task.get("label_count", 0))
crop_bbox_eps = tuple(task["crop_bbox_eps"]) if task["crop_bbox_eps"] else None
original_eps_bbox = tuple(task["original_eps_bbox"]) if task["original_eps_bbox"] else None
render_device = "pnggray"
reference_png_exact = None
reference_compare_path = reference_png
if (
reference_png
and reference_png.exists()
and crop_bbox_eps
and original_eps_bbox
and temp_reference_png
):
crop_image_to_bbox(reference_png, temp_reference_png, crop_bbox_eps, original_eps_bbox)
reference_compare_path = temp_reference_png
html_compare_path = html_png
if html_png and html_png.exists() and crop_bbox_eps and original_eps_bbox and temp_html_png:
crop_image_to_bbox(html_png, temp_html_png, crop_bbox_eps, original_eps_bbox)
html_compare_path = temp_html_png
if reference_compare_path and reference_compare_path.exists():
render_device = "pngalpha"
render_eps_to_png(eps_path, output_png, device=render_device)
reference_png_exact = images_equal_rgba(output_png, reference_compare_path)
if not reference_png_exact:
render_device = "pnggray"
render_eps_to_png(eps_path, output_png, device=render_device)
reference_png_exact = images_equal_rgba(output_png, reference_compare_path)
else:
render_eps_to_png(eps_path, output_png, device=render_device)
temp_no_text_eps.parent.mkdir(parents=True, exist_ok=True)
write_no_text_eps(source_code, temp_no_text_eps)
render_eps_to_png(temp_no_text_eps, no_text_png, device=render_device)
if not no_text_png.exists() and output_png.exists():
shutil.copy2(output_png, no_text_png)
no_text_status = "fallback_original_copy"
no_label_render = {
"status": "fallback_original_copy",
"compiler": "ghostscript",
"word_count": word_count,
"label_count": label_count,
}
else:
no_text_status = "rendered"
no_label_render = {
"status": "ok",
"compiler": "ghostscript",
"word_count": word_count,
"label_count": label_count,
}
overlay_check = overlay_metrics_from_pngs(output_png, no_text_png, word_count)
original_render_check = compare_image_paths(output_png, reference_compare_path if reference_compare_path and reference_compare_path.exists() else None)
render_check = dict(original_render_check)
html_exact = None
if html_compare_path and html_compare_path.exists():
html_exact = images_equal_rgba(output_png, html_compare_path)
pdf_caption_pages: list[int] = []
if pdf_text_path.exists() and captions:
pages = pdf_text_path.read_text(errors="ignore").split("\f")
normalized_pages = [normalize_space(page).lower() for page in pages]
for caption in captions:
normalized_caption = normalize_space(caption).lower()
if not normalized_caption:
continue
for page_number, page_text in enumerate(normalized_pages, start=1):
if normalized_caption in page_text:
pdf_caption_pages.append(page_number)
pdf_caption_pages = sorted(set(pdf_caption_pages))
output_width, output_height = image_dimensions(output_png)
return {
"output_png": str(output_png),
"no_text_png": str(no_text_png) if no_text_png.exists() else None,
"reference_png_exact": reference_png_exact,
"html_png_exact": html_exact,
"pdf_caption_pages": pdf_caption_pages,
"no_text_status": no_text_status,
"render_device": render_device,
"render_check_json": dumps_json(render_check),
"render_check_status": render_check.get("status", "not_run"),
"no_label_render_json": dumps_json(no_label_render),
"overlay_check_json": dumps_json(overlay_check),
"original_render_check_json": dumps_json(original_render_check),
"output_width": output_width,
"output_height": output_height,
"image_pixels_sha256": image_pixel_sha256(output_png),
"image_phash": compute_image_phash(output_png),
}
def main() -> None:
parser = argparse.ArgumentParser()
parser.add_argument(
"--repo-root",
type=Path,
default=Path("/workspace/SchemID"),
help="Path to the local HF dataset repo checkout.",
)
parser.add_argument(
"--workers",
type=int,
default=min(32, os.cpu_count() or 8),
help="Concurrent rendering workers.",
)
parser.add_argument(
"--upload",
action="store_true",
help="Upload derived/Source back to the HF dataset repo using hf upload-large-folder.",
)
parser.add_argument(
"--upload-workers",
type=int,
default=16,
help="hf upload-large-folder worker count.",
)
parser.add_argument(
"--liii-pdf-url",
default=DEFAULT_LIII_PDF_URL,
help="Version-matched LIII PDF URL used for verification.",
)
args = parser.parse_args()
repo_root = args.repo_root.resolve()
derived_root = repo_root / "derived" / "Source"
scripts_root = derived_root / "scripts"
work_root = derived_root / "work"
extracted_root = work_root / "inputs"
cache_root = work_root / "cache"
temp_root = work_root / "temp"
rendered_root = derived_root / "rendered"
code_root = derived_root / "circuit_generation_code"
metadata_root = derived_root / "metadata"
dataset_root = derived_root / "hf_dataset"
parquet_path = derived_root / "circuits.parquet"
payload_root = Path("/workspace/hf_upload_payload")
for path in [rendered_root, code_root, metadata_root, dataset_root, temp_root]:
if path.exists():
shutil.rmtree(path)
if parquet_path.exists():
parquet_path.unlink()
for path in [work_root, extracted_root, cache_root, temp_root, rendered_root, code_root, metadata_root]:
path.mkdir(parents=True, exist_ok=True)
ensure_inputs(repo_root, extracted_root)
pdf_text_cache_paths: dict[str, Path] = {}
pdf_sources: dict[str, dict[str, Any]] = {}
for book in BOOKS:
pdf_source = resolve_pdf_source(book, repo_root, cache_root, args.liii_pdf_url)
pdf_sources[book.slug] = pdf_source
pdf_path = Path(pdf_source["pdf_path_used"])
cache_path = cache_root / f"{book.slug}.txt"
load_pdf_text_pages(pdf_path, cache_path)
pdf_text_cache_paths[book.slug] = cache_path
records: list[dict[str, Any]] = []
render_jobs: list[dict[str, Any]] = []
pruned_records: list[dict[str, Any]] = []
structure_summary: dict[str, Any] = {"books": {}}
for book in BOOKS:
source_dir = extracted_root / book.extract_dir
pdf_source = pdf_sources[book.slug]
if book.source_kind == "sml":
figure_refs = parse_sml_references(book, source_dir)
else:
figure_refs = parse_latex_references(book, source_dir)
book_summary = {
"display_name": book.display_name,
"pdf_name": pdf_source["pdf_name_used"],
"pdf_origin": pdf_source["pdf_origin"],
"pdf_url_used": pdf_source["pdf_url_used"],
"pdf_path_used": pdf_source["pdf_path_used"],
"source_kind": book.source_kind,
"source_version": book.source_version,
"pdf_version_sync": pdf_source["pdf_version_sync"],
"referenced_figures": len(figure_refs),
"circuit_rows": 0,
"cropped_rows": 0,
"sanitized_rows": 0,
"pruned_rows": 0,
"source_notes": list(pdf_source["notes"]),
}
if not pdf_source["pdf_version_sync"]:
book_summary["source_notes"].append(
"Bundled PDF is newer than the available source tree. "
"Source is liii_2v16.latex (January 1, 2016) while the PDF metadata reports version 2.33 created on October 9, 2024."
)
for figure_stem, refs in sorted(figure_refs.items()):
eps_path = source_dir / f"{figure_stem}.eps"
if not eps_path.exists():
continue
eps_meta = parse_eps_metadata(eps_path)
if not eps_meta["is_circuit"]:
continue
prepared = prepare_figure_artifact(
book,
figure_stem,
refs,
eps_meta["code"],
temp_root,
)
if not prepared["keep"]:
book_summary["pruned_rows"] += 1
pruned_records.append(
{
"book": book.slug,
"figure_id": figure_stem,
"reason": prepared["reject_reason"],
"references": refs,
}
)
continue
book_summary["circuit_rows"] += 1
if prepared["extraction_mode"] == "cropped":
book_summary["cropped_rows"] += 1
if prepared["removed_procedures"]:
book_summary["sanitized_rows"] += 1
book_code_dir = code_root / book.slug
book_code_dir.mkdir(parents=True, exist_ok=True)
code_copy_path = book_code_dir / eps_path.name
code_copy_path.write_text(prepared["source_code"])
ir_fields = build_eps_ir(prepared["source_code"])
ir_payload = json.loads(ir_fields["circuit_ir_json"])
visible_word_count = sum(count_words(label.get("text", "")) for label in ir_payload.get("labels", []))
caption_value = first_caption(refs)
description_value = build_description(book, figure_stem, refs)
full_code_hash = sha256_text(normalize_code_for_hash(prepared["source_code"]))
body_hash = sha256_text(normalize_body_for_hash(prepared["source_code"]))
rendered_png = rendered_root / "original" / book.slug / f"{figure_stem}.png"
no_text_png = rendered_root / "no_text" / book.slug / f"{figure_stem}.png"
temp_no_text_eps = temp_root / "no_text_eps" / book.slug / f"{figure_stem}.eps"
temp_reference_png = temp_root / "reference_png" / book.slug / f"{figure_stem}.png"
temp_html_png = temp_root / "html_png" / book.slug / f"{figure_stem}.png"
captions = sorted(
{
ref["caption"]
for ref in refs
if ref.get("caption")
}
)
html_png = None
if book.html_dir:
candidate = extracted_root / "liechtml" / book.html_dir / f"{figure_stem}.png"
if candidate.exists():
html_png = candidate
reference_png = source_dir / f"{figure_stem}.png"
if not reference_png.exists():
reference_png = None
source_payload = {
"book": book.slug,
"display_name": book.display_name,
"pdf": pdf_source["pdf_name_used"],
"pdf_origin": pdf_source["pdf_origin"],
"pdf_url_used": pdf_source["pdf_url_used"],
"pdf_path_used": pdf_source["pdf_path_used"],
"bundled_pdf_name": pdf_source["bundled_pdf_name"],
"bundled_pdf_path": pdf_source["bundled_pdf_path"],
"pdf_version_sync": pdf_source["pdf_version_sync"],
"source_kind": book.source_kind,
"source_version": book.source_version,
"figure_id": figure_stem,
"eps_path": str(code_copy_path.relative_to(derived_root)),
"eps_creator": eps_meta["creator"],
"circuit_tokens": eps_meta["circuit_tokens"],
"extraction": {
"mode": prepared["extraction_mode"],
"crop_bbox_eps": prepared["crop_bbox_eps"],
"crop_bbox_px": prepared["crop_bbox_px"],
"removed_procedures": prepared["removed_procedures"],
"removed_auxiliary_grounds": prepared["removed_auxiliary_grounds"],
},
"references": refs,
"verification": {},
}
record = {
"record_id": f"{SOURCE_DATASET_NAME}:{book.slug}:{figure_stem}",
"source_dataset": SOURCE_DATASET_NAME,
"source_repo": SOURCE_REPO_ID,
"source_split": SOURCE_SPLIT,
"source_parquet": "derived/Source/circuits.parquet",
"source_row_index": -1,
"source_id": f"{book.slug}:{figure_stem}",
"source_uri": f"schemid-source://{book.slug}/{figure_stem}.eps",
"source_origin": SOURCE_ORIGIN,
"caption": caption_value or "",
"description": description_value,
"code": prepared["source_code"],
"image": str(rendered_png),
"width": 0,
"height": 0,
"full_code_hash": full_code_hash,
"tikz_body_hash": body_hash,
"caption_hash": sha256_text(caption_value or ""),
"image_pixels_sha256": None,
"image_phash": None,
"dedup_cluster_id": f"cluster:{full_code_hash}",
"structural_version": STRUCTURAL_VERSION,
"extraction_branch": EXTRACTION_BRANCH,
"Circuit Generation Code": prepared["source_code"],
"Circuit generated image": str(rendered_png),
"Circuit Generated image with no text": str(no_text_png),
"no_label": str(no_text_png),
"Source": source_payload,
"source_group": SOURCE_GROUP,
**ir_fields,
"_ir_payload": ir_payload,
"_word_count": visible_word_count,
}
records.append(record)
render_jobs.append(
{
"book": book.slug,
"figure_id": figure_stem,
"eps_path": str(code_copy_path),
"output_png": str(rendered_png),
"no_text_png": str(no_text_png),
"temp_no_text_eps": str(temp_no_text_eps),
"temp_reference_png": str(temp_reference_png),
"temp_html_png": str(temp_html_png),
"reference_png": str(reference_png) if reference_png else None,
"html_png": str(html_png) if html_png else None,
"pdf_text_path": str(pdf_text_cache_paths[book.slug]),
"captions": captions,
"source_code": prepared["source_code"],
"crop_bbox_eps": prepared["crop_bbox_eps"],
"original_eps_bbox": prepared["original_eps_bbox"],
"word_count": visible_word_count,
"label_count": ir_fields["label_count"],
}
)
structure_summary["books"][book.slug] = book_summary
with ThreadPoolExecutor(max_workers=args.workers) as executor:
future_map = {executor.submit(render_task, job): job for job in render_jobs}
render_results: dict[tuple[str, str], dict[str, Any]] = {}
for future in as_completed(future_map):
job = future_map[future]
result = future.result()
render_results[(job["book"], job["figure_id"])] = result
verification_summary: dict[str, Any] = {"books": {}}
dataset_rows: list[dict[str, Any]] = []
for source_row_index, record in enumerate(records):
source_payload = record["Source"]
key = (source_payload["book"], source_payload["figure_id"])
render_result = render_results[key]
record["source_row_index"] = source_row_index
record["width"] = int(render_result["output_width"])
record["height"] = int(render_result["output_height"])
record["image_pixels_sha256"] = render_result["image_pixels_sha256"]
record["image_phash"] = render_result["image_phash"]
record["render_check_json"] = render_result["render_check_json"]
record["render_check_status"] = render_result["render_check_status"]
record["no_label_render_json"] = render_result["no_label_render_json"]
record["overlay_check_json"] = render_result["overlay_check_json"]
record["original_render_check_json"] = render_result["original_render_check_json"]
verification = {
"reference_png_exact": render_result["reference_png_exact"],
"html_png_exact": render_result["html_png_exact"],
"pdf_caption_pages": render_result["pdf_caption_pages"],
"pdf_proxy_verified": bool(render_result["reference_png_exact"]) and source_payload["pdf_version_sync"],
"no_text_status": render_result["no_text_status"],
"render_device": render_result["render_device"],
}
if not source_payload["pdf_version_sync"]:
verification["notes"] = [
"Exact PDF/source verification is not reliable for this book because the PDF in use is not version-matched to the available source tree."
]
elif render_result["reference_png_exact"] is None:
verification["notes"] = [
"No bundled reference PNG was available for pixel-exact comparison. Caption-page hits were recorded against the matched PDF text stream."
]
elif render_result["reference_png_exact"] is False:
verification["notes"] = [
"Pixel-exact comparison against the bundled figure PNG did not match for this figure. Matching PDF caption pages were still recorded as provenance against the corresponding book PDF."
]
if render_result["html_png_exact"] is not None:
verification["notes"].append(
"Archived HTML PNG comparison was also recorded."
)
else:
verification["notes"] = [
"Exact pixel comparison was performed against the bundled figure PNG generated from the same source tree. Matching PDF caption pages were recorded as provenance against the corresponding book PDF."
]
if render_result["html_png_exact"] is not None:
verification["notes"].append(
"Archived HTML PNG comparison was also recorded."
)
extraction_mode = source_payload.get("extraction", {}).get("mode")
if extraction_mode == "cropped":
verification["notes"].append(
"Verification used the cropped circuit-only region from the reference figure."
)
elif extraction_mode == "sanitized":
verification["notes"].append(
"Circuit-only rendering removed non-circuit procedural elements before verification."
)
source_payload["verification"] = verification
original_render = json.loads(record["original_render_check_json"])
overlay = json.loads(record["overlay_check_json"])
no_label_render = json.loads(record["no_label_render_json"])
quality_bucket, keep_for_modeling, quality_reasons = classify_quality_row(
record,
original_render,
overlay,
no_label_render,
)
graph_fields = graph_metrics_for_row(record, overlay, original_render)
record["quality_bucket"] = quality_bucket
record["keep_for_modeling"] = keep_for_modeling
record["quality_reasons_json"] = dumps_json(quality_reasons)
record.update(graph_fields)
source_payload["ir_summary"] = {
"parse_status": record["parse_status"],
"component_count": record["component_count"],
"pin_count": record["pin_count"],
"net_count": record["net_count"],
"wire_count": record["wire_count"],
"label_count": record["label_count"],
"quality_bucket": quality_bucket,
"graph_quality_bucket": record["graph_quality_bucket"],
}
record.pop("_ir_payload", None)
record.pop("_word_count", None)
dataset_rows.append(
{
"record_id": record["record_id"],
"source_dataset": record["source_dataset"],
"source_repo": record["source_repo"],
"source_split": record["source_split"],
"source_parquet": record["source_parquet"],
"source_row_index": record["source_row_index"],
"source_id": record["source_id"],
"source_uri": record["source_uri"],
"source_origin": record["source_origin"],
"caption": record["caption"],
"description": record["description"],
"code": record["code"],
"image": record["image"],
"width": record["width"],
"height": record["height"],
"full_code_hash": record["full_code_hash"],
"tikz_body_hash": record["tikz_body_hash"],
"caption_hash": record["caption_hash"],
"image_pixels_sha256": record["image_pixels_sha256"],
"image_phash": record["image_phash"],
"dedup_cluster_id": record["dedup_cluster_id"],
"structural_version": record["structural_version"],
"extraction_branch": record["extraction_branch"],
"parse_status": record["parse_status"],
"circuit_ir_json": record["circuit_ir_json"],
"parse_warnings_json": record["parse_warnings_json"],
"unsupported_constructs_json": record["unsupported_constructs_json"],
"component_count": record["component_count"],
"pin_count": record["pin_count"],
"net_count": record["net_count"],
"wire_count": record["wire_count"],
"label_count": record["label_count"],
"render_check_json": record["render_check_json"],
"render_check_status": record["render_check_status"],
"no_label": record["no_label"],
"no_label_render_json": record["no_label_render_json"],
"overlay_check_json": record["overlay_check_json"],
"original_render_check_json": record["original_render_check_json"],
"quality_bucket": record["quality_bucket"],
"keep_for_modeling": record["keep_for_modeling"],
"quality_reasons_json": record["quality_reasons_json"],
"source_group": record["source_group"],
"graph_metrics_json": record["graph_metrics_json"],
"graph_underconnected_components_json": record["graph_underconnected_components_json"],
"graph_overlapping_active_components_json": record["graph_overlapping_active_components_json"],
"graph_reasons_core_json": record["graph_reasons_core_json"],
"graph_reasons_pretty_json": record["graph_reasons_pretty_json"],
"graph_reasons_pretty_render_json": record["graph_reasons_pretty_render_json"],
"graph_keep_graph_sane": record["graph_keep_graph_sane"],
"graph_keep_graph_sane_pretty": record["graph_keep_graph_sane_pretty"],
"graph_keep_graph_sane_pretty_render": record["graph_keep_graph_sane_pretty_render"],
"graph_quality_bucket": record["graph_quality_bucket"],
"Circuit Generation Code": record["Circuit Generation Code"],
"Circuit generated image": render_result["output_png"],
"Circuit Generated image with no text": render_result["no_text_png"],
"Source": json.dumps(source_payload, sort_keys=True),
}
)
verification_summary["books"].setdefault(
source_payload["book"],
{
"rows": 0,
"reference_png_exact_true": 0,
"reference_png_exact_false": 0,
"reference_png_exact_missing": 0,
"html_png_exact_true": 0,
"html_png_exact_false": 0,
"html_png_exact_missing": 0,
"pdf_proxy_verified_true": 0,
"pdf_proxy_verified_false": 0,
},
)
bucket = verification_summary["books"][source_payload["book"]]
bucket["rows"] += 1
if verification["reference_png_exact"] is True:
bucket["reference_png_exact_true"] += 1
elif verification["reference_png_exact"] is False:
bucket["reference_png_exact_false"] += 1
else:
bucket["reference_png_exact_missing"] += 1
if verification["html_png_exact"] is True:
bucket["html_png_exact_true"] += 1
elif verification["html_png_exact"] is False:
bucket["html_png_exact_false"] += 1
else:
bucket["html_png_exact_missing"] += 1
if verification["pdf_proxy_verified"]:
bucket["pdf_proxy_verified_true"] += 1
else:
bucket["pdf_proxy_verified_false"] += 1
metadata_root.mkdir(parents=True, exist_ok=True)
(metadata_root / "structure_summary.json").write_text(
json.dumps(structure_summary, indent=2, sort_keys=True) + "\n"
)
(metadata_root / "verification_summary.json").write_text(
json.dumps(verification_summary, indent=2, sort_keys=True) + "\n"
)
with (metadata_root / "rows.jsonl").open("w") as handle:
for row in dataset_rows:
handle.write(json.dumps(row, sort_keys=True) + "\n")
with (metadata_root / "pruned_figures.jsonl").open("w") as handle:
for row in pruned_records:
handle.write(json.dumps(row, sort_keys=True) + "\n")
features = Features(
{
"record_id": Value("string"),
"source_dataset": Value("string"),
"source_repo": Value("string"),
"source_split": Value("string"),
"source_parquet": Value("string"),
"source_row_index": Value("int64"),
"source_id": Value("string"),
"source_uri": Value("string"),
"source_origin": Value("string"),
"caption": Value("string"),
"description": Value("string"),
"code": Value("string"),
"image": HFImage(),
"width": Value("int32"),
"height": Value("int32"),
"full_code_hash": Value("string"),
"tikz_body_hash": Value("string"),
"caption_hash": Value("string"),
"image_pixels_sha256": Value("string"),
"image_phash": Value("string"),
"dedup_cluster_id": Value("string"),
"structural_version": Value("string"),
"extraction_branch": Value("string"),
"parse_status": Value("string"),
"circuit_ir_json": Value("string"),
"parse_warnings_json": Value("string"),
"unsupported_constructs_json": Value("string"),
"component_count": Value("int64"),
"pin_count": Value("int64"),
"net_count": Value("int64"),
"wire_count": Value("int64"),
"label_count": Value("int64"),
"render_check_json": Value("string"),
"render_check_status": Value("string"),
"no_label": HFImage(),
"no_label_render_json": Value("string"),
"overlay_check_json": Value("string"),
"original_render_check_json": Value("string"),
"quality_bucket": Value("string"),
"keep_for_modeling": Value("bool"),
"quality_reasons_json": Value("string"),
"source_group": Value("string"),
"graph_metrics_json": Value("string"),
"graph_underconnected_components_json": Value("string"),
"graph_overlapping_active_components_json": Value("string"),
"graph_reasons_core_json": Value("string"),
"graph_reasons_pretty_json": Value("string"),
"graph_reasons_pretty_render_json": Value("string"),
"graph_keep_graph_sane": Value("bool"),
"graph_keep_graph_sane_pretty": Value("bool"),
"graph_keep_graph_sane_pretty_render": Value("bool"),
"graph_quality_bucket": Value("string"),
"Circuit Generation Code": Value("string"),
"Circuit generated image": HFImage(),
"Circuit Generated image with no text": HFImage(),
"Source": Value("string"),
}
)
dataset = Dataset.from_list(dataset_rows, features=features)
if dataset_root.exists():
shutil.rmtree(dataset_root)
dataset.save_to_disk(str(dataset_root))
try:
dataset.to_parquet(str(parquet_path))
except Exception:
table = pa.Table.from_pylist(dataset_rows)
pq.write_table(table, parquet_path)
if args.upload:
make_payload_copy(derived_root, payload_root)
run(
[
"hf",
"upload-large-folder",
"lsnu/SchemID",
str(payload_root),
"--type",
"dataset",
"--num-workers",
str(args.upload_workers),
"--no-bars",
]
)
if __name__ == "__main__":
main()
"block",
"butterfly",
"crt_elec",
"displacer",