Files
karaoke-gen/backend/services/fake_workers/lyrics.py
T
Andrew Beveridge ☄️andClaude Opus 5.5 c277bc8ee3 feat: local E2E stack (fake workers + test API) + email-code sign-in (v0.275.0) (#1165)
## Summary
- **Local stack:** `scripts/local-stack.sh up --frontend` runs the
**real** backend on the Firestore + GCS emulators with `FAKE_WORKERS=1`.
In-process fake workers move jobs through their real states in seconds,
using tiny real media, so web Playwright and mobile Maestro full-journey
tests can run offline against the same endpoints.
- **Email-code sign-in** (nomad-mobile spec §4.1): `POST
/api/users/auth/send-code` + `verify-code`. The code logic is shared
with kjbox via `LoginCodeStore`, and sends are throttled per email and
per IP.
- **Bug fix found by the new suite:** `confirm-duration` moved jobs to
`separating_stage1`, from which they can never reach review. It now
resumes at `downloading`. No prod job had taken this path yet.

## Changes
- `backend/services/fake_workers/`: dispatch seam in
`WorkerService.trigger_*`, plus fake search, download, checkout and
outbox, scenarios, and per-user config. The real stem upload, transcode,
backing-vocals analysis and preview render are reused. Every check is
strict (`is True`), so a MagicMock settings object never enables the
fakes, and startup **refuses FAKE_WORKERS in production**.
- `/api/test/*` router (mounted only in that mode): `status`,
`scenario`, `fake-config`, `emails`, `reset`, plus the fake Stripe
checkout page. Paying it runs the real webhook handler.
- `frontend/e2e/local-stack/` (9 specs, ~50s):
  - sign-up → make → review → instrumental → download
  - buy and cancel credits
  - duration confirm, failed, complete and review states
  - code sign-in and lockout
- New required CI job `local-stack-e2e`.
- Docs: TESTING.md § Local stack, DEVELOPMENT.md, API.md, README,
LESSONS-LEARNED.
- `MAX_SIGNUPS_PER_IP` can now be set by env. Only the local stack
raises it; production keeps the default of 2.

## Testing
- [x] Backend unit: 6175 passed
- [x] Emulator: 152 passed
- [x] Frontend Jest: 1706 passed
- [x] Local-stack Playwright: 9/9 passed (CI mode)

## Review
- [x] CodeRabbit CLI review completed locally. 1 minor finding declined:
it suggested swallowing infrastructure errors in send-code as fake
"sent" responses, which would hide real outages from users.

@coderabbitai ignore

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

https://claude.ai/code/session_01AGuxtgoscF6RJGtpjHPg3W

---------

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

129 lines
4.0 KiB
Python

"""A fake but schema-valid ``corrections.json`` for the fake lyrics worker.
Built from the real ``CorrectionResult`` dataclasses, so if the schema the review
UI depends on changes, the fake changes with it (and its unit test catches
anything ``from_dict`` can no longer read).
"""
from __future__ import annotations
from typing import Any, Dict, List
from karaoke_gen.lyrics_transcriber.types import (
AnchorSequence,
CorrectionResult,
LyricsData,
LyricsMetadata,
LyricsSegment,
Word,
)
FAKE_LINES = (
"This is a fake song for testing",
"Every word arrives right on time",
"Sing along with the local stack",
"Nothing here was ever transcribed",
"Workers pretend and the jobs move on",
"Until the video is done",
)
REFERENCE_SOURCE = "lrclib"
LEAD_IN_SECONDS = 2.0
def _segments(prefix: str, duration: float) -> List[LyricsSegment]:
"""Spread FAKE_LINES evenly over the song, one word slot per word."""
usable = max(duration - LEAD_IN_SECONDS - 1.0, len(FAKE_LINES))
line_len = usable / len(FAKE_LINES)
segments = []
for i, line in enumerate(FAKE_LINES):
words_text = line.split()
start = LEAD_IN_SECONDS + i * line_len
slot = (line_len * 0.9) / len(words_text)
words = [
Word(
id=f"{prefix}w{i}_{j}",
text=text,
start_time=round(start + j * slot, 3),
end_time=round(start + (j + 1) * slot - 0.05, 3),
confidence=0.99,
)
for j, text in enumerate(words_text)
]
segments.append(
LyricsSegment(
id=f"{prefix}s{i}",
text=line,
words=words,
start_time=words[0].start_time,
end_time=words[-1].end_time,
)
)
return segments
def build_corrections(artist: str, title: str, duration: float) -> Dict[str, Any]:
"""Return a ``CorrectionResult.to_dict()`` whose transcription matches its reference."""
transcribed = _segments("t", duration)
reference = _segments("r", duration)
reference_lyrics = {
REFERENCE_SOURCE: LyricsData(
segments=reference,
metadata=LyricsMetadata(
source=REFERENCE_SOURCE,
track_name=title,
artist_names=artist,
duration_ms=int(duration * 1000),
is_synced=True,
lyrics_provider=REFERENCE_SOURCE,
lyrics_provider_id="fake",
),
source=REFERENCE_SOURCE,
)
}
t_ids = [w.id for s in transcribed for w in s.words]
r_ids = [w.id for s in reference for w in s.words]
anchors = [
AnchorSequence(
id="fake-anchor-0",
transcribed_word_ids=t_ids,
transcription_position=0,
reference_positions={REFERENCE_SOURCE: 0},
reference_word_ids={REFERENCE_SOURCE: r_ids},
confidence=1.0,
)
]
result = CorrectionResult(
original_segments=transcribed,
corrected_segments=transcribed,
corrections=[],
corrections_made=0,
confidence=1.0,
reference_lyrics=reference_lyrics,
anchor_sequences=anchors,
gap_sequences=[],
resized_segments=transcribed,
metadata={
"correction_type": "none",
"reason": "fake_workers",
"anchor_sequences_count": len(anchors),
"gap_sequences_count": 0,
"total_words": len(t_ids),
"correction_ratio": 0.0,
"available_handlers": [],
"enabled_handlers": [],
"agentic_routing": "disabled",
},
correction_steps=[],
word_id_map={},
segment_id_map={},
)
return result.to_dict()
def build_lrc(corrections: Dict[str, Any]) -> str:
lines = []
for seg in corrections["corrected_segments"]:
m, s = divmod(seg["start_time"], 60)
lines.append(f"[{int(m):02d}:{s:05.2f}]{seg['text']}")
return "\n".join(lines) + "\n"