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