Files
karaoke-gen/backend/services/auto_approval/models.py
T
Andrew Beveridge ☄️andClaude Fable 5 c2e31a5325 feat: 3-stem backing-vocals decider — confident WITH_BACKING verdict, shadow-first enforcement (v0.204.0) (#950)
## Summary

Phase 2B of fully-automated review (follows #949): the backing-vocals
decision gets a real decider. Today any track with audible ("pink")
backing content goes to human review; per the 20-job replay-review
corpus, pink → KEEP is right essentially always — the human
systematically *under*-keeps — except three detectable "pink but don't
keep" failure modes. This PR builds the 3-stem analysis that detects
them and lets the scorer emit a confident **WITH_BACKING** verdict.

- **New `karaoke_gen/instrumental_review/stem_comparison.py`** (pure
pydub): compares the backing / lead / full-vocals stems — per-stem
audible coverage + coverage ratio, envelope Pearson correlations, median
audible levels, lead-overlap fraction, within-run flatness. Runs in the
existing backing-vocals analysis step (screens_worker →
AudioAnalysisService) and is stored as
`backing_vocals_analysis.stem_comparison` on every new job. Best-effort:
any failure stores an error marker, never blocks the job.
- **Scorer v0.3.0**: the pink-present branch now decides — confident
WITH_BACKING (non-subjective, bias-to-keep per corpus) unless:
- **backing stem IS the lead** (catastrophic if kept): coverage ratio
≥0.80 + backing↔vocals correlation ≥0.80 + backing more audible than the
lead stem (the decisive discriminator — a plain dB-margin rule nearly
misfired on a genuine keep) → review;
- **noise-floor pink** (lo-fi mixes): median ≤ −35 dB across ≥15% of the
track, uncorrelated with the vocal line → review (marginal either way
per corpus);
- **lead bleed** (narrow): ≤3% audible with ≥0.95 lead overlap → review.
- **Executor**: a WITH_BACKING verdict auto-selects the with-backing
instrumental **only** behind `AUTO_APPROVAL_BACKING_KEEP_ENABLED`
(default **false** — shadow-first). While off, such jobs record blocker
`backing_keep_disabled` plus the full verdict/signals in
`processing_metadata.auto_approval`, accumulating prod shadow data
alongside human picks. Also requires the `instrumental_with_backing`
stem.

## Validation (real corpus stems, ~2.4 GB, private harness)

Downloaded all 20 corpus jobs' three stems from GCS and ran the decider
against the replay-review ground truth:

- **13/14 true keeps → confident WITH_BACKING**, including BOTH jobs the
human wrongly cleaned on quick review (44622ffa harmonized ahhs,
35ed9697 self-harmony hooks) — the decider beats the human here.
- 95d8e844 (marginal grungegaze, mostly noise pink) → review. All
clean-correct jobs → clean. **1d45b286 (backing stem is the lead —
worst-case if kept) → review.** Zero unsafe outcomes.
- Lyrics-side corpus validation (validate_scorer.py) unchanged and
green.

## Testing

- 21 new unit tests: synthetic-audio stem-comparison signal tests,
scorer decision branches modeled on the real corpus signal profiles,
executor flag/stem gating.
- Full backend suite: 4056 passed, 0 failed. Backend-only change (no
frontend, no user-facing strings).

## Rollout

Shadow-first: nothing changes for users at deploy. After reviewing prod
shadow verdicts vs human picks, set
`AUTO_APPROVAL_BACKING_KEEP_ENABLED=true` to let confident-keep jobs
(e.g. the Cher-class: lyrics solved, gated only by audible backing)
complete fully auto.

@coderabbitai ignore

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

Co-authored-by: Claude Fable 5 <noreply@anthropic.com>
2026-08-28 19:56:45 -04:00

137 lines
4.7 KiB
Python

"""Data models for the auto-approvability scorer.
These are plain dataclasses (JSON-serializable via ``asdict``) so the verdict can
be logged into ``processing_metadata`` and written into the offline recording
corpus without pulling in extra dependencies.
See ``docs/archive/2026-08-25-full-auto-review-design.md`` for the design.
"""
from __future__ import annotations
from dataclasses import asdict, dataclass, field
from enum import Enum
from typing import Any, Dict, List, Optional
class LyricsVerdict(str, Enum):
"""Whether the lyrics look safe to auto-approve without human review."""
AUTO = "auto" # confident the synced lyrics are already correct
REVIEW = "review" # needs a human
class BackingVerdict(str, Enum):
"""Backing-vocals decision confidence."""
CLEAN = "clean" # non-subjective: no backing vocals to retain -> clean
WITH_BACKING = "with_backing" # (reserved) confidently retain
REVIEW = "review" # subjective -> needs a human listen
@dataclass
class LyricsSignals:
"""The quantitative signals extracted from ``corrections.json``."""
total_words: int = 0
anchor_word_count: int = 0
gap_word_count: int = 0
anchor_word_fraction: float = 0.0
uncorrected_gap_fraction: float = 0.0
corrections_made: int = 0
anchor_sequences_count: int = 0
gap_sequences_count: int = 0
# Reference-lyrics agreement
accepted_reference_sources: List[str] = field(default_factory=list)
best_reference_relevance: float = 0.0
strong_reference_sources: int = 0
has_synced_reference: bool = False
# Guards
correction_actually_ran: bool = False
# AI auto-correct suggestions (auto-applied on review load — see corpus SYNTHESIS):
# gap words COVERED by a suggestion get fixed before a human would ever look,
# so post-AI confidence keys off the UNCOVERED remainder, not the raw gap count.
ai_suggestions_available: bool = False
ai_suggestion_count: int = 0
ai_full_consensus_count: int = 0
gap_words_covered_by_ai: int = 0
uncovered_gap_word_count: int = 0
uncovered_gap_fraction: float = 0.0
# Gating class: non-lexical vocalization sections (Pattern 3 — never fully auto)
vocalization_word_count: int = 0
vocalization_max_run: int = 0
long_vocalization_word_count: int = 0
has_vocalization_section: bool = False
# Gating class: phantom/hallucinated lines with absurd durations (Pattern 8)
max_word_duration_s: float = 0.0
absurd_duration_word_count: int = 0
suspicious_parenthetical_count: int = 0
has_phantom_signature: bool = False
@dataclass
class BackingSignals:
"""The quantitative signals extracted from ``backing_vocals_analysis``."""
analysis_present: bool = False
has_audible_content: bool = True
audible_percentage: float = 0.0
segment_count: int = 0
loud_segment_count: int = 0
peak_amplitude_db: Optional[float] = None
recommended_selection: Optional[str] = None
# 3-stem comparison (backing vs lead vs full vocals) — present on jobs
# analyzed since the Phase-2B backing decider; absent before that.
comparison_present: bool = False
coverage_ratio: float = 0.0
corr_backing_vocals: float = 0.0
corr_backing_lead: float = 0.0
lead_overlap_fraction: float = 0.0
lead_audible_fraction: float = 0.0
backing_audible_fraction: float = 0.0
backing_median_db: Optional[float] = None
lead_median_db: Optional[float] = None
backing_db_std: float = 0.0
flat_fraction: float = 0.0
@dataclass
class LyricsResult:
verdict: LyricsVerdict
tier: str # short label, e.g. "synced-perfect", "high-anchor", "needs-review"
signals: LyricsSignals
reasons: List[str] = field(default_factory=list)
@dataclass
class BackingResult:
verdict: BackingVerdict
non_subjective: bool # True only when the decision has no taste component
signals: BackingSignals
reasons: List[str] = field(default_factory=list)
@dataclass
class AutoApprovabilityVerdict:
"""Combined shadow verdict for a job.
``overall_auto`` is intentionally the *conjunction* of a confident lyrics
verdict and a non-subjective backing decision — the narrow, safe intersection
Andrew asked to start with. Anything less stays in human review.
"""
lyrics: LyricsResult
backing: BackingResult
overall_auto: bool
scorer_version: str
def to_dict(self) -> Dict[str, Any]:
# Convert Enum members to their plain string values so the dict is safe
# for both json.dumps and Firestore writes.
return asdict(
self,
dict_factory=lambda pairs: {
k: (v.value if isinstance(v, Enum) else v) for k, v in pairs
},
)