File size: 11,092 Bytes
d7b169c
 
 
 
a557890
d7b169c
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
a557890
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
d7b169c
 
 
 
 
 
 
 
 
 
 
 
 
 
a557890
d7b169c
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
a557890
d7b169c
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
a557890
 
 
 
 
 
 
 
 
d7b169c
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
#!/usr/bin/env python3

from __future__ import annotations

import argparse
import csv
import html
import json
import math
import re
import textwrap
from collections import defaultdict
from pathlib import Path

from PIL import Image, ImageDraw, ImageFont


REPO_ROOT = Path("/workspace/SchemID")
SOURCE_ROOT = REPO_ROOT / "derived" / "Source"
ROWS_PATH = SOURCE_ROOT / "metadata" / "rows.jsonl"
SHEETS_ROOT = SOURCE_ROOT / "sheets"

PAGE_W = 4200
PAGE_H = 5940
MARGIN_X = 140
MARGIN_Y = 140
PAGE_HEADER_H = 180
COLS = 2
ROWS = 3
GRID_GAP_X = 90
GRID_GAP_Y = 90
CARD_PADDING = 36
CARD_RADIUS = 28
PER_PAGE = COLS * ROWS

FONT_REGULAR = "/usr/share/fonts/truetype/dejavu/DejaVuSans.ttf"
FONT_BOLD = "/usr/share/fonts/truetype/dejavu/DejaVuSans-Bold.ttf"
TAG_RE = re.compile(r"<[^>]+>")
SPACE_RE = re.compile(r"\s+")

BOOK_ORDER = ["DC", "AC", "SEMI", "DIGI", "REF", "EXP", "LIII"]


def load_font(path: str, size: int) -> ImageFont.FreeTypeFont:
    return ImageFont.truetype(path, size=size)


TITLE_FONT = load_font(FONT_BOLD, 52)
CONTEXT_FONT = load_font(FONT_REGULAR, 34)
META_FONT = load_font(FONT_REGULAR, 30)
PAGE_TITLE_FONT = load_font(FONT_BOLD, 72)
PAGE_META_FONT = load_font(FONT_REGULAR, 36)


def clean_text(value: str | None) -> str:
    if not value:
        return ""
    value = html.unescape(value)
    value = TAG_RE.sub("", value)
    value = SPACE_RE.sub(" ", value).strip()
    return value


def first_ref(source_payload: dict) -> dict:
    refs = source_payload.get("references") or []
    return refs[0] if refs else {}


def sort_key(source_payload: dict) -> tuple:
    ref = first_ref(source_payload)
    return (
        clean_text(ref.get("reference_source")),
        ref.get("line") or 0,
        source_payload.get("figure_id") or "",
    )


def pick_primary_title(source_payload: dict) -> str:
    ref = first_ref(source_payload)
    for key in ("caption", "subsection", "section", "chapter"):
        text = clean_text(ref.get(key))
        if text:
            return text
    return f"{source_payload['book']} {source_payload['figure_id']}"


def pick_context(source_payload: dict) -> str:
    ref = first_ref(source_payload)
    parts: list[str] = []
    for key in ("chapter", "section", "subsection"):
        text = clean_text(ref.get(key))
        if text and text not in parts:
            parts.append(text)
    primary = pick_primary_title(source_payload)
    parts = [part for part in parts if part != primary]
    return " / ".join(parts)


def pick_source_line(source_payload: dict) -> str:
    ref = first_ref(source_payload)
    source_file = clean_text(ref.get("reference_source")) or "unknown"
    line = ref.get("line")
    line_text = f":{line}" if line else ""
    return (
        f"{source_payload['book']} {source_payload['figure_id']} | "
        f"{source_file}{line_text}"
    )


def draw_rounded_box(draw: ImageDraw.ImageDraw, box: tuple[int, int, int, int]) -> None:
    draw.rounded_rectangle(box, radius=CARD_RADIUS, fill="white", outline="#cfcfcf", width=4)


def fit_image(image: Image.Image, max_w: int, max_h: int) -> Image.Image:
    image = trim_image(image.convert("RGBA"))
    scale = min(max_w / image.width, max_h / image.height)
    new_size = (max(1, int(image.width * scale)), max(1, int(image.height * scale)))
    resized = image.resize(new_size, Image.Resampling.LANCZOS)
    white_bg = Image.new("RGBA", resized.size, (255, 255, 255, 255))
    return Image.alpha_composite(white_bg, resized).convert("RGB")


def trim_image(image: Image.Image) -> Image.Image:
    bg = Image.new("RGBA", image.size, (255, 255, 255, 255))
    flattened = Image.alpha_composite(bg, image).convert("RGB")
    pixels = flattened.load()
    min_x = flattened.width
    min_y = flattened.height
    max_x = -1
    max_y = -1

    for y in range(flattened.height):
        for x in range(flattened.width):
            r, g, b = pixels[x, y]
            if r < 250 or g < 250 or b < 250:
                if x < min_x:
                    min_x = x
                if y < min_y:
                    min_y = y
                if x > max_x:
                    max_x = x
                if y > max_y:
                    max_y = y

    if max_x < min_x or max_y < min_y:
        return image

    pad = 20
    min_x = max(0, min_x - pad)
    min_y = max(0, min_y - pad)
    max_x = min(image.width, max_x + pad + 1)
    max_y = min(image.height, max_y + pad + 1)
    return image.crop((min_x, min_y, max_x, max_y))


def wrap_lines(text: str, width: int) -> list[str]:
    if not text:
        return []
    wrapped = textwrap.wrap(text, width=width, break_long_words=False, replace_whitespace=False)
    return wrapped or [text]


def build_page(rows: list[dict], display_name: str, book: str, page_number: int, page_count: int, output_path: Path) -> None:
    page = Image.new("RGB", (PAGE_W, PAGE_H), "white")
    draw = ImageDraw.Draw(page)

    draw.text((MARGIN_X, MARGIN_Y - 10), display_name, fill="#111111", font=PAGE_TITLE_FONT)
    meta_text = f"Sheet {page_number} / {page_count}   |   {len(rows)} circuits on this page"
    draw.text((MARGIN_X, MARGIN_Y + 86), meta_text, fill="#444444", font=PAGE_META_FONT)

    grid_top = MARGIN_Y + PAGE_HEADER_H
    usable_w = PAGE_W - (2 * MARGIN_X) - ((COLS - 1) * GRID_GAP_X)
    usable_h = PAGE_H - grid_top - MARGIN_Y - ((ROWS - 1) * GRID_GAP_Y)
    card_w = usable_w // COLS
    card_h = usable_h // ROWS

    for idx, row in enumerate(rows):
        col = idx % COLS
        r = idx // COLS
        x0 = MARGIN_X + col * (card_w + GRID_GAP_X)
        y0 = grid_top + r * (card_h + GRID_GAP_Y)
        x1 = x0 + card_w
        y1 = y0 + card_h
        draw_rounded_box(draw, (x0, y0, x1, y1))

        content_x = x0 + CARD_PADDING
        content_y = y0 + CARD_PADDING
        content_w = card_w - (2 * CARD_PADDING)
        content_h = card_h - (2 * CARD_PADDING)

        primary = wrap_lines(row["primary_title"], width=42)[:3]
        context = wrap_lines(row["context"], width=60)[:3]
        meta = wrap_lines(row["source_line"], width=68)[:2]

        y_cursor = content_y
        for line in primary:
            draw.text((content_x, y_cursor), line, fill="#111111", font=TITLE_FONT)
            y_cursor += 62

        if context:
            y_cursor += 8
            for line in context:
                draw.text((content_x, y_cursor), line, fill="#444444", font=CONTEXT_FONT)
                y_cursor += 42

        image_box_top = y_cursor + 18
        meta_h = 40 * max(1, len(meta))
        image_box_h = content_h - (image_box_top - content_y) - meta_h - 18

        with Image.open(row["image_path"]) as circuit:
            fitted = fit_image(circuit, content_w, image_box_h)
        image_x = content_x + (content_w - fitted.width) // 2
        image_y = image_box_top + max(0, (image_box_h - fitted.height) // 2)
        page.paste(fitted.convert("RGB"), (image_x, image_y))

        meta_y = content_y + content_h - meta_h
        for line in meta:
            draw.text((content_x, meta_y), line, fill="#666666", font=META_FONT)
            meta_y += 38

    output_path.parent.mkdir(parents=True, exist_ok=True)
    page.save(output_path, format="PNG", compress_level=3)


def main() -> None:
    parser = argparse.ArgumentParser()
    parser.add_argument(
        "--image-field",
        default="Circuit generated image",
        choices=[
            "Circuit generated image",
            "Circuit Generated image with no text",
        ],
        help="Dataset row field containing the image path to place on the sheets.",
    )
    parser.add_argument(
        "--output-subdir",
        default="original",
        help="Subdirectory under derived/Source/sheets where the page PNGs will be written.",
    )
    parser.add_argument(
        "--manifest-name",
        default="sheet_manifest.csv",
        help="Manifest filename written under derived/Source/sheets.",
    )
    args = parser.parse_args()

    sheets_output_root = SHEETS_ROOT / args.output_subdir
    manifest_path = SHEETS_ROOT / args.manifest_name
    sheets_output_root.mkdir(parents=True, exist_ok=True)

    grouped: dict[str, list[dict]] = defaultdict(list)
    display_names: dict[str, str] = {}

    with ROWS_PATH.open() as handle:
        for line in handle:
            raw = json.loads(line)
            source_payload = json.loads(raw["Source"])
            book = source_payload["book"]
            display_names[book] = source_payload["display_name"]
            grouped[book].append(
                {
                    "book": book,
                    "figure_id": source_payload["figure_id"],
                    "image_path": Path(raw[args.image_field]),
                    "primary_title": pick_primary_title(source_payload),
                    "context": pick_context(source_payload),
                    "source_line": pick_source_line(source_payload),
                    "source_payload": source_payload,
                }
            )

    manifest_rows: list[dict[str, str]] = []
    for book in BOOK_ORDER:
        rows = grouped.get(book)
        if not rows:
            continue
        rows.sort(key=lambda row: sort_key(row["source_payload"]))
        display_name = display_names[book]
        page_count = math.ceil(len(rows) / PER_PAGE)
        for page_index in range(page_count):
            start = page_index * PER_PAGE
            end = start + PER_PAGE
            page_rows = rows[start:end]
            output_path = (
                sheets_output_root
                / book
                / f"{book}_sheet_{page_index + 1:03d}.png"
            )
            build_page(
                page_rows,
                display_name=display_name,
                book=book,
                page_number=page_index + 1,
                page_count=page_count,
                output_path=output_path,
            )
            manifest_rows.append(
                {
                    "book": book,
                    "display_name": display_name,
                    "page_number": str(page_index + 1),
                    "page_count": str(page_count),
                    "sheet_png": str(output_path.relative_to(SHEETS_ROOT)),
                    "figure_ids": "|".join(row["figure_id"] for row in page_rows),
                    "titles": " || ".join(row["primary_title"] for row in page_rows),
                }
            )

    keep_paths = {
        (SHEETS_ROOT / row["sheet_png"]).resolve()
        for row in manifest_rows
    }
    for path in sheets_output_root.rglob("*.png"):
        if path.resolve() not in keep_paths:
            path.unlink()

    with manifest_path.open("w", newline="") as handle:
        writer = csv.DictWriter(
            handle,
            fieldnames=[
                "book",
                "display_name",
                "page_number",
                "page_count",
                "sheet_png",
                "figure_ids",
                "titles",
            ],
        )
        writer.writeheader()
        writer.writerows(manifest_rows)


if __name__ == "__main__":
    main()