File size: 15,464 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 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 | 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 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 | import os
import subprocess
import shutil
import tempfile
import time
import uuid
import sys
from pathlib import Path
import json
import traceback
class NotebookProcessor:
def __init__(self, notebook_path, temp_output_dir):
# Convert to absolute paths relative to current file
if not os.path.isabs(notebook_path):
notebook_path = os.path.join(os.path.dirname(__file__), notebook_path)
if not os.path.isabs(temp_output_dir):
temp_output_dir = os.path.join(os.path.dirname(__file__), temp_output_dir)
self.notebook_path = notebook_path
self.temp_output_dir = temp_output_dir
self.audio_processor_script = os.path.join(os.path.dirname(__file__), "audio_processor.py")
# Ensure temp output directory exists
os.makedirs(self.temp_output_dir, exist_ok=True)
# Debug: Check if required components exist
self._debug_setup()
def _debug_setup(self):
"""Debug initial setup and log what's available."""
print("=== NOTEBOOK PROCESSOR DEBUG SETUP ===")
print(f"Notebook path: {self.notebook_path}")
print(f"Notebook exists: {os.path.exists(self.notebook_path)}")
print(f"Audio processor script: {self.audio_processor_script}")
print(f"Audio processor exists: {os.path.exists(self.audio_processor_script)}")
print(f"Temp output dir: {self.temp_output_dir}")
print(f"Current working directory: {os.getcwd()}")
# Check if required packages are installed
self._check_dependencies()
print("=" * 50)
def _check_dependencies(self):
"""Check if required packages are installed."""
print("\n--- Checking Dependencies ---")
try:
import nbconvert
print(f"β
nbconvert version: {nbconvert.__version__}")
except ImportError:
print("β nbconvert not installed!")
try:
import nbformat
print(f"β
nbformat version: {nbformat.__version__}")
except ImportError:
print("β nbformat not installed!")
try:
result = subprocess.run(['jupyter', '--version'], capture_output=True, text=True, timeout=10)
if result.returncode == 0:
print("β
Jupyter installed")
print(f" Jupyter output: {result.stdout.strip()}")
else:
print("β Jupyter command failed")
except Exception as e:
print(f"β Jupyter error: {e}")
try:
import torch
print(f"β
PyTorch version: {torch.__version__}")
print(f" CUDA available: {torch.cuda.is_available()}")
except ImportError:
print("β PyTorch not installed!")
def process_audio_file(self, input_audio_path, progress_callback=None):
"""Process audio file with proper path handling."""
print(f"\n=== PROCESSING AUDIO FILE ===")
print(f"Input file: {input_audio_path}")
print(f"File exists: {os.path.exists(input_audio_path)}")
try:
if progress_callback:
progress_callback(0.1, "Setting up processing environment...")
# Generate unique output filename
unique_id = str(uuid.uuid4())[:8]
output_filename = f"processed_output_{unique_id}.wav"
output_path = os.path.join(self.temp_output_dir, output_filename)
print(f"Expected output path: {output_path}")
# Copy input file to temp location for processing
temp_input_path = os.path.join(self.temp_output_dir, f"input_{unique_id}.wav")
print(f"Copying input to: {temp_input_path}")
shutil.copy2(input_audio_path, temp_input_path)
if not os.path.exists(temp_input_path):
print("β Failed to copy input file!")
return None
print(f"β
Input file copied successfully")
if progress_callback:
progress_callback(0.2, "Choosing processing method...")
success = False
# Method 1: Try standalone script (most reliable)
print("\n--- Attempting Method 1: Standalone Script ---")
if os.path.exists(self.audio_processor_script):
if progress_callback:
progress_callback(0.3, "Using standalone audio processor...")
success = self._process_with_script(temp_input_path, output_path, progress_callback)
print(f"Script method result: {success}")
else:
print("β Audio processor script not found")
# Method 2: Try notebook execution if script fails and notebook exists
if not success and os.path.exists(self.notebook_path):
print("\n--- Attempting Method 2: Notebook Execution ---")
if progress_callback:
progress_callback(0.3, "Executing Jupyter notebook...")
success = self._process_with_notebook(temp_input_path, output_path, progress_callback)
print(f"Notebook method result: {success}")
else:
if not os.path.exists(self.notebook_path):
print("β Notebook file not found")
# Method 3: Debug fallback (remove this in production)
if not success:
print("\n--- Attempting Method 3: Debug Fallback ---")
success = self._create_debug_output(temp_input_path, output_path, progress_callback)
print(f"Debug fallback result: {success}")
# Clean up temp input
if os.path.exists(temp_input_path):
os.remove(temp_input_path)
print("β
Cleaned up temp input file")
if progress_callback:
progress_callback(1.0, "Processing complete!" if success else "Processing failed!")
final_result = output_path if (success and os.path.exists(output_path)) else None
print(f"Final result: {final_result}")
print("=" * 50)
return final_result
except Exception as e:
print(f"β Error in notebook processor: {e}")
traceback.print_exc()
if progress_callback:
progress_callback(1.0, f"Error: {str(e)}")
return None
def _process_with_script(self, input_path, output_path, progress_callback=None):
"""Process using standalone Python script."""
try:
print(f"Running script: {self.audio_processor_script}")
print(f"Input: {input_path}")
print(f"Output: {output_path}")
if progress_callback:
progress_callback(0.4, "Loading neural models...")
# Use proper cross-platform paths
cmd = [
sys.executable,
self.audio_processor_script,
'--input', input_path,
'--output', output_path,
'--verbose'
]
print(f"Command: {' '.join(cmd)}")
if progress_callback:
progress_callback(0.5, "Running neural processing pipeline...")
# Run with timeout
result = subprocess.run(
cmd,
capture_output=True,
text=True,
timeout=300,
cwd=os.path.dirname(self.audio_processor_script)
)
print(f"Script return code: {result.returncode}")
print(f"Script stdout: {result.stdout}")
print(f"Script stderr: {result.stderr}")
if progress_callback:
progress_callback(0.8, "Finalizing audio synthesis...")
if result.returncode == 0:
if os.path.exists(output_path):
print(f"β
Script executed successfully, output: {output_path}")
return True
else:
print(f"β Script ran but output file not found")
return False
else:
print(f"β Script execution failed: {result.stderr}")
return False
except subprocess.TimeoutExpired:
print("β Script execution timeout")
if progress_callback:
progress_callback(1.0, "Processing timeout")
return False
except Exception as e:
print(f"β Error executing script: {e}")
traceback.print_exc()
return False
def _process_with_notebook(self, input_path, output_path, progress_callback=None):
"""Process using Jupyter notebook execution."""
try:
print(f"Processing with notebook: {self.notebook_path}")
if progress_callback:
progress_callback(0.4, "Preparing notebook execution...")
# Create modified notebook
modified_notebook_path = self._create_modified_notebook(input_path, output_path)
if not modified_notebook_path:
print("β Failed to create modified notebook")
return False
if progress_callback:
progress_callback(0.5, "Executing notebook cells...")
# Try to execute the notebook
success = self._execute_with_nbconvert(modified_notebook_path)
# Clean up
if os.path.exists(modified_notebook_path):
os.remove(modified_notebook_path)
if progress_callback:
progress_callback(0.8, "Processing notebook output...")
if success and os.path.exists(output_path):
print(f"β
Notebook executed successfully")
return True
else:
print(f"β Notebook execution failed")
return False
except Exception as e:
print(f"β Error executing notebook: {e}")
traceback.print_exc()
return False
def _create_modified_notebook(self, input_path, output_path):
"""Create a modified version of the notebook for processing."""
try:
with open(self.notebook_path, 'r', encoding='utf-8') as f:
notebook_content = json.load(f)
# Modify cells to use our paths and ensure CPU compatibility
modified_cells = 0
for cell in notebook_content.get('cells', []):
if cell.get('cell_type') == 'code':
source = cell.get('source', [])
if isinstance(source, list):
source = ''.join(source)
original_source = source
# Replace file paths
source = source.replace(
'r"C:\\Users\\beyon\\Downloads\\LJ001-0005.wav"',
f'r"{input_path}"'
)
source = source.replace(
'"C:\\Users\\beyon\\Downloads\\LJ001-0005.wav"',
f'"{input_path}"'
)
# Make CPU-safe by adding map_location
if 'torch.hub.load(' in source and 'map_location' not in source:
# Add CPU safety to model loading
source = source.replace(
'trust_repo=True).cuda()',
'trust_repo=True, map_location="cuda" if torch.cuda.is_available() else "cpu")'
)
source = source.replace(
'.cuda()',
'.cuda() if torch.cuda.is_available() else model'
)
modified_cells += 1
# Add output saving
if 'target = hifigan(mel)' in source:
source += f'\n\n# Save output\ntorchaudio.save(r"{output_path}", target.squeeze().cpu(), 16000)\nprint("Processing completed successfully!")'
modified_cells += 1
if source != original_source:
modified_cells += 1
# Update cell
cell['source'] = source.split('\n') if '\n' in source else [source]
print(f"Modified {modified_cells} cells for CPU compatibility")
# Save modified notebook
modified_path = os.path.join(self.temp_output_dir, f"modified_{uuid.uuid4().hex[:8]}.ipynb")
with open(modified_path, 'w', encoding='utf-8') as f:
json.dump(notebook_content, f, indent=2)
return modified_path
except Exception as e:
print(f"β Error creating modified notebook: {e}")
return None
def _execute_with_nbconvert(self, notebook_path):
"""Execute notebook using nbconvert."""
try:
cmd = [
'jupyter', 'nbconvert',
'--to', 'notebook',
'--execute',
'--output', notebook_path,
notebook_path
]
result = subprocess.run(cmd, capture_output=True, text=True, timeout=300)
print(f"NBConvert return code: {result.returncode}")
if result.returncode != 0:
print(f"NBConvert stderr: {result.stderr}")
return result.returncode == 0
except Exception as e:
print(f"β NBConvert error: {e}")
return False
def _create_debug_output(self, input_path, output_path, progress_callback=None):
"""Create debug output by copying input (fallback for testing only)."""
try:
print("Creating debug output (copying input as output)")
if progress_callback:
progress_callback(0.7, "Creating debug output...")
shutil.copy2(input_path, output_path)
if os.path.exists(output_path):
print(f"β
Debug output created: {output_path}")
return True
else:
print(f"β Failed to create debug output")
return False
except Exception as e:
print(f"β Error creating debug output: {e}")
return False |