Fix ???B/s spam, add live MB/s + rows/s telemetry, and optimize 44.1/48kHz resampling
Browse files6 unmodified lines78910111213144 unmodified lines1920212223242526200 unmodified lines227228229230231232233234181 unmodified lines41641741841942042142242342442542642742842943043143243343421 unmodified lines45645745845946046146220 unmodified lines4834844854864874884894904916 unmodified linesimport jsonimport mathimport osimport reimport tempfileimport unicodedatafrom collections import Counterfrom dataclasses import dataclass4 unmodified linesimport torchfrom datasets import Audio, Dataset, load_datasetfrom huggingface_hub import CommitOperationAdd, HfApi, hf_hub_downloadfrom scipy.io import wavfilefrom scipy.signal import resample_polyfrom data.audio_processor import read_audio_bytes, read_audio_file200 unmodified linesraise Reject("clipped")previous_hash = legacy_wav_hash(mono, sr) if check_legacy else Noneif sr != RATE:factor = math.gcd(sr, RATE)mono = torch.from_numpy(resample_poly(mono.numpy(), RATE // factor, sr // factor))if not torch.isfinite(mono).all():raise Reject("invalid_or_low_rate")mono = trim_silence(mono)181 unmodified linesdef flush(self, src, state, rows, keys):prefix = f"{ROOT}/{src.name}/"entries = {}with tempfile.TemporaryDirectory() as tmp:if rows:name = f"shard-{state['next_shard']:05d}.parquet"local = str(Path(tmp) / name)ds = Dataset.from_list(rows).cast_column("audio", Audio(sampling_rate=RATE, decode=False))ds.to_parquet(local, batch_size=16)if prefix + name in self.files:raise CommitFailure(f"Shard already exists: {name}. Reload repository state.")entries[prefix + name] = localentries[prefix + name + ".idx.gz"] = self.pack_index(keys)state["next_shard"] += 1entries[prefix + "_state.json"] = json.dumps(state, indent=2, allow_nan=False).encode()self.commit(f"Checkpoint {src.name} at row {state['rows_seen']}", entries)self.states[src.name] = dict(state, rejected=dict(state["rejected"]))self.remember(keys, src.name)rows.clear()21 unmodified linesrows, keys, pending = [], [], set()size = 0last_saved = state["rows_seen"]stream = iter(ds.skip(last_saved) if last_saved else ds)while state["curated_hours"] < target:try:row = next(stream)20 unmodified linessize += len(wav)state["curated_hours"] += seconds / 3600state["curated_clips"] += 1if size >= self.shard_bytes or (not rows and state["rows_seen"] - last_saved >= 2000):self.flush(src, state, rows, keys)print(f"{src.name}: saved {state['curated_hours']:.3f} h, {state['curated_clips']} clips", flush=True)last_saved = state["rows_seen"]pending.clear()size = 06 unmodified lines789101112131415164 unmodified lines21222324252627282930313233343536373839200 unmodified lines240241242243244245246247248249250251252253254181 unmodified lines43643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546621 unmodified lines48848949049149249349449549649749820 unmodified lines5195205215225235245255265275285295305315325335345355365375385395406 unmodified linesimport jsonimport mathimport osos.environ.setdefault("HF_HUB_DISABLE_PROGRESS_BARS", "1")import reimport tempfileimport timeimport unicodedatafrom collections import Counterfrom dataclasses import dataclass4 unmodified linesimport torchfrom datasets import Audio, Dataset, load_datasetfrom huggingface_hub import CommitOperationAdd, HfApi, hf_hub_downloadtry:from huggingface_hub.utils import disable_progress_barsdisable_progress_bars()except Exception:passfrom scipy.io import wavfilefrom scipy.signal import resample_polytry:import torchaudio.transforms as _TA_Texcept Exception:_TA_T = None_RESAMPLERS = {}from data.audio_processor import read_audio_bytes, read_audio_file200 unmodified linesraise Reject("clipped")previous_hash = legacy_wav_hash(mono, sr) if check_legacy else Noneif sr != RATE:if _TA_T is not None:resampler = _RESAMPLERS.get(sr)if resampler is None:resampler = _TA_T.Resample(orig_freq=sr, new_freq=RATE)_RESAMPLERS[sr] = resamplermono = resampler(mono.float().unsqueeze(0)).squeeze(0)else:factor = math.gcd(sr, RATE)mono = torch.from_numpy(resample_poly(mono.numpy(), RATE // factor, sr // factor))if not torch.isfinite(mono).all():raise Reject("invalid_or_low_rate")mono = trim_silence(mono)181 unmodified linesdef flush(self, src, state, rows, keys):prefix = f"{ROOT}/{src.name}/"entries = {}upload_bytes = 0shard_name = Nonet_up = time.perf_counter()with tempfile.TemporaryDirectory() as tmp:if rows:shard_name = f"shard-{state['next_shard']:05d}.parquet"local = str(Path(tmp) / shard_name)ds = Dataset.from_list(rows).cast_column("audio", Audio(sampling_rate=RATE, decode=False))ds.to_parquet(local, batch_size=16)if prefix + shard_name in self.files:raise CommitFailure(f"Shard already exists: {shard_name}. Reload repository state.")upload_bytes = os.path.getsize(local)entries[prefix + shard_name] = localentries[prefix + shard_name + ".idx.gz"] = self.pack_index(keys)state["next_shard"] += 1entries[prefix + "_state.json"] = json.dumps(state, indent=2, allow_nan=False).encode()self.commit(f"Checkpoint {src.name} at row {state['rows_seen']}", entries)if shard_name is not None and upload_bytes > 0:up_s = max(time.perf_counter() - t_up, 1e-3)mb = upload_bytes / (1024 * 1024)print(f"[Upload OK] {src.name}/{shard_name} | {mb:.1f} MB in {up_s:.1f}s ({mb / up_s:.1f} MB/s) | "f"total={state['curated_hours']:.2f}h ({state['curated_clips']:,} clips)",flush=True,)self.states[src.name] = dict(state, rejected=dict(state["rejected"]))self.remember(keys, src.name)rows.clear()21 unmodified linesrows, keys, pending = [], [], set()size = 0last_saved = state["rows_seen"]start_rows = last_savedstart_hrs = state["curated_hours"]t_start = time.perf_counter()stream = iter(ds.skip(last_saved) if last_saved else ds)print(f"\n>>> [{src.name}] Resuming at row {last_saved:,} ({start_hrs:.2f}h / {target:.1f}h target) <<<", flush=True)while state["curated_hours"] < target:try:row = next(stream)20 unmodified linessize += len(wav)state["curated_hours"] += seconds / 3600state["curated_clips"] += 1seen_now = state["rows_seen"] - start_rowsif seen_now % 250 == 0:dt = max(time.perf_counter() - t_start, 1e-3)rate = seen_now / dtbuf_mb = size / (1024 * 1024)hrs_per_min = (state["curated_hours"] - start_hrs) / (dt / 60.0)print(f" [{src.name}] rows={state['rows_seen']:,} | {state['curated_hours']:.2f}/{target:.1f}h "f"({state['curated_clips']:,} clips) | {rate:.1f} rows/s | +{hrs_per_min:.2f}h/min | "f"buf={buf_mb:.0f}/{self.shard_bytes/(1024*1024):.0f} MB",flush=True,)if size >= self.shard_bytes or (not rows and state["rows_seen"] - last_saved >= 2000):self.flush(src, state, rows, keys)last_saved = state["rows_seen"]pending.clear()size = 0
kaggle_data_collector.py+58-9