Download audio_processor.py from Themozhi/meity: direct link, hf CLI and curl.
- Browser
- Download file 10.5 kB
-
https://huggingface.co/spaces/Themozhi/meity/resolve/main/audio_processor.py
- Command line
-
hf download hf://spaces/Themozhi/meity/audio_processor.py
-
curl -L -o audio_processor.py https://huggingface.co/spaces/Themozhi/meity/resolve/main/audio_processor.py
10.5 kB
| #!/usr/bin/env python3 | |
| # -*- coding: utf-8 -*- | |
| """ | |
| CPU-safe audio processing script for dysarthric voice conversion. | |
| This version works on both CPU and GPU environments. | |
| """ | |
| import torch | |
| import torchaudio | |
| import argparse | |
| import os | |
| import sys | |
| import traceback | |
| from pathlib import Path | |
| def load_models(): | |
| """Load the pre-trained models with CPU-safe loading.""" | |
| print("=" * 60) | |
| print("LOADING MODELS") | |
| print("=" * 60) | |
| try: | |
| # Determine device and map_location | |
| device = "cuda" if torch.cuda.is_available() else "cpu" | |
| map_location = torch.device(device) | |
| print(f"Device: {device}") | |
| if device == "cpu": | |
| print("Warning: CUDA not available, using CPU (will be slower)") | |
| else: | |
| print(f"Using GPU: {torch.cuda.get_device_name()}") | |
| print("\n--- Loading HuBERT model ---") | |
| try: | |
| # Load with explicit map_location for CPU compatibility | |
| hubert = torch.hub.load( | |
| "Themozhi/hubert:main", | |
| "hubert_soft", | |
| trust_repo=True, | |
| map_location=map_location | |
| ) | |
| if device == "cuda": | |
| hubert = hubert.cuda() | |
| print("HuBERT model loaded successfully") | |
| except Exception as e: | |
| print(f"HuBERT loading failed: {e}") | |
| traceback.print_exc() | |
| return None, None, None, None | |
| print("\n--- Loading Acoustic model ---") | |
| try: | |
| # Load with explicit map_location for CPU compatibility | |
| acoustic = torch.hub.load( | |
| "Themozhi/acoustic-model:main", | |
| "hubert_soft", | |
| trust_repo=True, | |
| map_location=map_location | |
| ) | |
| if device == "cuda": | |
| acoustic = acoustic.cuda() | |
| print("Acoustic model loaded successfully") | |
| except Exception as e: | |
| print(f"Acoustic model loading failed: {e}") | |
| traceback.print_exc() | |
| return None, None, None, None | |
| print("\n--- Loading HiFi-GAN vocoder ---") | |
| try: | |
| # Load with explicit map_location for CPU compatibility | |
| hifigan = torch.hub.load( | |
| "Themozhi/hifigan:main", | |
| "hifigan_hubert_soft", | |
| trust_repo=True, | |
| map_location=map_location | |
| ) | |
| if device == "cuda": | |
| hifigan = hifigan.cuda() | |
| print("HiFi-GAN model loaded successfully") | |
| except Exception as e: | |
| print(f"HiFi-GAN loading failed: {e}") | |
| traceback.print_exc() | |
| return None, None, None, None | |
| print("\nAll models loaded successfully!") | |
| return hubert, acoustic, hifigan, device | |
| except Exception as e: | |
| print(f"Error loading models: {e}") | |
| traceback.print_exc() | |
| return None, None, None, None | |
| def process_audio(input_path, output_path, models): | |
| """Process the input audio file and save the result.""" | |
| hubert, acoustic, hifigan, device = models | |
| if None in models: | |
| print("Models not loaded properly") | |
| return False | |
| print("\n" + "=" * 60) | |
| print("PROCESSING AUDIO") | |
| print("=" * 60) | |
| try: | |
| print(f"Input file: {input_path}") | |
| print(f"Output file: {output_path}") | |
| # Check if input file exists | |
| if not os.path.exists(input_path): | |
| print(f"Error: Input file does not exist: {input_path}") | |
| return False | |
| # Load audio file | |
| print("\n--- Loading audio file ---") | |
| try: | |
| source, sr = torchaudio.load(input_path) | |
| print(f"Audio loaded successfully") | |
| print(f" Shape: {source.shape}, Sample rate: {sr}") | |
| except Exception as e: | |
| print(f"Error loading audio: {e}") | |
| return False | |
| # Resample to 16kHz if necessary | |
| if sr != 16000: | |
| print(f"--- Resampling from {sr}Hz to 16000Hz ---") | |
| try: | |
| source = torchaudio.functional.resample(source, sr, 16000) | |
| print(f"Resampling successful, new shape: {source.shape}") | |
| except Exception as e: | |
| print(f"Error resampling: {e}") | |
| return False | |
| # Add batch dimension and move to device | |
| print(f"\n--- Preparing tensor for {device} ---") | |
| try: | |
| source = source.unsqueeze(0) | |
| if device == "cuda": | |
| source = source.cuda() | |
| print("Moved to GPU") | |
| else: | |
| print("Using CPU") | |
| print(f"Final input shape: {source.shape}") | |
| except Exception as e: | |
| print(f"Error preparing tensor: {e}") | |
| return False | |
| print("\n--- Neural Processing Pipeline ---") | |
| try: | |
| with torch.inference_mode(): | |
| # Extract speech units | |
| print("Extracting speech units with HuBERT...") | |
| units = hubert.units(source) | |
| print(f"Speech units extracted, shape: {units.shape}") | |
| # Generate target spectrogram | |
| print("Generating target spectrogram...") | |
| mel = acoustic.generate(units).transpose(1, 2) | |
| print(f"Spectrogram generated, shape: {mel.shape}") | |
| # Generate audio waveform | |
| print("Synthesizing audio with HiFi-GAN...") | |
| target = hifigan(mel) | |
| print(f"Audio synthesized, shape: {target.shape}") | |
| except Exception as e: | |
| print(f"Error in neural processing: {e}") | |
| traceback.print_exc() | |
| return False | |
| # Prepare output | |
| print("\n--- Preparing output ---") | |
| try: | |
| target_cpu = target.squeeze().cpu() | |
| print(f"Output tensor shape: {target_cpu.shape}") | |
| # Fix tensor shape for torchaudio.save | |
| if target_cpu.ndim == 1: | |
| target_cpu = target_cpu.unsqueeze(0) | |
| # Ensure output directory exists | |
| output_dir = os.path.dirname(output_path) | |
| if output_dir: | |
| os.makedirs(output_dir, exist_ok=True) | |
| except Exception as e: | |
| print(f"Error preparing output: {e}") | |
| return False | |
| # Save the processed audio | |
| print(f"\n--- Saving to: {output_path} ---") | |
| try: | |
| torchaudio.save(output_path, target_cpu, 16000) | |
| print("Audio saved successfully") | |
| except Exception as e: | |
| print(f"Error saving audio: {e}") | |
| traceback.print_exc() | |
| return False | |
| # Verify output | |
| if os.path.exists(output_path): | |
| output_size = os.path.getsize(output_path) | |
| print(f"Output file verified, size: {output_size} bytes") | |
| print("Audio processing completed successfully!") | |
| return True | |
| else: | |
| print("Error: Output file was not created") | |
| return False | |
| except Exception as e: | |
| print(f"Unexpected error processing audio: {e}") | |
| traceback.print_exc() | |
| return False | |
| def test_environment(): | |
| """Test the environment setup.""" | |
| print("ENVIRONMENT TEST") | |
| print("=" * 60) | |
| print(f"Python version: {sys.version}") | |
| print(f"PyTorch version: {torch.__version__}") | |
| print(f"TorchAudio version: {torchaudio.__version__}") | |
| print(f"CUDA available: {torch.cuda.is_available()}") | |
| if torch.cuda.is_available(): | |
| print(f"CUDA version: {torch.version.cuda}") | |
| print(f"GPU count: {torch.cuda.device_count()}") | |
| for i in range(torch.cuda.device_count()): | |
| print(f"GPU {i}: {torch.cuda.get_device_name(i)}") | |
| # Test torch hub connectivity | |
| print("\n--- Testing model download capability ---") | |
| try: | |
| available_models = torch.hub.list("pytorch/vision", force_reload=False) | |
| print("Torch hub connectivity working") | |
| except Exception as e: | |
| print(f"Torch hub connectivity issue: {e}") | |
| def main(): | |
| """Main function to handle command-line execution.""" | |
| parser = argparse.ArgumentParser(description='Process dysarthric speech audio') | |
| parser.add_argument('--input', '-i', required=True, help='Input audio file path') | |
| parser.add_argument('--output', '-o', required=True, help='Output audio file path') | |
| parser.add_argument('--verbose', '-v', action='store_true', help='Verbose output') | |
| parser.add_argument('--test-env', action='store_true', help='Test environment only') | |
| args = parser.parse_args() | |
| print("DYSARTHRIC VOICE CONVERSION - AUDIO PROCESSOR") | |
| print("=" * 70) | |
| if args.test_env: | |
| test_environment() | |
| return | |
| # Validate input file | |
| if not os.path.exists(args.input): | |
| print(f"Error: Input file does not exist: {args.input}") | |
| sys.exit(1) | |
| print(f"Input file: {args.input}") | |
| print(f"Output file: {args.output}") | |
| try: | |
| # Test environment first if verbose | |
| if args.verbose: | |
| test_environment() | |
| # Load models | |
| models = load_models() | |
| if None in models: | |
| print("Failed to load models. Exiting...") | |
| sys.exit(1) | |
| # Process audio | |
| success = process_audio(args.input, args.output, models) | |
| if success: | |
| print("\n" + "=" * 70) | |
| print("PROCESSING COMPLETED SUCCESSFULLY!") | |
| print(f"Output saved to: {args.output}") | |
| sys.exit(0) | |
| else: | |
| print("\n" + "=" * 70) | |
| print("PROCESSING FAILED!") | |
| sys.exit(1) | |
| except KeyboardInterrupt: | |
| print("\nProcessing interrupted by user") | |
| sys.exit(1) | |
| except Exception as e: | |
| print(f"\nUnexpected error: {e}") | |
| traceback.print_exc() | |
| sys.exit(1) | |
| if __name__ == "__main__": | |
| main() |