xonecas.io
7517
Cd

clanker-and-the-dev / files

clanker-and-the-dev / .agents / skills / add-new-comic / scripts / generate_comic.py

7.5 KB
1from __future__ import annotations
2
3import argparse
4import html
5import json
6import subprocess
7import sys
8from pathlib import Path
9
10from PIL import Image, ImageOps
11
12from composite_panel import composite_panel
13from models import ComicSpec, load_spec
14
15
16def default_project_root() -> Path:
17    current = Path(__file__).resolve()
18    for parent in current.parents:
19        if (parent / "_config.yml").exists() and (parent / "AGENTS.md").exists():
20            return parent
21    raise RuntimeError("Could not locate repository root from skill script path")
22
23
24def compose_strip(_comic: ComicSpec, panel_paths: list[Path], output_path: Path, _project_root: Path) -> Path:
25    """Compose a panels-only comic image.
26
27    Page titles, credits, labels, and other site chrome belong in HTML/CSS, not
28    inside the generated PNG.  The strip image should be reusable as comic art
29    without baked-in headers, footers, metadata, or branding bars.
30    """
31    output_path.parent.mkdir(parents=True, exist_ok=True)
32    gap = 16
33    panels = [Image.open(path).convert("RGB") for path in panel_paths]
34    if not panels:
35        raise ValueError("Cannot compose a strip with no panels")
36
37    panel_width, panel_height = panels[0].size
38
39    if len(panels) == 1:
40        rows = [[panels[0]]]
41        strip_width = panel_width
42    elif len(panels) == 5:
43        strip_width = panel_width * 2 + gap
44        wide_final = Image.new("RGB", (strip_width, panel_height), "#000000")
45        final_panel = ImageOps.contain(panels[4], (strip_width, panel_height), method=Image.Resampling.LANCZOS)
46        wide_final.paste(final_panel, ((strip_width - final_panel.width) // 2, (panel_height - final_panel.height) // 2))
47        rows = [[panels[0], panels[1]], [panels[2], panels[3]], [wide_final]]
48    elif len(panels) == 3:
49        rows = [panels]
50        strip_width = panel_width * 3 + gap * 2
51    else:
52        cols = 2 if len(panels) in (2, 4) else 3
53        rows = [panels[i : i + cols] for i in range(0, len(panels), cols)]
54        strip_width = panel_width * cols + gap * (cols - 1)
55
56    strip_height = sum(row[0].height for row in rows) + gap * (len(rows) - 1)
57    strip = Image.new("RGB", (strip_width, strip_height), "#000000")
58
59    y = 0
60    for row in rows:
61        row_width = sum(panel.width for panel in row) + gap * (len(row) - 1)
62        x = (strip_width - row_width) // 2
63        for panel in row:
64            strip.paste(panel, (x, y))
65            x += panel.width + gap
66        y += row[0].height + gap
67
68    strip.save(output_path)
69    return output_path
70
71
72def write_post(comic: ComicSpec, strip_path: Path, project_root: Path) -> Path:
73    post_path = project_root / "_posts" / f"{comic.timestamp}-{comic.slug}.md"
74    asset_path = "/" + strip_path.relative_to(project_root).as_posix()
75    alt = html.escape(f"{comic.title} comic strip", quote=True)
76    credit = f"\n<p class=\"comic-credit\">Credit: {html.escape(comic.credit)}</p>\n" if comic.credit else ""
77    title_yaml = comic.title.replace('"', '\\"')
78    body = f"""---
79layout: post
80title: "{title_yaml}"
81---
82
83<div class="comic-strip image-comic">
84  <img src="{{{{ '{asset_path}' | relative_url }}}}" alt="{alt}">
85</div>{credit}
86"""
87    post_path.parent.mkdir(parents=True, exist_ok=True)
88    post_path.write_text(body, encoding="utf-8")
89    return post_path
90
91
92def generate_panel_in_worker(
93    spec_path: Path,
94    panel_index: int,
95    raw_path: Path,
96    output_dir: Path,
97    project_root: Path,
98) -> int:
99    seed_path = output_dir / f"seed-panel-{panel_index:02d}.json"
100    worker_path = Path(__file__).with_name("generate_panel_worker.py")
101    subprocess.run(
102        [
103            sys.executable,
104            str(worker_path),
105            str(spec_path),
106            str(panel_index),
107            str(raw_path),
108            "--project-root",
109            str(project_root),
110            "--seed-output",
111            str(seed_path),
112        ],
113        check=True,
114    )
115    data = json.loads(seed_path.read_text(encoding="utf-8"))
116    seed_path.unlink(missing_ok=True)
117    return int(data["seed"])
118
119
120def write_generation_metadata(output_dir: Path, panel_seeds: list[int], comic: ComicSpec) -> Path:
121    metadata_path = output_dir / "generation.json"
122    metadata = {
123        "title": comic.title,
124        "slug": comic.slug,
125        "timestamp": comic.timestamp,
126        "modelId": comic.generation.modelId,
127        "ipAdapterRepo": comic.generation.ipAdapterRepo,
128        "ipAdapterWeight": comic.generation.ipAdapterWeight,
129        "ipAdapterScale": comic.generation.ipAdapterScale,
130        "referenceImages": comic.generation.referenceImages,
131        "referenceCropMode": comic.generation.referenceCropMode,
132        "enableControlNet": comic.generation.enableControlNet,
133        "controlNetModelId": comic.generation.controlNetModelId if comic.generation.enableControlNet else None,
134        "controlGuideMode": comic.generation.controlGuideMode if comic.generation.enableControlNet else None,
135        "controlNetScale": comic.generation.controlNetScale if comic.generation.enableControlNet else None,
136        "controlNetStart": comic.generation.controlNetStart if comic.generation.enableControlNet else None,
137        "controlNetEnd": comic.generation.controlNetEnd if comic.generation.enableControlNet else None,
138        "artPostprocessMode": comic.generation.artPostprocessMode,
139        "lineArtThreshold": comic.generation.lineArtThreshold,
140        "lineArtStroke": comic.generation.lineArtStroke,
141        "panelSeeds": panel_seeds,
142    }
143    metadata_path.write_text(json.dumps(metadata, indent=2) + "\n", encoding="utf-8")
144    return metadata_path
145
146
147def generate_comic(spec_path: Path, project_root: Path) -> None:
148    comic = load_spec(spec_path)
149    output_dir = project_root / "assets" / "comics" / comic.slug
150    output_dir.mkdir(parents=True, exist_ok=True)
151
152    panel_paths: list[Path] = []
153    panel_seeds: list[int] = []
154    for index, panel in enumerate(comic.panels, start=1):
155        raw_path = output_dir / f"raw-panel-{index:02d}.png"
156        panel_path = output_dir / f"panel-{index:02d}.png"
157        seed = generate_panel_in_worker(spec_path, index, raw_path, output_dir, project_root)
158        composite_panel(
159            raw_path,
160            panel_path,
161            panel,
162            project_root,
163            index,
164            comic.generation.artPostprocessMode,
165            comic.generation.lineArtThreshold,
166            comic.generation.lineArtStroke,
167        )
168        panel_paths.append(panel_path)
169        panel_seeds.append(seed)
170        print(f"Generated {panel_path.relative_to(project_root)} with seed {seed}")
171
172    strip_path = compose_strip(comic, panel_paths, output_dir / "strip.png", project_root)
173    post_path = write_post(comic, strip_path, project_root)
174    metadata_path = write_generation_metadata(output_dir, panel_seeds, comic)
175
176    print(f"Wrote {strip_path.relative_to(project_root)}")
177    print(f"Wrote {post_path.relative_to(project_root)}")
178    print(f"Wrote {metadata_path.relative_to(project_root)}")
179
180
181def parse_args() -> argparse.Namespace:
182    parser = argparse.ArgumentParser(description="Generate a Clanker and the Dev SDXL comic from a JSON spec")
183    parser.add_argument("spec", type=Path, help="Path to comic image-generation spec JSON")
184    parser.add_argument(
185        "--project-root",
186        type=Path,
187        default=default_project_root(),
188        help="Repository root. Defaults to the parent repo of this skill.",
189    )
190    return parser.parse_args()
191
192
193def main() -> None:
194    args = parse_args()
195    generate_comic(args.spec.resolve(), args.project_root.resolve())
196
197
198if __name__ == "__main__":
199    main()