WORKFLOW §10 sammelt die Regeln, die messbar schiefgingen — mit Belegordner je Regel: Motiv vor Generierungsgröße, kein negative_prompt, Feld statt Muster, Ramp-Palette für Materialien, --colors 31 bei fester Palette, Symbole auf die Bounding-Box zuschneiden, nur auf Designgröße rastern, OFL mitliefern, zwei Schriften für zwei Aufgaben. falgen.py: --num-images (nur klein/9b), Preis-Cache gegen 429 auf der Pricing-API, Guard für FLUX 3 (kein image_size, kein Seed). Lizenzlog mit den 44 Zeilen dieses Durchgangs.
224 lines
9.5 KiB
Python
Executable file
224 lines
9.5 KiB
Python
Executable file
#!/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]:
|
||
"""Preis aus der fal-Pricing-API — mit 1-Stunden-Cache.
|
||
|
||
Bei Serien (20 Aufrufe hintereinander) antwortet die Pricing-API mit 429;
|
||
der Cache haelt den Lauf am Leben. Frisch geholt wird trotzdem zuerst,
|
||
damit der Preis vor dem Lauf wirklich aktuell ist.
|
||
"""
|
||
cache = Path(os.environ.get("XDG_CACHE_HOME", "~/.cache")).expanduser() / \
|
||
"falgen/preise.json"
|
||
alt: dict = {}
|
||
if cache.exists():
|
||
try:
|
||
alt = json.loads(cache.read_text())
|
||
except json.JSONDecodeError:
|
||
alt = {}
|
||
eintrag = alt.get(endpoint) or {}
|
||
jetzt = dt.datetime.now().timestamp()
|
||
|
||
url = f"https://api.fal.ai/v1/models/pricing?endpoint_id={endpoint}"
|
||
try:
|
||
body, _ = api(url, key)
|
||
except urllib.error.HTTPError as e:
|
||
if e.code == 429 and eintrag.get("unit") is not None:
|
||
minuten = int((jetzt - eintrag.get("t", 0)) / 60)
|
||
print(f" Hinweis: Pricing-API 429 — Preis aus Cache "
|
||
f"({minuten} min alt).")
|
||
return float(eintrag["unit"]), eintrag.get("name", "?")
|
||
if e.code == 429:
|
||
raise SystemExit(" Pricing-API 429 und kein Cache — kurz warten "
|
||
"und erneut versuchen.")
|
||
raise
|
||
|
||
p = (body.get("prices") or [{}])[0]
|
||
if "unit_price" not in p:
|
||
raise SystemExit(f" Kein Preis für {endpoint} gemeldet — Endpoint prüfen.")
|
||
unit, name = float(p["unit_price"]), p.get("unit", "?")
|
||
alt[endpoint] = {"unit": unit, "name": name, "t": jetzt}
|
||
cache.parent.mkdir(parents=True, exist_ok=True)
|
||
cache.write_text(json.dumps(alt, indent=1))
|
||
return unit, name
|
||
|
||
|
||
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("--num-images", type=int, default=1,
|
||
help="Bilder pro Aufruf (nur klein/9b kann bis 4; pro und flux-3 "
|
||
"erzeugen immer genau eins)")
|
||
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
|
||
|
||
# Was der Endpoint wirklich kann (Schemas geprüft 15.11.2026):
|
||
# klein/9b num_images 1-4, num_inference_steps 4-8
|
||
# flux-2-pro kein num_images, kein Guidance/Steps, ein Bild pro Aufruf
|
||
# flux-3 kein image_size (aspect_ratio + resolution), kein seed
|
||
if a.num_images < 1:
|
||
raise SystemExit(" --num-images muss mindestens 1 sein.")
|
||
if a.num_images > 1 and a.endpoint != "fal-ai/flux-2/klein/9b":
|
||
raise SystemExit(f" {a.endpoint} hat kein num_images im Schema — "
|
||
"genau ein Bild pro Aufruf.")
|
||
if a.endpoint == "blackforestlabs/flux-3/text-to-image":
|
||
raise SystemExit(" FLUX 3 kennt kein image_size: Schema ist aspect_ratio + "
|
||
"resolution (768sq|1k|1.5k|2k|4k) und hat keinen seed.")
|
||
|
||
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)
|
||
cost = mp * unit * a.num_images
|
||
per = f"{mp:.4f} MP × {unit} $/{unit_name}"
|
||
if a.num_images > 1:
|
||
per += f" × {a.num_images} Bilder"
|
||
print(f"Modell: {ALLOWLIST[a.endpoint]} ({a.endpoint}) — {per} = {cost:.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
|
||
if a.num_images > 1:
|
||
payload["num_images"] = a.num_images
|
||
|
||
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")
|
||
urls = [i.get("url") for i in (body.get("images") or [])]
|
||
urls = [u for u in urls if u]
|
||
if not urls:
|
||
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)
|
||
raws = []
|
||
for i, url in enumerate(urls, start=1):
|
||
suffix = f"_{i}" if len(urls) > 1 else ""
|
||
raw = out_dir / f"{name}{suffix}.png"
|
||
with urllib.request.urlopen(url, timeout=120) as r, raw.open("wb") as f:
|
||
f.write(r.read())
|
||
raws.append(raw)
|
||
raws[0].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} = {cost:.2f} USD"
|
||
+ (f", {len(urls)} Bilder" if len(urls) > 1 else ""),
|
||
])
|
||
|
||
for raw in raws:
|
||
print(f" Rohbild: {raw}")
|
||
print(f" Anfrage: {raws[0].with_suffix('.json')}")
|
||
print(f" Lizenzlog: 1 Zeile ergänzt (request_id {request_id})")
|
||
return 0
|
||
|
||
|
||
if __name__ == "__main__":
|
||
sys.exit(main())
|