Spaces:
Sleeping
Sleeping
File size: 21,956 Bytes
4e7bafb | 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 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 | """
Full Pipeline: Prompt β Manifest β Images β Selection β Composition
Orchestrates the complete workflow from user prompt to final MP4 video
"""
import requests
import json
import os
from pathlib import Path
from PIL import Image
from io import BytesIO
import asyncio
import subprocess
import sys
from datetime import datetime
# βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
# Configuration
# βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
MANIFEST_SERVER = "https://factorstudios-content-gen.hf.space"
IMAGE_SERVER = "https://factorstudios-pinteresting.hf.space"
PIPELINE_DIR = Path(__file__).parent
CANDIDATES_DIR = PIPELINE_DIR / "candidates"
SELECTED_DIR = PIPELINE_DIR / "selected"
RENDERS_DIR = PIPELINE_DIR / "renders"
# βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
# Step 1: Generate Manifest from Prompt
# βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
async def step_generate_manifest(prompt: str, output_dir: Path = PIPELINE_DIR) -> dict:
"""
Call content-gen server to generate manifest from prompt.
Saves manifest to manifest_response.json
Args:
prompt (str): User prompt describing video content
output_dir (Path): Directory to save manifest
Returns:
dict: Manifest with title and scenes
"""
print("\n" + "="*70)
print(f"[STEP 1] Generating Manifest from Prompt")
print("="*70)
print(f"Prompt: {prompt[:80]}...")
try:
# Call manifest generation server
payload = {"prompt": prompt}
print(f"Calling {MANIFEST_SERVER}/generate...")
response = requests.post(
f"{MANIFEST_SERVER}/generate",
json=payload,
timeout=60
)
response.raise_for_status()
manifest = response.json()
# Save manifest to file
manifest_path = output_dir / "manifest_response.json"
with open(manifest_path, "w") as f:
json.dump(manifest, f, indent=2)
scenes = manifest.get("scenes", [])
print(f"β Generated manifest with {len(scenes)} scenes")
print(f"β Saved to {manifest_path.name}")
# Print scene details
for idx, scene in enumerate(scenes):
label = scene.get("label", f"Scene {idx}")
query = scene.get("image_query", "")
print(f" Scene {idx}: {label} (query: '{query[:30]}...')")
return manifest
except Exception as e:
print(f"β Failed to generate manifest: {e}")
raise
# βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
# Step 2: Download Images for Each Scene
# βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
async def step_download_images(
manifest: dict,
output_dir: Path = CANDIDATES_DIR,
images_per_scene: int = 5
) -> int:
"""
Download images from pinteresting server for each scene in manifest.
IMPORTANT: Downloads image for TITLE (scene 0) + all scenes in manifest.scenes
Follows the pattern from test_api.py
Args:
manifest (dict): Manifest with title and scenes
output_dir (Path): Base directory to organize images
images_per_scene (int): Number of images per scene
Returns:
int: Total number of images downloaded
"""
print("\n" + "="*70)
print(f"[STEP 2] Downloading Images (Title + Scenes)")
print("="*70)
# Clear and recreate candidates directory
if output_dir.exists():
import shutil
shutil.rmtree(output_dir)
output_dir.mkdir(parents=True, exist_ok=True)
total_downloaded = 0
# STEP 2.0: Download image for TITLE (becomes scene_0)
title = manifest.get("title", "")
if title:
scene_dir = output_dir / "scene_0"
scene_dir.mkdir(parents=True, exist_ok=True)
print(f"\n[Scene 0] {title} (TITLE/INTRO)")
print(f" Query: {title}")
try:
payload = {
"keyword": title,
"count": images_per_scene
}
print(f" Calling {IMAGE_SERVER}/scrape...")
response = requests.post(
f"{IMAGE_SERVER}/scrape",
json=payload,
timeout=60
)
response.raise_for_status()
data = response.json()
images = data.get("images", [])
print(f" Downloaded {len(images)} images")
for img_idx, img_url in enumerate(images):
try:
img_response = requests.get(img_url, timeout=30)
if img_response.status_code == 200:
img_path = scene_dir / f"candidate_{img_idx:02d}.jpg"
with open(img_path, "wb") as f:
f.write(img_response.content)
total_downloaded += 1
except Exception as e:
print(f" β Failed to save image {img_idx}: {e}")
except Exception as e:
print(f" β Error downloading images for title: {e}")
# STEP 2.1: Download images for each content scene (becomes scene_1, scene_2, etc)
scenes = manifest.get("scenes", [])
for scene_idx, scene in enumerate(scenes):
actual_idx = scene_idx + 1 # scene_1, scene_2, etc (title is scene_0)
scene_label = scene.get("label", f"Scene {actual_idx}")
image_query = scene.get("image_query", "")
if not image_query:
print(f"\n[Scene {actual_idx}] β No image query found, skipping...")
continue
# Create scene-specific folder
scene_dir = output_dir / f"scene_{actual_idx}"
scene_dir.mkdir(parents=True, exist_ok=True)
print(f"\n[Scene {actual_idx}] {scene_label}")
print(f" Query: {image_query}")
# Fetch images from pinteresting API
try:
payload = {
"keyword": image_query,
"count": images_per_scene
}
print(f" Calling {IMAGE_SERVER}/scrape...")
response = requests.post(
f"{IMAGE_SERVER}/scrape",
json=payload,
timeout=60
)
response.raise_for_status()
data = response.json()
if data.get("success"):
images = data.get("images", [])
print(f" β Found {len(images)} images")
# Download each image
for img_idx, img_data in enumerate(images):
img_url = img_data.get("url")
if not img_url:
continue
try:
# Download image
img_response = requests.get(img_url, timeout=15)
img_response.raise_for_status()
# Verify it's a valid image
img = Image.open(BytesIO(img_response.content))
# Save image
file_name = f"candidate_{img_idx:02d}.jpg"
file_path = scene_dir / file_name
with open(file_path, "wb") as f:
f.write(img_response.content)
size_kb = len(img_response.content) / 1024
dims = f"{img_data.get('width', '?')}x{img_data.get('height', '?')}"
print(f" β {file_name} ({dims}, {size_kb:.0f}KB)")
total_downloaded += 1
except Exception as e:
print(f" β Image {img_idx} failed: {e}")
else:
print(f" β API Error: {data.get('message')}")
except Exception as e:
print(f" β Request failed: {e}")
print(f"\nβ Downloaded {total_downloaded} images total")
return total_downloaded
# βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
# Step 3: Select Best Image from Each Scene's Candidates
# βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
async def step_select_scenes(manifest: dict, candidates_dir: Path = CANDIDATES_DIR) -> dict:
"""
Select best image from each scene's candidate folder.
IMPORTANT: Selects from TITLE (scene_0) + all scenes in manifest.scenes
Evaluates by file size (largest = best quality).
Args:
manifest (dict): Manifest with scene count
candidates_dir (Path): Directory with candidate images
Returns:
dict: Selection results
"""
print("\n" + "="*70)
print(f"[STEP 3] Selecting Best Images from Candidates")
print("="*70)
# Ensure selected directory exists
SELECTED_DIR.mkdir(parents=True, exist_ok=True)
scenes = manifest.get("scenes", [])
selected_count = 0
# Select from scene_0 (title) through scene_N (content scenes)
# Total scenes = len(scenes) + 1 (for title as scene_0)
total_scene_count = len(scenes) + 1
for scene_idx in range(total_scene_count):
scene_folder = candidates_dir / f"scene_{scene_idx}"
if not scene_folder.exists():
if scene_idx == 0:
print(f"[Scene {scene_idx}] β No candidates found (TITLE)")
else:
print(f"[Scene {scene_idx}] β No candidates found")
continue
# Find largest image (best quality)
images = list(scene_folder.glob("*.jpg"))
if not images:
if scene_idx == 0:
print(f"[Scene {scene_idx}] β No JPEG images found (TITLE)")
else:
print(f"[Scene {scene_idx}] β No JPEG images found")
continue
best_img = max(images, key=lambda p: p.stat().st_size)
size_kb = best_img.stat().st_size / 1024
# Copy to selected folder
selected_path = SELECTED_DIR / f"scene_{scene_idx:02d}.jpg"
import shutil
shutil.copy2(best_img, selected_path)
if scene_idx == 0:
print(f"[Scene {scene_idx}] β Selected {best_img.name} ({size_kb:.0f}KB) [TITLE]")
else:
print(f"[Scene {scene_idx}] β Selected {best_img.name} ({size_kb:.0f}KB)")
selected_count += 1
print(f"\nβ Selected {selected_count} images ({total_scene_count} total: title + {len(scenes)} scenes)")
return {
"status": "success",
"selected": selected_count,
"total": total_scene_count
}
# βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
# Step 4: Compose Video with Selected Images and Manifest
# βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
async def step_compose_video(manifest: dict) -> dict:
"""
Compose final video using selected images and manifest labels.
Calls the FastAPI /compose endpoint which handles scene config generation.
Args:
manifest (dict): Manifest with title and scenes
Returns:
dict: Composition results with video path and metadata
"""
print("\n" + "="*70)
print(f"[STEP 4] Composing Video from Selected Images")
print("="*70)
scenes = manifest.get("scenes", [])
selected_images = sorted(SELECTED_DIR.glob("scene_*.jpg"))
print(f"Manifest title: {manifest.get('title', 'Untitled')}")
print(f"Selected images: {len(selected_images)}")
print(f"Required images: {len(scenes) + 1} (title + {len(scenes)} scenes)")
# Expected: title + all scenes
expected_images = len(scenes) + 1
if len(selected_images) != expected_images:
raise Exception(
f"Image count mismatch: expected {expected_images}, "
f"found {len(selected_images)}"
)
# Call the FastAPI /compose endpoint
print(f"\nCalling /compose endpoint...")
try:
payload = {
"title": manifest.get("title", "Untitled"),
"scenes": [
{
"label": s.get("label", f"Scene {idx}"),
"image_query": s.get("image_query", "")
}
for idx, s in enumerate(scenes)
]
}
response = requests.post(
f"http://localhost:7860/compose",
json=payload,
timeout=300
)
if response.status_code != 200:
error_data = response.json() if response.headers.get("content-type") == "application/json" else response.text
print(f"β Server returned {response.status_code}: {error_data}")
raise Exception(f"Compose endpoint failed: {error_data}")
# Check if response is binary (video file) or JSON
if response.headers.get("content-type", "").startswith("video"):
# Save video file
output_path = PIPELINE_DIR / "output_video.mp4"
with open(output_path, "wb") as f:
f.write(response.content)
size_mb = output_path.stat().st_size / (1024 * 1024)
print(f"β Video saved: {output_path.name} ({size_mb:.2f}MB)")
return {
"status": "success",
"video_path": str(output_path),
"size_mb": size_mb,
"scenes": len(scenes) + 1
}
else:
# Response is JSON (might be error or status)
data = response.json()
if data.get("status") == "success":
print(f"β Compose completed successfully")
return data
else:
raise Exception(f"Compose failed: {data.get('message', 'Unknown error')}")
except Exception as e:
print(f"β Composition failed: {e}")
raise
# Generate dynamic SCENE_CONFIG from manifest
print(f"\nGenerating scene configuration...")
try:
payload = {
"title": manifest.get("title", "Untitled"),
"scenes": [
{
"label": s.get("label", f"Scene {idx}"),
"image_query": s.get("image_query", "")
}
for idx, s in enumerate(scenes)
]
}
response = requests.post(
f"http://localhost:7860/compose",
json=payload,
timeout=300
)
if response.status_code != 200:
error_data = response.json() if response.headers.get("content-type") == "application/json" else response.text
print(f"β Server returned {response.status_code}: {error_data}")
raise Exception(f"Compose endpoint failed: {error_data}")
# Check if response is binary (video file) or JSON
if response.headers.get("content-type", "").startswith("video"):
# Save video file
output_path = PIPELINE_DIR / "output_video.mp4"
with open(output_path, "wb") as f:
f.write(response.content)
size_mb = output_path.stat().st_size / (1024 * 1024)
print(f"β Video saved: {output_path.name} ({size_mb:.2f}MB)")
return {
"status": "success",
"video_path": str(output_path),
"size_mb": size_mb,
"scenes": len(scenes) + 1
}
else:
# Response is JSON (might be error or status)
data = response.json()
if data.get("status") == "success":
print(f"β Compose completed successfully")
return data
else:
raise Exception(f"Compose failed: {data.get('message', 'Unknown error')}")
except Exception as e:
print(f"β Composition failed: {e}")
raise
# βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
# Main Pipeline Orchestrator
# βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
async def generate_video_from_prompt(prompt: str) -> dict:
"""
Complete pipeline: Prompt β Manifest β Images β Selection β Video
Args:
prompt (str): User prompt describing video content
Returns:
dict: Final result with video path or error
"""
try:
# Step 1: Generate manifest from prompt
manifest = await step_generate_manifest(prompt)
# Step 2: Download images for each scene
downloaded = await step_download_images(manifest)
if downloaded == 0:
raise Exception("No images were downloaded")
# Step 3: Select best images from candidates
selection = await step_select_scenes(manifest)
if selection["selected"] != selection["total"]:
raise Exception(
f"Selection incomplete: {selection['selected']}/{selection['total']}"
)
# Step 4: Compose final video
composition = await step_compose_video(manifest)
# Success!
print("\n" + "="*70)
print("[SUCCESS] Pipeline Complete!")
print("="*70)
print(f"Title: {manifest.get('title', 'Untitled')}")
print(f"Scenes: {len(manifest.get('scenes', []))}")
print(f"Video: {composition['output_path']}")
print(f"Size: {composition['size_mb']:.1f}MB")
print("="*70)
return {
"status": "success",
"message": "Video generated successfully",
"title": manifest.get("title"),
"scenes": len(manifest.get("scenes", [])),
"output_path": composition["output_path"],
"size_mb": composition["size_mb"],
}
except Exception as e:
print("\n" + "="*70)
print(f"[ERROR] Pipeline Failed: {e}")
print("="*70)
return {
"status": "error",
"message": str(e),
"output_path": None,
}
# βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
# Local Testing
# βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
if __name__ == "__main__":
import sys
if len(sys.argv) > 1:
prompt = " ".join(sys.argv[1:])
else:
prompt = "A motivational video about personal growth and success"
# Ensure directories exist
PIPELINE_DIR.mkdir(exist_ok=True)
RENDERS_DIR.mkdir(exist_ok=True)
# Run pipeline
result = asyncio.run(generate_video_from_prompt(prompt))
# Print final status
if result["status"] == "success":
print(f"\nβ Video saved to: {result['output_path']}")
sys.exit(0)
else:
print(f"\nβ Error: {result['message']}")
sys.exit(1)
|