fosters commited on
Commit
3763e7a
·
verified ·
1 Parent(s): c441c60

Fix: status bar instead of gr.Progress overlay, per-batch progress, total_rows from datasets-server

Browse files
Files changed (1) hide show
  1. app.py +215 -216
app.py CHANGED
@@ -2,7 +2,6 @@
2
 
3
  Classifies audio chunks in one or more HF datasets using the AST AudioSet model.
4
  Writes a ``<input>_classified`` dataset with id + audio + classification columns only.
5
- The audio column is kept as-is so the HF viewer shows an audio player.
6
  """
7
 
8
  from __future__ import annotations
@@ -23,58 +22,58 @@ import gradio as gr
23
  import pandas as pd
24
  import pyarrow as pa
25
  import pyarrow.parquet as pq
 
26
  import torch
27
  from huggingface_hub import HfApi, hf_hub_download
28
 
29
- from music_detector import ChunkVerdict, _get_ast_runtime, judge_chunk_files_batched
30
 
31
  # ---------------------------------------------------------------------------
32
  # Constants
33
  # ---------------------------------------------------------------------------
34
 
35
  N_CPUS = os.cpu_count() or 2
36
- torch.set_num_threads(N_CPUS) # let BLAS use all CPUs for AST inference
37
 
38
- BATCH_SIZE = 32
39
  DEFAULT_THRESHOLD = 0.25
40
  DEFAULT_NAMESPACE = "fosters"
41
- LOG_MAX_LINES = 500 # keep only last N lines in the log box
 
42
 
43
- # New classifier columns added to every output shard
44
  _CLASSIFIER_FIELDS = [
45
- pa.field("music_score", pa.float32()),
46
- pa.field("has_music", pa.bool_()),
47
- pa.field("contaminated", pa.bool_()),
48
- pa.field("flags", pa.string()),
49
- pa.field("top_labels", pa.string()),
50
- pa.field("rms_db", pa.float32()),
51
- pa.field("clipping_ratio", pa.float32()),
52
- pa.field("max_silence_sec",pa.float32()),
53
  ]
54
 
55
- _HF_FEATURES_CLASSIFIER = {
56
- "id": {"_type": "Value", "dtype": "string"},
57
- "audio": {"_type": "Audio"},
58
- "music_score": {"_type": "Value", "dtype": "float32"},
59
- "has_music": {"_type": "Value", "dtype": "bool"},
60
- "contaminated": {"_type": "Value", "dtype": "bool"},
61
- "flags": {"_type": "Value", "dtype": "string"},
62
- "top_labels": {"_type": "Value", "dtype": "string"},
63
- "rms_db": {"_type": "Value", "dtype": "float32"},
64
- "clipping_ratio": {"_type": "Value", "dtype": "float32"},
65
- "max_silence_sec":{"_type": "Value", "dtype": "float32"},
66
  }
67
 
 
 
68
  _OUTPUT_SCHEMA = pa.schema(
69
  [
70
  pa.field("id", pa.string()),
71
- pa.field("audio", pa.struct([
72
- pa.field("bytes", pa.binary()),
73
- pa.field("path", pa.string()),
74
- ])),
75
  *_CLASSIFIER_FIELDS,
76
  ],
77
- metadata={"huggingface": json.dumps({"info": {"features": _HF_FEATURES_CLASSIFIER}})},
78
  )
79
 
80
 
@@ -89,9 +88,9 @@ def _ts() -> str:
89
 
90
  def _default_out_repo(in_repo: str, suffix: str) -> str:
91
  parts = in_repo.split("/")
92
- name = parts[-1]
93
- ns = parts[0] if len(parts) > 1 else DEFAULT_NAMESPACE
94
- suf = suffix.strip()
95
  if not suf.startswith("_"):
96
  suf = "_" + suf
97
  return f"{ns}/{name}{suf}"
@@ -108,59 +107,63 @@ def _list_parquet_shards(repo_id: str, token: str | None) -> list[str]:
108
  )
109
 
110
 
111
- def _build_output_row(
112
- chunk_id: str,
113
- audio_bytes: bytes,
114
- audio_path_hint: str,
115
- verdict: ChunkVerdict,
116
- ) -> dict[str, Any]:
117
- return {
118
- "id": chunk_id,
119
- "audio": {"bytes": audio_bytes, "path": audio_path_hint},
120
- "music_score": verdict.music_score,
121
- "has_music": verdict.has_music,
122
- "contaminated": verdict.contaminated,
123
- "flags": ", ".join(verdict.flags),
124
- "top_labels": ", ".join(verdict.top_labels[:3]),
125
- "rms_db": verdict.rms_db,
126
- "clipping_ratio": verdict.clipping_ratio,
127
- "max_silence_sec":verdict.max_silence_sec,
128
- }
129
 
130
 
131
  def _rows_to_table(rows: list[dict[str, Any]]) -> pa.Table:
132
- audio_type = _OUTPUT_SCHEMA.field("audio").type
133
  return pa.table(
134
  {
135
- "id": pa.array([r["id"] for r in rows], type=pa.string()),
136
- "audio": pa.array(
137
- [{"bytes": r["audio"]["bytes"], "path": r["audio"]["path"]} for r in rows],
138
- type=audio_type,
139
  ),
140
- "music_score": pa.array([r["music_score"] for r in rows], type=pa.float32()),
141
- "has_music": pa.array([r["has_music"] for r in rows], type=pa.bool_()),
142
- "contaminated": pa.array([r["contaminated"] for r in rows], type=pa.bool_()),
143
- "flags": pa.array([r["flags"] for r in rows], type=pa.string()),
144
- "top_labels": pa.array([r["top_labels"] for r in rows], type=pa.string()),
145
- "rms_db": pa.array([r["rms_db"] for r in rows], type=pa.float32()),
146
- "clipping_ratio": pa.array([r["clipping_ratio"] for r in rows], type=pa.float32()),
147
- "max_silence_sec":pa.array([r["max_silence_sec"] for r in rows], type=pa.float32()),
148
  },
149
  schema=_OUTPUT_SCHEMA,
150
  )
151
 
152
 
153
- def _fmt_verdict(chunk_id: str, v: ChunkVerdict) -> str:
154
- status = "🔴 MUSIC" if v.has_music else ("⚠️ TECH" if v.flags else "✅ ok")
155
- labels = ", ".join(v.top_labels[:2])
156
- flags = f" [{', '.join(v.flags)}]" if v.flags else ""
157
- return f" {chunk_id}: score={v.music_score:.3f} {labels}{flags} {status}"
 
 
 
 
 
158
 
159
 
160
  # ---------------------------------------------------------------------------
161
- # Per-repo generator
162
  # ---------------------------------------------------------------------------
163
 
 
 
164
 
165
  def _process_repo(
166
  repo_id: str,
@@ -168,29 +171,33 @@ def _process_repo(
168
  music_threshold: float,
169
  private: bool,
170
  token: str | None,
171
- ) -> Generator[tuple[list[str], dict[str, Any] | None], None, None]:
172
- """Generator: process one repo. Yields (log_lines, stats_or_None).
173
 
174
- Yields after every BATCH_SIZE chunks so the UI stays responsive.
175
- Final yield carries the completed stats dict.
176
- """
177
  api = HfApi(token=token)
178
  short = repo_id.split("/")[-1]
179
 
180
- # --- list shards ---
181
- yield [f"[{_ts()}] {short}: listing parquet shards…"], None
182
  try:
183
  shard_names = _list_parquet_shards(repo_id, token)
184
  except Exception as exc:
185
- yield [f"[{_ts()}] {short}: ✗ cannot list shards: {exc}"], {"repo": repo_id, "error": str(exc)}
 
186
  return
187
 
188
  if not shard_names:
189
- msg = f"[{_ts()}] {short}: ✗ no data/train-*.parquet shards found"
190
- yield [msg], {"repo": repo_id, "error": "no shards"}
191
  return
192
 
193
- yield [f"[{_ts()}] {short}: {len(shard_names)} shard(s) creating output repo…"], None
 
 
 
 
 
 
 
194
  api.create_repo(repo_id=out_repo, repo_type="dataset", exist_ok=True, private=private)
195
 
196
  stats: dict[str, Any] = {
@@ -204,29 +211,33 @@ def _process_repo(
204
  out_parts: list[Path] = []
205
 
206
  for shard_idx, shard_name in enumerate(shard_names):
207
- # --- download shard ---
208
- yield [f"[{_ts()}] {short}: shard {shard_idx+1}/{len(shard_names)} — downloading…"], None
209
- t_shard = time.time()
 
 
210
  try:
211
  shard_path = hf_hub_download(
212
  repo_id=repo_id, filename=shard_name,
213
  repo_type="dataset", token=token,
214
  )
215
  except Exception as exc:
216
- yield [f"[{_ts()}] {short}: ✗ download failed: {exc}"], None
217
  continue
218
 
219
  in_table = pq.read_table(shard_path)
220
  n_rows = len(in_table)
221
  audio_col = in_table.column("audio")
222
  id_col = in_table.column("id").to_pylist()
 
223
 
224
  yield [
225
  f"[{_ts()}] {short}: shard {shard_idx+1}/{len(shard_names)} — "
226
- f"{n_rows} rows downloaded in {time.time()-t_shard:.1f}s, classifying…"
227
- ], None
 
 
228
 
229
- n_batches = (n_rows + BATCH_SIZE - 1) // BATCH_SIZE
230
  shard_rows: list[dict[str, Any]] = []
231
 
232
  for batch_idx in range(n_batches):
@@ -234,81 +245,85 @@ def _process_repo(
234
  b_end = min(b_start + BATCH_SIZE, n_rows)
235
  t_batch = time.time()
236
 
237
- batch_ids: list[str] = id_col[b_start:b_end]
238
- batch_audio_bytes: list[bytes] = [
239
- (audio_col[i].as_py() or {}).get("bytes") or b""
240
- for i in range(b_start, b_end)
241
- ]
242
- batch_path_hints: list[str] = [
243
- (audio_col[i].as_py() or {}).get("path") or "chunk.mp3"
244
- for i in range(b_start, b_end)
245
- ]
246
-
247
- # write temp audio files for the batch
248
  with tempfile.TemporaryDirectory() as audio_tmp:
249
- audio_files: list[Path] = []
250
- for k, (ab, ph) in enumerate(zip(batch_audio_bytes, batch_path_hints)):
251
- suffix = Path(ph).suffix or ".mp3"
252
- p = Path(audio_tmp) / f"chunk_{k:04d}{suffix}"
253
  p.write_bytes(ab)
254
- audio_files.append(p)
255
 
256
  verdicts = judge_chunk_files_batched(
257
- audio_files,
258
  music_threshold=music_threshold,
259
- batch_size=len(audio_files),
260
  device="cpu",
261
  )
262
 
263
- # accumulate output rows
264
- for chunk_id, audio_bytes, ph, v in zip(
265
- batch_ids, batch_audio_bytes, batch_path_hints, verdicts
266
- ):
267
- shard_rows.append(_build_output_row(chunk_id, audio_bytes, ph, v))
 
 
 
 
 
 
 
268
 
269
- # update stats
270
  n_cont = sum(v.contaminated for v in verdicts)
271
  n_music = sum(v.has_music for v in verdicts)
272
  n_tech = sum(bool(v.flags) and not v.has_music for v in verdicts)
273
- stats["total"] += b_end - b_start
274
- stats["contaminated"]+= n_cont
275
- stats["has_music"] += n_music
276
- stats["technical"] += n_tech
277
 
278
  elapsed = time.time() - t_batch
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
279
 
280
- log_lines = [""] # blank separator
281
- log_lines += [_fmt_verdict(cid, v) for cid, v in zip(batch_ids, verdicts)]
282
- log_lines += [
283
- f"[{_ts()}] batch {batch_idx+1}/{n_batches} "
284
- f"({b_end - b_start} chunks, {elapsed:.1f}s) "
285
- f"shard {shard_idx+1}/{len(shard_names)} "
286
- f"total {stats['total']} processed "
287
- f"contaminated {stats['contaminated']} "
288
- f"({100*stats['contaminated']/max(stats['total'],1):.1f}%)"
289
- ]
290
- yield log_lines, None
291
-
292
- # write shard
293
  out_table = _rows_to_table(shard_rows)
294
  out_part = out_data_dir / f"part_{shard_idx:05d}.parquet"
295
  pq.write_table(out_table, out_part, row_group_size=1, compression="snappy")
296
  out_parts.append(out_part)
297
  yield [
298
  f"[{_ts()}] {short}: shard {shard_idx+1} written "
299
- f"({len(shard_rows)} rows, {out_part.stat().st_size//1024} KB)"
300
- ], None
301
 
302
- # rename with final shard count
303
  n_shards = len(out_parts)
304
- final: list[Path] = []
305
  for i, p in enumerate(out_parts):
306
- dst = out_data_dir / f"train-{i:05d}-of-{n_shards:05d}.parquet"
307
- p.rename(dst)
308
- final.append(dst)
309
 
310
- # upload
311
- yield [f"[{_ts()}] {short}: uploading {n_shards} shard(s) → {out_repo}…"], None
312
  t_up = time.time()
313
  api.upload_folder(
314
  folder_path=str(out_data_dir),
@@ -322,28 +337,27 @@ def _process_repo(
322
  f"contaminated={stats['contaminated']})"
323
  ),
324
  )
 
 
325
  yield [
326
- f"[{_ts()}] {short}: ✓ uploaded in {time.time()-t_up:.1f}s "
327
- f" https://huggingface.co/datasets/{out_repo}"
328
- ], stats
329
 
330
 
331
  # ---------------------------------------------------------------------------
332
- # Gradio handler
333
  # ---------------------------------------------------------------------------
334
 
335
-
336
  def classify_repos(
337
  repos_text: str,
338
  out_suffix: str,
339
  music_threshold: float,
340
  private: bool,
341
  hf_token_input: str,
342
- progress: gr.Progress = gr.Progress(),
343
- ) -> Generator[tuple[str, pd.DataFrame, str], None, None]:
344
- """Main Gradio generator. Yields (log_text, summary_df, links_md)."""
345
- token = hf_token_input.strip() or os.environ.get("HF_TOKEN") or None
346
 
 
347
  repos = [
348
  r.strip()
349
  for line in repos_text.replace(",", "\n").splitlines()
@@ -351,49 +365,44 @@ def classify_repos(
351
  if r and "/" in r
352
  ]
353
  if not repos:
354
- yield "No valid repo IDs (expected owner/name format).", pd.DataFrame(), ""
355
  return
356
 
357
- log: list[str] = []
358
- summary_rows: list[dict[str, Any]] = []
359
- links: list[str] = []
360
 
361
- def _emit() -> tuple[str, pd.DataFrame, str]:
362
- log_text = "\n".join(log[-LOG_MAX_LINES:])
363
- df = pd.DataFrame(summary_rows) if summary_rows else pd.DataFrame()
364
- links_md = "## Output datasets\n" + "\n".join(links) if links else ""
365
- return log_text, df, links_md
366
 
367
- log.append(f"[{_ts()}] Starting: {len(repos)} repo(s), threshold={music_threshold:.2f}")
368
- log.append(f"[{_ts()}] CPUs={N_CPUS}, BATCH_SIZE={BATCH_SIZE}, "
369
- f"HF_XET={'1' if os.environ.get('HF_XET_HIGH_PERFORMANCE') else 'off'}")
 
370
 
371
- # Warm up model
372
- progress(0.0, desc="Loading AST model…")
373
- log.append(f"[{_ts()}] Loading AST model (MIT/ast-finetuned-audioset-10-10-0.4593)…")
374
- yield _emit()
375
  try:
376
  _get_ast_runtime("cpu")
377
  log.append(f"[{_ts()}] Model ready ✓")
378
  except Exception as exc:
379
  log.append(f"[{_ts()}] ✗ model load failed: {exc}")
380
- yield _emit()
381
  return
382
- yield _emit()
383
 
 
384
  t_total = time.time()
385
 
386
  for repo_idx, repo_id in enumerate(repos):
387
  out_repo = _default_out_repo(repo_id, out_suffix)
388
- log.append(f"\n[{_ts()}] {'─'*60}")
389
- log.append(f"[{_ts()}] [{repo_idx+1}/{len(repos)}] {repo_id}")
390
- log.append(f"[{_ts()}] output → {out_repo}")
391
- yield _emit()
392
 
393
- t_repo = time.time()
394
  final_stats: dict[str, Any] | None = None
395
 
396
- for new_lines, maybe_stats in _process_repo(
397
  repo_id=repo_id,
398
  out_repo=out_repo,
399
  music_threshold=music_threshold,
@@ -403,56 +412,39 @@ def classify_repos(
403
  log.extend(new_lines)
404
  if maybe_stats is not None:
405
  final_stats = maybe_stats
 
406
 
407
- # Update progress bar (rough estimate by chunk count)
408
- total_done = sum(r.get("total", 0) for r in summary_rows)
409
- if final_stats:
410
- total_done += final_stats.get("total", 0)
411
- progress(
412
- (repo_idx + min(
413
- (final_stats or {}).get("total", 0) / max(
414
- (final_stats or {}).get("total", 1), 1
415
- ), 1.0
416
- )) / len(repos),
417
- desc=f"[{repo_idx+1}/{len(repos)}] {repo_id.split('/')[-1]}",
418
- )
419
- yield _emit()
420
-
421
- # Build summary row
422
  if final_stats and "error" not in final_stats:
423
- total = final_stats["total"]
424
  cont = final_stats["contaminated"]
425
- summary_rows.append({
426
- "repo": repo_id.split("/")[-1],
427
- "chunks": total,
428
- "contam_%": f"{100*cont/max(total,1):.1f}",
429
- "music": final_stats["has_music"],
430
- "technical": final_stats["technical"],
431
- "time_s": f"{time.time()-t_repo:.0f}",
432
- "output": out_repo,
433
  })
434
  links.append(f"- [{out_repo}](https://huggingface.co/datasets/{out_repo})")
435
  log.append(
436
- f"[{_ts()}] {repo_id.split('/')[-1]}: DONE "
437
- f"total={total} contaminated={cont} ({100*cont/max(total,1):.1f}%) "
438
  f"music={final_stats['has_music']} technical={final_stats['technical']} "
439
  f"elapsed={time.time()-t_repo:.0f}s"
440
  )
441
  elif final_stats:
442
- err = final_stats.get("error", "unknown error")
443
- summary_rows.append({
444
  "repo": repo_id.split("/")[-1], "chunks": 0,
445
- "contam_%": "—", "music": 0, "technical": 0, "time_s": "—",
446
- "output": f"ERROR: {err}",
447
  })
448
- log.append(f"[{_ts()}] {repo_id.split('/')[-1]}: ✗ {err}")
449
 
450
- progress((repo_idx + 1) / len(repos), desc=f"Done {repo_idx+1}/{len(repos)}")
451
- yield _emit()
452
 
453
- log.append(f"\n[{_ts()}] {'='*60}")
454
  log.append(f"[{_ts()}] All done in {time.time()-t_total:.0f}s")
455
- yield _emit()
456
 
457
 
458
  # ---------------------------------------------------------------------------
@@ -466,10 +458,9 @@ Scores audio chunks for **music contamination** and **technical defects** using
466
  [MIT/ast-finetuned-audioset-10-10-0.4593](https://huggingface.co/MIT/ast-finetuned-audioset-10-10-0.4593)
467
  (527 AudioSet classes, multi-label sigmoid).
468
 
469
- **Input** — chunk dataset repo IDs (one per line, `owner/name` format).
470
- **Output** — `<input>_classified` with: `id · audio · music_score · has_music · contaminated · flags · top_labels · rms_db · clipping_ratio · max_silence_sec`.
471
-
472
- Sort by `music_score` ↓ in the HF viewer and press play to spot-check flagged chunks.
473
  """
474
 
475
  with gr.Blocks(title="Chunk Classifier") as demo:
@@ -480,7 +471,7 @@ with gr.Blocks(title="Chunk Classifier") as demo:
480
  repos_input = gr.Textbox(
481
  label="Dataset repo IDs (one per line)",
482
  placeholder="fosters/my-book-chunks\nfosters/another-book-chunks",
483
- lines=6,
484
  )
485
  with gr.Column(scale=1):
486
  out_suffix = gr.Textbox(
@@ -490,7 +481,7 @@ with gr.Blocks(title="Chunk Classifier") as demo:
490
  threshold = gr.Slider(
491
  0.10, 0.60, value=DEFAULT_THRESHOLD, step=0.05,
492
  label="Music threshold",
493
- info="Lower = more sensitive. Default 0.25 biased to recall.",
494
  )
495
  private_toggle = gr.Checkbox(label="Private output", value=True)
496
  token_input = gr.Textbox(
@@ -499,17 +490,25 @@ with gr.Blocks(title="Chunk Classifier") as demo:
499
  )
500
  run_btn = gr.Button("▶ Classify", variant="primary", size="lg")
501
 
 
 
 
 
 
 
 
 
502
  with gr.Row():
503
  with gr.Column(scale=3):
504
  log_out = gr.Textbox(
505
- label="Processing log (per-chunk detail, updates after every batch)",
506
  interactive=False,
507
- lines=30,
508
  max_lines=60,
509
  )
510
  with gr.Column(scale=2):
511
  summary_out = gr.Dataframe(
512
- label="Per-repo summary",
513
  headers=["repo", "chunks", "contam_%", "music", "technical", "time_s", "output"],
514
  wrap=True,
515
  )
@@ -518,7 +517,7 @@ with gr.Blocks(title="Chunk Classifier") as demo:
518
  run_btn.click(
519
  classify_repos,
520
  inputs=[repos_input, out_suffix, threshold, private_toggle, token_input],
521
- outputs=[log_out, summary_out, links_out],
522
  )
523
 
524
  demo.queue()
 
2
 
3
  Classifies audio chunks in one or more HF datasets using the AST AudioSet model.
4
  Writes a ``<input>_classified`` dataset with id + audio + classification columns only.
 
5
  """
6
 
7
  from __future__ import annotations
 
22
  import pandas as pd
23
  import pyarrow as pa
24
  import pyarrow.parquet as pq
25
+ import requests
26
  import torch
27
  from huggingface_hub import HfApi, hf_hub_download
28
 
29
+ from music_detector import _get_ast_runtime, judge_chunk_files_batched
30
 
31
  # ---------------------------------------------------------------------------
32
  # Constants
33
  # ---------------------------------------------------------------------------
34
 
35
  N_CPUS = os.cpu_count() or 2
36
+ torch.set_num_threads(N_CPUS)
37
 
38
+ BATCH_SIZE = 32
39
  DEFAULT_THRESHOLD = 0.25
40
  DEFAULT_NAMESPACE = "fosters"
41
+ LOG_MAX_LINES = 600
42
+ DATASETS_SERVER = "https://datasets-server.huggingface.co"
43
 
 
44
  _CLASSIFIER_FIELDS = [
45
+ pa.field("music_score", pa.float32()),
46
+ pa.field("has_music", pa.bool_()),
47
+ pa.field("contaminated", pa.bool_()),
48
+ pa.field("flags", pa.string()),
49
+ pa.field("top_labels", pa.string()),
50
+ pa.field("rms_db", pa.float32()),
51
+ pa.field("clipping_ratio", pa.float32()),
52
+ pa.field("max_silence_sec", pa.float32()),
53
  ]
54
 
55
+ _HF_FEATURES = {
56
+ "id": {"_type": "Value", "dtype": "string"},
57
+ "audio": {"_type": "Audio"},
58
+ "music_score": {"_type": "Value", "dtype": "float32"},
59
+ "has_music": {"_type": "Value", "dtype": "bool"},
60
+ "contaminated": {"_type": "Value", "dtype": "bool"},
61
+ "flags": {"_type": "Value", "dtype": "string"},
62
+ "top_labels": {"_type": "Value", "dtype": "string"},
63
+ "rms_db": {"_type": "Value", "dtype": "float32"},
64
+ "clipping_ratio": {"_type": "Value", "dtype": "float32"},
65
+ "max_silence_sec": {"_type": "Value", "dtype": "float32"},
66
  }
67
 
68
+ _AUDIO_PA_TYPE = pa.struct([pa.field("bytes", pa.binary()), pa.field("path", pa.string())])
69
+
70
  _OUTPUT_SCHEMA = pa.schema(
71
  [
72
  pa.field("id", pa.string()),
73
+ pa.field("audio", _AUDIO_PA_TYPE),
 
 
 
74
  *_CLASSIFIER_FIELDS,
75
  ],
76
+ metadata={"huggingface": json.dumps({"info": {"features": _HF_FEATURES}})},
77
  )
78
 
79
 
 
88
 
89
  def _default_out_repo(in_repo: str, suffix: str) -> str:
90
  parts = in_repo.split("/")
91
+ ns = parts[0] if len(parts) > 1 else DEFAULT_NAMESPACE
92
+ name = parts[-1]
93
+ suf = suffix.strip()
94
  if not suf.startswith("_"):
95
  suf = "_" + suf
96
  return f"{ns}/{name}{suf}"
 
107
  )
108
 
109
 
110
+ def _fetch_total_rows(repo_id: str, token: str | None) -> int | None:
111
+ """Get total row count via datasets-server (no download required)."""
112
+ try:
113
+ headers = {"Authorization": f"Bearer {token}"} if token else {}
114
+ r = requests.get(
115
+ f"{DATASETS_SERVER}/info",
116
+ params={"dataset": repo_id, "config": "default"},
117
+ headers=headers,
118
+ timeout=20,
119
+ )
120
+ if r.ok:
121
+ splits = r.json().get("dataset_info", {}).get("default", {}).get("splits", {})
122
+ return splits.get("train", {}).get("num_examples")
123
+ except Exception:
124
+ pass
125
+ return None
 
 
126
 
127
 
128
  def _rows_to_table(rows: list[dict[str, Any]]) -> pa.Table:
 
129
  return pa.table(
130
  {
131
+ "id": pa.array([r["id"] for r in rows], type=pa.string()),
132
+ "audio": pa.array(
133
+ [{"bytes": r["audio_bytes"], "path": r["audio_path"]} for r in rows],
134
+ type=_AUDIO_PA_TYPE,
135
  ),
136
+ "music_score": pa.array([r["music_score"] for r in rows], type=pa.float32()),
137
+ "has_music": pa.array([r["has_music"] for r in rows], type=pa.bool_()),
138
+ "contaminated": pa.array([r["contaminated"] for r in rows], type=pa.bool_()),
139
+ "flags": pa.array([r["flags"] for r in rows], type=pa.string()),
140
+ "top_labels": pa.array([r["top_labels"] for r in rows], type=pa.string()),
141
+ "rms_db": pa.array([r["rms_db"] for r in rows], type=pa.float32()),
142
+ "clipping_ratio": pa.array([r["clipping_ratio"] for r in rows], type=pa.float32()),
143
+ "max_silence_sec": pa.array([r["max_silence_sec"] for r in rows], type=pa.float32()),
144
  },
145
  schema=_OUTPUT_SCHEMA,
146
  )
147
 
148
 
149
+ def _fmt_chunk(chunk_id: str, v: Any) -> str: # v: ChunkVerdict
150
+ if v.has_music:
151
+ icon = "🔴"
152
+ elif v.flags:
153
+ icon = "⚠️"
154
+ else:
155
+ icon = "✅"
156
+ labels = ", ".join(v.top_labels[:2])
157
+ flags = f" [{', '.join(v.flags)}]" if v.flags else ""
158
+ return f" {icon} {chunk_id} score={v.music_score:.3f} {labels}{flags}"
159
 
160
 
161
  # ---------------------------------------------------------------------------
162
+ # Per-repo processing generator
163
  # ---------------------------------------------------------------------------
164
 
165
+ # Yields: (new_log_lines: list[str], status: str, chunks_done: int, stats: dict | None)
166
+ # chunks_done counts chunks processed so far in this repo (for caller progress math)
167
 
168
  def _process_repo(
169
  repo_id: str,
 
171
  music_threshold: float,
172
  private: bool,
173
  token: str | None,
174
+ ) -> Generator[tuple[list[str], str, int, dict[str, Any] | None], None, None]:
 
175
 
 
 
 
176
  api = HfApi(token=token)
177
  short = repo_id.split("/")[-1]
178
 
179
+ # List shards
180
+ yield [f"[{_ts()}] {short}: listing shards…"], "Listing shards…", 0, None
181
  try:
182
  shard_names = _list_parquet_shards(repo_id, token)
183
  except Exception as exc:
184
+ err = str(exc)
185
+ yield [f"[{_ts()}] {short}: ✗ {err}"], f"Error: {err}", 0, {"repo": repo_id, "error": err}
186
  return
187
 
188
  if not shard_names:
189
+ msg = "no data/train-*.parquet shards found"
190
+ yield [f"[{_ts()}] {short}: ✗ {msg}"], f"Error: {msg}", 0, {"repo": repo_id, "error": msg}
191
  return
192
 
193
+ # Get total row count (for progress display, not critical)
194
+ total_rows = _fetch_total_rows(repo_id, token)
195
+ total_str = str(total_rows) if total_rows else "?"
196
+
197
+ yield [
198
+ f"[{_ts()}] {short}: {len(shard_names)} shard(s), {total_str} rows total"
199
+ ], f"Preparing… {len(shard_names)} shards, {total_str} chunks", 0, None
200
+
201
  api.create_repo(repo_id=out_repo, repo_type="dataset", exist_ok=True, private=private)
202
 
203
  stats: dict[str, Any] = {
 
211
  out_parts: list[Path] = []
212
 
213
  for shard_idx, shard_name in enumerate(shard_names):
214
+ yield [
215
+ f"[{_ts()}] {short}: shard {shard_idx+1}/{len(shard_names)} — downloading…"
216
+ ], f"[{shard_idx+1}/{len(shard_names)}] downloading shard…", stats["total"], None
217
+
218
+ t_dl = time.time()
219
  try:
220
  shard_path = hf_hub_download(
221
  repo_id=repo_id, filename=shard_name,
222
  repo_type="dataset", token=token,
223
  )
224
  except Exception as exc:
225
+ yield [f"[{_ts()}] {short}: ✗ download failed: {exc}"], "Download error", stats["total"], None
226
  continue
227
 
228
  in_table = pq.read_table(shard_path)
229
  n_rows = len(in_table)
230
  audio_col = in_table.column("audio")
231
  id_col = in_table.column("id").to_pylist()
232
+ n_batches = (n_rows + BATCH_SIZE - 1) // BATCH_SIZE
233
 
234
  yield [
235
  f"[{_ts()}] {short}: shard {shard_idx+1}/{len(shard_names)} — "
236
+ f"{n_rows} rows, downloaded in {time.time()-t_dl:.1f}s"
237
+ ], (
238
+ f"[{shard_idx+1}/{len(shard_names)}] {n_rows} rows — starting inference…"
239
+ ), stats["total"], None
240
 
 
241
  shard_rows: list[dict[str, Any]] = []
242
 
243
  for batch_idx in range(n_batches):
 
245
  b_end = min(b_start + BATCH_SIZE, n_rows)
246
  t_batch = time.time()
247
 
248
+ batch_ids: list[str] = id_col[b_start:b_end]
249
+ batch_audio: list[dict] = [(audio_col[i].as_py() or {}) for i in range(b_start, b_end)]
250
+ batch_bytes: list[bytes] = [a.get("bytes") or b"" for a in batch_audio]
251
+ batch_paths: list[str] = [a.get("path") or "chunk.mp3" for a in batch_audio]
252
+
 
 
 
 
 
 
253
  with tempfile.TemporaryDirectory() as audio_tmp:
254
+ files: list[Path] = []
255
+ for k, (ab, ph) in enumerate(zip(batch_bytes, batch_paths)):
256
+ p = Path(audio_tmp) / f"c{k:04d}{Path(ph).suffix or '.mp3'}"
 
257
  p.write_bytes(ab)
258
+ files.append(p)
259
 
260
  verdicts = judge_chunk_files_batched(
261
+ files,
262
  music_threshold=music_threshold,
263
+ batch_size=len(files),
264
  device="cpu",
265
  )
266
 
267
+ for cid, ab, ph, v in zip(batch_ids, batch_bytes, batch_paths, verdicts):
268
+ shard_rows.append({
269
+ "id": cid, "audio_bytes": ab, "audio_path": ph,
270
+ "music_score": v.music_score,
271
+ "has_music": v.has_music,
272
+ "contaminated": v.contaminated,
273
+ "flags": ", ".join(v.flags),
274
+ "top_labels": ", ".join(v.top_labels[:3]),
275
+ "rms_db": v.rms_db,
276
+ "clipping_ratio": v.clipping_ratio,
277
+ "max_silence_sec": v.max_silence_sec,
278
+ })
279
 
 
280
  n_cont = sum(v.contaminated for v in verdicts)
281
  n_music = sum(v.has_music for v in verdicts)
282
  n_tech = sum(bool(v.flags) and not v.has_music for v in verdicts)
283
+ stats["total"] += b_end - b_start
284
+ stats["contaminated"] += n_cont
285
+ stats["has_music"] += n_music
286
+ stats["technical"] += n_tech
287
 
288
  elapsed = time.time() - t_batch
289
+ done = stats["total"]
290
+ cont_pct = 100 * stats["contaminated"] / max(done, 1)
291
+
292
+ # Build log lines: one per chunk + batch summary
293
+ chunk_lines = [_fmt_chunk(cid, v) for cid, v in zip(batch_ids, verdicts)]
294
+ summary_line = (
295
+ f"[{_ts()}] batch {batch_idx+1}/{n_batches} "
296
+ f"· shard {shard_idx+1}/{len(shard_names)} "
297
+ f"· {elapsed:.1f}s "
298
+ f"· total {done}/{total_str} chunks "
299
+ f"· contaminated {stats['contaminated']} ({cont_pct:.1f}%)"
300
+ )
301
+
302
+ status = (
303
+ f"[{shard_idx+1}/{len(shard_names)}] "
304
+ f"batch {batch_idx+1}/{n_batches} "
305
+ f"· {done}/{total_str} chunks "
306
+ f"· {cont_pct:.1f}% contaminated"
307
+ )
308
+
309
+ yield [""] + chunk_lines + [summary_line], status, done, None
310
 
311
+ # Write shard
 
 
 
 
 
 
 
 
 
 
 
 
312
  out_table = _rows_to_table(shard_rows)
313
  out_part = out_data_dir / f"part_{shard_idx:05d}.parquet"
314
  pq.write_table(out_table, out_part, row_group_size=1, compression="snappy")
315
  out_parts.append(out_part)
316
  yield [
317
  f"[{_ts()}] {short}: shard {shard_idx+1} written "
318
+ f"({len(shard_rows)} rows, {out_part.stat().st_size // 1024} KB)"
319
+ ], f"Shard {shard_idx+1} written, uploading…", stats["total"], None
320
 
321
+ # Rename + upload
322
  n_shards = len(out_parts)
 
323
  for i, p in enumerate(out_parts):
324
+ p.rename(out_data_dir / f"train-{i:05d}-of-{n_shards:05d}.parquet")
 
 
325
 
326
+ yield [f"[{_ts()}] {short}: uploading {n_shards} shard(s) → {out_repo}…"], "Uploading…", stats["total"], None
 
327
  t_up = time.time()
328
  api.upload_folder(
329
  folder_path=str(out_data_dir),
 
337
  f"contaminated={stats['contaminated']})"
338
  ),
339
  )
340
+
341
+ url = f"https://huggingface.co/datasets/{out_repo}"
342
  yield [
343
+ f"[{_ts()}] {short}: ✓ uploaded in {time.time()-t_up:.1f}s → {url}"
344
+ ], f"Done ✓ → {out_repo}", stats["total"], stats
 
345
 
346
 
347
  # ---------------------------------------------------------------------------
348
+ # Gradio generator (no gr.Progress — avoids overlay)
349
  # ---------------------------------------------------------------------------
350
 
351
+ # Outputs: log_text, status_text, summary_df, links_md
352
  def classify_repos(
353
  repos_text: str,
354
  out_suffix: str,
355
  music_threshold: float,
356
  private: bool,
357
  hf_token_input: str,
358
+ ) -> Generator[tuple[str, str, pd.DataFrame, str], None, None]:
 
 
 
359
 
360
+ token = hf_token_input.strip() or os.environ.get("HF_TOKEN") or None
361
  repos = [
362
  r.strip()
363
  for line in repos_text.replace(",", "\n").splitlines()
 
365
  if r and "/" in r
366
  ]
367
  if not repos:
368
+ yield "No valid repo IDs (expected owner/name format).", "", pd.DataFrame(), ""
369
  return
370
 
371
+ log: list[str] = []
372
+ rows: list[dict[str, Any]] = []
373
+ links: list[str] = []
374
 
375
+ def _snapshot(status: str) -> tuple[str, str, pd.DataFrame, str]:
376
+ log_text = "\n".join(log[-LOG_MAX_LINES:])
377
+ df = pd.DataFrame(rows) if rows else pd.DataFrame()
378
+ links_md = "## Output datasets\n" + "\n".join(links) if links else ""
379
+ return log_text, status, df, links_md
380
 
381
+ log.append(f"[{_ts()}] {len(repos)} repo(s) · threshold={music_threshold:.2f} · CPUs={N_CPUS}")
382
+ log.append(f"[{_ts()}] HF_XET_HIGH_PERFORMANCE={os.environ.get('HF_XET_HIGH_PERFORMANCE','off')}")
383
+ log.append(f"[{_ts()}] Loading AST model…")
384
+ yield _snapshot("Loading AST model…")
385
 
 
 
 
 
386
  try:
387
  _get_ast_runtime("cpu")
388
  log.append(f"[{_ts()}] Model ready ✓")
389
  except Exception as exc:
390
  log.append(f"[{_ts()}] ✗ model load failed: {exc}")
391
+ yield _snapshot(f"Error: {exc}")
392
  return
 
393
 
394
+ yield _snapshot("Model ready")
395
  t_total = time.time()
396
 
397
  for repo_idx, repo_id in enumerate(repos):
398
  out_repo = _default_out_repo(repo_id, out_suffix)
399
+ log.append(f"\n[{_ts()}] {'─'*56}")
400
+ log.append(f"[{_ts()}] [{repo_idx+1}/{len(repos)}] {repo_id} → {out_repo}")
 
 
401
 
402
+ t_repo = time.time()
403
  final_stats: dict[str, Any] | None = None
404
 
405
+ for new_lines, status, chunks_done, maybe_stats in _process_repo(
406
  repo_id=repo_id,
407
  out_repo=out_repo,
408
  music_threshold=music_threshold,
 
412
  log.extend(new_lines)
413
  if maybe_stats is not None:
414
  final_stats = maybe_stats
415
+ yield _snapshot(f"[{repo_idx+1}/{len(repos)}] {status}")
416
 
417
+ # Summary row
 
 
 
 
 
 
 
 
 
 
 
 
 
 
418
  if final_stats and "error" not in final_stats:
419
+ n = final_stats["total"]
420
  cont = final_stats["contaminated"]
421
+ rows.append({
422
+ "repo": repo_id.split("/")[-1],
423
+ "chunks": n,
424
+ "contam_%": f"{100*cont/max(n,1):.1f}",
425
+ "music": final_stats["has_music"],
426
+ "technical": final_stats["technical"],
427
+ "time_s": f"{time.time()-t_repo:.0f}",
428
+ "output": out_repo,
429
  })
430
  links.append(f"- [{out_repo}](https://huggingface.co/datasets/{out_repo})")
431
  log.append(
432
+ f"[{_ts()}] DONE total={n} contaminated={cont} ({100*cont/max(n,1):.1f}%) "
 
433
  f"music={final_stats['has_music']} technical={final_stats['technical']} "
434
  f"elapsed={time.time()-t_repo:.0f}s"
435
  )
436
  elif final_stats:
437
+ rows.append({
 
438
  "repo": repo_id.split("/")[-1], "chunks": 0,
439
+ "contam_%": "—", "music": 0, "technical": 0,
440
+ "time_s": "—", "output": f"ERROR: {final_stats.get('error')}",
441
  })
 
442
 
443
+ yield _snapshot(f"[{repo_idx+1}/{len(repos)}] done")
 
444
 
445
+ log.append(f"\n[{_ts()}] {'='*56}")
446
  log.append(f"[{_ts()}] All done in {time.time()-t_total:.0f}s")
447
+ yield _snapshot("All done ✓")
448
 
449
 
450
  # ---------------------------------------------------------------------------
 
458
  [MIT/ast-finetuned-audioset-10-10-0.4593](https://huggingface.co/MIT/ast-finetuned-audioset-10-10-0.4593)
459
  (527 AudioSet classes, multi-label sigmoid).
460
 
461
+ **Input** — chunk dataset repo IDs (one per line).
462
+ **Output** — `<input>_classified` with `id · audio · music_score · has_music · contaminated · flags · top_labels · rms_db · clipping_ratio · max_silence_sec`.
463
+ Sort by `music_score ↓` in the HF viewer and press play to spot-check.
 
464
  """
465
 
466
  with gr.Blocks(title="Chunk Classifier") as demo:
 
471
  repos_input = gr.Textbox(
472
  label="Dataset repo IDs (one per line)",
473
  placeholder="fosters/my-book-chunks\nfosters/another-book-chunks",
474
+ lines=5,
475
  )
476
  with gr.Column(scale=1):
477
  out_suffix = gr.Textbox(
 
481
  threshold = gr.Slider(
482
  0.10, 0.60, value=DEFAULT_THRESHOLD, step=0.05,
483
  label="Music threshold",
484
+ info="Lower = more sensitive (recall-biased). Default 0.25.",
485
  )
486
  private_toggle = gr.Checkbox(label="Private output", value=True)
487
  token_input = gr.Textbox(
 
490
  )
491
  run_btn = gr.Button("▶ Classify", variant="primary", size="lg")
492
 
493
+ # Status line — replaces gr.Progress() which caused overlay issues
494
+ status_out = gr.Textbox(
495
+ label="Status",
496
+ interactive=False,
497
+ lines=1,
498
+ max_lines=1,
499
+ )
500
+
501
  with gr.Row():
502
  with gr.Column(scale=3):
503
  log_out = gr.Textbox(
504
+ label="Processing log (updates every batch ~30s)",
505
  interactive=False,
506
+ lines=28,
507
  max_lines=60,
508
  )
509
  with gr.Column(scale=2):
510
  summary_out = gr.Dataframe(
511
+ label="Summary",
512
  headers=["repo", "chunks", "contam_%", "music", "technical", "time_s", "output"],
513
  wrap=True,
514
  )
 
517
  run_btn.click(
518
  classify_repos,
519
  inputs=[repos_input, out_suffix, threshold, private_toggle, token_input],
520
+ outputs=[log_out, status_out, summary_out, links_out],
521
  )
522
 
523
  demo.queue()