lsnu commited on
Commit
9c0afa4
·
verified ·
1 Parent(s): 062b1c7

Add files using upload-large-folder tool

Browse files
derived/Source/hf_dataset/dataset_info.json CHANGED
@@ -2,6 +2,212 @@
2
  "citation": "",
3
  "description": "",
4
  "features": {
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
5
  "Circuit Generation Code": {
6
  "dtype": "string",
7
  "_type": "Value"
 
2
  "citation": "",
3
  "description": "",
4
  "features": {
5
+ "record_id": {
6
+ "dtype": "string",
7
+ "_type": "Value"
8
+ },
9
+ "source_dataset": {
10
+ "dtype": "string",
11
+ "_type": "Value"
12
+ },
13
+ "source_repo": {
14
+ "dtype": "string",
15
+ "_type": "Value"
16
+ },
17
+ "source_split": {
18
+ "dtype": "string",
19
+ "_type": "Value"
20
+ },
21
+ "source_parquet": {
22
+ "dtype": "string",
23
+ "_type": "Value"
24
+ },
25
+ "source_row_index": {
26
+ "dtype": "int64",
27
+ "_type": "Value"
28
+ },
29
+ "source_id": {
30
+ "dtype": "string",
31
+ "_type": "Value"
32
+ },
33
+ "source_uri": {
34
+ "dtype": "string",
35
+ "_type": "Value"
36
+ },
37
+ "source_origin": {
38
+ "dtype": "string",
39
+ "_type": "Value"
40
+ },
41
+ "caption": {
42
+ "dtype": "string",
43
+ "_type": "Value"
44
+ },
45
+ "description": {
46
+ "dtype": "string",
47
+ "_type": "Value"
48
+ },
49
+ "code": {
50
+ "dtype": "string",
51
+ "_type": "Value"
52
+ },
53
+ "image": {
54
+ "_type": "Image"
55
+ },
56
+ "width": {
57
+ "dtype": "int32",
58
+ "_type": "Value"
59
+ },
60
+ "height": {
61
+ "dtype": "int32",
62
+ "_type": "Value"
63
+ },
64
+ "full_code_hash": {
65
+ "dtype": "string",
66
+ "_type": "Value"
67
+ },
68
+ "tikz_body_hash": {
69
+ "dtype": "string",
70
+ "_type": "Value"
71
+ },
72
+ "caption_hash": {
73
+ "dtype": "string",
74
+ "_type": "Value"
75
+ },
76
+ "image_pixels_sha256": {
77
+ "dtype": "string",
78
+ "_type": "Value"
79
+ },
80
+ "image_phash": {
81
+ "dtype": "string",
82
+ "_type": "Value"
83
+ },
84
+ "dedup_cluster_id": {
85
+ "dtype": "string",
86
+ "_type": "Value"
87
+ },
88
+ "structural_version": {
89
+ "dtype": "string",
90
+ "_type": "Value"
91
+ },
92
+ "extraction_branch": {
93
+ "dtype": "string",
94
+ "_type": "Value"
95
+ },
96
+ "parse_status": {
97
+ "dtype": "string",
98
+ "_type": "Value"
99
+ },
100
+ "circuit_ir_json": {
101
+ "dtype": "string",
102
+ "_type": "Value"
103
+ },
104
+ "parse_warnings_json": {
105
+ "dtype": "string",
106
+ "_type": "Value"
107
+ },
108
+ "unsupported_constructs_json": {
109
+ "dtype": "string",
110
+ "_type": "Value"
111
+ },
112
+ "component_count": {
113
+ "dtype": "int64",
114
+ "_type": "Value"
115
+ },
116
+ "pin_count": {
117
+ "dtype": "int64",
118
+ "_type": "Value"
119
+ },
120
+ "net_count": {
121
+ "dtype": "int64",
122
+ "_type": "Value"
123
+ },
124
+ "wire_count": {
125
+ "dtype": "int64",
126
+ "_type": "Value"
127
+ },
128
+ "label_count": {
129
+ "dtype": "int64",
130
+ "_type": "Value"
131
+ },
132
+ "render_check_json": {
133
+ "dtype": "string",
134
+ "_type": "Value"
135
+ },
136
+ "render_check_status": {
137
+ "dtype": "string",
138
+ "_type": "Value"
139
+ },
140
+ "no_label": {
141
+ "_type": "Image"
142
+ },
143
+ "no_label_render_json": {
144
+ "dtype": "string",
145
+ "_type": "Value"
146
+ },
147
+ "overlay_check_json": {
148
+ "dtype": "string",
149
+ "_type": "Value"
150
+ },
151
+ "original_render_check_json": {
152
+ "dtype": "string",
153
+ "_type": "Value"
154
+ },
155
+ "quality_bucket": {
156
+ "dtype": "string",
157
+ "_type": "Value"
158
+ },
159
+ "keep_for_modeling": {
160
+ "dtype": "bool",
161
+ "_type": "Value"
162
+ },
163
+ "quality_reasons_json": {
164
+ "dtype": "string",
165
+ "_type": "Value"
166
+ },
167
+ "source_group": {
168
+ "dtype": "string",
169
+ "_type": "Value"
170
+ },
171
+ "graph_metrics_json": {
172
+ "dtype": "string",
173
+ "_type": "Value"
174
+ },
175
+ "graph_underconnected_components_json": {
176
+ "dtype": "string",
177
+ "_type": "Value"
178
+ },
179
+ "graph_overlapping_active_components_json": {
180
+ "dtype": "string",
181
+ "_type": "Value"
182
+ },
183
+ "graph_reasons_core_json": {
184
+ "dtype": "string",
185
+ "_type": "Value"
186
+ },
187
+ "graph_reasons_pretty_json": {
188
+ "dtype": "string",
189
+ "_type": "Value"
190
+ },
191
+ "graph_reasons_pretty_render_json": {
192
+ "dtype": "string",
193
+ "_type": "Value"
194
+ },
195
+ "graph_keep_graph_sane": {
196
+ "dtype": "bool",
197
+ "_type": "Value"
198
+ },
199
+ "graph_keep_graph_sane_pretty": {
200
+ "dtype": "bool",
201
+ "_type": "Value"
202
+ },
203
+ "graph_keep_graph_sane_pretty_render": {
204
+ "dtype": "bool",
205
+ "_type": "Value"
206
+ },
207
+ "graph_quality_bucket": {
208
+ "dtype": "string",
209
+ "_type": "Value"
210
+ },
211
  "Circuit Generation Code": {
212
  "dtype": "string",
213
  "_type": "Value"
derived/Source/hf_dataset/state.json CHANGED
@@ -4,7 +4,7 @@
4
  "filename": "data-00000-of-00001.arrow"
5
  }
6
  ],
7
- "_fingerprint": "545a5d8fc5886e81",
8
  "_format_columns": null,
9
  "_format_kwargs": {},
10
  "_format_type": null,
 
4
  "filename": "data-00000-of-00001.arrow"
5
  }
6
  ],
7
+ "_fingerprint": "12dbf5a6aed9fa0d",
8
  "_format_columns": null,
9
  "_format_kwargs": {},
10
  "_format_type": null,
derived/Source/metadata/graph_reject_candidates.jsonl ADDED
The diff for this file is too large to render. See raw diff
 
derived/Source/metadata/graph_summary.json ADDED
@@ -0,0 +1,82 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "active_component_count_histogram": {
3
+ "0": 29,
4
+ "1": 171,
5
+ "10": 34,
6
+ "11": 27,
7
+ "12": 24,
8
+ "13": 14,
9
+ "14": 13,
10
+ "15": 9,
11
+ "16": 28,
12
+ "17": 2,
13
+ "18": 3,
14
+ "19": 7,
15
+ "2": 309,
16
+ "20": 3,
17
+ "21": 6,
18
+ "22": 3,
19
+ "23": 3,
20
+ "25": 3,
21
+ "26": 3,
22
+ "28": 5,
23
+ "3": 236,
24
+ "30": 1,
25
+ "31": 1,
26
+ "32": 5,
27
+ "36": 1,
28
+ "39": 1,
29
+ "4": 282,
30
+ "42": 1,
31
+ "44": 2,
32
+ "47": 1,
33
+ "5": 216,
34
+ "51": 1,
35
+ "6": 133,
36
+ "65": 1,
37
+ "67": 1,
38
+ "7": 81,
39
+ "8": 76,
40
+ "84": 1,
41
+ "86": 1,
42
+ "9": 38
43
+ },
44
+ "graph_quality_bucket_counts": {
45
+ "graph_reject": 1545,
46
+ "graph_sane_keep": 4,
47
+ "graph_sane_pretty_keep": 21,
48
+ "graph_sane_pretty_render_keep": 206
49
+ },
50
+ "quality_bucket_counts": {
51
+ "jank": 1530,
52
+ "well_generated": 246
53
+ },
54
+ "rows": 1776,
55
+ "top_graph_core_reasons": {
56
+ "active_component_span_overlap": 4,
57
+ "electrical_component_count_zero": 29,
58
+ "electrical_component_underconnected": 492,
59
+ "electrical_graph_components_gt_1": 975,
60
+ "one_pin_active_net_present": 1244,
61
+ "unrecognized_component_present": 985
62
+ },
63
+ "top_graph_pretty_reasons": {
64
+ "active_component_span_overlap": 4,
65
+ "electrical_component_count_zero": 29,
66
+ "electrical_component_underconnected": 492,
67
+ "electrical_graph_components_gt_1": 975,
68
+ "one_pin_active_net_present": 1244,
69
+ "unrecognized_component_present": 985,
70
+ "word_count_gt_50": 83
71
+ },
72
+ "top_graph_pretty_render_reasons": {
73
+ "active_component_span_overlap": 4,
74
+ "electrical_component_count_zero": 29,
75
+ "electrical_component_underconnected": 492,
76
+ "electrical_graph_components_gt_1": 975,
77
+ "one_pin_active_net_present": 1244,
78
+ "render_alignment_weak": 218,
79
+ "unrecognized_component_present": 985,
80
+ "word_count_gt_50": 83
81
+ }
82
+ }
derived/Source/scripts/build_circuit_dataset.py CHANGED
@@ -3,6 +3,7 @@
3
  from __future__ import annotations
4
 
5
  import argparse
 
6
  import json
7
  import math
8
  import os
@@ -13,6 +14,7 @@ import tarfile
13
  import urllib.parse
14
  import urllib.request
15
  import warnings
 
16
  from concurrent.futures import ThreadPoolExecutor, as_completed
17
  from dataclasses import dataclass
18
  from pathlib import Path
@@ -27,6 +29,22 @@ from PIL import Image, ImageChops
27
 
28
  PNG_DPI = 120
29
  DEFAULT_LIII_PDF_URL = "https://www.ibiblio.org/kuphaldt/socratic/sinst/book/liii_2v16.pdf"
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
30
  NO_TEXT_PS_OVERRIDE = (
31
  "\n"
32
  "/show { pop } bind def\n"
@@ -98,6 +116,72 @@ PROC_BBOX_CATALOG: dict[str, tuple[int, int, int, int]] = {
98
  "resistor": (-14, -64, 28, 128),
99
  "source": (-32, -64, 64, 128),
100
  }
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
101
  STRIP_INVOCATION_PROCEDURES = {"person", "person_shocked"}
102
  NON_CIRCUIT_SOURCE_PATTERNS: tuple[tuple[re.Pattern[str], str], ...] = (
103
  (
@@ -147,7 +231,7 @@ FULL_INVOCATION_LINE_RE = re.compile(
147
  r"^\s*(?P<scale>-?\d+(?:\.\d+)?)\s+(?P<rot>-?\d+(?:\.\d+)?)\s+"
148
  r"(?P<x>-?\d+(?:\.\d+)?)\s+(?P<y>-?\d+(?:\.\d+)?)\s+"
149
  r"(?P<name>[A-Za-z][A-Za-z0-9_]*)\s*$"
150
- )
151
  SML_TOKEN_RE = re.compile(
152
  r"(?P<chapter><chaptertitle>(?P<chapter_text>.*?)</chaptertitle>)"
153
  r"|(?P<section><sectiontitle>(?P<section_text>.*?)</sectiontitle>)"
@@ -160,6 +244,15 @@ LATEX_SECTION_RE = re.compile(
160
  LATEX_INCLUDE_RE = re.compile(
161
  r"\\includegraphics(?:\[[^]]*\])?\{(?P<name>[^}]+\.eps)\}"
162
  )
 
 
 
 
 
 
 
 
 
163
 
164
  warnings.filterwarnings(
165
  "ignore",
@@ -591,6 +684,1099 @@ def parse_page_transform(source_code: str) -> tuple[tuple[float, float, float, f
591
  return bbox, scale, tx, ty
592
 
593
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
594
  def placed_seed_boxes(source_code: str, image_size: tuple[int, int]) -> list[tuple[str, int, int, int, int]]:
595
  bbox, page_scale, tx, ty = parse_page_transform(source_code)
596
  page_parts = split_page_body(source_code)
@@ -978,6 +2164,8 @@ def render_task(task: dict[str, Any]) -> dict[str, Any]:
978
  pdf_text_path = Path(task["pdf_text_path"]) if task["pdf_text_path"] else None
979
  captions = task["captions"]
980
  source_code = task["source_code"]
 
 
981
  crop_bbox_eps = tuple(task["crop_bbox_eps"]) if task["crop_bbox_eps"] else None
982
  original_eps_bbox = tuple(task["original_eps_bbox"]) if task["original_eps_bbox"] else None
983
  render_device = "pnggray"
@@ -1013,6 +2201,15 @@ def render_task(task: dict[str, Any]) -> dict[str, Any]:
1013
  write_no_text_eps(source_code, temp_no_text_eps)
1014
  render_eps_to_png(temp_no_text_eps, no_text_png, device=render_device)
1015
  no_text_status = "rendered"
 
 
 
 
 
 
 
 
 
1016
 
1017
  html_exact = None
1018
  if html_compare_path and html_compare_path.exists():
@@ -1030,6 +2227,7 @@ def render_task(task: dict[str, Any]) -> dict[str, Any]:
1030
  if normalized_caption in page_text:
1031
  pdf_caption_pages.append(page_number)
1032
  pdf_caption_pages = sorted(set(pdf_caption_pages))
 
1033
 
1034
  return {
1035
  "output_png": str(output_png),
@@ -1039,6 +2237,15 @@ def render_task(task: dict[str, Any]) -> dict[str, Any]:
1039
  "pdf_caption_pages": pdf_caption_pages,
1040
  "no_text_status": no_text_status,
1041
  "render_device": render_device,
 
 
 
 
 
 
 
 
 
1042
  }
1043
 
1044
 
@@ -1181,6 +2388,13 @@ def main() -> None:
1181
  book_code_dir.mkdir(parents=True, exist_ok=True)
1182
  code_copy_path = book_code_dir / eps_path.name
1183
  code_copy_path.write_text(prepared["source_code"])
 
 
 
 
 
 
 
1184
 
1185
  rendered_png = rendered_root / "original" / book.slug / f"{figure_stem}.png"
1186
  no_text_png = rendered_root / "no_text" / book.slug / f"{figure_stem}.png"
@@ -1233,10 +2447,38 @@ def main() -> None:
1233
  }
1234
 
1235
  record = {
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1236
  "Circuit Generation Code": prepared["source_code"],
1237
  "Circuit generated image": str(rendered_png),
1238
  "Circuit Generated image with no text": str(no_text_png),
 
1239
  "Source": source_payload,
 
 
 
 
1240
  }
1241
  records.append(record)
1242
 
@@ -1257,6 +2499,8 @@ def main() -> None:
1257
  "source_code": prepared["source_code"],
1258
  "crop_bbox_eps": prepared["crop_bbox_eps"],
1259
  "original_eps_bbox": prepared["original_eps_bbox"],
 
 
1260
  }
1261
  )
1262
 
@@ -1273,10 +2517,20 @@ def main() -> None:
1273
  verification_summary: dict[str, Any] = {"books": {}}
1274
  dataset_rows: list[dict[str, Any]] = []
1275
 
1276
- for record in records:
1277
  source_payload = record["Source"]
1278
  key = (source_payload["book"], source_payload["figure_id"])
1279
  render_result = render_results[key]
 
 
 
 
 
 
 
 
 
 
1280
 
1281
  verification = {
1282
  "reference_png_exact": render_result["reference_png_exact"],
@@ -1321,9 +2575,87 @@ def main() -> None:
1321
  )
1322
 
1323
  source_payload["verification"] = verification
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1324
 
1325
  dataset_rows.append(
1326
  {
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1327
  "Circuit Generation Code": record["Circuit Generation Code"],
1328
  "Circuit generated image": render_result["output_png"],
1329
  "Circuit Generated image with no text": render_result["no_text_png"],
@@ -1380,6 +2712,58 @@ def main() -> None:
1380
 
1381
  features = Features(
1382
  {
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1383
  "Circuit Generation Code": Value("string"),
1384
  "Circuit generated image": HFImage(),
1385
  "Circuit Generated image with no text": HFImage(),
 
3
  from __future__ import annotations
4
 
5
  import argparse
6
+ import hashlib
7
  import json
8
  import math
9
  import os
 
14
  import urllib.parse
15
  import urllib.request
16
  import warnings
17
+ from collections import Counter, defaultdict
18
  from concurrent.futures import ThreadPoolExecutor, as_completed
19
  from dataclasses import dataclass
20
  from pathlib import Path
 
29
 
30
  PNG_DPI = 120
31
  DEFAULT_LIII_PDF_URL = "https://www.ibiblio.org/kuphaldt/socratic/sinst/book/liii_2v16.pdf"
32
+ STRUCTURAL_VERSION = "schemid_source_structural_v1"
33
+ EXTRACTION_BRANCH = "xcircuit_eps_ir_v1"
34
+ SOURCE_DATASET_NAME = "schemid_source_available"
35
+ SOURCE_REPO_ID = "lsnu/SchemID"
36
+ SOURCE_SPLIT = "train"
37
+ SOURCE_ORIGIN = "xcircuit_eps"
38
+ SOURCE_GROUP = "non_cosyn"
39
+ PAGE_SCOPE_ID = "page_001"
40
+ COORD_SNAP = 0.75
41
+ PHASH_SIZE = 8
42
+ PHASH_HIGHFREQ = 32
43
+ GRAPH_WORD_COUNT_MAX = 50
44
+ GRAPH_TEXT_FRACTION_MAX = 0.18
45
+ GRAPH_RENDER_MAE_MAX = 3.0
46
+ GRAPH_RENDER_PHASH_MAX = 8
47
+ GRAPH_DECORATIVE_MAX = 1
48
  NO_TEXT_PS_OVERRIDE = (
49
  "\n"
50
  "/show { pop } bind def\n"
 
116
  "resistor": (-14, -64, 28, 128),
117
  "source": (-32, -64, 64, 128),
118
  }
119
+ PROCEDURE_KIND_MAP: dict[str, tuple[str, str]] = {
120
+ "LED": ("indicator", "led"),
121
+ "acsource": ("source", "ac_source"),
122
+ "and_gate": ("logic", "logic_gate"),
123
+ "arrow": ("decorative", "arrow"),
124
+ "arrowhead": ("decorative", "arrowhead"),
125
+ "battery": ("source", "voltage_source"),
126
+ "breadboard": ("block", "breadboard"),
127
+ "capacitor": ("passive", "capacitor"),
128
+ "capacitor1": ("passive", "capacitor"),
129
+ "circle": ("io", "terminal"),
130
+ "diode": ("semiconductor", "diode"),
131
+ "dip_8": ("logic", "integrated_circuit"),
132
+ "dot": ("junction", "junction"),
133
+ "fuse_blown": ("protection", "fuse"),
134
+ "gnd": ("ground", "ground"),
135
+ "indicator": ("indicator", "indicator"),
136
+ "inductor": ("passive", "inductor"),
137
+ "invert": ("logic", "logic_gate"),
138
+ "jumper": ("switch", "jumper"),
139
+ "nand": ("logic", "logic_gate"),
140
+ "njf": ("semiconductor", "transistor"),
141
+ "no_contact": ("io", "terminal"),
142
+ "npn": ("semiconductor", "transistor"),
143
+ "opamp": ("active", "op_amp"),
144
+ "or_gate": ("logic", "logic_gate"),
145
+ "pnp": ("semiconductor", "transistor"),
146
+ "potentiometer": ("passive", "potentiometer"),
147
+ "potentiometer1": ("passive", "potentiometer"),
148
+ "real_batt": ("source", "voltage_source"),
149
+ "resistor": ("passive", "resistor"),
150
+ "resistor4": ("passive", "resistor"),
151
+ "source": ("source", "voltage_source"),
152
+ "transistor2": ("semiconductor", "transistor"),
153
+ }
154
+ ELECTRICAL_FAMILIES = {
155
+ "active",
156
+ "passive",
157
+ "source",
158
+ "semiconductor",
159
+ "switch",
160
+ "indicator",
161
+ "protection",
162
+ "ground",
163
+ "io",
164
+ "junction",
165
+ "logic",
166
+ }
167
+ MIN_CONNECTED_PINS = {
168
+ "ac_source": 2,
169
+ "capacitor": 2,
170
+ "diode": 2,
171
+ "fuse": 2,
172
+ "ground": 1,
173
+ "integrated_circuit": 2,
174
+ "inductor": 2,
175
+ "junction": 1,
176
+ "led": 2,
177
+ "logic_gate": 2,
178
+ "op_amp": 3,
179
+ "potentiometer": 3,
180
+ "resistor": 2,
181
+ "terminal": 1,
182
+ "transistor": 3,
183
+ "voltage_source": 2,
184
+ }
185
  STRIP_INVOCATION_PROCEDURES = {"person", "person_shocked"}
186
  NON_CIRCUIT_SOURCE_PATTERNS: tuple[tuple[re.Pattern[str], str], ...] = (
187
  (
 
231
  r"^\s*(?P<scale>-?\d+(?:\.\d+)?)\s+(?P<rot>-?\d+(?:\.\d+)?)\s+"
232
  r"(?P<x>-?\d+(?:\.\d+)?)\s+(?P<y>-?\d+(?:\.\d+)?)\s+"
233
  r"(?P<name>[A-Za-z][A-Za-z0-9_]*)\s*$"
234
+ , re.M)
235
  SML_TOKEN_RE = re.compile(
236
  r"(?P<chapter><chaptertitle>(?P<chapter_text>.*?)</chaptertitle>)"
237
  r"|(?P<section><sectiontitle>(?P<section_text>.*?)</sectiontitle>)"
 
244
  LATEX_INCLUDE_RE = re.compile(
245
  r"\\includegraphics(?:\[[^]]*\])?\{(?P<name>[^}]+\.eps)\}"
246
  )
247
+ LABEL_COMMAND_RE = re.compile(
248
+ r"(?P<raw>(?P<content>(?:\((?:\\.|[^\\)])*\)|\{[^{}]*\}|\s+)+?)\s+"
249
+ r"(?P<count>\d+)\s+(?P<just>-?\d+)\s+(?P<rot>-?\d+(?:\.\d+)?)\s+"
250
+ r"(?:(?P<scale>-?\d+(?:\.\d+)?)\s+)?"
251
+ r"(?P<x>-?\d+(?:\.\d+)?)\s+(?P<y>-?\d+(?:\.\d+)?)\s+"
252
+ r"(?P<kind>label|pinlabel|pinglobal|infolabel)\b)",
253
+ re.S,
254
+ )
255
+ PS_STRING_RE = re.compile(r"\((?:\\.|[^\\)])*\)")
256
 
257
  warnings.filterwarnings(
258
  "ignore",
 
684
  return bbox, scale, tx, ty
685
 
686
 
687
+ def dumps_json(value: Any) -> str:
688
+ return json.dumps(value, ensure_ascii=True, sort_keys=True)
689
+
690
+
691
+ def sha256_text(text: str) -> str:
692
+ return hashlib.sha256(text.encode("utf-8")).hexdigest()
693
+
694
+
695
+ def sha256_bytes(data: bytes) -> str:
696
+ return hashlib.sha256(data).hexdigest()
697
+
698
+
699
+ def normalize_code_for_hash(source_code: str) -> str:
700
+ return "\n".join(line.rstrip() for line in source_code.strip().splitlines())
701
+
702
+
703
+ def normalize_body_for_hash(source_code: str) -> str:
704
+ page_parts = split_page_body(source_code)
705
+ if not page_parts:
706
+ return normalize_code_for_hash(source_code)
707
+ return normalize_code_for_hash(page_parts[1])
708
+
709
+
710
+ def image_pixel_sha256(path: Path) -> str:
711
+ with Image.open(path) as image:
712
+ rgba = image.convert("RGBA")
713
+ return sha256_bytes(rgba.tobytes())
714
+
715
+
716
+ def image_dimensions(path: Path) -> tuple[int, int]:
717
+ with Image.open(path) as image:
718
+ return image.size
719
+
720
+
721
+ def _dct_matrix(size: int) -> np.ndarray:
722
+ matrix = np.zeros((size, size), dtype=np.float64)
723
+ factor = math.pi / (2.0 * size)
724
+ scale0 = math.sqrt(1.0 / size)
725
+ scale = math.sqrt(2.0 / size)
726
+ for k in range(size):
727
+ alpha = scale0 if k == 0 else scale
728
+ for n in range(size):
729
+ matrix[k, n] = alpha * math.cos((2 * n + 1) * k * factor)
730
+ return matrix
731
+
732
+
733
+ _PHASH_DCT = _dct_matrix(PHASH_HIGHFREQ)
734
+
735
+
736
+ def compute_image_phash(path: Path) -> str:
737
+ with Image.open(path) as image:
738
+ gray = image.convert("L").resize((PHASH_HIGHFREQ, PHASH_HIGHFREQ))
739
+ pixels = np.asarray(gray, dtype=np.float64)
740
+ transformed = _PHASH_DCT @ pixels @ _PHASH_DCT.T
741
+ low_freq = transformed[:PHASH_SIZE, :PHASH_SIZE]
742
+ flat = low_freq.flatten()
743
+ median = float(np.median(flat[1:])) if flat.size > 1 else float(flat[0])
744
+ bits = "".join("1" if value > median else "0" for value in flat)
745
+ return f"{int(bits, 2):0{len(bits) // 4}x}"
746
+
747
+
748
+ def phash_distance(left: str | None, right: str | None) -> int | None:
749
+ if not left or not right:
750
+ return None
751
+ return (int(left, 16) ^ int(right, 16)).bit_count()
752
+
753
+
754
+ def compare_image_paths(rendered_path: Path, reference_path: Path | None) -> dict[str, Any]:
755
+ if not reference_path or not reference_path.exists():
756
+ return {"status": "not_run"}
757
+
758
+ with Image.open(rendered_path) as rendered_img, Image.open(reference_path) as reference_img:
759
+ rendered = rendered_img.convert("RGBA")
760
+ reference = reference_img.convert("RGBA")
761
+ stored_size = list(reference.size)
762
+ rendered_size = list(rendered.size)
763
+ if rendered.size != reference.size:
764
+ reference = reference.resize(rendered.size)
765
+ diff = ImageChops.difference(rendered, reference).convert("L")
766
+ histogram = diff.histogram()
767
+ total_pixels = max(1, rendered.width * rendered.height)
768
+ diff_sum = int(sum(index * value for index, value in enumerate(histogram)))
769
+ mae = round(diff_sum / float(total_pixels), 6)
770
+ match = diff.getbbox() is None
771
+ rendered_hash = compute_image_phash(rendered_path)
772
+ reference_hash = compute_image_phash(reference_path)
773
+ return {
774
+ "status": "ok",
775
+ "match": match,
776
+ "mae": mae,
777
+ "phash_distance": phash_distance(rendered_hash, reference_hash),
778
+ "rendered_size": rendered_size,
779
+ "stored_size": stored_size,
780
+ }
781
+
782
+
783
+ def decode_ps_string(raw: str) -> str:
784
+ if raw.startswith("(") and raw.endswith(")"):
785
+ raw = raw[1:-1]
786
+ out: list[str] = []
787
+ index = 0
788
+ while index < len(raw):
789
+ char = raw[index]
790
+ if char != "\\":
791
+ out.append(char)
792
+ index += 1
793
+ continue
794
+ index += 1
795
+ if index >= len(raw):
796
+ break
797
+ escaped = raw[index]
798
+ if escaped in "()\\":
799
+ out.append(escaped)
800
+ index += 1
801
+ continue
802
+ if escaped == "n":
803
+ out.append("\n")
804
+ index += 1
805
+ continue
806
+ if escaped == "r":
807
+ out.append("\r")
808
+ index += 1
809
+ continue
810
+ if escaped == "t":
811
+ out.append("\t")
812
+ index += 1
813
+ continue
814
+ if escaped.isdigit():
815
+ octal = escaped
816
+ for _ in range(2):
817
+ if index + 1 < len(raw) and raw[index + 1].isdigit():
818
+ index += 1
819
+ octal += raw[index]
820
+ else:
821
+ break
822
+ out.append(chr(int(octal, 8)))
823
+ index += 1
824
+ continue
825
+ out.append(escaped)
826
+ index += 1
827
+ return normalize_space("".join(out).replace("\n", " "))
828
+
829
+
830
+ def extract_label_strings(content: str) -> list[str]:
831
+ return [decode_ps_string(match.group(0)) for match in PS_STRING_RE.finditer(content)]
832
+
833
+
834
+ def parse_visible_labels(body: str) -> list[dict[str, Any]]:
835
+ labels: list[dict[str, Any]] = []
836
+ for match in LABEL_COMMAND_RE.finditer(body):
837
+ if match.group("kind") not in {"label", "pinlabel", "pinglobal"}:
838
+ continue
839
+ parts = [value for value in extract_label_strings(match.group("content")) if value]
840
+ labels.append(
841
+ {
842
+ "raw": normalize_space(match.group("raw")),
843
+ "kind": match.group("kind"),
844
+ "text": normalize_space(" ".join(parts)),
845
+ "x": float(match.group("x")),
846
+ "y": float(match.group("y")),
847
+ "scale": float(match.group("scale")) if match.group("scale") else 1.0,
848
+ "rotation": float(match.group("rot")),
849
+ }
850
+ )
851
+ return labels
852
+
853
+
854
+ def parse_symbol_procedures(source_code: str) -> dict[str, str]:
855
+ lines = source_code.splitlines()
856
+ procedures: dict[str, str] = {}
857
+ index = 0
858
+ while index < len(lines):
859
+ line = lines[index]
860
+ if line.startswith("/") and line.rstrip().endswith("{"):
861
+ name = line[1:].split("{", 1)[0].strip()
862
+ depth = line.count("{") - line.count("}")
863
+ body_lines: list[str] = []
864
+ index += 1
865
+ while index < len(lines):
866
+ current = lines[index]
867
+ depth += current.count("{") - current.count("}")
868
+ if depth <= 0 and current.strip().endswith("def"):
869
+ break
870
+ body_lines.append(current)
871
+ index += 1
872
+ procedures[name] = "\n".join(body_lines)
873
+ index += 1
874
+ return procedures
875
+
876
+
877
+ def parse_symbol_pin_catalog(source_code: str) -> dict[str, list[dict[str, Any]]]:
878
+ pin_catalog: dict[str, list[dict[str, Any]]] = {}
879
+ for proc_name, body in parse_symbol_procedures(source_code).items():
880
+ entries: list[dict[str, Any]] = []
881
+ for match in LABEL_COMMAND_RE.finditer(body):
882
+ kind = match.group("kind")
883
+ if kind not in {"pinlabel", "pinglobal"}:
884
+ continue
885
+ strings = extract_label_strings(match.group("content"))
886
+ label_text = normalize_space(" ".join(strings))
887
+ entries.append(
888
+ {
889
+ "label": label_text,
890
+ "kind": "terminal" if kind == "pinlabel" else "global",
891
+ "x": float(match.group("x")),
892
+ "y": float(match.group("y")),
893
+ "raw": normalize_space(match.group("raw")),
894
+ }
895
+ )
896
+ if entries:
897
+ pin_catalog[proc_name] = entries
898
+ return pin_catalog
899
+
900
+
901
+ def component_family_kind(name: str) -> tuple[str, str]:
902
+ if name in PROCEDURE_KIND_MAP:
903
+ return PROCEDURE_KIND_MAP[name]
904
+ lower = name.lower()
905
+ if lower in {"clip", "label", "marks"} or lower.startswith("die_") or lower.startswith("truth_"):
906
+ return "decorative", lower
907
+ if "arrow" in lower:
908
+ return "decorative", lower
909
+ if "opamp" in lower or (lower.endswith("amp") and "lamp" not in lower):
910
+ return "active", "op_amp"
911
+ if name.endswith("_gate") or "gate" in lower or lower in {"nor", "buffer"} or "flipflop" in lower or lower.startswith("dip_"):
912
+ return "logic", "logic_gate"
913
+ if "resistor" in lower or lower == "strain_gauge":
914
+ return "passive", "resistor"
915
+ if "capacitor" in lower or "polarized" in lower:
916
+ return "passive", "capacitor"
917
+ if "inductor" in lower or "coil" in lower:
918
+ return "passive", "inductor"
919
+ if "transformer" in lower or lower == "core":
920
+ return "passive", "transformer"
921
+ if "battery" in lower or lower in {"vsource", "cell", "vdd", "vss", "vcc", "vee"}:
922
+ return "source", "voltage_source"
923
+ if "isource" in lower or "current" in lower:
924
+ return "source", "current_source"
925
+ if "switch" in lower or "toggle" in lower or "pushbutton" in lower or "contact" in lower:
926
+ return "switch", "switch"
927
+ if "diode" in lower or "mosfet" in lower or "jfet" in lower or lower in {"scr", "diode"} or "fet" in lower:
928
+ return "semiconductor", "transistor" if "fet" in lower or lower in {"scr"} else "diode"
929
+ if "lamp" in lower or "meter" in lower or "motor" in lower or "detector" in lower:
930
+ return "indicator", "indicator"
931
+ if "connector" in lower or "terminal" in lower or lower in {"stud", "tap", "powerpole"}:
932
+ return "io", "terminal"
933
+ if lower in {"fuse", "thermal_overload"}:
934
+ return "protection", "fuse"
935
+ if "relay" in lower:
936
+ return "switch", "relay"
937
+ return "unknown", name.lower()
938
+
939
+
940
+ def classify_component(component: dict[str, Any]) -> str:
941
+ family = component.get("family", "unknown")
942
+ kind = component.get("kind", "unknown")
943
+ if family in {"ground", "io", "junction"}:
944
+ return "terminal"
945
+ if family in {"active", "passive", "source", "semiconductor", "switch", "indicator", "protection", "logic"}:
946
+ return "electrical"
947
+ if family == "block":
948
+ return "decorative"
949
+ if family == "unknown":
950
+ return "unknown_bad"
951
+ return "other_bad"
952
+
953
+
954
+ def min_connected_pins(component: dict[str, Any]) -> int:
955
+ family = component.get("family", "unknown")
956
+ kind = component.get("kind", "unknown")
957
+ if kind in MIN_CONNECTED_PINS:
958
+ return MIN_CONNECTED_PINS[kind]
959
+ if family in {"active", "passive", "source", "semiconductor", "switch", "indicator", "protection", "logic"}:
960
+ return 2
961
+ return 1
962
+
963
+
964
+ def transform_component_point(
965
+ x: float,
966
+ y: float,
967
+ *,
968
+ scale: float,
969
+ rotation_deg: float,
970
+ origin_x: float,
971
+ origin_y: float,
972
+ page_scale: float,
973
+ page_tx: float,
974
+ page_ty: float,
975
+ ) -> tuple[float, float]:
976
+ effective_scale = abs(scale)
977
+ radians = math.radians(rotation_deg)
978
+ scaled_x = x * effective_scale
979
+ scaled_y = y * effective_scale
980
+ rotated_x = scaled_x * math.cos(radians) - scaled_y * math.sin(radians)
981
+ rotated_y = scaled_x * math.sin(radians) + scaled_y * math.cos(radians)
982
+ global_x = page_scale * (page_tx + origin_x + rotated_x)
983
+ global_y = page_scale * (page_ty + origin_y + rotated_y)
984
+ return global_x, global_y
985
+
986
+
987
+ def point_to_ref(x: float, y: float) -> str:
988
+ return f"coord:{PAGE_SCOPE_ID}:{x:.3f}:{y:.3f}"
989
+
990
+
991
+ def point_payload(x: float, y: float) -> dict[str, float]:
992
+ return {"x": round(x, 3), "y": round(y, 3)}
993
+
994
+
995
+ def bbox_from_points(points: list[tuple[float, float]]) -> tuple[float, float, float, float]:
996
+ xs = [point[0] for point in points]
997
+ ys = [point[1] for point in points]
998
+ return min(xs), min(ys), max(xs), max(ys)
999
+
1000
+
1001
+ def bbox_intersects(
1002
+ outer: tuple[float, float, float, float],
1003
+ inner: tuple[float, float, float, float],
1004
+ *,
1005
+ margin: float = 0.0,
1006
+ ) -> bool:
1007
+ left, bottom, right, top = outer
1008
+ in_left, in_bottom, in_right, in_top = inner
1009
+ return not (
1010
+ in_right < left - margin
1011
+ or in_left > right + margin
1012
+ or in_top < bottom - margin
1013
+ or in_bottom > top + margin
1014
+ )
1015
+
1016
+
1017
+ def point_inside_bbox(
1018
+ point: tuple[float, float],
1019
+ bbox: tuple[float, float, float, float],
1020
+ *,
1021
+ margin: float = 0.0,
1022
+ ) -> bool:
1023
+ x, y = point
1024
+ left, bottom, right, top = bbox
1025
+ return left - margin <= x <= right + margin and bottom - margin <= y <= top + margin
1026
+
1027
+
1028
+ def snap_key(point: tuple[float, float]) -> tuple[int, int]:
1029
+ return (round(point[0] / COORD_SNAP), round(point[1] / COORD_SNAP))
1030
+
1031
+
1032
+ def _projection_fraction(
1033
+ point: tuple[float, float],
1034
+ start: tuple[float, float],
1035
+ end: tuple[float, float],
1036
+ ) -> float:
1037
+ dx = end[0] - start[0]
1038
+ dy = end[1] - start[1]
1039
+ denom = dx * dx + dy * dy
1040
+ if denom <= 1e-9:
1041
+ return 0.0
1042
+ return ((point[0] - start[0]) * dx + (point[1] - start[1]) * dy) / denom
1043
+
1044
+
1045
+ def point_on_segment(
1046
+ point: tuple[float, float],
1047
+ start: tuple[float, float],
1048
+ end: tuple[float, float],
1049
+ *,
1050
+ tolerance: float = COORD_SNAP,
1051
+ ) -> bool:
1052
+ if start == end:
1053
+ return math.dist(point, start) <= tolerance
1054
+ t = _projection_fraction(point, start, end)
1055
+ if t < -1e-6 or t > 1.0 + 1e-6:
1056
+ return False
1057
+ projected = (start[0] + t * (end[0] - start[0]), start[1] + t * (end[1] - start[1]))
1058
+ return math.dist(projected, point) <= tolerance
1059
+
1060
+
1061
+ def segment_intersection(
1062
+ start_a: tuple[float, float],
1063
+ end_a: tuple[float, float],
1064
+ start_b: tuple[float, float],
1065
+ end_b: tuple[float, float],
1066
+ *,
1067
+ tolerance: float = COORD_SNAP,
1068
+ ) -> tuple[float, float] | None:
1069
+ ax1, ay1 = start_a
1070
+ ax2, ay2 = end_a
1071
+ bx1, by1 = start_b
1072
+ bx2, by2 = end_b
1073
+ denom = (ax1 - ax2) * (by1 - by2) - (ay1 - ay2) * (bx1 - bx2)
1074
+ if abs(denom) <= 1e-9:
1075
+ 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)]
1076
+ if shared:
1077
+ return min(shared)
1078
+ return None
1079
+ px = (
1080
+ (ax1 * ay2 - ay1 * ax2) * (bx1 - bx2)
1081
+ - (ax1 - ax2) * (bx1 * by2 - by1 * bx2)
1082
+ ) / denom
1083
+ py = (
1084
+ (ax1 * ay2 - ay1 * ax2) * (by1 - by2)
1085
+ - (ay1 - ay2) * (bx1 * by2 - by1 * bx2)
1086
+ ) / denom
1087
+ point = (px, py)
1088
+ if point_on_segment(point, start_a, end_a, tolerance=tolerance) and point_on_segment(point, start_b, end_b, tolerance=tolerance):
1089
+ return point
1090
+ return None
1091
+
1092
+
1093
+ def sort_points_on_segment(
1094
+ points: set[tuple[float, float]],
1095
+ start: tuple[float, float],
1096
+ end: tuple[float, float],
1097
+ ) -> list[tuple[float, float]]:
1098
+ return sorted(points, key=lambda point: _projection_fraction(point, start, end))
1099
+
1100
+
1101
+ def count_words(text: str) -> int:
1102
+ return len(re.findall(r"[A-Za-z0-9_]+", text))
1103
+
1104
+
1105
+ def first_caption(refs: list[dict[str, Any]]) -> str | None:
1106
+ for ref in refs:
1107
+ caption = normalize_space(ref.get("caption") or "")
1108
+ if caption:
1109
+ return caption
1110
+ return None
1111
+
1112
+
1113
+ def build_description(book: BookConfig, figure_stem: str, refs: list[dict[str, Any]]) -> str:
1114
+ parts = [book.display_name, f"Figure {figure_stem}"]
1115
+ if refs:
1116
+ ref = refs[0]
1117
+ for key in ("chapter", "section", "subsection"):
1118
+ value = normalize_space(ref.get(key) or "")
1119
+ if value:
1120
+ parts.append(value)
1121
+ caption = first_caption(refs)
1122
+ if caption:
1123
+ parts.append(caption)
1124
+ return " | ".join(parts)
1125
+
1126
+
1127
+ def synthesize_component_spans(components: list[dict[str, Any]], pins: list[dict[str, Any]]) -> list[dict[str, Any]]:
1128
+ pins_by_component: dict[str, list[dict[str, Any]]] = defaultdict(list)
1129
+ for pin in pins:
1130
+ pins_by_component[pin["component_id"]].append(pin)
1131
+
1132
+ spans: list[dict[str, Any]] = []
1133
+ span_index = 1
1134
+ for component in components:
1135
+ component_pins = pins_by_component.get(component["id"], [])
1136
+ if len(component_pins) != 2:
1137
+ continue
1138
+ ordered = sorted(component_pins, key=lambda item: item["id"])
1139
+ spans.append(
1140
+ {
1141
+ "id": f"wire_cmp_{span_index:04d}",
1142
+ "kind": "component_span",
1143
+ "conductive": False,
1144
+ "draw_options": [component["kind"]],
1145
+ "points": [
1146
+ {
1147
+ "kind": "coord",
1148
+ "raw": ordered[0]["point_ref"],
1149
+ "ref": ordered[0]["point_ref"],
1150
+ **ordered[0]["point"],
1151
+ },
1152
+ {
1153
+ "kind": "coord",
1154
+ "raw": ordered[1]["point_ref"],
1155
+ "ref": ordered[1]["point_ref"],
1156
+ **ordered[1]["point"],
1157
+ },
1158
+ ],
1159
+ "point_refs": [ordered[0]["point_ref"], ordered[1]["point_ref"]],
1160
+ "raw": component["raw"],
1161
+ "scope_id": PAGE_SCOPE_ID,
1162
+ "component_id": component["id"],
1163
+ }
1164
+ )
1165
+ span_index += 1
1166
+ return spans
1167
+
1168
+
1169
+ def build_eps_ir(source_code: str) -> dict[str, Any]:
1170
+ page_parts = split_page_body(source_code)
1171
+ if not page_parts:
1172
+ return {
1173
+ "parse_status": "failed",
1174
+ "circuit_ir_json": dumps_json({}),
1175
+ "parse_warnings_json": dumps_json(["missing_page_body"]),
1176
+ "unsupported_constructs_json": dumps_json([]),
1177
+ "component_count": 0,
1178
+ "pin_count": 0,
1179
+ "net_count": 0,
1180
+ "wire_count": 0,
1181
+ "label_count": 0,
1182
+ }
1183
+
1184
+ bbox, page_scale, page_tx, page_ty = parse_page_transform(source_code)
1185
+ _, body, _ = page_parts
1186
+ proc_pin_catalog = parse_symbol_pin_catalog(source_code)
1187
+ proc_bbox_catalog = {
1188
+ match.group("name"): (
1189
+ int(match.group("x")),
1190
+ int(match.group("y")),
1191
+ int(match.group("w")),
1192
+ int(match.group("h")),
1193
+ )
1194
+ for match in PROC_BBOX_RE.finditer(source_code)
1195
+ }
1196
+
1197
+ components: list[dict[str, Any]] = []
1198
+ pins: list[dict[str, Any]] = []
1199
+ transforms: list[dict[str, Any]] = [
1200
+ {
1201
+ "scope_id": PAGE_SCOPE_ID,
1202
+ "parent_scope_id": None,
1203
+ "raw": f"bbox={bbox}",
1204
+ "options": {
1205
+ "page_scale": round(page_scale, 6),
1206
+ "translate_x": round(page_tx, 3),
1207
+ "translate_y": round(page_ty, 3),
1208
+ "bounding_box": [round(value, 3) for value in bbox],
1209
+ },
1210
+ }
1211
+ ]
1212
+ warnings_list: list[str] = []
1213
+ unsupported_constructs: list[str] = []
1214
+
1215
+ pin_index = 1
1216
+ component_index = 1
1217
+ for match in FULL_INVOCATION_LINE_RE.finditer(body):
1218
+ proc_name = match.group("name")
1219
+ family, kind = component_family_kind(proc_name)
1220
+ origin_x = float(match.group("x"))
1221
+ origin_y = float(match.group("y"))
1222
+ rotation = float(match.group("rot"))
1223
+ scale = float(match.group("scale"))
1224
+
1225
+ local_bbox = proc_bbox_catalog.get(proc_name) or PROC_BBOX_CATALOG.get(proc_name)
1226
+ placed_bbox = None
1227
+ if local_bbox:
1228
+ bx, by, bw, bh = local_bbox
1229
+ corners = [
1230
+ transform_component_point(
1231
+ corner_x,
1232
+ corner_y,
1233
+ scale=scale,
1234
+ rotation_deg=rotation,
1235
+ origin_x=origin_x,
1236
+ origin_y=origin_y,
1237
+ page_scale=page_scale,
1238
+ page_tx=page_tx,
1239
+ page_ty=page_ty,
1240
+ )
1241
+ for corner_x, corner_y in (
1242
+ (bx, by),
1243
+ (bx + bw, by),
1244
+ (bx, by + bh),
1245
+ (bx + bw, by + bh),
1246
+ )
1247
+ ]
1248
+ placed_bbox = bbox_from_points(corners)
1249
+ if not bbox_intersects(bbox, placed_bbox, margin=COORD_SNAP):
1250
+ continue
1251
+
1252
+ global_origin = transform_component_point(
1253
+ 0.0,
1254
+ 0.0,
1255
+ scale=scale,
1256
+ rotation_deg=rotation,
1257
+ origin_x=origin_x,
1258
+ origin_y=origin_y,
1259
+ page_scale=page_scale,
1260
+ page_tx=page_tx,
1261
+ page_ty=page_ty,
1262
+ )
1263
+ if not point_inside_bbox(global_origin, bbox, margin=COORD_SNAP) and not placed_bbox:
1264
+ continue
1265
+
1266
+ component_id = f"cmp_{component_index:04d}"
1267
+ component_index += 1
1268
+ component_payload = {
1269
+ "id": component_id,
1270
+ "family": family,
1271
+ "kind": kind,
1272
+ "raw_kind": proc_name,
1273
+ "raw": normalize_space(match.group(0)),
1274
+ "scope_id": PAGE_SCOPE_ID,
1275
+ "point": point_payload(*global_origin),
1276
+ "point_ref": point_to_ref(*global_origin),
1277
+ "option_tokens": [proc_name],
1278
+ "options_raw": proc_name,
1279
+ "transform_id": f"xfm_{component_id}",
1280
+ }
1281
+ if placed_bbox:
1282
+ component_payload["bbox"] = [round(value, 3) for value in placed_bbox]
1283
+ components.append(component_payload)
1284
+ transforms.append(
1285
+ {
1286
+ "scope_id": component_payload["transform_id"],
1287
+ "parent_scope_id": PAGE_SCOPE_ID,
1288
+ "raw": normalize_space(match.group(0)),
1289
+ "options": {
1290
+ "procedure": proc_name,
1291
+ "scale": scale,
1292
+ "rotation": rotation,
1293
+ "origin_x": origin_x,
1294
+ "origin_y": origin_y,
1295
+ "bbox": component_payload.get("bbox"),
1296
+ },
1297
+ }
1298
+ )
1299
+
1300
+ local_pins = proc_pin_catalog.get(proc_name, [])
1301
+ if not local_pins and family in {"passive", "source", "indicator", "protection"} and local_bbox:
1302
+ bx, by, bw, bh = local_bbox
1303
+ if abs(bh) >= abs(bw):
1304
+ local_pins = [
1305
+ {"label": "start", "kind": "terminal", "x": 0.0, "y": by + bh, "raw": "inferred"},
1306
+ {"label": "end", "kind": "terminal", "x": 0.0, "y": by, "raw": "inferred"},
1307
+ ]
1308
+ else:
1309
+ local_pins = [
1310
+ {"label": "start", "kind": "terminal", "x": bx, "y": 0.0, "raw": "inferred"},
1311
+ {"label": "end", "kind": "terminal", "x": bx + bw, "y": 0.0, "raw": "inferred"},
1312
+ ]
1313
+ if not local_pins and family in {"junction", "io", "ground"}:
1314
+ local_pins = [
1315
+ {"label": kind, "kind": "terminal", "x": 0.0, "y": 0.0, "raw": "inferred"}
1316
+ ]
1317
+
1318
+ if not local_pins and family != "decorative":
1319
+ warnings_list.append(f"missing_pins:{proc_name}:{component_id}")
1320
+
1321
+ for pin_position, pin_info in enumerate(local_pins, start=1):
1322
+ global_point = transform_component_point(
1323
+ float(pin_info["x"]),
1324
+ float(pin_info["y"]),
1325
+ scale=scale,
1326
+ rotation_deg=rotation,
1327
+ origin_x=origin_x,
1328
+ origin_y=origin_y,
1329
+ page_scale=page_scale,
1330
+ page_tx=page_tx,
1331
+ page_ty=page_ty,
1332
+ )
1333
+ if not point_inside_bbox(global_point, bbox, margin=COORD_SNAP):
1334
+ continue
1335
+ name = pin_info["label"] or f"pin_{pin_position}"
1336
+ pin_id = f"{component_id}.pin_{pin_index:04d}"
1337
+ pin_index += 1
1338
+ pins.append(
1339
+ {
1340
+ "id": pin_id,
1341
+ "component_id": component_id,
1342
+ "name": name,
1343
+ "kind": pin_info.get("kind", "terminal"),
1344
+ "point": point_payload(*global_point),
1345
+ "point_ref": point_to_ref(*global_point),
1346
+ "raw": pin_info.get("raw"),
1347
+ }
1348
+ )
1349
+
1350
+ labels: list[dict[str, Any]] = []
1351
+ label_index = 1
1352
+ for label_info in parse_visible_labels(body):
1353
+ point = (
1354
+ page_scale * (page_tx + label_info["x"]),
1355
+ page_scale * (page_ty + label_info["y"]),
1356
+ )
1357
+ if not point_inside_bbox(point, bbox, margin=COORD_SNAP):
1358
+ continue
1359
+ labels.append(
1360
+ {
1361
+ "id": f"lbl_{label_index:04d}",
1362
+ "scope_id": PAGE_SCOPE_ID,
1363
+ "raw": label_info["raw"],
1364
+ "text": label_info["text"],
1365
+ "point": point_payload(*point),
1366
+ "point_ref": point_to_ref(*point),
1367
+ "kind": label_info["kind"],
1368
+ }
1369
+ )
1370
+ label_index += 1
1371
+
1372
+ wire_polylines: list[dict[str, Any]] = []
1373
+ wire_index = 1
1374
+ conductive_wire_ids: set[str] = set()
1375
+ for line in body.splitlines():
1376
+ stripped = line.strip()
1377
+ if not stripped.endswith("polygon"):
1378
+ continue
1379
+ tokens = stripped.split()
1380
+ if len(tokens) < 8:
1381
+ unsupported_constructs.append(f"polygon:{stripped}")
1382
+ continue
1383
+ try:
1384
+ style = int(float(tokens[0]))
1385
+ line_width = float(tokens[1])
1386
+ point_count = int(tokens[-2])
1387
+ coords = [float(value) for value in tokens[2:-2]]
1388
+ except ValueError:
1389
+ unsupported_constructs.append(f"polygon:{stripped}")
1390
+ continue
1391
+ if len(coords) != point_count * 2:
1392
+ unsupported_constructs.append(f"polygon_coord_mismatch:{stripped}")
1393
+ continue
1394
+ points = [
1395
+ (
1396
+ page_scale * (page_tx + coords[index]),
1397
+ page_scale * (page_ty + coords[index + 1]),
1398
+ )
1399
+ for index in range(0, len(coords), 2)
1400
+ ]
1401
+ poly_bbox = bbox_from_points(points)
1402
+ if not bbox_intersects(bbox, poly_bbox, margin=COORD_SNAP):
1403
+ continue
1404
+ conductive = bool(style & 1)
1405
+ wire_id = f"wire_{wire_index:04d}"
1406
+ wire_index += 1
1407
+ if conductive:
1408
+ conductive_wire_ids.add(wire_id)
1409
+ wire_polylines.append(
1410
+ {
1411
+ "id": wire_id,
1412
+ "kind": "wire" if conductive else "graphic_polyline",
1413
+ "conductive": conductive,
1414
+ "draw_options": [f"style:{style}", f"width:{line_width:g}"],
1415
+ "points": [
1416
+ {
1417
+ "kind": "coord",
1418
+ "raw": f"({coords[index]:g},{coords[index + 1]:g})",
1419
+ "ref": point_to_ref(*point),
1420
+ **point_payload(*point),
1421
+ }
1422
+ for index, point in zip(range(0, len(coords), 2), points)
1423
+ ],
1424
+ "point_refs": [point_to_ref(*point) for point in points],
1425
+ "raw": stripped,
1426
+ "scope_id": PAGE_SCOPE_ID,
1427
+ }
1428
+ )
1429
+
1430
+ wire_polylines.extend(synthesize_component_spans(components, pins))
1431
+
1432
+ node_points: dict[tuple[int, int], tuple[float, float]] = {}
1433
+ node_labels: dict[tuple[int, int], str] = {}
1434
+ node_sources: dict[str, set[str]] = defaultdict(set)
1435
+ graph_adjacency: dict[str, set[str]] = defaultdict(set)
1436
+
1437
+ def register_point(point: tuple[float, float]) -> str:
1438
+ key = snap_key(point)
1439
+ if key not in node_points:
1440
+ node_points[key] = (round(point[0], 3), round(point[1], 3))
1441
+ node_labels[key] = point_to_ref(*node_points[key])
1442
+ return node_labels[key]
1443
+
1444
+ segments: list[dict[str, Any]] = []
1445
+ for wire in wire_polylines:
1446
+ if not wire.get("conductive"):
1447
+ continue
1448
+ points = [(float(point["x"]), float(point["y"])) for point in wire["points"]]
1449
+ for start, end in zip(points, points[1:]):
1450
+ segments.append({"wire_id": wire["id"], "start": start, "end": end, "split_points": {start, end}})
1451
+
1452
+ for segment in segments:
1453
+ for pin in pins:
1454
+ point = (float(pin["point"]["x"]), float(pin["point"]["y"]))
1455
+ if point_on_segment(point, segment["start"], segment["end"]):
1456
+ segment["split_points"].add(point)
1457
+
1458
+ for index, left in enumerate(segments):
1459
+ for right in segments[index + 1 :]:
1460
+ intersection = segment_intersection(left["start"], left["end"], right["start"], right["end"])
1461
+ if intersection is None:
1462
+ continue
1463
+ left["split_points"].add(intersection)
1464
+ right["split_points"].add(intersection)
1465
+
1466
+ for segment in segments:
1467
+ ordered = sort_points_on_segment(segment["split_points"], segment["start"], segment["end"])
1468
+ if len(ordered) < 2:
1469
+ continue
1470
+ for start, end in zip(ordered, ordered[1:]):
1471
+ left_ref = register_point(start)
1472
+ right_ref = register_point(end)
1473
+ graph_adjacency[left_ref].add(right_ref)
1474
+ graph_adjacency[right_ref].add(left_ref)
1475
+ node_sources[left_ref].add(segment["wire_id"])
1476
+ node_sources[right_ref].add(segment["wire_id"])
1477
+
1478
+ pin_by_ref: dict[str, list[str]] = defaultdict(list)
1479
+ for pin in pins:
1480
+ point = (float(pin["point"]["x"]), float(pin["point"]["y"]))
1481
+ attached_ref = register_point(point)
1482
+ for existing_ref in list(graph_adjacency):
1483
+ existing_key = next(key for key, value in node_labels.items() if value == existing_ref)
1484
+ existing_point = node_points[existing_key]
1485
+ if math.dist(existing_point, point) <= COORD_SNAP:
1486
+ attached_ref = existing_ref
1487
+ break
1488
+ pin["point"] = point_payload(*next(node_points[key] for key, value in node_labels.items() if value == attached_ref))
1489
+ pin["point_ref"] = attached_ref
1490
+ pin_by_ref[attached_ref].append(pin["id"])
1491
+
1492
+ nets: list[dict[str, Any]] = []
1493
+ seen_nodes: set[str] = set()
1494
+ for node_ref in sorted(set(graph_adjacency) | set(pin_by_ref)):
1495
+ if node_ref in seen_nodes:
1496
+ continue
1497
+ stack = [node_ref]
1498
+ component_nodes: set[str] = set()
1499
+ while stack:
1500
+ current = stack.pop()
1501
+ if current in seen_nodes:
1502
+ continue
1503
+ seen_nodes.add(current)
1504
+ component_nodes.add(current)
1505
+ for neighbor in graph_adjacency.get(current, ()):
1506
+ if neighbor not in seen_nodes:
1507
+ stack.append(neighbor)
1508
+ net_pins = sorted({pin_id for ref in component_nodes for pin_id in pin_by_ref.get(ref, [])})
1509
+ net_wires = sorted({wire_id for ref in component_nodes for wire_id in node_sources.get(ref, set())})
1510
+ if not net_pins and not net_wires:
1511
+ continue
1512
+ nets.append(
1513
+ {
1514
+ "id": f"net_{len(nets) + 1:04d}",
1515
+ "pins": net_pins,
1516
+ "point_refs": sorted(component_nodes),
1517
+ "wire_ids": net_wires,
1518
+ }
1519
+ )
1520
+
1521
+ ir = {
1522
+ "components": components,
1523
+ "pins": pins,
1524
+ "nets": nets,
1525
+ "wire_polylines": wire_polylines,
1526
+ "transforms": transforms,
1527
+ "labels": labels,
1528
+ }
1529
+ parse_status = "partial" if warnings_list or unsupported_constructs else "ok"
1530
+ return {
1531
+ "parse_status": parse_status,
1532
+ "circuit_ir_json": dumps_json(ir),
1533
+ "parse_warnings_json": dumps_json(sorted(set(warnings_list))),
1534
+ "unsupported_constructs_json": dumps_json(sorted(set(unsupported_constructs))),
1535
+ "component_count": len(components),
1536
+ "pin_count": len(pins),
1537
+ "net_count": len(nets),
1538
+ "wire_count": len(wire_polylines),
1539
+ "label_count": len(labels),
1540
+ }
1541
+
1542
+
1543
+ def overlay_metrics_from_pngs(original_path: Path, no_text_path: Path, word_count: int) -> dict[str, Any]:
1544
+ with Image.open(original_path) as original_img, Image.open(no_text_path) as no_text_img:
1545
+ original = original_img.convert("RGB")
1546
+ no_text = no_text_img.convert("RGB")
1547
+ if original.size != no_text.size:
1548
+ no_text = no_text.resize(original.size)
1549
+ diff = ImageChops.difference(original, no_text).convert("L")
1550
+ histogram = diff.histogram()
1551
+ nonzero = int(sum(histogram[1:]))
1552
+ diff_sum = int(sum(index * value for index, value in enumerate(histogram)))
1553
+ total_pixels = max(1, original.width * original.height)
1554
+ return {
1555
+ "status": "ok",
1556
+ "width": original.width,
1557
+ "height": original.height,
1558
+ "outside_nonzero_pixels": 0,
1559
+ "outside_sum": 0,
1560
+ "outside_mean": 0.0,
1561
+ "inside_nonzero_pixels": nonzero,
1562
+ "inside_sum": diff_sum,
1563
+ "inside_mean": round(diff_sum / float(total_pixels), 6),
1564
+ "text_mask_pixels": nonzero,
1565
+ "text_mask_fraction": round(nonzero / float(total_pixels), 6),
1566
+ "word_count": word_count,
1567
+ "pass": True,
1568
+ "compiler": "ghostscript",
1569
+ }
1570
+
1571
+
1572
+ def classify_quality_row(
1573
+ row: dict[str, Any],
1574
+ original_render: dict[str, Any],
1575
+ overlay: dict[str, Any],
1576
+ no_label_render: dict[str, Any],
1577
+ ) -> tuple[str, bool, list[str]]:
1578
+ reasons: list[str] = []
1579
+ parse_warnings = json.loads(row.get("parse_warnings_json") or "[]")
1580
+ unsupported_constructs = json.loads(row.get("unsupported_constructs_json") or "[]")
1581
+
1582
+ if row.get("component_count", 0) <= 0:
1583
+ reasons.append("component_count_zero")
1584
+ if row.get("wire_count", 0) <= 0:
1585
+ reasons.append("wire_count_zero")
1586
+ if row.get("net_count", 0) <= 0:
1587
+ reasons.append("net_count_zero")
1588
+ if row.get("parse_status") == "failed":
1589
+ reasons.append("parse_failed")
1590
+ if no_label_render.get("status") != "ok":
1591
+ reasons.append(f"no_label_{no_label_render.get('status', 'error')}")
1592
+ if overlay.get("status") != "ok":
1593
+ reasons.append(f"overlay_{overlay.get('status', 'error')}")
1594
+ elif not overlay.get("pass", False):
1595
+ reasons.append("overlay_outside_text_changed")
1596
+ if original_render.get("status") != "ok":
1597
+ reasons.append(f"stored_compare_{original_render.get('status', 'error')}")
1598
+ elif not original_render.get("match", False):
1599
+ reasons.append("stored_compare_mismatch")
1600
+ if parse_warnings:
1601
+ reasons.append("parse_warnings_present")
1602
+ if unsupported_constructs:
1603
+ reasons.append("unsupported_constructs_present")
1604
+ keep = not reasons
1605
+ return ("well_generated" if keep else "jank", keep, reasons)
1606
+
1607
+
1608
+ def graph_metrics_for_row(row: dict[str, Any], overlay: dict[str, Any], original_render: dict[str, Any]) -> dict[str, Any]:
1609
+ ir = json.loads(row.get("circuit_ir_json") or "{}")
1610
+ components = ir.get("components", [])
1611
+ pins = ir.get("pins", [])
1612
+ nets = ir.get("nets", [])
1613
+ pin_to_component = {pin["id"]: pin["component_id"] for pin in pins}
1614
+ component_by_id = {component["id"]: component for component in components}
1615
+ component_classes = {component["id"]: classify_component(component) for component in components}
1616
+ component_class_counts = Counter(component_classes.values())
1617
+
1618
+ connected_pin_counts: Counter[str] = Counter()
1619
+ electrical_edges: set[tuple[str, str]] = set()
1620
+ one_pin_active_net_count = 0
1621
+ one_pin_terminal_only_net_count = 0
1622
+
1623
+ for net in nets:
1624
+ active_components: list[str] = []
1625
+ terminal_components: list[str] = []
1626
+ for pin_id in net.get("pins", []):
1627
+ component_id = pin_to_component.get(pin_id)
1628
+ if not component_id:
1629
+ continue
1630
+ connected_pin_counts[component_id] += 1
1631
+ classification = component_classes.get(component_id)
1632
+ if classification == "electrical":
1633
+ active_components.append(component_id)
1634
+ elif classification == "terminal":
1635
+ terminal_components.append(component_id)
1636
+ active_components = sorted(set(active_components))
1637
+ terminal_components = sorted(set(terminal_components))
1638
+ if len(active_components) == 1 and not terminal_components:
1639
+ one_pin_active_net_count += 1
1640
+ if not active_components and len(terminal_components) == 1:
1641
+ one_pin_terminal_only_net_count += 1
1642
+ for index, left in enumerate(active_components):
1643
+ for right in active_components[index + 1 :]:
1644
+ electrical_edges.add(tuple(sorted((left, right))))
1645
+ for right in terminal_components:
1646
+ electrical_edges.add(tuple(sorted((left, right))))
1647
+
1648
+ active_component_ids = sorted(component_id for component_id, value in component_classes.items() if value == "electrical")
1649
+ graph_component_ids = sorted(component_id for component_id, value in component_classes.items() if value in {"electrical", "terminal"})
1650
+ adjacency = {component_id: set() for component_id in graph_component_ids}
1651
+ for left, right in electrical_edges:
1652
+ adjacency.setdefault(left, set()).add(right)
1653
+ adjacency.setdefault(right, set()).add(left)
1654
+
1655
+ electrical_connected_components = 0
1656
+ seen: set[str] = set()
1657
+ for component_id in active_component_ids:
1658
+ if component_id in seen:
1659
+ continue
1660
+ electrical_connected_components += 1
1661
+ stack = [component_id]
1662
+ seen.add(component_id)
1663
+ while stack:
1664
+ current = stack.pop()
1665
+ for neighbor in adjacency.get(current, ()):
1666
+ if neighbor not in seen:
1667
+ seen.add(neighbor)
1668
+ stack.append(neighbor)
1669
+
1670
+ underconnected_components: list[dict[str, Any]] = []
1671
+ for component_id in active_component_ids:
1672
+ component = component_by_id[component_id]
1673
+ connected_pins = int(connected_pin_counts.get(component_id, 0))
1674
+ required_pins = min_connected_pins(component)
1675
+ if connected_pins < required_pins:
1676
+ underconnected_components.append(
1677
+ {
1678
+ "component_id": component_id,
1679
+ "family": component.get("family", "unknown"),
1680
+ "kind": component.get("kind", "unknown"),
1681
+ "connected_pins": connected_pins,
1682
+ "required_pins": required_pins,
1683
+ }
1684
+ )
1685
+
1686
+ overlapping_active_components: list[dict[str, Any]] = []
1687
+ span_map: dict[tuple[str, ...], list[dict[str, Any]]] = {}
1688
+ for component_id in active_component_ids:
1689
+ point_refs = tuple(sorted(set(pin.get("point_ref") for pin in pins if pin["component_id"] == component_id)))
1690
+ if len(point_refs) < 2:
1691
+ continue
1692
+ component = component_by_id[component_id]
1693
+ span_map.setdefault(point_refs, []).append(
1694
+ {
1695
+ "component_id": component_id,
1696
+ "family": component.get("family", "unknown"),
1697
+ "kind": component.get("kind", "unknown"),
1698
+ }
1699
+ )
1700
+ for point_refs, components_for_span in sorted(span_map.items()):
1701
+ if len(components_for_span) < 2:
1702
+ continue
1703
+ overlapping_active_components.append(
1704
+ {"point_refs": list(point_refs), "components": components_for_span}
1705
+ )
1706
+
1707
+ render_alignment_ok = (
1708
+ float(original_render.get("mae", 999.0)) <= GRAPH_RENDER_MAE_MAX
1709
+ or int(original_render.get("phash_distance", 999)) <= GRAPH_RENDER_PHASH_MAX
1710
+ )
1711
+
1712
+ graph_core_reasons: list[str] = []
1713
+ if row.get("parse_status") == "failed":
1714
+ graph_core_reasons.append("parse_not_ok")
1715
+ if len(active_component_ids) == 0:
1716
+ graph_core_reasons.append("electrical_component_count_zero")
1717
+ if electrical_connected_components > 1:
1718
+ graph_core_reasons.append("electrical_graph_components_gt_1")
1719
+ if underconnected_components:
1720
+ graph_core_reasons.append("electrical_component_underconnected")
1721
+ if one_pin_active_net_count > 0:
1722
+ graph_core_reasons.append("one_pin_active_net_present")
1723
+ if int(component_class_counts.get("unknown_bad", 0) + component_class_counts.get("other_bad", 0)) > 0:
1724
+ graph_core_reasons.append("unrecognized_component_present")
1725
+ if int(component_class_counts.get("decorative", 0)) > GRAPH_DECORATIVE_MAX:
1726
+ graph_core_reasons.append("decorative_component_count_gt_1")
1727
+ if overlapping_active_components:
1728
+ graph_core_reasons.append("active_component_span_overlap")
1729
+
1730
+ pretty_reasons = list(graph_core_reasons)
1731
+ if int(overlay.get("word_count", 0)) > GRAPH_WORD_COUNT_MAX:
1732
+ pretty_reasons.append("word_count_gt_50")
1733
+ if float(overlay.get("text_mask_fraction", 0.0)) > GRAPH_TEXT_FRACTION_MAX:
1734
+ pretty_reasons.append("text_mask_fraction_gt_0_18")
1735
+
1736
+ pretty_render_reasons = list(pretty_reasons)
1737
+ if not render_alignment_ok:
1738
+ pretty_render_reasons.append("render_alignment_weak")
1739
+
1740
+ keep_graph_sane = not graph_core_reasons
1741
+ keep_graph_sane_pretty = not pretty_reasons
1742
+ keep_graph_sane_pretty_render = not pretty_render_reasons
1743
+ if keep_graph_sane_pretty_render:
1744
+ bucket = "graph_sane_pretty_render_keep"
1745
+ elif keep_graph_sane_pretty:
1746
+ bucket = "graph_sane_pretty_keep"
1747
+ elif keep_graph_sane:
1748
+ bucket = "graph_sane_keep"
1749
+ else:
1750
+ bucket = "graph_reject"
1751
+
1752
+ metrics = {
1753
+ "active_component_count": len(active_component_ids),
1754
+ "graph_component_count": len(graph_component_ids),
1755
+ "electrical_connected_components": electrical_connected_components,
1756
+ "underconnected_component_count": len(underconnected_components),
1757
+ "overlapping_active_component_group_count": len(overlapping_active_components),
1758
+ "one_pin_active_net_count": one_pin_active_net_count,
1759
+ "one_pin_terminal_only_net_count": one_pin_terminal_only_net_count,
1760
+ "component_class_counts": dict(component_class_counts),
1761
+ "word_count": int(overlay.get("word_count", 0)),
1762
+ "text_mask_fraction": float(overlay.get("text_mask_fraction", 0.0)),
1763
+ "render_mae": float(original_render.get("mae", 999.0)),
1764
+ "render_phash_distance": int(original_render.get("phash_distance", 999) or 999),
1765
+ }
1766
+ return {
1767
+ "graph_metrics_json": dumps_json(metrics),
1768
+ "graph_underconnected_components_json": dumps_json(underconnected_components),
1769
+ "graph_overlapping_active_components_json": dumps_json(overlapping_active_components),
1770
+ "graph_reasons_core_json": dumps_json(graph_core_reasons),
1771
+ "graph_reasons_pretty_json": dumps_json(pretty_reasons),
1772
+ "graph_reasons_pretty_render_json": dumps_json(pretty_render_reasons),
1773
+ "graph_keep_graph_sane": keep_graph_sane,
1774
+ "graph_keep_graph_sane_pretty": keep_graph_sane_pretty,
1775
+ "graph_keep_graph_sane_pretty_render": keep_graph_sane_pretty_render,
1776
+ "graph_quality_bucket": bucket,
1777
+ }
1778
+
1779
+
1780
  def placed_seed_boxes(source_code: str, image_size: tuple[int, int]) -> list[tuple[str, int, int, int, int]]:
1781
  bbox, page_scale, tx, ty = parse_page_transform(source_code)
1782
  page_parts = split_page_body(source_code)
 
2164
  pdf_text_path = Path(task["pdf_text_path"]) if task["pdf_text_path"] else None
2165
  captions = task["captions"]
2166
  source_code = task["source_code"]
2167
+ word_count = int(task.get("word_count", 0))
2168
+ label_count = int(task.get("label_count", 0))
2169
  crop_bbox_eps = tuple(task["crop_bbox_eps"]) if task["crop_bbox_eps"] else None
2170
  original_eps_bbox = tuple(task["original_eps_bbox"]) if task["original_eps_bbox"] else None
2171
  render_device = "pnggray"
 
2201
  write_no_text_eps(source_code, temp_no_text_eps)
2202
  render_eps_to_png(temp_no_text_eps, no_text_png, device=render_device)
2203
  no_text_status = "rendered"
2204
+ no_label_render = {
2205
+ "status": "ok",
2206
+ "compiler": "ghostscript",
2207
+ "word_count": word_count,
2208
+ "label_count": label_count,
2209
+ }
2210
+ overlay_check = overlay_metrics_from_pngs(output_png, no_text_png, word_count)
2211
+ original_render_check = compare_image_paths(output_png, reference_compare_path if reference_compare_path and reference_compare_path.exists() else None)
2212
+ render_check = dict(original_render_check)
2213
 
2214
  html_exact = None
2215
  if html_compare_path and html_compare_path.exists():
 
2227
  if normalized_caption in page_text:
2228
  pdf_caption_pages.append(page_number)
2229
  pdf_caption_pages = sorted(set(pdf_caption_pages))
2230
+ output_width, output_height = image_dimensions(output_png)
2231
 
2232
  return {
2233
  "output_png": str(output_png),
 
2237
  "pdf_caption_pages": pdf_caption_pages,
2238
  "no_text_status": no_text_status,
2239
  "render_device": render_device,
2240
+ "render_check_json": dumps_json(render_check),
2241
+ "render_check_status": render_check.get("status", "not_run"),
2242
+ "no_label_render_json": dumps_json(no_label_render),
2243
+ "overlay_check_json": dumps_json(overlay_check),
2244
+ "original_render_check_json": dumps_json(original_render_check),
2245
+ "output_width": output_width,
2246
+ "output_height": output_height,
2247
+ "image_pixels_sha256": image_pixel_sha256(output_png),
2248
+ "image_phash": compute_image_phash(output_png),
2249
  }
2250
 
2251
 
 
2388
  book_code_dir.mkdir(parents=True, exist_ok=True)
2389
  code_copy_path = book_code_dir / eps_path.name
2390
  code_copy_path.write_text(prepared["source_code"])
2391
+ ir_fields = build_eps_ir(prepared["source_code"])
2392
+ ir_payload = json.loads(ir_fields["circuit_ir_json"])
2393
+ visible_word_count = sum(count_words(label.get("text", "")) for label in ir_payload.get("labels", []))
2394
+ caption_value = first_caption(refs)
2395
+ description_value = build_description(book, figure_stem, refs)
2396
+ full_code_hash = sha256_text(normalize_code_for_hash(prepared["source_code"]))
2397
+ body_hash = sha256_text(normalize_body_for_hash(prepared["source_code"]))
2398
 
2399
  rendered_png = rendered_root / "original" / book.slug / f"{figure_stem}.png"
2400
  no_text_png = rendered_root / "no_text" / book.slug / f"{figure_stem}.png"
 
2447
  }
2448
 
2449
  record = {
2450
+ "record_id": f"{SOURCE_DATASET_NAME}:{book.slug}:{figure_stem}",
2451
+ "source_dataset": SOURCE_DATASET_NAME,
2452
+ "source_repo": SOURCE_REPO_ID,
2453
+ "source_split": SOURCE_SPLIT,
2454
+ "source_parquet": "derived/Source/circuits.parquet",
2455
+ "source_row_index": -1,
2456
+ "source_id": f"{book.slug}:{figure_stem}",
2457
+ "source_uri": f"schemid-source://{book.slug}/{figure_stem}.eps",
2458
+ "source_origin": SOURCE_ORIGIN,
2459
+ "caption": caption_value or "",
2460
+ "description": description_value,
2461
+ "code": prepared["source_code"],
2462
+ "image": str(rendered_png),
2463
+ "width": 0,
2464
+ "height": 0,
2465
+ "full_code_hash": full_code_hash,
2466
+ "tikz_body_hash": body_hash,
2467
+ "caption_hash": sha256_text(caption_value or ""),
2468
+ "image_pixels_sha256": None,
2469
+ "image_phash": None,
2470
+ "dedup_cluster_id": f"cluster:{full_code_hash}",
2471
+ "structural_version": STRUCTURAL_VERSION,
2472
+ "extraction_branch": EXTRACTION_BRANCH,
2473
  "Circuit Generation Code": prepared["source_code"],
2474
  "Circuit generated image": str(rendered_png),
2475
  "Circuit Generated image with no text": str(no_text_png),
2476
+ "no_label": str(no_text_png),
2477
  "Source": source_payload,
2478
+ "source_group": SOURCE_GROUP,
2479
+ **ir_fields,
2480
+ "_ir_payload": ir_payload,
2481
+ "_word_count": visible_word_count,
2482
  }
2483
  records.append(record)
2484
 
 
2499
  "source_code": prepared["source_code"],
2500
  "crop_bbox_eps": prepared["crop_bbox_eps"],
2501
  "original_eps_bbox": prepared["original_eps_bbox"],
2502
+ "word_count": visible_word_count,
2503
+ "label_count": ir_fields["label_count"],
2504
  }
2505
  )
2506
 
 
2517
  verification_summary: dict[str, Any] = {"books": {}}
2518
  dataset_rows: list[dict[str, Any]] = []
2519
 
2520
+ for source_row_index, record in enumerate(records):
2521
  source_payload = record["Source"]
2522
  key = (source_payload["book"], source_payload["figure_id"])
2523
  render_result = render_results[key]
2524
+ record["source_row_index"] = source_row_index
2525
+ record["width"] = int(render_result["output_width"])
2526
+ record["height"] = int(render_result["output_height"])
2527
+ record["image_pixels_sha256"] = render_result["image_pixels_sha256"]
2528
+ record["image_phash"] = render_result["image_phash"]
2529
+ record["render_check_json"] = render_result["render_check_json"]
2530
+ record["render_check_status"] = render_result["render_check_status"]
2531
+ record["no_label_render_json"] = render_result["no_label_render_json"]
2532
+ record["overlay_check_json"] = render_result["overlay_check_json"]
2533
+ record["original_render_check_json"] = render_result["original_render_check_json"]
2534
 
2535
  verification = {
2536
  "reference_png_exact": render_result["reference_png_exact"],
 
2575
  )
2576
 
2577
  source_payload["verification"] = verification
2578
+ original_render = json.loads(record["original_render_check_json"])
2579
+ overlay = json.loads(record["overlay_check_json"])
2580
+ no_label_render = json.loads(record["no_label_render_json"])
2581
+ quality_bucket, keep_for_modeling, quality_reasons = classify_quality_row(
2582
+ record,
2583
+ original_render,
2584
+ overlay,
2585
+ no_label_render,
2586
+ )
2587
+ graph_fields = graph_metrics_for_row(record, overlay, original_render)
2588
+ record["quality_bucket"] = quality_bucket
2589
+ record["keep_for_modeling"] = keep_for_modeling
2590
+ record["quality_reasons_json"] = dumps_json(quality_reasons)
2591
+ record.update(graph_fields)
2592
+ source_payload["ir_summary"] = {
2593
+ "parse_status": record["parse_status"],
2594
+ "component_count": record["component_count"],
2595
+ "pin_count": record["pin_count"],
2596
+ "net_count": record["net_count"],
2597
+ "wire_count": record["wire_count"],
2598
+ "label_count": record["label_count"],
2599
+ "quality_bucket": quality_bucket,
2600
+ "graph_quality_bucket": record["graph_quality_bucket"],
2601
+ }
2602
+ record.pop("_ir_payload", None)
2603
+ record.pop("_word_count", None)
2604
 
2605
  dataset_rows.append(
2606
  {
2607
+ "record_id": record["record_id"],
2608
+ "source_dataset": record["source_dataset"],
2609
+ "source_repo": record["source_repo"],
2610
+ "source_split": record["source_split"],
2611
+ "source_parquet": record["source_parquet"],
2612
+ "source_row_index": record["source_row_index"],
2613
+ "source_id": record["source_id"],
2614
+ "source_uri": record["source_uri"],
2615
+ "source_origin": record["source_origin"],
2616
+ "caption": record["caption"],
2617
+ "description": record["description"],
2618
+ "code": record["code"],
2619
+ "image": record["image"],
2620
+ "width": record["width"],
2621
+ "height": record["height"],
2622
+ "full_code_hash": record["full_code_hash"],
2623
+ "tikz_body_hash": record["tikz_body_hash"],
2624
+ "caption_hash": record["caption_hash"],
2625
+ "image_pixels_sha256": record["image_pixels_sha256"],
2626
+ "image_phash": record["image_phash"],
2627
+ "dedup_cluster_id": record["dedup_cluster_id"],
2628
+ "structural_version": record["structural_version"],
2629
+ "extraction_branch": record["extraction_branch"],
2630
+ "parse_status": record["parse_status"],
2631
+ "circuit_ir_json": record["circuit_ir_json"],
2632
+ "parse_warnings_json": record["parse_warnings_json"],
2633
+ "unsupported_constructs_json": record["unsupported_constructs_json"],
2634
+ "component_count": record["component_count"],
2635
+ "pin_count": record["pin_count"],
2636
+ "net_count": record["net_count"],
2637
+ "wire_count": record["wire_count"],
2638
+ "label_count": record["label_count"],
2639
+ "render_check_json": record["render_check_json"],
2640
+ "render_check_status": record["render_check_status"],
2641
+ "no_label": record["no_label"],
2642
+ "no_label_render_json": record["no_label_render_json"],
2643
+ "overlay_check_json": record["overlay_check_json"],
2644
+ "original_render_check_json": record["original_render_check_json"],
2645
+ "quality_bucket": record["quality_bucket"],
2646
+ "keep_for_modeling": record["keep_for_modeling"],
2647
+ "quality_reasons_json": record["quality_reasons_json"],
2648
+ "source_group": record["source_group"],
2649
+ "graph_metrics_json": record["graph_metrics_json"],
2650
+ "graph_underconnected_components_json": record["graph_underconnected_components_json"],
2651
+ "graph_overlapping_active_components_json": record["graph_overlapping_active_components_json"],
2652
+ "graph_reasons_core_json": record["graph_reasons_core_json"],
2653
+ "graph_reasons_pretty_json": record["graph_reasons_pretty_json"],
2654
+ "graph_reasons_pretty_render_json": record["graph_reasons_pretty_render_json"],
2655
+ "graph_keep_graph_sane": record["graph_keep_graph_sane"],
2656
+ "graph_keep_graph_sane_pretty": record["graph_keep_graph_sane_pretty"],
2657
+ "graph_keep_graph_sane_pretty_render": record["graph_keep_graph_sane_pretty_render"],
2658
+ "graph_quality_bucket": record["graph_quality_bucket"],
2659
  "Circuit Generation Code": record["Circuit Generation Code"],
2660
  "Circuit generated image": render_result["output_png"],
2661
  "Circuit Generated image with no text": render_result["no_text_png"],
 
2712
 
2713
  features = Features(
2714
  {
2715
+ "record_id": Value("string"),
2716
+ "source_dataset": Value("string"),
2717
+ "source_repo": Value("string"),
2718
+ "source_split": Value("string"),
2719
+ "source_parquet": Value("string"),
2720
+ "source_row_index": Value("int64"),
2721
+ "source_id": Value("string"),
2722
+ "source_uri": Value("string"),
2723
+ "source_origin": Value("string"),
2724
+ "caption": Value("string"),
2725
+ "description": Value("string"),
2726
+ "code": Value("string"),
2727
+ "image": HFImage(),
2728
+ "width": Value("int32"),
2729
+ "height": Value("int32"),
2730
+ "full_code_hash": Value("string"),
2731
+ "tikz_body_hash": Value("string"),
2732
+ "caption_hash": Value("string"),
2733
+ "image_pixels_sha256": Value("string"),
2734
+ "image_phash": Value("string"),
2735
+ "dedup_cluster_id": Value("string"),
2736
+ "structural_version": Value("string"),
2737
+ "extraction_branch": Value("string"),
2738
+ "parse_status": Value("string"),
2739
+ "circuit_ir_json": Value("string"),
2740
+ "parse_warnings_json": Value("string"),
2741
+ "unsupported_constructs_json": Value("string"),
2742
+ "component_count": Value("int64"),
2743
+ "pin_count": Value("int64"),
2744
+ "net_count": Value("int64"),
2745
+ "wire_count": Value("int64"),
2746
+ "label_count": Value("int64"),
2747
+ "render_check_json": Value("string"),
2748
+ "render_check_status": Value("string"),
2749
+ "no_label": HFImage(),
2750
+ "no_label_render_json": Value("string"),
2751
+ "overlay_check_json": Value("string"),
2752
+ "original_render_check_json": Value("string"),
2753
+ "quality_bucket": Value("string"),
2754
+ "keep_for_modeling": Value("bool"),
2755
+ "quality_reasons_json": Value("string"),
2756
+ "source_group": Value("string"),
2757
+ "graph_metrics_json": Value("string"),
2758
+ "graph_underconnected_components_json": Value("string"),
2759
+ "graph_overlapping_active_components_json": Value("string"),
2760
+ "graph_reasons_core_json": Value("string"),
2761
+ "graph_reasons_pretty_json": Value("string"),
2762
+ "graph_reasons_pretty_render_json": Value("string"),
2763
+ "graph_keep_graph_sane": Value("bool"),
2764
+ "graph_keep_graph_sane_pretty": Value("bool"),
2765
+ "graph_keep_graph_sane_pretty_render": Value("bool"),
2766
+ "graph_quality_bucket": Value("string"),
2767
  "Circuit Generation Code": Value("string"),
2768
  "Circuit generated image": HFImage(),
2769
  "Circuit Generated image with no text": HFImage(),
derived/Source/scripts/generate_visual_table.py ADDED
@@ -0,0 +1,145 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #!/usr/bin/env python3
2
+
3
+ from __future__ import annotations
4
+
5
+ import csv
6
+ import html
7
+ import json
8
+ import os
9
+ from pathlib import Path
10
+
11
+
12
+ REPO_ROOT = Path("/workspace/SchemID")
13
+ SOURCE_ROOT = REPO_ROOT / "derived" / "Source"
14
+ ROWS_PATH = SOURCE_ROOT / "metadata" / "rows.jsonl"
15
+ VIS_ROOT = SOURCE_ROOT / "visuals"
16
+ CSV_PATH = VIS_ROOT / "four_column_table.csv"
17
+ HTML_PATH = VIS_ROOT / "four_column_table.html"
18
+
19
+
20
+ def rel_to_visuals(path: Path) -> str:
21
+ return os.path.relpath(path, VIS_ROOT)
22
+
23
+
24
+ def image_rel(path_str: str) -> str:
25
+ path = Path(path_str)
26
+ return rel_to_visuals(path)
27
+
28
+
29
+ def main() -> None:
30
+ VIS_ROOT.mkdir(parents=True, exist_ok=True)
31
+
32
+ rows: list[dict[str, str]] = []
33
+ with ROWS_PATH.open() as handle:
34
+ for line in handle:
35
+ raw = json.loads(line)
36
+ source_payload = json.loads(raw["Source"])
37
+ original_path = Path(raw["Circuit generated image"])
38
+ no_text_path = Path(raw["Circuit Generated image with no text"])
39
+ eps_path = SOURCE_ROOT / source_payload["eps_path"]
40
+ row = {
41
+ "Circuit Generation Code": raw["Circuit Generation Code"],
42
+ "Circuit generated image": image_rel(str(original_path)),
43
+ "Circuit Generated image with no text": image_rel(str(no_text_path)),
44
+ "Source": json.dumps(source_payload, sort_keys=True),
45
+ "Code File": rel_to_visuals(eps_path),
46
+ }
47
+ rows.append(row)
48
+
49
+ with CSV_PATH.open("w", newline="") as handle:
50
+ writer = csv.DictWriter(
51
+ handle,
52
+ fieldnames=[
53
+ "Circuit Generation Code",
54
+ "Circuit generated image",
55
+ "Circuit Generated image with no text",
56
+ "Source",
57
+ "Code File",
58
+ ],
59
+ )
60
+ writer.writeheader()
61
+ writer.writerows(rows)
62
+
63
+ parts = [
64
+ "<!doctype html>",
65
+ "<html lang='en'>",
66
+ "<head>",
67
+ "<meta charset='utf-8'>",
68
+ "<meta name='viewport' content='width=device-width, initial-scale=1'>",
69
+ "<title>SchemID 4-Column Circuit Table</title>",
70
+ "<style>",
71
+ "body { font-family: ui-monospace, SFMono-Regular, Menlo, Consolas, monospace; margin: 0; background: #f5f5f5; color: #111; }",
72
+ ".wrap { padding: 16px; }",
73
+ "h1 { margin: 0 0 8px; font-size: 24px; }",
74
+ "p { margin: 0 0 12px; }",
75
+ "a { color: #0b57d0; }",
76
+ ".meta { margin-bottom: 16px; }",
77
+ "table { border-collapse: collapse; width: 100%; background: #fff; table-layout: fixed; }",
78
+ "thead th { position: sticky; top: 0; background: #ececec; z-index: 1; }",
79
+ "th, td { border: 1px solid #ccc; padding: 8px; vertical-align: top; }",
80
+ "th:nth-child(1), td:nth-child(1) { width: 38%; }",
81
+ "th:nth-child(2), td:nth-child(2) { width: 18%; }",
82
+ "th:nth-child(3), td:nth-child(3) { width: 18%; }",
83
+ "th:nth-child(4), td:nth-child(4) { width: 26%; }",
84
+ "pre { margin: 0; white-space: pre-wrap; word-break: break-word; max-height: 360px; overflow: auto; }",
85
+ ".imgbox { background: #fff; min-height: 120px; display: flex; align-items: center; justify-content: center; }",
86
+ "img { max-width: 100%; height: auto; border: 1px solid #ddd; background: #fff; }",
87
+ ".source { max-height: 360px; overflow: auto; white-space: pre-wrap; word-break: break-word; }",
88
+ ".small { font-size: 12px; color: #555; margin-top: 6px; }",
89
+ "</style>",
90
+ "</head>",
91
+ "<body>",
92
+ "<div class='wrap'>",
93
+ "<h1>SchemID 4-Column Circuit Table</h1>",
94
+ f"<p class='meta'>Rows: {len(rows)}. CSV companion: <a href='four_column_table.csv'>four_column_table.csv</a>.</p>",
95
+ "<table>",
96
+ "<thead><tr><th>Circuit Generation Code</th><th>Circuit generated image</th><th>Circuit Generated image with no text</th><th>Source</th></tr></thead>",
97
+ "<tbody>",
98
+ ]
99
+
100
+ for row in rows:
101
+ code_text = html.escape(row["Circuit Generation Code"])
102
+ source_text = html.escape(row["Source"])
103
+ code_file = html.escape(row["Code File"])
104
+ original_rel = html.escape(row["Circuit generated image"])
105
+ no_text_rel = html.escape(row["Circuit Generated image with no text"])
106
+ parts.extend(
107
+ [
108
+ "<tr>",
109
+ (
110
+ "<td>"
111
+ f"<pre>{code_text}</pre>"
112
+ f"<div class='small'>File: <a href='{code_file}'>{code_file}</a></div>"
113
+ "</td>"
114
+ ),
115
+ (
116
+ "<td>"
117
+ f"<div class='imgbox'><a href='{original_rel}'><img loading='lazy' src='{original_rel}' alt='original circuit'></a></div>"
118
+ f"<div class='small'><a href='{original_rel}'>{original_rel}</a></div>"
119
+ "</td>"
120
+ ),
121
+ (
122
+ "<td>"
123
+ f"<div class='imgbox'><a href='{no_text_rel}'><img loading='lazy' src='{no_text_rel}' alt='no-text circuit'></a></div>"
124
+ f"<div class='small'><a href='{no_text_rel}'>{no_text_rel}</a></div>"
125
+ "</td>"
126
+ ),
127
+ f"<td><div class='source'>{source_text}</div></td>",
128
+ "</tr>",
129
+ ]
130
+ )
131
+
132
+ parts.extend(
133
+ [
134
+ "</tbody>",
135
+ "</table>",
136
+ "</div>",
137
+ "</body>",
138
+ "</html>",
139
+ ]
140
+ )
141
+ HTML_PATH.write_text("\n".join(parts))
142
+
143
+
144
+ if __name__ == "__main__":
145
+ main()