| import os |
| |
| os.environ["OMP_NUM_THREADS"] = "1" |
| os.environ["MKL_NUM_THREADS"] = "1" |
|
|
| import torch |
| import torchaudio |
| from pathlib import Path |
| import concurrent.futures |
| import time |
|
|
| def save_opus_async(waveform_cpu, out_path): |
| """ |
| Runs entirely on a background CPU thread. |
| Compresses the tensor to Opus and writes to disk. |
| """ |
| try: |
| |
| out_path.parent.mkdir(parents=True, exist_ok=True) |
| torchaudio.save(str(out_path), waveform_cpu, 16000, format="opus") |
| except Exception as e: |
| print(f"Failed to encode {out_path}: {e}") |
|
|
| def main(): |
| |
| torch.set_num_threads(1) |
| |
| |
| try: |
| torchaudio.set_audio_backend("ffmpeg") |
| print("Backend explicitly set to FFmpeg.") |
| except Exception as e: |
| print(f"Note: Could not explicitly set ffmpeg backend (might be default in your version): {e}") |
|
|
| |
| input_dir = Path("/mnt/jonathanDisk/ivritData") |
| output_dir = Path("/mnt/jonathanDisk/ivritDataOpus") |
| output_dir.mkdir(parents=True, exist_ok=True) |
|
|
| |
| device = torch.device("cuda" if torch.cuda.is_available() else "cpu") |
| print(f"Matrix math will execute on: {device}") |
| |
| |
| gpu_resamplers = {} |
|
|
| |
| print("Scanning directory for audio files...") |
| exts = ["*.wav", "*.flac", "*.mp3", "*.m4a", "*.ogg"] |
| files = [] |
| for ext in exts: |
| files.extend(list(input_dir.rglob(ext))) |
| |
| print(f"Found {len(files)} files to process.") |
|
|
| |
| |
| |
| max_workers = 12 |
| executor = concurrent.futures.ThreadPoolExecutor(max_workers=max_workers) |
| |
| start_time = time.time() |
| |
| for i, file_path in enumerate(files): |
| try: |
| |
| waveform, sr = torchaudio.load(file_path) |
| |
| |
| if sr != 16000: |
| |
| if sr not in gpu_resamplers: |
| gpu_resamplers[sr] = torchaudio.transforms.Resample(orig_freq=sr, new_freq=16000).to(device) |
| |
| waveform_gpu = waveform.to(device) |
| with torch.inference_mode(): |
| resampled_gpu = gpu_resamplers[sr](waveform_gpu) |
| waveform_16k_cpu = resampled_gpu.to("cpu") |
| else: |
| waveform_16k_cpu = waveform |
| |
| |
| rel_path = file_path.relative_to(input_dir) |
| out_path = output_dir / rel_path.with_suffix('.opus') |
| |
| |
| executor.submit(save_opus_async, waveform_16k_cpu, out_path) |
| |
| |
| if i % 5000 == 0 and i > 0: |
| print(f"Dispatched {i}/{len(files)} files to CPU encoders...") |
| |
| except Exception as e: |
| print(f"Error loading {file_path}: {e}") |
|
|
| print("Finished streaming files through GPU. Waiting for final CPU workers to flush Opus files to disk...") |
| |
| |
| executor.shutdown(wait=True) |
| |
| total_time = time.time() - start_time |
| print(f"Complete! Converted {len(files)} files to 16kHz Opus in {total_time:.2f} seconds.") |
|
|
| if __name__ == '__main__': |
| main() |