File size: 15,089 Bytes
60ec455
f5c2853
814d260
 
60ec455
f5c2853
 
 
 
60ec455
 
 
 
 
 
 
 
 
 
 
 
814d260
60ec455
 
 
 
 
 
814d260
28fc925
60ec455
 
 
814d260
60ec455
28fc925
814d260
60ec455
 
 
814d260
60ec455
f5c2853
814d260
60ec455
 
 
814d260
60ec455
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
814d260
60ec455
f5c2853
60ec455
 
f5c2853
60ec455
 
 
f5c2853
814d260
60ec455
 
 
 
 
 
 
814d260
60ec455
e128d93
60ec455
e128d93
60ec455
 
 
e128d93
60ec455
 
 
e128d93
60ec455
 
 
 
 
 
 
 
 
e128d93
60ec455
e128d93
 
60ec455
 
 
814d260
60ec455
 
814d260
60ec455
 
e128d93
60ec455
e128d93
60ec455
 
 
 
e128d93
60ec455
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
e128d93
60ec455
 
 
e128d93
60ec455
814d260
60ec455
 
 
e128d93
60ec455
e128d93
814d260
60ec455
 
 
814d260
60ec455
 
814d260
60ec455
 
 
f5c2853
60ec455
f5c2853
60ec455
 
 
f5c2853
60ec455
 
 
 
 
814d260
60ec455
 
 
 
f5c2853
60ec455
 
f5c2853
28fc925
60ec455
 
f5c2853
60ec455
 
 
 
f5c2853
60ec455
f5c2853
 
60ec455
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
814d260
60ec455
 
 
 
 
814d260
60ec455
f5c2853
60ec455
814d260
60ec455
 
 
 
814d260
60ec455
 
 
814d260
60ec455
 
 
814d260
60ec455
 
 
 
 
 
 
 
 
 
814d260
28fc925
60ec455
 
 
 
f5c2853
 
60ec455
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
28fc925
f5c2853
60ec455
 
814d260
60ec455
 
814d260
60ec455
814d260
f5c2853
60ec455
 
814d260
60ec455
 
 
814d260
60ec455
e128d93
60ec455
f5c2853
 
60ec455
 
 
f5c2853
 
 
60ec455
 
 
 
 
 
 
 
 
814d260
28fc925
e128d93
60ec455
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
e128d93
 
 
 
60ec455
e128d93
60ec455
 
 
e128d93
 
 
 
60ec455
 
e128d93
f5c2853
e128d93
60ec455
 
 
 
 
 
 
 
 
f5c2853
 
60ec455
 
 
 
 
 
 
f5c2853
 
 
 
 
814d260
f5c2853
60ec455
 
814d260
60ec455
 
 
 
 
 
 
 
 
814d260
60ec455
 
f5c2853
60ec455
f5c2853
28fc925
f5c2853
 
814d260
60ec455
 
f5c2853
 
60ec455
f5c2853
28fc925
60ec455
 
 
 
28fc925
 
 
 
 
 
 
60ec455
28fc925
60ec455
28fc925
60ec455
 
 
 
 
 
28fc925
60ec455
 
 
 
 
28fc925
60ec455
f5c2853
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
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
# 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.
"""