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

598 lines
28 KiB
Python

"""What each app does (MH8). Local tools run on our CPU for $0; image edits call one hosted model.
* ``image_edit``: one call per prompt, real subject/composition preserved. Tries
Meta's Muse Image first (``$0.01``/image, live 2026-10-28 — see
:func:`edit_image_auto`) and falls back to the fal queue
(``fal-ai/flux-pro/kontext``, $0.04 an image at cost, source and date in each
app file) when Muse is unconfigured or a call fails. The price shown to users
(each app's ``price.json``) is unchanged either way — this only improves our
real margin on every image-edit app run.
* ``transition``: two photos into a 5 s vertical clip with a moving cross-fade (ffmpeg).
* ``remove_bg``: a transparent PNG cut-out with rembg (MIT) when installed. Default
model is ``u2netp`` (not the heavier BiRefNet family) — see the comment at
:func:`remove_background` for the real, measured reason.
* ``beat_cut``: the clip re-cut so every cut lands on a beat of a library track
(onset envelope, then ``loops.beat_cut.snap_cuts_to_beats``), with the track mixed in.
* ``hook_score``: first-3 s signals measured from the clip (motion, early cut,
audio onset, speech share), scored by ``loops.predict_hook``; text and face
signals are not measured and are reported as not measured.
* ``transcribe``: a clip's audio (first ``TRANSCRIBE_MAX_SECONDS``) sent to
Muse Voice Transcribe (Meta Model API, ``$0.18``/hour, real adapter at
:mod:`app.domains.routing.providers.muse_voice_transcribe`); returns the
real transcript plus per-turn timestamps and an ``.srt`` caption file.
"""
from __future__ import annotations
import io
import json
import os
import subprocess
from contextlib import contextmanager
from dataclasses import dataclass
from typing import Any, Callable, Sequence
from loguru import logger
from app.domains.film.story8_render import FPS, GOP, HEIGHT, WIDTH, RenderError, ffmpeg_bin, run
EDIT_ENDPOINT = "https://fal.run/fal-ai/flux-pro/kontext"
TRANSITION_SECONDS = 5.0
BEAT_CUT_MAX_S = 30.0
SAMPLE_RATE = 22050
HOP = 512
class AppRunError(RuntimeError):
pass
# --------------------------------------------------------------------------- #
# Hosted image edit
# --------------------------------------------------------------------------- #
def edit_image(prompt: str, image_url: str, *, session: Any = None, api_key: str = "") -> bytes:
"""Edit one image via fal's hosted Flux Kontext queue ($0.04/image)."""
import requests
key = api_key or os.getenv("FAL_KEY", "")
if not key:
raise AppRunError("this app is not switched on yet")
http = session or requests
response = http.post(EDIT_ENDPOINT, headers={"Authorization": f"Key {key}", "Content-Type": "application/json"},
json={"prompt": prompt, "image_url": image_url}, timeout=120)
if response.status_code >= 400:
raise AppRunError(f"the image model refused this photo ({response.status_code})")
images = (response.json() or {}).get("images") or []
url = str((images[0] or {}).get("url") or "") if images else ""
if not url.startswith("https://"):
raise AppRunError("the image model returned no image")
got = http.get(url, timeout=120)
if got.status_code >= 400:
raise AppRunError("the edited image could not be downloaded")
return got.content
def _bytes_from_result_url(url: str, *, session: Any = None) -> bytes:
"""Resolve a provider result that's an ``https`` URL or a ``data:`` URL into raw bytes."""
if url.startswith("data:"):
import base64
_, _, b64 = url.partition(",")
try:
return base64.b64decode(b64)
except (ValueError, TypeError) as exc:
raise AppRunError("the edited image could not be decoded") from exc
import requests
http = session or requests
got = http.get(url, timeout=120)
if got.status_code >= 400:
raise AppRunError("the edited image could not be downloaded")
return got.content
def edit_image_muse(prompt: str, image_url: str, *, session: Any = None, api_key: str = "") -> bytes:
"""Edit one image via Muse Image (Meta Model API, ``$0.01``/image).
Real adapter, verified live 2026-10-28 (owner's Meta Global AI Developer
Hackathon credit): see :mod:`app.domains.routing.providers.muse_image`.
Raises :class:`AppRunError` (never a raw provider exception) so callers can
uniformly fall back to :func:`edit_image`.
"""
from app.domains.routing.providers.kling_fal import KlingError
from app.domains.routing.providers.muse_image import muse_generate_image
try:
result_url = muse_generate_image(
"", prompt, api_key=api_key, image_urls=(image_url,), session=session,
)
except KlingError as exc:
raise AppRunError(f"muse image edit failed: {exc}") from exc
return _bytes_from_result_url(result_url, session=session)
def edit_image_auto(prompt: str, image_url: str, *, muse_session: Any = None, fal_session: Any = None,
fal_api_key: str = "", muse_api_key: str = "") -> bytes:
"""Prefer Muse Image (real, ``$0.01``/image) when configured; fall back to fal (``$0.04``/image).
Both adapters share one contract: one prompt, one reference image, PNG/
WebP bytes back. Muse Image runs first purely as a real cost optimization
(4x cheaper, verified live 2026-10-28, see :func:`edit_image_muse`) — when
it is not configured, or a call fails for any reason, fal's Flux Kontext
queue (proven in production before this integration) runs exactly as
before. This never changes what the user is quoted or charged (each app's
``price.json`` is unchanged) — it only improves our real margin.
"""
from app.domains.routing.providers.muse_image import muse_api_key as resolve_muse_key
key = muse_api_key or resolve_muse_key()
if key:
try:
return edit_image_muse(prompt, image_url, session=muse_session, api_key=key)
except AppRunError as exc:
logger.info(f"apps-shelf muse image edit failed, falling back to fal: {exc}")
return edit_image(prompt, image_url, session=fal_session, api_key=fal_api_key)
def generate_image_muse(prompt: str, *, session: Any = None, api_key: str = "", size: str = "1024x1024") -> bytes:
"""Generate one brand-new image from text via Muse Image (Meta Model API, ``$0.01``/image).
Text-to-image, not edit: no reference image goes in, unlike
:func:`edit_image_muse`. Real adapter, verified live 2026-10-28 (owner's
Meta Global AI Developer Hackathon credit) — see
:mod:`app.domains.routing.providers.muse_image`. Raises
:class:`AppRunError` (never a raw provider exception), matching every
other apps-shelf runner's contract.
"""
from app.domains.routing.providers.kling_fal import KlingError
from app.domains.routing.providers.muse_image import muse_generate_image
try:
result_url = muse_generate_image("", prompt, api_key=api_key, session=session, size=size)
except KlingError as exc:
raise AppRunError(f"image generation failed: {exc}") from exc
return _bytes_from_result_url(result_url, session=session)
def generate_image_auto(prompt: str, *, session: Any = None, api_key: str = "") -> bytes:
"""Generate one image from a text prompt.
Unlike :func:`edit_image_auto`, there is only one real provider wired for
apps-shelf text-to-image (Muse Image's ``/v1/images/generations``) — no
fal fallback exists here, so this fails closed with a friendly message
when no Meta Model API key is configured (mirrors
``catalog.runner_ready``'s ``image_gen`` check).
"""
from app.domains.routing.providers.muse_image import muse_api_key as resolve_muse_key
key = api_key or resolve_muse_key()
if not key:
raise AppRunError("this app is not switched on yet")
return generate_image_muse(prompt, session=session, api_key=key)
def edit_prompts(edit: dict[str, Any], text: str = "") -> list[str]:
templates = list(edit.get("prompts") or [])
angles = list(edit.get("angles") or [])
if angles:
return [templates[0].format(angle=angle) for angle in angles]
return [t.format(text=text.strip()) for t in templates]
# --------------------------------------------------------------------------- #
# Transition
# --------------------------------------------------------------------------- #
def transition_command(first: str, second: str, out: str, *, seconds: float = TRANSITION_SECONDS,
ffmpeg: str | None = None) -> list[str]:
half = seconds / 2
fade = 1.0
prep = (f"scale={WIDTH}:{HEIGHT}:force_original_aspect_ratio=increase,crop={WIDTH}:{HEIGHT},"
f"zoompan=z='1+0.06*on/{int(half * FPS + fade * FPS)}':d={int(half * FPS + fade * FPS)}:"
f"s={WIDTH}x{HEIGHT}:fps={FPS},setsar=1,format=yuv420p")
graph = (f"[0:v]{prep}[a];[1:v]{prep}[b];"
f"[a][b]xfade=transition=smoothleft:duration={fade}:offset={half - fade / 2:.2f},format=yuv420p[v]")
return [ffmpeg or ffmpeg_bin(), "-y", "-hide_banner", "-loglevel", "error", "-loop", "1", "-t",
f"{half + fade:.2f}", "-i", first, "-loop", "1", "-t", f"{half + fade:.2f}", "-i", second,
"-filter_complex", graph, "-map", "[v]", "-t", f"{seconds:.2f}", "-c:v", "libx264", "-preset", "veryfast",
"-crf", "21", "-pix_fmt", "yuv420p", "-g", str(GOP), "-r", str(FPS), "-movflags", "+faststart", out]
# --------------------------------------------------------------------------- #
# One still image, slow zoom (image_gen app previews)
# --------------------------------------------------------------------------- #
IMAGE_GEN_LOOP_SECONDS = 4.0
def image_zoom_command(image: str, out: str, *, seconds: float = IMAGE_GEN_LOOP_SECONDS,
ffmpeg: str | None = None) -> list[str]:
"""A slow zoom-in loop over one still image — the shelf-tile preview for an
``image_gen`` app (there is no "before" to cross-fade from; the real
generated image is the whole story)."""
frames = max(1, int(seconds * FPS))
vf = (f"scale={WIDTH}:{HEIGHT}:force_original_aspect_ratio=increase,crop={WIDTH}:{HEIGHT},"
f"zoompan=z='1+0.08*on/{frames}':d={frames}:s={WIDTH}x{HEIGHT}:fps={FPS},setsar=1,format=yuv420p")
return [ffmpeg or ffmpeg_bin(), "-y", "-hide_banner", "-loglevel", "error", "-loop", "1", "-t", f"{seconds:.2f}",
"-i", image, "-vf", vf, "-t", f"{seconds:.2f}", "-c:v", "libx264", "-preset", "veryfast", "-crf", "21",
"-pix_fmt", "yuv420p", "-g", str(GOP), "-r", str(FPS), "-movflags", "+faststart", out]
# --------------------------------------------------------------------------- #
# Remove background
# --------------------------------------------------------------------------- #
# Real users upload arbitrary-size photos (a phone shot is commonly 3000-4000px
# on a side, 10-20x the pixel count of the 540x960 showcase asset this was first
# measured against). rembg/onnxruntime's peak memory and latency scale with input
# pixels, with NO bound before this fix — an unusually large upload could blow
# past the worker container's real memory ceiling regardless of which model is
# selected below. Downscaling to this cap before matting keeps worst-case memory
# and latency flat no matter what a user uploads; 1600px on the long edge is
# already far more than a vertical-video cutout or a social post needs.
REMOVE_BG_MAX_DIM = 1600
def _bound_image_for_matting(image: bytes, *, max_dim: int = REMOVE_BG_MAX_DIM) -> bytes:
"""Downscale ``image`` so its longer edge is at most ``max_dim`` px.
Returns the original bytes unchanged when already within bounds (no
recompression cost for the common case). Re-encodes as PNG when resized,
since the result only ever feeds a local matting call, never the user.
"""
from PIL import Image, UnidentifiedImageError
try:
with Image.open(io.BytesIO(image)) as im:
width, height = im.size
if max(width, height) <= max_dim:
return image
scale = max_dim / max(width, height)
resized = im.convert("RGB").resize(
(max(1, round(width * scale)), max(1, round(height * scale))),
Image.LANCZOS,
)
buf = io.BytesIO()
resized.save(buf, format="PNG")
return buf.getvalue()
except UnidentifiedImageError as exc:
raise AppRunError("that file is not a readable image") from exc
@contextmanager
def _single_threaded_onnx():
"""Scope ``OMP_NUM_THREADS`` down to 1 for the duration of a real rembg call.
rembg's own ``new_session()`` reads ``OMP_NUM_THREADS`` from the environment
and sets BOTH onnxruntime's ``inter_op_num_threads`` AND
``intra_op_num_threads`` to it (confirmed by reading the installed rembg
2.0.69's source). This repo sets ``OMP_NUM_THREADS=4`` container-wide for
ffmpeg/BLAS — a value rembg has no business repurposing for its own thread
pool, and doing so multiplies onnxruntime's peak working-set close to
linearly with thread count. Measured for real on the production worker
(2026-10-28): the SAME bounded (<=1600px) u2netp call that stayed under
1GB RSS in an isolated test ran away to a real dmesg OOM-kill at
anon-rss 2.58GB inside the actual long-lived worker container with 4
threads active. Nothing else in this process reads ``OMP_NUM_THREADS``
mid-request, so scoping it here is safe and fully reverted afterward.
"""
previous = os.environ.get("OMP_NUM_THREADS")
os.environ["OMP_NUM_THREADS"] = "1"
try:
yield
finally:
if previous is None:
os.environ.pop("OMP_NUM_THREADS", None)
else:
os.environ["OMP_NUM_THREADS"] = previous
def remove_background(image: bytes, *, remover: Callable[[bytes], bytes] | None = None) -> bytes:
if remover is None:
# Bounding only applies to the real rembg path below — it exists to cap
# that specific CPU/memory-heavy call's worst case, not to second-guess
# an injected `remover` (tests, or any future non-rembg backend), which
# owns its own input handling.
bounded = _bound_image_for_matting(image)
try:
from rembg import new_session, remove
except ImportError as exc:
raise AppRunError("background removal is not installed on this server") from exc
# Default model is u2netp, NOT birefnet-general-lite. Measured for real on
# the production worker container (2026-10-28, mem_limit 2.5g/swap 3g on
# this box's profile): birefnet-general-lite's Swin-transformer inference
# blew well past 4.5GB RSS and was still not finished after 5+ minutes on
# this box's CPU, which would OOM-kill the SHARED worker container (every
# other user's in-flight render dies with it) long before it ever returned
# a result. u2netp is dramatically lighter. Override via APPS_REMBG_MODEL
# only after confirming the box has real headroom for it.
with _single_threaded_onnx():
session = new_session(os.getenv("APPS_REMBG_MODEL", "u2netp"))
out = remove(bounded, session=session)
else:
out = remover(image)
from PIL import Image
with Image.open(io.BytesIO(out)) as im:
if im.mode != "RGBA":
raise AppRunError("the cut-out has no transparency")
return out
# --------------------------------------------------------------------------- #
# Audio analysis shared by beat cut and hook score
# --------------------------------------------------------------------------- #
def decode_audio(path: str, *, seconds: float | None = None, ffmpeg: str | None = None):
import numpy as np
command = [ffmpeg or ffmpeg_bin(), "-hide_banner", "-loglevel", "error", "-i", path]
if seconds:
command += ["-t", f"{seconds:.2f}"]
command += ["-vn", "-ac", "1", "-ar", str(SAMPLE_RATE), "-f", "s16le", "-"]
done = subprocess.run(command, capture_output=True, timeout=120, check=False)
if done.returncode != 0:
raise RenderError("could not read the audio")
return np.frombuffer(done.stdout, dtype=np.int16).astype("float32") / 32768.0
def rms_envelope(samples) -> Any:
import numpy as np
if len(samples) < HOP:
return np.zeros(0, dtype="float32")
frames = len(samples) // HOP
blocks = samples[: frames * HOP].reshape(frames, HOP)
return np.sqrt((blocks ** 2).mean(axis=1))
def detect_beats(samples, *, min_gap_s: float = 0.28) -> list[float]:
"""Beat times from the positive onset envelope with peak picking (seconds)."""
import numpy as np
env = rms_envelope(samples)
if env.size < 3:
return []
onset = np.maximum(0.0, np.diff(env, prepend=env[0]))
if onset.max() <= 0:
return []
threshold = onset.mean() + 1.0 * onset.std()
hop_s = HOP / SAMPLE_RATE
min_gap = int(min_gap_s / hop_s)
beats, last = [], -min_gap
for i in range(1, len(onset) - 1):
if onset[i] >= threshold and onset[i] >= onset[i - 1] and onset[i] >= onset[i + 1] and i - last >= min_gap:
beats.append(round(i * hop_s, 3))
last = i
return beats
# --------------------------------------------------------------------------- #
# Beat-synced cut
# --------------------------------------------------------------------------- #
@dataclass(frozen=True)
class Segment:
source_start: float
duration: float
def plan_beat_cut(clip_seconds: float, beats: Sequence[float], *, every_s: float = 1.2,
jump_s: float = 0.4) -> list[Segment]:
"""Cut points every ~``every_s`` snapped to beats; each cut jumps the source forward a little."""
from app.services.loops.beat_cut import snap_cuts_to_beats
length = min(float(clip_seconds), BEAT_CUT_MAX_S)
if length <= 1.0 or not beats:
raise AppRunError("the clip or the track is too short to cut on the beat")
raw = [t for t in _frange(every_s, length, every_s)]
snapped = sorted({round(c.nudged_s, 3) for c in snap_cuts_to_beats(raw, list(beats), fps=FPS)
if 0.3 < c.nudged_s < length - 0.3})
points = [0.0, *snapped, length]
segments, offset = [], 0.0
for start, end in zip(points, points[1:]):
duration = end - start
if duration <= 0.05:
continue
source = start + offset
if source + duration > clip_seconds:
source = max(0.0, clip_seconds - duration)
segments.append(Segment(source_start=round(source, 3), duration=round(duration, 3)))
offset += jump_s
return segments
def _frange(start: float, stop: float, step: float):
value = start
while value < stop:
yield value
value += step
def beat_cut_command(clip: str, music: str, segments: Sequence[Segment], out: str, *,
ffmpeg: str | None = None) -> list[str]:
parts, labels = [], []
for i, seg in enumerate(segments):
parts.append(f"[0:v]trim=start={seg.source_start}:duration={seg.duration},setpts=PTS-STARTPTS,"
f"scale={WIDTH}:{HEIGHT}:force_original_aspect_ratio=increase,crop={WIDTH}:{HEIGHT},"
f"fps={FPS},setsar=1[s{i}]")
labels.append(f"[s{i}]")
total = sum(s.duration for s in segments)
graph = ";".join(parts) + f";{''.join(labels)}concat=n={len(segments)}:v=1:a=0[v];" \
f"[1:a]atrim=duration={total:.3f},loudnorm=I=-15:TP=-1.5:LRA=11,aresample=44100[a]"
return [ffmpeg or ffmpeg_bin(), "-y", "-hide_banner", "-loglevel", "error", "-i", clip, "-i", music,
"-filter_complex", graph, "-map", "[v]", "-map", "[a]", "-c:v", "libx264", "-preset", "veryfast",
"-crf", "21", "-pix_fmt", "yuv420p", "-g", str(GOP), "-r", str(FPS), "-c:a", "aac", "-b:a", "160k",
"-t", f"{total:.3f}", "-movflags", "+faststart", out]
# --------------------------------------------------------------------------- #
# Hook score signals
# --------------------------------------------------------------------------- #
def probe_seconds(path: str) -> float:
ffprobe = ffmpeg_bin().replace("ffmpeg", "ffprobe")
done = subprocess.run([ffprobe, "-v", "error", "-show_entries", "format=duration", "-of", "json", path],
capture_output=True, text=True, timeout=30, check=False)
try:
return float(json.loads(done.stdout or "{}")["format"]["duration"])
except (KeyError, ValueError, TypeError) as exc:
raise AppRunError("we could not read that clip") from exc
def frame_diffs(path: str, *, seconds: float = 3.0, fps: int = 10, ffmpeg: str | None = None) -> list[float]:
"""Mean absolute difference between consecutive 64x114 grey frames (0..1)."""
import numpy as np
w, h = 64, 114
done = subprocess.run([ffmpeg or ffmpeg_bin(), "-hide_banner", "-loglevel", "error", "-i", path, "-t",
f"{seconds:.2f}", "-vf", f"fps={fps},scale={w}:{h},format=gray", "-f", "rawvideo", "-"],
capture_output=True, timeout=120, check=False)
if done.returncode != 0:
raise RenderError("could not read the video")
frames = np.frombuffer(done.stdout, dtype=np.uint8)
count = len(frames) // (w * h)
if count < 2:
return []
stack = frames[: count * w * h].reshape(count, h, w).astype("float32") / 255.0
return [float(x) for x in np.abs(np.diff(stack, axis=0)).mean(axis=(1, 2))]
def hook_signals(path: str, *, hook_end_s: float = 3.0) -> dict[str, Any]:
import numpy as np
diffs = frame_diffs(path, seconds=hook_end_s)
motion = min(1.0, float(np.mean(diffs)) * 8) if diffs else 0.0
early_cut = 1.0 if any(d > 0.25 for d in diffs[:15]) else 0.0
try:
samples = decode_audio(path, seconds=hook_end_s)
except RenderError:
samples = np.zeros(0, dtype="float32")
env = rms_envelope(samples)
first = env[: int(0.5 * SAMPLE_RATE / HOP)]
audio_onset = min(1.0, float(first.max()) * 6) if first.size else 0.0
speech = float((env > 0.02).mean()) if env.size else 0.0
return {"motion": round(motion, 3), "early_cut": early_cut, "audio_onset": round(audio_onset, 3),
"speech": round(speech, 3), "text": 0.0, "face_or_subject": 0.0, "hook_end_s": hook_end_s,
"not_measured": ["text", "face_or_subject"]}
def score_hook(signals: dict[str, Any], opening_line: str = "") -> dict[str, Any]:
from app.services.loops import HookSignals, predict_hook, suggest_hooks
fields = {k: signals[k] for k in ("motion", "text", "audio_onset", "early_cut", "speech", "face_or_subject",
"hook_end_s")}
res = predict_hook(HookSignals(**fields))
suggestions = ([{"shape": s.shape, "text": s.text} for s in
suggest_hooks(opening_line, passes_gate=res.passes_gate, reasons=res.reasons)]
if opening_line and not res.passes_gate else [])
return {"score": res.score, "passes_gate": res.passes_gate, "grade": res.grade, "reasons": list(res.reasons),
"suggestions": suggestions, "signals": signals}
# --------------------------------------------------------------------------- #
# Transcribe (Muse Voice Transcribe)
# --------------------------------------------------------------------------- #
# Real users could upload a long clip; this caps worst-case cost and worker
# time the same way BEAT_CUT_MAX_S bounds beat-cut (Muse Voice Transcribe is
# $0.18/hour, so even the cap costs under a cent, but an unbounded upload
# would still tie up the shared worker's soft_time_limit for no real benefit —
# nobody needs more than the first few minutes transcribed to judge the app).
TRANSCRIBE_MAX_SECONDS = 180.0
TRANSCRIBE_SAMPLE_RATE = 16000
def has_audio_stream(path: str, *, ffprobe: str | None = None) -> bool:
"""Whether ``path`` has a real audio stream (our showcase b-roll does not)."""
exe = ffprobe or ffmpeg_bin().replace("ffmpeg", "ffprobe")
done = subprocess.run([exe, "-v", "error", "-select_streams", "a", "-show_entries", "stream=index",
"-of", "csv=p=0", path], capture_output=True, text=True, timeout=30, check=False)
return bool(done.stdout.strip())
def extract_wav_command(video: str, out: str, *, seconds: float = TRANSCRIBE_MAX_SECONDS,
sample_rate: int = TRANSCRIBE_SAMPLE_RATE, ffmpeg: str | None = None) -> list[str]:
"""Mono 16-bit PCM WAV, capped to ``seconds`` — the exact shape Muse Voice Transcribe's docs require."""
return [ffmpeg or ffmpeg_bin(), "-y", "-hide_banner", "-loglevel", "error", "-i", video, "-t", f"{seconds:.2f}",
"-vn", "-ac", "1", "-ar", str(sample_rate), "-sample_fmt", "s16", out]
def transcribe_audio_muse(wav_bytes: bytes, *, api_key: str = "", session: Any = None) -> dict[str, Any]:
"""Transcribe one WAV clip via Muse Voice Transcribe (real adapter, ``$0.18``/hour).
Raises :class:`AppRunError` (never a raw provider exception), matching
every other apps-shelf runner's contract.
"""
from app.domains.routing.providers.kling_fal import KlingError
from app.domains.routing.providers.muse_voice_transcribe import transcribe_wav
try:
return transcribe_wav(wav_bytes, api_key=api_key, session=session)
except KlingError as exc:
raise AppRunError(f"transcription failed: {exc}") from exc
def transcribe_clip_auto(video: str, *, work_dir: str | None = None, api_key: str = "",
session: Any = None) -> dict[str, Any]:
"""Transcribe a video file's audio track end to end: probe, extract, call Muse.
Fails with an honest :class:`AppRunError` when the clip has no audio
track at all (same convention already used for dub jobs on silent
videos, per ``plans/menivor.md`` 2026-10-12) rather than sending a
guaranteed-empty request to the provider.
"""
if not has_audio_stream(video):
raise AppRunError("we couldn't hear anyone speaking in that clip")
with _maybe_tempdir(work_dir) as work:
wav_path = os.path.join(work, "audio.wav")
run(extract_wav_command(video, wav_path))
with open(wav_path, "rb") as fh:
wav_bytes = fh.read()
result = transcribe_audio_muse(wav_bytes, api_key=api_key, session=session)
if not result["transcript"].strip():
raise AppRunError("we couldn't hear anyone speaking in that clip")
return result
@contextmanager
def _maybe_tempdir(work_dir: str | None):
import tempfile
if work_dir:
yield work_dir
else:
with tempfile.TemporaryDirectory(prefix="apps-transcribe-") as work:
yield work
def build_srt(turns: Sequence[dict[str, Any]], *, fallback_transcript: str = "",
fallback_duration_ms: int = 0) -> str:
"""A real ``.srt`` caption file from Muse Voice Transcribe's turns.
Falls back to one entry spanning the whole clip when the provider
returned no turns (``PUSH_TO_TALK`` mode, or a very short clip) but did
return a transcript, so the downloaded file is never empty when there is
real text to show.
"""
entries = list(turns) or ([{"startMs": 0, "endMs": fallback_duration_ms or 4000,
"transcript": fallback_transcript}] if fallback_transcript.strip() else [])
lines = []
for i, turn in enumerate(entries, start=1):
text = str(turn.get("transcript") or "").strip()
if not text:
continue
lines.append(str(i))
lines.append(f"{_srt_ts(int(turn.get('startMs') or 0))} --> {_srt_ts(int(turn.get('endMs') or 0))}")
lines.append(text)
lines.append("")
return "\n".join(lines)
def _srt_ts(ms: int) -> str:
ms = max(0, int(ms))
hours, rem = divmod(ms, 3_600_000)
minutes, rem = divmod(rem, 60_000)
seconds, millis = divmod(rem, 1000)
return f"{hours:02d}:{minutes:02d}:{seconds:02d},{millis:03d}"
__all__ = ["AppRunError", "Segment", "beat_cut_command", "build_srt", "detect_beats", "edit_image",
"edit_image_auto", "edit_image_muse", "edit_prompts", "extract_wav_command", "generate_image_auto",
"generate_image_muse", "has_audio_stream", "hook_signals", "image_zoom_command", "plan_beat_cut",
"probe_seconds", "remove_background", "score_hook", "transcribe_audio_muse", "transcribe_clip_auto",
"transition_command", "run"]