Some checks are pending
build-images / api (push) Waiting to run
build-images / worker-gpu (push) Waiting to run
build-images / web (push) Waiting to run
codeql / Analyze (javascript-typescript) (push) Waiting to run
codeql / Analyze (python) (push) Waiting to run
perf / API hot-path micro-smoke (budgeted) (push) Waiting to run
perf / Desktop engine crates (release build check) (push) Waiting to run
vision2026-ci / Shared packages (TS≡Python golden parity) (comfy-workflow-schema) (push) Waiting to run
vision2026-ci / Shared packages (TS≡Python golden parity) (effects-core) (push) Waiting to run
vision2026-ci / Shared packages (TS≡Python golden parity) (eventbus-types) (push) Waiting to run
vision2026-ci / Shared packages (TS≡Python golden parity) (growth-analytics) (push) Waiting to run
vision2026-ci / Shared packages (TS≡Python golden parity) (trends-schema) (push) Waiting to run
vision2026-ci / API phase modules (ruff + pytest) (push) Waiting to run
vision2026-ci / Shared packages (TS≡Python golden parity) (provider-adapter-kit) (push) Waiting to run
vision2026-ci / Shared packages (TS≡Python golden parity) (publishing-connectors) (push) Waiting to run
vision2026-ci / Shared packages (TS≡Python golden parity) (render-core) (push) Waiting to run
vision2026-ci / Shared packages (TS≡Python golden parity) (shot-template-schema) (push) Waiting to run
vision2026-ci / Python SDK resource tests (push) Waiting to run
vision2026-ci / Desktop engine crates (test + clippy + fmt) (push) Waiting to run
vision2026-ci / Alembic upgrade + drift check (push) Waiting to run
vision2026-ci / Shared packages (TS≡Python golden parity) (caption-engine) (push) Waiting to run
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.
474 lines
23 KiB
Python
474 lines
23 KiB
Python
# ruff: noqa: F811 - pytest fixtures imported from the shared very-time test module
|
|
"""Very ___ Time v2: brand presets (Oxhan), lengths and end card, garment and identity references,
|
|
chest-text check in the worker, voice take, payoff choice, sound and the -14 LUFS master.
|
|
|
|
Provider lanes are chosen from the keys in the environment; these tests set only
|
|
REPLICATE_API_TOKEN (the owner's real setup) unless a test says otherwise, and
|
|
every provider call is a fake.
|
|
"""
|
|
|
|
from __future__ import annotations
|
|
|
|
import json
|
|
import re
|
|
import shutil
|
|
import subprocess
|
|
from pathlib import Path
|
|
|
|
import pytest
|
|
|
|
from app.domains.film import chest_check, story8, story8_render, story8_tasks, very_time, very_time_worker
|
|
from app.models.db.models import Job
|
|
|
|
from .test_very_time_template import ( # noqa: F401 - the shared fixture and helpers
|
|
BODY, H, FakeStore, _client, _deps, _fund, _png, _real_face_character, _uid, maker)
|
|
|
|
HAS_FFMPEG = bool(shutil.which("ffmpeg") and shutil.which("ffprobe"))
|
|
OXHAN = {"preset": "oxhan"}
|
|
|
|
|
|
@pytest.fixture(autouse=True)
|
|
def _replicate_only(monkeypatch, request):
|
|
request.getfixturevalue("maker") # the shared fixture sets the fal lane; this file runs Replicate only
|
|
for name in ("FAL_KEY", "ARK_API_KEY", "ELEVENLABS_API_KEY", "MUSETALK_API_KEY", "MUSETALK_BASE_URL",
|
|
"VERY_TIME_VIDEO_MODEL", "VERY_TIME_REFERENCE_VIDEO_MODEL", "VERY_TIME_IMAGE_MODEL",
|
|
"VERY_TIME_REFERENCE_IMAGE_MODEL", "VERY_TIME_CHEST_REROLLS"):
|
|
monkeypatch.delenv(name, raising=False)
|
|
monkeypatch.setenv("REPLICATE_API_TOKEN", "r8-test")
|
|
from app.config import config
|
|
|
|
monkeypatch.setitem(config.elevenlabs, "api_key", "")
|
|
|
|
|
|
def _inputs(**over):
|
|
return very_time.clean_inputs(**{**BODY, **over})
|
|
|
|
|
|
def _start(maker, mode="frames", **over):
|
|
inputs = _inputs(**over)
|
|
price = very_time.quote(very_time.build_frames(inputs), inputs)[mode]
|
|
_fund(maker, standard=price["standard_credits"], ai_video=price["ai_video_credits"])
|
|
with maker() as s:
|
|
job = very_time.start(s, _uid(maker), inputs, mode=mode, quoted=price)
|
|
s.commit()
|
|
return job.id
|
|
|
|
|
|
class FakeOcr:
|
|
"""Reads the chest as wrong ``bad`` times, then right."""
|
|
|
|
def __init__(self, bad: int, text: str = "VERY TURKISH TIME"):
|
|
self.bad, self.text, self.calls = bad, text, 0
|
|
|
|
def __call__(self, image: bytes):
|
|
self.calls += 1
|
|
read = "VXRY TQRKZ TOMB" if self.calls <= self.bad else self.text
|
|
return [chest_check.OcrLine(text=read, box=(300, 500, 500, 540), score=0.9)]
|
|
|
|
|
|
def _sine(path: str, seconds: float = 2.5, freq: int = 220) -> None:
|
|
subprocess.run([story8_render.ffmpeg_bin(), "-y", "-loglevel", "error", "-f", "lavfi", "-i",
|
|
f"sine=frequency={freq}:duration={seconds}:sample_rate=44100", "-af", "volume=6",
|
|
"-c:a", "libmp3lame", path], check=True)
|
|
|
|
|
|
def _vt_deps(store, **over):
|
|
calls = {"ref": [], "text": [], "sfx": [], "lipsync": []}
|
|
|
|
def voice_take(*, params, user_id, work, fetch, max_seconds):
|
|
path = str(Path(work) / "take.mp3")
|
|
_sine(path)
|
|
return path, 2.5, "auto"
|
|
|
|
def make_sfx(backend, prompt, seconds, out_path, *, clip_url="", image_url=""):
|
|
calls["sfx"].append((backend, prompt, round(seconds, 2)))
|
|
_sine(out_path, seconds=min(seconds, 1.0), freq=880)
|
|
return out_path
|
|
|
|
base = dict(
|
|
presign=lambda key: f"https://bucket.example.com/{key}",
|
|
ref_image=lambda prompt, negative, seed, urls, model: calls["ref"].append((prompt, list(urls), model))
|
|
or _png((seed % 255, 30, 40)),
|
|
text_image=lambda prompt, negative, seed, model: calls["text"].append(model) or _png((seed % 255, 60, 60)),
|
|
ocr=FakeOcr(0), voice_take=voice_take, make_sfx=make_sfx,
|
|
lipsync_submit=lambda backend, **kw: calls["lipsync"].append((backend, kw)) or {"provider": backend,
|
|
"run_id": "run-1"},
|
|
lipsync_poll=lambda run: ("completed", "https://cdn.example.com/lipsync.mp4"),
|
|
speech_present=lambda path: False,
|
|
download=lambda url: Path(store.objects["_clip_path"].decode()).read_bytes(),
|
|
)
|
|
base.update(over)
|
|
return very_time_worker.VtDeps(**base), calls
|
|
|
|
|
|
# --------------------------------------------------------------------------- #
|
|
# Inputs: brand preset, length, end card, options
|
|
# --------------------------------------------------------------------------- #
|
|
def test_oxhan_preset_fills_the_brand_host_line_and_cta():
|
|
inputs = _inputs(brand=OXHAN)
|
|
assert inputs.brand_preset == "oxhan" and inputs.chest_text == "VERY TURKISH TIME"
|
|
assert inputs.line == "You met me at a very Turkish time in my life."
|
|
assert inputs.cta == "Get yours at oxhanatelier.com" and inputs.end_card
|
|
assert "late 20s" in inputs.host and "oxblood" in inputs.garment
|
|
frames = very_time.build_frames(inputs)
|
|
assert all("Oxhan" in f["prompt"] or "late 20s" in f["prompt"] for f in frames)
|
|
assert "dante" not in json.dumps(very_time.brand_preset("oxhan")).lower().replace("do_not_copy", "")
|
|
custom = _inputs(brand={**OXHAN, "cta": "Get yours at shop.example", "chest_text": "very good time"},
|
|
line="You met me at a very calm time in my life.")
|
|
assert custom.cta == "Get yours at shop.example" and custom.chest_text == "very good time"
|
|
assert custom.line.startswith("You met me at a very calm")
|
|
|
|
|
|
def test_brand_assets_ship_and_have_stable_keys():
|
|
for asset in ("sheet", "garment", "logo"):
|
|
assert very_time.brand_asset_path("oxhan", asset).is_file()
|
|
assert very_time.brand_asset_key("oxhan", asset).startswith("brands/oxhan/v1/")
|
|
assert very_time.brand_asset_path("", "logo") is None
|
|
|
|
|
|
@pytest.mark.parametrize("duration", [10, 15, 30])
|
|
@pytest.mark.parametrize("card", [True, False])
|
|
def test_beats_scale_to_the_exact_length(duration, card):
|
|
seconds, end_s = very_time.beat_lengths(duration, end_card=card)
|
|
assert len(seconds) == 5 and abs(sum(seconds) + end_s - duration) < 1e-6
|
|
assert (end_s > 0) == card and all(s > 1.0 for s in seconds)
|
|
assert seconds[-1] == max(seconds) # the deadpan payoff stays the longest beat
|
|
|
|
|
|
def test_inputs_are_validated():
|
|
with pytest.raises(story8.Story8Error, match="10, 15 or 30"):
|
|
_inputs(duration_s=20)
|
|
with pytest.raises(story8.Story8Error):
|
|
_inputs(brand={"preset": "480inc"})
|
|
with pytest.raises(story8.Story8Error, match="uploaded"):
|
|
_inputs(brand={"garment_ref": "https://evil.example.com/x.png"})
|
|
with pytest.raises(story8.Story8Error):
|
|
_inputs(payoff="dub")
|
|
with pytest.raises(story8.Story8Error):
|
|
_inputs(voice={"engine": "robot"})
|
|
assert very_time.guard({**BODY, "cta": "Get yours, Kümmeltürke"}) == ["kummelturke"]
|
|
assert very_time.guard({**BODY, "reply_line": "sieg heil"}) == ["sieg heil"]
|
|
|
|
|
|
def test_thirty_seconds_prices_shots_by_length():
|
|
inputs = _inputs(duration_s=30, brand=OXHAN, voice={"engine": "eleven_v3"}, sound={"sfx": True})
|
|
rows = very_time.build_frames(inputs)
|
|
price = very_time.quote(rows, inputs)
|
|
clip = story8.clip_credits()
|
|
assert price["seconds"] == 30 and price["extras"] == {"voice_credits": 1, "sfx_credits": 1}
|
|
assert price["animated"]["ai_video_credits"] == sum(clip * -(-int(r["seconds"] * 10) // 50) for r in rows)
|
|
assert price["animated"]["ai_video_credits"] > 5 * clip
|
|
base = very_time.quote(very_time.build_frames(_inputs()), _inputs())
|
|
assert base["animated"]["ai_video_credits"] == 5 * clip # 15 s: unchanged from v1
|
|
|
|
|
|
# --------------------------------------------------------------------------- #
|
|
# Routes
|
|
# --------------------------------------------------------------------------- #
|
|
def test_plan_shows_length_end_card_lanes_and_extras(maker):
|
|
body = {**BODY, "duration_s": 30, "brand": OXHAN, "voice": {"engine": "eleven_v3"}, "sound": {"sfx": False}}
|
|
res = _client().post("/api/v1/film/very-time/plan", json=body, headers=H)
|
|
assert res.status_code == 200, res.text
|
|
data = res.json()["data"]
|
|
assert data["duration_s"] == 30 and data["brand_preset"] == "oxhan"
|
|
assert data["end_card"]["cta"] == "Get yours at oxhanatelier.com" and data["end_card"]["logo"]
|
|
assert abs(sum(b["seconds"] for b in data["beats"]) + data["end_card"]["seconds"] - 30) < 1e-6
|
|
assert data["quote"]["extras"]["voice_credits"] == 1 and data["lanes"]["animated"]
|
|
assert data["lanes"]["premium_voice"] # Replicate voice lane with no ElevenLabs key
|
|
|
|
|
|
def test_plan_refuses_someone_elses_garment(maker):
|
|
body = {**BODY, "brand": {"garment_ref": "uploads/not-mine.png"}}
|
|
res = _client().post("/api/v1/film/very-time/plan", json=body, headers=H)
|
|
assert res.status_code == 403
|
|
|
|
|
|
def test_start_with_only_replicate_picks_replicate_lanes(maker):
|
|
job_id = _start(maker, mode="animated", brand=OXHAN)
|
|
with maker() as s:
|
|
params = s.get(Job, job_id).params
|
|
assert params["video_model"].endswith("-replicate") and params["reference_image_model"].endswith("-replicate")
|
|
assert params["voice_backend"] == "free" or params["voice_backend"] == "replicate"
|
|
assert params["duration_s"] == 15 and params["end_card"]["cta"].startswith("Get yours")
|
|
assert params["payoff"] == "native" and params["chest_rerolls"] == 2
|
|
|
|
|
|
def test_start_refuses_missing_lanes(maker, monkeypatch):
|
|
monkeypatch.delenv("REPLICATE_API_TOKEN")
|
|
inputs = _inputs()
|
|
price = very_time.quote(very_time.build_frames(inputs), inputs)["frames"]
|
|
_fund(maker, standard=price["standard_credits"])
|
|
with maker() as s, pytest.raises(story8.Story8Error) as err:
|
|
very_time.start(s, _uid(maker), inputs, mode="frames", quoted=price)
|
|
assert err.value.status_code == 503
|
|
monkeypatch.setenv("REPLICATE_API_TOKEN", "r8")
|
|
monkeypatch.setattr("app.domains.film.very_time_lanes.sfx_backend", lambda env=None: "")
|
|
inputs = _inputs(sound={"sfx": True})
|
|
price = very_time.quote(very_time.build_frames(inputs), inputs)["frames"]
|
|
with maker() as s, pytest.raises(story8.Story8Error) as err:
|
|
very_time.start(s, _uid(maker), inputs, mode="frames", quoted=price)
|
|
assert err.value.code == "sfx_unavailable"
|
|
|
|
|
|
def test_start_refuses_someone_elses_take(maker):
|
|
inputs = _inputs(voice={"take_key": "vt-takes/someone/" + "a" * 32 + "/take-1.mp3"})
|
|
price = very_time.quote(very_time.build_frames(inputs), inputs)["frames"]
|
|
_fund(maker, standard=price["standard_credits"])
|
|
with maker() as s, pytest.raises(story8.Story8Error) as err:
|
|
very_time.start(s, _uid(maker), inputs, mode="frames", quoted=price)
|
|
assert err.value.code == "take_not_yours"
|
|
|
|
|
|
# --------------------------------------------------------------------------- #
|
|
# Worker: references, chest check, shots
|
|
# --------------------------------------------------------------------------- #
|
|
def test_frames_use_brand_sheet_and_garment_and_reroll_the_chest(maker, monkeypatch):
|
|
store = FakeStore()
|
|
job_id = _start(maker, brand=OXHAN)
|
|
vt, calls = _vt_deps(store, ocr=FakeOcr(bad=1))
|
|
deps = _deps(store, very_time=vt)
|
|
with maker() as s:
|
|
job = s.get(Job, job_id)
|
|
frames = story8_tasks.make_frames(s, job, "/tmp", deps)
|
|
params = dict(job.params)
|
|
assert "brands/oxhan/v1/sheet-console.jpg" in store.objects and "brands/oxhan/v1/garment.png" in store.objects
|
|
assert params["_sheet_key"] == "brands/oxhan/v1/sheet-console.jpg"
|
|
prompt, urls, model = calls["ref"][0]
|
|
assert model.endswith("-replicate") and urls[0].endswith("sheet-console.jpg") and urls[1].endswith("garment.png")
|
|
assert prompt.startswith("Image 1 is the character turnaround sheet") and "Image 2 shows the garment" in prompt
|
|
checked = [f for f in frames if f.get("chest")]
|
|
assert [f["index"] for f in checked] == [1, 4]
|
|
assert checked[0]["chest_check"]["status"] == "rerolled" and checked[1]["chest_check"]["status"] == "ok"
|
|
assert len(calls["ref"]) == 5 + 1 # one re-roll, house-paid
|
|
|
|
|
|
def test_chest_check_caps_rerolls_then_overlays(maker, monkeypatch):
|
|
monkeypatch.setenv("VERY_TIME_CHEST_REROLLS", "1")
|
|
store = FakeStore()
|
|
job_id = _start(maker, brand=OXHAN)
|
|
vt, calls = _vt_deps(store, ocr=FakeOcr(bad=99))
|
|
with maker() as s:
|
|
frames = story8_tasks.make_frames(s, s.get(Job, job_id), "/tmp", _deps(store, very_time=vt))
|
|
checked = [f["chest_check"] for f in frames if f.get("chest")]
|
|
assert all(c["status"] == "overlay" and c["attempts"] == 2 for c in checked)
|
|
assert len(calls["ref"]) == 3 + 2 * 2 # three plain beats + two checked beats x (1 + 1 re-roll)
|
|
with maker() as s: # the user paid once; no extra debit was made for the re-rolls
|
|
from app.models.db.repositories import CreditRepository
|
|
|
|
assert CreditRepository(s).balance(_uid(maker)) == 0
|
|
|
|
|
|
def test_no_brand_generates_a_host_sheet_once(maker):
|
|
store = FakeStore()
|
|
job_id = _start(maker, brand={"garment_ref": ""})
|
|
vt, calls = _vt_deps(store)
|
|
with maker() as s:
|
|
job = s.get(Job, job_id)
|
|
story8_tasks.make_frames(s, job, "/tmp", _deps(store, very_time=vt))
|
|
assert job.params["_sheet_key"] == f"jobs/{job_id}/story8/sheet.png"
|
|
assert "turnaround" in calls["text"][0] or calls["text"] # the sheet came from the text lane (no garment)
|
|
assert len(calls["ref"]) == 5
|
|
|
|
|
|
def test_shots_carry_identity_garment_and_audio_flags(maker):
|
|
store = FakeStore()
|
|
job_id = _start(maker, mode="animated", brand=OXHAN, sound={"room_tone": True})
|
|
vt, _ = _vt_deps(store)
|
|
assert story8_tasks.run(job_id, _deps(store, very_time=vt))["stage"] == "animating"
|
|
with maker() as s:
|
|
story = s.get(Job, job_id)
|
|
shots = [s.get(Job, story.params["_shots"][str(i)]).params for i in range(5)]
|
|
for shot in shots:
|
|
roles = [r["role"] for r in shot["references"]]
|
|
assert roles == ["first_frame", "identity", "garment"]
|
|
assert shot["video_model"] == "bytedance/seedance-2.0-r2v-replicate"
|
|
assert shot["generate_audio"] is True
|
|
|
|
|
|
def test_failed_shots_refund_their_own_length_priced_credits(maker):
|
|
store = FakeStore()
|
|
job_id = _start(maker, mode="animated", duration_s=30, brand=OXHAN)
|
|
vt, _ = _vt_deps(store)
|
|
deps = _deps(store, very_time=vt, burn_captions=False, grade=False)
|
|
story8_tasks.run(job_id, deps)
|
|
with maker() as s:
|
|
story = s.get(Job, job_id)
|
|
expected = sum(int(f["ai_credits"]) for f in story.params["frames"])
|
|
for shot_id in story.params["_shots"].values():
|
|
s.get(Job, shot_id).state = story8.TASK_STATE_FAILED
|
|
s.commit()
|
|
if not HAS_FFMPEG:
|
|
pytest.skip("ffmpeg required for the fallback render")
|
|
story8_tasks.assemble(job_id, deps)
|
|
with maker() as s:
|
|
assert s.get(Job, job_id).params["_refunds"]["ai_video_credits"] == expected
|
|
|
|
|
|
# --------------------------------------------------------------------------- #
|
|
# Payoff
|
|
# --------------------------------------------------------------------------- #
|
|
class _Job:
|
|
def __init__(self, params, job_id="j1"):
|
|
self.id, self.user_id, self.params = job_id, "u1", params
|
|
|
|
|
|
class _Session:
|
|
def flush(self):
|
|
pass
|
|
|
|
|
|
def _payoff_job(mode="native", backend="replicate", reply=""):
|
|
frames = [{"index": i, "line": "line" if i == 4 else "", "key": f"k{i}", "clip_key": f"c{i}", "seconds": 3.0}
|
|
for i in range(5)]
|
|
return _Job({"preset": "very-time", "frames": frames, "payoff": mode, "lipsync_backend": backend,
|
|
"reply_line": reply, "line": "line", "voice": {}})
|
|
|
|
|
|
def _payoff_deps(store, tmp_path, vt):
|
|
clip = tmp_path / "lip.mp4"
|
|
clip.write_bytes(b"mp4")
|
|
store.objects["_clip_path"] = str(clip).encode()
|
|
return _deps(store, very_time=vt, now=lambda: 100.0)
|
|
|
|
|
|
def test_payoff_native_keeps_the_shots_own_speech(tmp_path):
|
|
store = FakeStore()
|
|
vt, calls = _vt_deps(store, speech_present=lambda path: True)
|
|
job = _payoff_job()
|
|
assert very_time_worker.payoff_stage(_Session(), job, str(tmp_path), _payoff_deps(store, tmp_path, vt),
|
|
{4: "clip.mp4"}) == "done"
|
|
assert job.params["_payoff_used"] == "native" and not calls["lipsync"]
|
|
|
|
|
|
def test_payoff_falls_back_to_lipsync_with_the_chosen_take(tmp_path):
|
|
store = FakeStore()
|
|
vt, calls = _vt_deps(store, speech_present=lambda path: False)
|
|
job, deps = _payoff_job(), _payoff_deps(store, tmp_path, vt)
|
|
clips = {4: "clip.mp4"}
|
|
assert very_time_worker.payoff_stage(_Session(), job, str(tmp_path), deps, clips) == "wait"
|
|
backend, kwargs = calls["lipsync"][0]
|
|
assert backend == "replicate" and kwargs["audio_url"].endswith(f"jobs/{job.id}/story8/vo.mp3")
|
|
assert job.params["_take_key"] == "auto" and f"jobs/{job.id}/story8/vo.mp3" in store.objects
|
|
assert very_time_worker.payoff_stage(_Session(), job, str(tmp_path), deps, clips) == "done"
|
|
assert job.params["_payoff_used"] == "lipsync" and clips[4].endswith("payoff-lipsync.mp4")
|
|
|
|
|
|
@pytest.mark.parametrize("mode,backend,reply,poll,used", [
|
|
("voiceover", "replicate", "", ("completed", "u"), "voiceover"),
|
|
("native", "", "", ("completed", "u"), "native"),
|
|
("lipsync", "replicate", "", ("failed", ""), "voiceover"),
|
|
("native", "replicate", "Yes it was.", ("failed", ""), "voiceover"),
|
|
])
|
|
def test_payoff_fallbacks(tmp_path, mode, backend, reply, poll, used):
|
|
store = FakeStore()
|
|
vt, _ = _vt_deps(store, speech_present=lambda path: True, lipsync_poll=lambda run: poll)
|
|
job, deps = _payoff_job(mode, backend, reply), _payoff_deps(store, tmp_path, vt)
|
|
state = very_time_worker.payoff_stage(_Session(), job, str(tmp_path), deps, {4: "clip.mp4"})
|
|
if state == "wait":
|
|
state = very_time_worker.payoff_stage(_Session(), job, str(tmp_path), deps, {4: "clip.mp4"})
|
|
assert state == "done" and job.params["_payoff_used"] == used
|
|
|
|
|
|
def test_lipsync_times_out_to_voiceover(tmp_path):
|
|
store = FakeStore()
|
|
vt, _ = _vt_deps(store, lipsync_poll=lambda run: ("running", ""))
|
|
job = _payoff_job("lipsync")
|
|
deps = _payoff_deps(store, tmp_path, vt)
|
|
assert very_time_worker.payoff_stage(_Session(), job, str(tmp_path), deps, {4: "c"}) == "wait"
|
|
late = _deps(store, very_time=vt, now=lambda: 100.0 + very_time_worker.LIPSYNC_TIMEOUT_S + 1)
|
|
assert very_time_worker.payoff_stage(_Session(), job, str(tmp_path), late, {4: "c"}) == "done"
|
|
assert job.params["_payoff_used"] == "voiceover"
|
|
|
|
|
|
# --------------------------------------------------------------------------- #
|
|
# End card and the final command
|
|
# --------------------------------------------------------------------------- #
|
|
def test_end_card_image_has_logo_and_cta():
|
|
from PIL import Image
|
|
import io
|
|
|
|
logo = very_time.brand_asset_path("oxhan", "logo").read_bytes()
|
|
image = Image.open(io.BytesIO(very_time_worker.end_card_image(
|
|
cta="Get yours at oxhanatelier.com", logo=logo, background="#4A0E17", text_colour="#EFE8DC")))
|
|
assert image.size == (720, 1280)
|
|
assert image.getpixel((5, 5)) == (74, 14, 23)
|
|
middle = image.crop((60, 400, 660, 800)).getcolors(1 << 20)
|
|
assert len(middle) > 10 # logo and text were drawn
|
|
|
|
|
|
def test_final_command_grades_only_the_beats_and_cuts_to_length():
|
|
cmd = very_time_worker.final_command("b.mp4", "e.mp4", "m.wav", "o.mp4", total_s=10.0, ass_path=None,
|
|
fonts_dir=None, grade=["lut3d=x.cube"], ffmpeg="ffmpeg")
|
|
graph = cmd[cmd.index("-filter_complex") + 1]
|
|
assert graph.startswith("[0:v]lut3d=x.cube") and "[1:v]setsar=1" in graph and "concat=n=2" in graph
|
|
assert cmd[cmd.index("-t") + 1] == "10.000" and "2:a" in cmd
|
|
|
|
|
|
# --------------------------------------------------------------------------- #
|
|
# Real render (ffmpeg): exact length, end card, -14 LUFS master
|
|
# --------------------------------------------------------------------------- #
|
|
def _probe(data: bytes) -> dict:
|
|
out = subprocess.run(["ffprobe", "-v", "error", "-show_entries", "format=duration:stream=codec_type,width,height",
|
|
"-of", "json", "-"], input=data, capture_output=True, check=True)
|
|
return json.loads(out.stdout)
|
|
|
|
|
|
def _lufs(data: bytes, tmp_path: Path) -> float:
|
|
path = tmp_path / "out.mp4"
|
|
path.write_bytes(data)
|
|
out = subprocess.run([story8_render.ffmpeg_bin(), "-hide_banner", "-i", str(path), "-af", "ebur128",
|
|
"-f", "null", "-"], capture_output=True, text=True)
|
|
return float(re.findall(r"I:\s+(-?\d+(?:\.\d+)?) LUFS", out.stderr)[-1])
|
|
|
|
|
|
@pytest.mark.integration
|
|
@pytest.mark.skipif(not HAS_FFMPEG, reason="ffmpeg required")
|
|
@pytest.mark.parametrize("duration", [10, 30])
|
|
def test_oxhan_frames_render_exact_length_with_end_card(maker, tmp_path, duration):
|
|
store = FakeStore()
|
|
job_id = _start(maker, brand=OXHAN, duration_s=duration, sound={"sfx": True})
|
|
vt, calls = _vt_deps(store)
|
|
result = story8_tasks.run(job_id, _deps(store, very_time=vt, burn_captions=False, grade=False))
|
|
assert result["stage"] == "finished", result
|
|
data = store.objects[f"jobs/{job_id}/story8/final.mp4"]
|
|
info = _probe(data)
|
|
assert abs(float(info["format"]["duration"]) - duration) < 0.1
|
|
assert {st["codec_type"] for st in info["streams"]} == {"video", "audio"}
|
|
assert abs(_lufs(data, tmp_path) - (-14.0)) < 1.5
|
|
assert len(calls["sfx"]) == 4 and all(b == "replicate" for b, _, _ in calls["sfx"]) or \
|
|
all(b in ("replicate", "elevenlabs") for b, _, _ in calls["sfx"])
|
|
with maker() as s:
|
|
view = story8.job_view(s.get(Job, job_id))
|
|
assert view["duration_s"] == duration and view["payoff_used"] is None
|
|
assert [c["index"] for c in view["chest"]] == [1, 4]
|
|
|
|
|
|
@pytest.mark.integration
|
|
@pytest.mark.skipif(not HAS_FFMPEG, reason="ffmpeg required")
|
|
def test_animated_render_uses_native_speech_and_room_tone(maker, tmp_path):
|
|
store = FakeStore()
|
|
job_id = _start(maker, mode="animated", brand=OXHAN, sound={"room_tone": True})
|
|
vt, _ = _vt_deps(store, speech_present=lambda path: True)
|
|
deps = _deps(store, very_time=vt, burn_captions=False, grade=False)
|
|
story8_tasks.run(job_id, deps)
|
|
clip = tmp_path / "shot.mp4"
|
|
subprocess.run([story8_render.ffmpeg_bin(), "-y", "-loglevel", "error", "-f", "lavfi", "-i",
|
|
"testsrc=size=720x1280:rate=30:duration=6", "-f", "lavfi", "-i",
|
|
"sine=frequency=300:duration=6", "-shortest", "-c:v", "libx264", "-pix_fmt", "yuv420p",
|
|
"-c:a", "aac", str(clip)], check=True)
|
|
with maker() as s:
|
|
story = s.get(Job, job_id)
|
|
for index, shot_id in story.params["_shots"].items():
|
|
shot = s.get(Job, shot_id)
|
|
shot.state, shot.result_key = story8.TASK_STATE_COMPLETE, f"jobs/{shot_id}/broll/x.mp4"
|
|
store.objects[shot.result_key] = clip.read_bytes()
|
|
s.commit()
|
|
result = story8_tasks.assemble(job_id, deps)
|
|
assert result["stage"] == "finished", result
|
|
with maker() as s:
|
|
params = s.get(Job, job_id).params
|
|
assert params["_payoff_used"] == "native" and "_vo_key" not in params # the shot spoke; no voice-over made
|
|
data = store.objects[f"jobs/{job_id}/story8/final.mp4"]
|
|
assert abs(float(_probe(data)["format"]["duration"]) - 15.0) < 0.1
|
|
assert abs(_lufs(data, tmp_path) - (-14.0)) < 1.5
|