File size: 10,522 Bytes
426f1f2
 
 
d98cf2d
 
426f1f2
 
 
 
 
 
 
 
 
 
 
d98cf2d
426f1f2
 
 
 
 
d98cf2d
426f1f2
d98cf2d
 
426f1f2
 
 
 
 
 
 
 
 
d98cf2d
 
 
 
 
 
 
426f1f2
 
 
 
 
 
 
 
 
 
d98cf2d
 
 
 
 
 
 
426f1f2
 
 
 
 
 
 
 
 
 
d98cf2d
 
 
 
 
 
 
426f1f2
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
d98cf2d
426f1f2
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
d98cf2d
426f1f2
 
 
 
 
 
 
 
 
d98cf2d
426f1f2
 
 
 
 
 
 
 
 
 
 
d98cf2d
 
426f1f2
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
d98cf2d
426f1f2
 
 
 
 
d98cf2d
426f1f2
d98cf2d
426f1f2
 
 
 
 
d98cf2d
426f1f2
 
 
 
 
 
 
 
 
 
 
 
 
 
d98cf2d
426f1f2
 
d98cf2d
426f1f2
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
d98cf2d
426f1f2
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
d98cf2d
426f1f2
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
#!/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()