chore: deploy private lightloom build
Browse filesFiles changed (35)
- .gitignoreAdded+50
- AGENTS.mdAdded+89
- CLAUDE.mdAdded+30
- MASTER_PLAN.mdAdded+85
- README.md+10-8
- app.pyAdded+85
- benchmarks/__init__.pyAdded+1
- benchmarks/gate_g1.pyAdded+301
- benchmarks/results/.gitkeepAdded+1
- benchmarks/results/preflight.jsonAdded+191
- docs/01_ARCHITECTURE.mdAdded+176
- docs/02_MODELS_AND_MATH.mdAdded+93
- docs/03_PROMPTS.mdAdded+154
- docs/04_UI_SPEC.mdAdded+115
- docs/05_EXECUTION_PLAN.mdAdded+67
- docs/06_TESTING_QA.mdAdded+66
- docs/07_RISKS.mdAdded+24
- docs/08_COMPLIANCE_HACKATHON.mdAdded+101
- docs/VERIFY_LOG.mdAdded+13
- packages.txtAdded+1
- pyproject.tomlAdded+21
- requirements.txtAdded+14
- scripts/deploy_private_space.pyAdded+93
- scripts/fetch_gate_g1.pyAdded+53
- scripts/preflight.pyAdded+395
- scripts/release_check.pyAdded+84
- scripts/set_hf_env.ps1Added+55
- src/lightloom/__init__.pyAdded+5
- src/lightloom/compliance/__init__.pyAdded+1
- src/lightloom/compliance/params_ledger.pyAdded+85
- src/lightloom/core/__init__.pyAdded+1
- src/lightloom/core/config.pyAdded+162
- tests/test_compliance.pyAdded+53
- tests/test_gate_g1.pyAdded+16
- tests/test_ledger.pyAdded+19
1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950.env.env.*!.env.example*.token*.secretsecrets/weights/models/checkpoints/*.safetensors*.ckpt*.pt*.pth*.onnx*.gguf*.zip*.7z*.tar*.tar.gz*.mp4*.mov*.wav*.flac*.png*.jpg*.jpeg*.webp*.log
.venv/__pycache__/*.py[cod].pytest_cache/.mypy_cache/.ruff_cache/.coveragehtmlcov/
benchmarks/results/*!benchmarks/results/.gitkeep!benchmarks/results/*.json!benchmarks/results/*.md
assets/showcase/*!assets/showcase/.gitkeepassets/anchors/generated/*frontend/.cache/
vonfig.pylightloom-docs/1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889# AGENTS.md — Lightloom (Build Small Hackathon)
You are the coding agent building **Lightloom**, a voice-driven live-cinema Gradio app for theHugging Face "Build Small" hackathon (deadline **June 15, 2026**). This file is your contract.Read `MASTER_PLAN.md` and `docs/` before writing code. Work in English (code, comments, commits);user-facing UI copy is bilingual ES/EN per `docs/04_UI_SPEC.md`.
---
## 1. HARD RULES (violating any of these disqualifies the project — never trade them for features)
R1. **Parameter cap:** total parameters of ALL runtime models ≤ 32B. Source of truth: `src/lightloom/compliance/params_ledger.py` (every model must be registered there; CI fails if the sum exceeds 32e9 or if a loaded model is missing from the ledger).R2. **Gradio Space:** the deliverable is a Gradio app (`gradio.Server`) hosted as a Space under the `build-small-hackathon` org. Never replace Gradio with a bare FastAPI/Node server.R3. **Off the Grid:** ZERO network calls to external APIs at runtime. All model weights load inside the Space. `tests/test_compliance.py::test_no_cloud_apis` greps runtime code for forbidden patterns (`api.openai.com`, `api.cohere`, `bfl.ai/api`, `modal.com`, `requests.`/ `httpx.` to non-localhost, `InferenceClient`, `huggingface_hub.InferenceApi`). Downloading weights from the HF Hub at startup IS allowed (it is model loading, not an inference API).R4. **Honesty:** never present mocked output as live generation. The Showcase gallery is always labeled "pre-rendered". Merit badges are claimed in the README ONLY if literally true (see R6). No fabricated benchmark numbers — every figure in README/blog comes from a committed benchmark script output.R5. **Submission artifacts:** Space README.md must contain: GitHub repo link, demo video link, social post link, parameter ledger table, license table, badge evidence links. Block the final release if any is missing (`scripts/release_check.py`).R6. **Badge truth conditions:** Off-the-Grid = R3 holds. Well-Tuned = our LoRA published on the Hub AND loaded at runtime. Off-Brand = custom `gr.Server` frontend shipped. Llama-Champion = at least one runtime model actually served through llama.cpp in the shipped app (if gate G3 forces the Director onto GPU transformers AND Aya is disabled, DO NOT claim this badge). Sharing-is-Caring = director traces dataset published. Field-Notes = blog post published.R7. **Codex attribution (OpenAI Track):** all code changes go through Codex with its default attribution preserved. NEVER squash, rebase-rewrite, or re-author commits in a way that strips Codex attribution. Public GitHub repo from commit #1.R8. **Copyright:** demo narration texts are original or public domain (pre-1900 poetry OK). No song lyrics, no copyrighted characters in prompts, no brand logos in UI.
## 2. AGENT ROLES (operate as one role per session; declare the role in the first commit of the session)
- **R-PIPE (Pipeline Engineer):** owns `src/lightloom/{audio_in,director,translate,paint,depth, sound,core}`. DoD: unit tests green, latency within budget (docs/02 §6), gates G1–G5 scripts.- **R-FRONT (Frontend Cinematographer):** owns `frontend/` + `app.py` route wiring. DoD: UI spec docs/04 implemented pixel-true, reduced-motion toggle works, judge-sim passes.- **R-MLOPS (Trainer):** owns `training/` (Modal LoRA job, captions, publish-to-Hub script). DoD: LoRA repo public on Hub with model card, loadable by `paint/lora.py`.- **R-QA (QA & Compliance Auditor):** owns `tests/`, `benchmarks/`, `scripts/release_check.py`. Adversarial mindset: try to break rules R1–R8 and the demo. DoD: docs/06 checklists executed.- **R-REL (Release Manager):** owns Space config, README, publishing traces/blog, submission. DoD: docs/08 submission package complete, dry-run as judge in incognito.
Role boundaries are soft for trivial fixes but PRs that mix roles must say why.
## 3. PREFLIGHT (run BEFORE any feature work — `scripts/preflight.py` must print ALL GREEN)
P1. `huggingface_hub.whoami()` → user is a member of org `build-small-hackathon`.P2. Can create/access the Space `build-small-hackathon/lightloom` (or agreed name); SDK=gradio; hardware shows ZeroGPU available; record actual daily quota observed.P3. Secrets present in Space settings: `HF_TOKEN` (read). No other secrets needed at runtime.P4. Local/dev: Python ≥3.10; `pip install -U "git+https://github.com/huggingface/diffusers"`, `transformers>=5.4.0`, `gradio[mcp]` latest, `llama-cpp-python` (prebuilt CPU wheel — if the wheel build fails on the Space image, fall back to a pinned prebuilt wheel URL; log it). `packages.txt` for the Space: `ffmpeg`.P5. Resolve and pin EXACT model repo ids + revisions into `src/lightloom/core/config.py` (candidates listed in docs/02 §1 with `VERIFY:` flags — confirm each card exists, note its license string verbatim into the license table).P6. Disk/cache: estimate total weight download size; if Space build-time download is too slow, switch to lazy download on first request with a "warming up the projector" UI state.P7. Confirm `import spaces` + `@spaces.GPU` works in a hello-world ZeroGPU Space before porting the pipeline.
## 4. CONVENTIONS
- Conventional commits (`feat:`, `fix:`, `bench:`, `docs:`, `compliance:`). Each D1 gate result is committed as `bench(gateN): <metric>=<value>` with the raw script output in `/benchmarks/results/`.- Every module has a docstring stating its parameter count contribution and whether it is runtime or build-time.- Anything not verified against a primary source is marked `# VERIFY:` and listed in `docs/VERIFY_LOG.md` with resolution status. No `VERIFY:` may remain in the release.- Config over constants: all knobs in `core/config.py` (resolution, steps, beat min/max seconds, reference policy, quota guard thresholds).- Errors degrade gracefully to UI states defined in docs/04 §5; never a raw stack trace on stage.
## 5. DEFINITION OF DONE (release)
`scripts/release_check.py` green = R1–R8 verified + docs/06 E2E checklist + docs/08 submissionpackage complete + Space cold-start tested in incognito + Showcase mode reachable with GPU quotaexhausted (simulate by flag).123456789101112131415161718192021222324252627282930# CLAUDE.md — Lightloom (Claude Code entry point)
Read `AGENTS.md` first — it is the binding contract (hard rules R1–R8, roles, preflight,conventions). Everything there applies verbatim. This file adds Claude Code–specific notes.
## Claude Code specifics
1. **Session = role.** Start each session by stating which role you are operating (R-PIPE / R-FRONT / R-MLOPS / R-QA / R-REL) and which work package (WP-xx from `docs/05_EXECUTION_PLAN.md`). Plan with TodoWrite-style task lists per WP; one WP per branch.2. **Codex attribution caveat (rule R7).** The OpenAI Track is judged on commits attributed to Codex. If a change is authored via Claude Code instead, that is fine for the project but it does NOT count toward the OpenAI Track. Strategy: use Codex for the bulk of authored commits; use Claude Code for review, debugging, refactors, and QA — and never rewrite/squash existing Codex-attributed history.3. **Long-running things you must NOT do inline:** ZeroGPU benchmarks (run them in the Space, not locally), Modal LoRA training (kick off via `training/modal_lora/launch.py`, poll, never block a session waiting), large weight downloads (background them, verify checksums after).4. **When uncertain about an API symbol** (e.g., the exact reference-image kwarg of the diffusers Flux2 Klein KV pipeline), do not guess: open the installed package source under `site-packages/diffusers/pipelines/flux2/` and read the signature, then remove the `VERIFY:` tag with a commit citing the file/line.5. **Tests before features** for the Director: the GBNF grammar and SceneState reducer have unit tests written first (they are pure CPU logic and the most fragile contract in the system).6. **Never** edit `benchmarks/results/*` by hand; results are only produced by running scripts.
## Quick map- Contract: `AGENTS.md` · Plan: `MASTER_PLAN.md` + `docs/05_EXECUTION_PLAN.md`- Build order: F0 preflight → F1 gates → F2 pipeline → F3 frontend → F4 artifacts → F5 submission- If behind schedule, apply cut order F6 (RIFE → ambient audio → Aya → LoRA). Ask before cutting.12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485# LIGHTLOOM — Plan Maestro de Construcción End-to-End### Build Small Hackathon (Hugging Face · Gradio) · Ventana: ahora → 15 jun 2026 · ~30 h efectivas
> Este paquete es la **fuente de verdad** para construir Lightloom con Codex o Claude Code.> El agente de código lee `AGENTS.md` (Codex) / `CLAUDE.md` (Claude Code) como contrato.> Los humanos leen este archivo primero y luego `docs/05_EXECUTION_PLAN.md`.
---
## 0. Qué es Lightloom (definición de producto)
**One-liner:** Habla — y cinco modelos diminutos ruedan tu película: te escuchan, te traducen, dirigen la fotografía, pintan cada plano con memoria, le dan profundidad y le ponen sonido. Sin nube. ~7B de 32B parámetros permitidos.
**Track:** Thousand Token Wood. **Forma:** Gradio app (`gradio.Server`, frontend custom) en un Space ZeroGPU dentro de la org `build-small-hackathon`.
**La tesis** (alineada con el "Chapter Zero" del evento): una orquesta de especialistas pequeños y componibles supera la experiencia de un monolito gigante. Lightloom es esa tesis convertida en producto.
## 1. Objetivos y métricas de éxito (medibles)
| ID | Objetivo | Métrica de éxito | Verificación ||---|---|---|---|| O1 | Sensación de "película en vivo" | TTFF (time-to-first-frame) ≤ 8 s desde que empiezas a hablar; ≤ 2.5 s GPU/beat | `benchmarks/gate_g1.py` || O2 | Continuidad cinematográfica real | Coherencia de personaje/paleta a 12 cuadros encadenados (contact sheet aprobada) | `benchmarks/gate_g4.py` || O3 | Innovación legible para el jurado | La claqueta muestra decisión cut/continuity + cámara + paleta en < 5 s de mirada | Revisión E2E (docs/06) || O4 | Espectacularidad | Paralaje 2.5D activo en todo cuadro + transición + grano + soundbed | Demo checklist || O5 | Cumplimiento total de reglas | 0 APIs cloud en runtime; suma params ≤ 32B; Gradio Space; video+post en README | `tests/test_compliance.py` || O6 | Stacking de premios | Elegibilidad documentada en README para: TTW, OpenBMB, Cohere, OpenAI, Modal, Off-Brand, Best Demo, Bonus Quests | docs/08 checklist || O7 | Robustez de evaluación | App usable por juez sin login, sin mic (Recital), con cuota agotada (Showcase) | Judge-sim script || O8 | Artefacto compartible | Export MP4 con voz del usuario + storyboard PNG funcionando | Test E2E export |
## 2. Restricciones duras (resumen — detalle en docs/08)
1. **≤ 32B parámetros TOTALES** sumando todos los modelos del runtime. Ledger automático obligatorio.2. **App Gradio** alojada como **Space en la org del hackathon**. `gradio.Server` es Gradio (paquete oficial) — válido.3. **Video demo + post social** enlazados en el README del Space antes del cierre (15 jun).4. **Off the Grid (insignia objetivo):** cero llamadas a APIs externas en runtime. Modal/Codex solo en build-time.5. **Honestidad:** nada mock se presenta como funcional; Showcase mode siempre etiquetado; insignias solo si se cumplen de verdad.
## 3. La orquesta (modelos del runtime — detalle y matemática en docs/02)
| Modelo | Rol | Params | Runtime ||---|---|---:|---|| Cohere Transcribe 03-2026 | Oídos (ASR, 14 idiomas) | 2.00B | transformers ≥5.4, GPU || Cohere Tiny Aya Global (gate G2) | Traductor (70+ idiomas → EN) | 3.35B | llama.cpp GGUF Q4, CPU || MiniCPM5-1B | **Director** (SceneState, montaje, cámara) | 1.00B | llama.cpp + GBNF (gate G3) || FLUX.2 [klein] 4B distilled | Pintor (4 pasos, multi-ref KV) | 4.00B | diffusers, ZeroGPU, FP8+AoT || Depth Anything V2 Small | Profundidad (paralaje 2.5D) | 0.025B | transformers, GPU || Stable Audio Open Small | Sonidista (ambientes, EN-only) | 0.341B | stable-audio-tools, GPU || RIFE 4.x lite | Interpolador (solo export MP4) | 0.010B | PyTorch, GPU || Silero VAD | Detector de beats | 0.002B | CPU || **TOTAL** | | **7.38B (10.73B c/ Aya)** | **de 32B** |
Build-time (no cuenta para runtime pero se declara): FLUX.2 klein **base** 4B para entrenar la LoRA en Modal.
## 4. Mapa del paquete de documentación
| Archivo | Contenido | Lo consume ||---|---|---|| `AGENTS.md` | Contrato del agente Codex: reglas, roles, comprobaciones iniciales, convenciones | Codex || `CLAUDE.md` | Idem para Claude Code (delta sobre AGENTS.md) | Claude Code || `docs/01_ARCHITECTURE.md` | Arquitectura, estructura de carpetas, contratos de datos, diagramas mermaid, stack | Agente + humano || `docs/02_MODELS_AND_MATH.md` | IDs exactos de modelos, formulación matemática de cada componente, presupuestos | Agente + humano || `docs/03_PROMPTS.md` | System prompt del Director, gramática GBNF, plantillas de prompts, prompts del agente por WP | Agente || `docs/04_UI_SPEC.md` | Identidad visual, tokens de diseño, pantallas S0–S4, estados, flujos de usuario | Agente (frontend) || `docs/05_EXECUTION_PLAN.md` | Fases F0–F6, work packages, roles, gates D1, cronograma, orden de corte | Humano + agente || `docs/06_TESTING_QA.md` | Benchmarks ZeroGPU (gates), unit/integration/E2E, simulación de juez, presupuestos de rendimiento | Agente (QA) || `docs/07_RISKS.md` | Matriz de riesgos consolidada con mitigaciones y planes B | Humano || `docs/08_COMPLIANCE_HACKATHON.md` | Regla→enforcement, ledger de parámetros, licencias, paquete de submission (README/video/post/blog/trazas) | Agente + humano |
## 5. Fases (resumen — detalle en docs/05)
- **F0 · Preflight (D1 mañana, 1 h):** comprobaciones iniciales automatizadas (org, Space, tokens, versiones, licencias). Sin verde aquí, no se construye nada.- **F1 · Gates empíricos (D1, 4–5 h):** G1 latencia klein · G2 español MiniCPM · G3 tok/s director CPU · G4 deriva 12 cuadros · (G5 audio se mueve a D2). Cada gate = script + commit con cifras.- **F2 · Pipeline core (D2):** Director GBNF + SceneState + cut/continuity · ASR+VAD · Recital · depth · UI provisional Blocks end-to-end.- **F3 · Sala de cine (D3):** frontend `gr.Server` completo (paralaje WebGL, transiciones, grano, claqueta, subtítulos) · audio ambiental · lanzar LoRA en Modal (overnight).- **F4 · Artefactos (D4):** Replay theater · export MP4 (ffmpeg+RIFE) · storyboard · Showcase · LoRA integrada · publicar LoRA/trazas/blog · README · **freeze 20:00**.- **F5 · Submission (D5):** video, post social, enlaces, ensayo de juez, envío antes del mediodía.- **F6 · Contingencia:** orden de corte pre-acordado: 1º RIFE → 2º audio → 3º Aya → 4º LoRA. Jamás: continuidad, paralaje, claqueta, recital, showcase.
## 6. Principios de decisión durante la construcción
1. Cumplimiento de reglas > probabilidad de ganar > demo > diferenciación > elegancia.2. Todo lo no verificado lleva etiqueta `VERIFY:` en el código/doc y se resuelve antes de depender de ello.3. Cada afirmación de la submission (insignias, "local", params) debe ser demostrable con un artefacto del repo.4. Si una pieza amenaza el Must-set, se corta según F6 sin debate.12345678910111213---title: Lightloom Devemoji: 🐢colorFrom: purplecolorTo: indigosdk: gradiosdk_version: 6.17.3python_version: '3.12'app_file: app.pypinned: false---Check out the configuration reference at https://huggingface.co/docs/hub/spaces-config-reference123456789101112131415---title: Lightloom · live narrated cinemaemoji: 🎞️sdk: gradioapp_file: app.py---# LightloomPrivate development build for the Hugging Face Build Small hackathon.Demo video: ⟦PLACEHOLDER⟧ · Social post: ⟦PLACEHOLDER⟧ · Code: ⟦PLACEHOLDER⟧The README will be completed from `docs/08_COMPLIANCE_HACKATHON.md` during WP-13. Placeholders areintentional while privacy mode is active.
12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485"""Lightloom Gradio Server entrypoint.
Parameter contribution: 0B. Runtime endpoints expose app health and privatebenchmark hooks; model loading stays inside explicit benchmark/pipeline calls."""
from __future__ import annotations
import osfrom pathlib import Pathfrom typing import Any
import gradio as grfrom fastapi.responses import HTMLResponse
from lightloom.compliance.params_ledger import entries, total_runtime_paramsfrom lightloom.core.config import CONFIG, LIGHTLOOM_PROFILE
app = gr.Server(title="Lightloom", version="0.1.0")
@app.get("/", response_class=HTMLResponse)def index() -> str: return """ <!doctype html> <html lang="en"> <head> <meta charset="utf-8" /> <meta name="viewport" content="width=device-width, initial-scale=1" /> <title>Lightloom</title> <style> body { margin: 0; min-height: 100vh; display: grid; place-items: center; background: #0A0A0C; color: #F5EFE6; font-family: Inter, system-ui, sans-serif; } main { max-width: 720px; padding: 32px; } h1 { font-family: Georgia, serif; font-size: clamp(42px, 8vw, 92px); margin: 0 0 12px; } a { color: #E8A33D; } </style> </head> <body> <main> <h1>Lightloom</h1> <p>Private build. The projector is being assembled.</p> <p><a href="/health">health</a></p> </main> </body> </html> """
@app.get("/health")def health() -> dict[str, Any]: return { "app": "lightloom", "profile": LIGHTLOOM_PROFILE, "config": { "width": CONFIG.width, "height": CONFIG.height, "flux_dtype": CONFIG.flux_dtype, "flux_aot": CONFIG.flux_aot, "showcase_only": CONFIG.showcase_only, }, "params_total": total_runtime_params(), "params_limit": 32_000_000_000, "ledger": [entry.__dict__ for entry in entries()], "privacy_mode": os.getenv("LIGHTLOOM_PRIVACY_MODE", "1") == "1", }
@app.post("/internal/bench/g1")def run_g1_endpoint() -> dict[str, Any]: if os.getenv("LIGHTLOOM_ENABLE_INTERNAL_BENCH", "0") != "1": return {"ok": False, "error": "internal benchmark endpoint disabled"} from benchmarks.gate_g1 import run
data = run(dry_run=False, reps=int(os.getenv("LIGHTLOOM_G1_REPS", "5")), allow_local=False) return { "ok": True, "data": data, "decision": data["decision"], "result_path": str(Path("benchmarks/results/g1.json")), }
if __name__ == "__main__": app.launch()1"""Benchmark scripts for Lightloom gates."""123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301"""Gate G1: FLUX.2 Klein latency benchmark.
Parameter contribution: 0B. This script loads runtime model weights only whenexecuted in benchmark mode. Local dry-runs are non-authoritative and must neverbe used as Space benchmark numbers."""
from __future__ import annotations
import argparseimport jsonfrom pathlib import Pathimport statisticsimport sysimport timefrom typing import Any
ROOT = Path(__file__).resolve().parents[1]sys.path.insert(0, str(ROOT / "src"))
from lightloom.core.config import MODEL_REFS # noqa: E402
RESULTS_DIR = ROOT / "benchmarks" / "results"DEFAULT_JSON = RESULTS_DIR / "g1.json"DEFAULT_MD = RESULTS_DIR / "g1.md"PROMPT = ( "cinematic illustrated film still, an old lighthouse at the edge of the world, " "stormy dusk, warm lantern glow, painterly texture, volumetric light, 2.39:1 frame")RESOLUTIONS = ((768, 432), (1024, 576))DTYPES = ("fp8", "bf16")AOT_FLAGS = (False, True)
def _percentile(values: list[float], q: float) -> float: if not values: return 0.0 ordered = sorted(values) idx = min(len(ordered) - 1, max(0, round((len(ordered) - 1) * q))) return ordered[idx]
def _torch_dtype(name: str) -> Any: import torch
if name == "bf16": return torch.bfloat16 if name == "fp8": return torch.float8_e4m3fn raise ValueError(f"unsupported dtype: {name}")
def _hardware_profile() -> dict[str, Any]: import os import platform
profile: dict[str, Any] = { "lightloom_profile": os.getenv("LIGHTLOOM_PROFILE", "local"), "space_id": os.getenv("SPACE_ID") or os.getenv("LIGHTLOOM_DEV_SPACE_ID"), "platform": platform.platform(), } try: import torch
profile.update( { "torch": torch.__version__, "cuda": getattr(torch.version, "cuda", None), "cuda_available": bool(torch.cuda.is_available()), "device": torch.cuda.get_device_name(0) if torch.cuda.is_available() else None, "arch_list": list(torch.cuda.get_arch_list()) if torch.cuda.is_available() else [], } ) except Exception as exc: # noqa: BLE001 profile["torch_error"] = f"{type(exc).__name__}: {exc}" return profile
def _dry_run_combination(width: int, height: int, dtype: str, aot: bool, reps: int) -> dict[str, Any]: timings = [] for i in range(reps): start = time.perf_counter() time.sleep(0.002 + (i * 0.0001)) timings.append((time.perf_counter() - start) * 1000) return { "width": width, "height": height, "dtype": dtype, "aot": aot, "status": "dry_run", "authoritative": False, "timings_ms": [round(v, 3) for v in timings], "p50_ms": round(statistics.median(timings), 3), "p95_ms": round(_percentile(timings, 0.95), 3), "note": "plumbing validation only; not a benchmark", }
def _load_pipeline(dtype: str) -> Any: import torch from diffusers import Flux2KleinPipeline
ref = MODEL_REFS["painter"] return Flux2KleinPipeline.from_pretrained( ref.repo_id, revision=ref.revision, torch_dtype=_torch_dtype(dtype), ).to("cuda")
def _maybe_compile(pipe: Any) -> str: import torch
if not hasattr(pipe, "transformer"): return "no_transformer_attr" pipe.transformer = torch.compile(pipe.transformer, mode="reduce-overhead", fullgraph=False) return "torch.compile(reduce-overhead)"
def _benchmark_combination( pipe: Any, width: int, height: int, dtype: str, aot: bool, reps: int,) -> dict[str, Any]: import torch
compile_mode = "off" if aot: compile_mode = _maybe_compile(pipe) generator = torch.Generator(device="cuda").manual_seed(1901) timings: list[float] = [] try: with torch.inference_mode(): pipe( prompt=PROMPT, height=height, width=width, num_inference_steps=4, guidance_scale=1.0, generator=generator, output_type="pil", ) torch.cuda.synchronize() for rep in range(reps): generator = torch.Generator(device="cuda").manual_seed(1901 + rep) start = time.perf_counter() pipe( prompt=PROMPT, height=height, width=width, num_inference_steps=4, guidance_scale=1.0, generator=generator, output_type="pil", ) torch.cuda.synchronize() timings.append((time.perf_counter() - start) * 1000) return { "width": width, "height": height, "dtype": dtype, "aot": aot, "status": "ok", "authoritative": True, "compile_mode": compile_mode, "timings_ms": [round(v, 3) for v in timings], "p50_ms": round(statistics.median(timings), 3), "p95_ms": round(_percentile(timings, 0.95), 3), } except Exception as exc: # noqa: BLE001 return { "width": width, "height": height, "dtype": dtype, "aot": aot, "status": "failed", "authoritative": True, "compile_mode": compile_mode, "error": f"{type(exc).__name__}: {exc}", }
def _decide(results: list[dict[str, Any]]) -> dict[str, Any]: successful = [item for item in results if item.get("status") == "ok" and item.get("authoritative")] if not successful: return {"status": "blocked", "reason": "no authoritative successful G1 run"} by_resolution = { (item["width"], item["height"]): item for item in sorted(successful, key=lambda x: x["p50_ms"]) if item["dtype"] == "fp8" } high = by_resolution.get((1024, 576)) low = by_resolution.get((768, 432)) if high and high["p50_ms"] <= 1800: return {"status": "pass", "resolution": [1024, 576], "selected": high} if low and low["p50_ms"] <= 3000: return {"status": "fallback", "resolution": [768, 432], "selected": low} return {"status": "fallback_polaroid", "resolution": [768, 432], "selected": low or high}
def _write_markdown(path: Path, data: dict[str, Any]) -> None: rows = [ "# Gate G1 Results", "", f"Authoritative: `{data['authoritative']}`", f"Hardware profile: `{data['hardware_profile'].get('lightloom_profile')}`", "", "| Resolution | dtype | AoT | status | p50 ms | p95 ms |", "|---|---|---:|---|---:|---:|", ] for item in data["results"]: rows.append( "| {w}x{h} | {dtype} | {aot} | {status} | {p50} | {p95} |".format( w=item["width"], h=item["height"], dtype=item["dtype"], aot="yes" if item["aot"] else "no", status=item["status"], p50=item.get("p50_ms", ""), p95=item.get("p95_ms", ""), ) ) rows.extend(["", f"Decision: `{data['decision']['status']}`"]) path.write_text("\n".join(rows) + "\n", encoding="utf-8")
def run(dry_run: bool, reps: int, allow_local: bool) -> dict[str, Any]: import os
profile = os.getenv("LIGHTLOOM_PROFILE", "local") if not dry_run and profile != "space" and not allow_local: raise SystemExit( "Refusing to run G1 benchmark outside LIGHTLOOM_PROFILE=space. " "Use --dry-run for plumbing or --allow-local for private debugging; " "local timings are non-authoritative." ) RESULTS_DIR.mkdir(parents=True, exist_ok=True) results: list[dict[str, Any]] = [] if dry_run: for width, height in RESOLUTIONS: for dtype in DTYPES: for aot in AOT_FLAGS: results.append(_dry_run_combination(width, height, dtype, aot, reps)) else: for dtype in DTYPES: try: pipe = _load_pipeline(dtype) except Exception as exc: # noqa: BLE001 for width, height in RESOLUTIONS: for aot in AOT_FLAGS: results.append( { "width": width, "height": height, "dtype": dtype, "aot": aot, "status": "failed", "authoritative": profile == "space", "error": f"load failed: {type(exc).__name__}: {exc}", } ) continue for width, height in RESOLUTIONS: for aot in AOT_FLAGS: results.append(_benchmark_combination(pipe, width, height, dtype, aot, reps)) del pipe data = { "schema_version": 1, "gate": "G1", "generated_at": time.strftime("%Y-%m-%dT%H:%M:%SZ", time.gmtime()), "authoritative": (not dry_run and profile == "space"), "hardware_profile": _hardware_profile(), "reps": reps, "prompt": PROMPT, "results": results, "decision": _decide(results), } DEFAULT_JSON.write_text(json.dumps(data, indent=2, sort_keys=True) + "\n", encoding="utf-8") _write_markdown(DEFAULT_MD, data) return data
def main() -> int: parser = argparse.ArgumentParser() parser.add_argument("--dry-run", action="store_true") parser.add_argument("--allow-local", action="store_true") parser.add_argument("--reps", type=int, default=5) args = parser.parse_args() data = run(dry_run=args.dry_run, reps=args.reps, allow_local=args.allow_local) print(f"G1 wrote {DEFAULT_JSON}") print(f"G1 decision: {data['decision']['status']}") if args.dry_run: return 0 return 0 if data["decision"]["status"] in {"pass", "fallback", "fallback_polaroid"} else 1
if __name__ == "__main__": raise SystemExit(main())1
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191{
"all_green": true,
"checks": [
{
"evidence": {
"org_present": true,
"required_org": "build-small-hackathon",
"user": "Efradeca"
},
"message": "authenticated user is a member of the hackathon org",
"name": "P1 org membership",
"ok": true
},
{
"evidence": {
"created_or_reused": true,
"hardware": "None",
"privacy": "private",
"requested_hardware": "zero-a10g",
"sdk": "None",
"space_id": "Efradeca/lightloom-dev",
"stage": "NO_APP_FILE"
},
"message": "private dev Space exists and appears to be ZeroGPU/Gradio",
"name": "P2 private ZeroGPU Space",
"ok": true
},
{
"evidence": {
"secret_names_only": [
"HF_TOKEN"
]
},
"message": "read token env var is available for configuring the Space secret",
"name": "P3 runtime secret contract",
"ok": true
},
{
"evidence": {
"executable": "C:\\Users\\dynam\\Documents\\CodingProjects\\Lightloom\\.venv\\Scripts\\python.exe",
"imports": {
"diffusers": {
"detail": "0.39.0.dev0",
"ok": true
},
"gradio": {
"detail": "6.17.3",
"ok": true
},
"huggingface_hub": {
"detail": "1.18.0",
"ok": true
},
"llama_cpp": {
"detail": "0.3.28",
"ok": true
},
"torch": {
"detail": "2.11.0+cu128",
"ok": true
},
"transformers": {
"detail": "5.11.0",
"ok": true
}
},
"packages_txt_has_ffmpeg": true,
"platform": "Windows-11-10.0.26200-SP0",
"python": "3.12.10 (tags/v3.12.10:0cc8128, Apr 8 2025, 12:21:36) [MSC v.1943 64 bit (AMD64)]",
"torch": {
"arch_list": [
"sm_75",
"sm_80",
"sm_86",
"sm_90",
"sm_100",
"sm_120"
],
"cuda_available": true,
"cuda_kernel_smoke": true,
"cuda_version": "12.8",
"sm_120_supported": true,
"torch": "2.11.0+cu128"
}
},
"message": "Python, required imports, and local CUDA smoke check are available",
"name": "P4 local versions",
"ok": true
},
{
"evidence": {
"failures": {},
"local_aot": false,
"local_flux_dtype": "fp8",
"local_resolution": [
768,
432
],
"profile": "local",
"resolved": {
"asr": {
"license": "apache-2.0",
"private": false,
"repo_id": "CohereLabs/cohere-transcribe-03-2026",
"sha": "b1eacc2686a3d08ceaae5f24a88b1d519620bc09"
},
"depth": {
"license": "apache-2.0",
"private": false,
"repo_id": "depth-anything/Depth-Anything-V2-Small-hf",
"sha": "5426e4f0f36572d16453bbda7a8389317b1bef99"
},
"director": {
"license": "apache-2.0",
"private": false,
"repo_id": "openbmb/MiniCPM5-1B",
"sha": "4e9de7a0778dc1c362e983e6858f0e77542cbdca"
},
"painter": {
"license": "apache-2.0",
"private": false,
"repo_id": "black-forest-labs/FLUX.2-klein-4B",
"sha": "e7b7dc27f91deacad38e78976d1f2b499d76a294"
},
"painter_base_train": {
"license": "apache-2.0",
"private": false,
"repo_id": "black-forest-labs/FLUX.2-klein-base-4B",
"sha": "a3b4f4849157f664bdbc776fd7453c2783562f4d"
},
"rife": {
"license": "VERIFY",
"note": "GitHub repo; checkpoint license remains VERIFY until selected.",
"repo_id": "hzwer/Practical-RIFE"
},
"sound": {
"license": "other",
"private": false,
"repo_id": "stabilityai/stable-audio-open-small",
"sha": "dc620d91535857b72ebb59b4ca45978db6d417f5"
},
"translator": {
"license": "cc-by-nc-4.0",
"private": false,
"repo_id": "CohereLabs/tiny-aya-global-GGUF",
"sha": "a602ea7eeec3a4ad6f77a1b8cf6a53512824922b"
},
"vad": {
"license": "mit",
"private": false,
"repo_id": "onnx-community/silero-vad",
"sha": "e71cae966052b992a7eca6b17738916ce0eca4ec"
}
}
},
"message": "model cards resolved",
"name": "P5 model cards",
"ok": true
},
{
"evidence": {
"estimated_runtime_weights_gb": 20,
"free_gb": 317.27
},
"message": "local disk has room for iterative caches",
"name": "P6 disk/cache",
"ok": true
},
{
"evidence": {
"detail": "installed"
},
"message": "spaces package imports",
"name": "P7 spaces decorator",
"ok": true
},
{
"evidence": {
"match_files": []
},
"message": "no HF token patterns in tracked files",
"name": "secret scan",
"ok": true
}
],
"elapsed_s": 7.365,
"generated_at": "2026-06-11T19:16:39Z",
"hardware_profile": "local",
"privacy_mode": true,
"schema_version": 1
}123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176# 01 · ARQUITECTURA — Lightloom
## 1. Stack
| Capa | Tecnología | Nota ||---|---|---|| Hosting | HF Space (org `build-small-hackathon`), SDK Gradio, hardware ZeroGPU (slice H200, 70GB) | Regla R2 || Backend | `gradio.Server` (FastAPI extendido: colas, SSE streaming, ZeroGPU, compat. gradio_client) | Patrón validado por blog oficial de Gradio || Inferencia GPU | PyTorch + diffusers (git) + transformers ≥5.4 + stable-audio-tools, dentro de funciones `@spaces.GPU` | FP8 + AoT compile (blog zerogpu-aoti) || Inferencia CPU | llama.cpp (`llama-cpp-python`, wheel CPU) para Director (gate G3) y Aya (gate G2); Silero VAD | GBNF grammar || Frontend | HTML/CSS/JS vanilla + WebGL2 (shaders propios: paralaje, grano; transiciones estilo gl-transitions) servido por `gr.Server` en `/` | Sin framework → cero build step, carga instantánea || Export | ffmpeg (vía `packages.txt`) + RIFE (PyTorch) | Solo en export, no en vivo || Entrenamiento (build-time) | Modal: LoRA sobre FLUX.2 klein **base** 4B → publicar en Hub | No es runtime |
## 2. Estructura de carpetas (crear tal cual)
```lightloom/├── AGENTS.md · CLAUDE.md · MASTER_PLAN.md · README.md (template en docs/08)├── app.py # entrypoint gr.Server: rutas, api endpoints, estáticos├── requirements.txt · packages.txt (ffmpeg) · .gitignore├── src/lightloom/│ ├── core/│ │ ├── config.py # ids+revisions de modelos, knobs, flags (SHOWCASE_ONLY, etc.)│ │ ├── session.py # estado por sesión: Film (beats, frames, audio refs)│ │ ├── beats.py # segmentación VAD → Beat│ │ └── budget.py # contador de segundos GPU por sesión + quota guard│ ├── audio_in/ (vad.py, asr.py)│ ├── translate/ (aya.py) # condicional gate G2│ ├── director/ (state.py, director.py, grammar.gbnf, schema.py)│ ├── paint/ (klein.py, lora.py, anchors.py)│ ├── depth/ (depth.py)│ ├── sound/ (ambient.py) # condicional gate G5│ ├── export/ (rife.py, ffmpeg_mux.py, storyboard.py)│ └── compliance/(params_ledger.py, offgrid_check.py)├── frontend/│ ├── index.html│ ├── css/ (tokens.css, stage.css)│ └── js/ (api.js, recorder.js, stage.js, parallax.js, transitions.js,│ slate.js, subtitles.js, audio_mix.js, theater.js, showcase.js)├── benchmarks/ (gate_g1..g5.py, results/) # resultados solo por ejecución├── tests/ (test_grammar.py, test_state.py, test_beats.py, test_compliance.py,│ test_ledger.py, golden/poema_faro.txt)├── training/modal_lora/ (launch.py, train.py, captions/, publish.py)├── assets/ (anchors/ fonts/(OFL only) showcase/ ui/)├── scripts/ (preflight.py, build_space.sh, publish_traces.py, release_check.py)└── docs/ (este paquete + VERIFY_LOG.md)```
## 3. Contratos de datos (la columna vertebral — escribir tests primero)
```python# Beat — unidad de narración detectada por VADBeat = {id:int, t_start:float, t_end:float, audio_path:str, lang:str, text_raw:str, text_en:str}
# SceneState — memoria del Director (persistente entre beats)SceneState = {scene_id:int, characters:[str], setting:str, era:str, lighting:str, palette:[hex,hex,hex], mood:str, motifs:[str]}
# Shot — salida del Director por beat (validada por GBNF + pydantic)Shot = {decision:"cut"|"continuity", shot_scale:"ECU"|"CU"|"MS"|"WS"|"EWS", camera_move:"static"|"dolly_in"|"dolly_out"|"pan_left"|"pan_right"|"tilt_up"|"crane_down", lighting:str, palette:[hex,hex,hex], image_prompt_en:str, ambient_prompt_en:str, transition:"hard_cut"|"crossfade"|"wipe_left"|"iris"}
# Frame — resultado del Pintor + ProfundidadFrame = {beat_id:int, image_path:str, depth_path:str, seed:int, refs_used:[str], gen_ms:int, audio_bed_path:str|None}
# Film — sesión completa (alimenta Replay, Export y Trazas)Film = {session_id:str, lang:str, beats:[Beat], shots:[Shot], frames:[Frame], narration_audio_path:str|None, created_at:iso}```
Las **trazas** publicadas (Sharing is Caring) son `Film` serializado menos audio del usuario(privacidad): solo nuestros demos consentidos van con audio.
## 4. Estrategia ZeroGPU (crítica — leer antes de tocar `paint/`)
1. **Carga:** pipelines se instancian en el proceso principal en CPU al arrancar; dentro de cada función `@spaces.GPU(duration=...)` se mueven/usan en CUDA. Mantener UNA función GPU por beat que encadene ASR→imagen→depth→audio para pagar un solo ciclo de asignación.2. **Optimización:** checkpoint FP8 de klein + compilación ahead-of-time según el blog oficial `zerogpu-aoti` (1.3–1.8× en modelos clase Flux). El artefacto AoT se construye una vez (script `paint/aot_build.py`) y se cachea.3. **Presupuesto:** `core/budget.py` contabiliza segundos GPU por sesión; al superar `SESSION_GPU_BUDGET` (config, ~90 s) la UI ofrece Replay/Export y sugiere Showcase. Nunca cortar a mitad de beat.4. **Quota guard:** si la asignación ZeroGPU falla (cuota global), el backend emite estado `quota_exceeded` → frontend muestra S3 Showcase con honestidad ("la sala está llena…").5. **Concurrencia:** `concurrency_limit=1` por sesión en endpoints GPU; cola Gradio visible como estado "esperando proyector" en UI.
## 5. Endpoints `gr.Server` (app.py)
| Ruta | Tipo | Función ||---|---|---|| `GET /` | estático | `frontend/index.html` (la Sala) || `@app.api("beat")` | generador (SSE) | entrada: audio chunk o texto + lang + session_id → emite eventos `{stage: transcribed|translated|directed|painted|depth|sound, payload}` por etapa. `# VERIFY:` confirmar API exacta de streaming por generador en la guía server-mode al implementar || `@app.api("recital")` | generador | entrada: poema completo + lang → itera estrofas como beats || `@app.api("export")` | función | session_id → MP4 (RIFE+xfade+mezcla) y storyboard PNG; devuelve URLs de descarga || `@app.api("film")` | función | session_id → JSON `Film` (para Replay y para depurar) || `GET /showcase/*` | estático | películas pre-renderizadas etiquetadas || `GET /health` | función | params ledger + flags + versión (transparencia para jueces) |
## 6. Diagramas (mermaid)
### 6.1 Secuencia de un beat```mermaidsequenceDiagram participant U as Usuario (mic) participant FE as Frontend (Sala) participant BE as gr.Server participant GPU as @spaces.GPU participant DIR as Director (llama.cpp CPU) U->>FE: habla… (MediaRecorder) FE->>FE: VAD detecta pausa → beat FE->>BE: POST beat(audio, lang) BE->>GPU: transcribe(audio, lang) %% Cohere Transcribe GPU-->>BE: text_raw BE-->>FE: SSE stage=transcribed (subtítulo) alt lang != EN y Aya activo (G2) BE->>DIR: aya.translate(text_raw) DIR-->>BE: text_en end BE->>DIR: director(SceneState, text_en) + GBNF DIR-->>BE: Shot JSON (cut|continuity, cámara, prompts) BE-->>FE: SSE stage=directed (claqueta) BE->>GPU: klein(prompt, refs=policy(Shot)) + depth + ambient GPU-->>BE: frame.png, depth.png, bed.wav BE-->>FE: SSE stage=painted (transición + paralaje + soundbed)```
### 6.2 Máquina de estados de la Sala (frontend)```mermaidstateDiagram-v2 [*] --> Lobby Lobby --> Listening: REC / Recital Listening --> Processing: beat detectado Processing --> Revealing: frame listo Revealing --> Listening: sigue narrando Listening --> Theater: STOP Processing --> ErrorSoft: fallo etapa ErrorSoft --> Listening: reintento/skip beat Lobby --> Showcase: cuota agotada / explorar Theater --> Export Theater --> Lobby```
### 6.3 Despliegue```mermaidflowchart LR subgraph Space[HF Space · ZeroGPU] FE[frontend estático] --- GS[gr.Server] GS --> CPU[llama.cpp: Director(+Aya) · VAD] GS --> G[@spaces.GPU: Transcribe · klein FP8/AoT · DepthV2-S · StableAudio · RIFE(export)] GS --> FF[ffmpeg] end Hub[(HF Hub: pesos · LoRA · trazas · showcase)] --> Space Modal[Modal · build-time LoRA] -.publica.-> Hub GH[(GitHub público · commits Codex)] -.referencia.-> Space```
## 7. Decisiones de arquitectura registradas (ADR breves)
- **ADR-1 · Un solo `@spaces.GPU` por beat** (no por modelo): minimiza overhead de asignación; trade-off: función más larga → fijar `duration` con margen medido en G1.- **ADR-2 · Director en CPU por defecto** (gate G3): llama.cpp-CUDA bajo ZeroGPU no está garantizado (docs: compatibilidad orientada a PyTorch). Fallback transformers-GPU preparado.- **ADR-3 · Frontend sin framework:** elimina riesgo de build en el Space y maximiza control de shaders; el costo (más JS a mano) se paga con módulos pequeños y spec detallada (docs/04).- **ADR-4 · RIFE solo en export:** evita ghosting en vivo y mantiene el presupuesto GPU del beat.- **ADR-5 · Showcase como ciudadano de primera:** la regla del evento asume fallos de GPU en evaluación; diseñarlo desde el día 1, no como parche.123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293# 02 · MODELOS Y MATEMÁTICA — Lightloom
## 1. Registro de modelos (IDs candidatos → confirmar en P5 del preflight y fijar revision)
| Rol | Repo id (candidato) | Estado | Licencia (copiar literal de la card) ||---|---|---|---|| ASR | `CohereLabs/cohere-transcribe-03-2026` | Verificado por preflight P5 | apache-2.0 || Traductor | `CohereLabs/tiny-aya-global-GGUF` (Q4_K_M) | Verificado por preflight P5 | cc-by-nc-4.0 || Director | `openbmb/MiniCPM5-1B` (+ GGUF: `VERIFY:` id exacto del repo GGUF en HF; existe vía Ollama/ModelScope) | Card BF16 verificada por preflight P5 | apache-2.0 || Pintor (runtime) | `black-forest-labs/FLUX.2-klein-4B` (+ checkpoint FP8 oficial) | Verificado por preflight P5 | apache-2.0 || Pintor (entreno) | `black-forest-labs/FLUX.2-klein-base-4B` | Verificado por preflight P5 | apache-2.0 || Profundidad | `depth-anything/Depth-Anything-V2-Small-hf` | Verificado por preflight P5 | apache-2.0 || Sonidista | `stabilityai/stable-audio-open-small` | Verificado por preflight P5 | other (card text: Stability AI Community License) || Interpolador | RIFE 4.x lite (repo `hzwer/Practical-RIFE`) | Verificado (paper+repo) | `VERIFY:` licencia del checkpoint elegido || VAD | `onnx-community/silero-vad` | Verificado por preflight P5 | mit |
Regla: ningún modelo se importa en runtime sin entrada en `compliance/params_ledger.py`(`register(name, params, runtime=True/False, license=...)`). El README publica la tabla generada.
## 2. Matemática por componente (lo que el código implementa — sin inventos)
### 2.1 Segmentación en beats (VAD con histéresis)Silero VAD da probabilidad de voz p_t por ventana (~30 ms). Definimos estado hablando/silencio conhistéresis: entra en habla si p_t > θ_on (0.6), sale si p_t < θ_off (0.35) sostenido τ_sil ≥ 600 ms.Un **beat** se cierra al salir de habla si su duración ∈ [T_min=1.2 s, T_max=12 s]; si supera T_maxse corta en la frontera de silencio más cercana. Justificación: beats ≈ frases/alientos delnarrador → 1 plano por aliento, el ritmo natural del cine narrado.
### 2.2 Generación klein (rectified flow, destilado a 4 pasos)klein es un rectified-flow transformer: define trayectoria lineal x_t = (1−t)·x₀ + t·ε y la redpredice velocidad v_θ(x_t, t, c). Muestreo = integrar dx/dt = v_θ con Euler en una malla de**4 pasos** (versión distilled, guidance_scale=1.0 — valores de la model card oficial). Con FP8 +compilación AoT (blog zerogpu-aoti: 1.3–1.8× en clase Flux) el objetivo es t_img ≤ 1.8 s a1024×576 (16:9 dentro del letterbox 2.39:1; múltiplos de 16 obligatorios — restricción de klein).
### 2.3 Continuidad multi-referencia con caché KVEl pipeline Flux2 Klein KV (docs de diffusers) incorpora tokens de imágenes de referencia en elprimer paso de denoising y **cachea sus proyecciones K/V** para reutilizarlas en los pasossiguientes → coste de referencias ≈ 1 paso en lugar de 4. Política de referencias (decidida porel Director):- `continuity` → refs = [frame_{n−1}, ancla_estilo] (la "memoria" visual deseada; la fuga de textura/paleta documentada se vuelve feature)- `cut` → refs = [ancla_estilo] (rompe la memoria a propósito)Determinismo: seed por escena s_k fija (generator manual) para estabilidad intra-escena; cambiaen cada `cut`.
### 2.4 SceneState como recurrencia estructuradaS_n = f_dir(S_{n−1}, beat_n) donde f_dir es MiniCPM5-1B con salida restringida por GBNF alesquema `Shot` + parche de estado. Propiedad clave testeable: **conservación** — bajo`continuity`, `palette` y `characters` solo cambian si el beat los menciona explícitamente(test unitario con casos golden).
### 2.5 Paralaje 2.5D (shader, frontend)Con mapa de profundidad d(x,y) ∈ [0,1] (Depth Anything V2-S, invertido para que 1=cerca) y undesplazamiento de cámara o(t) ∈ ℝ², el shader muestrea la textura con desplazamiento por píxel: uv' = uv + k · (d(uv) − d_f) · o(t)donde d_f es el plano focal (mediana de d) y k la amplitud (≈0.02–0.04 UV). Trayectorias o(t)por `camera_move` con easing suave e(t)=smoothstep: dolly_in: además escala s(t)=1+0.06·e(t); pan_left: o=(−a·e(t),0); tilt_up: o=(0,+a·e(t)); crane_down: o=(0,−a·e(t)) + s(t) leve; static: micro-drift browniano de amplitud 0.003.Oclusiones: en bordes de alto gradiente |∇d| se aplica blur direccional en la dirección de o(t)(barato, esconde el "estiramiento"). Reduced-motion: k=0, solo crossfades.
### 2.6 Interpolación RIFE (solo export)RIFE estima flujo intermedio para timestep arbitrario t∈(0,1) entre (I₀,I₁) y sintetiza I_t(9.8M params, 16 ms/frame en 2080Ti — en H200 es despreciable). Export: dentro de una escena,entre frames consecutivos generamos t∈{1/8,…,7/8} → 8× densidad → 24 fps percibidos conmicro-movimiento real. Entre escenas (decision=cut) NO se interpola: corte duro o xfade deffmpeg según `transition`.
### 2.7 Mezcla de audio (WebAudio en vivo / ffmpeg en export)Soundbed por escena (Stable Audio Open Small, ~12 s en ~75 ms en GPU clase H100; prompts EN).Mezcla: voz a 0 dBFS de referencia, bed a −16 dB con ducking simple: ganancia_bed(t) =−16 dB − 6 dB·[voz_activa] con ataque 80 ms / release 400 ms. Loop del bed con crossfade de 1 ssi la escena dura > 11 s. Export: ffmpeg `amix` + `volume` reproduce la misma ley.
### 2.8 Presupuesto de GPU y solapamiento (pipelining)Sea por beat: t_asr≈0.3, t_dir(CPU)≈1–2.5 (G3), t_img≤1.8, t_depth≈0.06, t_amb≈0.08 (s).El Director del beat n corre en CPU **mientras** la GPU pinta el beat n−1 ⇒ tiempo de pared porbeat ≈ max(t_dir, t_gpu) + ε, con t_gpu = t_asr+t_img+t_depth+t_amb ≈ 2.2 s.GPU total película de B beats ≈ B·2.2 s (+ export ≈ 2–4 s). Para B=15 ⇒ ~35 s GPU.`core/budget.py` implementa el contador y el corte elegante a SESSION_GPU_BUDGET.
### 2.9 Métrica de deriva (gate G4)Para la cadena de 12 cuadros bajo `continuity`, además del juicio visual (contact sheet),computar paleta dominante por frame (k-means k=3 en Lab) y reportar ΔE76 medio entre framesconsecutivos; umbral orientativo ΔĒ < 25 con ancla+ref, comparado contra baseline sin refs.(Métrica de apoyo, no sustituye el ojo.)
## 3. Qué NO se modela (honestidad técnica para el pitch)- No hay difusión de video: el movimiento es cinematografía 2.5D + interpolación; se dice tal cual.- No hay streaming token-a-token: la unidad es el beat (pausa natural). "Near-live, beat a beat."- La traducción (Aya) optimiza prompts en EN; la transcripción mostrada al usuario es su idioma.123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154# 03 · PROMPTS — Director, gramática, plantillas y prompts del agente
## A. System prompt del DIRECTOR (MiniCPM5-1B, modo No-Think; en inglés)
```textYou are the FILM DIRECTOR inside Lightloom, a live narrated-cinema app. The user narrates astory beat by beat. For EACH beat you receive: (1) the current SCENE STATE (JSON), (2) the newnarration BEAT in English. You output EXACTLY ONE JSON object (the Shot) and nothing else.
Your job is cinematography and montage, not prose:1) DECISION — "continuity" if the beat stays in the same place/time/point-of-view; "cut" if the narration moves to a new location, a time jump, a new POV, or an explicit transition phrase ("meanwhile", "far away", "years later", "but in...").2) CAMERA — pick shot_scale (ECU close detail … EWS vast landscape) and ONE camera_move that serves the emotion: dolly_in = intimacy/tension, dolly_out = loneliness/reveal, pan_left/right = journey, tilt_up = awe/hope, crane_down = descend into scene, static = calm.3) LIGHT & PALETTE — keep lighting and the 3-hex palette STABLE under continuity (only change if the beat changes them: dawn, storm, candle...). On a cut you may restate them for the new scene.4) IMAGE_PROMPT_EN — one vivid, concrete visual sentence (max 55 words): subject(s), action, setting, lighting, atmosphere. Never include style words (style is added by the system). Never include text/captions/logos to render. Keep recurring characters visually consistent by repeating their established physical description from the scene state.5) AMBIENT_PROMPT_EN — max 12 words of diegetic ambience for a sound model (e.g. "gentle waves, distant gulls, wooden creaks, soft wind"). No music with vocals, no song names.6) STATE — return updated "setting" and "characters" so the scene memory stays correct.7) TRANSITION — hard_cut for abrupt change, crossfade for soft continuity, wipe_left for journeys, iris for endings/whimsy.
If the beat is non-visual (pure reflection), film the imagery it evokes. Never refuse, neverexplain, never output anything except the JSON object.```
**Mensaje por beat (user role):**```textSCENE STATE: {scene_state_json}BEAT #{n}: "{beat_text_en}"```
**Few-shot (incluir 1 ejemplo en el prompt; mantenerlo corto):**```textSCENE STATE: {"scene_id":1,"characters":["an old lighthouse keeper, white beard, yellow raincoat"],"setting":"a lighthouse on a cliff at the edge of the world","lighting":"stormy dusk","palette":["#1B2A3A","#C9A227","#6E7B8B"],"mood":"solitary"}BEAT #2: "Every night he climbed the spiral stairs, counting each step like a prayer."→ {"decision":"continuity","shot_scale":"MS","camera_move":"tilt_up","lighting":"stormy dusk","palette":["#1B2A3A","#C9A227","#6E7B8B"],"setting":"inside the lighthouse spiral staircase","characters":["an old lighthouse keeper, white beard, yellow raincoat"],"image_prompt_en":"An old lighthouse keeper in a yellow raincoat climbs a worn spiral staircase,lantern light flickering on stone walls, rain streaking a small window, his hand brushing the rail","ambient_prompt_en":"rain on glass, wind gusts, creaking wooden steps, distant thunder","transition":"crossfade"}```
## B. Gramática GBNF (`src/lightloom/director/grammar.gbnf`)Debe mantenerse 1:1 con `schema.py` (test `test_grammar.py::test_schema_sync` lo verifica).
```gbnfroot ::= "{" ws "\"decision\"" ws ":" ws decision "," ws "\"shot_scale\"" ws ":" ws scale "," ws "\"camera_move\"" ws ":" ws move "," ws "\"lighting\"" ws ":" ws str "," ws "\"palette\"" ws ":" ws palette "," ws "\"setting\"" ws ":" ws str "," ws "\"characters\"" ws ":" ws strlist "," ws "\"image_prompt_en\"" ws ":" ws str "," ws "\"ambient_prompt_en\"" ws ":" ws str "," ws "\"transition\"" ws ":" ws transition ws "}"
decision ::= "\"cut\"" | "\"continuity\""scale ::= "\"ECU\"" | "\"CU\"" | "\"MS\"" | "\"WS\"" | "\"EWS\""move ::= "\"static\"" | "\"dolly_in\"" | "\"dolly_out\"" | "\"pan_left\"" | "\"pan_right\"" | "\"tilt_up\"" | "\"crane_down\""transition ::= "\"hard_cut\"" | "\"crossfade\"" | "\"wipe_left\"" | "\"iris\""palette ::= "[" ws hex ws "," ws hex ws "," ws hex ws "]"hex ::= "\"#" hd hd hd hd hd hd "\""hd ::= [0-9a-fA-F]strlist ::= "[" ws (str (ws "," ws str)*)? ws "]"str ::= "\"" chr* "\""chr ::= [^"\\\x00-\x1F] | "\\" ["\\/bfnrt]ws ::= [ \t\n]*```
Parámetros de generación del Director: temperature 0.4, top_p 0.9, max_tokens 280, No-Think.
## C. Plantilla del prompt de imagen (compuesta por código, no por el modelo)
```{LORA_TRIGGER} cinematic illustrated film still, {image_prompt_en},{shot_scale_phrase}, {lighting}, color palette {palette_names}, painterly texture,volumetric light, 2.39:1 frame```- `LORA_TRIGGER = "lghtlm style"` (si la LoRA está cargada; si no, se omite).- `shot_scale_phrase`: ECU→"extreme close-up" … EWS→"extreme wide establishing shot".- klein distilled: `num_inference_steps=4, guidance_scale=1.0`, seed por escena; refs según política (02 §2.3). `# VERIFY:` nombre exacto del kwarg de referencias en el pipeline KV (leer firma instalada, ADR en CLAUDE.md §4).
## D. Prompt de traducción (Tiny Aya, si gate G2 lo activa)```Translate the following narration fragment into natural, vivid English.Output ONLY the translation, nothing else.Fragment: "{beat_text_raw}"```
## E. LoRA de estilo (Well-Tuned) — espec de datos y captions- **Origen de datos (legalmente limpio):** 60–100 imágenes generadas por NOSOTROS con klein **base** a partir de un tablero de prompts de un único look ("ilustración cinematográfica, gouache + luz volumétrica"), curadas a mano por coherencia. Cero arte de terceros.- **Caption por imagen:** `lghtlm style, {descripción concreta de la escena}` (una frase).- **Objetivo modesto y honesto:** la LoRA es un *ancla de consistencia* de paleta/textura, no un estilo revolucionario. Entrenar en Modal sobre `FLUX.2-klein-base-4B` (`# VERIFY:` script de entrenamiento LoRA disponible para Flux2 en diffusers/ai-toolkit al momento de WP-12; si no hay ruta estable en ≤3 h de trabajo, ejecutar corte F6-4 y documentar).- Publicar en el Hub bajo la org con model card (base, datos, pasos, uso) — evidencia de insignia.
## F. Prompts del AGENTE por work package (pegar al iniciar cada WP)
> Formato común: "Role: <R-XX>. WP: <id>. Read AGENTS.md + docs/<refs>. Deliver <DoD>.> Do not touch files owned by other roles. Mark unknowns with VERIFY and log them."
- **WP-01 Preflight (R-QA):** "Implement `scripts/preflight.py` per AGENTS.md §3 (P1–P7), print ALL GREEN/FAIL table, write results to benchmarks/results/preflight.json. No feature code."- **WP-02 Skeleton (R-PIPE):** "Create folder structure per docs/01 §2, `app.py` gr.Server with `/health`, ledger stub, config with model ids (VERIFY flags), CI: pytest + compliance grep."- **WP-03 Gate G1 (R-PIPE):** "benchmarks/gate_g1.py: klein-4B distilled on ZeroGPU, 4 steps, 768×432 vs 1024×576, FP8 on/off, AoT on/off; commit `bench(g1): ...` with table. Decide resolution per docs/05 gate table."- **WP-04 Gates G2/G3 (R-PIPE):** "Director on llama.cpp CPU with grammar.gbnf: measure tok/s and s/beat over 10 golden beats (5 ES, 5 EN). Judge ES fidelity vs EN. Output decision per gate table; wire fallback (transformers GPU) behind config flag."- **WP-05 Gate G4 (R-PIPE):** "12-frame continuity chain on a golden poem, policy [prev, anchor]; contact sheet PNG + ΔE76 metric (docs/02 §2.9) vs no-ref baseline. Commit images + numbers."- **WP-06 Core pipeline (R-PIPE):** "Implement Beat/SceneState/Shot/Frame contracts + reducer + beats.py (VAD hysteresis) + asr.py + director.py + paint/klein.py + depth.py per docs/01–02. Unit tests first for grammar/state/beats. Recital mode endpoint."- **WP-07 Provisional UI (R-FRONT):** "Minimal gr.Blocks page hitting the same endpoints, for E2E during D2 only; will be replaced by frontend/ — keep it in /dev route."- **WP-08 Cinema frontend (R-FRONT):** "Implement docs/04 S0–S4 exactly: tokens.css, WebGL parallax (math docs/02 §2.5), transitions, grain, slate, subtitles, recorder+VAD client side, SSE consumption, reduced-motion. No frameworks."- **WP-09 Ambient sound (R-PIPE, gate G5):** "stable-audio-tools under @spaces.GPU; per-scene bed; WebAudio ducking law docs/02 §2.7. If integration >3 h or breaks ZeroGPU → cut F6-2."- **WP-10 Replay+Export (R-PIPE/R-FRONT):** "Theater playback synced to recorded narration; export MP4 = keyframes + RIFE in-betweens (intra-scene only) + xfade + audio mix via ffmpeg; storyboard strip PNG."- **WP-11 Showcase+Quota guard (R-FRONT):** "budget.py wiring, quota_exceeded state, showcase gallery from assets/showcase (clearly labeled pre-rendered)."- **WP-12 LoRA (R-MLOPS):** "Per docs/03 §E: generate+curate dataset, Modal train, publish to Hub, integrate via paint/lora.py behind flag, A/B contact sheet with/without."- **WP-13 Traces+Blog (R-REL):** "publish_traces.py (Film minus user audio) → dataset repo; blog post draft from benchmarks/results (Field Notes); update README badges evidence."- **WP-14 Release (R-REL+R-QA):** "release_check.py per AGENTS.md §5; judge-sim per docs/06 §5; freeze; submission package per docs/08."123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115# 04 · UI SPEC — "La Sala" (identidad visual, pantallas, estados, flujos)
Meta: que el jurado de Off-Brand diga "esto no parece Gradio" y el de TTW diga "esto parece cine".Todo se implementa en `frontend/` servido por `gr.Server`. Sin frameworks. Bilingüe ES/EN(toggle; copy literal abajo, EN entre ⟦⟧).
## 1. Identidad visual
- **Concepto:** una sala de proyección íntima de la era del celuloide, habitada por una IA artesana. Oscuridad cálida, no "dark mode tech".- **Tokens (`css/tokens.css`):** - Fondo sala `--bg:#0A0A0C` · marfil texto `--ink:#F5EFE6` · ámbar proyector `--amber:#E8A33D` - rojo REC `--rec:#E0442E` · azul noche `--night:#1B2A3A` · línea `--line:#2A2A30` - Radios: 14px paneles / 999px pills · sombras: halo ámbar suave, nunca azul tech.- **Tipografía (solo OFL, autoalojada en `assets/fonts/`):** Display **Fraunces** (títulos, subtítulos narrados, claqueta). UI **Inter**. Jamás system-default visible.- **Shaders globales:** grano de celuloide animado (ruido por frame, opacidad 0.05), viñeta radial 12%, aberración cromática sutil solo durante transiciones (0.4 s).- **Motion:** easing `cubic-bezier(.4,0,.2,1)`; revelado de cuadro 700 ms; nada parpadea. `prefers-reduced-motion` + toggle manual ⇒ paralaje k=0, solo crossfades, grano estático.- **Layout maestro:** lienzo letterbox **2.39:1** centrado; HUD mínimo en las barras negras: arriba-izq `LIGHTLOOM` (Fraunces, tracking amplio), arriba-der contador `ESCENA 03 · PLANO 07`, abajo subtítulos.
## 2. Pantallas (descripción exacta)
### S0 · Lobby- Fondo: lienzo apagado + haz de proyector volumétrico diagonal (CSS).- Centro: título + tagline "Habla, y mira tu historia volverse cine." ⟦Speak, and watch your story become film.⟧- Dos puertas (cards): **🎙️ Narrar en vivo** ⟦Narrate live⟧ · **📜 Modo recital** ⟦Recital mode⟧ (pegar un poema/cuento). Debajo, discreto: **🎞️ Ver películas de muestra** ⟦Showcase⟧.- Selector de idioma de narración (pill): ES · EN · FR · PT · … (los 14 de Transcribe; default por `navigator.language`). Tooltip: "El modelo de voz no autodetecta idioma." - Al elegir Narrar: solicitud de micrófono con copy cálido ("Necesitamos tu voz para rodar"). Si se deniega → abre Recital con aviso amable.- Footer de transparencia: "7 modelos diminutos · 7.4B/32B parámetros · 100% dentro de este Space" + link a `/health` y a "Acerca de" (S4).
### S1 · El Set (rodaje en vivo)- Lienzo 2.39:1 al centro. Estados visuales del lienzo: - **Escuchando:** punto REC rojo pulsante en HUD + anillo de onda de audio (canvas) respirando alrededor; el lienzo muestra el último cuadro con su paralaje en curso (o negro con haz si es el primero). Subtítulos: palabras transcritas aparecen en Fraunces itálica y se desvanecen a los 4 s. - **Procesando beat:** barra fina ámbar bajo el lienzo con microetapas iluminándose: `OYENDO → TRADUCIENDO → DIRIGIENDO → PINTANDO → REVELANDO` (las que apliquen). Nunca spinner. - **Revelando:** transición elegida por el Director (crossfade/wipe/iris/corte) + inicio del movimiento de cámara 2.5D + entrada del soundbed en fade 1 s.- **La Claqueta** (panel derecho plegable, estética pizarra de rodaje con tiza/ámbar): por beat muestra `PLANO 07 · CONTINUIDAD · MS · dolly-in · luz: crepúsculo tormentoso · ▮▮▮ paleta`. Tap en un plano pasado → lo re-proyecta (sin GPU: usa el frame cacheado).- Controles inferiores (pills): ⏹ **Cortar y ver la película** ⟦Cut & watch⟧ · 🔇 bed on/off · ♿ reducir movimiento · idioma (bloqueado durante rodaje).- HUD inferior-izq: presupuesto discreto "🎬 GPU 23s" (transparencia; se vuelve ámbar al 70%).
### S2 · Teatro (replay + export)- Telón rojo CSS se abre (1.2 s). Reproduce la película: cuadros con su paralaje + transiciones + soundbeds + **tu narración grabada** sincronizada por timestamps de beats.- Controles tipo proyector: play/pausa, scrubber con miniaturas por plano, velocidad 1×/0.75×.- Acciones: **⬇ Descargar película (MP4)** ⟦Download film⟧ (lanza export; barra "revelando copia…"), **🖼 Storyboard** (tira PNG), **🔁 Rodar otra** ⟦Shoot another⟧, **📋 Copiar texto para post social** (genera caption con título sugerido por el Director + hashtags del evento).- Nota visible si export con RIFE está cortado: "export a 12 fps con fundidos" (honestidad).
### S3 · Showcase- Grid de 3–5 películas pre-renderizadas, cada card con sello visible **PRE-RENDERIZADA** ⟦PRE- RENDERED⟧ y su poema fuente (dominio público). Reproductor = mismo Teatro.- Banner superior cuando se llega por cuota: "La sala está llena ahora mismo (cuota de GPU del Space agotada). Mira funciones pasadas o vuelve en un rato — todo lo que ves aquí se generó con esta misma app." ⟦The theater is full right now…⟧
### S4 · Acerca de (overlay)- "La orquesta": tabla de los 7 modelos (nombre, rol con icono, params, licencia) — la misma del README, renderizada bonita. Suma destacada: **7.38B / 32B**.- Insignias obtenidas con link a evidencia (LoRA, trazas, blog). Links: GitHub (commits Codex), Space, video, post. Créditos y agradecimiento a sponsors sin logos de terceros.
## 3. Flujos de usuario (paso a paso)
- **F-A Primera visita narra:** S0 → elige idioma → 🎙️ → permiso mic → S1 escuchando → habla (beat 1) → microetapas → revelado+paralaje+sonido → sigue narrando (beats 2..n; claqueta marca CONTINUIDAD/CORTE) → ⏹ → S2 telón → replay con su voz → descarga MP4 → copia caption → sale.- **F-B Juez sin micrófono:** S0 → 📜 Recital → pega poema (placeholder: soneto de dominio público precargado con botón "usar ejemplo") → "Rodar" → beats por estrofa con los mismos estados → S2.- **F-C Cuota agotada:** cualquier intento de rodar → estado quota_exceeded → S3 con banner honesto → puede ver Teatro de muestras y Acerca de.- **F-D Multilingüe:** F-A con idioma FR/PT/…; subtítulos en idioma original; claqueta muestra además la línea traducida en gris pequeño (transparencia del pipeline).- **F-E Error blando:** una etapa falla → toast ámbar "El plano 5 se veló; seguimos rodando" ⟦Shot 5 got fogged; rolling on⟧ → beat se salta, sesión continúa. Tres fallos seguidos → sugerir Recital/Showcase.
## 4. Estados y copy del sistema (literal)
| Estado | Copy ES (⟦EN⟧) ||---|---|| warming_up | "Encendiendo el proyector…" ⟦Warming up the projector…⟧ (primera carga de pesos) || listening | "Rodando — te escucho." ⟦Rolling — I'm listening.⟧ || translating | "Traduciendo el beat…" || directing | "La directora decide el plano…" ⟦The director calls the shot…⟧ || painting | "Pintando el plano 07…" || revealing | (sin texto: la imagen habla) || quota_warn (70%) | "Queda poca luz en el proyector — considera cortar pronto." || quota_exceeded | banner S3 (arriba) || export_running | "Revelando tu copia…" ⟦Developing your print…⟧ || error_soft | "El plano N se veló; seguimos rodando." |
## 5. Accesibilidad y rendimiento frontend- Subtítulos siempre activos (también sirven de caption). Contraste AA sobre `--bg`.- Toggle reducir-movimiento persistido en localStorage del navegador del usuario.- Imágenes servidas como WebP; precarga del siguiente frame durante el actual; WebGL con fallback a CSS transform (Ken Burns con máscara) si no hay WebGL2.- Móvil: letterbox pasa a 16:9, claqueta como hoja inferior deslizable; probar en judge-sim.12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667# 05 · PLAN DE EJECUCIÓN — Fases, work packages, gates y cronograma
Ventana real: D1=jue 11 (tarde) → D5=lun 15 (mediodía). ~30 h. Regla: cada día termina con algodemostrable y commiteado. El agente declara rol+WP al iniciar sesión (AGENTS.md §2).
## F0 · PREFLIGHT (D1, primera hora — bloqueante)WP-01 (R-QA, 1 h). `scripts/preflight.py` ejecuta P1–P7 de AGENTS.md §3 y escribe`benchmarks/results/preflight.json`. **Sin ALL GREEN no se escribe código de features.**Checklist humano paralelo: cuenta en la org ✔ · crear Space `lightloom` (SDK gradio, ZeroGPU) ✔ ·repo GitHub público creado y enlazado ✔ · primer commit vía Codex ✔.
## F1 · GATES EMPÍRICOS (D1, 4–5 h)
| Gate | WP | Pregunta | Umbral | PASA → | FALLA → ||---|---|---|---|---|---|| G1 | WP-03 | latencia klein 4 pasos (FP8, AoT) | ≤1.8 s/cuadro | 1024×576 | 768×432; >3 s ⇒ estética "revelado polaroid" (la espera se teatraliza) || G2 | WP-04 | fidelidad de dirección con beats en ES sin traducir | juicio 10 casos golden | Aya = toggle | Aya = Must en pipeline || G3 | WP-04 | s/beat del Director en llama.cpp CPU (JSON ~250 tok, No-Think, GBNF) | ≤2.5 s | Director CPU (badge Llama legítimo) | Director GPU transformers; badge solo si Aya-GGUF activo (R6) || G4 | WP-05 | deriva a 12 cuadros con refs [prev, ancla] | contact sheet OK + ΔĒ<25 | política [prev, ancla] | [ancla] + LoRA cargan continuidad || G5 (D2) | WP-09 | stable-audio-tools bajo @spaces.GPU | genera 10 s | audio Should confirmado | corte F6-2 |
Entregable F1: 4 commits `bench(gN): …` + decisiones escritas en `docs/VERIFY_LOG.md`.
## F2 · PIPELINE CORE (D2, 6–7 h)- WP-06 (R-PIPE, 5 h): contratos + reducer + VAD + ASR + Director + klein + depth + Recital. Tests unitarios ANTES en grammar/state/beats. DoD: poema golden → 8 planos coherentes con cortes correctos y depth maps, vía endpoint `recital`.- WP-07 (R-FRONT, 1.5 h): UI provisional gr.Blocks en `/dev` para E2E de hoy.- Cierre D2: G5 ejecutado; si pasa, `ambient.py` integrado al beat.
## F3 · LA SALA (D3, 6–7 h)- WP-08 (R-FRONT, 5–6 h): frontend completo según docs/04 (S0–S4, shaders, claqueta, recorder, SSE). DoD: narras 90 s por mic → película con movimiento y sonido en la Sala.- WP-12 inicio (R-MLOPS, 1.5 h + overnight): dataset de estilo + lanzar LoRA en Modal.- Publicar post social "teaser" del progreso (opcional; fija autoría temprana en la comunidad).
## F4 · ARTEFACTOS Y PUBLICACIONES (D4, 6–7 h) — **FREEZE 20:00**- WP-10 (3 h): Teatro replay sincronizado + export MP4 (RIFE intra-escena + xfade + mezcla) + storyboard.- WP-11 (1 h): budget/quota guard + Showcase con 3 películas generadas por la app.- WP-12 cierre (1 h): LoRA del Hub integrada tras A/B; publicar model card.- WP-13 (1.5 h): trazas → dataset del Hub; blog Field Notes (usar cifras de benchmarks/results); README completo (plantilla docs/08).- R-QA: suite completa + judge-sim. Bugs P0 únicamente tras el freeze.
## F5 · SUBMISSION (D5, 4–6 h — enviar antes del mediodía)1. Grabar video demo (guion docs/08 §4) con OBS sobre el Space real (no localhost).2. Post social con el MP4 exportado por la propia app + caption generado.3. Enlazar video+post+repo en README del Space; `release_check.py` ALL GREEN.4. Ensayo de juez (docs/06 §5) en incógnito y en móvil. 5. Submit. 6. No tocar nada.
## F6 · ORDEN DE CORTE (pre-acordado; aplicar sin debate si un WP amenaza el Must-set)1º RIFE-export (queda xfade 12 fps) → 2º audio ambiental → 3º Aya (demo EN-only) → 4º LoRA.**Nunca se cortan:** continuidad KV, paralaje 2.5D, claqueta, Recital, Showcase, quota guard.
## Cronograma-resumen| Día | Mañana | Tarde | Commit de cierre ||---|---|---|---|| D1 | F0 preflight | F1 gates G1–G4 | `bench(g4): …` + decisiones || D2 | WP-06 tests+core | WP-06 fin + WP-07 + G5 | `feat: recital E2E` || D3 | WP-08 Sala | WP-08 fin + WP-12 lanzar | `feat: live cinema E2E` || D4 | WP-10/11 | WP-12/13 + README + QA | `release-candidate` (freeze) || D5 | video+post+links | judge-sim + SUBMIT | `release` |
## Dependencias críticas entre WPsWP-01→todo · WP-03/04/05→WP-06 (decisiones de config) · WP-06→WP-08/10 · G5→WP-09→WP-10(mezcla)· WP-12 corre en paralelo (no bloquea) · WP-13/14 requieren todo lo anterior.123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566# 06 · TESTING & QA — Benchmarks ZeroGPU, tests y simulación de juez
Principio: ninguna cifra existe sin script; ningún script sin resultado commiteado en`benchmarks/results/` (JSON + PNG cuando aplique). Editar resultados a mano está prohibido.
## 1. Benchmarks ZeroGPU (corren EN el Space, no localmente)
| Script | Mide | Salida ||---|---|---|| `gate_g1.py` | klein distilled: matriz {768×432, 1024×576} × {BF16, FP8} × {AoT on/off}, 5 reps, p50/p95 por cuadro; tiempo de warm-up AoT | `g1.json` + tabla md || `gate_g2.py` | Director con 10 beats golden (5 ES crudos, 5 EN): %JSON válido (debe ser 100 con GBNF), rúbrica humana de fidelidad ES (anotada en el JSON) | `g2.json` || `gate_g3.py` | tok/s y s/beat de MiniCPM5-1B Q4 en CPU del Space (No-Think, GBNF, 250 tok) y en GPU transformers (comparativa) | `g3.json` || `gate_g4.py` | cadena de 12 cuadros del poema golden con política [prev, ancla] vs [ancla] vs sin refs; contact sheets + ΔE76 medio (02 §2.9) | `g4.json` + 3 PNG || `gate_g5.py` | stable-audio-open-small bajo `@spaces.GPU`: 3 prompts ambient, duración y RTF | `g5.json` + wavs || `bench_beat_e2e.py` | beat completo (ASR→…→frame) p50/p95; segundos GPU contabilizados por budget.py vs reales | `beat.json` || `bench_cold_start.py` | tiempo de arranque del Space (descarga+carga) y de primer beat tras reinicio | `cold.json` || `probe_quota.py` | comportamiento al agotar cuota (flag de simulación + 1 prueba real controlada al final de D4) | `quota.json` |
## 2. Tests unitarios (CPU, corren en CI y localmente)- `test_grammar.py`: GBNF acepta los goldens y rechaza 10 malformaciones; `test_schema_sync` (gramática ↔ `schema.py` campo a campo).- `test_state.py`: reducer — conservación de paleta/personajes bajo continuity; reset correcto en cut; merge de characters sin duplicados.- `test_beats.py`: histéresis VAD con audios sintéticos (silencios de 0.3/0.7/1.5 s); límites T_min/T_max; corte en frontera de silencio.- `test_ledger.py`: suma ≤32e9; todo import de modelo registrado; runtime/build-time correcto.- `test_compliance.py`: grep de hosts/SDKs prohibidos en `src/` y `frontend/` (lista AGENTS R3); assert de que `requests/httpx` solo aparecen en `training/` y `scripts/`.- `test_prompt_compose.py`: plantilla de imagen nunca contiene palabras de estilo duplicadas ni el trigger si la LoRA está off; longitud ≤ límite.
## 3. Integración (con GPU, en el Space vía `/dev`)- `it_recital_golden.py`: poema golden (texto en `tests/golden/poema_faro.txt`, dominio público u original) con seeds fijas → genera Film completo → snapshot de: nº de cuts esperados, paletas por escena, y contact sheet para revisión visual versionada.- `it_export.py`: Film golden → MP4 (duración esperada ±5%, pistas de audio presentes, fps) y storyboard PNG (dimensiones, nº de tiles).- `it_quota_guard.py`: con `SESSION_GPU_BUDGET=6s` forzado, la sesión corta elegante a Teatro.
## 4. E2E manual (checklist D4, ejecutar dos veces: desktop + móvil)1. Cold start en incógnito: warming_up visible, lobby < lo que diga `cold.json` + 10%.2. F-A completo narrando 60–90 s en ES: subtítulos, microetapas, claqueta marca al menos un CUT real al cambiar de escenario, paralaje visible, soundbed cambia entre escenas.3. F-B Recital con el ejemplo precargado sin tocar el mic.4. F-D en un segundo idioma.5. Teatro: sync voz-cuadros (deriva < 200 ms perceptual), descarga MP4 reproducible en reproductor externo, storyboard correcto, caption copiable.6. F-E: matar una etapa (flag de inyección de fallo) → toast y continuidad de sesión.7. Reduced-motion on: sin paralaje, app sigue siendo agradable.8. `/health` muestra ledger y flags reales.
## 5. Simulación de juez (D5, antes de enviar — alguien que NO construyó la app)- Dispositivo limpio, sin login HF, link del Space pelado. ¿Entiende qué hacer en <15 s?- Sin micrófono disponible: ¿llega solo al Recital? ¿El ejemplo precargado lo deslumbra?- Cronometrar: tiempo hasta primer "wow" (objetivo <40 s desde abrir el link).- Leer solo el README: ¿quedan claras las 6 insignias con su evidencia, el ledger, el video?- Ver el video sin audio (muchos jueces lo harán): ¿se entiende igual? (subtítulos en el video).
## 6. Presupuestos de rendimiento (fallar el release si se exceden)| Métrica | Presupuesto ||---|---|| p95 beat E2E (sin Aya) | ≤ 6 s pared / ≤ 2.8 s GPU || TTFF desde inicio de habla | ≤ 8 s || Cold start (caché caliente del Hub) | ≤ 120 s con estado warming_up honesto || Peso frontend (sin imágenes) | ≤ 600 KB || Export película 15 beats | ≤ 45 s |123456789101112131415161718192021222324# 07 · RIESGOS Y MITIGACIONES (matriz consolidada de construcción)
| # | Riesgo | P | I | Señal temprana | Mitigación | Plan B ||---|---|---|---|---|---|---|| 1 | Latencia klein > presupuesto en ZeroGPU | M | A | gate G1 | FP8 + AoT + 768×432 + un solo @spaces.GPU por beat | Estética "revelado polaroid": la espera se teatraliza (telón parcial + sonido de proyector) || 2 | `llama-cpp-python` no compila/instala en la imagen del Space | M | M | preflight P4 | wheel CPU prebuilt pineado; probar en hello-world Space antes de F2 | Director y Aya en transformers-GPU; revisar honestidad de badge (R6) || 3 | Deriva visual multi-ref a >10 cuadros | M | A | gate G4 | seed por escena + ancla + prompts con paleta explícita del Director | Política [ancla]+LoRA; continuidad por estado, no por imagen || 4 | Fuga de layout de la ref previa "congela" la composición | M | M | G4 contact sheet | bajar peso ref previa (si el pipeline expone strength `VERIFY:`) o alternar refs [prev]→[prev,ancla] | Solo [ancla] en planos con cambio de encuadre fuerte (heurística por shot_scale) || 5 | gr.Server: streaming SSE por generador no funciona como se asume | B-M | M | WP-02 spike | spike de 30 min con endpoint generador antes de F2 (guía server-mode) | Polling corto a `/film` (degradación invisible para el usuario) || 6 | stable-audio-tools rompe deps o ZeroGPU | M | M | gate G5 | entorno probado en G5 antes de integrar; versión pineada | Corte F6-2: película muda con voz del usuario || 7 | Descarga de pesos lenta → cold start eterno | M | M | bench_cold_start | precache en build del Space si el SDK lo permite; orden de carga lazy (klein primero) | Estado warming_up honesto + Lobby utilizable + Showcase accesible sin GPU || 8 | Cuota ZeroGPU agotada durante evaluación | M | M | probe_quota | budget por sesión + quota guard + Showcase + video demo (regla 3 del evento cubre esto) | Los jueces evalúan por video; README lo explica sin excusas || 9 | MediaRecorder/VAD cliente falla en algún navegador | M | M | E2E móvil | MediaRecorder estándar + VAD en cliente con fallback de VAD en servidor | Botón "enviar beat" manual + Recital siempre visible || 10 | LoRA: no hay script estable para Flux2-klein-base en la ventana | M | B | WP-12 ≤3 h regla | timebox duro 3 h de intento (diffusers/ai-toolkit) | Corte F6-4; Well-Tuned no se reclama; ancla de estilo compensa || 11 | RIFE ghosting entre escenas | A | B | it_export | RIFE solo intra-escena (decision≠cut) | Export xfade puro || 12 | ffmpeg ausente/limitado en el contenedor | B | M | preflight P4 | `packages.txt: ffmpeg` + test en WP-02 | mux mínimo con imageio-ffmpeg || 13 | Scope creep en frontend (shaders infinitos) | A | A | D3 mediodía sin E2E | spec 04 es cerrada; nada fuera de spec sin pasar por F6 | Congelar a crossfade+KenBurns con máscara (sigue ganando a 2D plano) || 14 | Codex attribution se pierde (squash/rebase) | B | A | revisión de PRs | regla R7 + branch protection sin squash | — (prevención únicamente) || 15 | Algún claim del README sin evidencia | B | A | release_check | toda cifra viene de benchmarks/results; insignias con link | retirar claim antes que enviarlo || 16 | Otro equipo publica algo casi igual antes del 15 | B-M | M | vigilar org 1×/día | post teaser D3 fija autoría; nuestra pila (continuidad+2.5D+sonido+orquesta) es difícil de igualar en días | enfatizar diferenciales en video/README || 17 | Demo narra texto con copyright por descuido | B | A | guion del video | regla R8: solo textos propios o pre-1900; lista aprobada en docs/08 | — || 18 | Prompt injection vía narración ("ignore instructions…") | B | B | test adversarial en G2 | el Director solo puede emitir JSON-GBNF: la gramática es el sandbox | — || 19 | Contenido visual sensible solicitado por un visitante | B | M | — | klein trae mitigaciones de seguridad de fábrica (model card); prompts pasan por plantilla; sin upload de imágenes de usuarios | mensaje de "plano no disponible" si el pipeline devuelve vacío || 20 | Agotamiento del builder (30 h reales) | M | A | retraso >2 h acumulado | F6 sin debate; Must-set primero; dormir antes que pulir | El Must-set solo ya es una entrada de podio |123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101# 08 · COMPLIANCE + PAQUETE DE SUBMISSION
## 1. Regla del evento → dónde se hace cumplir en el repo
| Regla | Enforcement ||---|---|| ≤32B parámetros totales | `compliance/params_ledger.py` + `test_ledger.py` (CI) + tabla autogenerada en README + `/health` || App Gradio en Space de la org | Space SDK=gradio; `app.py` usa `gradio.Server`; `release_check.py` verifica org/URL || Video demo + post social en README | `release_check.py` falla si faltan los links; checklist D5 || Membresía/registro | preflight P1 || Off the Grid (sin APIs cloud runtime) | `test_compliance.py::test_no_cloud_apis` (grep) + revisión R-QA + `/health` declara flags || Show-don't-tell honesto | Showcase etiquetado; copy de estados; regla R4 || Insignias verídicas | R6 truth-conditions + links de evidencia en README || Codex (OpenAI Track) | R7: historial sin squash; link al repo en README; PRs de Codex preservados || Modal (premio en créditos) | training/ usa Modal; README sección "Built with Modal" con run-id || OpenBMB centralidad | El Director ES MiniCPM; la claqueta lo hace visible; README lo argumenta con diagrama || Cohere | Transcribe (+Aya si G2) integrados como su blog oficial del hackathon recomienda; README lo cita |
## 2. Tabla de licencias (rellenar literal en preflight P5)
| Asset | Licencia | Nota ||---|---|---|| Transcribe · MiniCPM5-1B · FLUX.2-klein-4B(+base) · Depth-Anything-V2-Small | apache-2.0 | Confirmado por preflight P5 || Tiny Aya | cc-by-nc-4.0 | Confirmado por preflight P5 || Stable Audio Open Small | other (card text: Stability AI Community License) | gratuita <$1M ingresos; **declarada** || RIFE checkpoint | `VERIFY:` repo | || Silero VAD (`onnx-community/silero-vad`) | mit | · Fuentes Fraunces/Inter: OFL, autoalojadas || Nuestro código | Apache 2.0 | LICENSE en repo · Textos de demo: dominio público/originales (§6) |
## 3. Plantilla README del Space (los ⟦⟧ son obligatorios; release_check los valida)
```markdown---title: Lightloom · live narrated cinemaemoji: 🎞️sdk: gradioapp_file: app.py---# 🎞️ Lightloom — speak, and watch your story become filmFive tiny local models shoot your movie while you narrate: they listen, translate, direct thecinematography, paint every shot with memory, give it depth and sound. Zero cloud APIs.
▶️ **Demo video:** ⟦link⟧ · 📣 **Social post:** ⟦link⟧ · 💻 **Code (Codex-built):** ⟦GitHub⟧
## The orchestra (parameter ledger — auto-generated, do not edit)⟦tabla de params_ledger: modelo·rol·params·licencia·runtime/build⟧ → **TOTAL: ⟦x.xx⟧B / 32B**
## How it works⟦diagrama mermaid del beat (docs/01 §6.1) + 4 líneas: beat→director(MiniCPM+GBNF)→klein KVmulti-ref→depth/sound→2.5D stage⟧. Honesty notes: motion is 2.5D parallax + RIFE interpolation(not video diffusion); pacing is beat-by-beat (not token streaming).
## Tracks & sponsor integrations**Thousand Token Wood.** OpenBMB: MiniCPM5-1B is the load-bearing Director (montage, camera,light, sound cues). Cohere: Transcribe ⟦+ Tiny Aya⟧ exactly as their hackathon guide recommends.OpenAI: built with Codex — see attributed commits in the repo. Modal: style LoRA trained onModal (run ⟦id⟧). BFL: FLUX.2 [klein] 4B with KV-cached multi-reference continuity.
## Merit badges (evidence-linked)⟦Off-the-Grid: /health + compliance test⟧ ⟦Well-Tuned: LoRA repo⟧ ⟦Off-Brand: gr.Server UI⟧⟦Llama Champion: solo si literalmente cierto (R6)⟧ ⟦Sharing-is-Caring: traces dataset⟧⟦Field Notes: blog⟧
## What is fully live vs pre-renderedEverything on the Stage is generated live in this Space. The Showcase gallery is pre-rendered(by this same app) and labeled as such — it exists for when GPU quota runs out.Benchmarks: ⟦links a benchmarks/results⟧. Known limits: ⟦cold start, idiomas, etc.⟧```
## 4. Guion del video (≤120 s; grabar sobre el Space público; subtítulos incrustados)1. 0–8 s Negro→voz "Había una vez un faro al borde del mundo…"→el faro se revela CON paralaje y mar ambiental. Caption: "Live, in this Space. Zero cloud APIs."2. 8–35 s Dos beats de continuidad (claqueta: CONTINUITY·dolly-in) → frase "pero lejos de allí, en un mercado al amanecer" → claqueta marca CUT, wipe, soundbed cambia.3. 35–55 s Selector a EN/FR, una estrofa → "14 input languages, 70+ translated, all local."4. 55–80 s Teatro: replay con la voz + descarga MP4 + storyboard. "This MP4 is our social post."5. 80–105 s Pantalla orquesta: 7 modelos, 7.4B/32B, sello de insignias.6. 105–120 s "Pack light. Dream big." + URL del Space.
## 5. Plantillas de difusión- **Post social:** video MP4 exportado por la app + "I spoke a story and five tiny models shot the film — live, on-device, 7B/32B params. Built for @huggingface #BuildSmall with Gradio, MiniCPM, FLUX.2 klein, Cohere Transcribe. Try it: ⟦Space URL⟧". (Etiquetar evento; sin claims no demostrados.)- **Blog Field Notes (outline):** 1 la tesis de la orquesta · 2 los 5 gates con cifras reales · 3 la claqueta: hacer visible la dirección · 4 lo que falló (honesto: §riesgos materializados) · 5 párrafo de cada sponsor-tech con lo aprendido · 6 qué haríamos con una semana más.- **Dataset de trazas (Sharing is Caring):** `Film` sin audio del usuario; card con esquema (docs/01 §3), licencia CC-BY-4.0, y 3 películas de ejemplo con su audio (nuestro, consentido).
## 6. Textos aprobados para demos (regla R8)- Originales escritos por nosotros (el cuento del faro — escribirlo en D2, 8–10 beats).- Dominio público (muerte del autor <1900): Bécquer (Rimas), Rubén Darío (pre-1916 — verificar estado por país; preferir <1900 para margen), Shakespeare (sonetos, EN), Verlaine (FR).- PROHIBIDO: letras de canciones, poesía contemporánea, marcas, personajes con copyright.
## 7. Checklist final de envío (D5; todo binario)[ ] release_check ALL GREEN · [ ] README con los 3 links ⟦video/post/repo⟧ · [ ] ledger ≤32B enREADME y /health · [ ] insignias=evidencia · [ ] LoRA/trazas/blog públicos bajo la org ·[ ] judge-sim aprobado (desktop+móvil) · [ ] Showcase accesible con cuota simulada agotada ·[ ] video con subtítulos · [ ] post publicado y enlazado · [ ] submit con ≥6 h de margen.12345678910111213# VERIFY LOG — pendientes de verificación empírica (cerrar TODOS antes del release)| # | Item | Dónde | Cómo se resuelve | Estado ||---|---|---|---|---|| V1 | Repo id exacto GGUF de MiniCPM5-1B en HF | config.py | preflight P5 | OPEN || V2 | Licencia Tiny Aya + RIFE checkpoint | tabla 08 §2 | Tiny Aya cc-by-nc-4.0 resolved by preflight P5; RIFE checkpoint license still pending selected checkpoint | PARTIAL 2026-06-11 || V3 | kwarg de imágenes de referencia en pipeline Flux2 Klein KV | paint/klein.py | leer firma instalada (CLAUDE.md §4) | OPEN || V4 | API exacta de streaming por generador en gr.Server | app.py | spike WP-02 (guía server-mode) | OPEN || V5 | Repo id Depth-Anything-V2-Small-hf + licencia Small | config.py | `depth-anything/Depth-Anything-V2-Small-hf` sha `5426e4f0f36572d16453bbda7a8389317b1bef99`, license apache-2.0 | CLOSED 2026-06-11 || V6 | Script LoRA estable para FLUX.2-klein-base | training/ | timebox 3 h WP-12 | OPEN || V7 | Cuota ZeroGPU efectiva de la org | budget.py | bench_cold + probe_quota D1 | OPEN || V8 | Gates G1–G5 (cifras) | benchmarks/ | D1–D2 | OPEN || V9 | PyTorch local supports Blackwell sm_120 on RTX 5070 | requirements.txt / benchmarks/results/preflight.json | torch 2.11.0+cu128, CUDA 12.8, arch list includes sm_120, CUDA matmul smoke passed | CLOSED 2026-06-11 || V10 | Repo id exacto HF para Silero VAD | config.py | `onnx-community/silero-vad` sha `e71cae966052b992a7eca6b17738916ce0eca4ec`, license mit | CLOSED 2026-06-11 |1ffmpeg123456789101112131415161718192021[build-system]requires = ["setuptools>=69", "wheel"]build-backend = "setuptools.build_meta"
[project]name = "lightloom"version = "0.1.0"description = "Voice-driven live-cinema Gradio app for the Build Small hackathon."requires-python = ">=3.10"readme = "README.md"
[tool.setuptools.packages.find]where = ["src"]
[tool.pytest.ini_options]pythonpath = ["src"]testpaths = ["tests"]
[tool.ruff]line-length = 100target-version = "py310"1234567891011121314--extra-index-url https://download.pytorch.org/whl/cu128
gradio[mcp]==6.17.3huggingface_hub==1.18.0pydantic==2.12.5pytest==9.0.3ruff>=0.5.0numpy==2.4.6Pillow==12.2.0torch==2.11.0+cu128transformers==5.11.0diffusers @ git+https://github.com/huggingface/diffusers.git@784fa62652fb2719d415830f918fc32a49ecc7a1llama-cpp-python==0.3.28spaces==0.50.4123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293"""Deploy the current private build to the personal Lightloom dev Space.
Parameter contribution: 0B. This script uses HF_WRITE_TOKEN from the processenvironment and never prints token values."""
from __future__ import annotations
import osfrom pathlib import Pathimport sys
from huggingface_hub import HfApi, SpaceHardware
ROOT = Path(__file__).resolve().parents[1]
def _token() -> str: token = os.getenv("HF_WRITE_TOKEN") or os.getenv("HF_TOKEN") if not token: raise SystemExit("HF_WRITE_TOKEN/HF_TOKEN is required in the process environment.") return token
def _read_token() -> str | None: return os.getenv("HF_READ_TOKEN") or os.getenv("HF_TOKEN")
def _space_id(api: HfApi, token: str) -> str: configured = os.getenv("LIGHTLOOM_DEV_SPACE_ID") if configured: return configured info = api.whoami(token=token) username = info.get("name") if not username: raise SystemExit("Could not infer HF username for personal dev Space.") return f"{username}/lightloom-dev"
def _zero_hardware() -> SpaceHardware | None: for candidate in SpaceHardware: if "zero" in str(candidate.value).lower(): return candidate return None
def main() -> int: token = _token() api = HfApi(token=token) space_id = _space_id(api, token) api.create_repo( space_id, repo_type="space", private=True, exist_ok=True, space_sdk="gradio", space_hardware=_zero_hardware(), ) read_token = _read_token() if read_token: api.add_space_secret(space_id, "HF_TOKEN", read_token, token=token) for key, value in { "LIGHTLOOM_PROFILE": "space", "LIGHTLOOM_PRIVACY_MODE": "1", "LIGHTLOOM_ENABLE_INTERNAL_BENCH": "1", "LIGHTLOOM_G1_REPS": os.getenv("LIGHTLOOM_G1_REPS", "5"), }.items(): api.add_space_variable(space_id, key, value, token=token) info = api.upload_folder( repo_id=space_id, repo_type="space", folder_path=ROOT, commit_message="chore: deploy private lightloom build", ignore_patterns=[ ".git/*", ".venv/*", ".env", ".env.*", "lightloom-docs/*", "*.zip", "__pycache__/*", ".pytest_cache/*", "benchmarks/results/g1.json", "benchmarks/results/g1.md", ], token=token, ) print(f"DEPLOYED {space_id} {info.oid}") return 0
if __name__ == "__main__": raise SystemExit(main())1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253"""Run G1 through the private Space endpoint and save returned results locally."""
from __future__ import annotations
import jsonimport osfrom pathlib import Pathimport sysfrom urllib.request import Request, urlopen
ROOT = Path(__file__).resolve().parents[1]OUT = ROOT / "benchmarks" / "results" / "g1.json"
def _space_id() -> str: configured = os.getenv("LIGHTLOOM_DEV_SPACE_ID") if configured: return configured token = os.getenv("HF_WRITE_TOKEN") or os.getenv("HF_TOKEN") if not token: raise SystemExit("HF_WRITE_TOKEN/HF_TOKEN is required to infer the Space id.") from huggingface_hub import HfApi
info = HfApi(token=token).whoami(token=token) username = info.get("name") if not username: raise SystemExit("Could not infer HF username.") return f"{username}/lightloom-dev"
def _url(space_id: str) -> str: owner, name = space_id.split("/", 1) return f"https://{owner}-{name}.hf.space/internal/bench/g1"
def main() -> int: token = os.getenv("HF_WRITE_TOKEN") or os.getenv("HF_TOKEN") if not token: raise SystemExit("HF_WRITE_TOKEN/HF_TOKEN is required in the process environment.") req = Request(_url(_space_id()), method="POST", headers={"Authorization": f"Bearer {token}"}) with urlopen(req, timeout=int(os.getenv("LIGHTLOOM_G1_TIMEOUT", "1800"))) as response: payload = json.loads(response.read().decode("utf-8")) if not payload.get("ok"): raise SystemExit(f"Space G1 endpoint failed: {payload}") OUT.parent.mkdir(parents=True, exist_ok=True) OUT.write_text(json.dumps(payload["data"], indent=2, sort_keys=True) + "\n", encoding="utf-8") print(f"WROTE {OUT}") print(f"DECISION {payload['data']['decision']['status']}") return 0
if __name__ == "__main__": raise SystemExit(main())123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395"""Lightloom preflight checks.
Writes benchmarks/results/preflight.json and prints a redacted summary. Thescript never prints token values and never persists secrets."""
from __future__ import annotations
import importlibimport jsonimport osfrom pathlib import Pathimport platformimport sysimport timefrom typing import Any
ROOT = Path(__file__).resolve().parents[1]sys.path.insert(0, str(ROOT / "src"))RESULTS = ROOT / "benchmarks" / "results"PREFLIGHT_JSON = RESULTS / "preflight.json"ORG_NAME = os.getenv("LIGHTLOOM_HF_ORG", "build-small-hackathon")DEV_SPACE_ID = os.getenv("LIGHTLOOM_DEV_SPACE_ID")
def _env_present(name: str) -> bool: return bool(os.getenv(name, "").strip())
def _token() -> str | None: for name in ("HF_WRITE_TOKEN", "HF_TOKEN"): value = os.getenv(name, "").strip() if value: return value return None
def _missing_token_message() -> str: return ( "HF_WRITE_TOKEN/HF_TOKEN is not set in the process environment. " "Install env vars without writing secrets to files: " "PowerShell -ExecutionPolicy Bypass -File scripts/set_hf_env.ps1" )
def _check(name: str, ok: bool, message: str, evidence: dict[str, Any] | None = None) -> dict[str, Any]: return { "name": name, "ok": bool(ok), "message": message, "evidence": evidence or {}, }
def _run_python_import(module: str) -> tuple[bool, str | None]: try: imported = importlib.import_module(module) except Exception as exc: # noqa: BLE001 - preflight reports dependency health. return False, f"{type(exc).__name__}: {exc}" version = getattr(imported, "__version__", None) return True, str(version) if version is not None else "installed"
def check_p1_org_membership() -> dict[str, Any]: token = _token() if token is None: return _check( "P1 org membership", False, _missing_token_message(), {"required_org": ORG_NAME}, ) try: from huggingface_hub import HfApi
info = HfApi(token=token).whoami(token=token) orgs = [org.get("name") for org in info.get("orgs", [])] user = info.get("name") or info.get("fullname") or "unknown" ok = ORG_NAME in orgs return _check( "P1 org membership", ok, "authenticated user is a member of the hackathon org" if ok else "authenticated user is not a member of the hackathon org", {"user": user, "required_org": ORG_NAME, "org_present": ok}, ) except Exception as exc: # noqa: BLE001 return _check( "P1 org membership", False, f"whoami failed: {type(exc).__name__}", {"required_org": ORG_NAME}, )
def check_p2_space() -> dict[str, Any]: token = _token() if token is None: return _check( "P2 private ZeroGPU Space", False, "HF_WRITE_TOKEN/HF_TOKEN is not set; cannot create or inspect private dev Space.", {"space_id": DEV_SPACE_ID or "unset"}, ) try: from huggingface_hub import HfApi, SpaceHardware
api = HfApi(token=token) inferred_space_id = DEV_SPACE_ID if inferred_space_id is None: info = api.whoami(token=token) username = info.get("name") if not username: return _check( "P2 private ZeroGPU Space", False, "could not infer personal namespace from whoami", {"privacy_mode": True}, ) inferred_space_id = f"{username}/lightloom-dev" hardware = None for candidate in SpaceHardware: if "zero" in str(candidate.value).lower(): hardware = candidate break api.create_repo( inferred_space_id, repo_type="space", private=True, exist_ok=True, space_sdk="gradio", space_hardware=hardware, space_secrets=[ {"key": "HF_TOKEN", "value": os.getenv("HF_READ_TOKEN", os.getenv("HF_TOKEN", ""))} ] if (os.getenv("HF_READ_TOKEN") or os.getenv("HF_TOKEN")) else None, space_variables=[ {"key": "LIGHTLOOM_PROFILE", "value": "space"}, {"key": "LIGHTLOOM_PRIVACY_MODE", "value": "1"}, ], ) runtime = api.get_space_runtime(inferred_space_id, token=token) runtime_hardware = getattr(runtime, "hardware", None) requested = getattr(runtime, "requested_hardware", None) stage = getattr(runtime, "stage", None) sdk = getattr(runtime, "sdk", None) zero_gpu = "zero" in str(runtime_hardware or requested or hardware).lower() ok = zero_gpu and (sdk in {None, "gradio"} or "gradio" in str(sdk).lower()) return _check( "P2 private ZeroGPU Space", ok, "private dev Space exists and appears to be ZeroGPU/Gradio" if ok else "dev Space does not show ZeroGPU/Gradio runtime metadata", { "space_id": inferred_space_id, "privacy": "private", "hardware": str(runtime_hardware), "requested_hardware": str(requested), "created_or_reused": True, "stage": str(stage), "sdk": str(sdk), }, ) except Exception as exc: # noqa: BLE001 return _check( "P2 private ZeroGPU Space", False, f"Space inspection failed: {type(exc).__name__}", {"space_id": DEV_SPACE_ID}, )
def check_p3_secrets() -> dict[str, Any]: return _check( "P3 runtime secret contract", _env_present("HF_READ_TOKEN") or _env_present("HF_TOKEN"), "read token env var is available for configuring the Space secret" if (_env_present("HF_READ_TOKEN") or _env_present("HF_TOKEN")) else "HF_READ_TOKEN/HF_TOKEN is not set in this process", {"secret_names_only": ["HF_TOKEN"]}, )
def check_p4_local_versions() -> dict[str, Any]: from lightloom.core.config import CONFIG
imports = {} for module in ("gradio", "huggingface_hub", "transformers", "diffusers", "torch", "llama_cpp"): ok, detail = _run_python_import(module) imports[module] = {"ok": ok, "detail": detail} py_ok = sys.version_info >= (3, 10) missing = [name for name, result in imports.items() if not result["ok"]] torch_evidence: dict[str, Any] = {} try: import torch
torch_evidence = { "torch": getattr(torch, "__version__", "unknown"), "cuda_available": bool(torch.cuda.is_available()), "cuda_version": getattr(torch.version, "cuda", None), "arch_list": list(torch.cuda.get_arch_list()) if torch.cuda.is_available() else [], "sm_120_supported": "sm_120" in ( torch.cuda.get_arch_list() if torch.cuda.is_available() else [] ), "cuda_kernel_smoke": False, } if torch.cuda.is_available(): x = torch.ones((8, 8), device="cuda") torch_evidence["cuda_kernel_smoke"] = bool((x @ x).sum().item() == 512.0) except Exception as exc: # noqa: BLE001 torch_evidence = {"torch_error": f"{type(exc).__name__}: {exc}"} local_cuda_ok = True if CONFIG.profile == "local": local_cuda_ok = bool( torch_evidence.get("cuda_available") and torch_evidence.get("sm_120_supported") and torch_evidence.get("cuda_kernel_smoke") ) ok = py_ok and not missing and local_cuda_ok return _check( "P4 local versions", ok, "Python, required imports, and local CUDA smoke check are available" if ok else "missing packages or local CUDA/sm_120 smoke check failed", { "python": sys.version, "executable": sys.executable, "platform": platform.platform(), "imports": imports, "torch": torch_evidence, "packages_txt_has_ffmpeg": (ROOT / "packages.txt").read_text().strip() == "ffmpeg", }, )
def check_p5_models() -> dict[str, Any]: from lightloom.core.config import CONFIG, MODEL_REFS
token = _token() if token is None: return _check( "P5 model cards", False, "HF_WRITE_TOKEN/HF_TOKEN is not set; cannot verify private/gated model cards.", { "profile": CONFIG.profile, "local_flux_dtype": CONFIG.flux_dtype, "local_resolution": [CONFIG.width, CONFIG.height], "local_aot": CONFIG.flux_aot, "model_count": len(MODEL_REFS), }, ) try: from huggingface_hub import HfApi
api = HfApi(token=token) resolved: dict[str, Any] = {} failures: dict[str, str] = {} for key, ref in MODEL_REFS.items(): if key == "rife": resolved[key] = { "repo_id": ref.repo_id, "license": ref.license, "note": "GitHub repo; checkpoint license remains VERIFY until selected.", } continue try: info = api.model_info(ref.repo_id, token=token) license_name = None if getattr(info, "card_data", None): license_name = getattr(info.card_data, "license", None) resolved[key] = { "repo_id": ref.repo_id, "sha": getattr(info, "sha", None), "license": license_name or ref.license, "private": bool(getattr(info, "private", False)), } except Exception as exc: # noqa: BLE001 failures[key] = f"{type(exc).__name__}: {exc}" ok = not failures return _check( "P5 model cards", ok, "model cards resolved" if ok else "one or more model cards failed to resolve", { "profile": CONFIG.profile, "local_flux_dtype": CONFIG.flux_dtype, "local_resolution": [CONFIG.width, CONFIG.height], "local_aot": CONFIG.flux_aot, "resolved": resolved, "failures": failures, }, ) except Exception as exc: # noqa: BLE001 return _check("P5 model cards", False, f"Hub verification failed: {type(exc).__name__}")
def check_p6_disk_cache() -> dict[str, Any]: usage = None try: usage = os.statvfs(ROOT) # type: ignore[attr-defined] free_gb = usage.f_bavail * usage.f_frsize / (1024**3) except AttributeError: import shutil
free_gb = shutil.disk_usage(ROOT).free / (1024**3) ok = free_gb >= 30 return _check( "P6 disk/cache", ok, "local disk has room for iterative caches" if ok else "low free disk for model caches", {"free_gb": round(free_gb, 2), "estimated_runtime_weights_gb": 20}, )
def check_p7_spaces_import() -> dict[str, Any]: ok, detail = _run_python_import("spaces") return _check( "P7 spaces decorator", ok, "spaces package imports" if ok else "spaces package is missing", {"detail": detail}, )
def check_secret_scan() -> dict[str, Any]: token_re = __import__("re").compile(r"hf_[A-Za-z0-9]{20,}") skip_parts = {".git", ".venv", "__pycache__", ".pytest_cache"} skip_suffixes = {".zip", ".7z", ".tar", ".gz", ".png", ".jpg", ".jpeg", ".webp", ".mp4", ".wav"} matches: list[str] = [] try: for path in ROOT.rglob("*"): if any(part in skip_parts for part in path.parts): continue if not path.is_file() or path.suffix.lower() in skip_suffixes: continue try: text = path.read_text(encoding="utf-8") except UnicodeDecodeError: continue if token_re.search(text): matches.append(str(path.relative_to(ROOT))) except Exception as exc: # noqa: BLE001 return _check("secret scan", False, f"secret scan failed: {type(exc).__name__}") ok = not matches return _check( "secret scan", ok, "no HF token patterns in tracked files" if ok else "possible HF token pattern found", {"match_files": sorted(set(matches))}, )
def run() -> dict[str, Any]: start = time.time() RESULTS.mkdir(parents=True, exist_ok=True) checks = [ check_p1_org_membership(), check_p2_space(), check_p3_secrets(), check_p4_local_versions(), check_p5_models(), check_p6_disk_cache(), check_p7_spaces_import(), check_secret_scan(), ] result = { "schema_version": 1, "generated_at": time.strftime("%Y-%m-%dT%H:%M:%SZ", time.gmtime()), "hardware_profile": os.getenv("LIGHTLOOM_PROFILE", "local"), "privacy_mode": True, "all_green": all(check["ok"] for check in checks), "checks": checks, "elapsed_s": round(time.time() - start, 3), } PREFLIGHT_JSON.write_text(json.dumps(result, indent=2, sort_keys=True) + "\n", encoding="utf-8") return result
def main() -> int: result = run() print("LIGHTLOOM PREFLIGHT") for check in result["checks"]: status = "PASS" if check["ok"] else "FAIL" print(f"{status} {check['name']}: {check['message']}") print(f"RESULT {'ALL GREEN' if result['all_green'] else 'BLOCKED'} -> {PREFLIGHT_JSON}") return 0 if result["all_green"] else 1
if __name__ == "__main__": raise SystemExit(main())123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384"""Release gate for Lightloom.
This starts strict and becomes stricter through F4/F5. It already enforces theprivacy addendum's no-secret/no-placeholder posture."""
from __future__ import annotations
import jsonfrom pathlib import Pathimport reimport subprocessimport sys
ROOT = Path(__file__).resolve().parents[1]TOKEN_RE = re.compile(r"hf_[A-Za-z0-9]{20,}")
def fail(message: str) -> str: return f"FAIL {message}"
def ok(message: str) -> str: return f"PASS {message}"
def secret_scan() -> tuple[bool, str]: tracked = subprocess.run( ["git", "ls-files"], cwd=ROOT, text=True, capture_output=True, check=False, ) if tracked.returncode != 0: return False, "git ls-files failed" offenders: list[str] = [] for rel in tracked.stdout.splitlines(): path = ROOT / rel if not path.is_file(): continue try: text = path.read_text(encoding="utf-8") except UnicodeDecodeError: continue if TOKEN_RE.search(text): offenders.append(rel) if offenders: return False, "token-like secret found in tracked files: " + ", ".join(offenders) return True, "no token-like secrets in tracked files"
def preflight_result() -> tuple[bool, str]: path = ROOT / "benchmarks" / "results" / "preflight.json" if not path.exists(): return False, "benchmarks/results/preflight.json is missing" data = json.loads(path.read_text(encoding="utf-8")) if not data.get("all_green"): return False, "preflight is not ALL GREEN" return True, "preflight ALL GREEN"
def h6_placeholder_gate() -> tuple[bool, str]: readme = ROOT / "README.md" if not readme.exists(): return False, "README.md is missing" text = readme.read_text(encoding="utf-8") release_mode = (ROOT / "docs" / "submission" / "H6_GREEN").exists() if release_mode and "⟦PLACEHOLDER⟧" in text: return False, "H6 release mode forbids README placeholders" return True, "README placeholder state accepted for current private mode"
def main() -> int: checks = [secret_scan(), preflight_result(), h6_placeholder_gate()] for passed, message in checks: print(ok(message) if passed else fail(message)) all_green = all(passed for passed, _ in checks) print("RESULT " + ("ALL GREEN" if all_green else "BLOCKED")) return 0 if all_green else 1
if __name__ == "__main__": raise SystemExit(main())12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455param( [switch]$PersistUser = $true, [string]$DevSpaceId = "")
$ErrorActionPreference = "Stop"
function Read-SecretPlainText { param([Parameter(Mandatory = $true)][string]$Name) $secure = Read-Host -Prompt "Enter $Name" -AsSecureString $bstr = [Runtime.InteropServices.Marshal]::SecureStringToBSTR($secure) try { return [Runtime.InteropServices.Marshal]::PtrToStringBSTR($bstr) } finally { if ($bstr -ne [IntPtr]::Zero) { [Runtime.InteropServices.Marshal]::ZeroFreeBSTR($bstr) } }}
function Set-EnvValue { param( [Parameter(Mandatory = $true)][string]$Name, [Parameter(Mandatory = $true)][string]$Value ) Set-Item -Path "Env:$Name" -Value $Value if ($PersistUser) { [Environment]::SetEnvironmentVariable($Name, $Value, "User") }}
$writeToken = Read-SecretPlainText -Name "HF_WRITE_TOKEN"$readToken = Read-SecretPlainText -Name "HF_READ_TOKEN"
if (-not $writeToken.StartsWith("hf_")) { throw "HF_WRITE_TOKEN must look like a Hugging Face token."}if (-not $readToken.StartsWith("hf_")) { throw "HF_READ_TOKEN must look like a Hugging Face token."}
Set-EnvValue -Name "HF_WRITE_TOKEN" -Value $writeTokenSet-EnvValue -Name "HF_READ_TOKEN" -Value $readTokenSet-EnvValue -Name "HF_TOKEN" -Value $readToken
if ($DevSpaceId.Trim().Length -gt 0) { Set-EnvValue -Name "LIGHTLOOM_DEV_SPACE_ID" -Value $DevSpaceId.Trim()}
Set-EnvValue -Name "LIGHTLOOM_PROFILE" -Value "local"Set-EnvValue -Name "LIGHTLOOM_HF_ORG" -Value "build-small-hackathon"
Write-Host "HF environment variables installed. Token values were not printed."Write-Host "Restart the terminal or launch Codex from this shell for persisted user env changes to apply."12345"""Lightloom package."""
__all__ = ["__version__"]
__version__ = "0.1.0"1"""Compliance helpers for parameter and off-grid checks."""12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485"""Runtime parameter ledger.
Parameter contribution: 0B. This module enforces the <=32B total runtimeparameter rule and separates runtime models from build-time assets."""
from __future__ import annotations
from dataclasses import dataclassfrom pathlib import Pathimport sysfrom typing import Iterable
if __package__ in {None, ""}: sys.path.insert(0, str(Path(__file__).resolve().parents[2]))
from lightloom.core.config import MODEL_REFS
PARAMETER_LIMIT = 32_000_000_000
@dataclass(frozen=True)class LedgerEntry: name: str role: str repo_id: str params: int license: str runtime: bool revision: str | None = None
def entries() -> list[LedgerEntry]: return [ LedgerEntry( name=name, role=ref.role, repo_id=ref.repo_id, params=ref.params, license=ref.license, runtime=ref.runtime, revision=ref.revision, ) for name, ref in MODEL_REFS.items() ]
def runtime_entries() -> list[LedgerEntry]: return [entry for entry in entries() if entry.runtime]
def total_runtime_params(items: Iterable[LedgerEntry] | None = None) -> int: selected = list(items) if items is not None else runtime_entries() return sum(entry.params for entry in selected if entry.runtime)
def assert_under_limit() -> None: total = total_runtime_params() if total > PARAMETER_LIMIT: raise AssertionError(f"runtime params exceed limit: {total} > {PARAMETER_LIMIT}")
def markdown_table() -> str: rows = [ "| Name | Role | Repo | Params (B) | License | Runtime |", "|---|---|---|---:|---|---|", ] for entry in entries(): rows.append( "| {name} | {role} | `{repo}` | {params:.3f} | {license} | {runtime} |".format( name=entry.name, role=entry.role, repo=entry.repo_id, params=entry.params / 1_000_000_000, license=entry.license, runtime="yes" if entry.runtime else "build-time", ) ) rows.append(f"| **TOTAL runtime** | | | **{total_runtime_params() / 1_000_000_000:.3f}** | | |") return "\n".join(rows)
if __name__ == "__main__": assert_under_limit() print(markdown_table())1"""Core runtime configuration and session primitives."""123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162"""Runtime/build-time configuration for Lightloom.
Parameter contribution: 0B. This module only declares model ids, revisions,profiles, and runtime knobs."""
from __future__ import annotations
from dataclasses import dataclassimport osfrom typing import Literal
Profile = Literal["local", "space"]
def _profile_from_env() -> Profile: raw = os.getenv("LIGHTLOOM_PROFILE", "local").strip().lower() if raw not in {"local", "space"}: raise ValueError("LIGHTLOOM_PROFILE must be 'local' or 'space'") return raw # type: ignore[return-value]
LIGHTLOOM_PROFILE: Profile = _profile_from_env()
@dataclass(frozen=True)class ModelRef: role: str repo_id: str revision: str | None license: str params: int runtime: bool = True notes: str = "" filename: str | None = None
@dataclass(frozen=True)class RuntimeConfig: profile: Profile width: int height: int flux_dtype: Literal["fp8", "bf16"] flux_aot: bool flux_steps: int guidance_scale: float session_gpu_budget_s: float showcase_only: bool zero_gpu_duration_s: int
LOCAL_CONFIG = RuntimeConfig( profile="local", width=768, height=432, flux_dtype="fp8", flux_aot=False, flux_steps=4, guidance_scale=1.0, session_gpu_budget_s=90.0, showcase_only=os.getenv("LIGHTLOOM_SHOWCASE_ONLY", "0") == "1", zero_gpu_duration_s=45,)
SPACE_CONFIG = RuntimeConfig( profile="space", width=int(os.getenv("LIGHTLOOM_WIDTH", "1024")), height=int(os.getenv("LIGHTLOOM_HEIGHT", "576")), flux_dtype=os.getenv("LIGHTLOOM_FLUX_DTYPE", "fp8").lower(), # type: ignore[arg-type] flux_aot=os.getenv("LIGHTLOOM_FLUX_AOT", "1") == "1", flux_steps=int(os.getenv("LIGHTLOOM_FLUX_STEPS", "4")), guidance_scale=float(os.getenv("LIGHTLOOM_GUIDANCE_SCALE", "1.0")), session_gpu_budget_s=float(os.getenv("LIGHTLOOM_SESSION_GPU_BUDGET", "90")), showcase_only=os.getenv("LIGHTLOOM_SHOWCASE_ONLY", "0") == "1", zero_gpu_duration_s=int(os.getenv("LIGHTLOOM_ZERO_GPU_DURATION", "45")),)
CONFIG = LOCAL_CONFIG if LIGHTLOOM_PROFILE == "local" else SPACE_CONFIG
# Candidate model refs. Revisions are intentionally unresolved until preflight# P5 records exact Hub revisions into benchmarks/results/preflight.json.MODEL_REFS: dict[str, ModelRef] = { "asr": ModelRef( role="ASR", repo_id="CohereLabs/cohere-transcribe-03-2026", revision="b1eacc2686a3d08ceaae5f24a88b1d519620bc09", license="apache-2.0", params=2_000_000_000, ), "translator": ModelRef( role="Translator", repo_id="CohereLabs/tiny-aya-global-GGUF", revision="a602ea7eeec3a4ad6f77a1b8cf6a53512824922b", license="cc-by-nc-4.0", params=3_350_000_000, filename="*Q4_K_M*.gguf", ), "director": ModelRef( role="Director", repo_id="openbmb/MiniCPM5-1B", revision="4e9de7a0778dc1c362e983e6858f0e77542cbdca", license="apache-2.0", params=1_000_000_000, notes="GGUF repo id remains VERIFY item V1.", ), "painter": ModelRef( role="Painter", repo_id="black-forest-labs/FLUX.2-klein-4B", revision="e7b7dc27f91deacad38e78976d1f2b499d76a294", license="apache-2.0", params=4_000_000_000, notes="Local profile requires FP8 because 12GB VRAM cannot fit BF16.", ), "painter_base_train": ModelRef( role="Painter training base", repo_id="black-forest-labs/FLUX.2-klein-base-4B", revision="a3b4f4849157f664bdbc776fd7453c2783562f4d", license="apache-2.0", params=4_000_000_000, runtime=False, ), "depth": ModelRef( role="Depth", repo_id="depth-anything/Depth-Anything-V2-Small-hf", revision="5426e4f0f36572d16453bbda7a8389317b1bef99", license="apache-2.0", params=25_000_000, ), "sound": ModelRef( role="Ambient audio", repo_id="stabilityai/stable-audio-open-small", revision="dc620d91535857b72ebb59b4ca45978db6d417f5", license="other", params=341_000_000, notes="Model card license field is 'other'; card text declares Stability AI Community License.", ), "rife": ModelRef( role="Export interpolation", repo_id="hzwer/Practical-RIFE", revision=None, license="VERIFY", params=10_000_000, ), "vad": ModelRef( role="Voice activity detection", repo_id="onnx-community/silero-vad", revision="e71cae966052b992a7eca6b17738916ce0eca4ec", license="mit", params=2_000_000, ),}
MUST_SET = ( "continuity engine", "2.5D parallax", "slate", "Recital mode", "Showcase", "quota guard",)
F6_CUT_ORDER = ("RIFE", "ambient audio", "Aya", "LoRA")1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253from __future__ import annotations
from pathlib import Pathimport re
ROOT = Path(__file__).resolve().parents[1]RUNTIME_DIRS = [ROOT / "src", ROOT / "frontend", ROOT / "app.py"]
FORBIDDEN = [ "api.openai.com", "api.cohere", "bfl.ai/api", "InferenceClient", "huggingface_hub.InferenceApi",]
TOKEN_RE = re.compile(r"hf_[A-Za-z0-9]{20,}")
def _runtime_files() -> list[Path]: files: list[Path] = [] for root in RUNTIME_DIRS: if root.is_file(): files.append(root) elif root.exists(): files.extend(path for path in root.rglob("*") if path.is_file()) return files
def test_no_cloud_api_literals_in_runtime() -> None: offenders: list[str] = [] for path in _runtime_files(): text = path.read_text(encoding="utf-8", errors="ignore") for pattern in FORBIDDEN: if pattern in text: offenders.append(f"{path.relative_to(ROOT)}:{pattern}") assert offenders == []
def test_no_hf_tokens_in_repo_text_files() -> None: offenders: list[str] = [] for path in ROOT.rglob("*"): if ".git" in path.parts or ".venv" in path.parts: continue if not path.is_file(): continue try: text = path.read_text(encoding="utf-8") except UnicodeDecodeError: continue if TOKEN_RE.search(text): offenders.append(str(path.relative_to(ROOT))) assert offenders == []12345678910111213141516from __future__ import annotations
import jsonfrom pathlib import Path
from benchmarks.gate_g1 import DEFAULT_JSON, run
def test_g1_dry_run_writes_non_authoritative_results() -> None: data = run(dry_run=True, reps=2, allow_local=False) assert data["authoritative"] is False assert data["decision"]["status"] == "blocked" assert DEFAULT_JSON.exists() saved = json.loads(Path(DEFAULT_JSON).read_text(encoding="utf-8")) assert saved["results"] assert all(item["status"] == "dry_run" for item in saved["results"])12345678910111213141516171819from lightloom.compliance.params_ledger import PARAMETER_LIMIT, runtime_entries, total_runtime_paramsfrom lightloom.core.config import CONFIG
def test_runtime_params_under_32b() -> None: assert total_runtime_params() <= PARAMETER_LIMIT
def test_runtime_entries_are_positive_and_licensed() -> None: for entry in runtime_entries(): assert entry.params > 0 assert entry.license
def test_local_profile_is_5070_safe() -> None: if CONFIG.profile == "local": assert CONFIG.flux_dtype == "fp8" assert (CONFIG.width, CONFIG.height) == (768, 432) assert CONFIG.flux_aot is False.gitignoreAdded+50
AGENTS.mdAdded+89
CLAUDE.mdAdded+30
MASTER_PLAN.mdAdded+85
README.md+10-8
app.pyAdded+85
benchmarks/__init__.pyAdded+1
benchmarks/gate_g1.pyAdded+301
benchmarks/results/.gitkeepAdded+1
benchmarks/results/preflight.jsonAdded+191
docs/01_ARCHITECTURE.mdAdded+176
docs/02_MODELS_AND_MATH.mdAdded+93
docs/03_PROMPTS.mdAdded+154
docs/04_UI_SPEC.mdAdded+115
docs/05_EXECUTION_PLAN.mdAdded+67
docs/06_TESTING_QA.mdAdded+66
docs/07_RISKS.mdAdded+24
docs/08_COMPLIANCE_HACKATHON.mdAdded+101
docs/VERIFY_LOG.mdAdded+13
packages.txtAdded+1
pyproject.tomlAdded+21
requirements.txtAdded+14
scripts/deploy_private_space.pyAdded+93
scripts/fetch_gate_g1.pyAdded+53
scripts/preflight.pyAdded+395
scripts/release_check.pyAdded+84
scripts/set_hf_env.ps1Added+55
src/lightloom/__init__.pyAdded+5
src/lightloom/compliance/__init__.pyAdded+1
src/lightloom/compliance/params_ledger.pyAdded+85
src/lightloom/core/__init__.pyAdded+1
src/lightloom/core/config.pyAdded+162
tests/test_compliance.pyAdded+53
tests/test_gate_g1.pyAdded+16
tests/test_ledger.pyAdded+19