# 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("""

๐Ÿงช ULTRA-SAFE DEBUG MODE

This version isolates and tests each component individually

""") # System status status_html = f"""

๐Ÿ”ง Import Status

""" gr.HTML(status_html) with gr.Tabs(): # Tab 1: Basic String Test with gr.TabItem("๐Ÿงช String Test"): with gr.Row(): test_input = gr.Textbox( value="bright colorful sunset image", label="Test String Input" ) test_btn = gr.Button("Test String Operations") test_output = gr.Textbox( label="Test Results", lines=10 ) if generator: test_btn.click( fn=generator.safe_string_test, inputs=[test_input], outputs=[test_output] ) # Tab 2: Image Processing Test with gr.TabItem("๐Ÿ“ธ Image Test"): with gr.Row(): with gr.Column(): image_input = gr.Image( type="pil", label="Upload Test Image" ) process_btn = gr.Button( "๐Ÿ”„ Process Image (Safe Mode)", variant="primary" ) with gr.Column(): status_output = gr.Markdown( value="Upload an image and click process", label="Processing Results" ) with gr.Row(): audio_output = gr.Audio(label="Generated Audio") file_output = gr.File(label="Audio File") if generator: process_btn.click( fn=generator.process_image_safe, inputs=[image_input], outputs=[gr.Video(visible=False), status_output, audio_output, file_output] ) gr.HTML("""

๐ŸŽฏ Debug Instructions

  1. String Test: Test if string operations work correctly
  2. Image Test: Upload an image to see where the error occurs
  3. Check Results: Look for the exact error location in the output
""") return demo # Launch if __name__ == "__main__": print("๐Ÿš€ Launching debug interface...") try: demo = create_minimal_interface() if demo is not None: demo.launch( server_name="0.0.0.0", server_port=7860, share=True ) else: print("โŒ Could not create interface") except Exception as e: print(f"โŒ Launch failed: {e}") print(traceback.format_exc()) # Minimal requirements.txt """ gradio==4.44.0 Pillow>=9.5.0 numpy>=1.24.0 soundfile>=0.12.0 torch>=2.0.0 transformers>=4.30.0 """ # Updated README.md """ --- title: Ultra-Safe Photo Soundtrack Debug emoji: ๐Ÿงช colorFrom: red colorTo: orange sdk: gradio sdk_version: "4.44.0" app_file: app.py pinned: false license: apache-2.0 --- # ๐Ÿงช Ultra-Safe Debug Mode This is a debugging version to isolate the "bool is not iterable" error. ## Features - โœ… Safe imports with individual error handling - โœ… Step-by-step processing with detailed logs - โœ… String operation testing - โœ… Fallbacks for every component - โœ… Detailed error reporting ## Debug Process 1. Upload to see import status 2. Test string operations 3. Process an image to find exact error location 4. Check detailed logs for the root cause This version will work even with missing dependencies and show exactly where errors occur. """