AxAva / app.py
citoreh's picture
Update app.py
60ec455 verified
# 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("""
<div style="text-align: center; background: #fff3cd; padding: 20px; border-radius: 10px; margin: 20px 0;">
<h1>πŸ§ͺ ULTRA-SAFE DEBUG MODE</h1>
<p><strong>This version isolates and tests each component individually</strong></p>
</div>
""")
# System status
status_html = f"""
<div style="background: #f8f9fa; padding: 15px; border-radius: 8px; margin: 10px 0;">
<h3>πŸ”§ Import Status</h3>
<ul>
{"".join([f"<li><strong>{k}:</strong> {'🟒 OK' if v else 'πŸ”΄ Failed'}</li>" for k, v in IMPORTS.items()])}
</ul>
</div>
"""
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("""
<div style="background: #e3f2fd; padding: 15px; border-radius: 8px; margin: 20px 0;">
<h3>🎯 Debug Instructions</h3>
<ol>
<li><strong>String Test:</strong> Test if string operations work correctly</li>
<li><strong>Image Test:</strong> Upload an image to see where the error occurs</li>
<li><strong>Check Results:</strong> Look for the exact error location in the output</li>
</ol>
</div>
""")
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.
"""