normanedev02 commited on
Commit
f4cd01f
·
1 Parent(s): 23212a4

Add anime generation app with characters, locations, and sample outputs

Browse files

- Add main app.py with anime scene generation logic
- Add character assets (cat, daughter, pediatrician)
- Add location backgrounds (classroom, lab)
- Add sample script JSON for testing
- Add generated output images
- Update requirements.txt with dependencies

.gitattributes CHANGED
@@ -35,3 +35,5 @@ saved_model/**/* filter=lfs diff=lfs merge=lfs -text
35
  *tfevents* filter=lfs diff=lfs merge=lfs -text
36
  *.png filter=lfs diff=lfs merge=lfs -text
37
  *.jfif filter=lfs diff=lfs merge=lfs -text
 
 
 
35
  *tfevents* filter=lfs diff=lfs merge=lfs -text
36
  *.png filter=lfs diff=lfs merge=lfs -text
37
  *.jfif filter=lfs diff=lfs merge=lfs -text
38
+ *.jpg filter=lfs diff=lfs merge=lfs -text
39
+ *.jpeg filter=lfs diff=lfs merge=lfs -text
Characters/cat.png ADDED

Git LFS Details

  • SHA256: 171447ffcd0e61247523e8ec0dc58c548ba37a564d19c1512409fb41d870d932
  • Pointer size: 132 Bytes
  • Size of remote file: 1.05 MB
Characters/daughter.png ADDED

Git LFS Details

  • SHA256: 25e5ba178cd5367876872e5cc4af9900f1da36eccd01f7206794f6e272d25914
  • Pointer size: 132 Bytes
  • Size of remote file: 1.13 MB
Characters/pediatrician 1.png ADDED

Git LFS Details

  • SHA256: e997a2e6dcc6694df45293231d200656d2f3463ab9286d4a2408f28163a2ee2e
  • Pointer size: 132 Bytes
  • Size of remote file: 1.29 MB
Locations/class room.jfif ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:9b03be02133261647436a0c0fa1de50ca7a054ab4f2cba425375800c2dc2d27f
3
+ size 3860130
Locations/lab.jfif ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:22dc424b08172e396f69272b1c0be77c410c46193492c66a5b3d040c0658e180
3
+ size 3067776
README.md CHANGED
@@ -1,13 +1,14 @@
1
  ---
2
  title: Radixlab Anime
3
- emoji: 😻
4
- colorFrom: yellow
5
- colorTo: green
6
  sdk: gradio
7
  sdk_version: 6.5.1
8
  app_file: app.py
9
  pinned: false
10
  license: mit
 
11
  ---
12
 
13
  Check out the configuration reference at https://huggingface.co/docs/hub/spaces-config-reference
 
1
  ---
2
  title: Radixlab Anime
3
+ emoji: 🏃
4
+ colorFrom: green
5
+ colorTo: red
6
  sdk: gradio
7
  sdk_version: 6.5.1
8
  app_file: app.py
9
  pinned: false
10
  license: mit
11
+ short_description: Milestone 1 of radixlab-anime
12
  ---
13
 
14
  Check out the configuration reference at https://huggingface.co/docs/hub/spaces-config-reference
app.py ADDED
@@ -0,0 +1,2166 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """
2
+ RadixLab Anime — Milestone 1 & 2: Text-to-Image + Video/Audio Pipeline
3
+ =======================================================================
4
+ A Gradio prototype that:
5
+
6
+ MILESTONE 1 (Complete):
7
+ - Parses JSON scripts
8
+ - Generates two images (A/B) per scene
9
+ - Supports reference-based image generation
10
+ - Allows per-scene approval or regeneration
11
+ - Preserves state across UI interactions
12
+
13
+ MILESTONE 2 (New):
14
+ - Converts approved images to short video clips (9:16) with camera motion
15
+ - Role-based audio engine (voiceover, dialogue, SFX)
16
+ - Audio + video synchronization
17
+ - Video Approval tab with per-scene clip management
18
+ """
19
+
20
+ import gradio as gr
21
+ import json
22
+ import os
23
+ import uuid
24
+ import warnings
25
+ import tempfile
26
+ import numpy as np
27
+ from PIL import Image, ImageDraw, ImageFont
28
+ from typing import Optional, Dict, List, Any, Tuple
29
+
30
+ warnings.filterwarnings("ignore")
31
+
32
+ # =============================================================================
33
+ # MOVIEPY INITIALIZATION (Required for Milestone 2)
34
+ # =============================================================================
35
+ MOVIEPY_AVAILABLE = False
36
+ ImageClip = None
37
+ ColorClip = None
38
+ CompositeVideoClip = None
39
+ AudioArrayClip = None
40
+ CompositeAudioClip = None
41
+
42
+ try:
43
+ # MoviePy 2.x import style
44
+ from moviepy import (
45
+ ImageClip, ColorClip, CompositeVideoClip,
46
+ AudioArrayClip, CompositeAudioClip
47
+ )
48
+ MOVIEPY_AVAILABLE = True
49
+ print("✅ MoviePy 2.x initialized successfully")
50
+ except ImportError:
51
+ try:
52
+ # MoviePy 1.x import style (fallback)
53
+ from moviepy.editor import (
54
+ ImageClip, ColorClip, CompositeVideoClip
55
+ )
56
+ from moviepy.audio.AudioClip import AudioArrayClip
57
+ from moviepy.editor import CompositeAudioClip
58
+ MOVIEPY_AVAILABLE = True
59
+ print("✅ MoviePy 1.x initialized successfully")
60
+ except ImportError:
61
+ print("⚠️ MoviePy not installed — video generation will be unavailable")
62
+ print(" Install with: pip install moviepy")
63
+
64
+ # =============================================================================
65
+ # CONFIGURATION & PATHS
66
+ # =============================================================================
67
+ BASE_DIR = os.path.dirname(os.path.abspath(__file__))
68
+ CHAR_DIR = os.path.join(BASE_DIR, "Characters")
69
+ LOC_DIR = os.path.join(BASE_DIR, "Locations")
70
+ OUTPUT_DIR_IMG = os.path.join(BASE_DIR, "outputs", "images")
71
+ OUTPUT_DIR_AUDIO = os.path.join(BASE_DIR, "outputs", "audio")
72
+ OUTPUT_DIR_VIDEO = os.path.join(BASE_DIR, "outputs", "video_clips")
73
+
74
+ # Create required directories (Milestone 1 + 2)
75
+ for d in [CHAR_DIR, LOC_DIR, OUTPUT_DIR_IMG, OUTPUT_DIR_AUDIO, OUTPUT_DIR_VIDEO]:
76
+ os.makedirs(d, exist_ok=True)
77
+
78
+ # Default video settings
79
+ DEFAULT_VIDEO_DURATION = 4.0 # seconds
80
+ DEFAULT_FPS = 24
81
+ VIDEO_WIDTH = 1080
82
+ VIDEO_HEIGHT = 1920 # 9:16 vertical format
83
+
84
+ # =============================================================================
85
+ # VERTEX AI INITIALIZATION (API Key based - Vertex AI Express)
86
+ # =============================================================================
87
+ VERTEX_API_KEY = None
88
+ VERTEX_AI_AVAILABLE = False
89
+
90
+ def init_vertex_ai():
91
+ """Initialize Vertex AI with API key authentication."""
92
+ global VERTEX_API_KEY, VERTEX_AI_AVAILABLE
93
+
94
+ # Check for API key in environment
95
+ api_key = os.getenv("VERTEX_API_KEY") or os.getenv("GOOGLE_API_KEY")
96
+
97
+ if not api_key:
98
+ print("⚠️ VERTEX_API_KEY not set — using mock image generation")
99
+ print(" Set VERTEX_API_KEY environment variable to enable real generation")
100
+ return False
101
+
102
+ # Validate API key by making a simple request
103
+ try:
104
+ import requests
105
+ url = f"https://aiplatform.googleapis.com/v1/publishers/google/models/gemini-2.5-flash-lite:generateContent?key={api_key}"
106
+ response = requests.post(url, json={
107
+ "contents": [{"role": "user", "parts": [{"text": "test"}]}]
108
+ }, timeout=30)
109
+
110
+ if response.status_code == 200:
111
+ VERTEX_API_KEY = api_key
112
+ VERTEX_AI_AVAILABLE = True
113
+ print("✅ Vertex AI Express initialized successfully (API key auth)")
114
+ return True
115
+ else:
116
+ print(f"⚠️ Vertex AI API key validation failed: {response.status_code}")
117
+ print(" Using mock image generation")
118
+ return False
119
+ except Exception as e:
120
+ print(f"⚠️ Vertex AI init failed: {e} — using mock image generation")
121
+ return False
122
+
123
+ # Try to initialize Vertex AI on module load
124
+ init_vertex_ai()
125
+
126
+ # =============================================================================
127
+ # VERTEX AI VIDEO (I2V) INITIALIZATION (Milestone 2)
128
+ # =============================================================================
129
+ video_model = None
130
+
131
+ def init_vertex_video():
132
+ """Initialize Vertex AI Video model if credentials are available."""
133
+ global video_model
134
+ try:
135
+ # NOTE: This is a placeholder for Vertex AI Video Generation API
136
+ # The actual API may differ - structure allows easy plug-in later
137
+ import vertexai
138
+
139
+ project_id = os.getenv("GCP_PROJECT_ID")
140
+ if not project_id:
141
+ print("⚠️ GCP_PROJECT_ID not set — using mock video generation")
142
+ return None
143
+
144
+ # Placeholder: Vertex AI Video Generation is not yet publicly available
145
+ # When available, initialization would go here
146
+ print("⚠️ Vertex AI Video API not available — using mock video generation")
147
+ return None
148
+
149
+ except ImportError:
150
+ print("⚠️ Vertex AI SDK not installed — using mock video generation")
151
+ return None
152
+ except Exception as e:
153
+ print(f"⚠️ Vertex AI Video init failed: {e} — using mock video generation")
154
+ return None
155
+
156
+ # Try to initialize Vertex Video on module load
157
+ video_model = init_vertex_video()
158
+
159
+ # =============================================================================
160
+ # REFERENCE IMAGE RESOLUTION
161
+ # =============================================================================
162
+ def find_reference_image(base_dir: str, ref_key: Optional[str]) -> Optional[str]:
163
+ """
164
+ Search for a reference image in the specified directory.
165
+
166
+ Args:
167
+ base_dir: Directory to search (Characters/ or Locations/)
168
+ ref_key: The reference key to match against filenames
169
+
170
+ Returns:
171
+ Full path to the image if found, None otherwise
172
+
173
+ Rules:
174
+ - If ref_key is None or empty → return None
175
+ - Search for ref_key with common image extensions
176
+ - Case-insensitive matching
177
+ - Handles filenames with spaces (matches underscores, spaces, hyphens)
178
+ - Supports .jfif format
179
+ """
180
+ if not ref_key or not ref_key.strip():
181
+ return None
182
+
183
+ ref_key = ref_key.strip()
184
+
185
+ # Supported image extensions (including .jfif for JPEG File Interchange Format)
186
+ extensions = [".png", ".jpg", ".jpeg", ".webp", ".jfif", ".gif", ".bmp"]
187
+
188
+ # Normalize ref_key for flexible matching (replace common separators)
189
+ def normalize_name(name: str) -> str:
190
+ """Normalize filename for comparison: lowercase, replace separators."""
191
+ return name.lower().replace("_", " ").replace("-", " ").strip()
192
+
193
+ ref_key_normalized = normalize_name(ref_key)
194
+
195
+ # Direct match attempts: try ref_key as-is with each extension
196
+ for ext in extensions:
197
+ # Try exact match
198
+ candidate = os.path.join(base_dir, f"{ref_key}{ext}")
199
+ if os.path.isfile(candidate):
200
+ return candidate
201
+
202
+ # Try with uppercase extension
203
+ candidate_upper = os.path.join(base_dir, f"{ref_key}{ext.upper()}")
204
+ if os.path.isfile(candidate_upper):
205
+ return candidate_upper
206
+
207
+ # Flexible matching: search directory for case-insensitive, separator-flexible match
208
+ if os.path.isdir(base_dir):
209
+ for filename in os.listdir(base_dir):
210
+ name_without_ext, ext = os.path.splitext(filename)
211
+
212
+ # Check if extension is supported
213
+ if ext.lower() not in extensions:
214
+ continue
215
+
216
+ # Normalize and compare
217
+ filename_normalized = normalize_name(name_without_ext)
218
+
219
+ # Exact normalized match
220
+ if filename_normalized == ref_key_normalized:
221
+ return os.path.join(base_dir, filename)
222
+
223
+ # Also try matching with underscores replaced by spaces and vice versa
224
+ ref_key_variants = [
225
+ ref_key.lower(),
226
+ ref_key.lower().replace("_", " "),
227
+ ref_key.lower().replace(" ", "_"),
228
+ ref_key.lower().replace("-", " "),
229
+ ref_key.lower().replace(" ", "-"),
230
+ ]
231
+
232
+ if name_without_ext.lower() in ref_key_variants:
233
+ return os.path.join(base_dir, filename)
234
+
235
+ return None
236
+
237
+
238
+ def resolve_references(ref_character_key: Optional[str], ref_location_key: Optional[str]) -> Dict[str, Optional[str]]:
239
+ """
240
+ Resolve character and location reference keys to actual image paths.
241
+
242
+ Returns:
243
+ Dictionary with 'character' and 'location' paths (or None if not found)
244
+ """
245
+ return {
246
+ "character": find_reference_image(CHAR_DIR, ref_character_key),
247
+ "location": find_reference_image(LOC_DIR, ref_location_key)
248
+ }
249
+
250
+ # =============================================================================
251
+ # TEXT-TO-IMAGE GENERATION
252
+ # =============================================================================
253
+ def generate_mock_image(prompt: str, scene_id: str, variant: str,
254
+ ref_images: Dict[str, Optional[str]] = None) -> str:
255
+ """
256
+ Generate a mock/placeholder image when Vertex AI is unavailable.
257
+ Creates a visually distinct placeholder with scene info.
258
+ """
259
+ # Create a vibrant placeholder image
260
+ width, height = 1080, 1920
261
+
262
+ # Use different colors for A vs B variants
263
+ if variant == "A":
264
+ bg_color = (45, 85, 135) # Deep blue
265
+ accent_color = (100, 180, 255) # Light blue
266
+ else:
267
+ bg_color = (95, 55, 115) # Deep purple
268
+ accent_color = (200, 150, 255) # Light purple
269
+
270
+ img = Image.new('RGB', (width, height), bg_color)
271
+ draw = ImageDraw.Draw(img)
272
+
273
+ # Add visual elements
274
+ # Gradient-like effect with rectangles
275
+ for i in range(0, height, 40):
276
+ alpha = int(255 * (1 - i / height))
277
+ color = tuple(min(255, c + 20) for c in bg_color)
278
+ draw.rectangle([0, i, width, i + 20], fill=color)
279
+
280
+ # Draw center panel
281
+ panel_margin = 80
282
+ panel_top = height // 3
283
+ panel_bottom = 2 * height // 3
284
+ draw.rectangle(
285
+ [panel_margin, panel_top, width - panel_margin, panel_bottom],
286
+ fill=(30, 30, 40),
287
+ outline=accent_color,
288
+ width=3
289
+ )
290
+
291
+ # Add text info
292
+ try:
293
+ font_large = ImageFont.truetype("/System/Library/Fonts/Helvetica.ttc", 48)
294
+ font_medium = ImageFont.truetype("/System/Library/Fonts/Helvetica.ttc", 32)
295
+ font_small = ImageFont.truetype("/System/Library/Fonts/Helvetica.ttc", 24)
296
+ except:
297
+ font_large = ImageFont.load_default()
298
+ font_medium = font_large
299
+ font_small = font_large
300
+
301
+ # Title
302
+ title = f"🎨 VARIANT {variant}"
303
+ draw.text((width // 2, panel_top + 60), title, fill=accent_color, font=font_large, anchor="mm")
304
+
305
+ # Scene ID
306
+ draw.text((width // 2, panel_top + 130), f"Scene: {scene_id}", fill=(200, 200, 200), font=font_medium, anchor="mm")
307
+
308
+ # Prompt preview (truncated)
309
+ prompt_preview = prompt[:60] + "..." if len(prompt) > 60 else prompt
310
+ draw.text((width // 2, panel_top + 200), prompt_preview, fill=(150, 150, 150), font=font_small, anchor="mm")
311
+
312
+ # Reference info
313
+ ref_info = []
314
+ if ref_images:
315
+ if ref_images.get("character"):
316
+ ref_info.append(f"📍 Char: {os.path.basename(ref_images['character'])}")
317
+ if ref_images.get("location"):
318
+ ref_info.append(f"📍 Loc: {os.path.basename(ref_images['location'])}")
319
+
320
+ if ref_info:
321
+ y_offset = panel_top + 280
322
+ for info in ref_info:
323
+ draw.text((width // 2, y_offset), info, fill=(180, 180, 180), font=font_small, anchor="mm")
324
+ y_offset += 40
325
+
326
+ # Mock label
327
+ draw.text((width // 2, panel_bottom - 50), "[ MOCK IMAGE - Vertex AI Unavailable ]",
328
+ fill=(100, 100, 100), font=font_small, anchor="mm")
329
+
330
+ # Save image
331
+ output_path = os.path.join(OUTPUT_DIR_IMG, f"{scene_id}_{variant}_{uuid.uuid4().hex[:8]}.png")
332
+ img.save(output_path, "PNG")
333
+
334
+ return output_path
335
+
336
+
337
+ def generate_t2i(prompt: str, scene_id: str, variant: str,
338
+ ref_images: Dict[str, Optional[str]] = None) -> Optional[str]:
339
+ """
340
+ Generate an image from text prompt, optionally using reference images.
341
+
342
+ Args:
343
+ prompt: The t2i_prompt text
344
+ scene_id: Scene identifier for naming
345
+ variant: "A" or "B" for the variant
346
+ ref_images: Dict with 'character' and 'location' paths
347
+
348
+ Returns:
349
+ Path to generated image, or None on failure
350
+ """
351
+ if not VERTEX_AI_AVAILABLE or not VERTEX_API_KEY:
352
+ # Use mock generation when Vertex AI is unavailable
353
+ return generate_mock_image(prompt, scene_id, variant, ref_images)
354
+
355
+ try:
356
+ import requests
357
+ import base64
358
+
359
+ # Build enhanced prompt for Kurzgesagt style
360
+ full_prompt = f"Kurzgesagt style, 2D flat vector animation, vibrant colors, minimalist design, {prompt}"
361
+
362
+ print(f"🎨 Generating image via Vertex AI Imagen for {scene_id}_{variant}...")
363
+
364
+ # Use Imagen 3 via Vertex AI Express REST API
365
+ url = f"https://aiplatform.googleapis.com/v1/publishers/google/models/imagen-3.0-generate-002:predict?key={VERTEX_API_KEY}"
366
+
367
+ payload = {
368
+ "instances": [{"prompt": full_prompt}],
369
+ "parameters": {
370
+ "sampleCount": 1,
371
+ "aspectRatio": "9:16"
372
+ }
373
+ }
374
+
375
+ response = requests.post(url, json=payload, timeout=120)
376
+
377
+ if response.status_code == 200:
378
+ data = response.json()
379
+ predictions = data.get('predictions', [])
380
+
381
+ if predictions and 'bytesBase64Encoded' in predictions[0]:
382
+ # Decode and save image
383
+ img_data = base64.b64decode(predictions[0]['bytesBase64Encoded'])
384
+ output_path = os.path.join(OUTPUT_DIR_IMG, f"{scene_id}_{variant}_{uuid.uuid4().hex[:8]}.png")
385
+
386
+ with open(output_path, 'wb') as f:
387
+ f.write(img_data)
388
+
389
+ print(f"✅ Image generated: {output_path}")
390
+ return output_path
391
+ else:
392
+ print(f"⚠️ Unexpected response format from Imagen API")
393
+ else:
394
+ print(f"❌ Imagen API error: {response.status_code} - {response.text[:200]}")
395
+
396
+ except Exception as e:
397
+ print(f"❌ Vertex AI generation failed: {e}")
398
+
399
+ # Fallback to mock on any failure
400
+ print("⚠️ Falling back to mock image generation")
401
+ return generate_mock_image(prompt, scene_id, variant, ref_images)
402
+
403
+ # =============================================================================
404
+ # MILESTONE 2: IMAGE-TO-VIDEO (I2V) GENERATION
405
+ # =============================================================================
406
+
407
+ def apply_camera_motion(clip, camera_motion: str, camera_type: str, duration: float):
408
+ """
409
+ Apply camera motion effects to an ImageClip.
410
+
411
+ Args:
412
+ clip: MoviePy ImageClip
413
+ camera_motion: Type of motion (zoom-in, zoom-out, pan-left, pan-right, tilt-up, tilt-down)
414
+ camera_type: Camera framing (wide, medium, close-up) - affects motion intensity
415
+ duration: Clip duration in seconds
416
+
417
+ Returns:
418
+ Modified clip with camera motion applied
419
+ """
420
+ if not MOVIEPY_AVAILABLE:
421
+ return clip
422
+
423
+ # Motion intensity based on camera type
424
+ intensity_map = {
425
+ "wide": 0.08,
426
+ "medium": 0.12,
427
+ "close-up": 0.18,
428
+ "closeup": 0.18,
429
+ }
430
+ intensity = intensity_map.get(camera_type.lower(), 0.10)
431
+
432
+ motion = camera_motion.lower().replace("_", "-").replace(" ", "-")
433
+
434
+ w, h = clip.size
435
+
436
+ # MoviePy 2.x uses resized() instead of resize()
437
+ # Check which method is available
438
+ resize_method = getattr(clip, 'resized', None) or getattr(clip, 'resize', None)
439
+
440
+ if motion in ["zoom-in", "zoomin"]:
441
+ # Gradual zoom in effect
442
+ def zoom_in(t):
443
+ scale = 1 + (intensity * t / duration)
444
+ return scale
445
+
446
+ if resize_method:
447
+ return resize_method(zoom_in).with_position(('center', 'center'))
448
+ return clip
449
+
450
+ elif motion in ["zoom-out", "zoomout"]:
451
+ # Start zoomed in, zoom out
452
+ def zoom_out(t):
453
+ scale = (1 + intensity) - (intensity * t / duration)
454
+ return scale
455
+
456
+ if resize_method:
457
+ return resize_method(zoom_out).with_position(('center', 'center'))
458
+ return clip
459
+
460
+ elif motion in ["pan-left", "panleft"]:
461
+ # Pan from right to left
462
+ def pan_left(t):
463
+ x_offset = int((intensity * w) * (1 - t / duration))
464
+ return (x_offset, 'center')
465
+
466
+ set_pos = getattr(clip, 'with_position', None) or getattr(clip, 'set_position', None)
467
+ return set_pos(pan_left) if set_pos else clip
468
+
469
+ elif motion in ["pan-right", "panright"]:
470
+ # Pan from left to right
471
+ def pan_right(t):
472
+ x_offset = -int((intensity * w) * (1 - t / duration))
473
+ return (x_offset, 'center')
474
+
475
+ set_pos = getattr(clip, 'with_position', None) or getattr(clip, 'set_position', None)
476
+ return set_pos(pan_right) if set_pos else clip
477
+
478
+ elif motion in ["tilt-up", "tiltup"]:
479
+ # Tilt from bottom to top
480
+ def tilt_up(t):
481
+ y_offset = int((intensity * h) * (1 - t / duration))
482
+ return ('center', y_offset)
483
+
484
+ return clip.set_position(tilt_up)
485
+
486
+ elif motion in ["tilt-down", "tiltdown"]:
487
+ # Tilt from top to bottom
488
+ def tilt_down(t):
489
+ y_offset = -int((intensity * h) * (1 - t / duration))
490
+ return ('center', y_offset)
491
+
492
+ return clip.set_position(tilt_down)
493
+
494
+ else:
495
+ # Default: subtle zoom-in
496
+ def default_zoom(t):
497
+ scale = 1 + (0.05 * t / duration)
498
+ return scale
499
+
500
+ return clip.resize(default_zoom).set_position(('center', 'center'))
501
+
502
+
503
+ def generate_video_from_image(
504
+ image_path: str,
505
+ camera_type: str = "medium",
506
+ camera_motion: str = "zoom-in",
507
+ duration: float = DEFAULT_VIDEO_DURATION,
508
+ scene_id: str = "scene"
509
+ ) -> Optional[str]:
510
+ """
511
+ Generate a video clip from a static image with camera motion.
512
+
513
+ MOCK MODE: Uses MoviePy to create simple video with camera motion effects.
514
+ REAL MODE: Would use Vertex AI Video Generation API (when available).
515
+
516
+ Args:
517
+ image_path: Path to the source image
518
+ camera_type: Wide, Medium, or Close-up
519
+ camera_motion: Zoom-in, Zoom-out, Pan-left, Pan-right, Tilt-up, Tilt-down
520
+ duration: Video duration in seconds
521
+ scene_id: Scene identifier for output naming
522
+
523
+ Returns:
524
+ Path to generated video file, or None on failure
525
+ """
526
+ if not MOVIEPY_AVAILABLE:
527
+ print("❌ MoviePy not available — cannot generate video")
528
+ return None
529
+
530
+ if not image_path or not os.path.isfile(image_path):
531
+ print(f"❌ Image not found: {image_path}")
532
+ return None
533
+
534
+ # Check if real Vertex AI Video is available
535
+ if video_model is not None:
536
+ # Future: Use real Vertex AI Video Generation
537
+ # return generate_vertex_video(image_path, camera_type, camera_motion, duration)
538
+ pass
539
+
540
+ # MOCK MODE: Generate video using MoviePy
541
+ print(f"📹 Generating mock video for {scene_id} (duration: {duration}s, motion: {camera_motion})")
542
+
543
+ try:
544
+ # Load and prepare the image
545
+ img = Image.open(image_path)
546
+
547
+ # Resize/crop to 9:16 aspect ratio if needed
548
+ target_ratio = VIDEO_WIDTH / VIDEO_HEIGHT
549
+ current_ratio = img.width / img.height
550
+
551
+ if current_ratio > target_ratio:
552
+ # Image is wider - crop width
553
+ new_width = int(img.height * target_ratio)
554
+ left = (img.width - new_width) // 2
555
+ img = img.crop((left, 0, left + new_width, img.height))
556
+ elif current_ratio < target_ratio:
557
+ # Image is taller - crop height
558
+ new_height = int(img.width / target_ratio)
559
+ top = (img.height - new_height) // 2
560
+ img = img.crop((0, top, img.width, top + new_height))
561
+
562
+ # Resize to target dimensions (slightly larger for motion headroom)
563
+ scale_factor = 1.2 # Extra room for camera motion
564
+ scaled_width = int(VIDEO_WIDTH * scale_factor)
565
+ scaled_height = int(VIDEO_HEIGHT * scale_factor)
566
+ img = img.resize((scaled_width, scaled_height), Image.Resampling.LANCZOS)
567
+
568
+ # Convert to numpy array for MoviePy
569
+ img_array = np.array(img)
570
+
571
+ # Create ImageClip
572
+ clip = ImageClip(img_array, duration=duration)
573
+
574
+ # Apply camera motion
575
+ clip = apply_camera_motion(clip, camera_motion, camera_type, duration)
576
+
577
+ # Create a container clip at target resolution
578
+ container = ColorClip(size=(VIDEO_WIDTH, VIDEO_HEIGHT), color=(0, 0, 0), duration=duration)
579
+
580
+ # Composite the image onto the container
581
+ final_clip = CompositeVideoClip([container, clip.set_position('center')])
582
+ final_clip = final_clip.set_duration(duration)
583
+
584
+ # Generate output path
585
+ output_filename = f"{scene_id}_video_{uuid.uuid4().hex[:8]}.mp4"
586
+ output_path = os.path.join(OUTPUT_DIR_VIDEO, output_filename)
587
+
588
+ # Write video file
589
+ final_clip.write_videofile(
590
+ output_path,
591
+ fps=DEFAULT_FPS,
592
+ codec='libx264',
593
+ audio=False, # Audio will be added separately
594
+ preset='medium',
595
+ verbose=False,
596
+ logger=None
597
+ )
598
+
599
+ # Clean up
600
+ final_clip.close()
601
+ clip.close()
602
+ container.close()
603
+
604
+ print(f"✅ Video generated: {output_path}")
605
+ return output_path
606
+
607
+ except Exception as e:
608
+ print(f"❌ Video generation failed: {e}")
609
+ import traceback
610
+ traceback.print_exc()
611
+ return None
612
+
613
+
614
+ # =============================================================================
615
+ # MILESTONE 2: ROLE-BASED AUDIO ENGINE
616
+ # =============================================================================
617
+
618
+ def generate_tone(frequency: float, duration: float, sample_rate: int = 44100, volume: float = 0.3) -> np.ndarray:
619
+ """Generate a simple sine wave tone."""
620
+ t = np.linspace(0, duration, int(sample_rate * duration), endpoint=False)
621
+ wave = volume * np.sin(2 * np.pi * frequency * t)
622
+ # Fade in/out to avoid clicks
623
+ fade_samples = int(sample_rate * 0.05)
624
+ if len(wave) > fade_samples * 2:
625
+ fade_in = np.linspace(0, 1, fade_samples)
626
+ fade_out = np.linspace(1, 0, fade_samples)
627
+ wave[:fade_samples] *= fade_in
628
+ wave[-fade_samples:] *= fade_out
629
+ return wave
630
+
631
+
632
+ def generate_voiceover_audio(text: str, duration: float, scene_id: str) -> Optional[str]:
633
+ """
634
+ Generate voiceover audio track.
635
+
636
+ MOCK MODE: Creates a placeholder audio with subtle tone.
637
+ REAL MODE: Would use Text-to-Speech API (Google TTS, ElevenLabs, etc.)
638
+
639
+ Args:
640
+ text: Voiceover text (used for duration estimation in real mode)
641
+ duration: Target duration in seconds
642
+ scene_id: Scene identifier for naming
643
+
644
+ Returns:
645
+ Path to audio file, or None on failure
646
+ """
647
+ if not MOVIEPY_AVAILABLE:
648
+ return None
649
+
650
+ print(f"🎙️ Generating mock voiceover for {scene_id}")
651
+
652
+ try:
653
+ sample_rate = 44100
654
+
655
+ # Create subtle background tone (mock voiceover)
656
+ # In real mode, this would be TTS output
657
+ t = np.linspace(0, duration, int(sample_rate * duration), endpoint=False)
658
+
659
+ # Create a "speech-like" pattern with varying frequencies
660
+ wave = np.zeros_like(t)
661
+
662
+ # Add subtle harmonics that simulate speech rhythm
663
+ base_freq = 120 # Typical male voice fundamental
664
+ for harmonic in [1, 2, 3]:
665
+ freq = base_freq * harmonic
666
+ amplitude = 0.1 / harmonic
667
+ # Add some variation
668
+ modulation = 1 + 0.3 * np.sin(2 * np.pi * 3 * t) # 3Hz modulation
669
+ wave += amplitude * modulation * np.sin(2 * np.pi * freq * t)
670
+
671
+ # Normalize and apply envelope
672
+ wave = wave / np.max(np.abs(wave)) * 0.3
673
+
674
+ # Apply speech-like envelope (pauses)
675
+ envelope = np.ones_like(t)
676
+ pause_interval = int(sample_rate * 0.5) # Pause every 0.5s
677
+ for i in range(0, len(t), pause_interval):
678
+ end = min(i + int(sample_rate * 0.1), len(t))
679
+ envelope[i:end] *= np.linspace(0.3, 1, end - i)
680
+
681
+ wave *= envelope
682
+
683
+ # Convert to stereo
684
+ stereo = np.column_stack([wave, wave])
685
+
686
+ # Create audio clip and save
687
+ audio_clip = AudioArrayClip(stereo, fps=sample_rate)
688
+
689
+ output_filename = f"{scene_id}_vo_{uuid.uuid4().hex[:8]}.mp3"
690
+ output_path = os.path.join(OUTPUT_DIR_AUDIO, output_filename)
691
+
692
+ # MoviePy 2.x compatibility - try different parameter combinations
693
+ try:
694
+ audio_clip.write_audiofile(output_path, fps=sample_rate, logger=None)
695
+ except TypeError:
696
+ audio_clip.write_audiofile(output_path, fps=sample_rate)
697
+ audio_clip.close()
698
+
699
+ print(f"✅ Voiceover generated: {output_path}")
700
+ return output_path
701
+
702
+ except Exception as e:
703
+ print(f"❌ Voiceover generation failed: {e}")
704
+ return None
705
+
706
+
707
+ def generate_dialogue_audio(
708
+ text: str,
709
+ character: str,
710
+ duration: float,
711
+ scene_id: str
712
+ ) -> Optional[str]:
713
+ """
714
+ Generate character dialogue audio.
715
+
716
+ MOCK MODE: Creates character-specific placeholder audio.
717
+ REAL MODE: Would use TTS with voice cloning/selection per character.
718
+
719
+ Args:
720
+ text: Dialogue text
721
+ character: Character name (for voice selection)
722
+ duration: Target duration
723
+ scene_id: Scene identifier
724
+
725
+ Returns:
726
+ Path to audio file, or None on failure
727
+ """
728
+ if not MOVIEPY_AVAILABLE:
729
+ return None
730
+
731
+ print(f"💬 Generating mock dialogue for {scene_id} (character: {character})")
732
+
733
+ try:
734
+ sample_rate = 44100
735
+ t = np.linspace(0, duration, int(sample_rate * duration), endpoint=False)
736
+
737
+ # Different base frequencies for different characters
738
+ # This simulates character-specific voices
739
+ char_lower = character.lower() if character else "default"
740
+
741
+ if "child" in char_lower or "daughter" in char_lower or "girl" in char_lower:
742
+ base_freq = 250 # Higher pitch for children
743
+ elif "woman" in char_lower or "female" in char_lower or "mother" in char_lower:
744
+ base_freq = 200 # Female voice
745
+ elif "cat" in char_lower or "animal" in char_lower:
746
+ base_freq = 400 # Higher pitch for animals
747
+ else:
748
+ base_freq = 130 # Default male voice
749
+
750
+ # Generate speech-like audio
751
+ wave = np.zeros_like(t)
752
+ for harmonic in [1, 2, 3, 4]:
753
+ freq = base_freq * harmonic
754
+ amplitude = 0.15 / harmonic
755
+ wave += amplitude * np.sin(2 * np.pi * freq * t)
756
+
757
+ # Add vibrato for natural feel
758
+ vibrato = 1 + 0.02 * np.sin(2 * np.pi * 5 * t)
759
+ wave *= vibrato
760
+
761
+ # Normalize
762
+ wave = wave / np.max(np.abs(wave)) * 0.4
763
+
764
+ # Stereo
765
+ stereo = np.column_stack([wave, wave])
766
+
767
+ audio_clip = AudioArrayClip(stereo, fps=sample_rate)
768
+
769
+ output_filename = f"{scene_id}_dialogue_{character}_{uuid.uuid4().hex[:8]}.mp3"
770
+ output_path = os.path.join(OUTPUT_DIR_AUDIO, output_filename)
771
+
772
+ # MoviePy 2.x compatibility
773
+ try:
774
+ audio_clip.write_audiofile(output_path, fps=sample_rate, logger=None)
775
+ except TypeError:
776
+ audio_clip.write_audiofile(output_path, fps=sample_rate)
777
+ audio_clip.close()
778
+
779
+ print(f"✅ Dialogue generated: {output_path}")
780
+ return output_path
781
+
782
+ except Exception as e:
783
+ print(f"❌ Dialogue generation failed: {e}")
784
+ return None
785
+
786
+
787
+ def generate_sfx_audio(
788
+ sfx_type: str,
789
+ duration: float,
790
+ scene_id: str,
791
+ volume: float = 0.2
792
+ ) -> Optional[str]:
793
+ """
794
+ Generate sound effects audio.
795
+
796
+ MOCK MODE: Creates ambient placeholder audio based on environment type.
797
+ REAL MODE: Would use sound effect library or generation API.
798
+
799
+ Args:
800
+ sfx_type: Type of sound effect (lab, classroom, forest, city, etc.)
801
+ duration: Duration in seconds
802
+ scene_id: Scene identifier
803
+ volume: Volume level (0-1)
804
+
805
+ Returns:
806
+ Path to audio file, or None on failure
807
+ """
808
+ if not MOVIEPY_AVAILABLE:
809
+ return None
810
+
811
+ print(f"🔊 Generating mock SFX for {scene_id} (type: {sfx_type})")
812
+
813
+ try:
814
+ sample_rate = 44100
815
+ t = np.linspace(0, duration, int(sample_rate * duration), endpoint=False)
816
+
817
+ sfx_lower = sfx_type.lower() if sfx_type else "ambient"
818
+
819
+ # Generate different ambient sounds based on environment
820
+ if "lab" in sfx_lower or "hospital" in sfx_lower or "medical" in sfx_lower:
821
+ # Lab/hospital: subtle electronic hum + beeps
822
+ hum = 0.05 * np.sin(2 * np.pi * 60 * t) # 60Hz electrical hum
823
+ # Occasional beeps
824
+ beep_freq = 880
825
+ beeps = np.zeros_like(t)
826
+ beep_interval = int(sample_rate * 2) # Beep every 2 seconds
827
+ for i in range(0, len(t), beep_interval):
828
+ end = min(i + int(sample_rate * 0.1), len(t))
829
+ beeps[i:end] = 0.1 * np.sin(2 * np.pi * beep_freq * np.arange(end - i) / sample_rate)
830
+ wave = hum + beeps
831
+
832
+ elif "classroom" in sfx_lower or "school" in sfx_lower or "class" in sfx_lower:
833
+ # Classroom: subtle ambient murmur
834
+ noise = np.random.randn(len(t)) * 0.02
835
+ # Low-pass filter effect via simple averaging
836
+ wave = np.convolve(noise, np.ones(100) / 100, mode='same')
837
+ # Add occasional pencil/paper sounds (high freq bursts)
838
+ for i in range(0, len(t), int(sample_rate * 3)):
839
+ end = min(i + int(sample_rate * 0.05), len(t))
840
+ wave[i:end] += 0.03 * np.random.randn(end - i)
841
+
842
+ elif "forest" in sfx_lower or "nature" in sfx_lower or "outdoor" in sfx_lower:
843
+ # Forest: wind + birds
844
+ wind = np.random.randn(len(t)) * 0.03
845
+ wind = np.convolve(wind, np.ones(500) / 500, mode='same')
846
+ # Bird chirps
847
+ birds = np.zeros_like(t)
848
+ for i in range(0, len(t), int(sample_rate * 1.5)):
849
+ if np.random.random() > 0.5:
850
+ chirp_len = int(sample_rate * 0.1)
851
+ end = min(i + chirp_len, len(t))
852
+ chirp_freq = np.random.uniform(2000, 4000)
853
+ birds[i:end] = 0.05 * np.sin(2 * np.pi * chirp_freq * np.arange(end - i) / sample_rate)
854
+ wave = wind + birds
855
+
856
+ elif "home" in sfx_lower or "house" in sfx_lower or "cozy" in sfx_lower:
857
+ # Home: very subtle ambient
858
+ wave = np.random.randn(len(t)) * 0.01
859
+ wave = np.convolve(wave, np.ones(200) / 200, mode='same')
860
+
861
+ else:
862
+ # Default: generic ambient
863
+ wave = np.random.randn(len(t)) * 0.02
864
+ wave = np.convolve(wave, np.ones(300) / 300, mode='same')
865
+
866
+ # Apply volume
867
+ wave = wave * volume
868
+
869
+ # Normalize if needed
870
+ max_val = np.max(np.abs(wave))
871
+ if max_val > 0:
872
+ wave = wave / max_val * volume * 0.3
873
+
874
+ # Stereo
875
+ stereo = np.column_stack([wave, wave])
876
+
877
+ audio_clip = AudioArrayClip(stereo, fps=sample_rate)
878
+
879
+ output_filename = f"{scene_id}_sfx_{uuid.uuid4().hex[:8]}.mp3"
880
+ output_path = os.path.join(OUTPUT_DIR_AUDIO, output_filename)
881
+
882
+ # MoviePy 2.x compatibility
883
+ try:
884
+ audio_clip.write_audiofile(output_path, fps=sample_rate, logger=None)
885
+ except TypeError:
886
+ audio_clip.write_audiofile(output_path, fps=sample_rate)
887
+ audio_clip.close()
888
+
889
+ print(f"✅ SFX generated: {output_path}")
890
+ return output_path
891
+
892
+ except Exception as e:
893
+ print(f"❌ SFX generation failed: {e}")
894
+ return None
895
+
896
+
897
+ def generate_audio_track(scene_data: Dict[str, Any], duration: float, scene_id: str) -> Dict[str, Optional[str]]:
898
+ """
899
+ Generate all audio tracks for a scene.
900
+
901
+ Supports 3 audio layers:
902
+ - Voiceover (VO): Narrator voice
903
+ - Dialogue: Character-specific voices
904
+ - SFX: Ambient/environmental sounds
905
+
906
+ Args:
907
+ scene_data: Scene data with audio fields (voiceover, dialogue_text, sound_effect, character)
908
+ duration: Target duration in seconds
909
+ scene_id: Scene identifier
910
+
911
+ Returns:
912
+ Dictionary with paths to generated audio files: {vo, dialogue, sfx}
913
+ """
914
+ audio_paths = {
915
+ "vo": None,
916
+ "dialogue": None,
917
+ "sfx": None
918
+ }
919
+
920
+ # Generate voiceover if present
921
+ voiceover_text = scene_data.get("voiceover") or scene_data.get("vo_text")
922
+ if voiceover_text:
923
+ audio_paths["vo"] = generate_voiceover_audio(voiceover_text, duration, scene_id)
924
+
925
+ # Generate dialogue if present
926
+ dialogue_text = scene_data.get("dialogue_text") or scene_data.get("dialogue")
927
+ character = scene_data.get("character", "narrator")
928
+ if dialogue_text:
929
+ audio_paths["dialogue"] = generate_dialogue_audio(dialogue_text, character, duration, scene_id)
930
+
931
+ # Generate SFX if present
932
+ sfx_type = scene_data.get("sound_effect") or scene_data.get("sfx") or scene_data.get("ambient")
933
+ if sfx_type:
934
+ audio_paths["sfx"] = generate_sfx_audio(sfx_type, duration, scene_id)
935
+
936
+ return audio_paths
937
+
938
+
939
+ # =============================================================================
940
+ # MILESTONE 2: AUDIO + VIDEO SYNCHRONIZATION
941
+ # =============================================================================
942
+
943
+ def combine_audio_video(
944
+ video_path: str,
945
+ audio_paths: Dict[str, Optional[str]],
946
+ scene_id: str
947
+ ) -> Optional[str]:
948
+ """
949
+ Combine video with audio tracks to create final clip.
950
+
951
+ Merges:
952
+ - Video track
953
+ - Voiceover (full volume)
954
+ - Dialogue (full volume)
955
+ - SFX (reduced volume, background)
956
+
957
+ Args:
958
+ video_path: Path to video file (without audio)
959
+ audio_paths: Dictionary with {vo, dialogue, sfx} audio file paths
960
+ scene_id: Scene identifier
961
+
962
+ Returns:
963
+ Path to final video with audio, or None on failure
964
+ """
965
+ if not MOVIEPY_AVAILABLE:
966
+ print("❌ MoviePy not available — cannot combine audio/video")
967
+ return None
968
+
969
+ if not video_path or not os.path.isfile(video_path):
970
+ print(f"❌ Video file not found: {video_path}")
971
+ return None
972
+
973
+ print(f"🎬 Combining audio and video for {scene_id}")
974
+
975
+ try:
976
+ # MoviePy 2.x imports
977
+ try:
978
+ from moviepy import VideoFileClip, AudioFileClip, CompositeAudioClip
979
+ except ImportError:
980
+ from moviepy.editor import VideoFileClip, AudioFileClip, CompositeAudioClip
981
+
982
+ # Load video
983
+ video = VideoFileClip(video_path)
984
+ video_duration = video.duration
985
+
986
+ # Collect audio clips
987
+ audio_clips = []
988
+
989
+ # Add voiceover (full volume)
990
+ if audio_paths.get("vo") and os.path.isfile(audio_paths["vo"]):
991
+ vo_clip = AudioFileClip(audio_paths["vo"])
992
+ # Adjust duration to match video
993
+ if vo_clip.duration > video_duration:
994
+ vo_clip = vo_clip.subclip(0, video_duration)
995
+ audio_clips.append(vo_clip)
996
+
997
+ # Add dialogue (full volume)
998
+ if audio_paths.get("dialogue") and os.path.isfile(audio_paths["dialogue"]):
999
+ dialogue_clip = AudioFileClip(audio_paths["dialogue"])
1000
+ if dialogue_clip.duration > video_duration:
1001
+ dialogue_clip = dialogue_clip.subclip(0, video_duration)
1002
+ audio_clips.append(dialogue_clip)
1003
+
1004
+ # Add SFX (reduced volume - background)
1005
+ if audio_paths.get("sfx") and os.path.isfile(audio_paths["sfx"]):
1006
+ sfx_clip = AudioFileClip(audio_paths["sfx"])
1007
+ if sfx_clip.duration > video_duration:
1008
+ sfx_clip = sfx_clip.subclip(0, video_duration)
1009
+ sfx_clip = sfx_clip.volumex(0.3) # Reduce SFX volume
1010
+ audio_clips.append(sfx_clip)
1011
+
1012
+ # Combine audio tracks
1013
+ if audio_clips:
1014
+ combined_audio = CompositeAudioClip(audio_clips)
1015
+ final_video = video.set_audio(combined_audio)
1016
+ else:
1017
+ # No audio - use video as-is
1018
+ final_video = video
1019
+
1020
+ # Generate output path
1021
+ output_filename = f"{scene_id}_final_{uuid.uuid4().hex[:8]}.mp4"
1022
+ output_path = os.path.join(OUTPUT_DIR_VIDEO, output_filename)
1023
+
1024
+ # Write final video
1025
+ final_video.write_videofile(
1026
+ output_path,
1027
+ fps=DEFAULT_FPS,
1028
+ codec='libx264',
1029
+ audio_codec='aac',
1030
+ preset='medium',
1031
+ verbose=False,
1032
+ logger=None
1033
+ )
1034
+
1035
+ # Clean up
1036
+ final_video.close()
1037
+ video.close()
1038
+ for clip in audio_clips:
1039
+ clip.close()
1040
+
1041
+ print(f"✅ Final clip generated: {output_path}")
1042
+ return output_path
1043
+
1044
+ except Exception as e:
1045
+ print(f"❌ Audio/video combination failed: {e}")
1046
+ import traceback
1047
+ traceback.print_exc()
1048
+ return None
1049
+
1050
+
1051
+ # =============================================================================
1052
+ # JSON PARSING (Milestone-1 + 2 Fields)
1053
+ # =============================================================================
1054
+ def parse_json_script(json_text: str) -> Tuple[List[Dict[str, Any]], str]:
1055
+ """
1056
+ Parse the JSON script and extract Milestone-1 + Milestone-2 fields.
1057
+
1058
+ Milestone 1 fields:
1059
+ - scene_id
1060
+ - ref_character_key
1061
+ - ref_location_key
1062
+ - t2i_prompt
1063
+
1064
+ Milestone 2 fields (new):
1065
+ - camera_type: Wide, Medium, Close-up
1066
+ - camera_motion: Zoom-in, Pan, Tilt, etc.
1067
+ - duration_target: Video duration in seconds
1068
+ - voiceover: Narrator text
1069
+ - dialogue_text: Character dialogue
1070
+ - character: Character name for dialogue voice
1071
+ - sound_effect: Ambient/SFX type
1072
+
1073
+ Returns:
1074
+ Tuple of (scenes_list, status_message)
1075
+ """
1076
+ # Type check - ensure input is a string
1077
+ if not isinstance(json_text, str):
1078
+ return [], "❌ Invalid input type: expected string"
1079
+
1080
+ if not json_text.strip():
1081
+ return [], "❌ No JSON provided"
1082
+
1083
+ try:
1084
+ data = json.loads(json_text)
1085
+ except json.JSONDecodeError as e:
1086
+ return [], f"❌ Invalid JSON: {e}"
1087
+
1088
+ # Handle both formats: direct array or {"scenes": [...]}
1089
+ if isinstance(data, list):
1090
+ raw_scenes = data
1091
+ elif isinstance(data, dict):
1092
+ raw_scenes = data.get("scenes", [])
1093
+ else:
1094
+ return [], "❌ JSON must be an array or object with 'scenes' array"
1095
+
1096
+ if not raw_scenes:
1097
+ return [], "❌ No scenes found in JSON"
1098
+
1099
+ parsed_scenes = []
1100
+ for idx, scene in enumerate(raw_scenes):
1101
+ scene_id = scene.get("scene_id") or scene.get("id") or f"scene_{idx + 1}"
1102
+
1103
+ parsed = {
1104
+ # Milestone 1 fields
1105
+ "scene_id": scene_id,
1106
+ "ref_character_key": scene.get("ref_character_key"),
1107
+ "ref_location_key": scene.get("ref_location_key"),
1108
+ "t2i_prompt": scene.get("t2i_prompt") or scene.get("prompt") or "",
1109
+
1110
+ # Milestone 2 fields - Video
1111
+ "camera_type": scene.get("camera_type", "medium"),
1112
+ "camera_motion": scene.get("camera_motion", "zoom-in"),
1113
+ "duration_target": float(scene.get("duration_target", DEFAULT_VIDEO_DURATION)),
1114
+
1115
+ # Milestone 2 fields - Audio
1116
+ "voiceover": scene.get("voiceover") or scene.get("vo_text"),
1117
+ "dialogue_text": scene.get("dialogue_text") or scene.get("dialogue"),
1118
+ "character": scene.get("character", "narrator"),
1119
+ "sound_effect": scene.get("sound_effect") or scene.get("sfx") or scene.get("ambient"),
1120
+ }
1121
+ parsed_scenes.append(parsed)
1122
+
1123
+ return parsed_scenes, f"✅ Parsed {len(parsed_scenes)} scene(s) successfully"
1124
+
1125
+ # =============================================================================
1126
+ # STATE MANAGEMENT (Milestone 1 + 2)
1127
+ # =============================================================================
1128
+ def create_initial_state() -> Dict[str, Any]:
1129
+ """Create the initial state structure for Milestone 1 + 2."""
1130
+ return {
1131
+ "scenes": [], # Parsed scene data
1132
+ "scene_states": {}, # Per-scene state (see get_scene_state for structure)
1133
+ "current_scene_idx": 0 # Currently viewed scene index
1134
+ }
1135
+
1136
+
1137
+ def get_scene_state(state: Dict, scene_id: str) -> Dict:
1138
+ """
1139
+ Get or create state for a specific scene.
1140
+
1141
+ State structure includes:
1142
+ - Milestone 1: image_a, image_b, selected_image, status (image approval)
1143
+ - Milestone 2: video_path, audio_paths, clip_status, duration
1144
+ """
1145
+ if scene_id not in state["scene_states"]:
1146
+ state["scene_states"][scene_id] = {
1147
+ # Milestone 1 - Image approval
1148
+ "image_a": None,
1149
+ "image_b": None,
1150
+ "selected_image": None,
1151
+ "status": "pending", # pending | approved (for images)
1152
+
1153
+ # Milestone 2 - Video/Audio
1154
+ "video_path": None, # Path to generated video (no audio)
1155
+ "audio_paths": { # Paths to audio tracks
1156
+ "vo": None,
1157
+ "dialogue": None,
1158
+ "sfx": None
1159
+ },
1160
+ "final_clip_path": None, # Path to final video with audio
1161
+ "clip_status": "pending", # pending | generated | approved
1162
+ "duration": DEFAULT_VIDEO_DURATION
1163
+ }
1164
+ else:
1165
+ # Ensure Milestone 2 fields exist for existing states
1166
+ scene_state = state["scene_states"][scene_id]
1167
+ if "video_path" not in scene_state:
1168
+ scene_state["video_path"] = None
1169
+ if "audio_paths" not in scene_state:
1170
+ scene_state["audio_paths"] = {"vo": None, "dialogue": None, "sfx": None}
1171
+ if "final_clip_path" not in scene_state:
1172
+ scene_state["final_clip_path"] = None
1173
+ if "clip_status" not in scene_state:
1174
+ scene_state["clip_status"] = "pending"
1175
+ if "duration" not in scene_state:
1176
+ scene_state["duration"] = DEFAULT_VIDEO_DURATION
1177
+
1178
+ return state["scene_states"][scene_id]
1179
+
1180
+ # =============================================================================
1181
+ # WORKFLOW FUNCTIONS
1182
+ # =============================================================================
1183
+ def load_and_parse_json(json_text: str, state: Dict) -> Tuple[Dict, str, gr.update]:
1184
+ """Parse JSON and initialize state for all scenes."""
1185
+ scenes, message = parse_json_script(json_text)
1186
+
1187
+ if not scenes:
1188
+ return state, message, gr.update(choices=[], value=None)
1189
+
1190
+ # Reset state with new scenes
1191
+ state = create_initial_state()
1192
+ state["scenes"] = scenes
1193
+
1194
+ # Initialize state for each scene
1195
+ for scene in scenes:
1196
+ state["scene_states"][scene["scene_id"]] = {
1197
+ "image_a": None,
1198
+ "image_b": None,
1199
+ "selected_image": None,
1200
+ "status": "pending"
1201
+ }
1202
+
1203
+ # Create dropdown choices
1204
+ choices = [f"{i+1}. {s['scene_id']}" for i, s in enumerate(scenes)]
1205
+
1206
+ return state, message, gr.update(choices=choices, value=choices[0] if choices else None)
1207
+
1208
+
1209
+ def get_scenes_preview(state: Dict) -> str:
1210
+ """Generate a markdown preview of all parsed scenes."""
1211
+ if not state or not state.get("scenes"):
1212
+ return "*No scenes loaded*"
1213
+
1214
+ lines = ["### 📋 Parsed Scenes\n"]
1215
+ for i, scene in enumerate(state["scenes"]):
1216
+ scene_state = state["scene_states"].get(scene["scene_id"], {})
1217
+ status_icon = "✅" if scene_state.get("status") == "approved" else "⏳"
1218
+
1219
+ lines.append(f"**{i+1}. {scene['scene_id']}** {status_icon}")
1220
+ lines.append(f" - Prompt: *{scene['t2i_prompt'][:80]}{'...' if len(scene['t2i_prompt']) > 80 else ''}*")
1221
+
1222
+ if scene.get("ref_character_key"):
1223
+ lines.append(f" - Character ref: `{scene['ref_character_key']}`")
1224
+ if scene.get("ref_location_key"):
1225
+ lines.append(f" - Location ref: `{scene['ref_location_key']}`")
1226
+ lines.append("")
1227
+
1228
+ return "\n".join(lines)
1229
+
1230
+
1231
+ def generate_scene_images(state: Dict, scene_selection: str) -> Tuple[Dict, Any, Any, str]:
1232
+ """Generate A/B images for the selected scene."""
1233
+ if not state or not state.get("scenes") or not scene_selection:
1234
+ return state, None, None, "❌ No scene selected"
1235
+
1236
+ # Parse scene index from selection
1237
+ try:
1238
+ idx = int(scene_selection.split(".")[0]) - 1
1239
+ scene = state["scenes"][idx]
1240
+ except (ValueError, IndexError):
1241
+ return state, None, None, "❌ Invalid scene selection"
1242
+
1243
+ scene_id = scene["scene_id"]
1244
+ prompt = scene["t2i_prompt"]
1245
+
1246
+ # Resolve references
1247
+ refs = resolve_references(
1248
+ scene.get("ref_character_key"),
1249
+ scene.get("ref_location_key")
1250
+ )
1251
+
1252
+ # Log reference resolution
1253
+ ref_log = []
1254
+ if scene.get("ref_character_key"):
1255
+ if refs["character"]:
1256
+ ref_log.append(f"✅ Character '{scene['ref_character_key']}' → `{refs['character']}`")
1257
+ else:
1258
+ ref_log.append(f"⚠️ Character '{scene['ref_character_key']}' not found in Characters/")
1259
+
1260
+ if scene.get("ref_location_key"):
1261
+ if refs["location"]:
1262
+ ref_log.append(f"✅ Location '{scene['ref_location_key']}' → `{refs['location']}`")
1263
+ else:
1264
+ ref_log.append(f"⚠️ Location '{scene['ref_location_key']}' not found in Locations/")
1265
+
1266
+ # Generate Image A
1267
+ image_a_path = generate_t2i(prompt, scene_id, "A", refs)
1268
+
1269
+ # Generate Image B
1270
+ image_b_path = generate_t2i(prompt, scene_id, "B", refs)
1271
+
1272
+ # Update state
1273
+ scene_state = get_scene_state(state, scene_id)
1274
+ scene_state["image_a"] = image_a_path
1275
+ scene_state["image_b"] = image_b_path
1276
+ # Keep selected_image if already approved, otherwise clear it
1277
+ if scene_state["status"] != "approved":
1278
+ scene_state["selected_image"] = None
1279
+ scene_state["status"] = "pending"
1280
+
1281
+ # Build status message
1282
+ ref_msg = "\n".join(ref_log) if ref_log else "No references specified"
1283
+ status = f"🎨 **Generated A/B for {scene_id}**\n\n{ref_msg}"
1284
+
1285
+ return state, image_a_path, image_b_path, status
1286
+
1287
+
1288
+ def regenerate_scene_images(state: Dict, scene_selection: str) -> Tuple[Dict, Any, Any, str]:
1289
+ """Regenerate images for ONLY the selected scene (does not affect other scenes)."""
1290
+ return generate_scene_images(state, scene_selection)
1291
+
1292
+
1293
+ def commit_image(state: Dict, scene_selection: str, choice: str) -> Tuple[Dict, str]:
1294
+ """
1295
+ Commit the selected image (A or B) for the scene.
1296
+ This marks the scene as approved and saves the selection to state.
1297
+ """
1298
+ if not state or not state.get("scenes") or not scene_selection:
1299
+ return state, "❌ No scene selected"
1300
+
1301
+ try:
1302
+ idx = int(scene_selection.split(".")[0]) - 1
1303
+ scene = state["scenes"][idx]
1304
+ except (ValueError, IndexError):
1305
+ return state, "❌ Invalid scene selection"
1306
+
1307
+ scene_id = scene["scene_id"]
1308
+ scene_state = get_scene_state(state, scene_id)
1309
+
1310
+ # Get the selected image path
1311
+ if choice == "A":
1312
+ selected = scene_state.get("image_a")
1313
+ else:
1314
+ selected = scene_state.get("image_b")
1315
+
1316
+ if not selected:
1317
+ return state, f"❌ Image {choice} not generated yet"
1318
+
1319
+ # Update state
1320
+ scene_state["selected_image"] = selected
1321
+ scene_state["status"] = "approved"
1322
+
1323
+ return state, f"✅ **Committed Image {choice}** for {scene_id}"
1324
+
1325
+
1326
+ def on_scene_change(state: Dict, scene_selection: str) -> Tuple[Any, Any, str, str]:
1327
+ """Handle scene selection change - load existing images if available."""
1328
+ if not state or not state.get("scenes") or not scene_selection:
1329
+ return None, None, "*Select a scene*", ""
1330
+
1331
+ try:
1332
+ idx = int(scene_selection.split(".")[0]) - 1
1333
+ scene = state["scenes"][idx]
1334
+ except (ValueError, IndexError):
1335
+ return None, None, "*Invalid selection*", ""
1336
+
1337
+ scene_id = scene["scene_id"]
1338
+ scene_state = get_scene_state(state, scene_id)
1339
+
1340
+ image_a = scene_state.get("image_a")
1341
+ image_b = scene_state.get("image_b")
1342
+
1343
+ # Build status
1344
+ status_lines = [f"### 🎬 {scene_id}"]
1345
+ status_lines.append(f"**Prompt:** {scene['t2i_prompt']}")
1346
+
1347
+ if scene.get("ref_character_key"):
1348
+ status_lines.append(f"**Character ref:** `{scene['ref_character_key']}`")
1349
+ if scene.get("ref_location_key"):
1350
+ status_lines.append(f"**Location ref:** `{scene['ref_location_key']}`")
1351
+
1352
+ # Approval status
1353
+ if scene_state["status"] == "approved":
1354
+ selected = "A" if scene_state["selected_image"] == image_a else "B"
1355
+ status_lines.append(f"\n✅ **APPROVED** — Image {selected} selected")
1356
+ else:
1357
+ status_lines.append(f"\n⏳ *Pending approval*")
1358
+
1359
+ status_md = "\n".join(status_lines)
1360
+
1361
+ # Action log
1362
+ if image_a and image_b:
1363
+ action_log = "Images loaded from state"
1364
+ else:
1365
+ action_log = 'Click "Generate A/B" to create images for this scene'
1366
+
1367
+ return image_a, image_b, status_md, action_log
1368
+
1369
+
1370
+ def get_approval_summary(state: Dict) -> str:
1371
+ """Generate summary of all scene approvals."""
1372
+ if not state or not state.get("scenes"):
1373
+ return "*No scenes loaded*"
1374
+
1375
+ lines = ["### 📊 Approval Summary\n"]
1376
+ approved = 0
1377
+ pending = 0
1378
+
1379
+ for scene in state["scenes"]:
1380
+ scene_state = state["scene_states"].get(scene["scene_id"], {})
1381
+ if scene_state.get("status") == "approved":
1382
+ approved += 1
1383
+ lines.append(f"✅ **{scene['scene_id']}** — Approved")
1384
+ else:
1385
+ pending += 1
1386
+ lines.append(f"⏳ **{scene['scene_id']}** — Pending")
1387
+
1388
+ lines.insert(1, f"**{approved}/{len(state['scenes'])}** scenes approved\n")
1389
+
1390
+ return "\n".join(lines)
1391
+
1392
+
1393
+ # =============================================================================
1394
+ # MILESTONE 2: VIDEO WORKFLOW FUNCTIONS
1395
+ # =============================================================================
1396
+
1397
+ def get_approved_scenes(state: Dict) -> List[Dict]:
1398
+ """Get list of scenes with approved images (ready for video generation)."""
1399
+ if not state or not state.get("scenes"):
1400
+ return []
1401
+
1402
+ approved = []
1403
+ for scene in state["scenes"]:
1404
+ scene_state = state["scene_states"].get(scene["scene_id"], {})
1405
+ if scene_state.get("status") == "approved" and scene_state.get("selected_image"):
1406
+ approved.append({
1407
+ **scene,
1408
+ "selected_image": scene_state["selected_image"],
1409
+ "clip_status": scene_state.get("clip_status", "pending"),
1410
+ "final_clip_path": scene_state.get("final_clip_path")
1411
+ })
1412
+ return approved
1413
+
1414
+
1415
+ def generate_scene_clip(state: Dict, scene_selection: str) -> Tuple[Dict, Optional[str], str]:
1416
+ """
1417
+ Generate video clip for a single scene.
1418
+
1419
+ Pipeline:
1420
+ 1. Get approved image
1421
+ 2. Generate video from image with camera motion
1422
+ 3. Generate audio tracks (VO, dialogue, SFX)
1423
+ 4. Combine audio + video
1424
+ 5. Update state
1425
+
1426
+ Returns:
1427
+ Tuple of (updated_state, video_path, status_message)
1428
+ """
1429
+ if not MOVIEPY_AVAILABLE:
1430
+ return state, None, "❌ MoviePy not installed — cannot generate video"
1431
+
1432
+ if not state or not state.get("scenes") or not scene_selection:
1433
+ return state, None, "❌ No scene selected"
1434
+
1435
+ # Parse scene index from selection
1436
+ try:
1437
+ idx = int(scene_selection.split(".")[0]) - 1
1438
+ scene = state["scenes"][idx]
1439
+ except (ValueError, IndexError):
1440
+ return state, None, "❌ Invalid scene selection"
1441
+
1442
+ scene_id = scene["scene_id"]
1443
+ scene_state = get_scene_state(state, scene_id)
1444
+
1445
+ # Check if image is approved
1446
+ if scene_state.get("status") != "approved" or not scene_state.get("selected_image"):
1447
+ return state, None, f"❌ Scene '{scene_id}' has no approved image. Approve an image first."
1448
+
1449
+ image_path = scene_state["selected_image"]
1450
+
1451
+ # Get video parameters from scene data
1452
+ camera_type = scene.get("camera_type", "medium")
1453
+ camera_motion = scene.get("camera_motion", "zoom-in")
1454
+ duration = scene.get("duration_target", DEFAULT_VIDEO_DURATION)
1455
+
1456
+ status_lines = [f"🎬 **Generating clip for {scene_id}**\n"]
1457
+ status_lines.append(f"- Camera: {camera_type} / {camera_motion}")
1458
+ status_lines.append(f"- Duration: {duration}s\n")
1459
+
1460
+ # Step 1: Generate video from image
1461
+ status_lines.append("📹 Generating video...")
1462
+ video_path = generate_video_from_image(
1463
+ image_path=image_path,
1464
+ camera_type=camera_type,
1465
+ camera_motion=camera_motion,
1466
+ duration=duration,
1467
+ scene_id=scene_id
1468
+ )
1469
+
1470
+ if not video_path:
1471
+ return state, None, f"❌ Video generation failed for {scene_id}"
1472
+
1473
+ scene_state["video_path"] = video_path
1474
+ scene_state["duration"] = duration
1475
+ status_lines.append(f"✅ Video generated")
1476
+
1477
+ # Step 2: Generate audio tracks
1478
+ status_lines.append("\n🎵 Generating audio...")
1479
+ audio_paths = generate_audio_track(scene, duration, scene_id)
1480
+ scene_state["audio_paths"] = audio_paths
1481
+
1482
+ audio_generated = []
1483
+ if audio_paths.get("vo"):
1484
+ audio_generated.append("VO")
1485
+ if audio_paths.get("dialogue"):
1486
+ audio_generated.append("Dialogue")
1487
+ if audio_paths.get("sfx"):
1488
+ audio_generated.append("SFX")
1489
+
1490
+ if audio_generated:
1491
+ status_lines.append(f"✅ Audio generated: {', '.join(audio_generated)}")
1492
+ else:
1493
+ status_lines.append("ℹ️ No audio specified in scene data")
1494
+
1495
+ # Step 3: Combine audio + video
1496
+ status_lines.append("\n🔗 Combining audio and video...")
1497
+ final_clip_path = combine_audio_video(video_path, audio_paths, scene_id)
1498
+
1499
+ if final_clip_path:
1500
+ scene_state["final_clip_path"] = final_clip_path
1501
+ scene_state["clip_status"] = "generated"
1502
+ status_lines.append(f"✅ Final clip ready!")
1503
+ else:
1504
+ # If audio combination fails, use video-only
1505
+ scene_state["final_clip_path"] = video_path
1506
+ scene_state["clip_status"] = "generated"
1507
+ status_lines.append("⚠️ Audio merge failed — using video only")
1508
+
1509
+ return state, scene_state["final_clip_path"], "\n".join(status_lines)
1510
+
1511
+
1512
+ def generate_all_clips(state: Dict) -> Tuple[Dict, str]:
1513
+ """
1514
+ Generate video clips for ALL approved scenes.
1515
+
1516
+ Returns:
1517
+ Tuple of (updated_state, status_message)
1518
+ """
1519
+ if not MOVIEPY_AVAILABLE:
1520
+ return state, "❌ MoviePy not installed — cannot generate videos"
1521
+
1522
+ if not state or not state.get("scenes"):
1523
+ return state, "❌ No scenes loaded"
1524
+
1525
+ approved_scenes = get_approved_scenes(state)
1526
+
1527
+ if not approved_scenes:
1528
+ return state, "❌ No approved scenes found. Approve images in the Visual Selection tab first."
1529
+
1530
+ status_lines = [f"### 🎬 Generating {len(approved_scenes)} clips\n"]
1531
+ success_count = 0
1532
+
1533
+ for scene in approved_scenes:
1534
+ scene_id = scene["scene_id"]
1535
+ scene_state = get_scene_state(state, scene_id)
1536
+
1537
+ # Skip if already generated
1538
+ if scene_state.get("clip_status") in ["generated", "approved"]:
1539
+ status_lines.append(f"⏭️ **{scene_id}** — Already generated")
1540
+ success_count += 1
1541
+ continue
1542
+
1543
+ status_lines.append(f"🎬 **{scene_id}** — Processing...")
1544
+
1545
+ # Find scene index for selection string
1546
+ for idx, s in enumerate(state["scenes"]):
1547
+ if s["scene_id"] == scene_id:
1548
+ selection = f"{idx + 1}. {scene_id}"
1549
+ break
1550
+
1551
+ # Generate clip
1552
+ state, clip_path, _ = generate_scene_clip(state, selection)
1553
+
1554
+ if clip_path:
1555
+ status_lines.append(f" ✅ Generated")
1556
+ success_count += 1
1557
+ else:
1558
+ status_lines.append(f" ❌ Failed")
1559
+
1560
+ status_lines.append(f"\n**Complete:** {success_count}/{len(approved_scenes)} clips generated")
1561
+
1562
+ return state, "\n".join(status_lines)
1563
+
1564
+
1565
+ def approve_clip(state: Dict, scene_selection: str) -> Tuple[Dict, str]:
1566
+ """Approve a generated clip."""
1567
+ if not state or not state.get("scenes") or not scene_selection:
1568
+ return state, "❌ No scene selected"
1569
+
1570
+ try:
1571
+ idx = int(scene_selection.split(".")[0]) - 1
1572
+ scene = state["scenes"][idx]
1573
+ except (ValueError, IndexError):
1574
+ return state, "❌ Invalid scene selection"
1575
+
1576
+ scene_id = scene["scene_id"]
1577
+ scene_state = get_scene_state(state, scene_id)
1578
+
1579
+ if scene_state.get("clip_status") == "pending":
1580
+ return state, f"❌ No clip generated for {scene_id}. Generate a clip first."
1581
+
1582
+ scene_state["clip_status"] = "approved"
1583
+ return state, f"✅ Clip approved for **{scene_id}**"
1584
+
1585
+
1586
+ def rerender_clip(state: Dict, scene_selection: str) -> Tuple[Dict, Optional[str], str]:
1587
+ """Re-render clip for a specific scene."""
1588
+ if not state or not state.get("scenes") or not scene_selection:
1589
+ return state, None, "❌ No scene selected"
1590
+
1591
+ try:
1592
+ idx = int(scene_selection.split(".")[0]) - 1
1593
+ scene = state["scenes"][idx]
1594
+ except (ValueError, IndexError):
1595
+ return state, None, "❌ Invalid scene selection"
1596
+
1597
+ scene_id = scene["scene_id"]
1598
+ scene_state = get_scene_state(state, scene_id)
1599
+
1600
+ # Reset clip status to allow regeneration
1601
+ scene_state["clip_status"] = "pending"
1602
+ scene_state["video_path"] = None
1603
+ scene_state["final_clip_path"] = None
1604
+ scene_state["audio_paths"] = {"vo": None, "dialogue": None, "sfx": None}
1605
+
1606
+ # Generate new clip
1607
+ return generate_scene_clip(state, scene_selection)
1608
+
1609
+
1610
+ def on_video_scene_change(state: Dict, scene_selection: str) -> Tuple[Optional[str], str, str]:
1611
+ """Handle scene selection change in Video Approval tab."""
1612
+ if not state or not state.get("scenes") or not scene_selection:
1613
+ return None, "*Select a scene*", ""
1614
+
1615
+ try:
1616
+ idx = int(scene_selection.split(".")[0]) - 1
1617
+ scene = state["scenes"][idx]
1618
+ except (ValueError, IndexError):
1619
+ return None, "*Invalid selection*", ""
1620
+
1621
+ scene_id = scene["scene_id"]
1622
+ scene_state = get_scene_state(state, scene_id)
1623
+
1624
+ # Get clip path
1625
+ clip_path = scene_state.get("final_clip_path")
1626
+
1627
+ # Build status
1628
+ status_lines = [f"### 🎬 {scene_id}"]
1629
+
1630
+ # Image status
1631
+ if scene_state.get("status") == "approved":
1632
+ status_lines.append("✅ Image: Approved")
1633
+ else:
1634
+ status_lines.append("⏳ Image: Not approved (go to Visual Selection tab)")
1635
+
1636
+ # Video parameters
1637
+ status_lines.append(f"\n**Video Settings:**")
1638
+ status_lines.append(f"- Camera: {scene.get('camera_type', 'medium')} / {scene.get('camera_motion', 'zoom-in')}")
1639
+ status_lines.append(f"- Duration: {scene.get('duration_target', DEFAULT_VIDEO_DURATION)}s")
1640
+
1641
+ # Audio info
1642
+ status_lines.append(f"\n**Audio:**")
1643
+ if scene.get("voiceover"):
1644
+ status_lines.append(f"- VO: \"{scene['voiceover'][:50]}...\"" if len(scene.get('voiceover', '')) > 50 else f"- VO: \"{scene.get('voiceover')}\"")
1645
+ if scene.get("dialogue_text"):
1646
+ status_lines.append(f"- Dialogue ({scene.get('character', 'narrator')}): \"{scene['dialogue_text'][:40]}...\"" if len(scene.get('dialogue_text', '')) > 40 else f"- Dialogue: \"{scene.get('dialogue_text')}\"")
1647
+ if scene.get("sound_effect"):
1648
+ status_lines.append(f"- SFX: {scene['sound_effect']}")
1649
+
1650
+ if not any([scene.get("voiceover"), scene.get("dialogue_text"), scene.get("sound_effect")]):
1651
+ status_lines.append("- (No audio specified)")
1652
+
1653
+ # Clip status
1654
+ clip_status = scene_state.get("clip_status", "pending")
1655
+ status_lines.append(f"\n**Clip Status:** ")
1656
+ if clip_status == "approved":
1657
+ status_lines.append("✅ Approved")
1658
+ elif clip_status == "generated":
1659
+ status_lines.append("🎥 Generated (pending approval)")
1660
+ else:
1661
+ status_lines.append("⏳ Not generated")
1662
+
1663
+ status_md = "\n".join(status_lines)
1664
+
1665
+ # Action log
1666
+ if clip_path:
1667
+ action_log = "Clip loaded from state"
1668
+ elif scene_state.get("status") != "approved":
1669
+ action_log = "⚠️ Approve an image first in the Visual Selection tab"
1670
+ else:
1671
+ action_log = 'Click "Generate Clip" to create video for this scene'
1672
+
1673
+ return clip_path, status_md, action_log
1674
+
1675
+
1676
+ def get_video_approval_summary(state: Dict) -> str:
1677
+ """Generate summary of all video clip statuses."""
1678
+ if not state or not state.get("scenes"):
1679
+ return "*No scenes loaded*"
1680
+
1681
+ lines = ["### 🎬 Video Approval Summary\n"]
1682
+ approved_images = 0
1683
+ generated_clips = 0
1684
+ approved_clips = 0
1685
+
1686
+ for scene in state["scenes"]:
1687
+ scene_state = state["scene_states"].get(scene["scene_id"], {})
1688
+
1689
+ img_status = "✅" if scene_state.get("status") == "approved" else "⏳"
1690
+ clip_status = scene_state.get("clip_status", "pending")
1691
+
1692
+ if scene_state.get("status") == "approved":
1693
+ approved_images += 1
1694
+
1695
+ if clip_status == "approved":
1696
+ clip_icon = "✅"
1697
+ approved_clips += 1
1698
+ generated_clips += 1
1699
+ elif clip_status == "generated":
1700
+ clip_icon = "🎥"
1701
+ generated_clips += 1
1702
+ else:
1703
+ clip_icon = "⏳"
1704
+
1705
+ lines.append(f"**{scene['scene_id']}** — Image: {img_status} | Clip: {clip_icon}")
1706
+
1707
+ lines.insert(1, f"**Images:** {approved_images}/{len(state['scenes'])} approved")
1708
+ lines.insert(2, f"**Clips:** {generated_clips}/{approved_images} generated | {approved_clips}/{generated_clips} approved\n")
1709
+
1710
+ return "\n".join(lines)
1711
+
1712
+
1713
+ def get_video_scene_choices(state: Dict) -> List[str]:
1714
+ """Get dropdown choices for video tab - only approved scenes."""
1715
+ if not state or not state.get("scenes"):
1716
+ return []
1717
+
1718
+ choices = []
1719
+ for i, scene in enumerate(state["scenes"]):
1720
+ scene_state = state["scene_states"].get(scene["scene_id"], {})
1721
+ # Show all scenes but indicate approval status
1722
+ status = "✅" if scene_state.get("status") == "approved" else "⏳"
1723
+ clip_status = scene_state.get("clip_status", "pending")
1724
+ clip_icon = "🎥" if clip_status in ["generated", "approved"] else ""
1725
+ choices.append(f"{i + 1}. {scene['scene_id']} {status}{clip_icon}")
1726
+
1727
+ return choices
1728
+
1729
+
1730
+ # =============================================================================
1731
+ # GRADIO UI — MILESTONE 1 + 2 (3 Tabs)
1732
+ # =============================================================================
1733
+ def create_app():
1734
+ """Create and configure the Gradio application."""
1735
+
1736
+ with gr.Blocks(
1737
+ title="RadixLab Anime — Milestone 1 & 2",
1738
+ theme=gr.themes.Soft(
1739
+ primary_hue="indigo",
1740
+ secondary_hue="purple",
1741
+ ),
1742
+ css="""
1743
+ .main-header { text-align: center; margin-bottom: 1rem; }
1744
+ .scene-panel { border: 1px solid #ddd; border-radius: 8px; padding: 1rem; }
1745
+ .commit-btn { min-height: 50px !important; }
1746
+ .status-approved { color: #22c55e; font-weight: bold; }
1747
+ .status-pending { color: #f59e0b; }
1748
+ """
1749
+ ) as app:
1750
+
1751
+ # Header
1752
+ gr.Markdown(
1753
+ """
1754
+ # 🎬 RadixLab Anime — Milestone 1 & 2
1755
+ ### Text-to-Image & Video Pipeline
1756
+
1757
+ *Parse scripts → Generate A/B images → Approve → Generate video clips with audio*
1758
+ """,
1759
+ elem_classes=["main-header"]
1760
+ )
1761
+
1762
+ # Persistent state
1763
+ state = gr.State(create_initial_state())
1764
+
1765
+ with gr.Tabs() as tabs:
1766
+
1767
+ # =====================================================
1768
+ # TAB 1: SCRIPTING
1769
+ # =====================================================
1770
+ with gr.Tab("📝 Scripting", id="scripting"):
1771
+ gr.Markdown("### Upload & Parse JSON Script")
1772
+
1773
+ with gr.Row():
1774
+ with gr.Column(scale=2):
1775
+ json_input = gr.Textbox(
1776
+ label="JSON Script",
1777
+ placeholder='''{
1778
+ "scenes": [
1779
+ {
1780
+ "scene_id": "scene_01",
1781
+ "ref_character_key": "hero",
1782
+ "ref_location_key": "forest",
1783
+ "t2i_prompt": "A brave hero standing in an enchanted forest",
1784
+ "camera_type": "medium",
1785
+ "camera_motion": "zoom-in",
1786
+ "duration_target": 4,
1787
+ "voiceover": "The hero begins their journey...",
1788
+ "sound_effect": "forest"
1789
+ }
1790
+ ]
1791
+ }''',
1792
+ lines=18,
1793
+ max_lines=30,
1794
+ )
1795
+
1796
+ with gr.Row():
1797
+ btn_parse = gr.Button("📋 Parse JSON", variant="primary", size="lg")
1798
+ btn_clear = gr.Button("🗑️ Clear", variant="secondary")
1799
+
1800
+ parse_status = gr.Markdown("*Paste your JSON script and click Parse*")
1801
+
1802
+ with gr.Column(scale=1):
1803
+ gr.Markdown("### 📖 Instructions")
1804
+ gr.Markdown("""
1805
+ 1. Paste your JSON script with scene definitions
1806
+ 2. Each scene can have:
1807
+ - `scene_id` — Unique identifier
1808
+ - `t2i_prompt` — Text prompt for image generation
1809
+ - `ref_character_key` — (Optional) Character reference
1810
+ - `ref_location_key` — (Optional) Location reference
1811
+ - `camera_type` — Wide, Medium, Close-up
1812
+ - `camera_motion` — Zoom-in, Pan-left, Tilt-up, etc.
1813
+ - `duration_target` — Video duration in seconds
1814
+ - `voiceover` — Narrator text
1815
+ - `dialogue_text` — Character dialogue
1816
+ - `sound_effect` — Ambient sound type
1817
+ 3. Click **Parse JSON** to load scenes
1818
+ 4. Go to **Visual Selection** tab to approve images
1819
+ 5. Go to **Video Approval** tab to generate clips
1820
+ """)
1821
+
1822
+ gr.Markdown("### 📁 Reference Folders")
1823
+ gr.Markdown(f"""
1824
+ Place reference images in:
1825
+ - `Characters/` — Character references
1826
+ - `Locations/` — Location/background references
1827
+
1828
+ Current paths:
1829
+ - `{CHAR_DIR}`
1830
+ - `{LOC_DIR}`
1831
+ """)
1832
+
1833
+ scenes_preview = gr.Markdown("*No scenes loaded*")
1834
+
1835
+ # =====================================================
1836
+ # TAB 2: VISUAL SELECTION
1837
+ # =====================================================
1838
+ with gr.Tab("🎨 Visual Selection", id="visual"):
1839
+ gr.Markdown("### A/B Image Generation & Approval")
1840
+
1841
+ with gr.Row():
1842
+ scene_dropdown = gr.Dropdown(
1843
+ label="Select Scene",
1844
+ choices=[],
1845
+ interactive=True,
1846
+ scale=2
1847
+ )
1848
+ btn_generate = gr.Button("🎨 Generate A/B", variant="primary", scale=1)
1849
+ btn_regenerate = gr.Button("🔄 Regenerate", variant="secondary", scale=1)
1850
+
1851
+ scene_status = gr.Markdown("*Select a scene to begin*")
1852
+
1853
+ with gr.Row(equal_height=True):
1854
+ # Image A Column
1855
+ with gr.Column():
1856
+ gr.Markdown("### Option A")
1857
+ image_a = gr.Image(
1858
+ label="Image A",
1859
+ type="filepath",
1860
+ height=500,
1861
+ interactive=False
1862
+ )
1863
+ btn_commit_a = gr.Button(
1864
+ "✅ Commit A",
1865
+ variant="primary",
1866
+ size="lg",
1867
+ elem_classes=["commit-btn"]
1868
+ )
1869
+
1870
+ # Image B Column
1871
+ with gr.Column():
1872
+ gr.Markdown("### Option B")
1873
+ image_b = gr.Image(
1874
+ label="Image B",
1875
+ type="filepath",
1876
+ height=500,
1877
+ interactive=False
1878
+ )
1879
+ btn_commit_b = gr.Button(
1880
+ "✅ Commit B",
1881
+ variant="primary",
1882
+ size="lg",
1883
+ elem_classes=["commit-btn"]
1884
+ )
1885
+
1886
+ action_log = gr.Markdown("")
1887
+
1888
+ gr.Markdown("---")
1889
+ approval_summary = gr.Markdown("*Parse a script to see approval summary*")
1890
+
1891
+ # =====================================================
1892
+ # TAB 3: VIDEO APPROVAL (Milestone 2)
1893
+ # =====================================================
1894
+ with gr.Tab("🎬 Video Approval", id="video"):
1895
+ gr.Markdown("### Generate & Approve Video Clips")
1896
+ gr.Markdown("*Convert approved images to video clips with camera motion and audio*")
1897
+
1898
+ with gr.Row():
1899
+ video_scene_dropdown = gr.Dropdown(
1900
+ label="Select Scene",
1901
+ choices=[],
1902
+ interactive=True,
1903
+ scale=2
1904
+ )
1905
+ btn_generate_clip = gr.Button("🎬 Generate Clip", variant="primary", scale=1)
1906
+ btn_generate_all = gr.Button("🎬 Generate All Clips", variant="secondary", scale=1)
1907
+
1908
+ video_scene_status = gr.Markdown("*Select a scene to begin*")
1909
+
1910
+ with gr.Row():
1911
+ with gr.Column(scale=2):
1912
+ video_preview = gr.Video(
1913
+ label="Video Preview",
1914
+ height=500,
1915
+ interactive=False
1916
+ )
1917
+
1918
+ with gr.Column(scale=1):
1919
+ gr.Markdown("### Actions")
1920
+ btn_approve_clip = gr.Button(
1921
+ "✅ Approve Clip",
1922
+ variant="primary",
1923
+ size="lg"
1924
+ )
1925
+ btn_rerender_clip = gr.Button(
1926
+ "🔄 Re-render Clip",
1927
+ variant="secondary",
1928
+ size="lg"
1929
+ )
1930
+
1931
+ gr.Markdown("---")
1932
+ gr.Markdown("### 📋 Instructions")
1933
+ gr.Markdown("""
1934
+ 1. **Approve images first** in the Visual Selection tab
1935
+ 2. Select a scene from the dropdown
1936
+ 3. Click **Generate Clip** to create video with audio
1937
+ 4. Preview the clip
1938
+ 5. **Approve** or **Re-render** as needed
1939
+
1940
+ **Note:** Only scenes with approved images can generate video clips.
1941
+ """)
1942
+
1943
+ video_action_log = gr.Markdown("")
1944
+
1945
+ gr.Markdown("---")
1946
+ video_approval_summary = gr.Markdown("*Parse a script to see video summary*")
1947
+
1948
+ # =================================================================
1949
+ # EVENT HANDLERS
1950
+ # =================================================================
1951
+
1952
+ # Tab 1: Scripting
1953
+ btn_parse.click(
1954
+ fn=load_and_parse_json,
1955
+ inputs=[json_input, state],
1956
+ outputs=[state, parse_status, scene_dropdown]
1957
+ ).then(
1958
+ fn=get_scenes_preview,
1959
+ inputs=[state],
1960
+ outputs=[scenes_preview]
1961
+ ).then(
1962
+ fn=get_approval_summary,
1963
+ inputs=[state],
1964
+ outputs=[approval_summary]
1965
+ )
1966
+
1967
+ btn_clear.click(
1968
+ fn=lambda: ("", create_initial_state(), "*No scenes loaded*", gr.update(choices=[], value=None)),
1969
+ inputs=[],
1970
+ outputs=[json_input, state, scenes_preview, scene_dropdown]
1971
+ )
1972
+
1973
+ # Tab 2: Visual Selection
1974
+ scene_dropdown.change(
1975
+ fn=on_scene_change,
1976
+ inputs=[state, scene_dropdown],
1977
+ outputs=[image_a, image_b, scene_status, action_log]
1978
+ )
1979
+
1980
+ btn_generate.click(
1981
+ fn=generate_scene_images,
1982
+ inputs=[state, scene_dropdown],
1983
+ outputs=[state, image_a, image_b, action_log]
1984
+ ).then(
1985
+ fn=on_scene_change,
1986
+ inputs=[state, scene_dropdown],
1987
+ outputs=[image_a, image_b, scene_status, action_log]
1988
+ )
1989
+
1990
+ btn_regenerate.click(
1991
+ fn=regenerate_scene_images,
1992
+ inputs=[state, scene_dropdown],
1993
+ outputs=[state, image_a, image_b, action_log]
1994
+ ).then(
1995
+ fn=on_scene_change,
1996
+ inputs=[state, scene_dropdown],
1997
+ outputs=[image_a, image_b, scene_status, action_log]
1998
+ )
1999
+
2000
+ btn_commit_a.click(
2001
+ fn=lambda s, sel: commit_image(s, sel, "A"),
2002
+ inputs=[state, scene_dropdown],
2003
+ outputs=[state, action_log]
2004
+ ).then(
2005
+ fn=on_scene_change,
2006
+ inputs=[state, scene_dropdown],
2007
+ outputs=[image_a, image_b, scene_status, action_log]
2008
+ ).then(
2009
+ fn=get_scenes_preview,
2010
+ inputs=[state],
2011
+ outputs=[scenes_preview]
2012
+ ).then(
2013
+ fn=get_approval_summary,
2014
+ inputs=[state],
2015
+ outputs=[approval_summary]
2016
+ )
2017
+
2018
+ btn_commit_b.click(
2019
+ fn=lambda s, sel: commit_image(s, sel, "B"),
2020
+ inputs=[state, scene_dropdown],
2021
+ outputs=[state, action_log]
2022
+ ).then(
2023
+ fn=on_scene_change,
2024
+ inputs=[state, scene_dropdown],
2025
+ outputs=[image_a, image_b, scene_status, action_log]
2026
+ ).then(
2027
+ fn=get_scenes_preview,
2028
+ inputs=[state],
2029
+ outputs=[scenes_preview]
2030
+ ).then(
2031
+ fn=get_approval_summary,
2032
+ inputs=[state],
2033
+ outputs=[approval_summary]
2034
+ ).then(
2035
+ # Update video tab dropdown when images are approved
2036
+ fn=lambda s: gr.update(choices=get_video_scene_choices(s), value=get_video_scene_choices(s)[0] if get_video_scene_choices(s) else None),
2037
+ inputs=[state],
2038
+ outputs=[video_scene_dropdown]
2039
+ ).then(
2040
+ fn=get_video_approval_summary,
2041
+ inputs=[state],
2042
+ outputs=[video_approval_summary]
2043
+ )
2044
+
2045
+ # =================================================================
2046
+ # TAB 3: VIDEO APPROVAL EVENT HANDLERS
2047
+ # =================================================================
2048
+
2049
+ # Scene selection change
2050
+ video_scene_dropdown.change(
2051
+ fn=on_video_scene_change,
2052
+ inputs=[state, video_scene_dropdown],
2053
+ outputs=[video_preview, video_scene_status, video_action_log]
2054
+ )
2055
+
2056
+ # Generate single clip
2057
+ btn_generate_clip.click(
2058
+ fn=generate_scene_clip,
2059
+ inputs=[state, video_scene_dropdown],
2060
+ outputs=[state, video_preview, video_action_log]
2061
+ ).then(
2062
+ fn=on_video_scene_change,
2063
+ inputs=[state, video_scene_dropdown],
2064
+ outputs=[video_preview, video_scene_status, video_action_log]
2065
+ ).then(
2066
+ fn=get_video_approval_summary,
2067
+ inputs=[state],
2068
+ outputs=[video_approval_summary]
2069
+ ).then(
2070
+ fn=lambda s: gr.update(choices=get_video_scene_choices(s)),
2071
+ inputs=[state],
2072
+ outputs=[video_scene_dropdown]
2073
+ )
2074
+
2075
+ # Generate all clips
2076
+ btn_generate_all.click(
2077
+ fn=generate_all_clips,
2078
+ inputs=[state],
2079
+ outputs=[state, video_action_log]
2080
+ ).then(
2081
+ fn=on_video_scene_change,
2082
+ inputs=[state, video_scene_dropdown],
2083
+ outputs=[video_preview, video_scene_status, video_action_log]
2084
+ ).then(
2085
+ fn=get_video_approval_summary,
2086
+ inputs=[state],
2087
+ outputs=[video_approval_summary]
2088
+ ).then(
2089
+ fn=lambda s: gr.update(choices=get_video_scene_choices(s)),
2090
+ inputs=[state],
2091
+ outputs=[video_scene_dropdown]
2092
+ )
2093
+
2094
+ # Approve clip
2095
+ btn_approve_clip.click(
2096
+ fn=approve_clip,
2097
+ inputs=[state, video_scene_dropdown],
2098
+ outputs=[state, video_action_log]
2099
+ ).then(
2100
+ fn=on_video_scene_change,
2101
+ inputs=[state, video_scene_dropdown],
2102
+ outputs=[video_preview, video_scene_status, video_action_log]
2103
+ ).then(
2104
+ fn=get_video_approval_summary,
2105
+ inputs=[state],
2106
+ outputs=[video_approval_summary]
2107
+ ).then(
2108
+ fn=lambda s: gr.update(choices=get_video_scene_choices(s)),
2109
+ inputs=[state],
2110
+ outputs=[video_scene_dropdown]
2111
+ )
2112
+
2113
+ # Re-render clip
2114
+ btn_rerender_clip.click(
2115
+ fn=rerender_clip,
2116
+ inputs=[state, video_scene_dropdown],
2117
+ outputs=[state, video_preview, video_action_log]
2118
+ ).then(
2119
+ fn=on_video_scene_change,
2120
+ inputs=[state, video_scene_dropdown],
2121
+ outputs=[video_preview, video_scene_status, video_action_log]
2122
+ ).then(
2123
+ fn=get_video_approval_summary,
2124
+ inputs=[state],
2125
+ outputs=[video_approval_summary]
2126
+ ).then(
2127
+ fn=lambda s: gr.update(choices=get_video_scene_choices(s)),
2128
+ inputs=[state],
2129
+ outputs=[video_scene_dropdown]
2130
+ )
2131
+
2132
+ # Update video tab when parsing JSON
2133
+ btn_parse.click(
2134
+ fn=load_and_parse_json,
2135
+ inputs=[json_input, state],
2136
+ outputs=[state, parse_status, scene_dropdown]
2137
+ ).then(
2138
+ fn=get_scenes_preview,
2139
+ inputs=[state],
2140
+ outputs=[scenes_preview]
2141
+ ).then(
2142
+ fn=get_approval_summary,
2143
+ inputs=[state],
2144
+ outputs=[approval_summary]
2145
+ ).then(
2146
+ fn=lambda s: gr.update(choices=get_video_scene_choices(s), value=get_video_scene_choices(s)[0] if get_video_scene_choices(s) else None),
2147
+ inputs=[state],
2148
+ outputs=[video_scene_dropdown]
2149
+ ).then(
2150
+ fn=get_video_approval_summary,
2151
+ inputs=[state],
2152
+ outputs=[video_approval_summary]
2153
+ )
2154
+
2155
+ return app
2156
+
2157
+ # =============================================================================
2158
+ # MAIN ENTRY POINT
2159
+ # =============================================================================
2160
+ if __name__ == "__main__":
2161
+ app = create_app()
2162
+ app.launch(
2163
+ server_name="0.0.0.0",
2164
+ server_port=7860,
2165
+ share=False
2166
+ )
outputs/.DS_Store ADDED
Binary file (6.15 kB). View file
 
outputs/images/.DS_Store ADDED
Binary file (6.15 kB). View file
 
outputs/images/scene_cat_REAL_7e83d099.png ADDED

Git LFS Details

  • SHA256: a58eb64badef23dace40ecb719120a8cc83fd27d8558712c675b4b04d7b3d448
  • Pointer size: 132 Bytes
  • Size of remote file: 1.45 MB
outputs/images/scene_classroom_A_e85225df.png ADDED

Git LFS Details

  • SHA256: 591dd525f8af0e13b8e0548373b29f3ab408925a6887f2fccaf897c155328b6e
  • Pointer size: 132 Bytes
  • Size of remote file: 1.44 MB
outputs/images/scene_doctor_A_175ee7df.png ADDED

Git LFS Details

  • SHA256: 11979b3a2dfce21bc280f934fcee89888fa9ca6106230595414bbe67af366da5
  • Pointer size: 132 Bytes
  • Size of remote file: 1.31 MB
requirements.txt ADDED
@@ -0,0 +1,17 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # RadixLab Anime — Milestone 1 & 2 Dependencies
2
+ # Text-to-Image A/B Workflow + Video/Audio Pipeline
3
+
4
+ # Core UI Framework
5
+ gradio>=4.0.0
6
+
7
+ # Image Processing
8
+ Pillow>=10.0.0
9
+ numpy>=1.24.0
10
+
11
+ # Video & Audio Processing (Milestone 2)
12
+ moviepy>=1.0.3
13
+
14
+ # Optional: Vertex AI (only needed if using Google Cloud for image/video generation)
15
+ # Uncomment if you have GCP credentials configured:
16
+ # google-cloud-aiplatform>=1.38.0
17
+ # vertexai>=1.38.0
sample_script.json ADDED
@@ -0,0 +1,61 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "scenes": [
3
+ {
4
+ "scene_id": "scene_01_classroom",
5
+ "ref_character_key": "daughter",
6
+ "ref_location_key": "class room",
7
+ "t2i_prompt": "A young girl sitting at her desk in a classroom, looking curious and attentive, colorful educational posters on the walls",
8
+ "camera_type": "medium",
9
+ "camera_motion": "zoom-in",
10
+ "duration_target": 4,
11
+ "voiceover": "Every day, children learn new things that shape their future.",
12
+ "sound_effect": "classroom"
13
+ },
14
+ {
15
+ "scene_id": "scene_02_lab_checkup",
16
+ "ref_character_key": "pediatrician 1",
17
+ "ref_location_key": "lab",
18
+ "t2i_prompt": "A friendly pediatrician in a medical lab examining test results, modern medical equipment in the background",
19
+ "camera_type": "close-up",
20
+ "camera_motion": "pan-right",
21
+ "duration_target": 5,
22
+ "dialogue_text": "The results look great! Everything is perfectly normal.",
23
+ "character": "doctor",
24
+ "sound_effect": "lab"
25
+ },
26
+ {
27
+ "scene_id": "scene_03_cat_home",
28
+ "ref_character_key": "cat",
29
+ "ref_location_key": null,
30
+ "t2i_prompt": "A cute black and white cat lounging comfortably at home, warm cozy atmosphere",
31
+ "camera_type": "wide",
32
+ "camera_motion": "tilt-down",
33
+ "duration_target": 3,
34
+ "voiceover": "Meanwhile at home, a furry friend waits patiently.",
35
+ "sound_effect": "home"
36
+ },
37
+ {
38
+ "scene_id": "scene_04_daughter_doctor",
39
+ "ref_character_key": "daughter",
40
+ "ref_location_key": "lab",
41
+ "t2i_prompt": "A young girl visiting the doctor's lab for a checkup, looking slightly nervous but brave",
42
+ "camera_type": "medium",
43
+ "camera_motion": "zoom-in",
44
+ "duration_target": 4,
45
+ "dialogue_text": "Am I going to be okay, doctor?",
46
+ "character": "child",
47
+ "sound_effect": "lab"
48
+ },
49
+ {
50
+ "scene_id": "scene_05_classroom_learning",
51
+ "ref_character_key": null,
52
+ "ref_location_key": "class_room",
53
+ "t2i_prompt": "An empty classroom with desks, a whiteboard, and educational materials, afternoon sunlight streaming through windows",
54
+ "camera_type": "wide",
55
+ "camera_motion": "pan-left",
56
+ "duration_target": 5,
57
+ "voiceover": "Education opens doors to endless possibilities.",
58
+ "sound_effect": "classroom"
59
+ }
60
+ ]
61
+ }