Python
Galería: un ejemplo por app
neuregexb1c5bde301a7
diff --git a/README.md b/README.mdindex 972cce6..cd725de 100644--- a/README.md+++ b/README.md@@ -19,7 +19,7 @@ browser ──▶ web/ + server/ (Node, Comfy SDK) ──▶ gateway :8000 ─|---|---|| Apps | 29 manifests, each with a workflow: 21 *ready* (an official template with only the edits listed in its recipe) and 8 *drafts* (models or LoRAs combined in ways a GPU run still has to confirm) || Workflows | Built from official sources by `tools/build_apps.py` (the two smoke apps are hand-written) and accepted by ComfyUI's validator: ComfyUI `e3bee7f` (0.42.0), ComfyUI-LTXVideo `44c8a36`, ComfyUI-CrossViewWarp `fbb1e93` |-| LoRA lab | 46 cases, at least one per app; the prompt each one would queue (values, overrides and inserted LoRAs) passes the same validator |+| LoRA lab | 47 cases, one showcase per app; the prompt each one would queue (values, overrides and inserted LoRAs) passes the same validator || End to end | Web UI → server → gateway → comfy-api-proxy → ComfyUI tested with the model-free smoke apps; lab chaining tested the same way || CI | `.github/workflows/validate.yml` runs all of the above on every push, including a CPU-only ComfyUI that checks every workflow and lab case (about 3 minutes) || GPU runs | Not yet. VRAM figures below are weight sizes, not measurements |@@ -89,31 +89,33 @@ Any ComfyUI works as the backend: run `comfy-api-proxy` next to it and `python itoo; only the unload-between-apps step is skipped. Draft apps stay locked in the UI and the CLI until you set`FREEFIELD_DRAFTS=1` (or pass `--draft` to `npm run app`).-## The LoRA lab+## The LoRA lab and the gallery-`lab/cases.json` lists LoRA experiments: reference clips are generated first, then every LoRA runs on them with a-fixed seed. The lab downloads missing models, records time and peak VRAM per case, and keeps going when one fails;-a case whose model could not be downloaded (say, a license not yet accepted) is skipped with the reason.+`lab/cases.json` lists experiments: reference images, clips and a song are generated first, then every app and LoRA+runs on them with a fixed seed. Each app has a *showcase* case, so one command makes an example of every app:```sh-python tools/comfy_validate.py --comfy-dir /path/to/ComfyUI --placeholders --lab lab/cases.json # free, CPU: every case's prompt is valid-modal run lab/lab_modal.py # all cases on an L40S-modal run lab/lab_modal.py --apps camera-moves,relight # only these apps (their reference cases come along)-FREEFIELD_GPU=A10G modal run lab/lab_modal.py --only ic-clean-plate-modal volume get freefield-lab <run_id> lab/results/<run_id>-python lab/review.py lab/results/<run_id> --apply-peaks # review page + measured VRAM into app.json+modal run --detach lab/lab_modal.py --showcase # one example per app + the references they need (36 cases)+modal run lab/lab_modal.py --pull <run_id> # only if the terminal closed before the end: copy back and publish```-Every app has at least one case, so a full run measures the peak VRAM of the whole catalog (46 cases, close to 300 GB-of models). Suggested order for the first GPU runs, smallest downloads first so problems show up cheaply:+`--detach` keeps the GPU job running if the terminal closes; the run id is printed at the start. Missing models are+downloaded first on a CPU container, so no GPU is billed while they arrive (the whole catalog is+close to 300 GB). Then one GPU container runs the cases, recording time and peak VRAM, and keeps going when one fails;+a case whose model could not be downloaded (say, a license not yet accepted) is skipped with the reason. Every output+also gets small web versions (a card, a poster for videos, a web-sized copy). At the end the run is copied to+`lab/results/<run_id>`, `review.html` is built there for rating, and `lab/publish.py` copies one example per app into+`web/examples/`: the web UI shows it as the app's thumbnail, as an *Example* block (inputs → output, with the settings+and a *Use these settings* button) and in the **gallery** tab.-1. `python tools/doctor.py` until nothing blocking is left.-2. Image apps (about 80 GB): `modal run lab/lab_modal.py --apps edit,character,product-shot,cinema-studio,styles,style-reference,relight,remove-bg,upscale`.-3. LTX-2.5 and audio (48 + 29 GB): `--apps video-t2v,video,speak,talking,music,sfx,smooth,upscale-video`, then- `--apps vfx-clean-plate,vfx-day-to-night,vfx-water,camera-copy,transitions`.-4. Wan and SCAIL (40 + 29 + 25 GB): `--apps camera-moves,recast,motion-transfer`.-5. Re-shoot (55 GB, needs the 48 GB card): `--apps reshoot`.-6. Review, apply the measured peaks, and set `"status": "ready"` on the drafts that passed.+```sh+modal run lab/lab_modal.py # every case (LoRA comparisons included) on an L40S+modal run lab/lab_modal.py --apps camera-moves,relight # only these apps (their reference cases come along)+FREEFIELD_GPU=A10G modal run lab/lab_modal.py --only ic-clean-plate # 24 GB parity check+python lab/publish.py lab/results/<run_id> # republish examples from a run you already have+python lab/review.py lab/results/<run_id> --apply-peaks # measured VRAM into each app.json+python tools/comfy_validate.py --comfy-dir /path/to/ComfyUI --placeholders --lab lab/cases.json # free, CPU: every case's prompt is valid+```## Add an appdiff --git a/lab/cases.json b/lab/cases.jsonindex 6c3ebd1..2490502 100644--- a/lab/cases.json+++ b/lab/cases.json@@ -1,7 +1,7 @@{"_about": "LoRA lab for LTX-2.5. References are generated first, then each LoRA runs on them with a fixed seed (42). Run on Modal: modal run lab/lab_modal.py","cases": [- {"id": "ref-face-a", "app": "z-image", "values": {"prompt": "Portrait of a woman with short black hair and a denim jacket, soft studio light, neutral grey background, photorealistic", "width": 1280, "height": 768},+ {"id": "ref-face-a", "showcase": true, "app": "z-image", "values": {"prompt": "Portrait of a woman with short black hair and a denim jacket, soft studio light, neutral grey background, photorealistic", "width": 1280, "height": 768},"note": "Reference still for image-to-video and transitions."},{"id": "ref-face-b", "app": "z-image", "values": {"prompt": "A polished bronze statue of a woman with short hair and a jacket, same framing, soft studio light, neutral grey background", "width": 1280, "height": 768},"note": "Last frame for the transition test."},@@ -11,11 +11,11 @@{"id": "ref-alley", "app": "video-t2v", "values": {"prompt": "Slow dolly forward through a narrow stone alley in daylight, cobblestones, potted plants, realistic", "duration": 4, "enhance": false},"note": "Reference clip for Water Simulation."},- {"id": "ic-clean-plate", "app": "vfx-clean-plate", "values": {"clip": "@case:ref-street", "size": 544},+ {"id": "ic-clean-plate", "showcase": true, "app": "vfx-clean-plate", "values": {"clip": "@case:ref-street", "size": 544},"note": "People should vanish; the background behind them should be plausible and stable."},- {"id": "ic-day-to-night", "app": "vfx-day-to-night", "values": {"clip": "@case:ref-street", "size": 448},+ {"id": "ic-day-to-night", "showcase": true, "app": "vfx-day-to-night", "values": {"clip": "@case:ref-street", "size": 448},"note": "Same shot at night; motion and layout identical to the reference."},- {"id": "ic-water", "app": "vfx-water", "values": {"clip": "@case:ref-alley"},+ {"id": "ic-water", "showcase": true, "app": "vfx-water", "values": {"clip": "@case:ref-alley"},"note": "Water should follow the alley's geometry. Prompting for this LoRA is a guess; read its model card if it fails."},{"id": "ic-refine-details", "app": "vfx-clean-plate", "values": {"clip": "@case:ref-street", "prompt": "The same city street, sharper fine detail and texture", "negative": "blurry, smeared"},"overrides": [{"node": "5004:5606", "field": "lora_name", "value": "ltx-2.5-22b-ic-lora-refine-details-1.0.safetensors"}],@@ -30,7 +30,7 @@"loras_download": [{"repo": "Lightricks/LTX-2.5-22b-IC-LoRA-Alpha-Gen", "file": "ltx-2.5-22b-ic-lora-alpha-gen-0.9.safetensors"}],"note": "Exploratory: should output a matte of the moving subjects."},- {"id": "baseline-t2v", "app": "video-t2v", "values": {"prompt": "A glass of water tips over on a wooden table and water splashes, macro shot", "duration": 4, "enhance": false},+ {"id": "baseline-t2v", "showcase": true, "app": "video-t2v", "values": {"prompt": "A glass of water tips over on a wooden table and water splashes, macro shot", "duration": 4, "enhance": false},"note": "No LoRA. Compare against the slow-motion and fluid cases, same prompt and seed."},{"id": "lora-slow-motion", "app": "video-t2v", "values": {"prompt": "A glass of water tips over on a wooden table and water splashes, macro shot, slow motion", "duration": 4, "enhance": false},"loras": [{"repo": "Lightricks/LTX-2.5-22b-LoRA-Slow-Motion-Control", "file": "ltx-2.5-22b-lora-slow-motion-control-1.0.safetensors", "strength": 1.0, "gb": 0.65}],@@ -41,18 +41,20 @@{"id": "lora-motion-enhancer", "app": "video-t2v", "values": {"prompt": "A dancer spins in an empty studio, flowing skirt, wide shot", "duration": 4, "enhance": false},"loras": [{"repo": "rzgar/LTX-2.3-Motion-Enhancer-n4w", "file": "LTX-2.3-Motion-Enhancer-n4w.safetensors", "strength": 0.8, "gb": 2.27}],"note": "Trained on 2.3: tests the 2.3 → 2.5 compatibility claim."},+ {"id": "i2v-portrait", "showcase": true, "app": "video", "values": {"image": "@case:ref-face-a", "prompt": "She slowly turns her head toward the window light and smiles, hair moving gently, soft natural light", "duration": 4, "enhance": false},+ "note": "Plain image-to-video, no LoRA: the reference for the LoRA cases below."},{"id": "lora-cinemagraph", "app": "video", "values": {"image": "@case:ref-face-a", "prompt": "Cinemagraph: only her hair moves gently in a breeze, everything else perfectly still", "duration": 4, "enhance": false},"loras": [{"repo": "Lightricks/LTX-2.5-22b-LoRA-Cinemagraph", "file": "ltx-2.5-22b-lora-cinemagraph-0.9.safetensors", "strength": 1.0, "gb": 0.20}],"note": "Official 2.5 LoRA. Only a small region should move."},{"id": "lora-ripple", "app": "video", "values": {"image": "@case:ref-face-a", "prompt": "A ripple distortion spreads across the frame like a stone dropped in water", "duration": 4, "enhance": false},"loras": [{"repo": "WepeNerd/LTX-Ripple", "file": "LTX25_Ripple_v11.safetensors", "strength": 1.0, "gb": 0.65}],"note": "Community 2.5 LoRA. The trigger phrase is not documented here; check its model card if nothing happens."},- {"id": "transition-statue", "app": "transitions", "values": {"first": "@case:ref-face-a", "last": "@case:ref-face-b", "prompt": "She slowly turns into a bronze statue, a smooth magical transformation", "duration": 4},+ {"id": "transition-statue", "showcase": true, "app": "transitions", "values": {"first": "@case:ref-face-a", "last": "@case:ref-face-b", "prompt": "She slowly turns into a bronze statue, a smooth magical transformation", "duration": 4},"note": "Transition LoRA from 2.3 on 2.5. The morph should be smooth and stay on her face."},- {"id": "ref-song", "app": "music", "values": {"style": "warm acoustic folk song, clear female lead vocal, gentle guitar, 92 bpm", "lyrics": "[verse]\nMorning light across the window\nCoffee warm and the city slow\n[chorus]\nSing it out, sing it out\nEvery little thing we know", "seconds": 10},+ {"id": "ref-song", "showcase": true, "app": "music", "values": {"style": "warm acoustic folk song, clear female lead vocal, gentle guitar, 92 bpm", "lyrics": "[verse]\nMorning light across the window\nCoffee warm and the city slow\n[chorus]\nSing it out, sing it out\nEvery little thing we know", "seconds": 10},"note": "Vocal reference for the talking avatar (MiniMax Music 3, original lyrics)."},- {"id": "talking-sing", "app": "talking", "values": {"portrait": "@case:ref-face-a", "audio": "@case:ref-song", "prompt": "She sings along to the song, natural lip movement, subtle head motion, expressive eyes, soft studio light", "duration": 5},+ {"id": "talking-sing", "showcase": true, "app": "talking", "values": {"portrait": "@case:ref-face-a", "audio": "@case:ref-song", "prompt": "She sings along to the song, natural lip movement, subtle head motion, expressive eyes, soft studio light", "duration": 5},"note": "Baseline audio-to-video: the lips should follow the vocal and the face should stay hers."},{"id": "lora-talking-head", "app": "talking", "values": {"portrait": "@case:ref-face-a", "audio": "@case:ref-song", "prompt": "She sings along to the song, natural lip movement, subtle head motion, expressive eyes, soft studio light", "duration": 5},"loras": [{"repo": "elix3r/LTX-2.3-22b-AV-LoRA-talking-head", "file": "LTX-2.3-22b-AV-LoRA-talking-head-v1.safetensors", "strength": 1.0, "gb": 0.43}],@@ -64,57 +66,57 @@"note": "Camera reference: a clean pan right."},{"id": "camera-copy-push", "app": "camera-copy", "values": {"image": "@case:ref-face-a", "clip": "@case:ref-alley", "prompt": "The camera slowly pushes in toward her face, soft studio light, shallow depth of field"},"note": "Cameraman v2 (2.3) on 2.5: the alley's dolly forward should become a push-in on the portrait."},- {"id": "camera-copy-pan", "app": "camera-copy", "values": {"image": "@case:ref-room", "clip": "@case:ref-pan", "prompt": "The camera pans to the right across the library, revealing more bookshelves and lamps"},+ {"id": "camera-copy-pan", "showcase": true, "app": "camera-copy", "values": {"image": "@case:ref-room", "clip": "@case:ref-pan", "prompt": "The camera pans to the right across the library, revealing more bookshelves and lamps"},"note": "The lake's pan right should move across the library; nothing from the lake should appear."},{"id": "camera-moves-fast", "app": "camera-moves", "preset": "fast", "values": {"image": "@case:ref-room", "prompt": "A cozy old library, dust floating in the lamp light, pages of an open book stirring", "camera": "Zoom In", "width": 832, "height": 480},"note": "Wan 2.2 Fun Camera with the 4-step LoRAs. A clean zoom in; compare speed and motion with the quality run."},- {"id": "camera-moves-quality", "app": "camera-moves", "values": {"image": "@case:ref-room", "prompt": "A cozy old library, dust floating in the lamp light, pages of an open book stirring", "camera": "Zoom In", "width": 832, "height": 480},+ {"id": "camera-moves-quality", "showcase": true, "app": "camera-moves", "values": {"image": "@case:ref-room", "prompt": "A cozy old library, dust floating in the lamp light, pages of an open book stirring", "camera": "Zoom In", "width": 832, "height": 480},"note": "Same shot with the template's 20 steps. Records the peak VRAM of the two 14B experts."},- {"id": "relight-neon", "app": "relight", "values": {"image": "@case:ref-face-a", "light": "neon night lighting, magenta and cyan rim light, dark moody background"},+ {"id": "relight-neon", "showcase": true, "app": "relight", "values": {"image": "@case:ref-face-a", "light": "neon night lighting, magenta and cyan rim light, dark moody background"},"note": "Same woman and framing, only the light changes. Records the peak VRAM of Qwen Image Edit (tight on 24 GB)."},- {"id": "smooth-slowmo", "app": "smooth", "values": {"clip": "@case:ref-street", "factor": 4, "mode": false},+ {"id": "smooth-slowmo", "showcase": true, "app": "smooth", "values": {"clip": "@case:ref-street", "factor": 4, "mode": false},"note": "FILM 4x as slow motion: four times longer at the same frame rate, no warping on the walkers."},{"id": "ref-painting", "app": "z-image", "values": {"prompt": "A thick impasto oil painting of a sunflower field under a swirling sky, bold visible brush strokes, vivid yellows and deep blues", "width": 1024, "height": 1024},"note": "Style reference for the Krea 2 test."},- {"id": "style-reference-lighthouse", "app": "style-reference", "values": {"style": "@case:ref-painting", "prompt": "a lighthouse on a cliff during a storm, waves crashing"},+ {"id": "style-reference-lighthouse", "showcase": true, "app": "style-reference", "values": {"style": "@case:ref-painting", "prompt": "a lighthouse on a cliff during a storm, waves crashing"},"note": "The lighthouse should come out as an impasto painting with the reference's palette, not a copy of the sunflowers."},- {"id": "styles-tarot", "app": "styles", "values": {"prompt": "a fox reading under a tree at dusk", "style": "vintage tarot style"},+ {"id": "styles-tarot", "showcase": true, "app": "styles", "values": {"prompt": "a fox reading under a tree at dusk", "style": "vintage tarot style"},"note": "Krea's vintage tarot LoRA: card border, aged paper, flat ornate illustration."},{"id": "ref-walk", "app": "video-t2v", "values": {"prompt": "Medium shot of a woman in a white shirt walking toward the camera on a city sidewalk, daylight, realistic", "duration": 4, "enhance": false},"note": "Driving clip for Recast: one person, clear motion."},{"id": "ref-character", "app": "z-image", "values": {"prompt": "Full body photo of a man in a red jacket, jeans and white sneakers standing straight, plain light grey studio background, photorealistic", "width": 768, "height": 1280},"note": "Character for Recast."},- {"id": "recast-walk", "app": "recast", "values": {"clip": "@case:ref-walk", "character": "@case:ref-character", "target": "woman", "prompt": "A man in a red jacket and jeans walks toward the camera on a city sidewalk, daylight, realistic", "width": 512, "height": 896},+ {"id": "recast-walk", "showcase": true, "app": "recast", "values": {"clip": "@case:ref-walk", "character": "@case:ref-character", "target": "woman", "prompt": "A man in a red jacket and jeans walks toward the camera on a city sidewalk, daylight, realistic", "width": 512, "height": 896},"note": "SCAIL-2: the man should take the woman's place and her walk, the street should stay."},{"id": "ref-product", "app": "z-image", "values": {"prompt": "A plain snapshot of a square glass perfume bottle with a gold cap and a small black label reading NOIR, on a white kitchen table, flat lighting", "width": 1024, "height": 1024},"note": "Product for Product Shot."},- {"id": "product-shot-splash", "app": "product-shot", "values": {"product": "@case:ref-product", "scene": "floating in mid-air with water splashing around it, high-speed photo, blue gradient background"},+ {"id": "product-shot-splash", "showcase": true, "app": "product-shot", "values": {"product": "@case:ref-product", "scene": "floating in mid-air with water splashing around it, high-speed photo, blue gradient background"},"note": "The bottle, cap and NOIR label must stay identical; only the scene changes."},- {"id": "speak-hello", "app": "speak", "values": {"image": "@case:ref-face-a", "line": "Hello! This voice and these lips come from a single photo and an open model.", "duration": 5, "aspect": "16:9 (Widescreen)"},+ {"id": "speak-hello", "showcase": true, "app": "speak", "values": {"image": "@case:ref-face-a", "line": "Hello! This voice and these lips come from a single photo and an open model.", "duration": 5, "aspect": "16:9 (Widescreen)"},"note": "LTX-2.5 voices the quoted line: is it intelligible, is it the right line, do the lips match?"},- {"id": "edit-jacket", "app": "edit", "values": {"image": "@case:ref-face-a", "instruction": "Change the denim jacket to deep red leather, keep everything else the same."},+ {"id": "edit-jacket", "showcase": true, "app": "edit", "values": {"image": "@case:ref-face-a", "instruction": "Change the denim jacket to deep red leather, keep everything else the same."},"note": "Only the jacket changes; face, hair and background stay."},- {"id": "character-market", "app": "character", "values": {"reference": "@case:ref-face-a", "scene": "walking through a night market, string lights, light rain"},+ {"id": "character-market", "showcase": true, "app": "character", "values": {"reference": "@case:ref-face-a", "scene": "walking through a night market, string lights, light rain"},"note": "Same woman (face, hair) in a new scene."},- {"id": "cinema-studio-detective", "app": "cinema-studio", "values": {"camera": "grand format 70mm film camera", "lens": "1970s cinema prime lens"},+ {"id": "cinema-studio-detective", "showcase": true, "app": "cinema-studio", "values": {"camera": "grand format 70mm film camera", "lens": "1970s cinema prime lens"},"note": "The camera and lens words should show: film grain and a vintage look."},- {"id": "remove-bg-product", "app": "remove-bg", "values": {"image": "@case:ref-product"},+ {"id": "remove-bg-product", "showcase": true, "app": "remove-bg", "values": {"image": "@case:ref-product"},"note": "A clean cut-out of the bottle with transparency."},- {"id": "upscale-face", "app": "upscale", "values": {"image": "@case:ref-face-a", "scale": 2},+ {"id": "upscale-face", "showcase": true, "app": "upscale", "values": {"image": "@case:ref-face-a", "scale": 2},"note": "2x with more detail in skin and hair, no plastic look."},- {"id": "upscale-video-street", "app": "upscale-video", "values": {"clip": "@case:ref-street"},+ {"id": "upscale-video-street", "showcase": true, "app": "upscale-video", "values": {"clip": "@case:ref-street"},"note": "SeedVR2 on a 4 s clip: sharper, no flicker."},- {"id": "sfx-rain", "app": "sfx", "values": {"description": "heavy rain on a tin roof with distant thunder", "seconds": 10},+ {"id": "sfx-rain", "showcase": true, "app": "sfx", "values": {"description": "heavy rain on a tin roof with distant thunder", "seconds": 10},"note": "Stable Audio 3: rain and thunder, no music."},- {"id": "motion-transfer-walk", "app": "motion-transfer", "values": {"character": "@case:ref-character", "motion": "@case:ref-walk", "character_prompt": "Character appearance description: a man in a red jacket, jeans and white sneakers", "action_prompt": "walking toward the camera on a city sidewalk"},+ {"id": "motion-transfer-walk", "showcase": true, "app": "motion-transfer", "values": {"character": "@case:ref-character", "motion": "@case:ref-walk", "character_prompt": "Character appearance description: a man in a red jacket, jeans and white sneakers", "action_prompt": "walking toward the camera on a city sidewalk"},"note": "Wan Animate 2: compare with recast-walk (SCAIL-2) on the same inputs."},- {"id": "reshoot-orbit", "app": "reshoot", "values": {"clip": "@case:ref-alley", "azimuth": -30, "elevation": 15, "duration": 4},+ {"id": "reshoot-orbit", "showcase": true, "app": "reshoot", "values": {"clip": "@case:ref-alley", "azimuth": -30, "elevation": 15, "duration": 4},"note": "MiniMax H3 + MoGe: the alley from 30 degrees to the left. Needs 48 GB (its text encoder alone is 27 GB)."}]}diff --git a/lab/core.py b/lab/core.pyindex c863b72..c238090 100644--- a/lab/core.py+++ b/lab/core.py@@ -181,6 +181,73 @@ def models_for_cases(cases: list[dict], apps_dir: Path) -> list[dict]:return out+# ---------------------------------------------------------------- web versions+IMAGE_EXT = {".png", ".jpg", ".jpeg", ".webp"}+VIDEO_EXT = {".mp4", ".webm", ".mov", ".mkv", ".gif"}+AUDIO_EXT = {".flac", ".mp3", ".wav", ".ogg", ".opus", ".m4a"}+ALPHA_PIX = re.compile(r"^(rgba|bgra|argb|abgr|ya\d|yuva|gbrap|pal8)")+++def media_kind(path: Path) -> str | None:+ ext = path.suffix.lower()+ return "image" if ext in IMAGE_EXT else "video" if ext in VIDEO_EXT else "audio" if ext in AUDIO_EXT else None+++def _ffmpeg(*args: str) -> bool:+ try:+ return subprocess.run(["ffmpeg", "-y", "-v", "error", *args], capture_output=True, timeout=600).returncode == 0+ except (OSError, subprocess.TimeoutExpired):+ return False+++def _has_alpha(path: Path) -> bool:+ try:+ out = subprocess.run(["ffprobe", "-v", "error", "-select_streams", "v:0", "-show_entries", "stream=pix_fmt",+ "-of", "csv=p=0", str(path)], capture_output=True, text=True, timeout=60).stdout.strip()+ except (OSError, subprocess.TimeoutExpired):+ return path.suffix.lower() == ".png"+ return bool(ALPHA_PIX.match(out))+++def web_versions(src: Path, dest: Path) -> dict:+ """Small files for the gallery: a card (thumbnail), a poster for videos and a web-sized full version.++ Images become JPEG (PNG when they have transparency), videos H.264 MP4 (the card muted, 5 s,+ 360 p), audio MP3 with a waveform picture as its card. Needs ffmpeg (the Modal image has it);+ without it the original file stands in for every version. Paths are relative to dest.parent.+ """+ kind = media_kind(src)+ out = {"type": kind, "card": None, "poster": None, "full": None, "source": src.name}+ if kind is None:+ return out+ dest.mkdir(parents=True, exist_ok=True)+ rel = lambda p: f"{dest.name}/{p.name}" # noqa: E731+ if kind == "image":+ ext = ".png" if _has_alpha(src) else ".jpg"+ q = [] if ext == ".png" else ["-q:v", "3"]+ if _ffmpeg("-i", str(src), "-vf", "scale='min(640,iw)':-2", *q, str(dest / f"card{ext}")):+ out["card"] = rel(dest / f"card{ext}")+ if _ffmpeg("-i", str(src), "-vf", "scale='min(1600,iw)':-2", *q, str(dest / f"full{ext}")):+ out["full"] = rel(dest / f"full{ext}")+ elif kind == "video":+ if _ffmpeg("-i", str(src), "-t", "5", "-vf", "scale=-2:'min(360,ih)'", "-an", "-c:v", "libx264", "-preset", "medium",+ "-crf", "30", "-pix_fmt", "yuv420p", "-movflags", "+faststart", str(dest / "card.mp4")):+ out["card"] = rel(dest / "card.mp4")+ if _ffmpeg("-i", str(src), "-vf", "thumbnail,scale='min(640,iw)':-2", "-frames:v", "1", "-q:v", "3", str(dest / "poster.jpg")):+ out["poster"] = rel(dest / "poster.jpg")+ if _ffmpeg("-i", str(src), "-vf", "scale=-2:'min(720,ih)'", "-c:v", "libx264", "-preset", "medium", "-crf", "26",+ "-pix_fmt", "yuv420p", "-c:a", "aac", "-b:a", "128k", "-movflags", "+faststart", str(dest / "full.mp4")):+ out["full"] = rel(dest / "full.mp4")+ else:+ if _ffmpeg("-i", str(src), "-filter_complex", "showwavespic=s=640x160:colors=#e8ff5a:scale=sqrt", "-frames:v", "1", str(dest / "card.png")):+ out["card"] = rel(dest / "card.png")+ if _ffmpeg("-i", str(src), "-c:a", "libmp3lame", "-b:a", "160k", str(dest / "full.mp3")):+ out["full"] = rel(dest / "full.mp3")+ if out["full"] is None: # no ffmpeg: the original is the full version+ out["full"] = src.name+ return out++# ---------------------------------------------------------------- runnerclass Lab:def __init__(self, url: str, input_dir: Path, output_dir: Path, results_dir: Path,@@ -216,10 +283,13 @@ class Lab:def run_case(self, case: dict) -> dict:cid = case["id"]res = {"id": cid, "app": case["app"], "status": "error", "seconds": None, "peak_vram_gb": None,- "files": [], "error": None, "values": {}, "loras": case.get("loras", []),- "overrides": case.get("overrides", []), "note": case.get("note", "")}+ "files": [], "error": None, "values": {}, "inputs": {}, "web": None, "loras": case.get("loras", []),+ "overrides": case.get("overrides", []), "note": case.get("note", ""), "showcase": bool(case.get("showcase"))}try:manifest, api, res["values"] = build_case(self.apps_dir, case, self._file_value)+ # where each file input came from ("@case:<id>", "asset:<name>" or a path), for the gallery+ types = {i["id"]: i["type"] for i in manifest.get("inputs", [])}+ res["inputs"] = {k: v for k, v in case.get("values", {}).items() if types.get(k) in FILE_TYPES}# skip, with the reason, when a file this exact prompt loads could not be downloadedused = {v for n in api.values() for v in n["inputs"].values() if isinstance(v, str)}lacking = sorted(used & set(self.missing))@@ -271,8 +341,11 @@ class Lab:shutil.copy(src, dst)saved.append(dst)self.outputs[cid] = saved- res["files"] = [str(p.relative_to(self.results_dir)) for p in saved]+ res["files"] = [p.relative_to(self.results_dir).as_posix() for p in saved]res["status"] = "ok" if saved else "no-output"+ if saved:+ web = web_versions(saved[0], out_dir / "web")+ res["web"] = {k: (f"{cid}/{v}" if k in ("card", "poster", "full") and v else v) for k, v in web.items()}except Exception as e: # keep going: one broken LoRA must not stop the batchres["error"] = f"{type(e).__name__}: {e}"return resdiff --git a/lab/lab_modal.py b/lab/lab_modal.pyindex 9bb7176..4d49587 100644--- a/lab/lab_modal.py+++ b/lab/lab_modal.py@@ -1,15 +1,17 @@-"""LoRA lab on Modal: launch a batch of cases, then download the results for review.+"""LoRA lab on Modal: launch a batch of cases, download the results, review and publish them.+ modal run lab/lab_modal.py --showcase # one example per app (+ the references they need)modal run lab/lab_modal.py # every case in lab/cases.json, on an L40S- FREEFIELD_GPU=A10G modal run lab/lab_modal.py --only ic-clean-plate,ic-day-to-night # 24 GB parity checkmodal run lab/lab_modal.py --apps camera-moves,relight # every case of these apps- modal volume get freefield-lab <run_id> lab/results/<run_id>- python lab/review.py lab/results/<run_id> # opens a gallery to rate each result+ FREEFIELD_GPU=A10G modal run lab/lab_modal.py --only ic-clean-plate,ic-day-to-night # 24 GB parity check+ modal run lab/lab_modal.py --pull <run_id> # copy back and publish a run that finished without you-Missing model files are downloaded into the "freefield-models" volume first (gated repos-need the "huggingface" secret and an accepted license). Results and a results.jsonl with-time and peak VRAM per case are written to the "freefield-lab" volume as they finish, so a-partial run is still useful.+Missing model files are downloaded first on a CPU container (no GPU billed while they+arrive) into the "freefield-models" volume; gated repos need the "huggingface" secret and an+accepted license. Results, a results.jsonl with time and peak VRAM per case, and small web+versions of every output go to the "freefield-lab" volume as each case finishes, so a partial+run is still useful. At the end the run is copied to lab/results/<run_id>, review.html is+built there, and the examples the web UI shows are refreshed (--no-publish to skip)."""from __future__ import annotations@@ -31,6 +33,15 @@ app = modal.App("freefield-lab")image = build_image().add_local_python_source("infra")[email protected](image=image, volumes={"/models": models_volume}, secrets=[hf_secret], timeout=4 * 3600, cpu=4, memory=8192)+def fetch(models: list[dict]) -> dict[str, str]:+ """Download the models a run needs, on CPU. Returns {file: reason} for those that failed."""+ fetched, failed = ensure_models(models)+ if fetched:+ models_volume.commit()+ return failed++@app.function(image=image, gpu=GPU, volumes={"/models": models_volume, "/lab": lab_volume},secrets=[hf_secret], timeout=8 * 3600)def run(cases: list[dict], run_id: str, assets: dict[str, bytes]) -> list[dict]:@@ -73,18 +84,58 @@ def with_dependencies(spec: list[dict], keep: set[str]) -> list[dict]:return [c for c in spec if c["id"] in seen]+def download_run(run_id: str, dest: Path) -> int:+ """Copy /<run_id> from the lab volume to dest; files already there with the same size are kept."""+ n = 0+ for entry in lab_volume.iterdir(f"/{run_id}", recursive=True):+ if int(entry.type) != 1: # 1 = file+ continue+ rel = entry.path.lstrip("/")+ rel = rel[len(run_id) + 1:] if rel.startswith(run_id + "/") else rel+ target = dest / rel+ if target.exists() and target.stat().st_size == entry.size:+ continue+ target.parent.mkdir(parents=True, exist_ok=True)+ with open(target, "wb") as f:+ for chunk in lab_volume.read_file(entry.path):+ f.write(chunk)+ n += 1+ return n+++def finish(run_id: str, publish: bool) -> None:+ """Copy the run to lab/results/<run_id>, build review.html there and publish the examples."""+ sys.path.insert(0, str(Path(__file__).resolve().parent))+ dest = Path("lab/results") / run_id+ print(f"downloading the run to {dest} ...")+ print(f" {download_run(run_id, dest)} new files")+ import review # lab/review.py+ review.main([str(dest)])+ print(f"review: {dest / 'review.html'}")+ if publish:+ import publish as publisher # lab/publish.py+ publisher.main([str(dest)])++@app.local_entrypoint()-def main(cases: str = "lab/cases.json", only: str = "", apps: str = "", run_id: str = ""):- """--only case,ids or --apps app,ids (their reference cases come along)."""+def main(cases: str = "lab/cases.json", only: str = "", apps: str = "", showcase: bool = False,+ run_id: str = "", publish: bool = True, pull: str = ""):+ """--showcase (one case per app), --only case,ids or --apps app,ids; their reference cases come along.+ --pull <run_id> only copies an earlier run back (say, after the terminal closed) and publishes it."""+ if pull:+ finish(pull, publish)+ returnspec = json.loads(Path(cases).read_text(encoding="utf-8"))["cases"]keep = set(filter(None, only.split(","))) | {c["id"] for c in spec if c["app"] in set(filter(None, apps.split(",")))}- if only or apps:+ if showcase:+ keep |= {c["id"] for c in spec if c.get("showcase")}+ if only or apps or showcase:unknown = set(filter(None, only.split(","))) - {c["id"] for c in spec}if unknown:raise SystemExit(f"unknown case id(s): {', '.join(sorted(unknown))}")spec = with_dependencies(spec, keep)if not spec:- raise SystemExit("no case matches --only/--apps")+ raise SystemExit("no case matches --only/--apps/--showcase")assets = {}for c in spec:for v in c.get("values", {}).values():@@ -92,9 +143,17 @@ def main(cases: str = "lab/cases.json", only: str = "", apps: str = "", run_id:name = v[len("asset:"):]assets[name] = (Path("lab/assets") / name).read_bytes()run_id = run_id or time.strftime("%Y%m%d-%H%M%S") + f"-{GPU.lower()}"- print(f"run {run_id}: {len(spec)} cases on {GPU}")+ sys.path.insert(0, str(Path(__file__).resolve().parent))+ import core # lab/core.py: which models these cases load+ needed = core.models_for_cases(spec, Path(__file__).resolve().parent.parent / "apps")+ print(f"run {run_id}: {len(spec)} cases; making sure {len(needed)} model files are in the volume (CPU)")+ failed = fetch.remote(needed)+ if failed:+ print(f"{len(failed)} file(s) could not be downloaded; the cases that need them will be skipped:")+ for name, reason in failed.items():+ print(f" {name}: {reason}")+ print(f"running on {GPU}")results = run.remote(spec, run_id, assets)ok = sum(r["status"] == "ok" for r in results)print(f"\n{ok}/{len(results)} ok")- print(f"download: modal volume get freefield-lab {run_id} lab/results/{run_id}")- print(f"review: python lab/review.py lab/results/{run_id}")+ finish(run_id, publish)diff --git a/lab/publish.py b/lab/publish.pynew file mode 100644index 0000000..85421e3--- /dev/null+++ b/lab/publish.py@@ -0,0 +1,116 @@+#!/usr/bin/env python3+"""Publish one example per app from a lab run into the web UI.++ python lab/publish.py lab/results/<run_id>++For every app it picks a case that succeeded (the one marked "showcase" in lab/cases.json if+it ran, otherwise the first one in file order) and copies that case's web versions into+web/examples/<app>/, plus small previews of the files the case was given (the reference images,+clips or songs made earlier in the run). web/examples/index.json lists them; the web UI uses it+for the app cards, the example shown with each app, and the gallery. Apps without a successful+case keep the example they had.+"""+from __future__ import annotations++import argparse+import json+import shutil+import sys+from pathlib import Path++ROOT = Path(__file__).resolve().parent.parent+EXAMPLES = ROOT / "web" / "examples"+HIDDEN = {"smoke", "smoke-invert"}+++def read_results(run_dir: Path) -> dict[str, dict]:+ """Last result per case id (results.jsonl is appended to when a run id is reused)."""+ out: dict[str, dict] = {}+ path = run_dir / "results.jsonl"+ if not path.exists():+ raise SystemExit(f"{path} not found; is {run_dir} a lab run folder?")+ for line in path.read_text(encoding="utf-8").splitlines():+ if line.strip():+ r = json.loads(line)+ out[r["id"]] = r+ return out+++def copy_as(run_dir: Path, rel: str | None, dest: Path, stem: str) -> str | None:+ """Copy run_dir/rel to dest/<stem><ext>; returns the path the web UI uses, or None."""+ if not rel or not (run_dir / rel).exists():+ return None+ target = dest / f"{stem}{Path(rel).suffix.lower()}"+ shutil.copy(run_dir / rel, target)+ return target.relative_to(ROOT / "web").as_posix()+++def main(argv: list[str] | None = None) -> int:+ ap = argparse.ArgumentParser(description=__doc__.splitlines()[0])+ ap.add_argument("run_dir", type=Path)+ a = ap.parse_args(argv)+ run_dir = a.run_dir.resolve()+ results = read_results(run_dir)+ order = [c["id"] for c in json.loads((ROOT / "lab" / "cases.json").read_text(encoding="utf-8"))["cases"]]+ rank = {cid: i for i, cid in enumerate(order)}+ meta = json.loads((run_dir / "run.json").read_text(encoding="utf-8")) if (run_dir / "run.json").exists() else {}++ index_path = EXAMPLES / "index.json"+ index = json.loads(index_path.read_text(encoding="utf-8")) if index_path.exists() else {"apps": {}}+ published, missing = [], []+ for manifest_path in sorted((ROOT / "apps").glob("*/app.json")):+ manifest = json.loads(manifest_path.read_text(encoding="utf-8"))+ app_id = manifest["id"]+ if app_id in HIDDEN:+ continue+ ok = [r for r in results.values() if r["app"] == app_id and r["status"] == "ok" and r.get("web")]+ if not ok:+ missing.append(app_id)+ continue+ pick = sorted(ok, key=lambda r: (not r.get("showcase"), rank.get(r["id"], 10**6)))[0]+ web = pick["web"]+ dest = EXAMPLES / app_id+ if dest.exists():+ shutil.rmtree(dest) # only ever our own generated folder+ dest.mkdir(parents=True)+ full = copy_as(run_dir, web.get("full"), dest, "full")+ card = copy_as(run_dir, web.get("card"), dest, "card") or (full if web.get("type") == "image" else None)+ poster = copy_as(run_dir, web.get("poster"), dest, "poster")++ labels = {i["id"]: i for i in manifest.get("inputs", [])}+ inputs = []+ for input_id, raw in (pick.get("inputs") or {}).items():+ src = None+ if isinstance(raw, str) and raw.startswith("@case:"):+ source = results.get(raw[len("@case:"):])+ if source and source.get("web"):+ w = source["web"]+ # a still for images, the poster for clips, the waveform for audio, plus the playable file+ src = copy_as(run_dir, w.get("card") if w.get("type") != "video" else w.get("poster"), dest, f"input-{input_id}")+ playable = copy_as(run_dir, w.get("full"), dest, f"input-{input_id}-full") if w.get("type") in ("video", "audio") else None+ inputs.append({"id": input_id, "label": labels.get(input_id, {}).get("label", input_id),+ "type": w.get("type"), "src": src, "full": playable, "from_case": source["id"]})+ continue+ inputs.append({"id": input_id, "label": labels.get(input_id, {}).get("label", input_id),+ "type": labels.get(input_id, {}).get("type"), "src": None, "full": None, "from": raw})++ shown = {k: v for k, v in (pick.get("values") or {}).items() if k != "seed"}+ index["apps"][app_id] = {+ "case": pick["id"], "type": web.get("type"), "card": card, "poster": poster, "full": full,+ "inputs": inputs, "values": shown, "seed": (pick.get("values") or {}).get("seed"),+ "seconds": pick.get("seconds"), "peak_vram_gb": pick.get("peak_vram_gb"),+ "gpu": meta.get("gpu"), "run": run_dir.name,+ }+ published.append(app_id)++ EXAMPLES.mkdir(parents=True, exist_ok=True)+ index["updated_from"] = run_dir.name+ index_path.write_text(json.dumps(index, indent=2, ensure_ascii=False) + "\n", encoding="utf-8")+ print(f"published {len(published)} app example(s) to {EXAMPLES.relative_to(ROOT)}")+ if missing:+ print(f"no successful case in this run for: {', '.join(missing)}")+ return 0+++if __name__ == "__main__":+ sys.exit(main())diff --git a/server/cli.ts b/server/cli.tsindex 01811a3..e36cfde 100644--- a/server/cli.ts+++ b/server/cli.ts@@ -5,7 +5,7 @@import { mkdirSync, readFileSync } from "node:fs";import { basename, join } from "node:path";import { loadRegistry } from "./registry.ts";-import { Runner, type Values } from "./runner.ts";+import { explainSubmitError, Runner, type Values } from "./runner.ts";const [cmd, ...rest] = process.argv.slice(2);const { apps, problems } = loadRegistry();@@ -60,7 +60,7 @@ if (cmd === "validate") {try {job = await runner.submit(app, values, preset);} catch (e) {- console.error(`could not submit ${app.id}: ${(e as Error).message}`);+ console.error(`could not submit ${app.id}: ${explainSubmitError(app, e) ?? (e as Error).message}`);process.exit(1);}console.log(`submitted ${app.id} → job ${job.id}`);diff --git a/server/runner.ts b/server/runner.tsindex c950f8f..0492286 100644--- a/server/runner.ts+++ b/server/runner.ts@@ -104,6 +104,41 @@ export function applyInputs(}}+type NodeError = { type?: string; message?: string; details?: string; extra_info?: { input_name?: string; received_value?: unknown } };+type NodeErrors = Record<string, { class_type?: string; errors?: NodeError[] } | NodeError[]>;++/**+ * Turn ComfyUI's validation errors (relayed by the proxy as details.node_errors) into lines a+ * person can act on. When a loader asks for a model file the backend does not have, say which+ * pack to download. Returns null for errors that are not workflow validation errors.+ */+export function explainSubmitError(app: App, e: unknown): string | null {+ const err = e as { code?: string; details?: { node_errors?: NodeErrors } | null; message?: string };+ if (err?.code !== "invalid_workflow") return null;+ const modelFiles = new Set(app.models.map((m) => m.file.split("/").pop()));+ const lines: string[] = [];+ let missingModel = false;+ for (const [node, entry] of Object.entries(err.details?.node_errors ?? {})) {+ const errors = Array.isArray(entry) ? entry : entry.errors ?? [];+ const cls = Array.isArray(entry) ? "" : entry.class_type ?? "";+ for (const x of errors) {+ const received = x.extra_info?.received_value ?? /'([^']+)' not in/.exec(x.details ?? "")?.[1];+ if (x.type === "value_not_in_list" && typeof received === "string" && modelFiles.has(received)) {+ missingModel = true;+ lines.push(`${cls || "node"} (node ${node}): model file ${received} is not on the backend`);+ } else {+ const detail = (x.details ?? "").replace(/ not in \[.*$/s, " is not one of the allowed values");+ lines.push(`${cls || "node"} (node ${node}): ${x.message ?? x.type ?? "invalid"}${detail ? ` (${detail.slice(0, 200)})` : ""}`);+ }+ }+ }+ if (!lines.length) lines.push(err.message ?? "workflow rejected");+ if (missingModel) {+ lines.push(`Download the "${app.pack}" pack first: modal run infra/modal_app.py::download --pack ${app.pack}`);+ }+ return `ComfyUI rejected the workflow:\n${lines.map((l) => ` ${l}`).join("\n")}`;+}+export type RunnerOptions = {/** Gateway in front of comfy-api-proxy, e.g. https://you--freefield-serve.modal.run */baseUrl?: string;diff --git a/server/server.ts b/server/server.tsindex 047bc4a..96026ee 100644--- a/server/server.ts+++ b/server/server.ts@@ -3,12 +3,13 @@// POST /api/apps/:id/run multipart form: one field per input id, optional "preset"// GET /api/jobs/:id status and outputs// GET /api/jobs/:id/outputs/:outputId output bytes-// Everything else is served from web/ when it exists.+// Everything else is served from web/ when it exists (with byte ranges, so videos seek everywhere).+// web/examples/ holds one example per app, written by lab/publish.py; /api/apps carries it along.import { createServer, type IncomingMessage, type ServerResponse } from "node:http";-import { existsSync, readFileSync, statSync } from "node:fs";+import { createReadStream, existsSync, readFileSync, statSync } from "node:fs";import { extname, join, normalize } from "node:path";import { loadRegistry, repoRoot, isFileInput, type App } from "./registry.ts";-import { InputError, Runner, type Values } from "./runner.ts";+import { explainSubmitError, InputError, Runner, type Values } from "./runner.ts";const root = repoRoot();const { apps, problems } = loadRegistry(root);@@ -27,9 +28,20 @@ const draftsAllowed = process.env.FREEFIELD_DRAFTS === "1";const MIME: Record<string, string> = {".html": "text/html; charset=utf-8", ".js": "text/javascript", ".css": "text/css", ".json": "application/json",- ".svg": "image/svg+xml", ".png": "image/png", ".webp": "image/webp", ".jpg": "image/jpeg", ".mp4": "video/mp4",+ ".svg": "image/svg+xml", ".png": "image/png", ".webp": "image/webp", ".jpg": "image/jpeg", ".jpeg": "image/jpeg",+ ".gif": "image/gif", ".mp4": "video/mp4", ".webm": "video/webm", ".mp3": "audio/mpeg",};+// one example per app (lab/publish.py); read on every catalog request so a new publish shows up without a restart+const examplesFile = join(root, "web", "examples", "index.json");+function loadExamples(): Record<string, unknown> {+ try {+ return existsSync(examplesFile) ? (JSON.parse(readFileSync(examplesFile, "utf-8")).apps ?? {}) : {};+ } catch {+ return {};+ }+}+function publicApp(a: App) {return {id: a.id, name: a.name, section: a.section, summary: a.summary ?? "", status: a.status, pack: a.pack,@@ -104,14 +116,22 @@ const server = createServer(async (req, res) => {const order = { image: 0, video: 1, audio: 2, utility: 3 } as Record<string, number>;const sorted = [...apps].sort((a, b) => order[a.section] - order[b.section]|| Number(b.status === "ready") - Number(a.status === "ready") || a.name.localeCompare(b.name));- return send(res, 200, { apps: sorted.map(publicApp) });+ const examples = loadExamples();+ return send(res, 200, { apps: sorted.map((a) => ({ ...publicApp(a), example: examples[a.id] ?? null })) });}if (req.method === "POST" && parts[1] === "apps" && parts[3] === "run") {const app = byId.get(parts[2]);if (!app) return send(res, 404, { error: "unknown app" });const { values, preset } = await readValues(app, await toRequest(req));- const job = await getRunner().submit(app, values, preset);- return send(res, 202, { id: job.id, status: job.status });+ try {+ const job = await getRunner().submit(app, values, preset);+ return send(res, 202, { id: job.id, status: job.status });+ } catch (e) {+ const explained = explainSubmitError(app, e);+ if (!explained) throw e;+ console.error(`[${app.id}] ${explained}`);+ return send(res, 422, { error: explained });+ }}if (req.method === "GET" && parts[1] === "jobs" && parts.length === 3) {return send(res, 200, await jobView(parts[2]));@@ -131,8 +151,21 @@ const server = createServer(async (req, res) => {const rel = normalize(url.pathname === "/" ? "index.html" : url.pathname.slice(1)).replace(/^(\.\.[/\\])+/, "");const file = join(webRoot, rel);if (file.startsWith(webRoot) && existsSync(file) && statSync(file).isFile()) {- res.writeHead(200, { "content-type": MIME[extname(file)] ?? "application/octet-stream" });- return res.end(readFileSync(file));+ const size = statSync(file).size;+ const type = MIME[extname(file).toLowerCase()] ?? "application/octet-stream";+ const range = /^bytes=(\d*)-(\d*)$/.exec(req.headers.range ?? "");+ if (range && (range[1] || range[2])) {+ const start = range[1] ? Number(range[1]) : Math.max(0, size - Number(range[2]));+ const end = range[1] && range[2] ? Math.min(Number(range[2]), size - 1) : size - 1;+ if (start > end || start >= size) {+ res.writeHead(416, { "content-range": `bytes */${size}` });+ return res.end();+ }+ res.writeHead(206, { "content-type": type, "content-length": end - start + 1, "content-range": `bytes ${start}-${end}/${size}`, "accept-ranges": "bytes" });+ return createReadStream(file, { start, end }).pipe(res);+ }+ res.writeHead(200, { "content-type": type, "content-length": size, "accept-ranges": "bytes" });+ return createReadStream(file).pipe(res);}return send(res, 404, { error: "not found" });} catch (e) {diff --git a/test/runner.test.ts b/test/runner.test.tsindex 169dba4..7b017fe 100644--- a/test/runner.test.ts+++ b/test/runner.test.ts@@ -1,7 +1,7 @@import { test } from "node:test";import assert from "node:assert/strict";import { loadRegistry } from "../server/registry.ts";-import { applyInputs, InputError, renderTemplate, resolveValues, Runner, type Settable } from "../server/runner.ts";+import { applyInputs, explainSubmitError, InputError, renderTemplate, resolveValues, Runner, type Settable } from "../server/runner.ts";const { apps } = loadRegistry();const byId = (id: string) => apps.find((a) => a.id === id)!;@@ -66,6 +66,22 @@ test("a select option writes its extra fields (style → LoRA file)", () => {assert.throws(() => resolveValues(app, { prompt: "a fox", style: "not a style" }), InputError);});+test("validation errors name the node and, for a missing model file, the pack to download", () => {+ const app = byId("edit");+ // the shape ComfyUI returns (captured from a real /prompt rejection), relayed by comfy-api-proxy+ const nodeErrors = {+ "1": { class_type: "UNETLoader", errors: [{ type: "value_not_in_list", message: "Value not in list",+ details: "unet_name: 'flux3-image-klein-int8-convrot.safetensors' not in (list of length 74)",+ extra_info: { input_name: "unet_name", received_value: "flux3-image-klein-int8-convrot.safetensors" } }] },+ "7": { class_type: "KSampler", errors: [{ type: "value_bigger_than_max", message: "Value bigger than max", details: "steps: 999" }] },+ };+ const msg = explainSubmitError(app, { code: "invalid_workflow", message: "Prompt outputs failed validation", details: { node_errors: nodeErrors } })!;+ assert.match(msg, /UNETLoader \(node 1\): model file flux3-image-klein-int8-convrot\.safetensors is not on the backend/);+ assert.match(msg, /KSampler \(node 7\): Value bigger than max \(steps: 999\)/);+ assert.match(msg, /--pack image-flux3/);+ assert.equal(explainSubmitError(app, new Error("network down")), null);+});+test("renderTemplate tidies empty placeholders", () => {assert.equal(renderTemplate("{a}, {b}, {c}", { a: "x", c: "z" }), "x, z");});diff --git a/web/index.html b/web/index.htmlindex 087eb0b..3256ead 100644--- a/web/index.html+++ b/web/index.html@@ -5,7 +5,8 @@<meta name="viewport" content="width=device-width, initial-scale=1"><title>Freefield</title><style>- /* Minimal menu + auto-generated forms. Everything on screen comes from /api/apps (the app.json files). */+ /* Menu + auto-generated forms + gallery. Everything on screen comes from /api/apps (the app.json files)+ and web/examples/index.json (one lab result per app, written by lab/publish.py). */:root { --bg:#0e1116; --panel:#161b22; --line:#2b333d; --ink:#e9edf2; --dim:#93a0ae; --accent:#e8ff5a; --bad:#ff7a6b; }* { box-sizing: border-box; }body { margin: 0; background: var(--bg); color: var(--ink); font: 15px/1.5 system-ui, -apple-system, "Segoe UI", sans-serif; }@@ -15,12 +16,20 @@nav { display: flex; gap: 6px; margin-left: auto; flex-wrap: wrap; }nav button { background: none; border: 1px solid var(--line); color: var(--ink); border-radius: 999px; padding: 4px 12px; cursor: pointer; }nav button[aria-pressed="true"] { background: var(--ink); color: var(--bg); }- main { display: grid; grid-template-columns: minmax(260px, 360px) 1fr; min-height: calc(100vh - 70px); }+ nav button.gallery-tab { border-color: var(--accent); }+ main { display: grid; grid-template-columns: minmax(280px, 380px) 1fr; min-height: calc(100vh - 70px); }@media (max-width: 760px) { main { grid-template-columns: 1fr; } }+ [hidden] { display: none !important; }#menu { border-right: 1px solid var(--line); padding: 12px; display: grid; gap: 8px; align-content: start; }- .item { text-align: left; background: var(--panel); border: 1px solid var(--line); border-radius: 10px; padding: 10px 12px; color: var(--ink); cursor: pointer; display: grid; gap: 2px; }+ .item { text-align: left; background: var(--panel); border: 1px solid var(--line); border-radius: 10px; padding: 8px; color: var(--ink); cursor: pointer;+ display: grid; grid-template-columns: 72px 1fr; gap: 10px; align-items: start; }+ .item.nothumb { grid-template-columns: 1fr; padding: 10px 12px; }.item[aria-current="true"] { border-color: var(--accent); }+ .item .txt { display: grid; gap: 2px; min-width: 0; }.item small { color: var(--dim); }+ .thumb { width: 72px; height: 72px; object-fit: cover; border-radius: 7px; background: #000; display: block; }+ .thumb.audio { object-fit: contain; background: #0b0f14; }+ img.alpha { background: repeating-conic-gradient(#232a33 0% 25%, #151a20 0% 50%) 50% / 16px 16px; } /* transparency shows as a checkerboard */.badge { font-size: 11px; text-transform: uppercase; letter-spacing: .08em; color: var(--dim); }#app { padding: 20px max(16px, env(safe-area-inset-right)) 40px 24px; display: grid; gap: 16px; align-content: start; min-width: 0; }#app h2 { margin: 0; font-size: 22px; }@@ -33,8 +42,9 @@.row { display: flex; gap: 10px; align-items: center; }button.run { justify-self: start; background: var(--accent); color: #11140a; border: 0; border-radius: 8px; padding: 10px 18px; font-weight: 700; cursor: pointer; }button.run:disabled { opacity: .45; cursor: not-allowed; }+ button.ghost { background: none; color: var(--ink); border: 1px solid var(--line); border-radius: 8px; padding: 6px 12px; cursor: pointer; font: inherit; }#status { color: var(--dim); min-height: 1.5em; }- #status.err { color: var(--bad); }+ #status.err { color: var(--bad); white-space: pre-wrap; }#outputs { display: grid; gap: 12px; grid-template-columns: repeat(auto-fill, minmax(280px, 1fr)); }#outputs img, #outputs video { width: 100%; border-radius: 10px; background: #000; }.note { margin: 0; max-width: 640px; padding: 8px 12px; border-left: 3px solid var(--accent); background: var(--panel); border-radius: 0 8px 8px 0; color: var(--dim); font-size: 14px; }@@ -44,6 +54,35 @@details summary { cursor: pointer; font-weight: 600; }details ul { margin: 8px 0 0; padding-left: 18px; display: grid; gap: 4px; }details li small { color: var(--dim); }+ /* example: what the app made in the lab, from which inputs, with which settings */+ .example { max-width: 860px; border: 1px solid var(--line); border-radius: 12px; background: var(--panel); padding: 12px; display: grid; gap: 10px; }+ .example h3 { margin: 0; font-size: 15px; display: flex; gap: 10px; align-items: baseline; flex-wrap: wrap; }+ .example h3 small { font-weight: 400; color: var(--dim); }+ .flow { display: grid; grid-template-columns: minmax(0, 1fr) auto minmax(0, 2fr); gap: 12px; align-items: center; }+ .flow.solo { grid-template-columns: 1fr; }+ @media (max-width: 760px) { .flow { grid-template-columns: 1fr; } .flow .arrow { transform: rotate(90deg); justify-self: center; } }+ .ins { display: grid; gap: 8px; }+ figure { margin: 0; display: grid; gap: 4px; }+ figure img, figure video { width: 100%; border-radius: 8px; background: #000; display: block; }+ figure audio { width: 100%; }+ figcaption { font-size: 12px; color: var(--dim); }+ .arrow { color: var(--accent); font-size: 22px; }+ dl.vals { margin: 0; display: grid; grid-template-columns: max-content 1fr; gap: 2px 12px; font-size: 13px; }+ dl.vals dt { color: var(--dim); } dl.vals dd { margin: 0; overflow-wrap: anywhere; }+ /* gallery */+ #gallery { padding: 16px max(16px, env(safe-area-inset-right)) 40px max(16px, env(safe-area-inset-left)); display: grid; gap: 14px; align-content: start; }+ #gallery .lead { margin: 0; color: var(--dim); }+ .tiles { display: grid; gap: 14px; grid-template-columns: repeat(auto-fill, minmax(min(100%, 300px), 1fr)); }+ .tile { text-align: left; background: var(--panel); border: 1px solid var(--line); border-radius: 12px; padding: 0; overflow: hidden; color: var(--ink); cursor: pointer; display: grid; font: inherit; }+ .tile:hover { border-color: var(--accent); }+ .tile .media { aspect-ratio: 16 / 10; background: #000; display: grid; place-items: center; overflow: hidden; }+ .tile .media img, .tile .media video { width: 100%; height: 100%; object-fit: cover; display: block; }+ .tile .media img.audio { object-fit: contain; padding: 12px; }+ .tile .meta { padding: 10px 12px; display: grid; gap: 4px; }+ .tile .from { display: flex; gap: 6px; align-items: center; color: var(--dim); font-size: 12px; }+ .tile .from img { width: 34px; height: 34px; object-fit: cover; border-radius: 5px; }+ .chips { display: flex; gap: 6px; flex-wrap: wrap; }+ .chips span { font-size: 12px; color: var(--dim); border: 1px solid var(--line); border-radius: 999px; padding: 2px 10px; }:focus-visible { outline: 2px solid var(--accent); outline-offset: 2px; }</style></head>@@ -53,17 +92,18 @@<p>Open-source Higgsfield on ComfyUI. Every app is one folder.</p><nav id="sections"></nav></header>-<main>+<main id="main"><div id="menu" aria-label="Apps"></div><section id="app" aria-live="polite"><p class="badge">Pick an app</p></section></main>+<section id="gallery" aria-label="Gallery" hidden></section><script>-let apps = [], section = "all", current = null;+let apps = [], section = "all", current = null, view = "apps";function el(tag, attrs = {}, ...kids) {const e = document.createElement(tag);for (const [k, v] of Object.entries(attrs)) {- if (k === "class") e.className = v; else if (k.startsWith("on")) e[k] = v; else if (v !== undefined && v !== null) e.setAttribute(k, v);+ if (k === "class") e.className = v; else if (k.startsWith("on")) e[k] = v; else if (v !== undefined && v !== null && v !== false) e.setAttribute(k, v);}for (const k of kids.flat()) e.append(k?.nodeType ? k : document.createTextNode(k ?? ""));return e;@@ -72,7 +112,18 @@ function el(tag, attrs = {}, ...kids) {function drawSections() {const names = ["all", ...new Set(apps.map(a => a.section))];const nav = document.getElementById("sections");- nav.replaceChildren(...names.map(n => el("button", { "aria-pressed": String(n === section), onclick: () => { section = n; drawSections(); drawMenu(); } }, n)));+ const shown = apps.filter(a => a.example).length;+ nav.replaceChildren(+ ...names.map(n => el("button", { "aria-pressed": String(view === "apps" && n === section), onclick: () => { section = n; show("apps"); } }, n)),+ el("button", { class: "gallery-tab", "aria-pressed": String(view === "gallery"), onclick: () => show("gallery") }, `gallery${shown ? ` · ${shown}` : ""}`));+}++function show(v) {+ view = v;+ document.getElementById("main").hidden = v !== "apps";+ document.getElementById("gallery").hidden = v !== "gallery";+ drawSections();+ if (v === "apps") drawMenu(); else drawGallery();}// what the VRAM verdict means on one 24 GB card (tools/catalog.py vram)@@ -94,11 +145,97 @@ function modelsPanel(a) {a.credits.length ? el("p", {}, el("small", {}, a.credits.join(" · "))) : "");}+// a still or a muted loop for a card; videos play while hovered (menu) or visible (gallery)+function preview(ex, cls) {+ if (!ex || !(ex.card || ex.poster)) return null;+ if (ex.type === "video" && ex.card) {+ const v = el("video", { class: cls, src: ex.card, poster: ex.poster, loop: "", playsinline: "", preload: "none" });+ v.muted = true;+ return v;+ }+ const src = ex.card || ex.poster;+ const extra = ex.type === "audio" ? " audio" : ex.type === "image" && /\.png$/i.test(src) ? " alpha" : "";+ return el("img", { class: `${cls}${extra}`, src, alt: "", loading: "lazy" });+}+const hoverPlay = (node, media) => {+ if (media?.tagName !== "VIDEO") return;+ node.onmouseenter = () => media.play().catch(() => {});+ node.onmouseleave = () => media.pause();+};+function drawMenu() {const list = apps.filter(a => section === "all" || a.section === section);- document.getElementById("menu").replaceChildren(...list.map(a =>- el("button", { class: "item", "aria-current": String(current?.id === a.id), onclick: () => open(a) },- el("span", { class: "badge" }, `${a.section} · ${a.status}`), el("strong", {}, a.name), el("small", {}, a.summary), fit(a))));+ document.getElementById("menu").replaceChildren(...list.map(a => {+ const media = preview(a.example, "thumb");+ const item = el("button", { class: `item${media ? "" : " nothumb"}`, "aria-current": String(current?.id === a.id), onclick: () => open(a) },+ media || "", el("span", { class: "txt" }, el("span", { class: "badge" }, `${a.section} · ${a.status}`), el("strong", {}, a.name), el("small", {}, a.summary), fit(a)));+ hoverPlay(item, media);+ return item;+ }));+}++function media(type, src, poster) {+ if (!src) return poster ? el("img", { src: poster, alt: "" }) : el("span", { class: "badge" }, "missing");+ if (type === "video") return el("video", { src, poster, controls: "", loop: "", playsinline: "", preload: "metadata" });+ if (type === "audio") return el("div", {}, poster ? el("img", { src: poster, alt: "" }) : "", el("audio", { src, controls: "", preload: "none" }));+ return el("img", { src, alt: "", class: /\.png$/i.test(src) ? "alpha" : null });+}++function exampleBlock(a, form) {+ const ex = a.example;+ if (!ex) return "";+ const labels = Object.fromEntries(a.inputs.map(i => [i.id, i]));+ const ins = (ex.inputs || []).map(i => el("figure", {},+ i.type === "image" || !i.full ? (i.src ? el("img", { src: i.src, alt: "", class: i.type === "image" && /\.png$/i.test(i.src) ? "alpha" : null }) : el("span", { class: "badge" }, String(i.from ?? "upload")))+ : media(i.type, i.full, i.src),+ el("figcaption", {}, i.label)));+ const stats = [ex.seconds != null ? `${Math.round(ex.seconds)} s` : "", ex.gpu ? `on ${ex.gpu.split(",")[0]}` : "",+ ex.peak_vram_gb != null ? `peak ${ex.peak_vram_gb} GB` : ""].filter(Boolean).join(" · ");+ const values = Object.entries(ex.values || {}).filter(([k]) => labels[k] && !["image", "video", "audio"].includes(labels[k].type));+ const use = el("button", { class: "ghost", type: "button", onclick: () => {+ for (const [k, v] of values) {+ const f = form.elements[k]; if (!f) continue;+ if (f.type === "checkbox") f.checked = v === true || v === "true"; else { f.value = String(v); f.dispatchEvent(new Event("input")); }+ }+ } }, "Use these settings");+ return el("section", { class: "example" },+ el("h3", {}, "Example", el("small", {}, [stats, ex.run ? `lab run ${ex.run}` : ""].filter(Boolean).join(" · "))),+ el("div", { class: `flow${ins.length ? "" : " solo"}` }, ins.length ? el("div", { class: "ins" }, ...ins) : "", ins.length ? el("span", { class: "arrow" }, "→") : "",+ el("figure", {}, media(ex.type, ex.full, ex.type === "audio" ? ex.card : ex.poster))),+ values.length ? el("dl", { class: "vals" }, ...values.flatMap(([k, v]) => {+ const opt = (labels[k].options || []).find(o => String(o.value) === String(v));+ return [el("dt", {}, labels[k].label), el("dd", {}, opt ? opt.label : String(v))];+ })) : "",+ values.length ? use : "");+}++function drawGallery() {+ const withEx = apps.filter(a => a.example);+ const without = apps.filter(a => !a.example && !a.id.startsWith("smoke"));+ const g = document.getElementById("gallery");+ if (!withEx.length) {+ g.replaceChildren(el("h2", {}, "Gallery"), el("p", { class: "lead" }, "No examples yet. Run one case per app on Modal, then come back:"),+ el("pre", {}, "modal run lab/lab_modal.py --showcase"));+ return;+ }+ const run = withEx.find(a => a.example.run)?.example;+ const tiles = withEx.map(a => {+ const m = preview(a.example, "") || el("span", { class: "badge" }, a.example.type);+ const tile = el("button", { class: "tile", onclick: () => { show("apps"); open(a); } },+ el("div", { class: "media" }, m),+ el("div", { class: "meta" }, el("span", { class: "badge" }, `${a.section} · ${a.higgsfield_feature || a.name}`), el("strong", {}, a.name),+ (a.example.inputs || []).some(i => i.src) ? el("span", { class: "from" }, "from",+ ...(a.example.inputs || []).filter(i => i.src).map(i => el("img", { src: i.src, alt: i.label, title: i.label }))) : ""));+ return tile;+ });+ g.replaceChildren(+ el("h2", {}, "Gallery"),+ el("p", { class: "lead" }, `${withEx.length} of ${withEx.length + without.length} apps, each from its showcase case${run?.run ? ` in lab run ${run.run}` : ""}${run?.gpu ? ` on ${run.gpu.split(",")[0]}` : ""}. Click one to open the app.`),+ el("div", { class: "tiles" }, ...tiles),+ without.length ? el("div", { class: "chips" }, el("span", {}, "no example yet:"), ...without.map(a => el("span", {}, a.name))) : "");+ // play the loops that are on screen, pause the rest+ const io = new IntersectionObserver(es => es.forEach(e => e.isIntersecting ? e.target.play().catch(() => {}) : e.target.pause()), { threshold: 0.4 });+ g.querySelectorAll(".tile video").forEach(v => io.observe(v));}function field(inp) {@@ -155,7 +292,8 @@ function open(a) {} catch (e) { status.className = "err"; status.textContent = e.message; }finally { run.disabled = !a.runnable; }};- document.getElementById("app").replaceChildren(el("p", { class: "badge" }, `${a.section} · ${a.pack} · ${a.status}`), el("h2", {}, a.name), el("p", {}, a.summary), a.notes ? el("p", { class: "note" }, a.notes) : "", fit(a), modelsPanel(a), form, status, outputs);+ document.getElementById("app").replaceChildren(el("p", { class: "badge" }, `${a.section} · ${a.pack} · ${a.status}`), el("h2", {}, a.name), el("p", {}, a.summary),+ a.notes ? el("p", { class: "note" }, a.notes) : "", fit(a), exampleBlock(a, form), modelsPanel(a), form, status, outputs);if (matchMedia("(max-width: 760px)").matches) document.getElementById("app").scrollIntoView({ behavior: "smooth" });}