feat(bulk): album cover thumbnails + lossless BEST CHOICE at 10+ seeders (was 50) (#1211)

## Summary
- **Album cover thumbnails** in Bulk → By album. Album rows and the
tracklist header show the release group's front cover from the Cover Art
Archive (`coverartarchive.org/release-group/{mbid}/front-250`).
- Loaded lazily in the browser, never through our backend or the
MusicBrainz API.
- The disc icon stays as a placeholder, and remains when the album has
no cover (404).
- **Lossless torrents with 10+ seeders now count as BEST CHOICE** (tier
1 / auto-pick); the bar was 50.
- Prompted by a real batch (Chase & Status, *No More Idols*): all 12
jobs were parked for manual selection even though the right lossless
album torrent (31 / 15 seeders, filename matching) was the top result.
- Shared `BEST_CHOICE_MIN_SEEDERS` constant in backend
`pick_auto_selection` and frontend `categorizeResult`, plus a test
asserting the two match. The review-fixtures e2e spec uses the constant
too.
  - Availability labels (High ≥50 / Medium ≥10 / Low) are unchanged.
- **Also affects** unattended KaraokeHunt conversions, which call
`pick_auto_selection`. The title/filename check still guards them.
- Fake search `recommended` (tier 2) shape drops to 5 seeders; fixture
regenerated.

Follow-up (separate PRs): release-aware bulk album search/download. One
album-level flacfetch search instead of N per-track searches;
flacfetch's search executor is single-threaded, which is why 4/12
searches in that batch timed out at 95s.

## Testing
- Jest: all of `lib/__tests__` + bulk tests pass (355), including 3 new
cover-art tests and threshold boundary tests (9 vs 10).
- Backend: 6604 passed. The 8 failures are in
`test_emulator_integration.py`, which only runs when a local Firestore
emulator is up; it hit a stale emulator from another session. That
covers job creation, which this PR doesn't touch.
- Checked a real CAA cover (200 via archive.org redirect, ~2s cold) and
a missing cover (404).
- Code review: CodeRabbit CLI unavailable (invalid token / org
mismatch), so a local Superpowers review ran instead. Its fixes are in
the last commit.

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

https://claude.ai/code/session_019MixBuvzxB1c5AYc3mbDyW

---------

Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
Andrew Beveridge ☄️andClaude Opus 5.5 authored and GitHub committed 2026-10-22 12:41:59 -04:00
1 parent 5f72e618cc
commit 73fa5d7c01
12 files changed
+155 -27

No files matched your search

+6 -2
View File
@@ -63,6 +63,10 @@ AudioDownloadResult = AudioFetchResult
# parity tests in backend/tests/test_bulk_foundations.py guard the behaviour.
# ---------------------------------------------------------------------------
# Seeders a lossless torrent needs to count as "BEST CHOICE" (and so be auto-picked).
# A lossless torrent with even ~10 seeders is almost always the right source.
BEST_CHOICE_MIN_SEEDERS = 10
_BEST_RESULT_PRIORITY = [
"BEST CHOICE",
"STUDIO ALBUMS",
@@ -92,7 +96,7 @@ def _categorize_result(result: Dict[str, Any]) -> str:
# Vinyl rips checked before BEST CHOICE (surface noise -> poor for karaoke)
if is_lossless and media == "vinyl":
return "VINYL RIPS"
if is_lossless and seeders >= 50:
if is_lossless and seeders >= BEST_CHOICE_MIN_SEEDERS:
return "BEST CHOICE"
if is_lossless and is_24bit:
return "HI-RES 24-BIT"
@@ -175,7 +179,7 @@ def pick_auto_selection(results: List[Dict[str, Any]], search_title: str = "") -
"""Return the index to auto-select, or None if no confident lossless pick.
Tier-1 rule (mirrors getSearchConfidence): the best result must be in the
BEST CHOICE category (lossless, 50+ seeders, non-vinyl) AND its filename
BEST CHOICE category (lossless, BEST_CHOICE_MIN_SEEDERS+ seeders, non-vinyl) AND its filename
must match ``search_title`` (the song the user searched for). Otherwise we
defer to human selection.
"""
+2 -2
View File
@@ -9,7 +9,7 @@ every provider "works".
(``getSearchConfidence`` in frontend/lib/audio-search-utils.ts):
- ``perfect`` (tier 1): well-seeded lossless torrent of the right track ("BEST CHOICE").
- ``recommended`` (tier 2): the right track, lossless, but only 20 seeders.
- ``recommended`` (tier 2): the right track, lossless, but only 5 seeders.
- ``unsure`` (tier 3): every result names a different track; 3 seeders.
``frontend_fixture()`` writes these shapes to ``FRONTEND_FIXTURE``, which the
@@ -39,7 +39,7 @@ def _source_id(provider: str, artist: str, title: str) -> str:
def build_results(artist: str, title: str, duration: int, confidence: str = "perfect") -> List[AudioSearchResult]:
"""The three fake results for ``artist`` / ``title`` in ``confidence``'s shape."""
seeders = {"perfect": 120, "recommended": 20, "unsure": 3}[confidence]
seeders = {"perfect": 120, "recommended": 5, "unsure": 3}[confidence]
track = _MISMATCHED_TITLE if confidence == "unsure" else title
results = [
AudioSearchResult(
+19 -2
View File
@@ -72,9 +72,14 @@ class TestPickAutoSelection:
assert pick_auto_selection([_lossy(0), _lossy(1)], "Bohemian Rhapsody") is None
def test_lossless_but_low_seeders_returns_none(self):
# seeders < 50 -> STUDIO ALBUMS, not BEST CHOICE -> tier 2, no auto-pick
# seeders < 10 -> STUDIO ALBUMS, not BEST CHOICE -> tier 2, no auto-pick
from backend.services.audio_search_service import pick_auto_selection
assert pick_auto_selection([_lossless_best(0, seeders=10)], "Bohemian Rhapsody") is None
assert pick_auto_selection([_lossless_best(0, seeders=9)], "Bohemian Rhapsody") is None
def test_lossless_with_ten_seeders_is_auto_picked(self):
# A modestly-seeded lossless album torrent (e.g. 15-31 seeders) is still the right pick.
from backend.services.audio_search_service import pick_auto_selection
assert pick_auto_selection([_lossy(0), _lossless_best(1, seeders=10)], "Bohemian Rhapsody") == 1
def test_filename_mismatch_returns_none(self):
# best is lossless+well-seeded but the file is clearly a different track
@@ -106,3 +111,15 @@ class TestPickAutoSelection:
from backend.services.audio_search_service import pick_auto_selection
r = _lossless_best(0, seeders=80, title="Someone", target_file="04 - Someone.flac")
assert pick_auto_selection([r], "One") is None
def test_best_choice_min_seeders_matches_frontend():
"""The tier-1 seeder bar is duplicated in the frontend; keep the two in lockstep."""
import re
from pathlib import Path
from backend.services.audio_search_service import BEST_CHOICE_MIN_SEEDERS
ts = (Path(__file__).resolve().parents[2] / "frontend" / "lib" / "audio-search-utils.ts").read_text()
m = re.search(r"export const BEST_CHOICE_MIN_SEEDERS = (\d+)", ts)
assert m, "BEST_CHOICE_MIN_SEEDERS not found in frontend/lib/audio-search-utils.ts"
assert int(m.group(1)) == BEST_CHOICE_MIN_SEEDERS
+3 -1
View File
@@ -465,12 +465,14 @@ class TestFakeSearchConfidence:
FakeConfig(search_confidence="maybe").validate()
def test_fake_search_confidence_shapes(self):
from backend.services.audio_search_service import BEST_CHOICE_MIN_SEEDERS
perfect = self._search("perfect")
assert perfect[0]["seeders"] >= 50 and perfect[0]["target_file"] == "01 - Song.flac"
recommended = self._search("recommended")
# Lossless and the right track, but not well seeded enough for "BEST CHOICE".
assert recommended[0]["is_lossless"] is True and 10 <= recommended[0]["seeders"] < 50
assert recommended[0]["is_lossless"] is True and 0 < recommended[0]["seeders"] < BEST_CHOICE_MIN_SEEDERS
assert recommended[0]["target_file"] == "01 - Song.flac"
unsure = self._search("unsure")
+10 -1
View File
@@ -527,7 +527,16 @@ and `docs/archive/2026-07-20-edge-security-*.md`.
(`getSearchConfidence`) and `backend/services/audio_search_service.py`
(`pick_auto_selection`). The backend port drives the `bulk_search_worker`
auto-select decision. If you change the rule, change BOTH — the parity is guarded
by `backend/tests/test_bulk_foundations.py`.
by `backend/tests/test_bulk_foundations.py`. The seeder bar for BEST CHOICE is the
`BEST_CHOICE_MIN_SEEDERS` constant on both sides (10 since Oct 2026; it was 50, which
parked well-matched lossless album torrents with 15-31 seeders for manual choice). A
test asserts the two values match. The bar also applies to unattended KaraokeHunt
conversions (`karaokehunt_conversion.py` calls `pick_auto_selection`), where the
title/filename check is the guard against wrong picks.
- **Album cover thumbnails** in the By-album picker load straight from the Cover Art
Archive in the browser (`coverartarchive.org/release-group/{mbid}/front-250`), with the
disc icon as fallback when there's no cover. This isn't the live MusicBrainz API, and no
request goes through our backend.
- **The duration-delta charge is replicated** in `bulk_search_worker._auto_select`
using the same primitives/state keys (`credits_charged`/`select_charge_applied`)
as `audio_search.select_audio_source`, rather than refactoring the proven money
@@ -151,3 +151,43 @@ describe('BulkMode (album sub-mode)', () => {
expect(screen.getByRole('button', { name: 'Create 2 karaoke videos' })).toBeInTheDocument()
})
})
describe('BulkAlbumMode cover art', () => {
async function walkToAlbums() {
fireEvent.change(screen.getByPlaceholderText('Search for an artist…'), { target: { value: 'Britney' } })
fireEvent.click(screen.getByRole('button', { name: /^Search$/ }))
fireEvent.click(await screen.findByRole('button', { name: /Britney Spears/ }))
await screen.findByText('Choose an album')
}
const coverImg = (container: HTMLElement) =>
container.querySelector('img[src^="https://coverartarchive.org/"]') as HTMLImageElement | null
it('requests the release-group front cover for each album row, hidden until loaded', async () => {
const { container } = render(<Harness />)
await walkToAlbums()
const img = coverImg(container)!
expect(img.getAttribute('src')).toBe('https://coverartarchive.org/release-group/rg-1/front-250')
expect(img).toHaveAttribute('loading', 'lazy')
expect(img.className).toContain('invisible')
fireEvent.load(img)
expect(img.className).not.toContain('invisible')
})
it('falls back to the disc icon when the album has no cover art', async () => {
const { container } = render(<Harness />)
await walkToAlbums()
fireEvent.error(coverImg(container)!)
expect(coverImg(container)).toBeNull()
// The album row is still there and clickable.
expect(screen.getByRole('button', { name: /Oops!\.\.\.I Did It Again/ })).toBeEnabled()
})
it('shows the picked album cover on the tracklist step', async () => {
const { container } = render(<Harness />)
await walkToTracklist()
expect(coverImg(container)?.getAttribute('src')).toBe(
'https://coverartarchive.org/release-group/rg-1/front-250',
)
})
})
+52 -8
View File
@@ -127,9 +127,45 @@ function StepHeading({ icon: Icon, title, subtitle }: { icon: LucideIcon; title:
)
}
/** Cover Art Archive front-cover thumbnail for a release group (free, keyed by MBID). */
export function coverArtUrl(releaseGroupMbid: string, size: 250 | 500 = 250): string {
return `https://coverartarchive.org/release-group/${encodeURIComponent(releaseGroupMbid)}/front-${size}`
}
/**
* Album cover with the icon tile as placeholder: the image is only revealed once
* it loads, and albums with no cover in the archive (404) keep the icon.
*/
function AlbumArt({ mbid, icon: Icon, className }: { mbid?: string | null; icon: LucideIcon; className: string }) {
const [state, setState] = useState<"loading" | "loaded" | "failed">("loading")
return (
<span
className={`${className} relative rounded-md overflow-hidden flex items-center justify-center shrink-0`}
style={{ backgroundColor: "rgba(255,255,255,0.06)", color: "var(--text-muted)" }}
>
{state !== "loaded" && <Icon className="w-4 h-4" />}
{mbid && state !== "failed" && (
// eslint-disable-next-line @next/next/no-img-element
<img
src={coverArtUrl(mbid)}
alt=""
loading="lazy"
decoding="async"
referrerPolicy="no-referrer"
onLoad={() => setState("loaded")}
onError={() => setState("failed")}
className={`absolute inset-0 w-full h-full object-cover ${state === "loaded" ? "" : "invisible"}`}
/>
)}
</span>
)
}
/** A bordered, obviously-clickable result row (artist or album) with a trailing chevron. */
function PickRow({ icon: Icon, title, subtitle, meta, onClick, disabled }: {
function PickRow({ icon: Icon, artMbid, title, subtitle, meta, onClick, disabled }: {
icon: LucideIcon
/** Release-group MBID → show its cover art in place of the icon (album rows). */
artMbid?: string
title: string
subtitle?: string
meta?: ReactNode
@@ -144,12 +180,16 @@ function PickRow({ icon: Icon, title, subtitle, meta, onClick, disabled }: {
className="w-full text-start rounded-md border px-2.5 py-2 flex items-center gap-3 transition-colors hover:bg-white/5 hover:border-pink-400/50 disabled:opacity-50 disabled:pointer-events-none"
style={{ borderColor: "var(--card-border)" }}
>
<span
className="w-8 h-8 rounded-md flex items-center justify-center shrink-0"
style={{ backgroundColor: "rgba(255,255,255,0.06)", color: "var(--text-muted)" }}
>
<Icon className="w-4 h-4" />
</span>
{artMbid ? (
<AlbumArt mbid={artMbid} icon={Icon} className="w-10 h-10" />
) : (
<span
className="w-8 h-8 rounded-md flex items-center justify-center shrink-0"
style={{ backgroundColor: "rgba(255,255,255,0.06)", color: "var(--text-muted)" }}
>
<Icon className="w-4 h-4" />
</span>
)}
<span className="flex-1 min-w-0">
<span className="block text-sm truncate" style={{ color: "var(--text)" }}>{title}</span>
{subtitle && <span className="block text-xs truncate" style={{ color: "var(--text-muted)" }}>{subtitle}</span>}
@@ -307,7 +347,10 @@ export function BulkAlbumMode({ rows, onChange, disabled }: BulkAlbumModeProps)
return (
<div className="space-y-3">
{stepper}
<StepHeading icon={ListMusic} title={t("chooseTracks")} subtitle={`${artist.name} — ${tracklist.title}`} />
<div className="flex items-center gap-3">
{albumMbid && <AlbumArt key={albumMbid} mbid={albumMbid} icon={Disc3} className="w-12 h-12" />}
<StepHeading icon={ListMusic} title={t("chooseTracks")} subtitle={`${artist.name} — ${tracklist.title}`} />
</div>
<div className="flex items-center justify-between gap-2 flex-wrap">
<div className="flex items-center gap-2">
@@ -417,6 +460,7 @@ export function BulkAlbumMode({ rows, onChange, disabled }: BulkAlbumModeProps)
<PickRow
key={a.release_group_mbid}
icon={Disc3}
artMbid={a.release_group_mbid}
onClick={() => pickAlbum(a)}
disabled={disabled}
title={a.title}
@@ -22,6 +22,7 @@
import { test as base, expect, chromium, type Page, type BrowserContext } from '@playwright/test';
import * as fs from 'fs';
import * as path from 'path';
import { BEST_CHOICE_MIN_SEEDERS } from '../../lib/audio-search-utils';
// --- Persistent Chrome profile (bookmarks bar enabled) ---
@@ -100,14 +101,14 @@ function computeTier(fixture: Fixture): 1 | 2 | 3 {
for (const r of fixture.results) {
if (r.is_lossless && r.quality_data?.media?.toLowerCase() === 'vinyl') continue;
if (!best) { best = r; continue; }
const isBestChoice = r.is_lossless && (r.seeders ?? 0) >= 50 && r.quality_data?.media?.toLowerCase() !== 'vinyl';
const currentIsBest = best.is_lossless && (best.seeders ?? 0) >= 50 && best.quality_data?.media?.toLowerCase() !== 'vinyl';
const isBestChoice = r.is_lossless && (r.seeders ?? 0) >= BEST_CHOICE_MIN_SEEDERS && r.quality_data?.media?.toLowerCase() !== 'vinyl';
const currentIsBest = best.is_lossless && (best.seeders ?? 0) >= BEST_CHOICE_MIN_SEEDERS && best.quality_data?.media?.toLowerCase() !== 'vinyl';
if (isBestChoice && !currentIsBest) best = r;
else if (isBestChoice && currentIsBest && (r.seeders ?? 0) > (best.seeders ?? 0)) best = r;
}
if (!best) best = fixture.results[0];
const isBestChoice = best.is_lossless && (best.seeders ?? 0) >= 50 && best.quality_data?.media?.toLowerCase() !== 'vinyl';
const isBestChoice = best.is_lossless && (best.seeders ?? 0) >= BEST_CHOICE_MIN_SEEDERS && best.quality_data?.media?.toLowerCase() !== 'vinyl';
const hasLossless = fixture.results.some(
(r: any) => r.is_lossless && r.provider?.toLowerCase() !== 'youtube' && r.quality_data?.media?.toLowerCase() !== 'vinyl'
);
@@ -36,7 +36,12 @@ describe('categorizeResult', () => {
expect(categorizeResult(result)).toBe('YOUTUBE')
})
it('categorizes lossless with 50+ seeders as BEST CHOICE', () => {
it('categorizes lossless with 10 seeders as BEST CHOICE', () => {
expect(categorizeResult(makeResult({ is_lossless: true, seeders: 10, release_type: 'Album' }))).toBe('BEST CHOICE')
expect(categorizeResult(makeResult({ is_lossless: true, seeders: 9, release_type: 'Album' }))).toBe('STUDIO ALBUMS')
})
it('categorizes well-seeded lossless (100) as BEST CHOICE', () => {
const result = makeResult({ index: 0, is_lossless: true, seeders: 55 })
expect(categorizeResult(result)).toBe('BEST CHOICE')
})
@@ -164,7 +169,7 @@ describe('groupResults', () => {
it('groups results by category', () => {
const results = [
makeResult({ index: 0, is_lossless: true, seeders: 100 }), // BEST CHOICE
makeResult({ index: 1, is_lossless: true, seeders: 10, release_type: 'Album' }), // STUDIO ALBUMS
makeResult({ index: 1, is_lossless: true, seeders: 5, release_type: 'Album' }), // STUDIO ALBUMS
makeResult({ index: 2, is_lossless: true, seeders: 60 }), // BEST CHOICE
]
const groups = groupResults(results)
@@ -446,9 +451,9 @@ describe('getSearchConfidence', () => {
expect(confidence.warnings.some(w => w.includes('Spies'))).toBe(true)
})
it('returns tier 2 for studio album with moderate seeders', () => {
it('returns tier 2 for studio album with few seeders', () => {
const results = [
makeResult({ index: 0, is_lossless: true, seeders: 20, release_type: 'Album', target_file: '01 - Yellow.flac' }),
makeResult({ index: 0, is_lossless: true, seeders: 9, release_type: 'Album', target_file: '01 - Yellow.flac' }),
]
const confidence = getSearchConfidence(results, 'Yellow')
expect(confidence.tier).toBe(2)
@@ -68,7 +68,7 @@
"quality": "FLAC 16bit CD",
"source_id": "30871261464f73cc",
"index": 0,
"seeders": 20,
"seeders": 5,
"target_file": "01 - Fake Song.flac",
"year": 2001,
"label": "Fake Records",
+8 -2
View File
@@ -27,6 +27,12 @@ export interface CategoryConfig {
borderColor: string
}
/**
* Seeders a lossless torrent needs to count as BEST CHOICE (and tier 1 / auto-pick).
* Keep in sync with BEST_CHOICE_MIN_SEEDERS in backend/services/audio_search_service.py.
*/
export const BEST_CHOICE_MIN_SEEDERS = 10
export const CATEGORY_CONFIG: Record<string, CategoryConfig> = {
'BEST CHOICE': { name: 'BEST CHOICE', maxDisplay: 3, color: 'text-amber-400', borderColor: 'border-amber-500/30' },
'HI-RES 24-BIT': { name: 'HI-RES 24-BIT', maxDisplay: 3, color: 'text-purple-400', borderColor: 'border-purple-500/30' },
@@ -78,8 +84,8 @@ export function categorizeResult(result: ExtendedAudioSearchResult): string {
return 'VINYL RIPS'
}
// Best choice (50+ seeders, lossless, non-vinyl)
if (isLossless && seeders >= 50) {
// Best choice (lossless, non-vinyl, enough seeders to download reliably)
if (isLossless && seeders >= BEST_CHOICE_MIN_SEEDERS) {
return 'BEST CHOICE'
}
+1 -1
View File
@@ -1,6 +1,6 @@
[tool.poetry]
name = "karaoke-gen"
version = "0.280.3"
version = "0.281.0"
description = "Generate karaoke videos with synchronized lyrics. Handles the entire process from downloading audio and lyrics to creating the final video with title screens."
authors = ["Andrew Beveridge <andrew@beveridge.uk>"]
license = "MIT"