# app.py - Ultra-Safe Debugging Version import os import sys import traceback import tempfile import warnings warnings.filterwarnings('ignore') print("๐ Starting ULTRA-SAFE mode...") print(f"Python: {sys.version}") # Safe imports with individual error handling IMPORTS = { 'torch': False, 'numpy': False, 'PIL': False, 'gradio': False, 'soundfile': False, 'transformers': False } try: import torch IMPORTS['torch'] = True print("โ PyTorch imported") except Exception as e: print(f"โ PyTorch failed: {e}") try: import numpy as np IMPORTS['numpy'] = True print("โ NumPy imported") except Exception as e: print(f"โ NumPy failed: {e}") try: from PIL import Image IMPORTS['PIL'] = True print("โ PIL imported") except Exception as e: print(f"โ PIL failed: {e}") try: import gradio as gr IMPORTS['gradio'] = True print("โ Gradio imported") except Exception as e: print(f"โ Gradio failed: {e}") try: import soundfile as sf IMPORTS['soundfile'] = True print("โ SoundFile imported") except Exception as e: print(f"โ SoundFile failed: {e}") # Only try transformers if basic imports work if IMPORTS['torch']: try: from transformers import BlipProcessor, BlipForConditionalGeneration from transformers import MusicgenForConditionalGeneration, AutoProcessor IMPORTS['transformers'] = True print("โ Transformers imported") except Exception as e: print(f"โ Transformers failed: {e}") class SafeGenerator: def __init__(self): print("๐ง Initializing Safe Generator...") self.working = True def safe_string_test(self, input_val): """Test string operations safely""" print(f"๐งช Testing string operations with: {input_val} (type: {type(input_val)})") try: # Convert to string safely if input_val is None: str_val = "none" elif isinstance(input_val, str): str_val = input_val elif isinstance(input_val, (int, float, bool)): str_val = str(input_val) else: str_val = repr(input_val) print(f"โ String conversion: '{str_val}'") # Test lower operation lower_val = str_val.lower() print(f"โ Lower operation: '{lower_val}'") # Test 'in' operation with known string test_keywords = ['test', 'image', 'bright'] results = [] for keyword in test_keywords: try: result = keyword in lower_val results.append(f"{keyword}: {result}") print(f"โ '{keyword}' in '{lower_val}': {result}") except Exception as e: error_msg = f"โ Error with '{keyword}': {e}" results.append(error_msg) print(error_msg) return f"String test passed. Results: {', '.join(results)}" except Exception as e: error_msg = f"โ String test failed: {e}\n{traceback.format_exc()}" print(error_msg) return error_msg def create_simple_description(self, image): """Create description without any AI models""" try: if not IMPORTS['numpy'] or not IMPORTS['PIL']: return "simple image", "simple image, ambient music" print("๐ Creating simple description...") # Basic image analysis img_array = np.array(image) h, w, c = img_array.shape print(f"๐ Image dimensions: {w}x{h}x{c}") # Safe color analysis try: mean_color = np.mean(img_array, axis=(0, 1)) brightness = float(np.mean(mean_color)) print(f"๐ก Brightness: {brightness}") # Safe brightness categorization if brightness > 200: brightness_desc = "bright" elif brightness < 100: brightness_desc = "dark" else: brightness_desc = "medium" print(f"๐ท๏ธ Brightness category: {brightness_desc}") except Exception as e: print(f"โ ๏ธ Color analysis failed: {e}") brightness_desc = "colorful" # Build description safely base_desc = f"{brightness_desc} image" enhanced_desc = f"{base_desc}, peaceful music" print(f"๐ Description: '{base_desc}' -> '{enhanced_desc}'") # Test the strings before returning test_result = self.safe_string_test(base_desc) print(f"๐งช String test result: {test_result}") return base_desc, enhanced_desc except Exception as e: error_msg = f"โ Description creation failed: {e}\n{traceback.format_exc()}" print(error_msg) return "error image", "error image, quiet music" def create_simple_audio(self, duration=10): """Create simple audio without AI""" try: if not IMPORTS['numpy']: print("โ NumPy not available for audio") return None, None print(f"๐ต Creating {duration}s simple audio...") # Create simple tone sample_rate = 22050 t = np.linspace(0, duration, int(duration * sample_rate)) # Simple pleasant tone (C major chord) freq1, freq2, freq3 = 261.63, 329.63, 392.00 # C, E, G audio = (np.sin(2 * np.pi * freq1 * t) * 0.3 + np.sin(2 * np.pi * freq2 * t) * 0.2 + np.sin(2 * np.pi * freq3 * t) * 0.2) # Add fade in/out fade_samples = int(0.5 * sample_rate) # 0.5 second fade audio[:fade_samples] *= np.linspace(0, 1, fade_samples) audio[-fade_samples:] *= np.linspace(1, 0, fade_samples) print(f"โ Audio created: {len(audio)} samples at {sample_rate}Hz") return audio.astype(np.float32), sample_rate except Exception as e: print(f"โ Audio creation failed: {e}") return None, None def process_image_safe(self, image): """Ultra-safe image processing""" print("๐ Starting SAFE image processing...") if image is None: return None, "โ No image provided", None, None try: # Step 1: Test the image print("๐ธ Step 1: Testing image...") img_info = f"Image type: {type(image)}" if hasattr(image, 'size'): img_info += f", Size: {image.size}" print(img_info) # Step 2: Create description print("๐ Step 2: Creating description...") description, music_prompt = self.create_simple_description(image) # Step 3: Test strings print("๐งช Step 3: Testing strings...") desc_test = self.safe_string_test(description) prompt_test = self.safe_string_test(music_prompt) # Step 4: Create audio print("๐ต Step 4: Creating audio...") audio_data, sample_rate = self.create_simple_audio(10) # Step 5: Save audio if successful audio_file = None if audio_data is not None and IMPORTS['soundfile']: try: print("๐พ Step 5: Saving audio...") with tempfile.NamedTemporaryFile(suffix='.wav', delete=False) as f: sf.write(f.name, audio_data, sample_rate) audio_file = f.name print(f"โ Audio saved: {audio_file}") except Exception as e: print(f"โ ๏ธ Audio save failed: {e}") # Prepare results status_msg = f""" **โ SAFE MODE PROCESSING COMPLETE** **Image Analysis:** - {img_info} **Generated Text:** - Description: "{description}" - Music Prompt: "{music_prompt}" **String Tests:** - Description test: {desc_test[:100]}... - Prompt test: {prompt_test[:100]}... **Audio:** - Status: {'โ Created' if audio_data is not None else 'โ Failed'} - Duration: {len(audio_data)/sample_rate:.1f}s if audio_data else 'N/A' **System Status:** - PyTorch: {'โ ' if IMPORTS['torch'] else 'โ'} - NumPy: {'โ ' if IMPORTS['numpy'] else 'โ'} - PIL: {'โ ' if IMPORTS['PIL'] else 'โ'} - SoundFile: {'โ ' if IMPORTS['soundfile'] else 'โ'} - Transformers: {'โ ' if IMPORTS['transformers'] else 'โ'} """ audio_output = (sample_rate, audio_data) if audio_data is not None else None print("โ Safe processing completed successfully!") return None, status_msg, audio_output, audio_file except Exception as e: error_msg = f""" โ **SAFE MODE ERROR** **Error:** {str(e)} **Location:** {traceback.format_exc()} **System Info:** - Python: {sys.version} - Working directory: {os.getcwd()} - Environment: {dict(os.environ).get('SPACE_ID', 'Local')} **Import Status:** {chr(10).join([f"- {k}: {'โ ' if v else 'โ'}" for k, v in IMPORTS.items()])} """ print(error_msg) return None, error_msg, None, None # Initialize generator print("๐ฌ Initializing generator...") try: generator = SafeGenerator() print("โ Generator ready!") except Exception as e: print(f"โ Generator failed: {e}") generator = None def create_minimal_interface(): """Create minimal interface for debugging""" if not IMPORTS['gradio']: print("โ Cannot create interface - Gradio not available") return None print("๐ฅ๏ธ Creating minimal interface...") with gr.Blocks(title="๐งช Ultra-Safe Debug Mode") as demo: gr.HTML("""
This version isolates and tests each component individually