taloria/art/tools/falgen.py
torsten 039064a7c4 art: erste Kreatur über fal und Größenklassen für Sprites (--canvas)
Die Ratte ist der Probelauf für den fal-Pfad auf dem MacBook Air (M4,
24 GB, keine lokale FLUX-GPU): FLUX.2 [klein] 9B über fal, 1024x1024,
Seed 271828, zwei Läufe zu je 0,0063 $. Die Handschrift passt zum lokal
erzeugten Wolf.

Zwei Entscheidungen aus dem Lauf:

- Der Schwanz war zu dick (5-7 px statt 4,7 im Rohbild). Ursache ist die
  Vorlage plus die Pflicht-Kontur, nicht pixelize: das Modell malt eine
  gleich dicke Röhre, und 1 px Kontur je Seite sind bei einer 4-px-Linie
  30-40 % der sichtbaren Dicke. Behoben über den Prompt ("thin ... tapering
  to a point"), eine Variable. --cutout 20/26 getestet und verworfen — die
  Flutfüllung frisst dann die Körpermitte.
- Die Ratte soll deutlich kleiner als der Wolf sein. Canvas bleibt für alle
  Kreaturen 96x96, die Zeichnung darin hat eine Klasse: klein 56, mittel 96,
  groß 128. Dafür neu in pixelize.py: --canvas (bei --size zeichnen, mittig
  auf größeren transparenten Grund setzen). Gemessen: Bbox 47x34 gegen
  74x46 beim Wolf, also 47 % der Fläche.

Dokumentiert in final/Creatures/README (Klassen, Messwerte, cutout-Grenze),
roadmap 0.1 (Entscheidung eingetragen), WORKFLOW §4 (Flag) und prompts §8
(Sprite-Template um "thin and tapering" ergänzt, Klassen statt "eher
64x64"). prep/rat-test/ hält beide Läufe, den Prompt und drei
Vergleichsblätter (Schwanz v1, Größenstufen, Wolf vs. Ratte).

Außerdem: .DS_Store in .gitignore (der Finder legte drei davon in art/),
falgen-Docstring auf das echte Key-Format korrigiert (fal_sk_...,
key_id:key_secret statt hf_...).
2026-11-14 21:43:14 +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=fal_sk_... # Format key_id:key_secret, 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())