taloria/art/tools/falgen.py
torsten 1c0cb6d595 art: Wolf-Test fürs MacBook vorbereitet — falgen, vergleich, SDXL-Jobs
Ziel: auf dem Air (M4, 24 GB) prüfen, ob Kampf-Sprites zur bestehenden Serie
passen — über fal (0,6 Cent/Bild) oder SDXL lokal (0 €). Vergleichsbasis ist
der vorhandene Wolf (FLUX.2 klein 9B, Seed 271828), Prompt wörtlich derselbe.

Damit die zwei Regeln aus AGENTS.md auf einem fremden Rechner nicht an der
Tipparbeit scheitern, sind sie jetzt Werkzeug statt Disziplin:

- art/tools/falgen.py: nur die vier Allowlist-Endpoints, Preis vorab über die
  fal-Pricing-API (Modell + Preis in einer Zeile), Rohbild in die Workbench,
  Request-JSON daneben, Lizenzzeile mit request_id automatisch. Nur stdlib.
- art/tools/vergleich.py: beschriftetes Vergleichsblatt, alle Bilder auf
  gleiche Breite (nearest) — der Code, der bisher dreimal inline stand.
- art/workflows/sdxl_wolf_s{271828,314159,880417}.json: API-Format,
  1024x1024, 32 Steps, CFG 6.5, dpmpp_2m/karras, gegen die lokale ComfyUI
  validiert (valid, 0 Fehler).
- art/prep/wolf-test/: Testplan mit beiden Wegen, Abnahmekriterien und dem
  Prompt als prompt.txt — die Kommandos laufen unverändert auf beiden Rechnern.
- art/SETUP.md §4.1: fal-Weg ohne ComfyUI für den Mac; art/README: die zwei
  Werkzeuge in der Übersicht
- license-log.csv: eine Zeile für den Werkzeug-Smoke-Test (256x256, 0,0004 $)

Der fal-Pfad ist end-to-end geprüft (Pricing, Aufruf, Download, Logzeile),
der SDXL-Graph validiert, aber auf dem Air noch nicht gelaufen.
2026-11-14 20:58:04 +01:00

163 lines
6.8 KiB
Python
Executable file
Raw Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

#!/usr/bin/env python3
"""Bild über einen fal.ai-Endpoint erzeugen — Allowlist, Preis, Rohbild, Lizenzlog.
Der Grund für dieses Werkzeug: auf einem Rechner ohne nutzbare lokale GPU
(MacBook Air, 24 GB) ist fal der einzige Weg zu FLUX.2. Damit dabei die zwei
Regeln aus `AGENTS.md` nicht an der Tipparbeit scheitern, sind sie hier
verdrahtet:
* **Allowlist** — nur die vier freigegebenen Endpoints, keine Ausnahmen.
* **Preis vor dem Lauf** — `estimate_cost` über die fal-Pricing-API, mit dem
echten Input; Modell und Preis in einer Zeile.
* **Lizenzlog** — jede Erzeugung schreibt ihre Zeile nach `art/license-log.csv`
(`datum,endpoint_id,request_id,prompt,seed,lizenz`), mit `request_id` aus dem
Antwort-Header.
export FAL_KEY=hf_... # nie ins Repo
python3 art/tools/falgen.py \\
--prompt-file prompts/wolf.txt --endpoint fal-ai/flux-2/klein/9b \\
--size 1024x1024 --seed 271828 --kategorie Creatures --name monster_wolf_s271828
Das Rohbild landet in `$WORKBENCH/assets/raw/<Kategorie>/` (Vorgabe
`~/Dokumente/workbench_taloria`), die exakte Anfrage als `.json` daneben —
damit ist der Lauf ohne Modell reproduzierbar. Danach wie immer `pixelize.py`.
--dry-run nur Allowlist + Preis, kein Aufruf, keine Kosten.
"""
from __future__ import annotations
import argparse
import csv
import datetime as dt
import json
import os
import sys
import urllib.error
import urllib.request
from pathlib import Path
ART = Path(__file__).resolve().parent.parent
LICENSE_LOG = ART / "license-log.csv"
# Endpoints aus AGENTS.md. Preis wird zur Laufzeit geholt, nicht hier gepflegt.
ALLOWLIST = {
"fal-ai/flux-2-pro": "FLUX.2 [pro]",
"blackforestlabs/flux-3/text-to-image": "FLUX.3",
"fal-ai/flux-2/klein/9b": "FLUX.2 [klein] 9B",
"fal-ai/flux/schnell": "FLUX.1 [schnell]",
}
LICENSES = {
"fal-ai/flux-2-pro": "FLUX.2 [pro] über fal.ai (BFL Non-Commercial License: "
"Gewichte/Selbsthosting; Outputs nach §2d frei nutzbar, "
"keine IP-Indemnity)",
"blackforestlabs/flux-3/text-to-image": "FLUX.3 über fal.ai (BFL-Lizenz; "
"Outputs frei nutzbar, keine IP-Indemnity)",
"fal-ai/flux-2/klein/9b": "FLUX.2 [klein] 9B über fal.ai (BFL Non-Commercial "
"License: Gewichte/Selbsthosting; Outputs nach §2d frei "
"nutzbar, keine IP-Indemnity)",
"fal-ai/flux/schnell": "FLUX.1 [schnell] über fal.ai (Apache 2.0)",
}
def api(url: str, key: str, payload: dict | None = None) -> tuple[dict, dict]:
data = json.dumps(payload).encode() if payload is not None else None
req = urllib.request.Request(url, data=data, headers={
"Authorization": f"Key {key}",
"Content-Type": "application/json",
})
with urllib.request.urlopen(req, timeout=180) as r:
return json.loads(r.read().decode()), dict(r.headers)
def price_of(endpoint: str, key: str) -> tuple[float, str]:
url = f"https://api.fal.ai/v1/models/pricing?endpoint_id={endpoint}"
body, _ = api(url, key)
p = (body.get("prices") or [{}])[0]
if "unit_price" not in p:
raise SystemExit(f" Kein Preis für {endpoint} gemeldet — Endpoint prüfen.")
return float(p["unit_price"]), p.get("unit", "?")
def parse_size(text: str) -> tuple[int, int]:
try:
w, h = (int(v) for v in text.lower().split("x"))
except ValueError:
raise SystemExit(f" --size erwartet BREITExHOEHE, nicht {text!r}")
if w % 16 or h % 16:
print(f" Hinweis: {w}x{h} ist kein Vielfaches von 16 — fal rundet ggf.")
return w, h
def main(argv: list[str] | None = None) -> int:
ap = argparse.ArgumentParser(description=__doc__,
formatter_class=argparse.RawDescriptionHelpFormatter)
ap.add_argument("--prompt")
ap.add_argument("--prompt-file", type=Path)
ap.add_argument("--endpoint", required=True, choices=sorted(ALLOWLIST))
ap.add_argument("--size", default="1024x1024")
ap.add_argument("--seed", type=int)
ap.add_argument("--kategorie", default="Pictures",
help="Workbench-Ordner unter assets/raw/ (Default: Pictures)")
ap.add_argument("--name", help="Dateiname ohne .png (Default: aus Endpoint+Seed)")
ap.add_argument("--out-dir", type=Path,
help="Zielordner für das Rohbild (Default: Workbench)")
ap.add_argument("--dry-run", action="store_true", help="nur Preis, kein Aufruf")
a = ap.parse_args(argv)
if bool(a.prompt) == bool(a.prompt_file):
raise SystemExit(" Genau eines von --prompt / --prompt-file angeben.")
prompt = a.prompt if a.prompt else a.prompt_file.read_text().strip()
w, h = parse_size(a.size)
mp = w * h / 1_000_000
key = os.environ.get("FAL_KEY", "").strip()
if not key:
raise SystemExit(" FAL_KEY fehlt. `export FAL_KEY=...` (nicht ins Repo schreiben).")
unit, unit_name = price_of(a.endpoint, key)
print(f"Modell: {ALLOWLIST[a.endpoint]} ({a.endpoint}) — "
f"{mp:.4f} MP × {unit} $/{unit_name} = {mp * unit:.4f} $")
if a.dry_run:
print(" (dry-run: nichts erzeugt, nichts berechnet)")
return 0
payload = {"prompt": prompt, "image_size": {"width": w, "height": h},
"output_format": "png"}
if a.seed is not None:
payload["seed"] = a.seed
body, headers = api(f"https://fal.run/{a.endpoint}", key, payload)
request_id = headers.get("x-fal-request-id") or headers.get("X-Fal-Request-Id")
units = headers.get("x-fal-billable-units") or headers.get("X-Fal-Billable-Units")
url = (body.get("images") or [{}])[0].get("url")
if not url:
raise SystemExit(f" Antwort ohne Bild: {json.dumps(body)[:300]}")
name = a.name or f"fal_{a.endpoint.split('/')[-1]}" + (
f"_s{a.seed}" if a.seed is not None else "")
out_dir = a.out_dir or (Path(os.environ.get(
"WORKBENCH", "~/Dokumente/workbench_taloria")).expanduser()
/ "assets" / "raw" / a.kategorie)
out_dir.mkdir(parents=True, exist_ok=True)
raw = out_dir / f"{name}.png"
with urllib.request.urlopen(url, timeout=120) as r, raw.open("wb") as f:
f.write(r.read())
raw.with_suffix(".json").write_text(json.dumps(payload, indent=1))
with LICENSE_LOG.open("a", newline="") as f:
csv.writer(f, quoting=csv.QUOTE_MINIMAL).writerow([
dt.date.today().isoformat(), a.endpoint, request_id, prompt,
a.seed if a.seed is not None else "",
f"{LICENSES[a.endpoint]} - {w}x{h}, {mp:.4f} MP, "
f"x-fal-billable-units {units} = {mp * unit:.2f} USD",
])
print(f" Rohbild: {raw}")
print(f" Anfrage: {raw.with_suffix('.json')}")
print(f" Lizenzlog: 1 Zeile ergänzt (request_id {request_id})")
return 0
if __name__ == "__main__":
sys.exit(main())