Update core/visual_engine.py
Browse files- core/visual_engine.py +182 -289
core/visual_engine.py
CHANGED
@@ -24,7 +24,7 @@ import random
|
|
24 |
import logging
|
25 |
|
26 |
logger = logging.getLogger(__name__)
|
27 |
-
logger.setLevel(logging.INFO)
|
28 |
|
29 |
# --- ElevenLabs Client Import ---
|
30 |
ELEVENLABS_CLIENT_IMPORTED = False
|
@@ -38,19 +38,17 @@ try:
|
|
38 |
Voice = ImportedVoice
|
39 |
VoiceSettings = ImportedVoiceSettings
|
40 |
ELEVENLABS_CLIENT_IMPORTED = True
|
41 |
-
logger.info("ElevenLabs client components imported.")
|
42 |
except Exception as e_eleven:
|
43 |
-
logger.warning(f"ElevenLabs client import failed: {e_eleven}. Audio generation disabled.")
|
44 |
|
45 |
# --- RunwayML Client Import (Placeholder) ---
|
46 |
RUNWAYML_SDK_IMPORTED = False
|
47 |
RunwayMLClient = None # Placeholder for the actual RunwayML client class
|
48 |
try:
|
49 |
-
# This is a hypothetical import. Replace with actual RunwayML SDK import if available.
|
50 |
# Example: from runwayml import RunwayClient as ImportedRunwayMLClient
|
51 |
# RunwayMLClient = ImportedRunwayMLClient
|
52 |
# RUNWAYML_SDK_IMPORTED = True
|
53 |
-
# logger.info("RunwayML SDK (placeholder) imported.")
|
54 |
logger.info("RunwayML SDK import is a placeholder. Actual SDK needed for Runway features.")
|
55 |
except ImportError:
|
56 |
logger.warning("RunwayML SDK (placeholder) not found. RunwayML video generation will be disabled.")
|
@@ -66,28 +64,34 @@ class VisualEngine:
|
|
66 |
self.font_filename = "arial.ttf"
|
67 |
font_paths_to_try = [
|
68 |
self.font_filename,
|
69 |
-
f"/usr/share/fonts/truetype/dejavu/DejaVuSans-Bold.ttf",
|
70 |
-
f"/usr/share/fonts/truetype/liberation/LiberationSans-Bold.ttf",
|
71 |
-
f"/System/Library/Fonts/Supplemental/Arial.ttf",
|
72 |
-
f"C:/Windows/Fonts/arial.ttf",
|
73 |
-
f"/usr/local/share/fonts/truetype/mycustomfonts/{self.font_filename}"
|
74 |
]
|
75 |
self.font_path_pil = next((p for p in font_paths_to_try if os.path.exists(p)), None)
|
76 |
self.font_size_pil = 20
|
77 |
self.video_overlay_font_size = 30
|
78 |
self.video_overlay_font_color = 'white'
|
79 |
-
self.video_overlay_font = 'Liberation-Sans-Bold' # For MoviePy TextClip
|
80 |
|
81 |
try:
|
82 |
-
|
83 |
-
|
84 |
-
|
85 |
-
|
86 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
87 |
|
88 |
self.openai_api_key = None; self.USE_AI_IMAGE_GENERATION = False
|
89 |
self.dalle_model = "dall-e-3"; self.image_size_dalle3 = "1792x1024"
|
90 |
-
self.video_frame_size = (1280, 720)
|
91 |
|
92 |
self.elevenlabs_api_key = None; self.USE_ELEVENLABS = False
|
93 |
self.elevenlabs_client = None
|
@@ -97,17 +101,14 @@ class VisualEngine:
|
|
97 |
else: self.elevenlabs_voice_settings = None
|
98 |
|
99 |
self.pexels_api_key = None; self.USE_PEXELS = False
|
100 |
-
|
101 |
-
# <<< RUNWAYML START >>>
|
102 |
self.runway_api_key = None; self.USE_RUNWAYML = False
|
103 |
-
self.runway_client = None
|
104 |
-
# <<< RUNWAYML END >>>
|
105 |
|
106 |
logger.info("VisualEngine initialized.")
|
107 |
|
108 |
def set_openai_api_key(self,k):
|
109 |
self.openai_api_key=k; self.USE_AI_IMAGE_GENERATION=bool(k)
|
110 |
-
logger.info(f"DALL-E ({self.dalle_model}) {'Ready.' if k else 'Disabled.'}")
|
111 |
|
112 |
def set_elevenlabs_api_key(self,api_key, voice_id_from_secret=None):
|
113 |
self.elevenlabs_api_key=api_key
|
@@ -118,50 +119,39 @@ class VisualEngine:
|
|
118 |
self.USE_ELEVENLABS=bool(self.elevenlabs_client)
|
119 |
logger.info(f"ElevenLabs Client {'Ready' if self.USE_ELEVENLABS else 'Failed Init'} (Voice ID: {self.elevenlabs_voice_id}).")
|
120 |
except Exception as e: logger.error(f"ElevenLabs client init error: {e}. Disabled.", exc_info=True); self.USE_ELEVENLABS=False
|
121 |
-
else: self.USE_ELEVENLABS=False; logger.info("ElevenLabs Disabled (no key or SDK).")
|
122 |
|
123 |
def set_pexels_api_key(self,k):
|
124 |
self.pexels_api_key=k; self.USE_PEXELS=bool(k)
|
125 |
-
logger.info(f"Pexels Search {'Ready.' if k else 'Disabled.'}")
|
126 |
|
127 |
-
# <<< RUNWAYML START >>>
|
128 |
def set_runway_api_key(self, k):
|
129 |
self.runway_api_key = k
|
130 |
-
if k and RUNWAYML_SDK_IMPORTED and RunwayMLClient:
|
131 |
try:
|
132 |
# self.runway_client = RunwayMLClient(api_key=k) # Actual initialization
|
133 |
-
self.USE_RUNWAYML = True # Assume success for placeholder
|
134 |
-
logger.info(f"RunwayML Client (Placeholder) {'Ready.' if self.USE_RUNWAYML else 'Failed Init.'}")
|
135 |
-
except Exception as e:
|
136 |
-
|
137 |
-
|
138 |
-
|
139 |
-
|
140 |
-
logger.info("RunwayML API Key set. SDK (Placeholder) not imported/used. Direct API calls would be needed.")
|
141 |
-
else:
|
142 |
-
self.USE_RUNWAYML = False
|
143 |
-
logger.info("RunwayML Disabled (no API key or SDK issue).")
|
144 |
-
# <<< RUNWAYML END >>>
|
145 |
|
146 |
def _get_text_dimensions(self,text_content,font_obj):
|
147 |
-
# ... (no changes from your previous version)
|
148 |
if not text_content: return 0,self.font_size_pil
|
149 |
try:
|
150 |
-
if hasattr(font_obj,'getbbox'):
|
151 |
bbox=font_obj.getbbox(text_content);w=bbox[2]-bbox[0];h=bbox[3]-bbox[1]
|
152 |
return w, h if h > 0 else self.font_size_pil
|
153 |
-
elif hasattr(font_obj,'getsize'):
|
154 |
w,h=font_obj.getsize(text_content)
|
155 |
return w, h if h > 0 else self.font_size_pil
|
156 |
-
else:
|
157 |
-
|
158 |
-
except Exception as e:
|
159 |
-
logger.warning(f"Error in _get_text_dimensions for '{text_content[:20]}...': {e}")
|
160 |
-
return int(len(text_content)*self.font_size_pil*0.6),int(self.font_size_pil*1.2) # Fallback
|
161 |
-
|
162 |
|
163 |
def _create_placeholder_image_content(self,text_description,filename,size=None):
|
164 |
-
#
|
165 |
if size is None: size = self.video_frame_size
|
166 |
img=Image.new('RGB',size,color=(20,20,40));d=ImageDraw.Draw(img);padding=25;max_w=size[0]-(2*padding);lines=[];
|
167 |
if not text_description: text_description="(Placeholder: No prompt text)"
|
@@ -172,18 +162,14 @@ class VisualEngine:
|
|
172 |
else:
|
173 |
if current_line: lines.append(current_line.strip());
|
174 |
current_line=word+" "
|
175 |
-
if current_line.strip(): lines.append(current_line.strip())
|
176 |
-
if not lines and text_description: lines.append(text_description[:int(max_w//(self.font_size_pil*0.6 +1))]+"..." if text_description else "(Text too long)")
|
177 |
elif not lines: lines.append("(Placeholder Text Error)")
|
178 |
-
|
179 |
_,single_line_h=self._get_text_dimensions("Ay",self.font); single_line_h = single_line_h if single_line_h > 0 else self.font_size_pil + 2
|
180 |
-
|
181 |
max_lines_to_display=min(len(lines),(size[1]-(2*padding))//(single_line_h+2)) if single_line_h > 0 else 1
|
182 |
-
if max_lines_to_display <=0: max_lines_to_display = 1
|
183 |
-
|
184 |
y_text_start = padding + (size[1]-(2*padding) - max_lines_to_display*(single_line_h+2))/2.0
|
185 |
y_text = y_text_start
|
186 |
-
|
187 |
for i in range(max_lines_to_display):
|
188 |
line_content=lines[i];line_w,_=self._get_text_dimensions(line_content,self.font);x_text=(size[0]-line_w)/2.0
|
189 |
d.text((x_text,y_text),line_content,font=self.font,fill=(200,200,180));y_text+=single_line_h+2
|
@@ -192,12 +178,10 @@ class VisualEngine:
|
|
192 |
try:img.save(filepath);return filepath
|
193 |
except Exception as e:logger.error(f"Saving placeholder image {filepath}: {e}", exc_info=True);return None
|
194 |
|
195 |
-
|
196 |
def _search_pexels_image(self, query, output_filename_base):
|
197 |
-
#
|
198 |
if not self.USE_PEXELS or not self.pexels_api_key: return None
|
199 |
headers = {"Authorization": self.pexels_api_key}; params = {"query": query, "per_page": 1, "orientation": "landscape", "size": "large"}
|
200 |
-
# Use a more unique filename for Pexels images to avoid clashes if query is similar
|
201 |
pexels_filename = output_filename_base.replace(".png", f"_pexels_{random.randint(1000,9999)}.jpg").replace(".mp4", f"_pexels_{random.randint(1000,9999)}.jpg")
|
202 |
filepath = os.path.join(self.output_dir, pexels_filename)
|
203 |
try:
|
@@ -205,7 +189,7 @@ class VisualEngine:
|
|
205 |
response = requests.get("https://api.pexels.com/v1/search", headers=headers, params=params, timeout=20)
|
206 |
response.raise_for_status(); data = response.json()
|
207 |
if data.get("photos") and len(data["photos"]) > 0:
|
208 |
-
photo_url = data["photos"][0]["src"]["large2x"]
|
209 |
image_response = requests.get(photo_url, timeout=60); image_response.raise_for_status()
|
210 |
img_data = Image.open(io.BytesIO(image_response.content))
|
211 |
if img_data.mode != 'RGB': img_data = img_data.convert('RGB')
|
@@ -214,129 +198,61 @@ class VisualEngine:
|
|
214 |
except Exception as e: logger.error(f"Pexels search/download for query '{query}': {e}", exc_info=True)
|
215 |
return None
|
216 |
|
217 |
-
|
218 |
-
# <<< RUNWAYML START >>>
|
219 |
def _generate_video_clip_with_runwayml(self, prompt_text, scene_identifier_filename_base, target_duration_seconds=4, input_image_path=None):
|
220 |
-
"""
|
221 |
-
Placeholder for generating a video clip using RunwayML.
|
222 |
-
This needs to be implemented with the actual RunwayML SDK or API.
|
223 |
-
"""
|
224 |
if not self.USE_RUNWAYML or not self.runway_api_key:
|
225 |
logger.warning("RunwayML not enabled or API key missing. Cannot generate video clip.")
|
226 |
return None
|
227 |
-
|
228 |
output_video_filename = scene_identifier_filename_base.replace(".png", ".mp4") # Ensure .mp4 extension
|
229 |
output_video_filepath = os.path.join(self.output_dir, output_video_filename)
|
230 |
-
|
231 |
logger.info(f"Attempting RunwayML video generation for: {prompt_text[:100]}... (Target duration: {target_duration_seconds}s)")
|
232 |
-
|
233 |
-
|
234 |
-
# --- START ACTUAL RUNWAYML API INTERACTION (HYPOTHETICAL) ---
|
235 |
-
# This section is highly dependent on RunwayML's specific API/SDK.
|
236 |
-
# Example using a hypothetical SDK:
|
237 |
-
# try:
|
238 |
-
# if not self.runway_client:
|
239 |
-
# # self.runway_client = RunwayMLClient(api_key=self.runway_api_key) # Or however it's initialized
|
240 |
-
# logger.warning("RunwayML client not initialized (Placeholder).")
|
241 |
-
# # For placeholder, simulate creating a dummy video file
|
242 |
-
# return self._create_placeholder_video_content(prompt_text, output_video_filename, duration=target_duration_seconds)
|
243 |
-
|
244 |
-
|
245 |
-
# generation_params = {
|
246 |
-
# "text_prompt": prompt_text,
|
247 |
-
# "duration_seconds": target_duration_seconds,
|
248 |
-
# "width": self.video_frame_size[0], # Or Runway's supported sizes
|
249 |
-
# "height": self.video_frame_size[1],
|
250 |
-
# # Add other params like seed, motion scale, etc.
|
251 |
-
# }
|
252 |
-
# if input_image_path and os.path.exists(input_image_path):
|
253 |
-
# generation_params["input_image_path"] = input_image_path # For image-to-video
|
254 |
-
# logger.info(f"Using input image for RunwayML: {input_image_path}")
|
255 |
-
|
256 |
-
# task_id = self.runway_client.submit_video_generation_task(**generation_params) # Hypothetical
|
257 |
-
# logger.info(f"RunwayML task submitted: {task_id}. Polling for completion...")
|
258 |
-
|
259 |
-
# while True:
|
260 |
-
# status = self.runway_client.get_task_status(task_id) # Hypothetical
|
261 |
-
# if status == "completed":
|
262 |
-
# video_url = self.runway_client.get_video_url(task_id) # Hypothetical
|
263 |
-
# video_response = requests.get(video_url, stream=True, timeout=300)
|
264 |
-
# video_response.raise_for_status()
|
265 |
-
# with open(output_video_filepath, 'wb') as f:
|
266 |
-
# for chunk in video_response.iter_content(chunk_size=8192):
|
267 |
-
# f.write(chunk)
|
268 |
-
# logger.info(f"RunwayML video downloaded and saved: {output_video_filepath}")
|
269 |
-
# return output_video_filepath
|
270 |
-
# elif status in ["failed", "error"]:
|
271 |
-
# logger.error(f"RunwayML task {task_id} failed.")
|
272 |
-
# return None
|
273 |
-
# time.sleep(10) # Poll interval
|
274 |
-
|
275 |
-
# except Exception as e:
|
276 |
-
# logger.error(f"Error during RunwayML video generation: {e}", exc_info=True)
|
277 |
-
# return None
|
278 |
# --- END ACTUAL RUNWAYML API INTERACTION (HYPOTHETICAL) ---
|
279 |
-
|
280 |
-
# For now, as a placeholder, create a dummy MP4 file with MoviePy
|
281 |
-
# This allows the rest of the pipeline to be tested.
|
282 |
-
# **REPLACE THIS WITH ACTUAL RUNWAYML CALLS**
|
283 |
-
logger.warning("Using PLACEHOLDER video generation for RunwayML.")
|
284 |
return self._create_placeholder_video_content(f"[RunwayML Placeholder] {prompt_text}", output_video_filename, duration=target_duration_seconds)
|
285 |
|
286 |
def _create_placeholder_video_content(self, text_description, filename, duration=4, size=None):
|
287 |
-
"""Creates a short video clip with text as a placeholder."""
|
288 |
if size is None: size = self.video_frame_size
|
289 |
filepath = os.path.join(self.output_dir, filename)
|
290 |
-
|
291 |
-
# Create a simple text clip
|
292 |
txt_clip = TextClip(text_description, fontsize=50, color='white', font=self.video_overlay_font,
|
293 |
bg_color='black', size=size, method='caption').set_duration(duration)
|
294 |
-
|
295 |
try:
|
296 |
txt_clip.write_videofile(filepath, fps=24, codec='libx264', preset='ultrafast', logger=None)
|
297 |
logger.info(f"Placeholder video saved: {filepath}")
|
298 |
return filepath
|
299 |
-
except Exception as e:
|
300 |
-
logger.error(f"Failed to create placeholder video {filepath}: {e}", exc_info=True)
|
301 |
-
return None
|
302 |
finally:
|
303 |
if hasattr(txt_clip, 'close'): txt_clip.close()
|
304 |
-
# <<< RUNWAYML END >>>
|
305 |
-
|
306 |
|
307 |
def generate_scene_asset(self, image_prompt_text, scene_data, scene_identifier_filename_base,
|
308 |
generate_as_video_clip=False, runway_target_duration=4, input_image_for_runway=None):
|
309 |
-
"""
|
310 |
-
Generates either an image or a video clip for a scene.
|
311 |
-
Returns a dictionary: {'path': asset_path, 'type': 'image'/'video', 'error': bool}
|
312 |
-
"""
|
313 |
-
# Ensure scene_identifier_filename_base does not have an extension yet, or handle it
|
314 |
base_name, _ = os.path.splitext(scene_identifier_filename_base)
|
|
|
315 |
|
316 |
if generate_as_video_clip and self.USE_RUNWAYML:
|
317 |
logger.info(f"Attempting RunwayML video clip generation for {base_name}")
|
318 |
video_path = self._generate_video_clip_with_runwayml(
|
319 |
-
image_prompt_text,
|
320 |
-
base_name, # Pass base name, function will add .mp4
|
321 |
target_duration_seconds=runway_target_duration,
|
322 |
input_image_path=input_image_for_runway
|
323 |
)
|
324 |
if video_path and os.path.exists(video_path):
|
325 |
-
|
|
|
326 |
else:
|
327 |
logger.warning(f"RunwayML video clip generation failed for {base_name}. Falling back to image.")
|
|
|
328 |
# Fall through to image generation
|
329 |
|
330 |
# Image Generation (DALL-E, Pexels, Placeholder)
|
331 |
-
|
332 |
-
image_filename_with_ext = base_name + ".png"
|
333 |
filepath = os.path.join(self.output_dir, image_filename_with_ext)
|
|
|
334 |
|
335 |
if self.USE_AI_IMAGE_GENERATION and self.openai_api_key:
|
336 |
max_retries = 2
|
337 |
for attempt in range(max_retries):
|
338 |
try:
|
339 |
-
# ... (DALL-E generation logic - no changes from your previous version) ...
|
340 |
logger.info(f"Attempt {attempt+1}: DALL-E ({self.dalle_model}) for: {image_prompt_text[:100]}...")
|
341 |
client = openai.OpenAI(api_key=self.openai_api_key, timeout=90.0)
|
342 |
response = client.images.generate(model=self.dalle_model, prompt=image_prompt_text, n=1, size=self.image_size_dalle3, quality="hd", response_format="url", style="vivid")
|
@@ -346,120 +262,93 @@ class VisualEngine:
|
|
346 |
img_data = Image.open(io.BytesIO(image_response.content));
|
347 |
if img_data.mode != 'RGB': img_data = img_data.convert('RGB')
|
348 |
img_data.save(filepath); logger.info(f"AI Image (DALL-E) saved: {filepath}");
|
349 |
-
|
350 |
-
|
351 |
-
|
352 |
-
|
353 |
-
except
|
354 |
-
except
|
355 |
-
|
356 |
-
logger.warning("DALL-E generation failed. Trying Pexels fallback...")
|
357 |
|
358 |
-
|
359 |
-
if self.USE_PEXELS:
|
360 |
pexels_query_text = scene_data.get('pexels_search_query_감독', f"{scene_data.get('emotional_beat','')} {scene_data.get('setting_description','')}")
|
361 |
-
pexels_path = self._search_pexels_image(pexels_query_text, image_filename_with_ext)
|
362 |
if pexels_path:
|
363 |
-
|
364 |
-
|
365 |
-
|
366 |
-
|
367 |
-
|
368 |
-
|
369 |
-
if
|
370 |
-
|
371 |
-
|
372 |
-
|
373 |
-
|
|
|
|
|
|
|
|
|
|
|
374 |
|
375 |
def generate_narration_audio(self, text_to_narrate, output_filename="narration_overall.mp3"):
|
376 |
-
#
|
377 |
if not self.USE_ELEVENLABS or not self.elevenlabs_client or not text_to_narrate:
|
378 |
logger.info("ElevenLabs conditions not met (API key, client init, or text). Skipping audio.")
|
379 |
return None
|
380 |
-
|
381 |
audio_filepath = os.path.join(self.output_dir, output_filename)
|
382 |
try:
|
383 |
logger.info(f"Generating ElevenLabs audio (Voice ID: {self.elevenlabs_voice_id}) for: {text_to_narrate[:70]}...")
|
384 |
-
|
385 |
audio_stream_method = None
|
386 |
if hasattr(self.elevenlabs_client, 'text_to_speech') and hasattr(self.elevenlabs_client.text_to_speech, 'stream'):
|
387 |
-
audio_stream_method = self.elevenlabs_client.text_to_speech.stream
|
388 |
-
|
389 |
-
elif hasattr(self.elevenlabs_client, '
|
390 |
-
audio_stream_method = self.elevenlabs_client.generate_stream
|
391 |
-
logger.info("Using elevenlabs_client.generate_stream()")
|
392 |
-
elif hasattr(self.elevenlabs_client, 'generate'): # Fallback to non-streaming
|
393 |
logger.info("Using elevenlabs_client.generate() (non-streaming).")
|
394 |
-
# This one doesn't return a stream, it returns bytes directly
|
395 |
voice_param = Voice(voice_id=str(self.elevenlabs_voice_id), settings=self.elevenlabs_voice_settings) if Voice and self.elevenlabs_voice_settings else str(self.elevenlabs_voice_id)
|
396 |
-
audio_bytes = self.elevenlabs_client.generate(
|
397 |
-
|
398 |
-
|
399 |
-
|
400 |
-
)
|
401 |
-
with open(audio_filepath, "wb") as f:
|
402 |
-
f.write(audio_bytes)
|
403 |
-
logger.info(f"ElevenLabs audio (non-streamed) saved: {audio_filepath}")
|
404 |
-
return audio_filepath
|
405 |
-
else:
|
406 |
-
logger.error("No recognized audio generation method found on ElevenLabs client.")
|
407 |
-
return None
|
408 |
|
409 |
-
# If we have a streaming method
|
410 |
if audio_stream_method:
|
411 |
voice_param_for_stream = {"voice_id": str(self.elevenlabs_voice_id)}
|
412 |
-
#
|
413 |
-
# if self.elevenlabs_voice_settings and hasattr(self.elevenlabs_voice_settings, 'dict'):
|
414 |
-
# voice_param_for_stream["voice_settings"] = self.elevenlabs_voice_settings.dict()
|
415 |
-
# For Pydantic v2 style for elevenlabs skd >=1.0
|
416 |
-
if self.elevenlabs_voice_settings and hasattr(self.elevenlabs_voice_settings, 'model_dump'):
|
417 |
voice_param_for_stream["voice_settings"] = self.elevenlabs_voice_settings.model_dump()
|
418 |
-
elif self.elevenlabs_voice_settings : #
|
419 |
-
voice_param_for_stream["voice_settings"] = self.elevenlabs_voice_settings
|
420 |
-
|
421 |
-
|
422 |
-
|
423 |
-
model_id="eleven_multilingual_v2",
|
424 |
-
**voice_param_for_stream
|
425 |
-
)
|
426 |
with open(audio_filepath, "wb") as f:
|
427 |
for chunk in audio_data_iterator:
|
428 |
if chunk: f.write(chunk)
|
429 |
-
logger.info(f"ElevenLabs audio (streamed) saved: {audio_filepath}")
|
430 |
-
|
431 |
-
|
432 |
-
except AttributeError as ae:
|
433 |
-
logger.error(f"AttributeError with ElevenLabs client: {ae}. SDK method/params might be different.", exc_info=True)
|
434 |
-
except Exception as e:
|
435 |
-
logger.error(f"Error generating ElevenLabs audio: {e}", exc_info=True)
|
436 |
return None
|
437 |
|
438 |
def assemble_animatic_from_assets(self, asset_data_list, overall_narration_path=None, output_filename="final_video.mp4", fps=24):
|
439 |
-
"""
|
440 |
-
Assembles the final video from a list of assets (images or video clips).
|
441 |
-
Each item in asset_data_list should be a dict like:
|
442 |
-
{'path': 'path/to/asset', 'type': 'image'|'video', 'duration': desired_scene_duration_in_animatic,
|
443 |
-
'scene_num': num, 'key_action': 'text'}
|
444 |
-
"""
|
445 |
if not asset_data_list:
|
446 |
logger.warning("No asset data provided for animatic assembly.")
|
447 |
return None
|
448 |
|
449 |
processed_moviepy_clips = []
|
450 |
narration_audio_clip = None
|
451 |
-
final_composite_clip = None
|
452 |
total_video_duration_from_assets = sum(item.get('duration', 4.5) for item in asset_data_list)
|
453 |
logger.info(f"Assembling animatic from {len(asset_data_list)} assets. Target frame: {self.video_frame_size}. Approx total duration: {total_video_duration_from_assets:.2f}s.")
|
454 |
|
455 |
for i, asset_info in enumerate(asset_data_list):
|
456 |
asset_path = asset_info.get('path')
|
457 |
asset_type = asset_info.get('type')
|
458 |
-
|
459 |
-
target_scene_duration = asset_info.get('duration', 4.5) # Default if not specified
|
460 |
scene_num = asset_info.get('scene_num', i + 1)
|
461 |
key_action = asset_info.get('key_action', '')
|
462 |
|
|
|
|
|
463 |
if not (asset_path and os.path.exists(asset_path)):
|
464 |
logger.warning(f"Asset not found for Scene {scene_num}: {asset_path}. Skipping.")
|
465 |
continue
|
@@ -467,65 +356,82 @@ class VisualEngine:
|
|
467 |
logger.warning(f"Scene {scene_num} has invalid duration ({target_scene_duration}s). Skipping.")
|
468 |
continue
|
469 |
|
470 |
-
|
471 |
try:
|
472 |
if asset_type == 'image':
|
|
|
473 |
pil_img = Image.open(asset_path)
|
474 |
-
|
|
|
|
|
|
|
|
|
|
|
475 |
img_copy = pil_img.copy()
|
476 |
resample_filter = Image.Resampling.LANCZOS if hasattr(Image.Resampling, 'LANCZOS') else (Image.ANTIALIAS if hasattr(Image, 'ANTIALIAS') else Image.BILINEAR)
|
477 |
img_copy.thumbnail(self.video_frame_size, resample_filter)
|
478 |
-
|
|
|
|
|
|
|
479 |
xo, yo = (self.video_frame_size[0] - img_copy.width) // 2, (self.video_frame_size[1] - img_copy.height) // 2
|
480 |
-
|
481 |
-
|
482 |
-
current_clip_base = ImageClip(frame_np).set_duration(target_scene_duration)
|
483 |
|
484 |
-
#
|
485 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
486 |
end_scale = random.uniform(1.03, 1.08)
|
487 |
-
|
488 |
-
|
489 |
-
|
490 |
-
current_clip = current_clip_base
|
491 |
|
492 |
elif asset_type == 'video':
|
493 |
-
|
494 |
-
#
|
495 |
-
|
496 |
-
|
|
|
497 |
if source_video_clip.duration > target_scene_duration:
|
498 |
-
|
499 |
elif source_video_clip.duration < target_scene_duration:
|
500 |
-
|
501 |
-
|
502 |
-
|
503 |
-
|
504 |
-
|
505 |
-
logger.info(f"Runway clip for S{scene_num} ({source_video_clip.duration:.2f}s) shorter than target ({target_scene_duration:.2f}s), will play once.")
|
506 |
-
else: # Durations match
|
507 |
-
current_clip = source_video_clip
|
508 |
|
509 |
-
#
|
510 |
-
|
511 |
-
current_clip = current_clip.set_duration(target_scene_duration)
|
512 |
-
|
513 |
|
514 |
-
|
515 |
-
|
516 |
-
|
517 |
|
518 |
-
#
|
519 |
-
if
|
|
|
520 |
source_video_clip.close()
|
|
|
521 |
|
|
|
522 |
|
523 |
-
|
524 |
-
logger.
|
525 |
-
continue
|
526 |
-
|
527 |
-
# Add text overlay
|
528 |
-
if current_clip and key_action:
|
529 |
text_overlay_duration = min(target_scene_duration - 0.5, target_scene_duration * 0.8) if target_scene_duration > 0.5 else target_scene_duration
|
530 |
text_overlay_start = (target_scene_duration - text_overlay_duration) / 2.0
|
531 |
if text_overlay_duration > 0:
|
@@ -535,61 +441,48 @@ class VisualEngine:
|
|
535 |
method='caption', align='West', size=(self.video_frame_size[0] * 0.9, None),
|
536 |
kerning=-1, stroke_color='black', stroke_width=1.5
|
537 |
).set_duration(text_overlay_duration).set_start(text_overlay_start).set_position(('center', 0.92), relative=True)
|
538 |
-
|
|
|
539 |
|
540 |
-
if
|
541 |
-
|
|
|
|
|
|
|
542 |
|
543 |
-
except Exception as e:
|
544 |
-
logger.error(f"Error processing asset for Scene {scene_num} ({asset_path}): {e}", exc_info=True)
|
545 |
-
if current_clip and hasattr(current_clip, 'close'): current_clip.close() # Ensure closure on error
|
546 |
-
|
547 |
-
if not processed_moviepy_clips:
|
548 |
-
logger.warning("No MoviePy clips successfully processed. Aborting animatic assembly.")
|
549 |
-
return None
|
550 |
|
|
|
|
|
551 |
transition_duration = 0.75
|
552 |
try:
|
553 |
-
if len(processed_moviepy_clips) > 1:
|
554 |
-
|
555 |
-
|
556 |
-
final_composite_clip = processed_moviepy_clips[0]
|
557 |
-
else: # Should have been caught above, but defensive
|
558 |
-
logger.error("No clips available for final concatenation.")
|
559 |
-
return None
|
560 |
|
|
|
|
|
561 |
|
562 |
-
if final_composite_clip.duration >
|
563 |
-
final_composite_clip = final_composite_clip.fx(vfx.fadein, transition_duration).fx(vfx.fadeout, transition_duration)
|
564 |
-
elif final_composite_clip.duration > 0:
|
565 |
-
final_composite_clip = final_composite_clip.fx(vfx.fadein, min(transition_duration, final_composite_clip.duration/2.0))
|
566 |
-
|
567 |
-
if overall_narration_path and os.path.exists(overall_narration_path):
|
568 |
try:
|
569 |
narration_audio_clip = AudioFileClip(overall_narration_path)
|
570 |
-
if
|
571 |
logger.info(f"Narration ({narration_audio_clip.duration:.2f}s) shorter than visuals ({final_composite_clip.duration:.2f}s). Trimming video.")
|
572 |
final_composite_clip = final_composite_clip.subclip(0, narration_audio_clip.duration)
|
573 |
-
|
574 |
-
|
575 |
-
if narration_audio_clip and final_composite_clip.duration > 0: # Check again
|
576 |
-
final_composite_clip = final_composite_clip.set_audio(narration_audio_clip)
|
577 |
-
logger.info("Overall narration added.")
|
578 |
except Exception as e: logger.error(f"Adding narration error: {e}", exc_info=True)
|
|
|
579 |
|
580 |
if final_composite_clip and final_composite_clip.duration > 0:
|
581 |
output_path = os.path.join(self.output_dir, output_filename)
|
582 |
logger.info(f"Writing final animatic: {output_path} (Duration: {final_composite_clip.duration:.2f}s)")
|
583 |
-
final_composite_clip.write_videofile(
|
584 |
-
|
585 |
-
|
586 |
-
remove_temp=True, threads=os.cpu_count() or 2, logger='bar', bitrate="5000k"
|
587 |
-
)
|
588 |
logger.info(f"Animatic created: {output_path}"); return output_path
|
589 |
-
else: logger.error("Final animatic clip invalid
|
590 |
except Exception as e: logger.error(f"Animatic writing error: {e}", exc_info=True); return None
|
591 |
finally:
|
592 |
-
for
|
593 |
-
if hasattr(
|
594 |
if narration_audio_clip and hasattr(narration_audio_clip, 'close'): narration_audio_clip.close()
|
595 |
if final_composite_clip and hasattr(final_composite_clip, 'close'): final_composite_clip.close()
|
|
|
24 |
import logging
|
25 |
|
26 |
logger = logging.getLogger(__name__)
|
27 |
+
logger.setLevel(logging.INFO) # Set default logging level for this module
|
28 |
|
29 |
# --- ElevenLabs Client Import ---
|
30 |
ELEVENLABS_CLIENT_IMPORTED = False
|
|
|
38 |
Voice = ImportedVoice
|
39 |
VoiceSettings = ImportedVoiceSettings
|
40 |
ELEVENLABS_CLIENT_IMPORTED = True
|
41 |
+
logger.info("ElevenLabs client components imported successfully.")
|
42 |
except Exception as e_eleven:
|
43 |
+
logger.warning(f"ElevenLabs client import failed: {e_eleven}. Audio generation will be disabled.")
|
44 |
|
45 |
# --- RunwayML Client Import (Placeholder) ---
|
46 |
RUNWAYML_SDK_IMPORTED = False
|
47 |
RunwayMLClient = None # Placeholder for the actual RunwayML client class
|
48 |
try:
|
|
|
49 |
# Example: from runwayml import RunwayClient as ImportedRunwayMLClient
|
50 |
# RunwayMLClient = ImportedRunwayMLClient
|
51 |
# RUNWAYML_SDK_IMPORTED = True
|
|
|
52 |
logger.info("RunwayML SDK import is a placeholder. Actual SDK needed for Runway features.")
|
53 |
except ImportError:
|
54 |
logger.warning("RunwayML SDK (placeholder) not found. RunwayML video generation will be disabled.")
|
|
|
64 |
self.font_filename = "arial.ttf"
|
65 |
font_paths_to_try = [
|
66 |
self.font_filename,
|
67 |
+
f"/usr/share/fonts/truetype/dejavu/DejaVuSans-Bold.ttf", # Common on Linux
|
68 |
+
f"/usr/share/fonts/truetype/liberation/LiberationSans-Bold.ttf", # Common on Linux
|
69 |
+
f"/System/Library/Fonts/Supplemental/Arial.ttf", # macOS
|
70 |
+
f"C:/Windows/Fonts/arial.ttf", # Windows
|
71 |
+
f"/usr/local/share/fonts/truetype/mycustomfonts/{self.font_filename}" # Custom container path
|
72 |
]
|
73 |
self.font_path_pil = next((p for p in font_paths_to_try if os.path.exists(p)), None)
|
74 |
self.font_size_pil = 20
|
75 |
self.video_overlay_font_size = 30
|
76 |
self.video_overlay_font_color = 'white'
|
77 |
+
self.video_overlay_font = 'Liberation-Sans-Bold' # For MoviePy TextClip (ImageMagick name)
|
78 |
|
79 |
try:
|
80 |
+
if self.font_path_pil:
|
81 |
+
self.font = ImageFont.truetype(self.font_path_pil, self.font_size_pil)
|
82 |
+
logger.info(f"Pillow font loaded: {self.font_path_pil}.")
|
83 |
+
else: # Fallback to default if no path found
|
84 |
+
self.font = ImageFont.load_default()
|
85 |
+
logger.warning("Custom Pillow font not found from paths. Using default. Text rendering might be basic.")
|
86 |
+
self.font_size_pil = 10 # Default font is smaller
|
87 |
+
except IOError as e_font: # Catch specific IOError for font loading
|
88 |
+
logger.error(f"Pillow font loading IOError for '{self.font_path_pil if self.font_path_pil else 'default'}': {e_font}. Using default.")
|
89 |
+
self.font = ImageFont.load_default()
|
90 |
+
self.font_size_pil = 10
|
91 |
|
92 |
self.openai_api_key = None; self.USE_AI_IMAGE_GENERATION = False
|
93 |
self.dalle_model = "dall-e-3"; self.image_size_dalle3 = "1792x1024"
|
94 |
+
self.video_frame_size = (1280, 720) # Standard HD 16:9
|
95 |
|
96 |
self.elevenlabs_api_key = None; self.USE_ELEVENLABS = False
|
97 |
self.elevenlabs_client = None
|
|
|
101 |
else: self.elevenlabs_voice_settings = None
|
102 |
|
103 |
self.pexels_api_key = None; self.USE_PEXELS = False
|
|
|
|
|
104 |
self.runway_api_key = None; self.USE_RUNWAYML = False
|
105 |
+
self.runway_client = None
|
|
|
106 |
|
107 |
logger.info("VisualEngine initialized.")
|
108 |
|
109 |
def set_openai_api_key(self,k):
|
110 |
self.openai_api_key=k; self.USE_AI_IMAGE_GENERATION=bool(k)
|
111 |
+
logger.info(f"DALL-E ({self.dalle_model}) {'Ready.' if k else 'Disabled (no API key).'}")
|
112 |
|
113 |
def set_elevenlabs_api_key(self,api_key, voice_id_from_secret=None):
|
114 |
self.elevenlabs_api_key=api_key
|
|
|
119 |
self.USE_ELEVENLABS=bool(self.elevenlabs_client)
|
120 |
logger.info(f"ElevenLabs Client {'Ready' if self.USE_ELEVENLABS else 'Failed Init'} (Voice ID: {self.elevenlabs_voice_id}).")
|
121 |
except Exception as e: logger.error(f"ElevenLabs client init error: {e}. Disabled.", exc_info=True); self.USE_ELEVENLABS=False
|
122 |
+
else: self.USE_ELEVENLABS=False; logger.info("ElevenLabs Disabled (no API key or SDK issue).")
|
123 |
|
124 |
def set_pexels_api_key(self,k):
|
125 |
self.pexels_api_key=k; self.USE_PEXELS=bool(k)
|
126 |
+
logger.info(f"Pexels Search {'Ready.' if k else 'Disabled (no API key).'}")
|
127 |
|
|
|
128 |
def set_runway_api_key(self, k):
|
129 |
self.runway_api_key = k
|
130 |
+
if k and RUNWAYML_SDK_IMPORTED and RunwayMLClient:
|
131 |
try:
|
132 |
# self.runway_client = RunwayMLClient(api_key=k) # Actual initialization
|
133 |
+
self.USE_RUNWAYML = True # Assume success for placeholder with hypothetical SDK
|
134 |
+
logger.info(f"RunwayML Client (Placeholder with SDK) {'Ready.' if self.USE_RUNWAYML else 'Failed Init.'}")
|
135 |
+
except Exception as e: logger.error(f"RunwayML client (Placeholder with SDK) init error: {e}. Disabled.", exc_info=True); self.USE_RUNWAYML = False
|
136 |
+
elif k: # API key provided, but SDK might not be used/imported (e.g., direct HTTP)
|
137 |
+
self.USE_RUNWAYML = True
|
138 |
+
logger.info("RunwayML API Key set. Using direct API calls or placeholder (SDK not fully integrated/imported).")
|
139 |
+
else: self.USE_RUNWAYML = False; logger.info("RunwayML Disabled (no API key).")
|
|
|
|
|
|
|
|
|
|
|
140 |
|
141 |
def _get_text_dimensions(self,text_content,font_obj):
|
|
|
142 |
if not text_content: return 0,self.font_size_pil
|
143 |
try:
|
144 |
+
if hasattr(font_obj,'getbbox'):
|
145 |
bbox=font_obj.getbbox(text_content);w=bbox[2]-bbox[0];h=bbox[3]-bbox[1]
|
146 |
return w, h if h > 0 else self.font_size_pil
|
147 |
+
elif hasattr(font_obj,'getsize'):
|
148 |
w,h=font_obj.getsize(text_content)
|
149 |
return w, h if h > 0 else self.font_size_pil
|
150 |
+
else: return int(len(text_content)*self.font_size_pil*0.6),int(self.font_size_pil*1.2 if self.font_size_pil*1.2>0 else self.font_size_pil)
|
151 |
+
except Exception as e: logger.warning(f"Error in _get_text_dimensions for '{text_content[:20]}...': {e}"); return int(len(text_content)*self.font_size_pil*0.6),int(self.font_size_pil*1.2)
|
|
|
|
|
|
|
|
|
152 |
|
153 |
def _create_placeholder_image_content(self,text_description,filename,size=None):
|
154 |
+
# (No significant changes from your previous correct version)
|
155 |
if size is None: size = self.video_frame_size
|
156 |
img=Image.new('RGB',size,color=(20,20,40));d=ImageDraw.Draw(img);padding=25;max_w=size[0]-(2*padding);lines=[];
|
157 |
if not text_description: text_description="(Placeholder: No prompt text)"
|
|
|
162 |
else:
|
163 |
if current_line: lines.append(current_line.strip());
|
164 |
current_line=word+" "
|
165 |
+
if current_line.strip(): lines.append(current_line.strip())
|
166 |
+
if not lines and text_description: lines.append(text_description[:int(max_w//(self.font_size_pil*0.6 +1))]+"..." if text_description else "(Text too long)")
|
167 |
elif not lines: lines.append("(Placeholder Text Error)")
|
|
|
168 |
_,single_line_h=self._get_text_dimensions("Ay",self.font); single_line_h = single_line_h if single_line_h > 0 else self.font_size_pil + 2
|
|
|
169 |
max_lines_to_display=min(len(lines),(size[1]-(2*padding))//(single_line_h+2)) if single_line_h > 0 else 1
|
170 |
+
if max_lines_to_display <=0: max_lines_to_display = 1
|
|
|
171 |
y_text_start = padding + (size[1]-(2*padding) - max_lines_to_display*(single_line_h+2))/2.0
|
172 |
y_text = y_text_start
|
|
|
173 |
for i in range(max_lines_to_display):
|
174 |
line_content=lines[i];line_w,_=self._get_text_dimensions(line_content,self.font);x_text=(size[0]-line_w)/2.0
|
175 |
d.text((x_text,y_text),line_content,font=self.font,fill=(200,200,180));y_text+=single_line_h+2
|
|
|
178 |
try:img.save(filepath);return filepath
|
179 |
except Exception as e:logger.error(f"Saving placeholder image {filepath}: {e}", exc_info=True);return None
|
180 |
|
|
|
181 |
def _search_pexels_image(self, query, output_filename_base):
|
182 |
+
# (No significant changes from your previous correct version)
|
183 |
if not self.USE_PEXELS or not self.pexels_api_key: return None
|
184 |
headers = {"Authorization": self.pexels_api_key}; params = {"query": query, "per_page": 1, "orientation": "landscape", "size": "large"}
|
|
|
185 |
pexels_filename = output_filename_base.replace(".png", f"_pexels_{random.randint(1000,9999)}.jpg").replace(".mp4", f"_pexels_{random.randint(1000,9999)}.jpg")
|
186 |
filepath = os.path.join(self.output_dir, pexels_filename)
|
187 |
try:
|
|
|
189 |
response = requests.get("https://api.pexels.com/v1/search", headers=headers, params=params, timeout=20)
|
190 |
response.raise_for_status(); data = response.json()
|
191 |
if data.get("photos") and len(data["photos"]) > 0:
|
192 |
+
photo_url = data["photos"][0]["src"]["large2x"]
|
193 |
image_response = requests.get(photo_url, timeout=60); image_response.raise_for_status()
|
194 |
img_data = Image.open(io.BytesIO(image_response.content))
|
195 |
if img_data.mode != 'RGB': img_data = img_data.convert('RGB')
|
|
|
198 |
except Exception as e: logger.error(f"Pexels search/download for query '{query}': {e}", exc_info=True)
|
199 |
return None
|
200 |
|
|
|
|
|
201 |
def _generate_video_clip_with_runwayml(self, prompt_text, scene_identifier_filename_base, target_duration_seconds=4, input_image_path=None):
|
|
|
|
|
|
|
|
|
202 |
if not self.USE_RUNWAYML or not self.runway_api_key:
|
203 |
logger.warning("RunwayML not enabled or API key missing. Cannot generate video clip.")
|
204 |
return None
|
|
|
205 |
output_video_filename = scene_identifier_filename_base.replace(".png", ".mp4") # Ensure .mp4 extension
|
206 |
output_video_filepath = os.path.join(self.output_dir, output_video_filename)
|
|
|
207 |
logger.info(f"Attempting RunwayML video generation for: {prompt_text[:100]}... (Target duration: {target_duration_seconds}s)")
|
208 |
+
# --- START ACTUAL RUNWAYML API INTERACTION (HYPOTHETICAL - NEEDS IMPLEMENTATION) ---
|
209 |
+
# ... (Your actual RunwayML API call logic would go here) ...
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
210 |
# --- END ACTUAL RUNWAYML API INTERACTION (HYPOTHETICAL) ---
|
211 |
+
logger.warning("Using PLACEHOLDER video generation for RunwayML as actual API calls are not implemented.")
|
|
|
|
|
|
|
|
|
212 |
return self._create_placeholder_video_content(f"[RunwayML Placeholder] {prompt_text}", output_video_filename, duration=target_duration_seconds)
|
213 |
|
214 |
def _create_placeholder_video_content(self, text_description, filename, duration=4, size=None):
|
|
|
215 |
if size is None: size = self.video_frame_size
|
216 |
filepath = os.path.join(self.output_dir, filename)
|
|
|
|
|
217 |
txt_clip = TextClip(text_description, fontsize=50, color='white', font=self.video_overlay_font,
|
218 |
bg_color='black', size=size, method='caption').set_duration(duration)
|
|
|
219 |
try:
|
220 |
txt_clip.write_videofile(filepath, fps=24, codec='libx264', preset='ultrafast', logger=None)
|
221 |
logger.info(f"Placeholder video saved: {filepath}")
|
222 |
return filepath
|
223 |
+
except Exception as e: logger.error(f"Failed to create placeholder video {filepath}: {e}", exc_info=True); return None
|
|
|
|
|
224 |
finally:
|
225 |
if hasattr(txt_clip, 'close'): txt_clip.close()
|
|
|
|
|
226 |
|
227 |
def generate_scene_asset(self, image_prompt_text, scene_data, scene_identifier_filename_base,
|
228 |
generate_as_video_clip=False, runway_target_duration=4, input_image_for_runway=None):
|
|
|
|
|
|
|
|
|
|
|
229 |
base_name, _ = os.path.splitext(scene_identifier_filename_base)
|
230 |
+
asset_info = {'path': None, 'type': 'none', 'error': True, 'prompt_used': image_prompt_text, 'error_message': 'Generation not attempted'}
|
231 |
|
232 |
if generate_as_video_clip and self.USE_RUNWAYML:
|
233 |
logger.info(f"Attempting RunwayML video clip generation for {base_name}")
|
234 |
video_path = self._generate_video_clip_with_runwayml(
|
235 |
+
image_prompt_text, base_name,
|
|
|
236 |
target_duration_seconds=runway_target_duration,
|
237 |
input_image_path=input_image_for_runway
|
238 |
)
|
239 |
if video_path and os.path.exists(video_path):
|
240 |
+
asset_info = {'path': video_path, 'type': 'video', 'error': False, 'prompt_used': image_prompt_text}
|
241 |
+
return asset_info # Successfully generated video
|
242 |
else:
|
243 |
logger.warning(f"RunwayML video clip generation failed for {base_name}. Falling back to image.")
|
244 |
+
asset_info['error_message'] = "RunwayML video generation failed."
|
245 |
# Fall through to image generation
|
246 |
|
247 |
# Image Generation (DALL-E, Pexels, Placeholder)
|
248 |
+
image_filename_with_ext = base_name + ".png" # Ensure .png for image
|
|
|
249 |
filepath = os.path.join(self.output_dir, image_filename_with_ext)
|
250 |
+
asset_info['type'] = 'image' # Tentatively set type to image for this path
|
251 |
|
252 |
if self.USE_AI_IMAGE_GENERATION and self.openai_api_key:
|
253 |
max_retries = 2
|
254 |
for attempt in range(max_retries):
|
255 |
try:
|
|
|
256 |
logger.info(f"Attempt {attempt+1}: DALL-E ({self.dalle_model}) for: {image_prompt_text[:100]}...")
|
257 |
client = openai.OpenAI(api_key=self.openai_api_key, timeout=90.0)
|
258 |
response = client.images.generate(model=self.dalle_model, prompt=image_prompt_text, n=1, size=self.image_size_dalle3, quality="hd", response_format="url", style="vivid")
|
|
|
262 |
img_data = Image.open(io.BytesIO(image_response.content));
|
263 |
if img_data.mode != 'RGB': img_data = img_data.convert('RGB')
|
264 |
img_data.save(filepath); logger.info(f"AI Image (DALL-E) saved: {filepath}");
|
265 |
+
asset_info = {'path': filepath, 'type': 'image', 'error': False, 'prompt_used': image_prompt_text, 'revised_prompt': revised_prompt}
|
266 |
+
return asset_info
|
267 |
+
except openai.RateLimitError as e_rate: logger.warning(f"OpenAI Rate Limit: {e_rate}. Retrying..."); time.sleep(5 * (attempt + 1)); asset_info['error_message'] = str(e_rate)
|
268 |
+
except openai.APIError as e_api: logger.error(f"OpenAI API Error: {e_api}"); asset_info['error_message'] = str(e_api); break
|
269 |
+
except requests.exceptions.RequestException as e_req: logger.error(f"Requests Error (DALL-E download): {e_req}"); asset_info['error_message'] = str(e_req); break
|
270 |
+
except Exception as e_gen: logger.error(f"Generic error (DALL-E gen): {e_gen}", exc_info=True); asset_info['error_message'] = str(e_gen); break
|
271 |
+
if attempt == max_retries - 1: logger.error("Max retries for DALL-E RateLimitError."); break
|
272 |
+
if asset_info['error']: logger.warning("DALL-E generation failed. Trying Pexels fallback...")
|
273 |
|
274 |
+
if self.USE_PEXELS and (asset_info['error'] or not (self.USE_AI_IMAGE_GENERATION and self.openai_api_key)): # Try Pexels if DALL-E failed or disabled
|
|
|
275 |
pexels_query_text = scene_data.get('pexels_search_query_감독', f"{scene_data.get('emotional_beat','')} {scene_data.get('setting_description','')}")
|
276 |
+
pexels_path = self._search_pexels_image(pexels_query_text, image_filename_with_ext)
|
277 |
if pexels_path:
|
278 |
+
asset_info = {'path': pexels_path, 'type': 'image', 'error': False, 'prompt_used': f"Pexels: {pexels_query_text}"}
|
279 |
+
return asset_info
|
280 |
+
asset_info['error_message'] = (asset_info.get('error_message', "") + " Pexels search also failed or disabled.").strip()
|
281 |
+
if not asset_info['error']: logger.warning("Pexels search failed or disabled.") # If DALL-E wasn't even tried
|
282 |
+
|
283 |
+
# Fallback to placeholder if all else fails
|
284 |
+
if asset_info['error']: # Only create placeholder if previous steps failed
|
285 |
+
logger.warning("All generation methods failed. Using placeholder image.")
|
286 |
+
placeholder_prompt_text = asset_info.get('prompt_used', image_prompt_text) # Use the prompt that was attempted
|
287 |
+
placeholder_path = self._create_placeholder_image_content(f"[Fallback Placeholder] {placeholder_prompt_text[:100]}...", image_filename_with_ext)
|
288 |
+
if placeholder_path:
|
289 |
+
asset_info = {'path': placeholder_path, 'type': 'image', 'error': False, 'prompt_used': placeholder_prompt_text}
|
290 |
+
return asset_info
|
291 |
+
else: # Final failure
|
292 |
+
asset_info['error_message'] = (asset_info.get('error_message', "") + " Placeholder creation also failed.").strip()
|
293 |
+
return asset_info # Return whatever state asset_info is in (could be error=True)
|
294 |
|
295 |
def generate_narration_audio(self, text_to_narrate, output_filename="narration_overall.mp3"):
|
296 |
+
# (No significant changes from your previous correct version, ensure error handling is robust)
|
297 |
if not self.USE_ELEVENLABS or not self.elevenlabs_client or not text_to_narrate:
|
298 |
logger.info("ElevenLabs conditions not met (API key, client init, or text). Skipping audio.")
|
299 |
return None
|
|
|
300 |
audio_filepath = os.path.join(self.output_dir, output_filename)
|
301 |
try:
|
302 |
logger.info(f"Generating ElevenLabs audio (Voice ID: {self.elevenlabs_voice_id}) for: {text_to_narrate[:70]}...")
|
|
|
303 |
audio_stream_method = None
|
304 |
if hasattr(self.elevenlabs_client, 'text_to_speech') and hasattr(self.elevenlabs_client.text_to_speech, 'stream'):
|
305 |
+
audio_stream_method = self.elevenlabs_client.text_to_speech.stream; logger.info("Using elevenlabs_client.text_to_speech.stream()")
|
306 |
+
elif hasattr(self.elevenlabs_client, 'generate_stream') : audio_stream_method = self.elevenlabs_client.generate_stream; logger.info("Using elevenlabs_client.generate_stream()")
|
307 |
+
elif hasattr(self.elevenlabs_client, 'generate'):
|
|
|
|
|
|
|
308 |
logger.info("Using elevenlabs_client.generate() (non-streaming).")
|
|
|
309 |
voice_param = Voice(voice_id=str(self.elevenlabs_voice_id), settings=self.elevenlabs_voice_settings) if Voice and self.elevenlabs_voice_settings else str(self.elevenlabs_voice_id)
|
310 |
+
audio_bytes = self.elevenlabs_client.generate(text=text_to_narrate, voice=voice_param, model="eleven_multilingual_v2")
|
311 |
+
with open(audio_filepath, "wb") as f: f.write(audio_bytes)
|
312 |
+
logger.info(f"ElevenLabs audio (non-streamed) saved: {audio_filepath}"); return audio_filepath
|
313 |
+
else: logger.error("No recognized audio generation method found on ElevenLabs client."); return None
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
314 |
|
|
|
315 |
if audio_stream_method:
|
316 |
voice_param_for_stream = {"voice_id": str(self.elevenlabs_voice_id)}
|
317 |
+
if self.elevenlabs_voice_settings and hasattr(self.elevenlabs_voice_settings, 'model_dump'): # Pydantic v2 for elevenlabs sdk >=1.0
|
|
|
|
|
|
|
|
|
318 |
voice_param_for_stream["voice_settings"] = self.elevenlabs_voice_settings.model_dump()
|
319 |
+
elif self.elevenlabs_voice_settings and hasattr(self.elevenlabs_voice_settings, 'dict'): # Pydantic v1 for elevenlabs sdk <1.0
|
320 |
+
voice_param_for_stream["voice_settings"] = self.elevenlabs_voice_settings.dict()
|
321 |
+
elif self.elevenlabs_voice_settings : voice_param_for_stream["voice_settings"] = self.elevenlabs_voice_settings
|
322 |
+
|
323 |
+
audio_data_iterator = audio_stream_method(text=text_to_narrate, model_id="eleven_multilingual_v2", **voice_param_for_stream)
|
|
|
|
|
|
|
324 |
with open(audio_filepath, "wb") as f:
|
325 |
for chunk in audio_data_iterator:
|
326 |
if chunk: f.write(chunk)
|
327 |
+
logger.info(f"ElevenLabs audio (streamed) saved: {audio_filepath}"); return audio_filepath
|
328 |
+
except AttributeError as ae: logger.error(f"AttributeError with ElevenLabs client: {ae}. SDK method/params might be different.", exc_info=True)
|
329 |
+
except Exception as e: logger.error(f"Error generating ElevenLabs audio: {e}", exc_info=True)
|
|
|
|
|
|
|
|
|
330 |
return None
|
331 |
|
332 |
def assemble_animatic_from_assets(self, asset_data_list, overall_narration_path=None, output_filename="final_video.mp4", fps=24):
|
|
|
|
|
|
|
|
|
|
|
|
|
333 |
if not asset_data_list:
|
334 |
logger.warning("No asset data provided for animatic assembly.")
|
335 |
return None
|
336 |
|
337 |
processed_moviepy_clips = []
|
338 |
narration_audio_clip = None
|
339 |
+
final_composite_clip = None # Renamed to avoid conflict in finally block
|
340 |
total_video_duration_from_assets = sum(item.get('duration', 4.5) for item in asset_data_list)
|
341 |
logger.info(f"Assembling animatic from {len(asset_data_list)} assets. Target frame: {self.video_frame_size}. Approx total duration: {total_video_duration_from_assets:.2f}s.")
|
342 |
|
343 |
for i, asset_info in enumerate(asset_data_list):
|
344 |
asset_path = asset_info.get('path')
|
345 |
asset_type = asset_info.get('type')
|
346 |
+
target_scene_duration = asset_info.get('duration', 4.5)
|
|
|
347 |
scene_num = asset_info.get('scene_num', i + 1)
|
348 |
key_action = asset_info.get('key_action', '')
|
349 |
|
350 |
+
logger.info(f"Processing Scene {scene_num}: Path='{asset_path}', Type='{asset_type}', Target Duration='{target_scene_duration}'s")
|
351 |
+
|
352 |
if not (asset_path and os.path.exists(asset_path)):
|
353 |
logger.warning(f"Asset not found for Scene {scene_num}: {asset_path}. Skipping.")
|
354 |
continue
|
|
|
356 |
logger.warning(f"Scene {scene_num} has invalid duration ({target_scene_duration}s). Skipping.")
|
357 |
continue
|
358 |
|
359 |
+
current_clip_for_scene = None
|
360 |
try:
|
361 |
if asset_type == 'image':
|
362 |
+
logger.debug(f"S{scene_num}: Loading image asset from {asset_path}")
|
363 |
pil_img = Image.open(asset_path)
|
364 |
+
logger.debug(f"S{scene_num}: Image loaded. Mode: {pil_img.mode}, Size: {pil_img.size}")
|
365 |
+
|
366 |
+
# Ensure image is RGBA for consistent pasting, then convert to RGB for MoviePy
|
367 |
+
if pil_img.mode != 'RGBA':
|
368 |
+
pil_img = pil_img.convert('RGBA') # Convert to RGBA to handle transparency uniformly
|
369 |
+
|
370 |
img_copy = pil_img.copy()
|
371 |
resample_filter = Image.Resampling.LANCZOS if hasattr(Image.Resampling, 'LANCZOS') else (Image.ANTIALIAS if hasattr(Image, 'ANTIALIAS') else Image.BILINEAR)
|
372 |
img_copy.thumbnail(self.video_frame_size, resample_filter)
|
373 |
+
logger.debug(f"S{scene_num}: Image thumbnailed to: {img_copy.size}")
|
374 |
+
|
375 |
+
# Create an RGBA canvas, paste the (potentially RGBA) image onto it
|
376 |
+
canvas_rgba = Image.new('RGBA', self.video_frame_size, (0, 0, 0, 0)) # Fully transparent
|
377 |
xo, yo = (self.video_frame_size[0] - img_copy.width) // 2, (self.video_frame_size[1] - img_copy.height) // 2
|
378 |
+
canvas_rgba.paste(img_copy, (xo, yo), img_copy) # Paste using image's own alpha
|
379 |
+
logger.debug(f"S{scene_num}: Image pasted onto RGBA canvas.")
|
|
|
380 |
|
381 |
+
# Now create a final RGB canvas and paste the RGBA canvas onto it, effectively blending alpha
|
382 |
+
final_rgb_canvas = Image.new("RGB", self.video_frame_size, (random.randint(0,5), random.randint(0,5), random.randint(0,5))) # Dark background
|
383 |
+
final_rgb_canvas.paste(canvas_rgba, mask=canvas_rgba.split()[3]) # Use alpha channel of canvas_rgba as mask
|
384 |
+
|
385 |
+
debug_canvas_path = os.path.join(self.output_dir, f"debug_final_rgb_canvas_scene_{scene_num}.png")
|
386 |
+
try: final_rgb_canvas.save(debug_canvas_path); logger.info(f"DEBUG: Saved final RGB canvas for scene {scene_num} to {debug_canvas_path}")
|
387 |
+
except Exception as e_save_canvas: logger.error(f"DEBUG: Failed to save final RGB canvas for scene {scene_num}: {e_save_canvas}")
|
388 |
+
|
389 |
+
frame_np = np.array(final_rgb_canvas)
|
390 |
+
logger.debug(f"S{scene_num}: Final RGB canvas to NumPy. Shape: {frame_np.shape}, Dtype: {frame_np.dtype}")
|
391 |
+
if frame_np.size == 0: logger.error(f"S{scene_num}: NumPy array for ImageClip is empty! Skipping."); continue
|
392 |
+
|
393 |
+
current_clip_base = ImageClip(frame_np, transparent=False, ismask=False).set_duration(target_scene_duration)
|
394 |
+
logger.debug(f"S{scene_num}: Base ImageClip created.")
|
395 |
+
|
396 |
+
current_clip_for_scene = current_clip_base
|
397 |
+
try: # Ken Burns
|
398 |
end_scale = random.uniform(1.03, 1.08)
|
399 |
+
current_clip_for_scene = current_clip_base.fx(vfx.resize, lambda t: 1 + (end_scale - 1) * (t / target_scene_duration)).set_position('center')
|
400 |
+
logger.debug(f"S{scene_num}: Ken Burns effect applied.")
|
401 |
+
except Exception as e_fx: logger.error(f"S{scene_num}: Ken Burns error: {e_fx}. Using static.", exc_info=False); current_clip_for_scene = current_clip_base
|
|
|
402 |
|
403 |
elif asset_type == 'video':
|
404 |
+
logger.debug(f"S{scene_num}: Loading video asset from {asset_path}")
|
405 |
+
# Ensure target_resolution is (height, width) for VideoFileClip resizing parameter
|
406 |
+
source_video_clip = VideoFileClip(asset_path, target_resolution=(self.video_frame_size[1], self.video_frame_size[0]) if self.video_frame_size else None)
|
407 |
+
|
408 |
+
temp_clip = source_video_clip # Work with a temporary variable
|
409 |
if source_video_clip.duration > target_scene_duration:
|
410 |
+
temp_clip = source_video_clip.subclip(0, target_scene_duration)
|
411 |
elif source_video_clip.duration < target_scene_duration:
|
412 |
+
if target_scene_duration / source_video_clip.duration > 1.5 and source_video_clip.duration > 0.1:
|
413 |
+
temp_clip = source_video_clip.loop(duration=target_scene_duration)
|
414 |
+
else: # Play once, MoviePy will pad if needed during concatenation if durations differ
|
415 |
+
temp_clip = source_video_clip.set_duration(source_video_clip.duration) # Keep its own duration
|
416 |
+
logger.info(f"Video clip for S{scene_num} ({source_video_clip.duration:.2f}s) is shorter than target animatic duration ({target_scene_duration:.2f}s). It will play once at its native length.")
|
|
|
|
|
|
|
417 |
|
418 |
+
# Crucially, ensure the clip used in concatenation has the target_scene_duration
|
419 |
+
current_clip_for_scene = temp_clip.set_duration(target_scene_duration)
|
|
|
|
|
420 |
|
421 |
+
if current_clip_for_scene.size != list(self.video_frame_size):
|
422 |
+
logger.debug(f"S{scene_num}: Resizing video clip from {current_clip_for_scene.size} to {self.video_frame_size}")
|
423 |
+
current_clip_for_scene = current_clip_for_scene.resize(self.video_frame_size)
|
424 |
|
425 |
+
# Only close source_video_clip if it's different from what we are keeping (e.g., after subclip)
|
426 |
+
# And if it's not the same object as current_clip_for_scene
|
427 |
+
if source_video_clip is not current_clip_for_scene and hasattr(source_video_clip, 'close'):
|
428 |
source_video_clip.close()
|
429 |
+
logger.debug(f"S{scene_num}: Video asset processed. Final duration for scene: {current_clip_for_scene.duration:.2f}s")
|
430 |
|
431 |
+
else: logger.warning(f"S{scene_num}: Unknown asset type '{asset_type}'. Skipping."); continue
|
432 |
|
433 |
+
if current_clip_for_scene and key_action: # Add text overlay
|
434 |
+
logger.debug(f"S{scene_num}: Adding text overlay: '{key_action}'")
|
|
|
|
|
|
|
|
|
435 |
text_overlay_duration = min(target_scene_duration - 0.5, target_scene_duration * 0.8) if target_scene_duration > 0.5 else target_scene_duration
|
436 |
text_overlay_start = (target_scene_duration - text_overlay_duration) / 2.0
|
437 |
if text_overlay_duration > 0:
|
|
|
441 |
method='caption', align='West', size=(self.video_frame_size[0] * 0.9, None),
|
442 |
kerning=-1, stroke_color='black', stroke_width=1.5
|
443 |
).set_duration(text_overlay_duration).set_start(text_overlay_start).set_position(('center', 0.92), relative=True)
|
444 |
+
current_clip_for_scene = CompositeVideoClip([current_clip_for_scene, txt_clip], size=self.video_frame_size, use_bgclip=True)
|
445 |
+
logger.debug(f"S{scene_num}: Text overlay composited.")
|
446 |
|
447 |
+
if current_clip_for_scene: processed_moviepy_clips.append(current_clip_for_scene); logger.info(f"S{scene_num}: Asset successfully processed and added to final list.")
|
448 |
+
except Exception as e: logger.error(f"Error processing asset for Scene {scene_num} ({asset_path}): {e}", exc_info=True)
|
449 |
+
finally: # Ensure individual clips are closed if they were opened and an error occurred mid-processing
|
450 |
+
if current_clip_for_scene and asset_type == 'video' and hasattr(current_clip_for_scene, 'reader') and current_clip_for_scene.reader:
|
451 |
+
if hasattr(current_clip_for_scene, 'close'): current_clip_for_scene.close()
|
452 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
453 |
|
454 |
+
if not processed_moviepy_clips: logger.warning("No MoviePy clips processed. Aborting animatic assembly."); return None
|
455 |
+
|
456 |
transition_duration = 0.75
|
457 |
try:
|
458 |
+
if len(processed_moviepy_clips) > 1: final_composite_clip = concatenate_videoclips(processed_moviepy_clips, padding=-transition_duration, method="compose")
|
459 |
+
elif processed_moviepy_clips: final_composite_clip = processed_moviepy_clips[0]
|
460 |
+
else: logger.error("No clips for final concatenation."); return None
|
|
|
|
|
|
|
|
|
461 |
|
462 |
+
if final_composite_clip.duration > transition_duration * 2: final_composite_clip = final_composite_clip.fx(vfx.fadein, transition_duration).fx(vfx.fadeout, transition_duration)
|
463 |
+
elif final_composite_clip.duration > 0: final_composite_clip = final_composite_clip.fx(vfx.fadein, min(transition_duration, final_composite_clip.duration/2.0))
|
464 |
|
465 |
+
if overall_narration_path and os.path.exists(overall_narration_path) and final_composite_clip.duration > 0:
|
|
|
|
|
|
|
|
|
|
|
466 |
try:
|
467 |
narration_audio_clip = AudioFileClip(overall_narration_path)
|
468 |
+
if narration_audio_clip.duration < final_composite_clip.duration:
|
469 |
logger.info(f"Narration ({narration_audio_clip.duration:.2f}s) shorter than visuals ({final_composite_clip.duration:.2f}s). Trimming video.")
|
470 |
final_composite_clip = final_composite_clip.subclip(0, narration_audio_clip.duration)
|
471 |
+
final_composite_clip = final_composite_clip.set_audio(narration_audio_clip); logger.info("Overall narration added.")
|
|
|
|
|
|
|
|
|
472 |
except Exception as e: logger.error(f"Adding narration error: {e}", exc_info=True)
|
473 |
+
elif final_composite_clip.duration <= 0 : logger.warning("Video has no duration. Audio not added.")
|
474 |
|
475 |
if final_composite_clip and final_composite_clip.duration > 0:
|
476 |
output_path = os.path.join(self.output_dir, output_filename)
|
477 |
logger.info(f"Writing final animatic: {output_path} (Duration: {final_composite_clip.duration:.2f}s)")
|
478 |
+
final_composite_clip.write_videofile(output_path, fps=fps, codec='libx264', preset='medium', audio_codec='aac',
|
479 |
+
temp_audiofile=os.path.join(self.output_dir, f'temp-audio-{os.urandom(4).hex()}.m4a'),
|
480 |
+
remove_temp=True, threads=os.cpu_count() or 2, logger='bar', bitrate="5000k")
|
|
|
|
|
481 |
logger.info(f"Animatic created: {output_path}"); return output_path
|
482 |
+
else: logger.error("Final animatic clip invalid. Not writing file."); return None
|
483 |
except Exception as e: logger.error(f"Animatic writing error: {e}", exc_info=True); return None
|
484 |
finally:
|
485 |
+
for clip_obj in processed_moviepy_clips:
|
486 |
+
if hasattr(clip_obj, 'close'): clip_obj.close()
|
487 |
if narration_audio_clip and hasattr(narration_audio_clip, 'close'): narration_audio_clip.close()
|
488 |
if final_composite_clip and hasattr(final_composite_clip, 'close'): final_composite_clip.close()
|