From 89546223395edf84f5985d77b7c97eb2252982ab Mon Sep 17 00:00:00 2001 From: Robert O'Brien Date: Tue, 5 May 2026 09:17:50 -0700 Subject: [PATCH 1/2] fingerprint: parallelize ACR via ProcessPoolExecutor; viewer: progressive results, reanalyze buttons, redirect on ingest MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Speed up fingerprinting by ~10-20x by switching from sequential ACR calls to 20 worker processes — threads serialise on the GIL held by the acrcloud native C extension, so ProcessPoolExecutor is the only path to true parallelism. Each worker creates its own ACRCloudRecognizer from a config dict. Progressive UX: - Fingerprint windows now stream results into tracks.json as they complete (writes a "partial": true marker), and viewer polling reloads the fingerprint step while it's still "running" rather than waiting for done. - Library page redirects to the set page as soon as ingest finishes (set_id is known) so users see analysis populate live instead of staring at a log. Reanalyze controls: - New POST /api/sets/{set_id}/analyze endpoint accepts {steps: [...]} and reruns just those steps via orchestrator.reanalyze_steps() — leaves other step statuses untouched. - ↺ reanalyze buttons on BPM, Key, Waveform, and Tracklist panels; click POSTs the request, subscribes to the SSE job stream, and reloads the step's data the moment it's done. Misc: drop uvicorn log level to "warning" to silence per-request audio range chatter. --- src/setplot/cli.py | 2 +- src/setplot/pipeline/fingerprint.py | 273 ++++++++++++++++----------- src/setplot/pipeline/orchestrator.py | 102 +++++++++- src/setplot/server/routers/ingest.py | 25 +++ src/setplot/viewer/set.html | 12 ++ src/setplot/viewer/static/viewer.js | 64 +++++++ 6 files changed, 362 insertions(+), 116 deletions(-) diff --git a/src/setplot/cli.py b/src/setplot/cli.py index d2167b3..20589fe 100644 --- a/src/setplot/cli.py +++ b/src/setplot/cli.py @@ -229,7 +229,7 @@ def _open_browser_after_bind() -> None: if not no_browser: threading.Thread(target=_open_browser_after_bind, daemon=True).start() typer.echo(f"SetPlot serving on {url} (Ctrl-C to stop)") - uvicorn.run(create_app(), host=host, port=port, log_level="info") + uvicorn.run(create_app(), host=host, port=port, log_level="warning") if __name__ == "__main__": diff --git a/src/setplot/pipeline/fingerprint.py b/src/setplot/pipeline/fingerprint.py index ae5d81a..a6c4456 100644 --- a/src/setplot/pipeline/fingerprint.py +++ b/src/setplot/pipeline/fingerprint.py @@ -12,11 +12,13 @@ import subprocess import sys import time +from collections.abc import Callable +from concurrent.futures import ProcessPoolExecutor, as_completed from dataclasses import dataclass, field from pathlib import Path import requests -from acrcloud.recognizer import ACRCloudRecognizer + # ---------- ACRCloud request/response reference --------------------------------------------------- # Request params we control: @@ -47,6 +49,37 @@ _FATAL_ACR_STATUS_CODES = frozenset({3001, 3002, 3003, 3014}) +def _recognize_window_worker( + config: dict, + file_path: str, + t: int, + rec_length: int, + idx: int, + total_windows: int, +) -> tuple[int, str | None]: + """Run in a worker process — bypasses the GIL held by the ACR C extension. + + Returns (idx, raw_json_str) or (idx, None) after all retries exhausted. + """ + from acrcloud.recognizer import ACRCloudRecognizer + + rec = ACRCloudRecognizer(config) + backoff = 2.0 + for _attempt in range(5): + try: + raw = rec.recognize_by_file(file_path, t, rec_length) + return idx, raw if isinstance(raw, str) else json.dumps(raw) + except Exception as e: + print( + f" [{idx}/{total_windows}] t={t}s error: {e} (retry in {backoff:.1f}s)", + file=sys.stderr, + ) + time.sleep(backoff) + backoff *= 2 + print(f" [{idx}/{total_windows}] t={t}s: giving up on window", file=sys.stderr) + return idx, None + + class FingerprintAuthError(RuntimeError): """Raised when ACR returns a non-recoverable auth/quota status code. @@ -302,7 +335,7 @@ def audd_recognize(token: str, file_path: Path, t_seconds: float, length_seconds def scan_file( - recognizer: ACRCloudRecognizer, + recognizer_config: dict, file_path: Path, duration_s: float, stride_s: float, @@ -311,6 +344,7 @@ def scan_file( end_s: float, audd_token: str | None = None, host_for_logs: str = "?", + window_cb: Callable[[float, list[Hit]], None] | None = None, ) -> tuple[list[Hit], dict]: hits: list[Hit] = [] observed_keys: dict[str, set] = { @@ -319,121 +353,148 @@ def scan_file( "external_metadata_providers": set(), "audd_result": set(), } - t = start_s stop = min(end_s, duration_s) total_windows = max(1, int((stop - start_s) // stride_s) + 1) - idx = 0 + windows: list[tuple[int, float]] = [] + t = start_s + idx = 0 while t < stop: idx += 1 - backoff = 2.0 - for _attempt in range(5): + windows.append((idx, t)) + t += stride_s + + # ProcessPoolExecutor bypasses the GIL held by the ACR native C extension, + # giving true parallelism for fingerprint extraction + API calls. + with ProcessPoolExecutor(max_workers=20) as executor: + future_to_window = { + executor.submit( + _recognize_window_worker, + recognizer_config, + str(file_path), + int(t), + rec_length, + idx, + total_windows, + ): (idx, t) + for idx, t in windows + } + + for future in as_completed(future_to_window): + idx, t = future_to_window[future] try: - raw = recognizer.recognize_by_file(str(file_path), int(t), rec_length) - break + _, raw = future.result() except Exception as e: - print( - f" [{idx}/{total_windows}] t={t:.0f}s error: {e} (retry in {backoff:.1f}s)", - file=sys.stderr, + print(f" [{idx}/{total_windows}] t={fmt_ts(t)} error: {e}", file=sys.stderr) + if window_cb is not None: + window_cb(t, []) + continue + + if raw is None: + if window_cb is not None: + window_cb(t, []) + continue + + resp = json.loads(raw) if isinstance(raw, str) else raw + code = (resp.get("status") or {}).get("code") + meta = resp.get("metadata") or {} + observed_keys["metadata"].update(meta.keys()) + music = list(meta.get("music") or []) + for row in music + list(meta.get("humming") or []): + observed_keys["music_row"].update(row.keys()) + observed_keys["external_metadata_providers"].update( + (row.get("external_metadata") or {}).keys() ) - time.sleep(backoff) - backoff *= 2 - else: - print(f" [{idx}/{total_windows}] t={t:.0f}s: giving up on window", file=sys.stderr) - t += stride_s - continue - - resp = json.loads(raw) if isinstance(raw, str) else raw - code = (resp.get("status") or {}).get("code") - meta = resp.get("metadata") or {} - observed_keys["metadata"].update(meta.keys()) - music = list(meta.get("music") or []) - for row in music + list(meta.get("humming") or []): - observed_keys["music_row"].update(row.keys()) - observed_keys["external_metadata_providers"].update((row.get("external_metadata") or {}).keys()) - for row in meta.get("humming") or []: - row_copy = dict(row) - row_copy.setdefault("result_from", 2) - music.append(row_copy) - custom_files = meta.get("custom_files") or [] - if custom_files: - print( - f" custom-bucket hits: {len(custom_files)} " - f"titles={[c.get('title') for c in custom_files[:3]]}" - ) - - if code == 0 and music: - window_hits = [parse_music_row(row, t, rec_length) for row in music] - window_hits.sort(key=lambda h: -h.score) - hits.extend(window_hits) - header = ( - f" [{idx}/{total_windows}] t={fmt_ts(t)} " - f"({len(window_hits)} candidate{'s' if len(window_hits) != 1 else ''})" - ) - print(header) - for wh in window_hits: - po_mm = wh.play_offset_ms // 60000 - po_ss = (wh.play_offset_ms % 60000) // 1000 - dur_mm = wh.duration_ms // 60000 - dur_ss = (wh.duration_ms % 60000) // 1000 - pos = f"track-pos {po_mm:02d}:{po_ss:02d}/{dur_mm:02d}:{dur_ss:02d}" + for row in meta.get("humming") or []: + row_copy = dict(row) + row_copy.setdefault("result_from", 2) + music.append(row_copy) + custom_files = meta.get("custom_files") or [] + if custom_files: print( - f" score={wh.score:>3} {pos} {wh.artists} — {wh.title}" - + (f" [ISRC {wh.isrc}]" if wh.isrc else "") + f" custom-bucket hits: {len(custom_files)} " + f"titles={[c.get('title') for c in custom_files[:3]]}" ) - elif code == 1001: - print(f" [{idx}/{total_windows}] t={fmt_ts(t)} acr: no match") - elif code in _FATAL_ACR_STATUS_CODES: - # Auth / quota / project-config errors aren't going to recover by - # continuing to grind through the rest of the file — every window - # would burn another wasted call. Abort loudly. - msg = (resp.get("status") or {}).get("msg", "?") - raise FingerprintAuthError( - f"ACR returned status {code} {msg!r} on window {idx}/{total_windows}. " - f"Check ACR_HOST / ACR_ACCESS_KEY / ACR_ACCESS_SECRET — these creds " - f"don't work against {host_for_logs!r}." - ) - else: - msg = (resp.get("status") or {}).get("msg", "?") - print(f" [{idx}/{total_windows}] t={fmt_ts(t)} acr: status={code} {msg}", file=sys.stderr) - - if audd_token: - audd_backoff = 2.0 - aud_resp: dict = {} - for _attempt in range(3): - try: - aud_resp = audd_recognize(audd_token, file_path, t, rec_length) - break - except Exception as e: - print(f" audd error: {e} (retry in {audd_backoff:.1f}s)", file=sys.stderr) - time.sleep(audd_backoff) - audd_backoff *= 2 - else: - aud_resp = {"status": "error", "error": {"error_message": "all retries failed"}} - observed_keys["audd_result"].update( - (aud_resp.get("result") or {}).keys() if isinstance(aud_resp.get("result"), dict) else [] - ) - if aud_resp.get("status") == "success" and aud_resp.get("result"): - wh = parse_audd_result(aud_resp["result"], t, rec_length) - hits.append(wh) - po_mm = wh.play_offset_ms // 60000 - po_ss = (wh.play_offset_ms % 60000) // 1000 - dur_mm = wh.duration_ms // 60000 - dur_ss = (wh.duration_ms % 60000) // 1000 - print( - f" [AUDD] track-pos {po_mm:02d}:{po_ss:02d}/{dur_mm:02d}:{dur_ss:02d} " - f"{wh.artists} — {wh.title}" - + (f" [ISRC {wh.isrc}]" if wh.isrc else "") - + (f" {wh.song_link}" if wh.song_link else "") + if code == 0 and music: + window_hits = [parse_music_row(row, t, rec_length) for row in music] + window_hits.sort(key=lambda h: -h.score) + hits.extend(window_hits) + this_window_hits: list[Hit] = list(window_hits) + header = ( + f" [{idx}/{total_windows}] t={fmt_ts(t)} " + f"({len(window_hits)} candidate{'s' if len(window_hits) != 1 else ''})" ) - elif aud_resp.get("status") == "success": - print(" [AUDD] no match") + print(header) + for wh in window_hits: + po_mm = wh.play_offset_ms // 60000 + po_ss = (wh.play_offset_ms % 60000) // 1000 + dur_mm = wh.duration_ms // 60000 + dur_ss = (wh.duration_ms % 60000) // 1000 + pos = f"track-pos {po_mm:02d}:{po_ss:02d}/{dur_mm:02d}:{dur_ss:02d}" + print( + f" score={wh.score:>3} {pos} {wh.artists} — {wh.title}" + + (f" [ISRC {wh.isrc}]" if wh.isrc else "") + ) else: - err = (aud_resp.get("error") or {}).get("error_message", aud_resp.get("status")) - print(f" [AUDD] error: {err}", file=sys.stderr) - - t += stride_s + this_window_hits = [] + if code == 1001: + print(f" [{idx}/{total_windows}] t={fmt_ts(t)} acr: no match") + elif code in _FATAL_ACR_STATUS_CODES: + msg = (resp.get("status") or {}).get("msg", "?") + raise FingerprintAuthError( + f"ACR returned status {code} {msg!r} on window {idx}/{total_windows}. " + f"Check ACR_HOST / ACR_ACCESS_KEY / ACR_ACCESS_SECRET — these creds " + f"don't work against {host_for_logs!r}." + ) + else: + msg = (resp.get("status") or {}).get("msg", "?") + print( + f" [{idx}/{total_windows}] t={fmt_ts(t)} acr: status={code} {msg}", + file=sys.stderr, + ) + + if audd_token: + audd_backoff = 2.0 + aud_resp: dict = {} + for _attempt in range(3): + try: + aud_resp = audd_recognize(audd_token, file_path, t, rec_length) + break + except Exception as e: + print(f" audd error: {e} (retry in {audd_backoff:.1f}s)", file=sys.stderr) + time.sleep(audd_backoff) + audd_backoff *= 2 + else: + aud_resp = {"status": "error", "error": {"error_message": "all retries failed"}} + + observed_keys["audd_result"].update( + (aud_resp.get("result") or {}).keys() + if isinstance(aud_resp.get("result"), dict) + else [] + ) + if aud_resp.get("status") == "success" and aud_resp.get("result"): + wh = parse_audd_result(aud_resp["result"], t, rec_length) + hits.append(wh) + this_window_hits.append(wh) + po_mm = wh.play_offset_ms // 60000 + po_ss = (wh.play_offset_ms % 60000) // 1000 + dur_mm = wh.duration_ms // 60000 + dur_ss = (wh.duration_ms % 60000) // 1000 + print( + f" [AUDD] track-pos {po_mm:02d}:{po_ss:02d}/{dur_mm:02d}:{dur_ss:02d} " + f"{wh.artists} — {wh.title}" + + (f" [ISRC {wh.isrc}]" if wh.isrc else "") + + (f" {wh.song_link}" if wh.song_link else "") + ) + elif aud_resp.get("status") == "success": + print(" [AUDD] no match") + else: + err = (aud_resp.get("error") or {}).get("error_message", aud_resp.get("status")) + print(f" [AUDD] error: {err}", file=sys.stderr) + + if window_cb is not None: + window_cb(t, this_window_hits) return hits, observed_keys @@ -673,7 +734,7 @@ def run( "Get them at https://console.acrcloud.com -> your Audio/Video Recognition project." ) - recognizer = ACRCloudRecognizer({"host": host, "access_key": key, "access_secret": secret, "timeout": 15}) + recognizer_config = {"host": host, "access_key": key, "access_secret": secret, "timeout": 15} duration = probe_duration(file) print(f"File: {file} duration={fmt_ts(duration)}") @@ -686,7 +747,7 @@ def run( raise RuntimeError("--audd requires AUDD_TOKEN env var.") hits, observed = scan_file( - recognizer, + recognizer_config, file, duration, stride, diff --git a/src/setplot/pipeline/orchestrator.py b/src/setplot/pipeline/orchestrator.py index 2663acc..275f419 100644 --- a/src/setplot/pipeline/orchestrator.py +++ b/src/setplot/pipeline/orchestrator.py @@ -162,7 +162,13 @@ def _merged_to_viewer_shape(merged: list[dict[str, Any]]) -> list[dict[str, Any] return out -def _run_fingerprint(set_id: str, root: Path | None, stride: float, rec_length: int) -> Path: +def _run_fingerprint( + set_id: str, + root: Path | None, + stride: float, + rec_length: int, + event_cb: EventCb = None, +) -> Path: src = store.find_source(set_id, root=root) if src is None: raise FileNotFoundError(f"no source media in set {set_id}") @@ -177,12 +183,49 @@ def _run_fingerprint(set_id: str, root: Path | None, stride: float, rec_length: "in your shell or a project .env to enable fingerprinting." ) - from acrcloud.recognizer import ACRCloudRecognizer - - recognizer = ACRCloudRecognizer({"host": host, "access_key": key, "access_secret": secret, "timeout": 15}) + recognizer_config = {"host": host, "access_key": key, "access_secret": secret, "timeout": 15} duration = fp_mod.probe_duration(src) + total_windows = max(1, int(duration // stride) + 1) + out = store.step_output_path(set_id, "fingerprint", root=root) + + partial_hits: list[fp_mod.Hit] = [] + partial_windows: dict[str, list[dict[str, Any]]] = {} + completed_count = 0 + + def _write_partial() -> None: + merged = fp_mod.dedupe_and_merge(partial_hits) + out.write_text( + json.dumps( + { + "stride_s": stride, + "rec_length_s": rec_length, + "merged": _merged_to_viewer_shape(merged), + "windows": partial_windows, + "partial": True, + }, + ensure_ascii=False, + ) + ) + + def window_cb(t: float, window_hits: list[fp_mod.Hit]) -> None: + nonlocal completed_count + completed_count += 1 + partial_hits.extend(window_hits) + if window_hits: + bucket = partial_windows.setdefault(str(int(t)), []) + for h in window_hits: + bucket.append(_hit_to_window_candidate(h)) + bucket.sort(key=lambda c: -c["score"]) + _write_partial() + _emit(event_cb, { + "step": "fingerprint", + "state": "running", + "progress": completed_count, + "total": total_windows, + }) + hits, _observed = fp_mod.scan_file( - recognizer, + recognizer_config, src, duration, stride, @@ -191,19 +234,17 @@ def _run_fingerprint(set_id: str, root: Path | None, stride: float, rec_length: float("inf"), audd_token=None, host_for_logs=host, + window_cb=window_cb, ) merged = fp_mod.dedupe_and_merge(hits) - # Build per-window candidates dict keyed by window_start_s (as a string for JSON). windows: dict[str, list[dict[str, Any]]] = {} for h in hits: bucket = windows.setdefault(str(int(h.window_start_s)), []) bucket.append(_hit_to_window_candidate(h)) - # Sort each window's candidates by descending score. for cands in windows.values(): cands.sort(key=lambda c: -c["score"]) - out = store.step_output_path(set_id, "fingerprint", root=root) out.write_text( json.dumps( { @@ -253,7 +294,7 @@ def analyze( "peaks": lambda: _run_peaks(set_id, root), "bpm": lambda: _run_bpm(set_id, root, bpm_step, bpm_window, chunk_min, bpm_engine), "key": lambda: _run_key(set_id, root, key_step, key_window, chunk_min, key_engine), - "fingerprint": lambda: _run_fingerprint(set_id, root, fingerprint_stride, fingerprint_rec_length), + "fingerprint": lambda: _run_fingerprint(set_id, root, fingerprint_stride, fingerprint_rec_length, event_cb), } # status.json is the only shared mutable state — update_step is a @@ -290,3 +331,46 @@ def _run_one(step_name: str, runner: Callable[[], Path]) -> None: wait([ex.submit(_run_one, n, r) for n, r in to_run]) return store.read_status(set_id, root=root)["steps"] + + +def reanalyze_steps( + set_id: str, + steps: list[str], + *, + root: Path | None = None, + bpm_step: float = 5.0, + bpm_window: float = 36.0, + bpm_engine: str = "essentia", + key_step: float = 10.0, + key_window: float = 48.0, + key_engine: str = "essentia", + fingerprint_stride: float = 30.0, + fingerprint_rec_length: int = 10, + chunk_min: float = 10.0, + event_cb: EventCb = None, +) -> dict[str, str]: + """Re-run only the listed steps, leaving all other step statuses untouched.""" + if not store.set_dir(set_id, root=root).exists(): + raise FileNotFoundError(f"set {set_id} not found") + for s in steps: + if s not in store.STEPS: + raise ValueError(f"unknown step: {s!r}") + + runners: dict[str, Callable[[], Path]] = { + "peaks": lambda: _run_peaks(set_id, root), + "bpm": lambda: _run_bpm(set_id, root, bpm_step, bpm_window, chunk_min, bpm_engine), + "key": lambda: _run_key(set_id, root, key_step, key_window, chunk_min, key_engine), + "fingerprint": lambda: _run_fingerprint(set_id, root, fingerprint_stride, fingerprint_rec_length, event_cb), + } + for step_name in steps: + store.update_step(set_id, step_name, "running", root=root) + _emit(event_cb, {"step": step_name, "state": "running"}) + try: + runners[step_name]() + store.update_step(set_id, step_name, "done", root=root) + _emit(event_cb, {"step": step_name, "state": "done"}) + except Exception as exc: + store.update_step(set_id, step_name, f"failed: {exc}", root=root) + _emit(event_cb, {"step": step_name, "state": "failed", "error": str(exc)}) + + return store.read_status(set_id, root=root)["steps"] diff --git a/src/setplot/server/routers/ingest.py b/src/setplot/server/routers/ingest.py index 4dcfc5e..b38f476 100644 --- a/src/setplot/server/routers/ingest.py +++ b/src/setplot/server/routers/ingest.py @@ -31,6 +31,11 @@ class IngestRequest(BaseModel): key_engine: str = "essentia" +class ReanalyzeRequest(BaseModel): + steps: list[str] + key_engine: str = "essentia" + + def _format_sse(event: dict[str, Any], event_type: str | None = None) -> bytes: """RFC: each SSE message is ``event: \\ndata: \\n\\n``.""" lines = [] @@ -64,6 +69,26 @@ def cb(ev: dict[str, Any]) -> None: bus.close_job(job_id) +def _run_reanalyze_for_job(job_id: str, set_id: str, req: ReanalyzeRequest) -> None: + try: + def cb(ev: dict[str, Any]) -> None: + bus.publish(job_id, {**ev, "set_id": set_id}) + + orchestrator.reanalyze_steps(set_id, req.steps, key_engine=req.key_engine, event_cb=cb) + bus.publish(job_id, {"step": "all", "state": "done", "set_id": set_id}) + except Exception as exc: + bus.publish(job_id, {"step": "?", "state": "failed", "error": str(exc)}) + finally: + bus.close_job(job_id) + + +@router.post("/sets/{set_id}/analyze") +async def reanalyze(set_id: str, req: ReanalyzeRequest, background: BackgroundTasks) -> dict[str, str]: + job_id = bus.create_job() + background.add_task(_run_reanalyze_for_job, job_id, set_id, req) + return {"job_id": job_id} + + @router.post("/ingest") async def ingest(req: IngestRequest, background: BackgroundTasks) -> dict[str, str]: job_id = bus.create_job() diff --git a/src/setplot/viewer/set.html b/src/setplot/viewer/set.html index 433da51..af856c4 100644 --- a/src/setplot/viewer/set.html +++ b/src/setplot/viewer/set.html @@ -143,6 +143,14 @@ .legend { display: flex; gap: 12px; font-size: 10px; color: var(--fg-dim); margin-top: 3px; align-items: center; } .legend-swatch { display: inline-block; width: 10px; height: 10px; border-radius: 2px; margin-right: 4px; vertical-align: middle; border: 1px solid rgba(255,255,255,0.1); } + + .reanalyze-btn { background: none; border: 1px solid var(--border); color: var(--fg-dim); + border-radius: 3px; padding: 1px 6px; font-size: 11px; cursor: pointer; line-height: 1.4; + transition: color 0.15s, border-color 0.15s; } + .reanalyze-btn:hover { color: var(--accent); border-color: var(--accent); } + .reanalyze-btn:disabled { opacity: 0.4; cursor: default; } + .reanalyze-btn.running { color: var(--accent-2); border-color: var(--accent-2); + animation: pulse 1.6s ease-in-out infinite; } @@ -167,6 +175,7 @@
BPM — zoomed view scroll to zoom · drag to seek · double-click to reset zoom +
@@ -193,6 +202,7 @@
Camelot key — hour 1–12 on the y-axis A=minor (cyan) · B=major (yellow) · low-confidence (<0.45) hidden +
@@ -203,6 +213,7 @@
Audio waveform — same time axis as BPM click to seek · scroll to playback (wavesurfer) +
@@ -250,6 +261,7 @@
Tracklist
+