import os import multiprocessing from lhotse import CutSet from tqdm.auto import tqdm # --- EXACT PATHS --- INPUT_MANIFEST = "/home/jonathan/lhotse_workspace/trimmed_utterance_cuts_16k_fixed.jsonl.gz" OUTPUT_MANIFEST = "/home/jonathan/lhotse_workspace/bulletproof_cuts_for_shar.jsonl.gz" POISON_REPORT = "/home/jonathan/lhotse_workspace/poison_files_report.txt" def _isolated_audio_test(cut): """ Runs in an isolated process. If ffmpeg segfaults on a truncated file, it only kills this child process. """ try: _ = cut.load_audio() except Exception: # Standard Python errors (e.g. file missing) os._exit(1) # Successfully read without dying os._exit(0) def main(): print(f"Loading master manifest: {INPUT_MANIFEST}") cuts = CutSet.from_file(INPUT_MANIFEST) # --- PHASE 1: Find the most dangerous cut for each physical file --- print("\n[Phase 1] Mapping physical files to find boundary cuts...") file_to_boundary_cut = {} for cut in tqdm(cuts, desc="Mapping"): if not cut.has_recording: continue source_path = cut.recording.sources[0].source # Test only the cut that reaches the FURTHEST into the audio file if source_path not in file_to_boundary_cut: file_to_boundary_cut[source_path] = cut else: if cut.end > file_to_boundary_cut[source_path].end: file_to_boundary_cut[source_path] = cut total_files = len(file_to_boundary_cut) print(f"Found {total_files} unique physical audio files.") # --- PHASE 2: Safely test the boundaries --- print("\n[Phase 2] Testing boundaries in isolated environments...") poison_files = set() for path, test_cut in tqdm(file_to_boundary_cut.items(), desc="Detonating Tests"): p = multiprocessing.Process(target=_isolated_audio_test, args=(test_cut,)) p.start() p.join() # Wait for it to finish or crash # If exitcode != 0 (like -11 for Segfault), the file is poison. if p.exitcode != 0: poison_files.add(path) # --- PHASE 3: Amputation --- print(f"\n[Phase 3] Amputation. Found {len(poison_files)} poisoned files.") if len(poison_files) > 0: with open(POISON_REPORT, "w") as f: for pf in poison_files: f.write(f"{pf}\n") print(f"Saved corrupted file list to {POISON_REPORT}") # Filter out ANY cut that relies on a poisoned file print("Filtering corrupted files out of the manifest...") clean_cuts = cuts.filter( lambda c: c.has_recording and c.recording.sources[0].source not in poison_files ) else: print("No poison files found! Your dataset is perfectly clean.") clean_cuts = cuts print(f"\nFinal clean manifest size: {len(clean_cuts)} cuts (Original: {len(cuts)})") print(f"Saving to {OUTPUT_MANIFEST}...") clean_cuts.to_file(OUTPUT_MANIFEST) print("\n✅ Done. You are clear to export.") if __name__ == '__main__': # Required for safe multiprocessing in Python multiprocessing.set_start_method('spawn', force=True) main()