Files
karaoke-gen/backend/tests/test_theme_preview_service.py
T
Andrew Beveridge ☄️andClaude Opus 5.5 60687d6cd6 feat(theme): editable + previewed end screen; optional title/end screens (v0.268.0) (#1134)
## Summary
Randy Vild (tenant `randy-vild`) emailed: *"I have completed 3 songs but
all three songs produce the large text at the end even though I have in
my settings smaller text like in my beginning."*

Root cause: the theme editor's size/position sliders only edit
`intro.*`. The end screen has its own `end.*` layout (title 350 /
closing message 400 / yellow capitals artist in Randy's theme). The
editor neither exposed it nor previewed it ("The end screen isn't
previewed").

## Changes
- **End screen tab**: own title/artist colours, size + position sliders
(closing message, song title, artist), show/hide song title / artist
name, capitals toggles, and **Copy title card layout**. That copies the
title card's regions/colours/capitals and moves the closing message just
above the title, or below the artist if there's no room, so they never
overlap.
- **End screen preview**: `theme_preview_service.render_end_screen` uses
the same `VideoGenerator.create_end_video` as `screens_worker`. The
preview column shows the screen for the active tab plus the lyrics
frame; Advanced shows all three.
- **Leave out the title card / end screen**: optional `intro.enabled` /
`end.enabled` (absent = included; not added to the DEFAULT_*
required-field lists). The setting is honoured end to end:
- The screens worker skips the omitted screen and records
`state_data.screens_included`.
- The video worker's prerequisite check and the `/retry` ladder
(`_has_title_screen`, which also requires `screens_progress: complete`)
treat an omitted screen as done.
- The orchestrator sets the omitted screen's path to `None` and gives
the original-vocals guide an intro offset of 0.
- Encoding passes explicit `include_title_screen` /
`include_end_screen=false` to the GCE worker. Without them, its loose
`*title*.png` / `*end*.png` globs would rebuild the screen from
`style/*_background.png`.
- `LocalEncodingService.encode_lossless_mp4` builds the concat from
whichever segments exist (1–3).
  - The portrait renderer drops omitted cards.
- 11 new strings × 33 locales (`endScreenHint` removed). Docs: API.md,
README.md.

## Verification
- `make test` all green: frontend 1665 tests; backend unit, integration
and emulator suites.
- New `backend/tests/test_theme_screen_omission.py`, 28 tests:
  - screens worker for all 4 include combinations;
  - prerequisites and the retry helper;
  - orchestrator config and encoder options;
  - GCE `run_encoding` with decoy theme PNGs present;
  - concat for n = 1/2/3.
- Real-ffmpeg renders:
- end-screen preview (its own background; text size changes only the end
screen);
  - portrait durations with screens omitted.
- Frontend: editor tests for the end tab, copy layout, region toggles
and enable switches, plus unit tests for the `copyTitleCardLayoutToEnd`
util.
- Rendered Randy's real theme locally:
  - as saved, the end screen reproduces the large text;
  - after Copy title card layout, it matches his title card.
- Local CodeRabbit review: 0 findings.

## Deploy notes
- The worker paths changed (`gce_encoding/`,
`local_encoding_service.py`, `karaoke_gen/`), so CI blue-green redeploys
the encoding worker.
- Existing themes are unaffected: they have no `enabled` key.

@coderabbitai ignore

🤖 Generated with [Claude Code](https://claude.com/claude-code)

Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-08 15:09:25 -04:00

198 lines
7.1 KiB
Python

"""
Real renders of the tenant theme preview (title card + karaoke frame).
Uses the production renderers end-to-end with a colour-background theme and a
bundled font; storage is faked in-memory. Skipped without ffmpeg (CI installs it).
"""
import io
import shutil
import pytest
from PIL import Image
from backend.services import theme_preview_service as tps
pytestmark = pytest.mark.skipif(shutil.which("ffmpeg") is None, reason="ffmpeg not installed")
def _theme(sung="255, 0, 0, 255", bg="#102030"):
return {
"intro": {
"background_color": bg,
"background_image": None,
"font": "AvenirNext-Bold.ttf",
"title_color": "#ffffff",
"artist_color": "#ffdf6b",
"title_region": "370,980,3100,350",
"artist_region": "370,1400,3100,450",
},
"karaoke": {
"background_color": bg,
"background_image": None,
"font_path": "AvenirNext-Bold.ttf",
"font": "Avenir Next Bold",
"ass_name": "Nomad",
"primary_color": sung,
"secondary_color": "255, 255, 255, 255",
"outline_color": "0, 0, 0, 255",
"back_color": "0, 0, 0, 0",
"bold": False, "italic": False, "scale_x": 100, "scale_y": 100, "spacing": 0,
"border_style": 1, "outline": 1, "shadow": 0, "margin_l": 0, "margin_r": 0, "margin_v": 0,
},
"end": {},
"cdg": {},
}
class _NoGcsAssets:
"""Storage whose theme has no uploaded assets (font resolves to bundled)."""
class _Bucket:
def get_blob(self, path):
return None
bucket = _Bucket()
def _img(data: bytes) -> Image.Image:
return Image.open(io.BytesIO(data)).convert("RGB")
def test_renders_title_card_and_karaoke_frame():
tps._CACHE.clear()
result = tps.render_theme_preview("t1", _theme(), artist="Randy Vild", title="What Goes Up", storage=_NoGcsAssets())
title, karaoke = _img(result.title_card), _img(result.karaoke_frame)
assert title.size == (1280, 720)
assert karaoke.size == (1280, 720)
# The theme's solid #102030 background is what's in the corners of both frames
for frame in (title, karaoke):
r, g, b = frame.getpixel((8, 8))
assert abs(r - 0x10) <= 6 and abs(g - 0x20) <= 6 and abs(b - 0x30) <= 6
urls = result.as_data_urls()
assert urls["title_card"].startswith("data:image/jpeg;base64,")
def test_sung_colour_is_what_changes_in_the_karaoke_frame():
"""The frame shows a part-sung line, so changing only the sung colour must
change the karaoke frame (and not the title card)."""
tps._CACHE.clear()
red = tps.render_theme_preview("t1", _theme(sung="255, 0, 0, 255"), storage=_NoGcsAssets())
green = tps.render_theme_preview("t1", _theme(sung="0, 255, 0, 255"), storage=_NoGcsAssets())
assert red.title_card == green.title_card
assert red.karaoke_frame != green.karaoke_frame
reds = sum(1 for r, g, b in _img(red.karaoke_frame).getdata() if r > 200 and g < 60 and b < 60)
greens = sum(1 for r, g, b in _img(green.karaoke_frame).getdata() if g > 200 and r < 60 and b < 60)
assert reds > 200 and greens > 200
def test_identical_drafts_are_cached():
tps._CACHE.clear()
a = tps.render_theme_preview("t1", _theme(), storage=_NoGcsAssets())
b = tps.render_theme_preview("t1", _theme(), storage=_NoGcsAssets())
assert a is b
def test_missing_background_asset_is_a_preview_error():
theme = _theme()
theme["karaoke"]["background_image"] = "missing.jpg"
with pytest.raises(tps.ThemePreviewError, match="missing.jpg"):
tps.resolve_assets(theme, "t1", storage=_NoGcsAssets())
def test_font_family_name_from_bundled_font():
import os
name = tps.font_family_name(os.path.join(tps.BUNDLED_FONTS_DIR, "AvenirNext-Bold.ttf"))
assert name.startswith("Avenir Next")
def test_evict_keeps_cache_under_limit(tmp_path):
import os
import time
for i in range(5):
p = tmp_path / f"f{i}"
p.write_bytes(b"x" * 100)
os.utime(p, (time.time() - 100 + i, time.time()))
tps._evict(str(tmp_path), 250, keep=str(tmp_path / "f0"))
remaining = sorted(p.name for p in tmp_path.iterdir())
assert sum((tmp_path / n).stat().st_size for n in remaining) <= 250
assert "f0" in remaining # the file just written is never evicted
def test_failed_download_leaves_no_partial_cache_file(tmp_path, monkeypatch):
monkeypatch.setattr(tps, "ASSET_CACHE_ROOT", str(tmp_path))
class Blob:
generation = 7
def download_to_filename(self, path):
open(path, "wb").write(b"partial")
raise IOError("network died")
class Storage:
class bucket:
@staticmethod
def get_blob(path):
return Blob()
with pytest.raises(IOError):
tps._local_theme_asset(Storage, "t1", "bg.jpg")
assert not any(f.is_file() for f in tmp_path.rglob("*"))
def _with_end(theme, **end):
theme["end"] = {
"background_color": "#301020",
"background_image": None,
"font": "AvenirNext-Bold.ttf",
"title_color": "#ffffff",
"artist_color": "#ffdf6b",
"title_region": "370,900,3100,350",
"artist_region": "370,1450,3100,200",
"extra_text": "THANK YOU FOR SINGING!",
"extra_text_color": "#ff7acc",
"extra_text_region": "370,400,3100,400",
**end,
}
return theme
def test_renders_the_end_screen_with_its_own_background_and_layout():
tps._CACHE.clear()
result = tps.render_theme_preview("t1", _with_end(_theme()), artist="Randy Vild", storage=_NoGcsAssets())
end = _img(result.end_screen)
assert end.size == (1280, 720)
r, g, b = end.getpixel((8, 8)) # the end section's own #301020, not the title card's
assert abs(r - 0x30) <= 6 and abs(g - 0x10) <= 6 and abs(b - 0x20) <= 6
assert result.as_data_urls()["end_screen"].startswith("data:image/jpeg;base64,")
def test_end_screen_text_size_changes_only_the_end_screen():
"""Randy Vild's report: the end screen's text size is its own setting."""
tps._CACHE.clear()
big = tps.render_theme_preview("t1", _with_end(_theme()), storage=_NoGcsAssets())
small = tps.render_theme_preview(
"t1", _with_end(_theme(), title_region="370,900,3100,120", extra_text_region="370,400,3100,120"),
storage=_NoGcsAssets(),
)
assert big.title_card == small.title_card
assert big.end_screen != small.end_screen
def text_pixels(data):
return sum(1 for r, g, b in _img(data).getdata() if r > 200 and g > 200 and b > 200)
assert text_pixels(small.end_screen) < text_pixels(big.end_screen) * 0.6
def test_omitted_screens_are_not_rendered():
tps._CACHE.clear()
theme = _with_end(_theme())
theme["intro"]["enabled"] = False
theme["end"]["enabled"] = False
result = tps.render_theme_preview("t1", theme, storage=_NoGcsAssets())
assert result.title_card is None and result.end_screen is None
assert _img(result.karaoke_frame).size == (1280, 720)
urls = result.as_data_urls()
assert urls["title_card"] is None and urls["end_screen"] is None