Spaces:
No application file
No application file
Delete app.py
Browse files
app.py
DELETED
|
@@ -1,784 +0,0 @@
|
|
| 1 |
-
"""
|
| 2 |
-
SPACE 2: Image Agent with Enhanced Prompting & English Text
|
| 3 |
-
===================================================
|
| 4 |
-
✅ Smart prompt engineering for beautiful, consistent images
|
| 5 |
-
✅ English text in thumbnails
|
| 6 |
-
✅ Automatic video reception from Space 3
|
| 7 |
-
"""
|
| 8 |
-
import os
|
| 9 |
-
import io
|
| 10 |
-
import json
|
| 11 |
-
import base64
|
| 12 |
-
import logging
|
| 13 |
-
import shutil
|
| 14 |
-
import gradio as gr
|
| 15 |
-
from typing import List, Dict, Any, Optional
|
| 16 |
-
from PIL import Image
|
| 17 |
-
import torch
|
| 18 |
-
from gradio_client import Client
|
| 19 |
-
from datetime import datetime
|
| 20 |
-
import pickle
|
| 21 |
-
|
| 22 |
-
logging.basicConfig(level=logging.INFO)
|
| 23 |
-
log = logging.getLogger("image_agent_space")
|
| 24 |
-
|
| 25 |
-
|
| 26 |
-
# ==================== Configuration ====================
|
| 27 |
-
|
| 28 |
-
HF_MODEL = os.getenv("HF_MODEL", "stabilityai/stable-diffusion-2-1")
|
| 29 |
-
DEVICE = "cuda" if torch.cuda.is_available() else "cpu"
|
| 30 |
-
IMAGE_SIZE = (1024, 576) # 16:9 aspect ratio
|
| 31 |
-
|
| 32 |
-
# Space URLs
|
| 33 |
-
TEXT_AGENT_URL = os.getenv("TEXT_AGENT_URL", "https://mustafa-albakkar-text_agent.hf.space")
|
| 34 |
-
VIDEO_AGENT_URL = os.getenv("VIDEO_AGENT_URL", "https://mustafa-albakkar-video_agent.hf.space")
|
| 35 |
-
|
| 36 |
-
# Memory file
|
| 37 |
-
MEMORY_FILE = "/tmp/video_memory.pkl"
|
| 38 |
-
VIDEO_STORAGE = "/tmp/videos"
|
| 39 |
-
|
| 40 |
-
# Create storage directory
|
| 41 |
-
os.makedirs(VIDEO_STORAGE, exist_ok=True)
|
| 42 |
-
|
| 43 |
-
|
| 44 |
-
# ==================== Smart Prompt Engineering ====================
|
| 45 |
-
|
| 46 |
-
class PromptEnhancer:
|
| 47 |
-
"""Enhances prompts for better, more consistent images"""
|
| 48 |
-
|
| 49 |
-
# Quality boosters
|
| 50 |
-
QUALITY_BOOSTERS = [
|
| 51 |
-
"high quality",
|
| 52 |
-
"detailed",
|
| 53 |
-
"professional",
|
| 54 |
-
"sharp focus",
|
| 55 |
-
"4k resolution",
|
| 56 |
-
"masterpiece"
|
| 57 |
-
]
|
| 58 |
-
|
| 59 |
-
# Lighting terms for consistency
|
| 60 |
-
LIGHTING_STYLES = {
|
| 61 |
-
"cinematic": "cinematic lighting, dramatic shadows, golden hour",
|
| 62 |
-
"soft": "soft diffused lighting, gentle shadows, natural light",
|
| 63 |
-
"dramatic": "dramatic lighting, high contrast, chiaroscuro",
|
| 64 |
-
"bright": "bright even lighting, well lit, studio lighting",
|
| 65 |
-
"mystical": "ethereal lighting, magical glow, ambient light"
|
| 66 |
-
}
|
| 67 |
-
|
| 68 |
-
# Negative prompts to avoid bad outputs
|
| 69 |
-
NEGATIVE_PROMPT = (
|
| 70 |
-
"ugly, blurry, low quality, distorted, deformed, "
|
| 71 |
-
"bad anatomy, worst quality, low res, jpeg artifacts, "
|
| 72 |
-
"watermark, text, signature, logo, username"
|
| 73 |
-
)
|
| 74 |
-
|
| 75 |
-
@staticmethod
|
| 76 |
-
def enhance_prompt(
|
| 77 |
-
base_prompt: str,
|
| 78 |
-
visual_style: str,
|
| 79 |
-
scene_number: int,
|
| 80 |
-
total_scenes: int,
|
| 81 |
-
context_text: str = "" # NEW: English text for more context
|
| 82 |
-
) -> tuple[str, str]:
|
| 83 |
-
"""
|
| 84 |
-
Enhance prompt for better quality and consistency
|
| 85 |
-
|
| 86 |
-
Args:
|
| 87 |
-
base_prompt: Base visual description
|
| 88 |
-
visual_style: User's visual style
|
| 89 |
-
scene_number: Current scene number
|
| 90 |
-
total_scenes: Total number of scenes
|
| 91 |
-
context_text: English text of the scene for additional context
|
| 92 |
-
|
| 93 |
-
Returns: (enhanced_positive_prompt, negative_prompt)
|
| 94 |
-
"""
|
| 95 |
-
|
| 96 |
-
# Clean the base prompt
|
| 97 |
-
prompt = base_prompt.strip()
|
| 98 |
-
|
| 99 |
-
# IMPORTANT: Ensure prompt is in English
|
| 100 |
-
# Check if prompt contains Arabic characters
|
| 101 |
-
has_arabic = any('\u0600' <= c <= '\u06FF' for c in prompt)
|
| 102 |
-
|
| 103 |
-
if has_arabic:
|
| 104 |
-
log.warning(f"⚠️ Scene {scene_number}: visual_prompt contains Arabic characters!")
|
| 105 |
-
log.warning(f" Original: {prompt[:50]}...")
|
| 106 |
-
# Don't use Arabic prompts - Stable Diffusion works best with English
|
| 107 |
-
# Use context_text as fallback
|
| 108 |
-
if context_text:
|
| 109 |
-
prompt = f"scene depicting: {context_text[:100]}"
|
| 110 |
-
log.info(f" Using English context instead: {prompt[:50]}...")
|
| 111 |
-
else:
|
| 112 |
-
prompt = "cinematic scene, detailed, professional"
|
| 113 |
-
log.warning(f" Using generic prompt as fallback")
|
| 114 |
-
|
| 115 |
-
# Add context from English text if available and not already detailed
|
| 116 |
-
if context_text and len(prompt.split()) < 10:
|
| 117 |
-
# Short prompt - enhance with context
|
| 118 |
-
prompt = f"{prompt}, depicting: {context_text[:80]}"
|
| 119 |
-
|
| 120 |
-
# Extract keywords for lighting style
|
| 121 |
-
style_lower = visual_style.lower()
|
| 122 |
-
lighting = ""
|
| 123 |
-
for key, light_style in PromptEnhancer.LIGHTING_STYLES.items():
|
| 124 |
-
if key in style_lower:
|
| 125 |
-
lighting = light_style
|
| 126 |
-
break
|
| 127 |
-
|
| 128 |
-
if not lighting:
|
| 129 |
-
lighting = PromptEnhancer.LIGHTING_STYLES["cinematic"] # default
|
| 130 |
-
|
| 131 |
-
# Build enhanced prompt
|
| 132 |
-
components = [
|
| 133 |
-
prompt, # Visual prompt (now guaranteed English)
|
| 134 |
-
lighting, # Consistent lighting
|
| 135 |
-
visual_style, # User's style
|
| 136 |
-
]
|
| 137 |
-
|
| 138 |
-
# Add quality terms (not all, just a few for consistency)
|
| 139 |
-
components.extend(PromptEnhancer.QUALITY_BOOSTERS[:3])
|
| 140 |
-
|
| 141 |
-
# Add framing hint for consistency
|
| 142 |
-
if scene_number == 1:
|
| 143 |
-
components.append("establishing shot, wide angle")
|
| 144 |
-
elif scene_number == total_scenes:
|
| 145 |
-
components.append("closing shot, thoughtful composition")
|
| 146 |
-
else:
|
| 147 |
-
components.append("medium shot, balanced composition")
|
| 148 |
-
|
| 149 |
-
# Join all components
|
| 150 |
-
enhanced_prompt = ", ".join(components)
|
| 151 |
-
|
| 152 |
-
# Log the enhancement
|
| 153 |
-
log.info(f"📸 Scene {scene_number} Enhanced Prompt: {enhanced_prompt[:100]}...")
|
| 154 |
-
|
| 155 |
-
return enhanced_prompt, PromptEnhancer.NEGATIVE_PROMPT
|
| 156 |
-
|
| 157 |
-
@staticmethod
|
| 158 |
-
def ensure_consistency(prompts: List[str], style: str) -> List[str]:
|
| 159 |
-
"""
|
| 160 |
-
Add consistency keywords across all prompts
|
| 161 |
-
"""
|
| 162 |
-
consistency_terms = f"consistent style, {style}, cohesive visual narrative"
|
| 163 |
-
|
| 164 |
-
enhanced = []
|
| 165 |
-
for prompt in prompts:
|
| 166 |
-
if consistency_terms not in prompt:
|
| 167 |
-
enhanced.append(f"{prompt}, {consistency_terms}")
|
| 168 |
-
else:
|
| 169 |
-
enhanced.append(prompt)
|
| 170 |
-
|
| 171 |
-
return enhanced
|
| 172 |
-
|
| 173 |
-
|
| 174 |
-
# ==================== Memory Manager ====================
|
| 175 |
-
|
| 176 |
-
class VideoMemory:
|
| 177 |
-
"""Manages video history and current video"""
|
| 178 |
-
|
| 179 |
-
def __init__(self):
|
| 180 |
-
self.current_video = None
|
| 181 |
-
self.current_thumbnail = None
|
| 182 |
-
self.history = []
|
| 183 |
-
self.load_memory()
|
| 184 |
-
|
| 185 |
-
def load_memory(self):
|
| 186 |
-
"""Load memory from disk"""
|
| 187 |
-
try:
|
| 188 |
-
if os.path.exists(MEMORY_FILE):
|
| 189 |
-
with open(MEMORY_FILE, 'rb') as f:
|
| 190 |
-
data = pickle.load(f)
|
| 191 |
-
self.current_video = data.get('current_video')
|
| 192 |
-
self.current_thumbnail = data.get('current_thumbnail')
|
| 193 |
-
self.history = data.get('history', [])
|
| 194 |
-
log.info("✅ Memory loaded")
|
| 195 |
-
except Exception as e:
|
| 196 |
-
log.error(f"Memory load failed: {e}")
|
| 197 |
-
|
| 198 |
-
def save_memory(self):
|
| 199 |
-
"""Save memory to disk"""
|
| 200 |
-
try:
|
| 201 |
-
data = {
|
| 202 |
-
'current_video': self.current_video,
|
| 203 |
-
'current_thumbnail': self.current_thumbnail,
|
| 204 |
-
'history': self.history
|
| 205 |
-
}
|
| 206 |
-
with open(MEMORY_FILE, 'wb') as f:
|
| 207 |
-
pickle.dump(data, f)
|
| 208 |
-
log.info("✅ Memory saved")
|
| 209 |
-
except Exception as e:
|
| 210 |
-
log.error(f"Memory save failed: {e}")
|
| 211 |
-
|
| 212 |
-
def add_video(self, video_path: str, thumbnail_path: str = None, metadata: dict = None):
|
| 213 |
-
"""Add new video to memory"""
|
| 214 |
-
timestamp = datetime.now().strftime("%Y%m%d_%H%M%S")
|
| 215 |
-
stored_video = os.path.join(VIDEO_STORAGE, f"video_{timestamp}.mp4")
|
| 216 |
-
stored_thumbnail = None
|
| 217 |
-
|
| 218 |
-
try:
|
| 219 |
-
shutil.copy2(video_path, stored_video)
|
| 220 |
-
self.current_video = stored_video
|
| 221 |
-
|
| 222 |
-
if thumbnail_path and os.path.exists(thumbnail_path):
|
| 223 |
-
stored_thumbnail = os.path.join(VIDEO_STORAGE, f"thumb_{timestamp}.png")
|
| 224 |
-
shutil.copy2(thumbnail_path, stored_thumbnail)
|
| 225 |
-
self.current_thumbnail = stored_thumbnail
|
| 226 |
-
|
| 227 |
-
entry = {
|
| 228 |
-
'video_path': stored_video,
|
| 229 |
-
'thumbnail_path': stored_thumbnail,
|
| 230 |
-
'timestamp': datetime.now().isoformat(),
|
| 231 |
-
'metadata': metadata or {}
|
| 232 |
-
}
|
| 233 |
-
self.history.append(entry)
|
| 234 |
-
|
| 235 |
-
if len(self.history) > 10:
|
| 236 |
-
old_entry = self.history.pop(0)
|
| 237 |
-
try:
|
| 238 |
-
if old_entry['video_path'] and os.path.exists(old_entry['video_path']):
|
| 239 |
-
os.remove(old_entry['video_path'])
|
| 240 |
-
if old_entry.get('thumbnail_path') and os.path.exists(old_entry['thumbnail_path']):
|
| 241 |
-
os.remove(old_entry['thumbnail_path'])
|
| 242 |
-
except:
|
| 243 |
-
pass
|
| 244 |
-
|
| 245 |
-
self.save_memory()
|
| 246 |
-
log.info(f"✅ Video saved to memory: {stored_video}")
|
| 247 |
-
|
| 248 |
-
except Exception as e:
|
| 249 |
-
log.error(f"Failed to add video to memory: {e}")
|
| 250 |
-
|
| 251 |
-
def get_current(self):
|
| 252 |
-
"""Get current video and thumbnail"""
|
| 253 |
-
return self.current_video, self.current_thumbnail
|
| 254 |
-
|
| 255 |
-
|
| 256 |
-
# ==================== Image Generator ====================
|
| 257 |
-
|
| 258 |
-
class ImageGenerator:
|
| 259 |
-
"""Image generation with smart prompt engineering"""
|
| 260 |
-
|
| 261 |
-
def __init__(self):
|
| 262 |
-
self.pipeline = None
|
| 263 |
-
self.device = DEVICE
|
| 264 |
-
self.prompt_enhancer = PromptEnhancer()
|
| 265 |
-
log.info(f"Initializing on device: {self.device}")
|
| 266 |
-
|
| 267 |
-
try:
|
| 268 |
-
self._load_pipeline()
|
| 269 |
-
except Exception as e:
|
| 270 |
-
log.error(f"Failed to load pipeline: {e}")
|
| 271 |
-
self.pipeline = None
|
| 272 |
-
|
| 273 |
-
def _load_pipeline(self):
|
| 274 |
-
"""Load Stable Diffusion pipeline"""
|
| 275 |
-
try:
|
| 276 |
-
from optimum.intel.openvino import OVDiffusionPipeline
|
| 277 |
-
|
| 278 |
-
openvino_models = [
|
| 279 |
-
"OpenVINO/stable-diffusion-2-1-int8-ov",
|
| 280 |
-
"OpenVINO/stable-diffusion-xl-base-1.0-int8-ov",
|
| 281 |
-
]
|
| 282 |
-
|
| 283 |
-
for model in openvino_models:
|
| 284 |
-
try:
|
| 285 |
-
self.pipeline = OVDiffusionPipeline.from_pretrained(model)
|
| 286 |
-
log.info(f"✅ Loaded OpenVINO model: {model}")
|
| 287 |
-
return
|
| 288 |
-
except:
|
| 289 |
-
continue
|
| 290 |
-
|
| 291 |
-
raise RuntimeError("No OpenVINO model available")
|
| 292 |
-
|
| 293 |
-
except Exception as e:
|
| 294 |
-
log.warning(f"OpenVINO failed: {e}")
|
| 295 |
-
|
| 296 |
-
from diffusers import StableDiffusionPipeline
|
| 297 |
-
|
| 298 |
-
pipeline_args = {}
|
| 299 |
-
if self.device == "cuda":
|
| 300 |
-
pipeline_args['torch_dtype'] = torch.float16
|
| 301 |
-
|
| 302 |
-
self.pipeline = StableDiffusionPipeline.from_pretrained(
|
| 303 |
-
HF_MODEL,
|
| 304 |
-
**pipeline_args
|
| 305 |
-
)
|
| 306 |
-
self.pipeline = self.pipeline.to(self.device)
|
| 307 |
-
log.info(f"✅ Loaded Diffusers model: {HF_MODEL}")
|
| 308 |
-
|
| 309 |
-
def generate(
|
| 310 |
-
self,
|
| 311 |
-
prompt: str,
|
| 312 |
-
scene_id: int,
|
| 313 |
-
visual_style: str = "",
|
| 314 |
-
scene_number: int = 1,
|
| 315 |
-
total_scenes: int = 1,
|
| 316 |
-
context_text: str = "" # NEW: English text for context
|
| 317 |
-
) -> Dict[str, Any]:
|
| 318 |
-
"""Generate image with enhanced prompting"""
|
| 319 |
-
|
| 320 |
-
if self.pipeline is None:
|
| 321 |
-
return {
|
| 322 |
-
"success": False,
|
| 323 |
-
"scene_id": scene_id,
|
| 324 |
-
"error": "Pipeline not initialized"
|
| 325 |
-
}
|
| 326 |
-
|
| 327 |
-
try:
|
| 328 |
-
log.info(f"Generating image for scene {scene_id}")
|
| 329 |
-
|
| 330 |
-
# Enhance prompt for better quality (now with English context)
|
| 331 |
-
enhanced_prompt, negative_prompt = self.prompt_enhancer.enhance_prompt(
|
| 332 |
-
prompt,
|
| 333 |
-
visual_style,
|
| 334 |
-
scene_number,
|
| 335 |
-
total_scenes,
|
| 336 |
-
context_text # Pass English text for better context
|
| 337 |
-
)
|
| 338 |
-
|
| 339 |
-
log.info(f"Original: {prompt[:80]}...")
|
| 340 |
-
log.info(f"Enhanced: {enhanced_prompt[:80]}...")
|
| 341 |
-
|
| 342 |
-
# Generate with enhanced prompts
|
| 343 |
-
generation_params = {
|
| 344 |
-
"prompt": enhanced_prompt,
|
| 345 |
-
"num_inference_steps": 30,
|
| 346 |
-
"guidance_scale": 7.5,
|
| 347 |
-
"height": IMAGE_SIZE[1],
|
| 348 |
-
"width": IMAGE_SIZE[0]
|
| 349 |
-
}
|
| 350 |
-
|
| 351 |
-
# Add negative prompt if pipeline supports it
|
| 352 |
-
if hasattr(self.pipeline, 'negative_prompt'):
|
| 353 |
-
generation_params["negative_prompt"] = negative_prompt
|
| 354 |
-
|
| 355 |
-
result = self.pipeline(**generation_params)
|
| 356 |
-
|
| 357 |
-
if hasattr(result, 'nsfw_content_detected') and any(result.nsfw_content_detected):
|
| 358 |
-
return {
|
| 359 |
-
"success": False,
|
| 360 |
-
"scene_id": scene_id,
|
| 361 |
-
"error": "NSFW content detected"
|
| 362 |
-
}
|
| 363 |
-
|
| 364 |
-
if not hasattr(result, 'images') or not result.images:
|
| 365 |
-
return {
|
| 366 |
-
"success": False,
|
| 367 |
-
"scene_id": scene_id,
|
| 368 |
-
"error": "No image generated"
|
| 369 |
-
}
|
| 370 |
-
|
| 371 |
-
image = result.images[0]
|
| 372 |
-
|
| 373 |
-
if image.mode != 'RGB':
|
| 374 |
-
image = image.convert('RGB')
|
| 375 |
-
|
| 376 |
-
buffered = io.BytesIO()
|
| 377 |
-
image.save(buffered, format="PNG")
|
| 378 |
-
img_base64 = base64.b64encode(buffered.getvalue()).decode('utf-8')
|
| 379 |
-
|
| 380 |
-
log.info(f"✅ Image generated for scene {scene_id}")
|
| 381 |
-
|
| 382 |
-
return {
|
| 383 |
-
"success": True,
|
| 384 |
-
"scene_id": scene_id,
|
| 385 |
-
"image_base64": img_base64,
|
| 386 |
-
"image": image
|
| 387 |
-
}
|
| 388 |
-
|
| 389 |
-
except Exception as e:
|
| 390 |
-
log.error(f"Generation failed for scene {scene_id}: {e}")
|
| 391 |
-
import traceback
|
| 392 |
-
traceback.print_exc()
|
| 393 |
-
|
| 394 |
-
return {
|
| 395 |
-
"success": False,
|
| 396 |
-
"scene_id": scene_id,
|
| 397 |
-
"error": str(e)
|
| 398 |
-
}
|
| 399 |
-
|
| 400 |
-
|
| 401 |
-
# ==================== Gradio Client Integration ====================
|
| 402 |
-
|
| 403 |
-
class SpaceConnector:
|
| 404 |
-
"""Connects to other spaces via Gradio Client"""
|
| 405 |
-
|
| 406 |
-
def __init__(self):
|
| 407 |
-
self.text_agent = None
|
| 408 |
-
self.video_agent = None
|
| 409 |
-
|
| 410 |
-
if TEXT_AGENT_URL:
|
| 411 |
-
try:
|
| 412 |
-
log.info(f"Connecting to Text Agent: {TEXT_AGENT_URL}")
|
| 413 |
-
self.text_agent = Client(TEXT_AGENT_URL)
|
| 414 |
-
log.info("✅ Text Agent connected")
|
| 415 |
-
except Exception as e:
|
| 416 |
-
log.error(f"Text Agent connection failed: {e}")
|
| 417 |
-
|
| 418 |
-
if VIDEO_AGENT_URL:
|
| 419 |
-
try:
|
| 420 |
-
log.info(f"Connecting to Video Agent: {VIDEO_AGENT_URL}")
|
| 421 |
-
self.video_agent = Client(VIDEO_AGENT_URL)
|
| 422 |
-
log.info("✅ Video Agent connected")
|
| 423 |
-
except Exception as e:
|
| 424 |
-
log.error(f"Video Agent connection failed: {e}")
|
| 425 |
-
|
| 426 |
-
def get_scenes_from_text_agent(
|
| 427 |
-
self,
|
| 428 |
-
text: str,
|
| 429 |
-
language: str = "ar",
|
| 430 |
-
visual_style: str = "",
|
| 431 |
-
target_duration: int = 15
|
| 432 |
-
) -> Optional[Dict]:
|
| 433 |
-
"""Call Text Agent to get scenes"""
|
| 434 |
-
|
| 435 |
-
if not self.text_agent:
|
| 436 |
-
log.error("Text Agent not connected")
|
| 437 |
-
return None
|
| 438 |
-
|
| 439 |
-
try:
|
| 440 |
-
log.info("Calling Text Agent...")
|
| 441 |
-
|
| 442 |
-
result = self.text_agent.predict(
|
| 443 |
-
text=text,
|
| 444 |
-
language=language,
|
| 445 |
-
visual_style=visual_style,
|
| 446 |
-
target_scene_duration=target_duration,
|
| 447 |
-
api_name="/process_text"
|
| 448 |
-
)
|
| 449 |
-
|
| 450 |
-
log.info("✅ Received scenes from Text Agent")
|
| 451 |
-
return result
|
| 452 |
-
|
| 453 |
-
except Exception as e:
|
| 454 |
-
log.error(f"Text Agent call failed: {e}")
|
| 455 |
-
return None
|
| 456 |
-
|
| 457 |
-
def send_to_video_agent(self, scenes_data: Dict) -> Optional[str]:
|
| 458 |
-
"""Send processed scenes to Video Agent"""
|
| 459 |
-
|
| 460 |
-
if not self.video_agent:
|
| 461 |
-
log.error("Video Agent not connected")
|
| 462 |
-
return None
|
| 463 |
-
|
| 464 |
-
try:
|
| 465 |
-
log.info("Calling Video Agent...")
|
| 466 |
-
|
| 467 |
-
result = self.video_agent.predict(
|
| 468 |
-
scenes_json=json.dumps(scenes_data),
|
| 469 |
-
api_name="/create_video_api"
|
| 470 |
-
)
|
| 471 |
-
|
| 472 |
-
log.info("✅ Video Agent response received")
|
| 473 |
-
return result
|
| 474 |
-
|
| 475 |
-
except Exception as e:
|
| 476 |
-
log.error(f"Video Agent call failed: {e}")
|
| 477 |
-
return None
|
| 478 |
-
|
| 479 |
-
|
| 480 |
-
# ==================== Global Instances ====================
|
| 481 |
-
|
| 482 |
-
image_generator = ImageGenerator()
|
| 483 |
-
space_connector = SpaceConnector()
|
| 484 |
-
video_memory = VideoMemory()
|
| 485 |
-
|
| 486 |
-
|
| 487 |
-
# ==================== Gradio Functions ====================
|
| 488 |
-
|
| 489 |
-
def receive_video_from_space3(video_path: str, thumbnail_path: str = None):
|
| 490 |
-
"""API endpoint for Space 3 to send video back"""
|
| 491 |
-
try:
|
| 492 |
-
if video_path and os.path.exists(video_path):
|
| 493 |
-
video_memory.add_video(video_path, thumbnail_path)
|
| 494 |
-
return {"success": True, "message": "Video received and saved"}
|
| 495 |
-
else:
|
| 496 |
-
return {"success": False, "message": "Video path invalid"}
|
| 497 |
-
except Exception as e:
|
| 498 |
-
log.error(f"Failed to receive video: {e}")
|
| 499 |
-
return {"success": False, "message": str(e)}
|
| 500 |
-
|
| 501 |
-
|
| 502 |
-
def process_full_pipeline(
|
| 503 |
-
text: str,
|
| 504 |
-
language: str,
|
| 505 |
-
visual_style: str,
|
| 506 |
-
target_duration: int,
|
| 507 |
-
auto_send_to_video: bool
|
| 508 |
-
) -> tuple:
|
| 509 |
-
"""Complete pipeline with enhanced prompting"""
|
| 510 |
-
|
| 511 |
-
if not text or len(text.strip()) < 100:
|
| 512 |
-
current_video, current_thumb = video_memory.get_current()
|
| 513 |
-
return None, None, current_video, current_thumb, "❌ Text must be at least 100 characters"
|
| 514 |
-
|
| 515 |
-
try:
|
| 516 |
-
# Step 1: Get scenes from Text Agent
|
| 517 |
-
scenes_data = space_connector.get_scenes_from_text_agent(
|
| 518 |
-
text, language, visual_style, target_duration
|
| 519 |
-
)
|
| 520 |
-
|
| 521 |
-
if not scenes_data:
|
| 522 |
-
current_video, current_thumb = video_memory.get_current()
|
| 523 |
-
return None, None, current_video, current_thumb, "❌ Failed to get scenes from Text Agent"
|
| 524 |
-
|
| 525 |
-
scenes = scenes_data.get("scenes", [])
|
| 526 |
-
visual_style = scenes_data.get("visual_style", visual_style)
|
| 527 |
-
|
| 528 |
-
if not scenes:
|
| 529 |
-
current_video, current_thumb = video_memory.get_current()
|
| 530 |
-
return None, None, current_video, current_thumb, "❌ No scenes received"
|
| 531 |
-
|
| 532 |
-
log.info(f"Processing {len(scenes)} scenes with enhanced prompting...")
|
| 533 |
-
|
| 534 |
-
# Step 2: Generate images with enhanced prompts
|
| 535 |
-
results = []
|
| 536 |
-
gallery_images = []
|
| 537 |
-
total_scenes = len(scenes)
|
| 538 |
-
|
| 539 |
-
for idx, scene in enumerate(scenes, 1):
|
| 540 |
-
scene_id = scene.get("scene_id", idx)
|
| 541 |
-
visual_prompt = scene.get("visual_prompt", "")
|
| 542 |
-
|
| 543 |
-
# Extract English text early for use in prompt enhancement
|
| 544 |
-
english_text = scene.get("text_english", "")
|
| 545 |
-
if not english_text:
|
| 546 |
-
english_text = scene.get("text", "")
|
| 547 |
-
|
| 548 |
-
if not visual_prompt:
|
| 549 |
-
continue
|
| 550 |
-
|
| 551 |
-
# Generate with enhanced prompt + English context
|
| 552 |
-
result = image_generator.generate(
|
| 553 |
-
visual_prompt,
|
| 554 |
-
scene_id,
|
| 555 |
-
visual_style,
|
| 556 |
-
idx, # scene number
|
| 557 |
-
total_scenes,
|
| 558 |
-
english_text # ✅ Pass English text for better prompts
|
| 559 |
-
)
|
| 560 |
-
|
| 561 |
-
if result["success"]:
|
| 562 |
-
# English text already extracted above
|
| 563 |
-
if not english_text or not english_text.strip():
|
| 564 |
-
log.warning(f"⚠️ Scene {scene_id}: text_english missing!")
|
| 565 |
-
else:
|
| 566 |
-
log.info(f"✓ Scene {scene_id}: English text: {english_text[:50]}...")
|
| 567 |
-
|
| 568 |
-
results.append({
|
| 569 |
-
"scene_id": scene_id,
|
| 570 |
-
"text": english_text, # ✅ English for TTS
|
| 571 |
-
"text_english": english_text, # ✅ Also pass for thumbnail
|
| 572 |
-
"image_base64": result["image_base64"],
|
| 573 |
-
"prompt": visual_prompt
|
| 574 |
-
})
|
| 575 |
-
|
| 576 |
-
gallery_images.append((result["image"], f"Scene {scene_id}"))
|
| 577 |
-
else:
|
| 578 |
-
log.error(f"Failed scene {scene_id}: {result.get('error')}")
|
| 579 |
-
|
| 580 |
-
# Step 3: Validate & prepare output
|
| 581 |
-
output_json = {
|
| 582 |
-
"scenes": results,
|
| 583 |
-
"total_scenes": len(results),
|
| 584 |
-
"visual_style": visual_style,
|
| 585 |
-
"language": "en"
|
| 586 |
-
}
|
| 587 |
-
|
| 588 |
-
# Validation
|
| 589 |
-
arabic_scenes = []
|
| 590 |
-
for r in results:
|
| 591 |
-
text = r.get("text", "")
|
| 592 |
-
if any('\u0600' <= c <= '\u06FF' for c in text):
|
| 593 |
-
arabic_scenes.append(r["scene_id"])
|
| 594 |
-
|
| 595 |
-
if arabic_scenes:
|
| 596 |
-
log.error(f"❌ {len(arabic_scenes)} scenes contain Arabic: {arabic_scenes}")
|
| 597 |
-
else:
|
| 598 |
-
log.info(f"✅ All {len(results)} scenes have English text")
|
| 599 |
-
|
| 600 |
-
status_msg = f"""✅ Image Generation Complete (Enhanced Prompts)!
|
| 601 |
-
|
| 602 |
-
📊 **Results:**
|
| 603 |
-
- Total Scenes: {len(scenes)}
|
| 604 |
-
- Images Generated: {len(results)} (with smart prompting)
|
| 605 |
-
- Failed: {len(scenes) - len(results)}
|
| 606 |
-
- Language: English (TTS ready)
|
| 607 |
-
|
| 608 |
-
✨ **Enhancements Applied:**
|
| 609 |
-
- Consistent lighting and quality
|
| 610 |
-
- Professional composition
|
| 611 |
-
- Negative prompts for better output
|
| 612 |
-
- Scene-aware framing
|
| 613 |
-
|
| 614 |
-
📋 **Images:**
|
| 615 |
-
"""
|
| 616 |
-
for r in results:
|
| 617 |
-
status_msg += f"\n- Scene {r['scene_id']}: ✅ Generated (Enhanced)"
|
| 618 |
-
|
| 619 |
-
# Step 4: Send to Video Agent
|
| 620 |
-
if auto_send_to_video and results:
|
| 621 |
-
status_msg += "\n\n🎬 Sending to Video Agent..."
|
| 622 |
-
video_result = space_connector.send_to_video_agent(output_json)
|
| 623 |
-
|
| 624 |
-
if video_result:
|
| 625 |
-
status_msg += "\n✅ Video processing started!"
|
| 626 |
-
else:
|
| 627 |
-
status_msg += "\n⚠️ Failed to start video generation"
|
| 628 |
-
|
| 629 |
-
current_video, current_thumb = video_memory.get_current()
|
| 630 |
-
|
| 631 |
-
return (
|
| 632 |
-
json.dumps(output_json, indent=2),
|
| 633 |
-
gallery_images,
|
| 634 |
-
current_video,
|
| 635 |
-
current_thumb,
|
| 636 |
-
status_msg
|
| 637 |
-
)
|
| 638 |
-
|
| 639 |
-
except Exception as e:
|
| 640 |
-
log.error(f"Pipeline failed: {e}")
|
| 641 |
-
import traceback
|
| 642 |
-
traceback.print_exc()
|
| 643 |
-
current_video, current_thumb = video_memory.get_current()
|
| 644 |
-
return None, None, current_video, current_thumb, f"❌ Error: {str(e)}"
|
| 645 |
-
|
| 646 |
-
|
| 647 |
-
def refresh_video_display():
|
| 648 |
-
"""Refresh video display"""
|
| 649 |
-
video_path, thumbnail_path = video_memory.get_current()
|
| 650 |
-
|
| 651 |
-
if video_path and os.path.exists(video_path):
|
| 652 |
-
return video_path, thumbnail_path, "✅ Current video loaded"
|
| 653 |
-
else:
|
| 654 |
-
return None, None, "ℹ️ No video yet"
|
| 655 |
-
|
| 656 |
-
|
| 657 |
-
# ==================== Gradio Interface ====================
|
| 658 |
-
|
| 659 |
-
text_agent_status = "✅ Connected" if space_connector.text_agent else "⚠️ Not Connected"
|
| 660 |
-
video_agent_status = "✅ Connected" if space_connector.video_agent else "⚠️ Not Connected"
|
| 661 |
-
|
| 662 |
-
with gr.Blocks(title="Image Agent - Enhanced", theme=gr.themes.Soft()) as demo:
|
| 663 |
-
|
| 664 |
-
gr.Markdown("# 🎨 Image Agent - Enhanced with Smart Prompting")
|
| 665 |
-
gr.Markdown("**Space 2/3** - Beautiful, consistent images + English thumbnails")
|
| 666 |
-
|
| 667 |
-
status_indicator = gr.Markdown(
|
| 668 |
-
f"**Device:** {DEVICE.upper()} | "
|
| 669 |
-
f"**Text Agent:** {text_agent_status} | "
|
| 670 |
-
f"**Video Agent:** {video_agent_status} | "
|
| 671 |
-
f"**✨ Enhanced Prompting: ON**"
|
| 672 |
-
)
|
| 673 |
-
|
| 674 |
-
gr.Markdown("---")
|
| 675 |
-
|
| 676 |
-
with gr.Tab("🚀 Automated Pipeline"):
|
| 677 |
-
gr.Markdown("### Complete Flow with Enhanced Image Generation")
|
| 678 |
-
|
| 679 |
-
with gr.Row():
|
| 680 |
-
with gr.Column(scale=1):
|
| 681 |
-
text_input = gr.Textbox(
|
| 682 |
-
label="Input Text (Arabic or English)",
|
| 683 |
-
placeholder="أدخل نصك هنا...",
|
| 684 |
-
lines=10
|
| 685 |
-
)
|
| 686 |
-
|
| 687 |
-
with gr.Row():
|
| 688 |
-
language_input = gr.Radio(
|
| 689 |
-
choices=["ar", "en"],
|
| 690 |
-
value="ar",
|
| 691 |
-
label="Input Language"
|
| 692 |
-
)
|
| 693 |
-
|
| 694 |
-
duration_input = gr.Slider(
|
| 695 |
-
minimum=10,
|
| 696 |
-
maximum=30,
|
| 697 |
-
value=15,
|
| 698 |
-
step=1,
|
| 699 |
-
label="Scene Duration (sec)"
|
| 700 |
-
)
|
| 701 |
-
|
| 702 |
-
style_input = gr.Textbox(
|
| 703 |
-
label="Visual Style",
|
| 704 |
-
value="cinematic, high quality, 4k",
|
| 705 |
-
lines=1
|
| 706 |
-
)
|
| 707 |
-
|
| 708 |
-
auto_video_checkbox = gr.Checkbox(
|
| 709 |
-
label="Auto-send to Video Agent",
|
| 710 |
-
value=True
|
| 711 |
-
)
|
| 712 |
-
|
| 713 |
-
process_btn = gr.Button("🚀 Start Enhanced Pipeline", variant="primary", size="lg")
|
| 714 |
-
|
| 715 |
-
status_output = gr.Textbox(label="Status", lines=15)
|
| 716 |
-
|
| 717 |
-
with gr.Column(scale=1):
|
| 718 |
-
gallery_output = gr.Gallery(
|
| 719 |
-
label="Generated Images (Enhanced)",
|
| 720 |
-
columns=2,
|
| 721 |
-
height=400
|
| 722 |
-
)
|
| 723 |
-
|
| 724 |
-
gr.Markdown("### 📹 Final Video")
|
| 725 |
-
|
| 726 |
-
refresh_btn = gr.Button("🔄 Refresh Video", size="sm")
|
| 727 |
-
|
| 728 |
-
video_display = gr.Video(label="Video", height=300)
|
| 729 |
-
thumbnail_display = gr.Image(label="Thumbnail", type="filepath", height=200)
|
| 730 |
-
|
| 731 |
-
json_output = gr.Code(label="JSON Output", language="json", lines=10)
|
| 732 |
-
|
| 733 |
-
process_btn.click(
|
| 734 |
-
fn=process_full_pipeline,
|
| 735 |
-
inputs=[text_input, language_input, style_input, duration_input, auto_video_checkbox],
|
| 736 |
-
outputs=[json_output, gallery_output, video_display, thumbnail_display, status_output]
|
| 737 |
-
)
|
| 738 |
-
|
| 739 |
-
refresh_btn.click(
|
| 740 |
-
fn=refresh_video_display,
|
| 741 |
-
inputs=[],
|
| 742 |
-
outputs=[video_display, thumbnail_display, status_output]
|
| 743 |
-
)
|
| 744 |
-
|
| 745 |
-
with gr.Tab("🔌 API"):
|
| 746 |
-
gr.Markdown("### API Receiver for Space 3")
|
| 747 |
-
api_video_path = gr.Textbox(label="video_path")
|
| 748 |
-
api_thumb_path = gr.Textbox(label="thumbnail_path")
|
| 749 |
-
api_receive_btn = gr.Button("Receive")
|
| 750 |
-
api_result = gr.JSON(label="Result")
|
| 751 |
-
|
| 752 |
-
api_receive_btn.click(
|
| 753 |
-
fn=receive_video_from_space3,
|
| 754 |
-
inputs=[api_video_path, api_thumb_path],
|
| 755 |
-
outputs=api_result,
|
| 756 |
-
api_name="receive_video"
|
| 757 |
-
)
|
| 758 |
-
|
| 759 |
-
gr.Markdown("---")
|
| 760 |
-
gr.Markdown("""
|
| 761 |
-
### ✨ Enhanced Features
|
| 762 |
-
|
| 763 |
-
**Smart Image Generation:**
|
| 764 |
-
- ✅ Consistent lighting across all scenes
|
| 765 |
-
- ✅ Professional composition (establishing, medium, closing shots)
|
| 766 |
-
- ✅ Quality boosters (sharp focus, detailed, 4k)
|
| 767 |
-
- ✅ Negative prompts to avoid bad outputs
|
| 768 |
-
- ✅ Scene-aware framing for narrative flow
|
| 769 |
-
|
| 770 |
-
**English Text:**
|
| 771 |
-
- ✅ All text in English for TTS
|
| 772 |
-
- ✅ Thumbnails use English text
|
| 773 |
-
- ✅ Validation checks
|
| 774 |
-
|
| 775 |
-
**Set in Secrets:**
|
| 776 |
-
- `TEXT_AGENT_URL` - Text Agent space
|
| 777 |
-
- `VIDEO_AGENT_URL` - Video Agent space
|
| 778 |
-
""")
|
| 779 |
-
|
| 780 |
-
|
| 781 |
-
if __name__ == "__main__":
|
| 782 |
-
PORT = int(os.getenv("PORT", "7860"))
|
| 783 |
-
log.info("Starting Enhanced Image Agent...")
|
| 784 |
-
demo.launch(server_name="0.0.0.0", server_port=PORT)
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
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