SchemID / derived /Source /scripts /generate_visual_sheets.py
lsnu's picture
Add files using upload-large-folder tool
a557890 verified
#!/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()