xyz / lhotseWorkspace /opusTransform.py
benderrodriguez's picture
Upload folder using huggingface_hub (part 37)
9e060c3 verified
Raw
History Blame Contribute Delete
4.08 kB
import os
# Prevent PyTorch from spawning hundreds of OpenMP threads and locking up your i7
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:
# Ensure subdirectories exist if your source folder has nested folders
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():
# Enforce single-threading for PyTorch operations
torch.set_num_threads(1)
# Force the FFmpeg backend globally for reading any weird audio extensions
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}")
# Set up exact paths
input_dir = Path("/mnt/jonathanDisk/ivritData")
output_dir = Path("/mnt/jonathanDisk/ivritDataOpus")
output_dir.mkdir(parents=True, exist_ok=True)
# Initialize GPU
device = torch.device("cuda" if torch.cuda.is_available() else "cpu")
print(f"Matrix math will execute on: {device}")
# Dictionary to cache GPU resamplers dynamically based on input sample rates
gpu_resamplers = {}
# Scan for all standard audio formats recursively
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.")
# Launch a ThreadPool for the Opus encoding
# We use ThreadPool instead of ProcessPool here because torchaudio.save
# releases the Python GIL (C++ level I/O), making threads incredibly fast with zero memory overhead.
max_workers = 12
executor = concurrent.futures.ThreadPoolExecutor(max_workers=max_workers)
start_time = time.time()
for i, file_path in enumerate(files):
try:
# 1. Fast FFmpeg Load (CPU)
waveform, sr = torchaudio.load(file_path)
# 2. Lightning Fast GPU Resample
if sr != 16000:
# Create/cache a resampler if we encounter a new sample rate
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
# 3. Map the output path to mirror the input directory structure
rel_path = file_path.relative_to(input_dir)
out_path = output_dir / rel_path.with_suffix('.opus')
# 4. Fire and forget to the background CPU Opus encoders
executor.submit(save_opus_async, waveform_16k_cpu, out_path)
# Status tracking
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...")
# This prevents the script from exiting until the final Opus file is written
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()