Ame commited on
Commit
decded9
·
1 Parent(s): b7a929e

update .gitignore and remove art tools

Browse files
.gitignore CHANGED
@@ -10,12 +10,14 @@ scratch_*/
10
  # Editor and operating-system files
11
  .idea/
12
  .vscode/
 
 
13
  node_modules/
14
  __pycache__/
15
  .DS_Store
16
  Thumbs.db
17
  desktop.ini
18
-
19
  # Paradox and tooling caches
20
  .launcher-cache/
21
  shadercache/
 
10
  # Editor and operating-system files
11
  .idea/
12
  .vscode/
13
+ .claude
14
+
15
  node_modules/
16
  __pycache__/
17
  .DS_Store
18
  Thumbs.db
19
  desktop.ini
20
+ .editorconfig
21
  # Paradox and tooling caches
22
  .launcher-cache/
23
  shadercache/
tools/art/README.md DELETED
@@ -1,43 +0,0 @@
1
- # AB art generator
2
-
3
- Read the repository root `DESIGN.md` before generating an asset. The approved AB GUI reference in `design/reference/` is the default visual reference for later GUI, icon, and related asset work.
4
-
5
- ## Environment
6
-
7
- ```powershell
8
- conda env create -f tools/art/environment.yml
9
- ```
10
-
11
- The tool reads its key exclusively from the `OPENROUTER_API_KEY` environment variable. It never writes the key into a run manifest.
12
-
13
- Requests target OpenRouter's dedicated Images API with the fixed `openai/gpt-image-2` model. The generator uses the machine's direct network path and does not inherit `HTTP_PROXY` or `HTTPS_PROXY`.
14
-
15
- Image generation uses the OpenRouter SSE stream and only saves the final `image_generation.completed` image. Reference images are supplied as OpenRouter `input_references` data URLs. The manifest records the completed event's actual usage cost.
16
-
17
- ## Generate the GUI reference candidates
18
-
19
- ```powershell
20
- conda run -n ab-art python tools/art/generate.py generate --preset gui-style-reference --count 3
21
- ```
22
-
23
- Candidates, the contact sheet, and the full run manifest are written under `temp/art/`. The command sends paid requests immediately.
24
-
25
- ## Generate another asset
26
-
27
- Write a UTF-8 prompt file, then use the current approved reference image:
28
-
29
- ```powershell
30
- conda run -n ab-art python tools/art/generate.py generate --prompt-file temp/art/example_prompt.txt --name example --reference design/reference/ab_gui_style_reference_v1.png
31
- ```
32
-
33
- Repeat `--reference` to send multiple PNG reference images. Omit it only when deliberately starting a new visual direction.
34
-
35
- ## Promote an approved candidate
36
-
37
- Candidate indices are one-based and match `candidate_01.png`, `candidate_02.png`, and so on.
38
-
39
- ```powershell
40
- conda run -n ab-art python tools/art/generate.py promote --run temp/art/<run-directory> --image 1 --name ab_gui_style_reference_v1
41
- ```
42
-
43
- Promotion writes a PNG and JSON provenance record to `design/reference/`. Existing names are never overwritten.
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
tools/art/environment.yml DELETED
@@ -1,7 +0,0 @@
1
- name: ab-art
2
- channels:
3
- - conda-forge
4
- dependencies:
5
- - python=3.12
6
- - pillow=12.1
7
- - requests=2.34
 
 
 
 
 
 
 
 
tools/art/generate.py DELETED
@@ -1,376 +0,0 @@
1
- #!/usr/bin/env python3
2
- """Generate and promote Ab Integro visual assets through OpenRouter."""
3
-
4
- from __future__ import annotations
5
-
6
- import argparse
7
- import base64
8
- import hashlib
9
- import io
10
- import json
11
- import math
12
- import os
13
- import re
14
- import shutil
15
- from datetime import datetime, timezone
16
- from decimal import Decimal
17
- from pathlib import Path
18
-
19
- import requests
20
- from PIL import Image
21
-
22
-
23
- REPO_ROOT = Path(__file__).resolve().parents[2]
24
- ART_ROOT = Path(__file__).resolve().parent
25
- CANDIDATE_ROOT = REPO_ROOT / "temp" / "art"
26
- REFERENCE_ROOT = REPO_ROOT / "design" / "reference"
27
- API_BASE = "https://openrouter.ai/api/v1"
28
- MODEL = "openai/gpt-image-2"
29
- API_KEY_ENV = "OPENROUTER_API_KEY"
30
- MODEL_TIMEOUT = 30
31
- IMAGE_TIMEOUT = 600
32
- SLUG = re.compile(r"^[a-z0-9][a-z0-9_-]*$")
33
- SIZE = re.compile(r"^(\d+)x(\d+)$")
34
-
35
-
36
- def read_api_key() -> str:
37
- return os.environ[API_KEY_ENV]
38
-
39
-
40
- def sha256_file(path: Path) -> str:
41
- digest = hashlib.sha256()
42
- with path.open("rb") as source:
43
- for chunk in iter(lambda: source.read(1024 * 1024), b""):
44
- digest.update(chunk)
45
- return digest.hexdigest()
46
-
47
-
48
- def write_json(path: Path, value: dict) -> None:
49
- path.write_text(json.dumps(value, ensure_ascii=False, indent=2) + "\n", encoding="utf-8")
50
-
51
-
52
- def auth_headers(api_key: str) -> dict[str, str]:
53
- return {"Authorization": f"Bearer {api_key}"}
54
-
55
-
56
- def create_session() -> requests.Session:
57
- session = requests.Session()
58
- session.trust_env = False
59
- return session
60
-
61
-
62
- def fetch_model_pricing(session: requests.Session, api_key: str) -> list[dict]:
63
- response = session.get(
64
- f"{API_BASE}/images/models/{MODEL}/endpoints",
65
- headers=auth_headers(api_key),
66
- timeout=MODEL_TIMEOUT,
67
- )
68
- response.raise_for_status()
69
- endpoint = response.json()["endpoints"][0]
70
- return endpoint["pricing"]
71
-
72
-
73
- def load_preset(name: str, art_root: Path = ART_ROOT) -> dict:
74
- path = art_root / "presets" / f"{name}.json"
75
- return json.loads(path.read_text(encoding="utf-8"))
76
-
77
-
78
- def parse_size(value: str) -> tuple[int, int]:
79
- match = SIZE.fullmatch(value)
80
- if match is None:
81
- raise ValueError(f"invalid image size: {value}")
82
- return int(match.group(1)), int(match.group(2))
83
-
84
-
85
- def validate_slug(value: str) -> str:
86
- if SLUG.fullmatch(value) is None:
87
- raise ValueError(f"invalid name: {value}")
88
- return value
89
-
90
-
91
- def validate_image(encoded: str, expected_size: tuple[int, int]) -> bytes:
92
- image_bytes = base64.b64decode(encoded, validate=True)
93
- with Image.open(io.BytesIO(image_bytes)) as image:
94
- image.load()
95
- if image.format != "PNG":
96
- raise ValueError(f"provider returned {image.format}, expected PNG")
97
- if image.size != expected_size:
98
- raise ValueError(f"provider returned {image.size}, expected {expected_size}")
99
- return image_bytes
100
-
101
-
102
- def decode_stream_image(response: requests.Response, expected_size: tuple[int, int]) -> tuple[bytes, dict]:
103
- completed: dict | None = None
104
- for line in response.iter_lines(decode_unicode=True):
105
- if not line.startswith("data: "):
106
- continue
107
- data = line.removeprefix("data: ")
108
- if data == "[DONE]":
109
- continue
110
- event = json.loads(data)
111
- if event["type"] in ("image_generation.completed", "image_edit.completed"):
112
- completed = event
113
- if completed is None:
114
- raise ValueError("image stream ended without a completed event")
115
- return validate_image(completed["b64_json"], expected_size), completed
116
-
117
-
118
- def input_references(references: list[Path]) -> list[dict]:
119
- return [
120
- {
121
- "type": "image_url",
122
- "image_url": {
123
- "url": "data:image/png;base64," + base64.b64encode(path.read_bytes()).decode("ascii"),
124
- },
125
- }
126
- for path in references
127
- ]
128
-
129
-
130
- def request_image(
131
- session: requests.Session,
132
- api_key: str,
133
- prompt: str,
134
- size: str,
135
- quality: str,
136
- output_format: str,
137
- references: list[Path],
138
- ) -> tuple[bytes, str | None, str, dict]:
139
- expected_size = parse_size(size)
140
- fields = {
141
- "model": MODEL,
142
- "prompt": prompt,
143
- "size": size,
144
- "quality": quality,
145
- "output_format": output_format,
146
- "n": 1,
147
- }
148
- width, height = expected_size
149
- endpoint = f"{API_BASE}/images"
150
- payload = {
151
- **fields,
152
- "aspect_ratio": f"{width // math.gcd(width, height)}:{height // math.gcd(width, height)}",
153
- "background": "opaque",
154
- "input_references": input_references(references),
155
- "stream": True,
156
- }
157
- response = session.post(
158
- endpoint,
159
- headers={**auth_headers(api_key), "Content-Type": "application/json"},
160
- json=payload,
161
- timeout=IMAGE_TIMEOUT,
162
- stream=True,
163
- )
164
- response.raise_for_status()
165
- image_bytes, completed = decode_stream_image(response, expected_size)
166
- return image_bytes, response.headers.get("x-request-id"), endpoint, completed["usage"]
167
-
168
-
169
- def create_contact_sheet(images: list[Path], destination: Path) -> None:
170
- cell_width = 512
171
- cell_height = 341
172
- columns = min(3, len(images))
173
- rows = math.ceil(len(images) / columns)
174
- sheet = Image.new("RGB", (columns * cell_width, rows * cell_height), "white")
175
- for index, path in enumerate(images):
176
- with Image.open(path) as source:
177
- thumbnail = source.convert("RGB")
178
- thumbnail.thumbnail((cell_width, cell_height), Image.Resampling.LANCZOS)
179
- x = (index % columns) * cell_width + (cell_width - thumbnail.width) // 2
180
- y = (index // columns) * cell_height + (cell_height - thumbnail.height) // 2
181
- sheet.paste(thumbnail, (x, y))
182
- sheet.save(destination, format="PNG")
183
-
184
-
185
- def run_timestamp(now: datetime | None = None) -> str:
186
- instant = now or datetime.now(timezone.utc)
187
- return instant.astimezone(timezone.utc).strftime("%Y%m%dT%H%M%S.%fZ")
188
-
189
-
190
- def generate_run(
191
- *,
192
- session: requests.Session,
193
- api_key: str,
194
- prompt: str,
195
- name: str,
196
- count: int,
197
- size: str,
198
- quality: str,
199
- output_format: str,
200
- references: list[Path],
201
- output_root: Path = CANDIDATE_ROOT,
202
- now: datetime | None = None,
203
- ) -> Path:
204
- validate_slug(name)
205
- if count < 1:
206
- raise ValueError("count must be at least 1")
207
- parse_size(size)
208
- endpoint_pricing = fetch_model_pricing(session, api_key)
209
- run_dir = output_root / f"{run_timestamp(now)}_{name}"
210
- run_dir.mkdir(parents=True)
211
- reference_records = [
212
- {"path": str(path.resolve()), "sha256": sha256_file(path)} for path in references
213
- ]
214
- manifest = {
215
- "schema_version": 1,
216
- "name": name,
217
- "created_at": datetime.now(timezone.utc).isoformat(),
218
- "provider": "OpenRouter",
219
- "model": MODEL,
220
- "prompt": prompt,
221
- "parameters": {
222
- "size": size,
223
- "quality": quality,
224
- "output_format": output_format,
225
- "count": count,
226
- },
227
- "pricing": {"currency": "USD", "endpoint_pricing": endpoint_pricing, "actual_total": "0"},
228
- "references": reference_records,
229
- "outputs": [],
230
- }
231
- manifest_path = run_dir / "manifest.json"
232
- write_json(manifest_path, manifest)
233
-
234
- output_paths: list[Path] = []
235
- for index in range(1, count + 1):
236
- image_bytes, request_id, endpoint, usage = request_image(
237
- session,
238
- api_key,
239
- prompt,
240
- size,
241
- quality,
242
- output_format,
243
- references,
244
- )
245
- output_path = run_dir / f"candidate_{index:02d}.png"
246
- output_path.write_bytes(image_bytes)
247
- output_paths.append(output_path)
248
- manifest["outputs"].append(
249
- {
250
- "index": index,
251
- "file": output_path.name,
252
- "sha256": sha256_file(output_path),
253
- "endpoint": endpoint,
254
- "request_id": request_id,
255
- "usage": usage,
256
- }
257
- )
258
- manifest["pricing"]["actual_total"] = str(
259
- sum(Decimal(str(item["usage"]["cost"])) for item in manifest["outputs"])
260
- )
261
- write_json(manifest_path, manifest)
262
- print(f"generated {index}/{count}: {output_path}")
263
-
264
- contact_sheet = run_dir / "contact_sheet.png"
265
- create_contact_sheet(output_paths, contact_sheet)
266
- manifest["contact_sheet"] = {
267
- "file": contact_sheet.name,
268
- "sha256": sha256_file(contact_sheet),
269
- }
270
- write_json(manifest_path, manifest)
271
- print(f"manifest: {manifest_path}")
272
- print(f"actual cost: USD {manifest['pricing']['actual_total']}")
273
- return run_dir
274
-
275
-
276
- def promote(run_dir: Path, image_index: int, name: str, reference_root: Path = REFERENCE_ROOT) -> tuple[Path, Path]:
277
- validate_slug(name)
278
- manifest_path = run_dir / "manifest.json"
279
- manifest = json.loads(manifest_path.read_text(encoding="utf-8"))
280
- output = next(item for item in manifest["outputs"] if item["index"] == image_index)
281
- source_image = run_dir / output["file"]
282
- target_image = reference_root / f"{name}.png"
283
- target_manifest = reference_root / f"{name}.json"
284
- if target_image.exists() or target_manifest.exists():
285
- raise FileExistsError(f"reference already exists: {name}")
286
- reference_root.mkdir(parents=True, exist_ok=True)
287
- shutil.copy2(source_image, target_image)
288
- promoted = {
289
- "schema_version": 1,
290
- "name": name,
291
- "approved_at": datetime.now(timezone.utc).isoformat(),
292
- "source_run": str(run_dir.resolve()),
293
- "source_manifest_sha256": sha256_file(manifest_path),
294
- "source_index": image_index,
295
- "provider": manifest["provider"],
296
- "model": manifest["model"],
297
- "prompt": manifest["prompt"],
298
- "parameters": manifest["parameters"],
299
- "pricing": manifest["pricing"],
300
- "references": manifest["references"],
301
- "request_id": output["request_id"],
302
- "sha256": sha256_file(target_image),
303
- }
304
- write_json(target_manifest, promoted)
305
- return target_image, target_manifest
306
-
307
-
308
- def resolve_generate_args(args: argparse.Namespace) -> dict:
309
- if args.preset:
310
- preset = load_preset(args.preset)
311
- prompt_path = ART_ROOT / preset["prompt_file"]
312
- name = args.name or preset["name"]
313
- count = args.count if args.count is not None else preset["default_count"]
314
- size = args.size or preset["size"]
315
- quality = args.quality or preset["quality"]
316
- output_format = preset["output_format"]
317
- else:
318
- if args.name is None:
319
- raise ValueError("--name is required with --prompt-file")
320
- prompt_path = args.prompt_file
321
- name = args.name
322
- count = args.count if args.count is not None else 1
323
- size = args.size or "1536x1024"
324
- quality = args.quality or "high"
325
- output_format = "png"
326
- return {
327
- "prompt": prompt_path.read_text(encoding="utf-8").strip(),
328
- "name": name,
329
- "count": count,
330
- "size": size,
331
- "quality": quality,
332
- "output_format": output_format,
333
- "references": args.reference,
334
- }
335
-
336
-
337
- def build_parser() -> argparse.ArgumentParser:
338
- parser = argparse.ArgumentParser(description=__doc__)
339
- subparsers = parser.add_subparsers(dest="command", required=True)
340
-
341
- generate = subparsers.add_parser("generate", help="generate candidate images")
342
- source = generate.add_mutually_exclusive_group(required=True)
343
- source.add_argument("--preset")
344
- source.add_argument("--prompt-file", type=Path)
345
- generate.add_argument("--name")
346
- generate.add_argument("--reference", type=Path, action="append", default=[])
347
- generate.add_argument("--count", type=int)
348
- generate.add_argument("--size")
349
- generate.add_argument("--quality", choices=("low", "medium", "high"))
350
-
351
- promote_parser = subparsers.add_parser("promote", help="promote one candidate into design/reference")
352
- promote_parser.add_argument("--run", type=Path, required=True)
353
- promote_parser.add_argument("--image", type=int, required=True)
354
- promote_parser.add_argument("--name", required=True)
355
- return parser
356
-
357
-
358
- def main() -> None:
359
- args = build_parser().parse_args()
360
- if args.command == "generate":
361
- values = resolve_generate_args(args)
362
- with create_session() as session:
363
- run_dir = generate_run(
364
- session=session,
365
- api_key=read_api_key(),
366
- **values,
367
- )
368
- print(f"run: {run_dir}")
369
- else:
370
- image, metadata = promote(args.run, args.image, args.name)
371
- print(f"promoted: {image}")
372
- print(f"metadata: {metadata}")
373
-
374
-
375
- if __name__ == "__main__":
376
- main()
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
tools/art/presets/gui-style-reference.json DELETED
@@ -1,8 +0,0 @@
1
- {
2
- "name": "gui-style-reference",
3
- "prompt_file": "prompts/gui_style_reference.txt",
4
- "size": "1536x1024",
5
- "quality": "high",
6
- "output_format": "png",
7
- "default_count": 3
8
- }
 
 
 
 
 
 
 
 
 
tools/art/prompts/gui_style_reference.txt DELETED
@@ -1,13 +0,0 @@
1
- Create a polished visual style reference sheet for the historical grand strategy game mod Ab Integro.
2
-
3
- The image is an orthographic product-design board on a clean neutral white background. Arrange a coherent family of UI parts with generous separation and no overlap: one complete early-modern event dialog as the main object, one detached title plaque, three compact button states, several straight border segments, two corner ornaments, one circular seal, four material samples, and ten plain color swatches.
4
-
5
- The central concept is a global early-modern archive assembled by navigators, clerks, merchants, scholars, and imperial administrators. The UI must feel like a precise archival instrument used for centuries, not a European palace frame and not a theatrical prop.
6
-
7
- Use these exact material colors as the controlling palette: near-black indigo #101820 for the main lacquered or dyed-leather surfaces; charcoal brown-black #181817 for recessed content areas; aged brass #9A7441 for narrow structural lines and nodes; dark copper #6E4938 for metal shadows and wear; warm paper #D8C7A2; warm off-white #E3DDD0 for primary typography placeholders; secondary gray #AFA99E; restrained cinnabar #883431 for sovereignty, warning, and seals; malachite #31584B for economic accents; ultramarine #36556E for diplomatic and scholarly accents.
8
-
9
- Use narrow double-line aged-brass frames, precise engraved linework, subtle map latitude arcs and copperplate hatching, four-way rosette or compass-star corner nodes, deep indigo lacquer and embossed leather, restrained paper fibers, an impressed seal, and believable small metal fasteners. Ornament must be globally legible through abstract shared geometry rather than a collage of culture-specific motifs.
10
-
11
- The complete event dialog must have a thin outer frame, a dark indigo title plaque fixed by small brass studs, a recessed charcoal content field, a framed image placeholder, orderly typographic placeholder lines, and a stable bottom action area. Use placeholder bars and lines only. Do not render readable interface copy, captions, annotations, component names, arrows, measurements, legends, logos, watermarks, or explanatory text anywhere on the sheet.
12
-
13
- The result must look production-ready for Europa Universalis IV: dense but readable, materially rich but restrained, historically grounded between the fifteenth and eighteenth centuries, globally oriented, and distinct from vanilla EU4. Avoid thick bright-gold rococo frames, oversized curled foliage, gemstones, fantasy runes, steampunk machinery, modern flat UI, glassmorphism, neon light, glowing edges, blue-purple gradients, excessive distressing, burned paper, and decorative clutter.
 
 
 
 
 
 
 
 
 
 
 
 
 
 
tools/art/test/test_generate.py DELETED
@@ -1,206 +0,0 @@
1
- from __future__ import annotations
2
-
3
- import base64
4
- import io
5
- import json
6
- import os
7
- import sys
8
- import tempfile
9
- import unittest
10
- from datetime import datetime, timezone
11
- from pathlib import Path
12
- from unittest.mock import patch
13
-
14
- import requests
15
- from PIL import Image
16
-
17
-
18
- ART_ROOT = Path(__file__).resolve().parents[1]
19
- sys.path.insert(0, str(ART_ROOT))
20
-
21
- import generate
22
-
23
-
24
- def png_bytes(size: tuple[int, int] = (64, 64), color: str = "#101820") -> bytes:
25
- buffer = io.BytesIO()
26
- Image.new("RGB", size, color).save(buffer, format="PNG")
27
- return buffer.getvalue()
28
-
29
-
30
- class FakeResponse:
31
- def __init__(self, payload: dict, status: int = 200, request_id: str = "req_test") -> None:
32
- self.payload = payload
33
- self.status = status
34
- self.headers = {"x-request-id": request_id}
35
-
36
- def json(self) -> dict:
37
- return self.payload
38
-
39
- def raise_for_status(self) -> None:
40
- if self.status >= 400:
41
- raise requests.HTTPError(f"HTTP {self.status}")
42
-
43
- def iter_lines(self, decode_unicode: bool = False):
44
- encoded = self.payload["data"][0]["b64_json"]
45
- yield "event: image_generation.completed"
46
- yield "data: " + json.dumps(
47
- {
48
- "type": "image_generation.completed",
49
- "b64_json": encoded,
50
- "usage": self.payload["usage"],
51
- }
52
- )
53
-
54
-
55
- class FakeSession:
56
- def __init__(self, image_responses: list[FakeResponse] | None = None, model_status: int = 200) -> None:
57
- self.image_responses = list(image_responses or [])
58
- self.model_status = model_status
59
- self.get_calls: list[dict] = []
60
- self.post_calls: list[dict] = []
61
-
62
- def get(self, url: str, **kwargs) -> FakeResponse:
63
- self.get_calls.append({"url": url, **kwargs})
64
- return FakeResponse(
65
- {
66
- "endpoints": [
67
- {"pricing": [{"billable": "output_image", "unit": "token", "cost_usd": 0.00003}]}
68
- ]
69
- },
70
- status=self.model_status,
71
- )
72
-
73
- def post(self, url: str, **kwargs) -> FakeResponse:
74
- call = {"url": url, **kwargs}
75
- if "files" in call:
76
- call["file_snapshots"] = [
77
- (field, spec[0], spec[1].read(), spec[2]) for field, spec in call["files"]
78
- ]
79
- self.post_calls.append(call)
80
- return self.image_responses.pop(0)
81
-
82
-
83
- def image_response(size: tuple[int, int] = (64, 64), request_id: str = "req_test") -> FakeResponse:
84
- encoded = base64.b64encode(png_bytes(size)).decode("ascii")
85
- return FakeResponse(
86
- {"data": [{"b64_json": encoded}], "usage": {"cost": 0.13}},
87
- request_id=request_id,
88
- )
89
-
90
-
91
- class GeneratorTests(unittest.TestCase):
92
- def test_session_does_not_inherit_proxy_environment(self) -> None:
93
- with generate.create_session() as session:
94
- self.assertFalse(session.trust_env)
95
-
96
- def test_generation_writes_candidates_contact_sheet_and_secret_free_manifest(self) -> None:
97
- with tempfile.TemporaryDirectory() as temp:
98
- root = Path(temp)
99
- session = FakeSession([image_response(request_id="req_1"), image_response(request_id="req_2")])
100
- run_dir = generate.generate_run(
101
- session=session,
102
- api_key="secret-test-key",
103
- prompt="test prompt",
104
- name="test-run",
105
- count=2,
106
- size="64x64",
107
- quality="high",
108
- output_format="png",
109
- references=[],
110
- output_root=root,
111
- now=datetime(2026, 8, 1, tzinfo=timezone.utc),
112
- )
113
-
114
- self.assertTrue((run_dir / "candidate_01.png").is_file())
115
- self.assertTrue((run_dir / "candidate_02.png").is_file())
116
- self.assertTrue((run_dir / "contact_sheet.png").is_file())
117
- manifest_text = (run_dir / "manifest.json").read_text(encoding="utf-8")
118
- self.assertNotIn("secret-test-key", manifest_text)
119
- manifest = json.loads(manifest_text)
120
- self.assertEqual(manifest["pricing"]["actual_total"], "0.26")
121
- self.assertEqual([item["request_id"] for item in manifest["outputs"]], ["req_1", "req_2"])
122
- self.assertEqual(session.post_calls[0]["json"]["model"], generate.MODEL)
123
- self.assertTrue(session.post_calls[0]["json"]["stream"])
124
- self.assertEqual(session.post_calls[0]["json"]["aspect_ratio"], "1:1")
125
- self.assertEqual(session.post_calls[0]["headers"]["Authorization"], "Bearer secret-test-key")
126
-
127
- def test_reference_image_uses_openrouter_input_references(self) -> None:
128
- with tempfile.TemporaryDirectory() as temp:
129
- reference = Path(temp) / "reference.png"
130
- reference.write_bytes(png_bytes())
131
- session = FakeSession([image_response()])
132
- result, request_id, endpoint, usage = generate.request_image(
133
- session,
134
- "secret",
135
- "edit prompt",
136
- "64x64",
137
- "high",
138
- "png",
139
- [reference],
140
- )
141
- call = session.post_calls[0]
142
- self.assertEqual(result, png_bytes())
143
- self.assertEqual(request_id, "req_test")
144
- self.assertEqual(usage["cost"], 0.13)
145
- self.assertTrue(endpoint.endswith("/images"))
146
- self.assertEqual(call["json"]["model"], generate.MODEL)
147
- self.assertEqual(call["json"]["input_references"][0]["type"], "image_url")
148
- self.assertTrue(call["json"]["input_references"][0]["image_url"]["url"].startswith("data:image/png;base64,"))
149
-
150
- def test_invalid_preset_fails(self) -> None:
151
- with tempfile.TemporaryDirectory() as temp:
152
- with self.assertRaises(FileNotFoundError):
153
- generate.load_preset("missing", Path(temp))
154
-
155
- def test_missing_environment_key_fails(self) -> None:
156
- with patch.dict(os.environ, {}, clear=True):
157
- with self.assertRaises(KeyError):
158
- generate.read_api_key()
159
-
160
- def test_http_error_fails(self) -> None:
161
- session = FakeSession(model_status=500)
162
- with self.assertRaises(requests.HTTPError):
163
- generate.fetch_model_pricing(session, "secret")
164
-
165
- def test_missing_base64_fails(self) -> None:
166
- response = FakeResponse({"data": [{}], "usage": {"cost": 0.13}})
167
- response.iter_lines = lambda decode_unicode=False: iter(
168
- ("data: " + json.dumps({"type": "image_generation.completed"}),)
169
- )
170
- with self.assertRaises(KeyError):
171
- generate.decode_stream_image(response, (64, 64))
172
-
173
- def test_stream_without_completed_event_fails(self) -> None:
174
- response = FakeResponse({"data": [{"b64_json": base64.b64encode(png_bytes()).decode("ascii")}]})
175
- response.iter_lines = lambda decode_unicode=False: iter(("data: [DONE]",))
176
- with self.assertRaises(ValueError):
177
- generate.decode_stream_image(response, (64, 64))
178
-
179
- def test_promote_records_provenance_and_refuses_overwrite(self) -> None:
180
- with tempfile.TemporaryDirectory() as temp:
181
- root = Path(temp)
182
- run_dir = root / "run"
183
- reference_root = root / "references"
184
- run_dir.mkdir()
185
- image = run_dir / "candidate_01.png"
186
- image.write_bytes(png_bytes())
187
- manifest = {
188
- "provider": "OpenRouter",
189
- "model": generate.MODEL,
190
- "prompt": "prompt",
191
- "parameters": {"size": "64x64", "quality": "high", "output_format": "png", "count": 1},
192
- "pricing": {"currency": "USD", "endpoint_pricing": [], "actual_total": "0"},
193
- "references": [],
194
- "outputs": [{"index": 1, "file": image.name, "request_id": "req_1"}],
195
- }
196
- generate.write_json(run_dir / "manifest.json", manifest)
197
-
198
- target, metadata = generate.promote(run_dir, 1, "reference_v1", reference_root)
199
- self.assertTrue(target.is_file())
200
- self.assertEqual(json.loads(metadata.read_text(encoding="utf-8"))["sha256"], generate.sha256_file(target))
201
- with self.assertRaises(FileExistsError):
202
- generate.promote(run_dir, 1, "reference_v1", reference_root)
203
-
204
-
205
- if __name__ == "__main__":
206
- unittest.main()