videogen/apps/api/app/domains/apps_shelf/preview_render.py
caelum0x d56639a594
Some checks failed
build-images / web (push) Has been cancelled
vision2026-ci / Python SDK resource tests (push) Has been cancelled
build-images / api (push) Has been cancelled
build-images / worker-gpu (push) Has been cancelled
vision2026-ci / Shared packages (TS≡Python golden parity) (comfy-workflow-schema) (push) Has been cancelled
vision2026-ci / Shared packages (TS≡Python golden parity) (effects-core) (push) Has been cancelled
vision2026-ci / Shared packages (TS≡Python golden parity) (eventbus-types) (push) Has been cancelled
vision2026-ci / Shared packages (TS≡Python golden parity) (growth-analytics) (push) Has been cancelled
vision2026-ci / Shared packages (TS≡Python golden parity) (provider-adapter-kit) (push) Has been cancelled
vision2026-ci / Shared packages (TS≡Python golden parity) (publishing-connectors) (push) Has been cancelled
vision2026-ci / Shared packages (TS≡Python golden parity) (render-core) (push) Has been cancelled
vision2026-ci / Shared packages (TS≡Python golden parity) (shot-template-schema) (push) Has been cancelled
vision2026-ci / Shared packages (TS≡Python golden parity) (trends-schema) (push) Has been cancelled
vision2026-ci / Desktop engine crates (test + clippy + fmt) (push) Has been cancelled
codeql / Analyze (javascript-typescript) (push) Has been cancelled
codeql / Analyze (python) (push) Has been cancelled
perf / API hot-path micro-smoke (budgeted) (push) Has been cancelled
perf / Desktop engine crates (release build check) (push) Has been cancelled
vision2026-ci / API phase modules (ruff + pytest) (push) Has been cancelled
vision2026-ci / Alembic upgrade + drift check (push) Has been cancelled
vision2026-ci / Shared packages (TS≡Python golden parity) (caption-engine) (push) Has been cancelled
Menivor — open source release (MIT), free to use and fork
Paid, hosted product at menivor.com, now retired as a company project.
Fresh squashed history of the cleaned working tree (secret-scanned,
no .env, no customer data, no outreach logs). Built on
MoneyPrinterTurbo (MIT, harry0703) — see NOTICE.
2026-12-04 02:10:26 +03:00

357 lines
18 KiB
Python

"""Render the apps-shelf preview loops for the local tools ($0, our own lanes)
and the ``image_edit`` apps (now real and cheap via Muse Image, $0.01-0.09).
Mirrors ``presets_hub/preview_render.py``'s pattern: real output from the
actual production runner (``runners.py``), never placeholder art. Covers:
* ``transition`` and ``beat_cut`` run the real app pipeline (the same
functions ``tasks.execute`` calls for a paying user) over one of our own
showcase clips/photos, so the preview is a genuine sample of the app's own
output.
* ``hook_score`` produces no video of its own (it returns a score, not
media) — its "preview" is a short muted loop of the real clip it analyzes,
the same honest convention the apps catalog already uses for ``plan``-kind
apps that reuse a real showcase loop instead of a fabricated one.
* ``remove_bg`` needs the optional ``rembg`` package (MIT; see the ``matting``
extra in ``pyproject.toml`` and ``requirements.txt``). Its preview is a real
before/after: the actual ``runners.remove_background`` cutout flattened onto
a plain backdrop, crossfaded from the original photo with the SAME
``runners.transition_command`` the ``transition`` app itself uses — no new
video-composition code, just the real cutout as one of its two inputs.
* ``expand``/``relight``/``product-in-scene``/``nine-angles`` (the four
``image_edit`` apps) call the exact production path
(``runners.edit_image_auto``), which now runs for real on Muse Image
($0.01/image, live 2026-10-28 — see ``routing/providers/muse_image.py``)
with fal Kontext ($0.04/image) only as a fallback. ``preview-jobs.json``'s
``$0.48`` total was priced at the old fal-only rate; the real Muse cost for
all four previews (1+9+1+1 = 12 images) is **$0.12**, paid for real out of
the owner's Meta Model API credit — no ``FAL_KEY``/promo-budget decision
needed anymore (``catalog.runner_ready`` accepts ``MODEL_API_KEY`` alone).
Output goes to a staging folder; uploading to the public media bucket and
recording it live (``apps_previews.py --record``, then
``APPS_PREVIEWS_LIVE=1``) is a deploy step, same as presets.
python -m app.domains.apps_shelf.preview_render [--now] [ids...]
"""
from __future__ import annotations
import argparse
import base64
import mimetypes
import os
from collections.abc import Iterable, Sequence
from pathlib import Path
from . import runners
REPO = Path(__file__).resolve().parents[5]
STAGING = Path(os.environ.get("SHOWCASE_OUT", REPO / "public-samples-staging")) / "presets" / "apps"
SOURCES = Path(os.environ.get("SHOWCASE_WORK", "/tmp/menivor-showcase")) / "sources"
MUSIC = REPO / "apps" / "api" / "assets" / "resource" / "songs" / "output000.mp3"
#: Our own showcase assets (already public on the media bucket, licence tracked
#: in ``tools/ops/showcase/sources.json``) reused as render inputs, same as
#: ``apps_previews.py``'s job plan.
CLIP = "showcase/barber-meme.mp4"
PRODUCT_POSTER = "showcase/serum-morning-poster.jpg"
SECOND_POSTER = "showcase/latte-cafe-poster.jpg"
#: ``transcribe``'s own showcase asset: unlike every other source above, this
#: one needs a REAL spoken audio track (the others are all silent b-roll),
#: so it's a separate clip, not CLIP reused — see ``render_transcribe``.
TRANSCRIBE_SOURCE = "showcase/transcript-narration.mp4"
#: Plain backdrop the real cutout is flattened onto for the before/after loop
#: (near-black, matches the dark cards the shelf tiles sit on).
CUTOUT_BACKDROP_RGB = (17, 19, 26)
#: Local tools this renderer covers (no FAL_KEY; ``remove_bg`` needs ``rembg``,
#: installed by default since the 2026-10-28 apps-shelf preview pass).
ZERO_DEP_TOOLS: tuple[str, ...] = ("transition", "beat_cut", "hook_score", "remove_bg")
#: The four ``image_edit`` apps, with the real ``text``/``choice`` preview
#: input each one's own JSON preset actually consumes (``edit_prompts``
#: ignores the unused ones; mirrors ``preview-jobs.json``'s real inputs).
IMAGE_EDIT_APPS: dict[str, str] = {
"expand": "",
"relight": "golden hour",
"product-in-scene": "a sunlit marble bathroom shelf",
"nine-angles": "",
}
#: The ``image_gen`` apps (text-to-image, no reference photo), with the real
#: preview prompt each one's own JSON preset actually consumes.
IMAGE_GEN_APPS: dict[str, str] = {
"thumbnail": "a cozy neighborhood coffee shop at golden hour, warm light through the window, "
"steam rising from a cup, shallow depth of field, cinematic",
}
#: The ``transcribe`` app (Muse Voice Transcribe, $0.18/hour of real audio —
#: a few seconds of showcase narration costs well under a cent). Separate
#: from ``ZERO_DEP_TOOLS`` for the same "costs real money, name it
#: explicitly" reason as ``IMAGE_EDIT_APPS``/``IMAGE_GEN_APPS``.
TRANSCRIBE_APPS: tuple[str, ...] = ("transcript",)
HOOK_SCORE_LOOP_SECONDS = 4.0
IMAGE_EDIT_FRAME_SECONDS = 0.6
def _poster(loop: str, dest: str, *, seek: float = 1.0) -> None:
runners.run(["ffmpeg", "-v", "error", "-y", "-ss", f"{seek:.2f}", "-i", loop, "-frames:v", "1", "-q:v", "5", dest])
def render_transition(first: str, second: str, out_dir: Path) -> dict:
out_dir.mkdir(parents=True, exist_ok=True)
out = out_dir / "transition.mp4"
poster = out_dir / "transition.jpg"
runners.run(runners.transition_command(first, second, str(out)))
_poster(str(out), str(poster))
return {"loop": "presets/apps/transition.mp4", "poster": "presets/apps/transition.jpg"}
def render_beat_cut(clip: str, music: str, out_dir: Path) -> dict:
out_dir.mkdir(parents=True, exist_ok=True)
clip_seconds = min(runners.probe_seconds(clip), runners.BEAT_CUT_MAX_S)
beats = runners.detect_beats(runners.decode_audio(music, seconds=runners.BEAT_CUT_MAX_S + 2))
segments = runners.plan_beat_cut(clip_seconds, beats)
out = out_dir / "beat-cut.mp4"
poster = out_dir / "beat-cut.jpg"
runners.run(runners.beat_cut_command(clip, music, segments, str(out)))
_poster(str(out), str(poster))
return {"loop": "presets/apps/beat-cut.mp4", "poster": "presets/apps/beat-cut.jpg"}
def render_hook_score(clip: str, out_dir: Path, *, seconds: float = HOOK_SCORE_LOOP_SECONDS) -> dict:
"""``hook_score`` has no media output; the honest preview is the real clip it scores."""
out_dir.mkdir(parents=True, exist_ok=True)
out = out_dir / "hook-score.mp4"
poster = out_dir / "hook-score.jpg"
runners.run(["ffmpeg", "-v", "error", "-y", "-i", clip, "-an", "-t", f"{seconds:.2f}", "-c:v", "libx264",
"-preset", "slow", "-crf", "23", "-profile:v", "high", "-pix_fmt", "yuv420p",
"-movflags", "+faststart", str(out)])
_poster(str(out), str(poster))
return {"loop": "presets/apps/hook-score.mp4", "poster": "presets/apps/hook-score.jpg"}
def flatten_cutout(cutout_path: str, dest_path: str, *, rgb: tuple[int, int, int] = CUTOUT_BACKDROP_RGB) -> None:
"""Composite a real RGBA cutout onto a plain backdrop (for a crossfade input)."""
from PIL import Image
with Image.open(cutout_path) as cutout:
cutout = cutout.convert("RGBA")
backdrop = Image.new("RGB", cutout.size, rgb)
backdrop.paste(cutout, mask=cutout.split()[-1])
backdrop.save(dest_path)
def render_remove_bg(image: str, out_dir: Path) -> dict:
"""Before/after: the real photo crossfading into its real ``rembg`` cutout."""
out_dir.mkdir(parents=True, exist_ok=True)
cutout_png = out_dir / "remove-background-cutout.png"
flattened = out_dir / "remove-background-flattened.jpg"
with open(image, "rb") as fh:
cutout_png.write_bytes(runners.remove_background(fh.read()))
flatten_cutout(str(cutout_png), str(flattened))
out = out_dir / "remove-background.mp4"
poster = out_dir / "remove-background.jpg"
runners.run(runners.transition_command(image, str(flattened), str(out)))
_poster(str(out), str(poster))
return {"loop": "presets/apps/remove-background.mp4", "poster": "presets/apps/remove-background.jpg"}
def render_transcribe(video: str, out_dir: Path, *, api_key: str = "") -> dict:
"""Before/after: a real frame from the clip, then the real Muse Voice
Transcribe transcript burned over it as a caption card.
Calls ``runners.transcribe_clip_auto`` — the exact function
``tasks.execute`` uses for a paying ``transcript`` run — against
``video`` (which, unlike our silent showcase b-roll, must carry real
speech; see ``apps_previews.py``'s ``transcribe`` job note). Reuses
``adstudio.cards.render_card``, the SAME Pillow caption-card renderer
production captions already draw with (no libass/libfreetype dependency
on FFmpeg's own ``drawtext``/``subtitles`` filters, no new text-drawing
code), composited onto the real frame with plain alpha-over — then the
SAME ``transition_command`` every other before/after preview uses.
"""
from PIL import Image
from app.domains.adstudio.cards import Card, render_card
from app.domains.film.story8_render import HEIGHT, WIDTH
out_dir.mkdir(parents=True, exist_ok=True)
result = runners.transcribe_clip_auto(video, api_key=api_key)
before = out_dir / "transcript-before.jpg"
_poster(video, str(before), seek=0.2)
overlay = out_dir / "transcript-overlay.png"
render_card(Card(text=result["transcript"], style="body"), WIDTH, HEIGHT, str(overlay))
after = out_dir / "transcript-after.jpg"
with Image.open(before) as base_im, Image.open(overlay) as overlay_im:
base = base_im.convert("RGBA").resize((WIDTH, HEIGHT))
composed = Image.alpha_composite(base, overlay_im.convert("RGBA"))
composed.convert("RGB").save(after, quality=92)
out = out_dir / "transcript.mp4"
poster = out_dir / "transcript.jpg"
runners.run(runners.transition_command(str(before), str(after), str(out)))
_poster(str(out), str(poster), seek=4.5)
return {"loop": "presets/apps/transcript.mp4", "poster": "presets/apps/transcript.jpg",
"transcript": result["transcript"]}
def _data_url(path: str) -> str:
"""A local file as a ``data:`` URL — the shape Muse Image's edits endpoint
accepts directly (verified live 2026-10-28), no upload/hosting required."""
mime = mimetypes.guess_type(path)[0] or "image/jpeg"
data = Path(path).read_bytes()
return f"data:{mime};base64,{base64.b64encode(data).decode('ascii')}"
def render_image_edit(app_id: str, image: str, out_dir: Path, *, text: str = "") -> dict:
"""Render one ``image_edit`` app's real preview via the production edit path.
Calls ``runners.edit_image_auto`` — the exact function ``tasks.execute``
uses for a paying run — once per prompt (``nine-angles`` makes 9 real
calls, one per angle; every other app makes 1). Muse Image runs first
($0.01/image, live); fal only if Muse is unconfigured or fails. A single
edited frame crossfades from the original photo (same
``runners.transition_command`` every other before/after preview uses); a
multi-frame app (``nine-angles``) concatenates its real frames into a
short slideshow instead — still 100% real output, no synthetic frames.
"""
from app.domains.apps_shelf import catalog
app = catalog.get(app_id)
if app is None or app.runner != "image_edit":
raise ValueError(f"{app_id!r} is not a catalog image_edit app")
out_dir.mkdir(parents=True, exist_ok=True)
prompts = runners.edit_prompts(app.edit, text)
url = _data_url(image)
frame_paths: list[str] = []
for i, prompt in enumerate(prompts):
data = runners.edit_image_auto(prompt, url)
frame = out_dir / f"{app_id}-frame-{i}.jpg"
from PIL import Image
import io as _io
with Image.open(_io.BytesIO(data)) as im:
im.convert("RGB").save(frame, quality=92)
frame_paths.append(str(frame))
out = out_dir / f"{app_id}.mp4"
poster = out_dir / f"{app_id}.jpg"
if len(frame_paths) == 1:
runners.run(runners.transition_command(image, frame_paths[0], str(out)))
# The crossfade lands at [2.0s, 3.0s) (TRANSITION_SECONDS=5, half=2.5,
# fade=1.0 — see transition_command); seek past it so the tile shows
# the real Muse-edited "after" frame, not the pre-crossfade original
# (a real bug caught in this pass: the default ts=1.0 seek produced
# byte-identical posters for expand/relight/product-in-scene, since
# all three share the same source photo and hadn't started fading yet).
_poster(str(out), str(poster), seek=4.5)
else:
_concat_slideshow(frame_paths, str(out), seconds_each=IMAGE_EDIT_FRAME_SECONDS)
_poster(str(out), str(poster))
return {"loop": f"presets/apps/{app_id}.mp4", "poster": f"presets/apps/{app_id}.jpg"}
def render_image_gen(app_id: str, out_dir: Path, *, text: str) -> dict:
"""Render one ``image_gen`` app's real preview via the production text-to-image path.
Calls ``runners.generate_image_auto`` — the exact function ``tasks.execute``
uses for a paying run — once, with no reference photo (there is nothing to
cross-fade from; the real generated image is the whole tile). The loop is
a slow zoom over that one real frame (``runners.image_zoom_command``).
"""
from app.domains.apps_shelf import catalog
app = catalog.get(app_id)
if app is None or app.runner != "image_gen":
raise ValueError(f"{app_id!r} is not a catalog image_gen app")
out_dir.mkdir(parents=True, exist_ok=True)
prompt = runners.edit_prompts(app.edit, text)[0]
data = runners.generate_image_auto(prompt)
frame = out_dir / f"{app_id}-frame.jpg"
from PIL import Image
import io as _io
with Image.open(_io.BytesIO(data)) as im:
im.convert("RGB").save(frame, quality=92)
out = out_dir / f"{app_id}.mp4"
poster = out_dir / f"{app_id}.jpg"
runners.run(runners.image_zoom_command(str(frame), str(out)))
_poster(str(out), str(poster), seek=1.0)
return {"loop": f"presets/apps/{app_id}.mp4", "poster": f"presets/apps/{app_id}.jpg"}
def _concat_slideshow(frames: Sequence[str], out: str, *, seconds_each: float) -> None:
"""A real ffmpeg slideshow over N real frames (``nine-angles``'s 9 real edits)."""
import tempfile
from app.domains.film.story8_render import FPS, GOP, HEIGHT, WIDTH, ffmpeg_bin
with tempfile.TemporaryDirectory(prefix="apps-slideshow-") as work:
list_path = os.path.join(work, "concat.txt")
with open(list_path, "w", encoding="utf-8") as fh:
for frame in frames:
fh.write(f"file '{frame}'\nduration {seconds_each}\n")
fh.write(f"file '{frames[-1]}'\n") # concat demuxer needs the last entry repeated
scale = f"scale={WIDTH}:{HEIGHT}:force_original_aspect_ratio=increase,crop={WIDTH}:{HEIGHT}"
runners.run([
ffmpeg_bin(), "-y", "-hide_banner", "-loglevel", "error", "-f", "concat", "-safe", "0",
"-i", list_path, "-vf", f"{scale},fps={FPS},setsar=1,format=yuv420p", "-c:v", "libx264",
"-preset", "veryfast", "-crf", "21", "-pix_fmt", "yuv420p", "-g", str(GOP), "-r", str(FPS),
"-movflags", "+faststart", out,
])
def render(app_id: str, *, sources: Path = SOURCES, out_dir: Path = STAGING) -> dict:
out_dir.mkdir(parents=True, exist_ok=True)
clip = str(sources / "barber-meme.mp4")
product_photo = str(sources / "serum-morning-poster.jpg")
if app_id == "transition":
return render_transition(product_photo, str(sources / "latte-cafe-poster.jpg"), out_dir)
if app_id == "beat_cut":
return render_beat_cut(clip, str(MUSIC), out_dir)
if app_id == "hook_score":
return render_hook_score(clip, out_dir)
if app_id == "remove_bg":
return render_remove_bg(product_photo, out_dir)
if app_id in IMAGE_EDIT_APPS:
return render_image_edit(app_id, product_photo, out_dir, text=IMAGE_EDIT_APPS[app_id])
if app_id in IMAGE_GEN_APPS:
return render_image_gen(app_id, out_dir, text=IMAGE_GEN_APPS[app_id])
if app_id in TRANSCRIBE_APPS:
return render_transcribe(str(sources / "transcript-narration.mp4"), out_dir)
raise ValueError(
f"no renderer for {app_id!r} (see ZERO_DEP_TOOLS / IMAGE_EDIT_APPS / IMAGE_GEN_APPS / TRANSCRIBE_APPS)")
def main(argv: Iterable[str] | None = None) -> int:
parser = argparse.ArgumentParser(description="Render apps-shelf preview loops")
parser.add_argument("ids", nargs="*",
help=f"ids to render (default: the {len(ZERO_DEP_TOOLS)} free local tools only — "
f"the {len(IMAGE_EDIT_APPS)} image_edit apps, {len(IMAGE_GEN_APPS)} image_gen app and "
f"{len(TRANSCRIBE_APPS)} transcribe app cost real money per Muse/fal call and must be "
f"named explicitly)")
args = parser.parse_args(list(argv) if argv is not None else None)
known = set(ZERO_DEP_TOOLS) | set(IMAGE_EDIT_APPS) | set(IMAGE_GEN_APPS) | set(TRANSCRIBE_APPS)
wanted: Sequence[str] = args.ids or list(ZERO_DEP_TOOLS)
for app_id in wanted:
if app_id not in known:
print(f"skip {app_id}: not a known renderer "
f"(see ZERO_DEP_TOOLS / IMAGE_EDIT_APPS / IMAGE_GEN_APPS / TRANSCRIBE_APPS)")
continue
entry = render(app_id)
print(f"{app_id}: {entry['loop']}")
return 0
if __name__ == "__main__":
raise SystemExit(main())
__all__ = ["CLIP", "CUTOUT_BACKDROP_RGB", "IMAGE_EDIT_APPS", "IMAGE_GEN_APPS", "MUSIC", "PRODUCT_POSTER",
"SECOND_POSTER", "STAGING", "TRANSCRIBE_APPS", "TRANSCRIBE_SOURCE", "ZERO_DEP_TOOLS", "flatten_cutout",
"render", "render_beat_cut", "render_hook_score", "render_image_edit", "render_image_gen",
"render_remove_bg", "render_transcribe", "render_transition"]