Mustafa-albakkar commited on
Commit
04325de
ยท
verified ยท
1 Parent(s): dc77e2e

Upload image_agent_v2_fixed.py

Browse files
Files changed (1) hide show
  1. image_agent_v2_fixed.py +745 -0
image_agent_v2_fixed.py ADDED
@@ -0,0 +1,745 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """
2
+ SPACE 2: Image Agent with Gradio Client Integration + Video Display
3
+ ===================================================
4
+ - Receives data from Space 1 via Gradio Client
5
+ - Generates images using Stable Diffusion
6
+ - Sends data to Space 3 via Gradio Client
7
+ - Receives and displays final video from Space 3
8
+ - Includes memory for video history
9
+ """
10
+ import os
11
+ import io
12
+ import json
13
+ import base64
14
+ import logging
15
+ import shutil
16
+ import gradio as gr
17
+ from typing import List, Dict, Any, Optional
18
+ from PIL import Image
19
+ import torch
20
+ from gradio_client import Client
21
+ from datetime import datetime
22
+ import pickle
23
+
24
+ logging.basicConfig(level=logging.INFO)
25
+ log = logging.getLogger("image_agent_space")
26
+
27
+
28
+ # ==================== Configuration ====================
29
+
30
+ HF_MODEL = os.getenv("HF_MODEL", "stabilityai/stable-diffusion-2-1")
31
+ DEVICE = "cuda" if torch.cuda.is_available() else "cpu"
32
+ IMAGE_SIZE = (1024, 576) # 16:9 aspect ratio
33
+
34
+ # Space URLs
35
+ TEXT_AGENT_URL = os.getenv("TEXT_AGENT_URL", "https://mustafa-albakkar-text_agent.hf.space")
36
+ VIDEO_AGENT_URL = os.getenv("VIDEO_AGENT_URL", "https://mustafa-albakkar-video_agent.hf.space")
37
+
38
+ # Memory file
39
+ MEMORY_FILE = "/tmp/video_memory.pkl"
40
+ VIDEO_STORAGE = "/tmp/videos"
41
+
42
+ # Create storage directory
43
+ os.makedirs(VIDEO_STORAGE, exist_ok=True)
44
+
45
+
46
+ # ==================== Memory Manager ====================
47
+
48
+ class VideoMemory:
49
+ """Manages video history and current video"""
50
+
51
+ def __init__(self):
52
+ self.current_video = None
53
+ self.current_thumbnail = None
54
+ self.history = []
55
+ self.load_memory()
56
+
57
+ def load_memory(self):
58
+ """Load memory from disk"""
59
+ try:
60
+ if os.path.exists(MEMORY_FILE):
61
+ with open(MEMORY_FILE, 'rb') as f:
62
+ data = pickle.load(f)
63
+ self.current_video = data.get('current_video')
64
+ self.current_thumbnail = data.get('current_thumbnail')
65
+ self.history = data.get('history', [])
66
+ log.info("โœ… Memory loaded")
67
+ except Exception as e:
68
+ log.error(f"Memory load failed: {e}")
69
+
70
+ def save_memory(self):
71
+ """Save memory to disk"""
72
+ try:
73
+ data = {
74
+ 'current_video': self.current_video,
75
+ 'current_thumbnail': self.current_thumbnail,
76
+ 'history': self.history
77
+ }
78
+ with open(MEMORY_FILE, 'wb') as f:
79
+ pickle.dump(data, f)
80
+ log.info("โœ… Memory saved")
81
+ except Exception as e:
82
+ log.error(f"Memory save failed: {e}")
83
+
84
+ def add_video(self, video_path: str, thumbnail_path: str = None, metadata: dict = None):
85
+ """Add new video to memory"""
86
+ # Copy to permanent storage
87
+ timestamp = datetime.now().strftime("%Y%m%d_%H%M%S")
88
+ stored_video = os.path.join(VIDEO_STORAGE, f"video_{timestamp}.mp4")
89
+ stored_thumbnail = None
90
+
91
+ try:
92
+ shutil.copy2(video_path, stored_video)
93
+ self.current_video = stored_video
94
+
95
+ if thumbnail_path and os.path.exists(thumbnail_path):
96
+ stored_thumbnail = os.path.join(VIDEO_STORAGE, f"thumb_{timestamp}.png")
97
+ shutil.copy2(thumbnail_path, stored_thumbnail)
98
+ self.current_thumbnail = stored_thumbnail
99
+
100
+ entry = {
101
+ 'video_path': stored_video,
102
+ 'thumbnail_path': stored_thumbnail,
103
+ 'timestamp': datetime.now().isoformat(),
104
+ 'metadata': metadata or {}
105
+ }
106
+ self.history.append(entry)
107
+
108
+ # Keep only last 10 videos
109
+ if len(self.history) > 10:
110
+ old_entry = self.history.pop(0)
111
+ # Clean up old files
112
+ try:
113
+ if old_entry['video_path'] and os.path.exists(old_entry['video_path']):
114
+ os.remove(old_entry['video_path'])
115
+ if old_entry.get('thumbnail_path') and os.path.exists(old_entry['thumbnail_path']):
116
+ os.remove(old_entry['thumbnail_path'])
117
+ except:
118
+ pass
119
+
120
+ self.save_memory()
121
+ log.info(f"โœ… Video saved to memory: {stored_video}")
122
+
123
+ except Exception as e:
124
+ log.error(f"Failed to add video to memory: {e}")
125
+
126
+ def get_current(self):
127
+ """Get current video and thumbnail"""
128
+ return self.current_video, self.current_thumbnail
129
+
130
+
131
+ # ==================== Image Generator ====================
132
+
133
+ class ImageGenerator:
134
+ """Image generation using Stable Diffusion"""
135
+
136
+ def __init__(self):
137
+ self.pipeline = None
138
+ self.device = DEVICE
139
+ log.info(f"Initializing on device: {self.device}")
140
+
141
+ try:
142
+ self._load_pipeline()
143
+ except Exception as e:
144
+ log.error(f"Failed to load pipeline: {e}")
145
+ self.pipeline = None
146
+
147
+ def _load_pipeline(self):
148
+ """Load Stable Diffusion pipeline"""
149
+ try:
150
+ from optimum.intel.openvino import OVDiffusionPipeline
151
+
152
+ openvino_models = [
153
+ "OpenVINO/stable-diffusion-2-1-int8-ov",
154
+ "OpenVINO/stable-diffusion-xl-base-1.0-int8-ov",
155
+ ]
156
+
157
+ for model in openvino_models:
158
+ try:
159
+ self.pipeline = OVDiffusionPipeline.from_pretrained(model)
160
+ log.info(f"โœ… Loaded OpenVINO model: {model}")
161
+ return
162
+ except:
163
+ continue
164
+
165
+ raise RuntimeError("No OpenVINO model available")
166
+
167
+ except Exception as e:
168
+ log.warning(f"OpenVINO failed: {e}")
169
+
170
+ from diffusers import StableDiffusionPipeline
171
+
172
+ pipeline_args = {}
173
+ if self.device == "cuda":
174
+ pipeline_args['torch_dtype'] = torch.float16
175
+
176
+ self.pipeline = StableDiffusionPipeline.from_pretrained(
177
+ HF_MODEL,
178
+ **pipeline_args
179
+ )
180
+ self.pipeline = self.pipeline.to(self.device)
181
+ log.info(f"โœ… Loaded Diffusers model: {HF_MODEL}")
182
+
183
+ def generate(self, prompt: str, scene_id: int) -> Dict[str, Any]:
184
+ """Generate image from prompt"""
185
+
186
+ if self.pipeline is None:
187
+ return {
188
+ "success": False,
189
+ "scene_id": scene_id,
190
+ "error": "Pipeline not initialized"
191
+ }
192
+
193
+ try:
194
+ log.info(f"Generating image for scene {scene_id}")
195
+ log.info(f"Prompt: {prompt[:100]}...")
196
+
197
+ result = self.pipeline(
198
+ prompt,
199
+ num_inference_steps=30,
200
+ guidance_scale=7.5,
201
+ height=IMAGE_SIZE[1],
202
+ width=IMAGE_SIZE[0]
203
+ )
204
+
205
+ if hasattr(result, 'nsfw_content_detected') and any(result.nsfw_content_detected):
206
+ return {
207
+ "success": False,
208
+ "scene_id": scene_id,
209
+ "error": "NSFW content detected"
210
+ }
211
+
212
+ if not hasattr(result, 'images') or not result.images:
213
+ return {
214
+ "success": False,
215
+ "scene_id": scene_id,
216
+ "error": "No image generated"
217
+ }
218
+
219
+ image = result.images[0]
220
+
221
+ if image.mode != 'RGB':
222
+ image = image.convert('RGB')
223
+
224
+ buffered = io.BytesIO()
225
+ image.save(buffered, format="PNG")
226
+ img_base64 = base64.b64encode(buffered.getvalue()).decode('utf-8')
227
+
228
+ log.info(f"โœ… Image generated for scene {scene_id}")
229
+
230
+ return {
231
+ "success": True,
232
+ "scene_id": scene_id,
233
+ "image_base64": img_base64,
234
+ "image": image
235
+ }
236
+
237
+ except Exception as e:
238
+ log.error(f"Generation failed for scene {scene_id}: {e}")
239
+ import traceback
240
+ traceback.print_exc()
241
+
242
+ return {
243
+ "success": False,
244
+ "scene_id": scene_id,
245
+ "error": str(e)
246
+ }
247
+
248
+
249
+ # ==================== Gradio Client Integration ====================
250
+
251
+ class SpaceConnector:
252
+ """Connects to other spaces via Gradio Client"""
253
+
254
+ def __init__(self):
255
+ self.text_agent = None
256
+ self.video_agent = None
257
+
258
+ # Connect to Text Agent
259
+ if TEXT_AGENT_URL:
260
+ try:
261
+ log.info(f"Connecting to Text Agent: {TEXT_AGENT_URL}")
262
+ self.text_agent = Client(TEXT_AGENT_URL)
263
+ log.info("โœ… Text Agent connected")
264
+ except Exception as e:
265
+ log.error(f"Text Agent connection failed: {e}")
266
+
267
+ # Connect to Video Agent
268
+ if VIDEO_AGENT_URL:
269
+ try:
270
+ log.info(f"Connecting to Video Agent: {VIDEO_AGENT_URL}")
271
+ self.video_agent = Client(VIDEO_AGENT_URL)
272
+ log.info("โœ… Video Agent connected")
273
+ except Exception as e:
274
+ log.error(f"Video Agent connection failed: {e}")
275
+
276
+ def get_scenes_from_text_agent(
277
+ self,
278
+ text: str,
279
+ language: str = "ar",
280
+ visual_style: str = "",
281
+ target_duration: int = 15
282
+ ) -> Optional[Dict]:
283
+ """Call Text Agent to get scenes"""
284
+
285
+ if not self.text_agent:
286
+ log.error("Text Agent not connected")
287
+ return None
288
+
289
+ try:
290
+ log.info("Calling Text Agent...")
291
+
292
+ result = self.text_agent.predict(
293
+ text=text,
294
+ language=language,
295
+ visual_style=visual_style,
296
+ target_scene_duration=target_duration,
297
+ api_name="/process_text"
298
+ )
299
+
300
+ log.info("โœ… Received scenes from Text Agent")
301
+ return result
302
+
303
+ except Exception as e:
304
+ log.error(f"Text Agent call failed: {e}")
305
+ return None
306
+
307
+ def send_to_video_agent(self, scenes_data: Dict) -> Optional[str]:
308
+ """Send processed scenes to Video Agent"""
309
+
310
+ if not self.video_agent:
311
+ log.error("Video Agent not connected")
312
+ return None
313
+
314
+ try:
315
+ log.info("Calling Video Agent...")
316
+
317
+ result = self.video_agent.predict(
318
+ scenes_json=json.dumps(scenes_data),
319
+ api_name="/create_video_api"
320
+ )
321
+
322
+ log.info("โœ… Video Agent response received")
323
+ return result
324
+
325
+ except Exception as e:
326
+ log.error(f"Video Agent call failed: {e}")
327
+ return None
328
+
329
+
330
+ # ==================== Global Instances ====================
331
+
332
+ image_generator = ImageGenerator()
333
+ space_connector = SpaceConnector()
334
+ video_memory = VideoMemory()
335
+
336
+
337
+ # ==================== Gradio Functions ====================
338
+
339
+ def receive_video_from_space3(video_path: str, thumbnail_path: str = None):
340
+ """API endpoint for Space 3 to send video back"""
341
+ try:
342
+ if video_path and os.path.exists(video_path):
343
+ video_memory.add_video(video_path, thumbnail_path)
344
+ return {"success": True, "message": "Video received and saved"}
345
+ else:
346
+ return {"success": False, "message": "Video path invalid"}
347
+ except Exception as e:
348
+ log.error(f"Failed to receive video: {e}")
349
+ return {"success": False, "message": str(e)}
350
+
351
+
352
+ def process_full_pipeline(
353
+ text: str,
354
+ language: str,
355
+ visual_style: str,
356
+ target_duration: int,
357
+ auto_send_to_video: bool
358
+ ) -> tuple:
359
+ """Complete pipeline: Text โ†’ Images โ†’ Video"""
360
+
361
+ if not text or len(text.strip()) < 100:
362
+ current_video, current_thumb = video_memory.get_current()
363
+ return None, None, current_video, current_thumb, "โŒ Text must be at least 100 characters"
364
+
365
+ try:
366
+ # Step 1: Get scenes from Text Agent
367
+ scenes_data = space_connector.get_scenes_from_text_agent(
368
+ text, language, visual_style, target_duration
369
+ )
370
+
371
+ if not scenes_data:
372
+ current_video, current_thumb = video_memory.get_current()
373
+ return None, None, current_video, current_thumb, "โŒ Failed to get scenes from Text Agent"
374
+
375
+ scenes = scenes_data.get("scenes", [])
376
+ visual_style = scenes_data.get("visual_style", visual_style)
377
+
378
+ if not scenes:
379
+ current_video, current_thumb = video_memory.get_current()
380
+ return None, None, current_video, current_thumb, "โŒ No scenes received"
381
+
382
+ log.info(f"Processing {len(scenes)} scenes...")
383
+
384
+ # Step 2: Generate images for each scene
385
+ results = []
386
+ gallery_images = []
387
+
388
+ for scene in scenes:
389
+ scene_id = scene.get("scene_id", 0)
390
+ visual_prompt = scene.get("visual_prompt", "")
391
+
392
+ if not visual_prompt:
393
+ continue
394
+
395
+ full_prompt = f"{visual_prompt}, {visual_style}"
396
+
397
+ result = image_generator.generate(full_prompt, scene_id)
398
+
399
+ if result["success"]:
400
+ # FIXED: Always use text_english for TTS (English voice)
401
+ english_text = scene.get("text_english", "")
402
+ if not english_text:
403
+ # Fallback to original text if translation missing
404
+ english_text = scene.get("text", "")
405
+
406
+ log.info(f"Scene {scene_id} - Using English text: {english_text[:50]}...")
407
+
408
+ results.append({
409
+ "scene_id": scene_id,
410
+ "text": english_text, # Send English translation to Video Agent
411
+ "image_base64": result["image_base64"],
412
+ "prompt": visual_prompt
413
+ })
414
+
415
+ gallery_images.append((result["image"], f"Scene {scene_id}"))
416
+ else:
417
+ log.error(f"Failed scene {scene_id}: {result.get('error')}")
418
+
419
+ # Step 3: Prepare output
420
+ output_json = {
421
+ "scenes": results,
422
+ "total_scenes": len(results),
423
+ "visual_style": visual_style,
424
+ "language": "en" # Always English for TTS
425
+ }
426
+
427
+ status_msg = f"""โœ… Image Generation Complete!
428
+
429
+ ๐Ÿ“Š **Results:**
430
+ - Total Scenes Processed: {len(scenes)}
431
+ - Images Generated: {len(results)}
432
+ - Failed: {len(scenes) - len(results)}
433
+ - Language: English (TTS ready)
434
+
435
+ ๐Ÿ“‹ **Images:**
436
+ """
437
+ for r in results:
438
+ status_msg += f"\n- Scene {r['scene_id']}: โœ… Generated (English text)"
439
+
440
+ # Step 4: Send to Video Agent
441
+ if auto_send_to_video and results:
442
+ status_msg += "\n\n๐ŸŽฌ Sending to Video Agent..."
443
+ video_result = space_connector.send_to_video_agent(output_json)
444
+
445
+ if video_result:
446
+ status_msg += "\n\nโœ… Video processing started in Space 3!"
447
+ status_msg += "\nโณ Video will appear here when ready (refresh to check)"
448
+ else:
449
+ status_msg += "\n\nโš ๏ธ Failed to start video generation"
450
+
451
+ # Return current video from memory
452
+ current_video, current_thumb = video_memory.get_current()
453
+
454
+ return (
455
+ json.dumps(output_json, indent=2),
456
+ gallery_images,
457
+ current_video,
458
+ current_thumb,
459
+ status_msg
460
+ )
461
+
462
+ except Exception as e:
463
+ log.error(f"Pipeline failed: {e}")
464
+ import traceback
465
+ traceback.print_exc()
466
+ current_video, current_thumb = video_memory.get_current()
467
+ return None, None, current_video, current_thumb, f"โŒ Error: {str(e)}"
468
+
469
+
470
+ def refresh_video_display():
471
+ """Refresh and display current video from memory"""
472
+ video_path, thumbnail_path = video_memory.get_current()
473
+
474
+ if video_path and os.path.exists(video_path):
475
+ return video_path, thumbnail_path, "โœ… Current video loaded from memory"
476
+ else:
477
+ return None, None, "โ„น๏ธ No video in memory yet"
478
+
479
+
480
+ def process_scenes_manual(scenes_json: str, visual_style: str) -> tuple:
481
+ """Process scenes from manual JSON input (legacy mode)"""
482
+
483
+ if not scenes_json or not scenes_json.strip():
484
+ return None, None, "โŒ Please provide scenes JSON"
485
+
486
+ try:
487
+ data = json.loads(scenes_json)
488
+
489
+ if "scenes" in data:
490
+ scenes = data["scenes"]
491
+ visual_style = data.get("visual_style", visual_style)
492
+ elif isinstance(data, list):
493
+ scenes = data
494
+ else:
495
+ return None, None, "โŒ Invalid JSON format"
496
+
497
+ if not scenes:
498
+ return None, None, "โŒ No scenes found in JSON"
499
+
500
+ log.info(f"Processing {len(scenes)} scenes...")
501
+
502
+ results = []
503
+ gallery_images = []
504
+
505
+ for scene in scenes:
506
+ scene_id = scene.get("scene_id", 0)
507
+ visual_prompt = scene.get("visual_prompt", "")
508
+
509
+ # FIXED: Always use text_english for TTS
510
+ english_text = scene.get("text_english", "")
511
+ if not english_text:
512
+ english_text = scene.get("text", "")
513
+
514
+ if not visual_prompt:
515
+ continue
516
+
517
+ full_prompt = f"{visual_prompt}, {visual_style}"
518
+
519
+ result = image_generator.generate(full_prompt, scene_id)
520
+
521
+ if result["success"]:
522
+ results.append({
523
+ "scene_id": scene_id,
524
+ "text": english_text, # Send English translation
525
+ "image_base64": result["image_base64"],
526
+ "prompt": visual_prompt
527
+ })
528
+
529
+ gallery_images.append((result["image"], f"Scene {scene_id}"))
530
+
531
+ output_json = {
532
+ "scenes": results,
533
+ "total_scenes": len(results),
534
+ "visual_style": visual_style,
535
+ "language": "en" # Always English
536
+ }
537
+
538
+ status_msg = f"""โœ… Image Generation Complete!
539
+
540
+ ๐Ÿ“Š **Results:**
541
+ - Images Generated: {len(results)}
542
+ - Language: English (TTS ready)
543
+
544
+ ๐Ÿ“‹ **Ready for Space 3 (Video Agent)**
545
+ """
546
+
547
+ return (
548
+ json.dumps(output_json, indent=2),
549
+ gallery_images,
550
+ status_msg
551
+ )
552
+
553
+ except Exception as e:
554
+ log.error(f"Processing failed: {e}")
555
+ return None, None, f"โŒ Error: {str(e)}"
556
+
557
+
558
+ # ==================== Gradio Interface ====================
559
+
560
+ text_agent_status = "โœ… Connected" if space_connector.text_agent else "โš ๏ธ Not Connected (set TEXT_AGENT_URL)"
561
+ video_agent_status = "โœ… Connected" if space_connector.video_agent else "โš ๏ธ Not Connected (set VIDEO_AGENT_URL)"
562
+
563
+ with gr.Blocks(title="Image Agent with Auto-Integration", theme=gr.themes.Soft()) as demo:
564
+
565
+ gr.Markdown("# ๐ŸŽจ Image Agent - Automated Pipeline with Video Display")
566
+ gr.Markdown("**Space 2/3** - Generates images with automatic integration and video display")
567
+
568
+ status_indicator = gr.Markdown(
569
+ f"**Device:** {DEVICE.upper()} | "
570
+ f"**Text Agent:** {text_agent_status} | "
571
+ f"**Video Agent:** {video_agent_status}"
572
+ )
573
+
574
+ gr.Markdown("---")
575
+
576
+ with gr.Tab("๐Ÿš€ Automated Pipeline"):
577
+ gr.Markdown("### Complete Flow: Text โ†’ Images โ†’ Video (with display)")
578
+ gr.Markdown("Enter text here and let the system handle everything!")
579
+
580
+ with gr.Row():
581
+ with gr.Column(scale=1):
582
+ text_input = gr.Textbox(
583
+ label="Input Text (Arabic or English)",
584
+ placeholder="ุฃุฏุฎู„ ู†ุตูƒ ู‡ู†ุง...",
585
+ lines=10
586
+ )
587
+
588
+ with gr.Row():
589
+ language_input = gr.Radio(
590
+ choices=["ar", "en"],
591
+ value="ar",
592
+ label="Input Language"
593
+ )
594
+
595
+ duration_input = gr.Slider(
596
+ minimum=10,
597
+ maximum=30,
598
+ value=15,
599
+ step=1,
600
+ label="Scene Duration (sec)"
601
+ )
602
+
603
+ style_input = gr.Textbox(
604
+ label="Visual Style",
605
+ value="cinematic, high quality, 4k",
606
+ lines=1
607
+ )
608
+
609
+ auto_video_checkbox = gr.Checkbox(
610
+ label="Auto-send to Video Agent (Space 3)",
611
+ value=True
612
+ )
613
+
614
+ process_btn = gr.Button("๐Ÿš€ Start Complete Pipeline", variant="primary", size="lg")
615
+
616
+ status_output = gr.Textbox(label="Status", lines=15)
617
+
618
+ with gr.Column(scale=1):
619
+ gallery_output = gr.Gallery(
620
+ label="Generated Images",
621
+ columns=2,
622
+ height=400
623
+ )
624
+
625
+ gr.Markdown("### ๐Ÿ“น Final Video from Space 3")
626
+
627
+ refresh_btn = gr.Button("๐Ÿ”„ Refresh Video Display", size="sm")
628
+
629
+ video_display = gr.Video(
630
+ label="Final Video",
631
+ height=300
632
+ )
633
+
634
+ thumbnail_display = gr.Image(
635
+ label="Thumbnail",
636
+ type="filepath",
637
+ height=200
638
+ )
639
+
640
+ json_output = gr.Code(
641
+ label="JSON Output (for manual transfer to Space 3)",
642
+ language="json",
643
+ lines=10
644
+ )
645
+
646
+ process_btn.click(
647
+ fn=process_full_pipeline,
648
+ inputs=[text_input, language_input, style_input, duration_input, auto_video_checkbox],
649
+ outputs=[json_output, gallery_output, video_display, thumbnail_display, status_output]
650
+ )
651
+
652
+ refresh_btn.click(
653
+ fn=refresh_video_display,
654
+ inputs=[],
655
+ outputs=[video_display, thumbnail_display, status_output]
656
+ )
657
+
658
+ with gr.Tab("๐Ÿ“‹ Manual Mode"):
659
+ gr.Markdown("### Process Scenes from JSON (Legacy)")
660
+
661
+ with gr.Row():
662
+ with gr.Column():
663
+ manual_scenes = gr.Code(
664
+ label="Scenes JSON (from Space 1)",
665
+ language="json",
666
+ lines=15
667
+ )
668
+
669
+ manual_style = gr.Textbox(
670
+ label="Visual Style Override",
671
+ value="cinematic, high quality"
672
+ )
673
+
674
+ manual_btn = gr.Button("๐ŸŽจ Generate Images")
675
+
676
+ manual_status = gr.Textbox(label="Status", lines=10)
677
+
678
+ with gr.Column():
679
+ manual_gallery = gr.Gallery(
680
+ label="Generated Images",
681
+ columns=2,
682
+ height=600
683
+ )
684
+
685
+ manual_output = gr.Code(
686
+ label="JSON Output",
687
+ language="json",
688
+ lines=10
689
+ )
690
+
691
+ manual_btn.click(
692
+ fn=process_scenes_manual,
693
+ inputs=[manual_scenes, manual_style],
694
+ outputs=[manual_output, manual_gallery, manual_status]
695
+ )
696
+
697
+ # API endpoint for Space 3 to send video back
698
+ with gr.Tab("๐Ÿ”Œ API Receiver"):
699
+ gr.Markdown("### API for Space 3 to send video back")
700
+ api_video_path = gr.Textbox(label="video_path")
701
+ api_thumb_path = gr.Textbox(label="thumbnail_path")
702
+ api_receive_btn = gr.Button("Receive Video")
703
+ api_result = gr.JSON(label="Result")
704
+
705
+ api_receive_btn.click(
706
+ fn=receive_video_from_space3,
707
+ inputs=[api_video_path, api_thumb_path],
708
+ outputs=api_result,
709
+ api_name="receive_video"
710
+ )
711
+
712
+ gr.Markdown("---")
713
+ gr.Markdown("""
714
+ ### ๐Ÿ”„ How It Works
715
+
716
+ **Automated Mode:**
717
+ 1. Enter Arabic or English text
718
+ 2. System calls Space 1 (Text Agent) to get scenes
719
+ 3. Generates images for all scenes
720
+ 4. **FIXED:** Always sends English translated text to Space 3
721
+ 5. Space 3 sends video back automatically
722
+ 6. Video is saved in memory for later viewing
723
+ 7. Use refresh button to reload video anytime
724
+
725
+ **Manual Mode:**
726
+ - Paste JSON from Space 1
727
+ - Generate images
728
+ - Copy JSON to Space 3
729
+
730
+ **Features:**
731
+ - โœ… Video display with persistent memory
732
+ - โœ… Refresh button to reload video anytime
733
+ - โœ… Automatic video reception from Space 3
734
+ - โœ… **FIXED:** English text now sent correctly to TTS
735
+
736
+ **Environment Variables (set in Space Secrets):**
737
+ - `TEXT_AGENT_URL` - Your Text Agent space
738
+ - `VIDEO_AGENT_URL` - Your Video Agent space
739
+ """)
740
+
741
+
742
+ if __name__ == "__main__":
743
+ PORT = int(os.getenv("PORT", "7860"))
744
+ log.info("Starting Image Agent Space with Auto-Integration and Video Display...")
745
+ demo.launch(server_name="0.0.0.0", server_port=PORT)