Update core/visual_engine.py
Browse files- core/visual_engine.py +371 -672
core/visual_engine.py
CHANGED
@@ -1,39 +1,40 @@
|
|
1 |
# core/visual_engine.py
|
2 |
from PIL import Image, ImageDraw, ImageFont, ImageOps
|
3 |
-
|
4 |
-
|
5 |
-
if hasattr(Image, 'Resampling') and hasattr(Image.Resampling, 'LANCZOS'): # Pillow 9+
|
6 |
-
if not hasattr(Image, 'ANTIALIAS'):
|
7 |
-
Image.ANTIALIAS = Image.Resampling.LANCZOS
|
8 |
-
elif hasattr(Image, 'LANCZOS'): # Pillow 8
|
9 |
-
if not hasattr(Image, 'ANTIALIAS'):
|
10 |
-
Image.ANTIALIAS = Image.LANCZOS
|
11 |
-
elif not hasattr(Image, 'ANTIALIAS'):
|
12 |
-
print("WARNING: Pillow version lacks common Resampling attributes or ANTIALIAS. Video effects might fail.")
|
13 |
-
except Exception as e_mp:
|
14 |
-
print(f"WARNING: ANTIALIAS monkey-patch error: {e_mp}")
|
15 |
-
# --- END MONKEY PATCH ---
|
16 |
-
|
17 |
-
from moviepy.editor import (ImageClip, VideoFileClip, concatenate_videoclips, TextClip,
|
18 |
-
CompositeVideoClip, AudioFileClip)
|
19 |
-
import moviepy.video.fx.all as vfx
|
20 |
import numpy as np
|
21 |
import os
|
22 |
-
import openai
|
23 |
import requests
|
24 |
import io
|
25 |
import time
|
26 |
import random
|
27 |
import logging
|
28 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
29 |
logger = logging.getLogger(__name__)
|
30 |
-
logger.setLevel(logging.
|
31 |
|
32 |
-
# ---
|
33 |
ELEVENLABS_CLIENT_IMPORTED = False
|
34 |
-
ElevenLabsAPIClient = None
|
35 |
-
Voice = None
|
36 |
-
VoiceSettings = None
|
37 |
try:
|
38 |
from elevenlabs.client import ElevenLabs as ImportedElevenLabsClient
|
39 |
from elevenlabs import Voice as ImportedVoice, VoiceSettings as ImportedVoiceSettings
|
@@ -41,694 +42,392 @@ try:
|
|
41 |
Voice = ImportedVoice
|
42 |
VoiceSettings = ImportedVoiceSettings
|
43 |
ELEVENLABS_CLIENT_IMPORTED = True
|
44 |
-
logger.info("ElevenLabs client components imported.")
|
45 |
-
except
|
46 |
-
logger.warning(
|
|
|
|
|
47 |
|
48 |
-
# --- RunwayML Client Import (Placeholder) ---
|
49 |
RUNWAYML_SDK_IMPORTED = False
|
50 |
-
|
51 |
try:
|
52 |
-
|
|
|
|
|
|
|
53 |
except ImportError:
|
54 |
-
logger.warning("RunwayML SDK (
|
55 |
-
except Exception as
|
56 |
-
logger.warning(f"
|
57 |
|
58 |
|
59 |
class VisualEngine:
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
60 |
def __init__(self, output_dir="temp_cinegen_media", default_elevenlabs_voice_id="Rachel"):
|
61 |
self.output_dir = output_dir
|
62 |
os.makedirs(self.output_dir, exist_ok=True)
|
63 |
-
self.
|
64 |
-
font_paths_to_try = [
|
65 |
-
|
66 |
-
|
67 |
-
|
68 |
-
|
69 |
-
f"
|
70 |
-
f"
|
71 |
-
|
72 |
-
self.
|
73 |
-
self.font_size_pil = 20
|
74 |
-
self.video_overlay_font_size = 30
|
75 |
-
self.video_overlay_font_color = 'white'
|
76 |
-
self.video_overlay_font = 'DejaVu-Sans-Bold'
|
77 |
-
|
78 |
-
try:
|
79 |
-
if self.font_path_pil:
|
80 |
-
self.font = ImageFont.truetype(self.font_path_pil, self.font_size_pil)
|
81 |
-
logger.info(f"Pillow font loaded: {self.font_path_pil}.")
|
82 |
-
else:
|
83 |
-
self.font = ImageFont.load_default()
|
84 |
-
logger.warning("Using default Pillow font.")
|
85 |
-
self.font_size_pil = 10
|
86 |
-
except IOError as e_font:
|
87 |
-
logger.error(f"Pillow font loading IOError: {e_font}. Using default.")
|
88 |
-
self.font = ImageFont.load_default()
|
89 |
-
self.font_size_pil = 10
|
90 |
-
|
91 |
-
self.openai_api_key = None
|
92 |
-
self.USE_AI_IMAGE_GENERATION = False
|
93 |
-
self.dalle_model = "dall-e-3"
|
94 |
-
self.image_size_dalle3 = "1792x1024"
|
95 |
self.video_frame_size = (1280, 720)
|
96 |
-
self.elevenlabs_api_key = None
|
97 |
-
self.USE_ELEVENLABS = False
|
98 |
-
self.elevenlabs_client = None
|
99 |
self.elevenlabs_voice_id = default_elevenlabs_voice_id
|
100 |
-
if VoiceSettings and ELEVENLABS_CLIENT_IMPORTED:
|
101 |
-
|
102 |
-
|
103 |
-
|
104 |
-
|
105 |
-
|
106 |
-
)
|
107 |
-
else:
|
108 |
-
self.elevenlabs_voice_settings = None
|
109 |
-
self.pexels_api_key = None
|
110 |
-
self.USE_PEXELS = False
|
111 |
-
self.runway_api_key = None
|
112 |
-
self.USE_RUNWAYML = False
|
113 |
-
self.runway_client = None
|
114 |
logger.info("VisualEngine initialized.")
|
115 |
|
116 |
-
def set_openai_api_key(self,
|
117 |
-
|
118 |
-
self.
|
119 |
-
|
120 |
-
|
121 |
-
|
122 |
-
|
123 |
-
|
124 |
-
|
125 |
-
|
126 |
-
|
127 |
-
|
128 |
-
|
129 |
-
|
130 |
-
|
131 |
-
|
132 |
-
|
133 |
-
|
134 |
-
|
135 |
-
|
|
|
|
|
|
|
136 |
|
137 |
-
def
|
138 |
-
|
139 |
-
|
140 |
-
|
|
|
|
|
|
|
|
|
|
|
141 |
|
142 |
-
def
|
143 |
-
|
144 |
-
|
145 |
-
|
146 |
-
|
147 |
-
logger.info(f"RunwayML Client (Placeholder SDK) {'Ready.' if self.USE_RUNWAYML else 'Failed Init.'}")
|
148 |
-
except Exception as e:
|
149 |
-
logger.error(f"RunwayML client (Placeholder SDK) init error: {e}. Disabled.", exc_info=True)
|
150 |
-
self.USE_RUNWAYML = False
|
151 |
-
elif k:
|
152 |
-
self.USE_RUNWAYML = True
|
153 |
-
logger.info("RunwayML API Key set (direct API or placeholder).")
|
154 |
-
else:
|
155 |
-
self.USE_RUNWAYML = False
|
156 |
-
logger.info("RunwayML Disabled (no API key).")
|
157 |
|
158 |
-
def _get_text_dimensions(self, text_content,
|
159 |
-
|
160 |
-
|
161 |
-
|
162 |
try:
|
163 |
-
if hasattr(
|
164 |
-
|
165 |
-
|
166 |
-
|
167 |
-
return width, height if height > 0 else default_line_height
|
168 |
-
elif hasattr(font_obj, 'getsize'):
|
169 |
-
width, height = font_obj.getsize(text_content)
|
170 |
-
return width, height if height > 0 else default_line_height
|
171 |
-
else:
|
172 |
-
return int(len(text_content) * default_line_height * 0.6), int(default_line_height * 1.2)
|
173 |
-
except Exception as e:
|
174 |
-
logger.warning(f"Error in _get_text_dimensions for '{text_content[:20]}...': {e}")
|
175 |
-
return int(len(text_content) * self.font_size_pil * 0.6), int(self.font_size_pil * 1.2)
|
176 |
|
177 |
-
def _create_placeholder_image_content(self,
|
178 |
-
|
179 |
-
|
180 |
-
img = Image.new('RGB', size, color=(20, 20, 40))
|
181 |
-
|
182 |
-
|
183 |
-
|
184 |
-
|
185 |
-
|
186 |
-
|
187 |
-
|
188 |
-
|
189 |
-
|
190 |
-
test_line = current_line + word + " "
|
191 |
-
line_width_test, _ = self._get_text_dimensions(test_line.strip(), self.font)
|
192 |
-
if line_width_test <= max_text_width:
|
193 |
-
current_line = test_line
|
194 |
-
else:
|
195 |
-
if current_line.strip():
|
196 |
-
lines.append(current_line.strip())
|
197 |
-
word_width, _ = self._get_text_dimensions(word, self.font)
|
198 |
-
if word_width > max_text_width:
|
199 |
-
avg_char_w = self._get_text_dimensions("A", self.font)[0] or 10
|
200 |
-
chars_that_fit = int(max_text_width / avg_char_w) if avg_char_w > 0 else 10
|
201 |
-
if len(word) > chars_that_fit:
|
202 |
-
lines.append(word[:chars_that_fit-3] + "...")
|
203 |
-
else:
|
204 |
-
lines.append(word)
|
205 |
-
current_line = ""
|
206 |
-
else:
|
207 |
-
current_line = word + " "
|
208 |
-
if current_line.strip():
|
209 |
-
lines.append(current_line.strip())
|
210 |
-
if not lines and text_description:
|
211 |
-
avg_char_w = self._get_text_dimensions("A", self.font)[0] or 10
|
212 |
-
chars_that_fit = int(max_text_width / avg_char_w) if avg_char_w > 0 else 10
|
213 |
-
if len(text_description) > chars_that_fit:
|
214 |
-
lines.append(text_description[:chars_that_fit-3] + "...")
|
215 |
else:
|
216 |
-
|
217 |
-
|
218 |
-
|
219 |
-
|
220 |
-
|
221 |
-
|
222 |
-
|
223 |
-
|
224 |
-
|
225 |
-
|
226 |
-
|
227 |
-
|
228 |
-
|
229 |
-
|
230 |
-
|
231 |
-
|
232 |
-
|
233 |
-
|
234 |
-
if
|
235 |
-
|
236 |
-
|
237 |
-
|
238 |
-
|
239 |
-
|
240 |
-
try:
|
241 |
-
img.save(filepath)
|
242 |
-
return filepath
|
243 |
-
except Exception as e:
|
244 |
-
logger.error(f"Error saving placeholder image {filepath}: {e}", exc_info=True)
|
245 |
-
return None
|
246 |
|
247 |
-
def _search_pexels_image(self,
|
248 |
-
|
249 |
-
|
250 |
-
|
251 |
-
|
252 |
-
|
253 |
-
|
254 |
-
|
255 |
try:
|
256 |
-
logger.info(f"Pexels
|
257 |
-
|
258 |
-
|
259 |
-
|
260 |
-
|
261 |
-
|
262 |
-
if
|
263 |
-
|
264 |
-
|
265 |
-
logger.
|
266 |
-
|
267 |
-
|
268 |
-
|
269 |
-
|
270 |
-
|
271 |
-
|
272 |
-
|
273 |
-
logger.info(f"Pexels image saved successfully: {filepath}")
|
274 |
-
return filepath
|
275 |
-
else:
|
276 |
-
logger.info(f"No photos found on Pexels for query: '{effective_query}'")
|
277 |
-
return None
|
278 |
-
except requests.exceptions.RequestException as e_req:
|
279 |
-
logger.error(f"Pexels request error for query '{query}': {e_req}", exc_info=True)
|
280 |
-
except json.JSONDecodeError as e_json:
|
281 |
-
logger.error(f"Pexels JSON decode error for query '{query}': {e_json}", exc_info=True)
|
282 |
-
except Exception as e:
|
283 |
-
logger.error(f"General Pexels error for query '{query}': {e}", exc_info=True)
|
284 |
-
return None
|
285 |
|
286 |
-
def _generate_video_clip_with_runwayml(self,
|
287 |
-
|
288 |
-
|
289 |
-
|
290 |
-
|
291 |
-
|
292 |
-
|
293 |
-
|
294 |
-
|
295 |
-
|
296 |
-
logger.info(f"Runway Gen-4
|
297 |
-
logger.warning("Using PLACEHOLDER video for Runway Gen-4.")
|
298 |
-
img_clip = None
|
299 |
-
txt_c = None
|
300 |
-
final_ph_clip = None
|
301 |
try:
|
302 |
-
|
303 |
-
|
304 |
-
|
305 |
-
|
306 |
-
|
307 |
-
|
308 |
-
|
309 |
-
|
310 |
-
|
311 |
-
|
312 |
-
|
313 |
-
|
314 |
-
|
315 |
-
|
316 |
-
|
317 |
-
|
318 |
-
|
319 |
-
|
320 |
-
|
321 |
-
|
322 |
-
|
323 |
-
|
324 |
-
txt_c.close()
|
325 |
-
if final_ph_clip and hasattr(final_ph_clip, 'close'):
|
326 |
-
final_ph_clip.close()
|
327 |
|
328 |
-
def _create_placeholder_video_content(self,
|
329 |
-
|
330 |
-
|
331 |
-
|
332 |
-
|
333 |
-
try:
|
334 |
-
|
335 |
-
|
336 |
-
|
337 |
-
|
338 |
-
|
339 |
-
|
340 |
-
|
341 |
-
method='caption'
|
342 |
-
).set_duration(duration)
|
343 |
-
txt_clip.write_videofile(
|
344 |
-
filepath,
|
345 |
-
fps=24,
|
346 |
-
codec='libx264',
|
347 |
-
preset='ultrafast',
|
348 |
-
logger=None,
|
349 |
-
threads=2
|
350 |
-
)
|
351 |
-
logger.info(f"Generic placeholder video created successfully: {filepath}")
|
352 |
-
return filepath
|
353 |
-
except Exception as e:
|
354 |
-
logger.error(f"Failed to create generic placeholder video {filepath}: {e}", exc_info=True)
|
355 |
return None
|
356 |
-
finally:
|
357 |
-
if
|
358 |
-
|
359 |
-
|
360 |
-
except Exception as e_close:
|
361 |
-
logger.warning(f"Error closing TextClip in _create_placeholder_video_content: {e_close}")
|
362 |
-
|
363 |
def generate_scene_asset(self, image_generation_prompt_text, motion_prompt_text_for_video,
|
364 |
-
|
365 |
-
|
366 |
-
|
367 |
-
|
368 |
-
|
369 |
-
|
370 |
-
|
371 |
-
|
372 |
-
'error_message': 'Generation not attempted'
|
373 |
-
}
|
374 |
-
input_image_for_runway_path = None
|
375 |
-
image_filename_for_base = base_name + "_base_image.png"
|
376 |
-
temp_image_asset_info = {
|
377 |
-
'error': True,
|
378 |
-
'prompt_used': image_generation_prompt_text,
|
379 |
-
'error_message': 'Base image generation not attempted'
|
380 |
-
}
|
381 |
-
|
382 |
if self.USE_AI_IMAGE_GENERATION and self.openai_api_key:
|
383 |
-
|
384 |
-
for
|
385 |
-
|
386 |
-
|
387 |
-
logger.info(f"
|
388 |
-
|
389 |
-
|
390 |
-
|
391 |
-
|
392 |
-
|
393 |
-
|
394 |
-
|
395 |
-
|
396 |
-
|
397 |
-
|
398 |
-
|
399 |
-
|
400 |
-
|
401 |
-
|
402 |
-
|
403 |
-
|
404 |
-
|
405 |
-
|
406 |
-
|
407 |
-
|
408 |
-
|
409 |
-
|
410 |
-
|
411 |
-
|
412 |
-
|
413 |
-
'error': False,
|
414 |
-
'prompt_used': image_generation_prompt_text,
|
415 |
-
'revised_prompt': rp
|
416 |
-
}
|
417 |
-
break
|
418 |
-
except openai.RateLimitError as e:
|
419 |
-
logger.warning(f"OpenAI Rate Limit {att_n+1}: {e}. Retry...")
|
420 |
-
time.sleep(5 * (att_n + 1))
|
421 |
-
temp_image_asset_info['error_message'] = str(e)
|
422 |
-
except Exception as e:
|
423 |
-
logger.error(f"DALL-E error: {e}", exc_info=True)
|
424 |
-
temp_image_asset_info['error_message'] = str(e)
|
425 |
-
break
|
426 |
-
if temp_image_asset_info['error']:
|
427 |
-
logger.warning(f"DALL-E failed after {att_n+1} attempts for base image.")
|
428 |
|
429 |
-
|
430 |
-
|
431 |
-
|
432 |
-
|
433 |
-
if pp:
|
434 |
-
input_image_for_runway_path = pp
|
435 |
-
temp_image_asset_info = {
|
436 |
-
'path': pp,
|
437 |
-
'type': 'image',
|
438 |
-
'error': False,
|
439 |
-
'prompt_used': f"Pexels: {pqt}"
|
440 |
-
}
|
441 |
-
else:
|
442 |
-
current_em = temp_image_asset_info.get('error_message', "")
|
443 |
-
temp_image_asset_info['error_message'] = (current_em + " Pexels failed.").strip()
|
444 |
-
|
445 |
-
if temp_image_asset_info['error']:
|
446 |
-
logger.warning("Base image (DALL-E/Pexels) failed. Placeholder base image.")
|
447 |
-
ppt = temp_image_asset_info.get('prompt_used', image_generation_prompt_text)
|
448 |
-
php = self._create_placeholder_image_content(f"[Base Img Placeholder] {ppt[:100]}...", image_filename_for_base)
|
449 |
-
if php:
|
450 |
-
input_image_for_runway_path = php
|
451 |
-
temp_image_asset_info = {
|
452 |
-
'path': php,
|
453 |
-
'type': 'image',
|
454 |
-
'error': False,
|
455 |
-
'prompt_used': ppt
|
456 |
-
}
|
457 |
-
else:
|
458 |
-
current_em = temp_image_asset_info.get('error_message', "")
|
459 |
-
temp_image_asset_info['error_message'] = (current_em + " Base placeholder failed.").strip()
|
460 |
-
|
461 |
-
if generate_as_video_clip:
|
462 |
-
if self.USE_RUNWAYML and input_image_for_runway_path:
|
463 |
-
video_path = self._generate_video_clip_with_runwayml(
|
464 |
-
motion_prompt_text_for_video,
|
465 |
-
input_image_for_runway_path,
|
466 |
-
base_name,
|
467 |
-
runway_target_duration
|
468 |
-
)
|
469 |
-
if video_path and os.path.exists(video_path):
|
470 |
-
return {
|
471 |
-
'path': video_path,
|
472 |
-
'type': 'video',
|
473 |
-
'error': False,
|
474 |
-
'prompt_used': motion_prompt_text_for_video,
|
475 |
-
'base_image_path': input_image_for_runway_path
|
476 |
-
}
|
477 |
-
else:
|
478 |
-
asset_info = temp_image_asset_info
|
479 |
-
asset_info['error'] = True
|
480 |
-
asset_info['error_message'] = "RunwayML video gen failed; using base image."
|
481 |
-
asset_info['type'] = 'image'
|
482 |
-
return asset_info
|
483 |
-
elif not self.USE_RUNWAYML:
|
484 |
-
asset_info = temp_image_asset_info
|
485 |
-
asset_info['error_message'] = "RunwayML disabled; using base image."
|
486 |
-
asset_info['type'] = 'image'
|
487 |
-
return asset_info
|
488 |
-
else:
|
489 |
-
asset_info = temp_image_asset_info
|
490 |
-
asset_info['error_message'] = (asset_info.get('error_message', "") + " Base image failed, Runway video not attempted.").strip()
|
491 |
-
asset_info['type'] = 'image'
|
492 |
-
return asset_info
|
493 |
-
else:
|
494 |
-
return temp_image_asset_info
|
495 |
-
|
496 |
-
def generate_narration_audio(self, ttn, ofn="narration_overall.mp3"):
|
497 |
-
if not self.USE_ELEVENLABS or not self.elevenlabs_client or not ttn:
|
498 |
-
logger.info("11L skip.")
|
499 |
return None
|
500 |
-
|
501 |
try:
|
502 |
-
logger.info(f"
|
503 |
-
|
504 |
-
if hasattr(self.
|
505 |
-
|
506 |
-
|
507 |
-
|
508 |
-
|
509 |
-
logger.info("Using
|
510 |
-
|
511 |
-
|
512 |
-
|
513 |
-
|
514 |
-
|
515 |
-
|
516 |
-
f.write(ab)
|
517 |
-
logger.info(f"11L audio (non-stream): {afp}")
|
518 |
-
return afp
|
519 |
-
else:
|
520 |
-
logger.error("No 11L audio method.")
|
521 |
-
return None
|
522 |
|
523 |
-
if
|
524 |
-
|
525 |
-
if self.
|
526 |
-
if hasattr(self.
|
527 |
-
|
528 |
-
|
529 |
-
|
530 |
-
|
531 |
-
|
532 |
-
|
533 |
-
|
534 |
-
|
535 |
-
|
536 |
-
f.write(c)
|
537 |
-
logger.info(f"11L audio (stream): {afp}")
|
538 |
-
return afp
|
539 |
-
except Exception as e:
|
540 |
-
logger.error(f"11L audio error: {e}", exc_info=True)
|
541 |
-
return None
|
542 |
|
543 |
-
def assemble_animatic_from_assets(self, asset_data_list, overall_narration_path=None, output_filename="final_video.mp4", fps=24):
|
544 |
-
if not asset_data_list:
|
545 |
-
logger.warning("No assets for animatic.")
|
546 |
-
return None
|
547 |
-
processed_clips = []
|
548 |
-
narration_clip = None
|
549 |
-
final_clip = None
|
550 |
-
logger.info(f"Assembling from {len(asset_data_list)} assets. Frame: {self.video_frame_size}.")
|
551 |
-
|
552 |
-
for i, asset_info in enumerate(asset_data_list):
|
553 |
-
asset_path = asset_info.get('path')
|
554 |
-
asset_type = asset_info.get('type')
|
555 |
-
scene_dur = asset_info.get('duration', 4.5)
|
556 |
-
scene_num = asset_info.get('scene_num', i + 1)
|
557 |
-
key_action = asset_info.get('key_action', '')
|
558 |
-
logger.info(f"S{scene_num}: Path='{asset_path}', Type='{asset_type}', Dur='{scene_dur}'s")
|
559 |
-
|
560 |
-
if not (asset_path and os.path.exists(asset_path)):
|
561 |
-
logger.warning(f"S{scene_num}: Not found '{asset_path}'. Skip.")
|
562 |
-
continue
|
563 |
-
if scene_dur <= 0:
|
564 |
-
logger.warning(f"S{scene_num}: Invalid duration ({scene_dur}s). Skip.")
|
565 |
-
continue
|
566 |
|
567 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
568 |
try:
|
569 |
-
if
|
570 |
-
|
571 |
-
|
572 |
-
|
573 |
-
|
574 |
-
|
575 |
-
|
576 |
-
|
577 |
-
|
578 |
-
|
579 |
-
|
580 |
-
|
581 |
-
|
582 |
-
|
583 |
-
|
584 |
-
|
585 |
-
|
586 |
-
|
587 |
-
|
588 |
-
|
589 |
-
if frame_np.size == 0 or frame_np.ndim != 3 or frame_np.shape[2] != 3:
|
590 |
-
logger.error(f"S{scene_num}: Invalid NumPy. Skip.")
|
591 |
-
continue
|
592 |
-
clip_base = ImageClip(frame_np, transparent=False).set_duration(scene_dur)
|
593 |
-
mvpy_dbg_path = os.path.join(self.output_dir, f"debug_MOVIEPY_FRAME_S{scene_num}.png")
|
594 |
-
clip_base.save_frame(mvpy_dbg_path, t=0.1)
|
595 |
-
logger.info(f"DEBUG: Saved MOVIEPY_FRAME_S{scene_num} to {mvpy_dbg_path}")
|
596 |
-
clip_fx = clip_base
|
597 |
-
try:
|
598 |
-
es = random.uniform(1.03, 1.08)
|
599 |
-
clip_fx = clip_base.fx(
|
600 |
-
vfx.resize,
|
601 |
-
lambda t: 1 + (es - 1) * (t / scene_dur) if scene_dur > 0 else 1
|
602 |
-
).set_position('center')
|
603 |
-
except Exception as e:
|
604 |
-
logger.error(f"S{scene_num} Ken Burns error: {e}", exc_info=False)
|
605 |
-
current_scene_mvpy_clip = clip_fx
|
606 |
-
elif asset_type == 'video':
|
607 |
-
src_clip = None
|
608 |
try:
|
609 |
-
|
610 |
-
|
611 |
-
|
612 |
-
|
613 |
-
)
|
614 |
-
tmp_clip = src_clip
|
615 |
-
if src_clip.duration != scene_dur:
|
616 |
-
if src_clip.duration > scene_dur:
|
617 |
-
tmp_clip = src_clip.subclip(0, scene_dur)
|
618 |
else:
|
619 |
-
if
|
620 |
-
|
621 |
-
|
622 |
-
|
623 |
-
|
624 |
-
current_scene_mvpy_clip = tmp_clip.set_duration(scene_dur)
|
625 |
-
if current_scene_mvpy_clip.size != list(self.video_frame_size):
|
626 |
-
current_scene_mvpy_clip = current_scene_mvpy_clip.resize(self.video_frame_size)
|
627 |
-
except Exception as e:
|
628 |
-
logger.error(f"S{scene_num} Video load error '{asset_path}':{e}", exc_info=True)
|
629 |
-
continue
|
630 |
finally:
|
631 |
-
if
|
632 |
-
|
633 |
-
|
634 |
-
logger.warning(f"S{scene_num} Unknown asset type '{asset_type}'. Skip.")
|
635 |
-
continue
|
636 |
-
|
637 |
-
if current_scene_mvpy_clip and key_action:
|
638 |
try:
|
639 |
-
|
640 |
-
|
641 |
-
|
642 |
-
|
643 |
-
|
644 |
-
|
645 |
-
|
646 |
-
|
647 |
-
method='caption',
|
648 |
-
align='West',
|
649 |
-
size=(self.video_frame_size[0] * 0.9, None),
|
650 |
-
kerning=-1,
|
651 |
-
stroke_color='black',
|
652 |
-
stroke_width=1.5
|
653 |
-
).set_duration(to_dur).set_start(to_start).set_position(('center', 0.92), relative=True)
|
654 |
-
current_scene_mvpy_clip = CompositeVideoClip(
|
655 |
-
[current_scene_mvpy_clip, txt_c],
|
656 |
-
size=self.video_frame_size,
|
657 |
-
use_bgclip=True
|
658 |
-
)
|
659 |
-
except Exception as e:
|
660 |
-
logger.error(f"S{scene_num} TextClip error:{e}. No text.", exc_info=True)
|
661 |
-
|
662 |
-
if current_scene_mvpy_clip:
|
663 |
-
processed_clips.append(current_scene_mvpy_clip)
|
664 |
-
logger.info(f"S{scene_num} Processed. Dur:{current_scene_mvpy_clip.duration:.2f}s.")
|
665 |
-
except Exception as e:
|
666 |
-
logger.error(f"MAJOR Error S{scene_num} ({asset_path}):{e}", exc_info=True)
|
667 |
finally:
|
668 |
-
if
|
669 |
-
try:
|
670 |
-
|
671 |
-
|
672 |
-
|
673 |
-
|
674 |
-
if not processed_clips:
|
675 |
-
logger.warning("No clips processed. Abort.")
|
676 |
-
return None
|
677 |
-
td = 0.75
|
678 |
try:
|
679 |
-
logger.info(f"Concatenating {len(
|
680 |
-
if len(
|
681 |
-
|
682 |
-
|
683 |
-
|
684 |
-
if
|
685 |
-
|
686 |
-
|
687 |
-
|
688 |
-
|
689 |
-
|
690 |
-
|
691 |
-
|
692 |
-
|
693 |
-
|
694 |
-
|
695 |
-
|
696 |
-
|
697 |
-
logger.info("Narration added.")
|
698 |
-
except Exception as e:
|
699 |
-
logger.error(f"Narration add error:{e}", exc_info=True)
|
700 |
-
elif final_clip.duration <= 0:
|
701 |
-
logger.warning("Video no duration. No audio.")
|
702 |
-
if final_clip and final_clip.duration > 0:
|
703 |
-
op = os.path.join(self.output_dir, output_filename)
|
704 |
-
logger.info(f"Writing video:{op} (Dur:{final_clip.duration:.2f}s)")
|
705 |
-
final_clip.write_videofile(
|
706 |
-
op,
|
707 |
-
fps=fps,
|
708 |
-
codec='libx264',
|
709 |
-
preset='medium',
|
710 |
-
audio_codec='aac',
|
711 |
-
temp_audiofile=os.path.join(self.output_dir, f'temp-audio-{os.urandom(4).hex()}.m4a'),
|
712 |
-
remove_temp=True,
|
713 |
-
threads=os.cpu_count() or 2,
|
714 |
-
logger='bar',
|
715 |
-
bitrate="5000k",
|
716 |
-
ffmpeg_params=["-pix_fmt", "yuv420p"]
|
717 |
-
)
|
718 |
-
logger.info(f"Video created:{op}")
|
719 |
-
return op
|
720 |
-
else:
|
721 |
-
logger.error("Final clip invalid. No write.")
|
722 |
-
return None
|
723 |
-
except Exception as e:
|
724 |
-
logger.error(f"Video write error:{e}", exc_info=True)
|
725 |
-
return None
|
726 |
finally:
|
727 |
-
logger.debug("Closing all MoviePy clips in `assemble_animatic_from_assets` finally block.")
|
728 |
-
|
729 |
-
for
|
730 |
-
if
|
731 |
-
try:
|
732 |
-
|
733 |
-
except Exception as e_close:
|
734 |
-
logger.warning(f"Ignoring error while closing a clip: {e_close}")
|
|
|
1 |
# core/visual_engine.py
|
2 |
from PIL import Image, ImageDraw, ImageFont, ImageOps
|
3 |
+
import base64
|
4 |
+
import mimetypes
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
5 |
import numpy as np
|
6 |
import os
|
7 |
+
import openai # Ensure this is OpenAI v1.x.x+
|
8 |
import requests
|
9 |
import io
|
10 |
import time
|
11 |
import random
|
12 |
import logging
|
13 |
|
14 |
+
# --- MoviePy Imports ---
|
15 |
+
from moviepy.editor import (ImageClip, VideoFileClip, concatenate_videoclips, TextClip,
|
16 |
+
CompositeVideoClip, AudioFileClip)
|
17 |
+
import moviepy.video.fx.all as vfx
|
18 |
+
|
19 |
+
# --- MONKEY PATCH for Pillow/MoviePy compatibility ---
|
20 |
+
try:
|
21 |
+
if hasattr(Image, 'Resampling') and hasattr(Image.Resampling, 'LANCZOS'): # Pillow 9+
|
22 |
+
if not hasattr(Image, 'ANTIALIAS'): Image.ANTIALIAS = Image.Resampling.LANCZOS
|
23 |
+
elif hasattr(Image, 'LANCZOS'): # Pillow 8
|
24 |
+
if not hasattr(Image, 'ANTIALIAS'): Image.ANTIALIAS = Image.LANCZOS
|
25 |
+
elif not hasattr(Image, 'ANTIALIAS'):
|
26 |
+
print("WARNING: Pillow version lacks common Resampling attributes or ANTIALIAS. MoviePy effects might fail or look different.")
|
27 |
+
except Exception as e_monkey_patch:
|
28 |
+
print(f"WARNING: An unexpected error occurred during Pillow ANTIALIAS monkey-patch: {e_monkey_patch}")
|
29 |
+
|
30 |
logger = logging.getLogger(__name__)
|
31 |
+
# logger.setLevel(logging.DEBUG) # Uncomment for verbose debugging
|
32 |
|
33 |
+
# --- External Service Client Imports ---
|
34 |
ELEVENLABS_CLIENT_IMPORTED = False
|
35 |
+
ElevenLabsAPIClient = None
|
36 |
+
Voice = None
|
37 |
+
VoiceSettings = None
|
38 |
try:
|
39 |
from elevenlabs.client import ElevenLabs as ImportedElevenLabsClient
|
40 |
from elevenlabs import Voice as ImportedVoice, VoiceSettings as ImportedVoiceSettings
|
|
|
42 |
Voice = ImportedVoice
|
43 |
VoiceSettings = ImportedVoiceSettings
|
44 |
ELEVENLABS_CLIENT_IMPORTED = True
|
45 |
+
logger.info("ElevenLabs client components (SDK v1.x.x pattern) imported successfully.")
|
46 |
+
except ImportError:
|
47 |
+
logger.warning("ElevenLabs SDK not found (expected 'pip install elevenlabs>=1.0.0'). Audio generation will be disabled.")
|
48 |
+
except Exception as e_eleven_import_general:
|
49 |
+
logger.warning(f"General error importing ElevenLabs client components: {e_eleven_import_general}. Audio generation disabled.")
|
50 |
|
|
|
51 |
RUNWAYML_SDK_IMPORTED = False
|
52 |
+
RunwayMLAPIClientClass = None
|
53 |
try:
|
54 |
+
from runwayml import RunwayML as ImportedRunwayMLAPIClientClass
|
55 |
+
RunwayMLAPIClientClass = ImportedRunwayMLAPIClientClass
|
56 |
+
RUNWAYML_SDK_IMPORTED = True
|
57 |
+
logger.info("RunwayML SDK (runwayml) imported successfully.")
|
58 |
except ImportError:
|
59 |
+
logger.warning("RunwayML SDK not found (pip install runwayml). RunwayML video generation will be disabled.")
|
60 |
+
except Exception as e_runway_sdk_import_general:
|
61 |
+
logger.warning(f"General error importing RunwayML SDK: {e_runway_sdk_import_general}. RunwayML features disabled.")
|
62 |
|
63 |
|
64 |
class VisualEngine:
|
65 |
+
DEFAULT_FONT_SIZE_PIL = 10
|
66 |
+
PREFERRED_FONT_SIZE_PIL = 20
|
67 |
+
VIDEO_OVERLAY_FONT_SIZE = 30
|
68 |
+
VIDEO_OVERLAY_FONT_COLOR = 'white'
|
69 |
+
DEFAULT_MOVIEPY_FONT = 'DejaVu-Sans-Bold'
|
70 |
+
PREFERRED_MOVIEPY_FONT = 'Liberation-Sans-Bold'
|
71 |
+
|
72 |
def __init__(self, output_dir="temp_cinegen_media", default_elevenlabs_voice_id="Rachel"):
|
73 |
self.output_dir = output_dir
|
74 |
os.makedirs(self.output_dir, exist_ok=True)
|
75 |
+
self.font_filename_pil_preference = "DejaVuSans-Bold.ttf"
|
76 |
+
font_paths_to_try = [ self.font_filename_pil_preference, f"/usr/share/fonts/truetype/dejavu/{self.font_filename_pil_preference}", f"/usr/share/fonts/truetype/liberation/LiberationSans-Bold.ttf", f"/System/Library/Fonts/Supplemental/Arial.ttf", f"C:/Windows/Fonts/arial.ttf", f"/usr/local/share/fonts/truetype/mycustomfonts/arial.ttf"]
|
77 |
+
self.resolved_font_path_pil = next((p for p in font_paths_to_try if os.path.exists(p)), None)
|
78 |
+
self.active_font_pil = ImageFont.load_default(); self.active_font_size_pil = self.DEFAULT_FONT_SIZE_PIL
|
79 |
+
self.active_moviepy_font_name = self.DEFAULT_MOVIEPY_FONT
|
80 |
+
if self.resolved_font_path_pil:
|
81 |
+
try: self.active_font_pil = ImageFont.truetype(self.resolved_font_path_pil, self.PREFERRED_FONT_SIZE_PIL); self.active_font_size_pil = self.PREFERRED_FONT_SIZE_PIL; logger.info(f"Pillow font: {self.resolved_font_path_pil} sz {self.active_font_size_pil}."); self.active_moviepy_font_name = 'DejaVu-Sans-Bold' if "dejavu" in self.resolved_font_path_pil.lower() else ('Liberation-Sans-Bold' if "liberation" in self.resolved_font_path_pil.lower() else self.DEFAULT_MOVIEPY_FONT)
|
82 |
+
except IOError as e_font_load_io: logger.error(f"Pillow font IOError '{self.resolved_font_path_pil}': {e_font_load_io}. Default.")
|
83 |
+
else: logger.warning("Preferred Pillow font not found. Default.")
|
84 |
+
self.openai_api_key = None; self.USE_AI_IMAGE_GENERATION = False; self.dalle_model = "dall-e-3"; self.image_size_dalle3 = "1792x1024"
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
85 |
self.video_frame_size = (1280, 720)
|
86 |
+
self.elevenlabs_api_key = None; self.USE_ELEVENLABS = False; self.elevenlabs_client_instance = None
|
|
|
|
|
87 |
self.elevenlabs_voice_id = default_elevenlabs_voice_id
|
88 |
+
if VoiceSettings and ELEVENLABS_CLIENT_IMPORTED: self.elevenlabs_voice_settings_obj = VoiceSettings(stability=0.60, similarity_boost=0.80, style=0.15, use_speaker_boost=True)
|
89 |
+
else: self.elevenlabs_voice_settings_obj = None
|
90 |
+
self.pexels_api_key = None; self.USE_PEXELS = False
|
91 |
+
self.runway_api_key = None; self.USE_RUNWAYML = False; self.runway_ml_sdk_client_instance = None
|
92 |
+
if RUNWAYML_SDK_IMPORTED and RunwayMLAPIClientClass and os.getenv("RUNWAYML_API_SECRET"):
|
93 |
+
try: self.runway_ml_sdk_client_instance = RunwayMLAPIClientClass(); self.USE_RUNWAYML = True; logger.info("RunwayML Client init from env var at startup.")
|
94 |
+
except Exception as e_runway_init_startup: logger.error(f"Initial RunwayML client init failed: {e_runway_init_startup}"); self.USE_RUNWAYML = False
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
95 |
logger.info("VisualEngine initialized.")
|
96 |
|
97 |
+
def set_openai_api_key(self, api_key_value): self.openai_api_key = api_key_value; self.USE_AI_IMAGE_GENERATION = bool(api_key_value); logger.info(f"DALL-E status: {'Ready' if self.USE_AI_IMAGE_GENERATION else 'Disabled'}")
|
98 |
+
def set_elevenlabs_api_key(self, api_key_value, voice_id_from_secret=None):
|
99 |
+
self.elevenlabs_api_key = api_key_value
|
100 |
+
if voice_id_from_secret: self.elevenlabs_voice_id = voice_id_from_secret
|
101 |
+
if api_key_value and ELEVENLABS_CLIENT_IMPORTED and ElevenLabsAPIClient:
|
102 |
+
try: self.elevenlabs_client_instance = ElevenLabsAPIClient(api_key=api_key_value); self.USE_ELEVENLABS = bool(self.elevenlabs_client_instance); logger.info(f"11L Client: {'Ready' if self.USE_ELEVENLABS else 'Failed'} (Voice: {self.elevenlabs_voice_id})")
|
103 |
+
except Exception as e_11l_setkey_init: logger.error(f"11L client init error: {e_11l_setkey_init}. Disabled.", exc_info=True); self.USE_ELEVENLABS=False; self.elevenlabs_client_instance=None
|
104 |
+
else: self.USE_ELEVENLABS = False; logger.info(f"11L Disabled (key/SDK).")
|
105 |
+
def set_pexels_api_key(self, api_key_value): self.pexels_api_key = api_key_value; self.USE_PEXELS = bool(api_key_value); logger.info(f"Pexels status: {'Ready' if self.USE_PEXELS else 'Disabled'}")
|
106 |
+
def set_runway_api_key(self, api_key_value):
|
107 |
+
self.runway_api_key = api_key_value
|
108 |
+
if api_key_value:
|
109 |
+
if RUNWAYML_SDK_IMPORTED and RunwayMLAPIClientClass:
|
110 |
+
if not self.runway_ml_sdk_client_instance:
|
111 |
+
try:
|
112 |
+
original_env_secret = os.getenv("RUNWAYML_API_SECRET")
|
113 |
+
if not original_env_secret: os.environ["RUNWAYML_API_SECRET"] = api_key_value; logger.info("Temp set RUNWAYML_API_SECRET for SDK.")
|
114 |
+
self.runway_ml_sdk_client_instance = RunwayMLAPIClientClass(); self.USE_RUNWAYML = True; logger.info("RunwayML Client init via set_runway_api_key.")
|
115 |
+
if not original_env_secret: del os.environ["RUNWAYML_API_SECRET"]; logger.info("Cleared temp RUNWAYML_API_SECRET.")
|
116 |
+
except Exception as e_runway_setkey_init: logger.error(f"RunwayML Client init in set_runway_api_key fail: {e_runway_setkey_init}", exc_info=True); self.USE_RUNWAYML=False;self.runway_ml_sdk_client_instance=None
|
117 |
+
else: self.USE_RUNWAYML = True; logger.info("RunwayML Client already init.")
|
118 |
+
else: logger.warning("RunwayML SDK not imported. Service disabled."); self.USE_RUNWAYML = False
|
119 |
+
else: self.USE_RUNWAYML = False; self.runway_ml_sdk_client_instance = None; logger.info("RunwayML Disabled (no API key).")
|
120 |
|
121 |
+
def _image_to_data_uri(self, image_path):
|
122 |
+
# (Implementation from before)
|
123 |
+
try: mime_type,_=mimetypes.guess_type(image_path)
|
124 |
+
if not mime_type:ext=os.path.splitext(image_path)[1].lower();mime_map={".png":"image/png",".jpg":"image/jpeg",".jpeg":"image/jpeg",".webp":"image/webp"};mime_type=mime_map.get(ext,"application/octet-stream");
|
125 |
+
if mime_type=="application/octet-stream":logger.warning(f"Unknown MIME for {image_path}, using {mime_type}.")
|
126 |
+
with open(image_path,"rb")as image_file:encoded_string=base64.b64encode(image_file.read()).decode('utf-8')
|
127 |
+
data_uri=f"data:{mime_type};base64,{encoded_string}";logger.debug(f"Data URI for {os.path.basename(image_path)} (start): {data_uri[:100]}...");return data_uri
|
128 |
+
except FileNotFoundError:logger.error(f"Img not found {image_path} for data URI.");return None
|
129 |
+
except Exception as e:logger.error(f"Error converting {image_path} to data URI:{e}",exc_info=True);return None
|
130 |
|
131 |
+
def _map_resolution_to_runway_ratio(self, width, height):
|
132 |
+
# (Implementation from before)
|
133 |
+
ratio_str=f"{width}:{height}";supported_ratios_gen4=["1280:720","720:1280","1104:832","832:1104","960:960","1584:672"];
|
134 |
+
if ratio_str in supported_ratios_gen4:return ratio_str
|
135 |
+
logger.warning(f"Res {ratio_str} not in Gen-4 list. Default 1280:720.");return "1280:720"
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
136 |
|
137 |
+
def _get_text_dimensions(self, text_content, font_object_pil):
|
138 |
+
# (Implementation from before)
|
139 |
+
dch=getattr(font_object_pil,'size',self.active_font_size_pil);
|
140 |
+
if not text_content:return 0,dch
|
141 |
try:
|
142 |
+
if hasattr(font_object_pil,'getbbox'):bb=font_object_pil.getbbox(text_content);w=bb[2]-bb[0];h=bb[3]-bb[1];return w,h if h>0 else dch
|
143 |
+
elif hasattr(font_object_pil,'getsize'):w,h=font_object_pil.getsize(text_content);return w,h if h>0 else dch
|
144 |
+
else:return int(len(text_content)*dch*0.6),int(dch*1.2)
|
145 |
+
except Exception as e_getdim_inner:logger.warning(f"Error in _get_text_dimensions:{e_getdim_inner}");return int(len(text_content)*self.active_font_size_pil*0.6),int(self.active_font_size_pil*1.2) # Renamed e
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
146 |
|
147 |
+
def _create_placeholder_image_content(self,text_description,filename,size=None):
|
148 |
+
# (Corrected version from previous response)
|
149 |
+
if size is None: size = self.video_frame_size
|
150 |
+
img = Image.new('RGB', size, color=(20, 20, 40)); d = ImageDraw.Draw(img); padding = 25
|
151 |
+
max_w = size[0] - (2 * padding); lines_for_placeholder = []
|
152 |
+
if not text_description: text_description = "(Placeholder Image)"
|
153 |
+
words_list = text_description.split(); current_line_buffer = ""
|
154 |
+
for word_idx, word_item in enumerate(words_list):
|
155 |
+
prospective_addition = word_item + (" " if word_idx < len(words_list) - 1 else "")
|
156 |
+
test_line_candidate = current_line_buffer + prospective_addition
|
157 |
+
current_w_text, _ = self._get_text_dimensions(test_line_candidate, self.active_font_pil)
|
158 |
+
if current_w_text == 0 and test_line_candidate.strip(): current_w_text = len(test_line_candidate) * (self.active_font_size_pil * 0.6)
|
159 |
+
if current_w_text <= max_w: current_line_buffer = test_line_candidate
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
160 |
else:
|
161 |
+
if current_line_buffer.strip(): lines_for_placeholder.append(current_line_buffer.strip())
|
162 |
+
current_line_buffer = prospective_addition
|
163 |
+
if current_line_buffer.strip(): lines_for_placeholder.append(current_line_buffer.strip())
|
164 |
+
if not lines_for_placeholder and text_description:
|
165 |
+
avg_char_w_est, _ = self._get_text_dimensions("W", self.active_font_pil); avg_char_w_est = avg_char_w_est or (self.active_font_size_pil * 0.6)
|
166 |
+
chars_per_line_est = int(max_w / avg_char_w_est) if avg_char_w_est > 0 else 20
|
167 |
+
lines_for_placeholder.append(text_description[:chars_per_line_est] + ("..." if len(text_description) > chars_per_line_est else ""))
|
168 |
+
elif not lines_for_placeholder: lines_for_placeholder.append("(Placeholder Error)")
|
169 |
+
_, single_h = self._get_text_dimensions("Ay", self.active_font_pil); single_h = single_h if single_h > 0 else self.active_font_size_pil + 2
|
170 |
+
max_l = min(len(lines_for_placeholder), (size[1] - (2 * padding)) // (single_h + 2)) if single_h > 0 else 1; max_l = max(1, max_l)
|
171 |
+
y_p = padding + (size[1] - (2 * padding) - max_l * (single_h + 2)) / 2.0
|
172 |
+
for i_line in range(max_l):
|
173 |
+
line_txt_content = lines_for_placeholder[i_line]; line_w_val, _ = self._get_text_dimensions(line_txt_content, self.active_font_pil)
|
174 |
+
if line_w_val == 0 and line_txt_content.strip(): line_w_val = len(line_txt_content) * (self.active_font_size_pil * 0.6)
|
175 |
+
x_p = (size[0] - line_w_val) / 2.0
|
176 |
+
try: d.text((x_p, y_p), line_txt_content, font=self.active_font_pil, fill=(200, 200, 180))
|
177 |
+
except Exception as e_draw: logger.error(f"Pillow d.text error: {e_draw} for '{line_txt_content}'")
|
178 |
+
y_p += single_h + 2
|
179 |
+
if i_line == 6 and max_l > 7:
|
180 |
+
try: d.text((x_p, y_p), "...", font=self.active_font_pil, fill=(200, 200, 180))
|
181 |
+
except Exception as e_elip: logger.error(f"Pillow d.text ellipsis error: {e_elip}"); break
|
182 |
+
filepath_placeholder = os.path.join(self.output_dir, filename)
|
183 |
+
try: img.save(filepath_placeholder); return filepath_placeholder
|
184 |
+
except Exception as e_save: logger.error(f"Saving placeholder image '{filepath_placeholder}' error: {e_save}", exc_info=True); return None
|
|
|
|
|
|
|
|
|
|
|
|
|
185 |
|
186 |
+
def _search_pexels_image(self, query_str, output_fn_base):
|
187 |
+
# (Corrected version from previous response)
|
188 |
+
if not self.USE_PEXELS or not self.pexels_api_key: return None
|
189 |
+
http_headers = {"Authorization": self.pexels_api_key}
|
190 |
+
http_params = {"query": query_str, "per_page": 1, "orientation": "landscape", "size": "large2x"}
|
191 |
+
base_name_px, _ = os.path.splitext(output_fn_base)
|
192 |
+
pexels_fn_str = base_name_px + f"_pexels_{random.randint(1000,9999)}.jpg"
|
193 |
+
file_path_px = os.path.join(self.output_dir, pexels_fn_str)
|
194 |
try:
|
195 |
+
logger.info(f"Pexels: Searching for '{query_str}'")
|
196 |
+
eff_query_px = " ".join(query_str.split()[:5])
|
197 |
+
http_params["query"] = eff_query_px
|
198 |
+
response_px = requests.get("https://api.pexels.com/v1/search", headers=http_headers, params=http_params, timeout=20)
|
199 |
+
response_px.raise_for_status()
|
200 |
+
data_px = response_px.json()
|
201 |
+
if data_px.get("photos") and len(data_px["photos"]) > 0:
|
202 |
+
photo_details_px = data_px["photos"][0]
|
203 |
+
photo_url_px = photo_details_px.get("src", {}).get("large2x")
|
204 |
+
if not photo_url_px: logger.warning(f"Pexels: 'large2x' URL missing for '{eff_query_px}'. Details: {photo_details_px}"); return None
|
205 |
+
image_response_px = requests.get(photo_url_px, timeout=60); image_response_px.raise_for_status()
|
206 |
+
img_pil_data_px = Image.open(io.BytesIO(image_response_px.content))
|
207 |
+
if img_pil_data_px.mode != 'RGB': img_pil_data_px = img_pil_data_px.convert('RGB')
|
208 |
+
img_pil_data_px.save(file_path_px); logger.info(f"Pexels: Image saved to {file_path_px}"); return file_path_px
|
209 |
+
else: logger.info(f"Pexels: No photos for '{eff_query_px}'."); return None
|
210 |
+
except requests.exceptions.RequestException as e_req_px: logger.error(f"Pexels: RequestException for '{query_str}': {e_req_px}", exc_info=False); return None
|
211 |
+
except Exception as e_px_gen: logger.error(f"Pexels: General error for '{query_str}': {e_px_gen}", exc_info=True); return None
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
212 |
|
213 |
+
def _generate_video_clip_with_runwayml(self, text_prompt_for_motion, input_image_path, scene_identifier_filename_base, target_duration_seconds=5):
|
214 |
+
# (Updated RunwayML integration from before)
|
215 |
+
if not self.USE_RUNWAYML or not self.runway_ml_sdk_client_instance: logger.warning("RunwayML not enabled/client not init. Skip video."); return None
|
216 |
+
if not input_image_path or not os.path.exists(input_image_path): logger.error(f"Runway Gen-4 needs input image. Path invalid: {input_image_path}"); return None
|
217 |
+
image_data_uri_str = self._image_to_data_uri(input_image_path)
|
218 |
+
if not image_data_uri_str: return None
|
219 |
+
runway_dur = 10 if target_duration_seconds >= 8 else 5
|
220 |
+
runway_ratio = self._map_resolution_to_runway_ratio(self.video_frame_size[0], self.video_frame_size[1])
|
221 |
+
base_name_for_runway_vid, _ = os.path.splitext(scene_identifier_filename_base); output_vid_fn = base_name_for_runway_vid + f"_runway_gen4_d{runway_dur}s.mp4"
|
222 |
+
output_vid_fp = os.path.join(self.output_dir, output_vid_fn)
|
223 |
+
logger.info(f"Runway Gen-4 task: motion='{text_prompt_for_motion[:100]}...', img='{os.path.basename(input_image_path)}', dur={runway_dur}s, ratio='{runway_ratio}'")
|
|
|
|
|
|
|
|
|
224 |
try:
|
225 |
+
task_submitted_runway = self.runway_ml_sdk_client_instance.image_to_video.create(model='gen4_turbo', prompt_image=image_data_uri_str, prompt_text=text_prompt_for_motion, duration=runway_dur, ratio=runway_ratio)
|
226 |
+
task_id_runway = task_submitted_runway.id; logger.info(f"Runway Gen-4 task ID: {task_id_runway}. Polling...")
|
227 |
+
poll_sec=10; max_poll_count=36; poll_start_time = time.time()
|
228 |
+
while time.time() - poll_start_time < max_poll_count * poll_sec:
|
229 |
+
time.sleep(poll_sec); task_details_runway = self.runway_ml_sdk_client_instance.tasks.retrieve(id=task_id_runway)
|
230 |
+
logger.info(f"Runway task {task_id_runway} status: {task_details_runway.status}")
|
231 |
+
if task_details_runway.status == 'SUCCEEDED':
|
232 |
+
output_url_runway = getattr(getattr(task_details_runway,'output',None),'url',None) or \
|
233 |
+
(getattr(task_details_runway,'artifacts',None) and task_details_runway.artifacts[0].url if task_details_runway.artifacts and hasattr(task_details_runway.artifacts[0],'url') else None) or \
|
234 |
+
(getattr(task_details_runway,'artifacts',None) and task_details_runway.artifacts[0].download_url if task_details_runway.artifacts and hasattr(task_details_runway.artifacts[0],'download_url') else None)
|
235 |
+
if not output_url_runway: logger.error(f"Runway task {task_id_runway} SUCCEEDED, but no output URL. Details: {vars(task_details_runway) if hasattr(task_details_runway,'__dict__') else task_details_runway}"); return None
|
236 |
+
logger.info(f"Runway task {task_id_runway} SUCCEEDED. Downloading: {output_url_runway}")
|
237 |
+
video_resp_get = requests.get(output_url_runway, stream=True, timeout=300); video_resp_get.raise_for_status()
|
238 |
+
with open(output_vid_fp,'wb') as f_vid:
|
239 |
+
for chunk_data in video_resp_get.iter_content(chunk_size=8192): f_vid.write(chunk_data)
|
240 |
+
logger.info(f"Runway Gen-4 video saved: {output_vid_fp}"); return output_vid_fp
|
241 |
+
elif task_details_runway.status in ['FAILED','ABORTED','ERROR']:
|
242 |
+
err_msg_runway = getattr(task_details_runway,'error_message',None) or getattr(getattr(task_details_runway,'output',None),'error',"Unknown Runway error.")
|
243 |
+
logger.error(f"Runway task {task_id_runway} status: {task_details_runway.status}. Error: {err_msg_runway}"); return None
|
244 |
+
logger.warning(f"Runway task {task_id_runway} timed out."); return None
|
245 |
+
except AttributeError as ae_sdk: logger.error(f"RunwayML SDK AttrError: {ae_sdk}. SDK/methods changed?", exc_info=True); return None
|
246 |
+
except Exception as e_runway_gen: logger.error(f"Runway Gen-4 API error: {e_runway_gen}", exc_info=True); return None
|
|
|
|
|
|
|
247 |
|
248 |
+
def _create_placeholder_video_content(self, text_desc_ph, filename_ph, duration_ph=4, size_ph=None):
|
249 |
+
# <<< THIS IS THE CORRECTED METHOD >>>
|
250 |
+
if size_ph is None: size_ph = self.video_frame_size
|
251 |
+
filepath_ph = os.path.join(self.output_dir, filename_ph)
|
252 |
+
text_clip_ph = None
|
253 |
+
try: # Ensure try block is here
|
254 |
+
text_clip_ph = TextClip(text_desc_ph, fontsize=50, color='white', font=self.video_overlay_font,
|
255 |
+
bg_color='black', size=size_ph, method='caption').set_duration(duration_ph)
|
256 |
+
text_clip_ph.write_videofile(filepath_ph, fps=24, codec='libx264', preset='ultrafast', logger=None, threads=2)
|
257 |
+
logger.info(f"Generic placeholder video created: {filepath_ph}")
|
258 |
+
return filepath_ph
|
259 |
+
except Exception as e_ph_vid:
|
260 |
+
logger.error(f"Failed to create generic placeholder video '{filepath_ph}': {e_ph_vid}", exc_info=True)
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
261 |
return None
|
262 |
+
finally: # Ensure finally block is here
|
263 |
+
if text_clip_ph and hasattr(text_clip_ph, 'close'):
|
264 |
+
text_clip_ph.close()
|
265 |
+
|
|
|
|
|
|
|
266 |
def generate_scene_asset(self, image_generation_prompt_text, motion_prompt_text_for_video,
|
267 |
+
scene_data_dict, scene_identifier_fn_base,
|
268 |
+
generate_as_video_clip_flag=False, runway_target_dur_val=5):
|
269 |
+
# (Corrected DALL-E loop from previous response)
|
270 |
+
base_name_asset, _ = os.path.splitext(scene_identifier_fn_base)
|
271 |
+
asset_info_result = {'path': None, 'type': 'none', 'error': True, 'prompt_used': image_generation_prompt_text, 'error_message': 'Asset generation init failed'}
|
272 |
+
path_for_input_image_runway = None
|
273 |
+
fn_for_base_image = base_name_asset + ("_base_for_video.png" if generate_as_video_clip_flag else ".png")
|
274 |
+
fp_for_base_image = os.path.join(self.output_dir, fn_for_base_image)
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
275 |
if self.USE_AI_IMAGE_GENERATION and self.openai_api_key:
|
276 |
+
max_r_dalle, attempt_count_dalle = 2,0;
|
277 |
+
for att_n_dalle in range(max_r_dalle):
|
278 |
+
attempt_count_dalle = att_n_dalle + 1
|
279 |
+
try:
|
280 |
+
logger.info(f"Att {attempt_count_dalle} DALL-E (base img): {image_generation_prompt_text[:70]}..."); oai_cl = openai.OpenAI(api_key=self.openai_api_key,timeout=90.0); oai_r = oai_cl.images.generate(model=self.dalle_model,prompt=image_generation_prompt_text,n=1,size=self.image_size_dalle3,quality="hd",response_format="url",style="vivid"); oai_iu = oai_r.data[0].url; oai_rp = getattr(oai_r.data[0],'revised_prompt',None);
|
281 |
+
if oai_rp: logger.info(f"DALL-E revised: {oai_rp[:70]}...")
|
282 |
+
oai_ir = requests.get(oai_iu,timeout=120); oai_ir.raise_for_status(); oai_id = Image.open(io.BytesIO(oai_ir.content));
|
283 |
+
if oai_id.mode!='RGB': oai_id=oai_id.convert('RGB')
|
284 |
+
oai_id.save(fp_for_base_image); logger.info(f"DALL-E base img saved: {fp_for_base_image}"); path_for_input_image_runway=fp_for_base_image; asset_info_result={'path':fp_for_base_image,'type':'image','error':False,'prompt_used':image_generation_prompt_text,'revised_prompt':oai_rp}; break
|
285 |
+
except openai.RateLimitError as e_oai_rl: logger.warning(f"OpenAI RateLimit Att {attempt_count_dalle}:{e_oai_rl}.Retry...");time.sleep(5*attempt_count_dalle);asset_info_result['error_message']=str(e_oai_rl)
|
286 |
+
except openai.APIError as e_oai_api: logger.error(f"OpenAI APIError Att {attempt_count_dalle}:{e_oai_api}");asset_info_result['error_message']=str(e_oai_api);break
|
287 |
+
except requests.exceptions.RequestException as e_oai_req: logger.error(f"Requests Err DALL-E Att {attempt_count_dalle}:{e_oai_req}");asset_info_result['error_message']=str(e_oai_req);break
|
288 |
+
except Exception as e_oai_gen: logger.error(f"General DALL-E Err Att {attempt_count_dalle}:{e_oai_gen}",exc_info=True);asset_info_result['error_message']=str(e_oai_gen);break
|
289 |
+
if asset_info_result['error']: logger.warning(f"DALL-E failed after {attempt_count_dalle} attempts for base img.")
|
290 |
+
if asset_info_result['error'] and self.USE_PEXELS:
|
291 |
+
logger.info("Trying Pexels for base img.");px_qt=scene_data_dict.get('pexels_search_query_감독',f"{scene_data_dict.get('emotional_beat','')} {scene_data_dict.get('setting_description','')}");px_pp=self._search_pexels_image(px_qt,fn_for_base_image);
|
292 |
+
if px_pp:path_for_input_image_runway=px_pp;asset_info_result={'path':px_pp,'type':'image','error':False,'prompt_used':f"Pexels:{px_qt}"}
|
293 |
+
else:current_em_px=asset_info_result.get('error_message',"");asset_info_result['error_message']=(current_em_px+" Pexels failed for base.").strip()
|
294 |
+
if asset_info_result['error']:
|
295 |
+
logger.warning("Base img (DALL-E/Pexels) failed. Using placeholder.");ph_ppt=asset_info_result.get('prompt_used',image_generation_prompt_text);php=self._create_placeholder_image_content(f"[Base Placeholder]{ph_ppt[:70]}...",fn_for_base_image);
|
296 |
+
if php:path_for_input_image_runway=php;asset_info_result={'path':php,'type':'image','error':False,'prompt_used':ph_ppt}
|
297 |
+
else:current_em_ph=asset_info_result.get('error_message',"");asset_info_result['error_message']=(current_em_ph+" Base placeholder failed.").strip()
|
298 |
+
if generate_as_video_clip_flag:
|
299 |
+
if not path_for_input_image_runway:logger.error("RunwayML video: base img failed.");asset_info_result['error']=True;asset_info_result['error_message']=(asset_info_result.get('error_message',"")+" Base img miss, Runway abort.").strip();asset_info_result['type']='none';return asset_info_result
|
300 |
+
if self.USE_RUNWAYML:
|
301 |
+
runway_video_p=self._generate_video_clip_with_runwayml(motion_prompt_text_for_video,path_for_input_image_runway,base_name_asset,runway_target_dur_val)
|
302 |
+
if runway_video_p and os.path.exists(runway_video_p):asset_info_result={'path':runway_video_p,'type':'video','error':False,'prompt_used':motion_prompt_text_for_video,'base_image_path':path_for_input_image_runway}
|
303 |
+
else:logger.warning(f"RunwayML video failed for {base_name_asset}. Fallback to base img.");asset_info_result['error']=True;asset_info_result['error_message']=(asset_info_result.get('error_message',"Base img ok.")+" RunwayML video fail; use base img.").strip();asset_info_result['path']=path_for_input_image_runway;asset_info_result['type']='image';asset_info_result['prompt_used']=image_generation_prompt_text
|
304 |
+
else:logger.warning("RunwayML selected but disabled. Use base img.");asset_info_result['error']=True;asset_info_result['error_message']=(asset_info_result.get('error_message',"Base img ok.")+" RunwayML disabled; use base img.").strip();asset_info_result['path']=path_for_input_image_runway;asset_info_result['type']='image';asset_info_result['prompt_used']=image_generation_prompt_text
|
305 |
+
return asset_info_result
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
306 |
|
307 |
+
def generate_narration_audio(self, text_to_narrate, output_filename="narration_overall.mp3"):
|
308 |
+
# <<< CORRECTED VERSION OF THIS METHOD >>>
|
309 |
+
if not self.USE_ELEVENLABS or not self.elevenlabs_client_instance or not text_to_narrate:
|
310 |
+
logger.info("ElevenLabs conditions not met (service disabled, client not init, or no text). Skipping audio generation.")
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
311 |
return None
|
312 |
+
audio_filepath_narration = os.path.join(self.output_dir, output_filename)
|
313 |
try:
|
314 |
+
logger.info(f"Generating ElevenLabs audio (Voice ID: {self.elevenlabs_voice_id}) for text: \"{text_to_narrate[:70]}...\"")
|
315 |
+
audio_stream_method_11l = None
|
316 |
+
if hasattr(self.elevenlabs_client_instance, 'text_to_speech') and hasattr(self.elevenlabs_client_instance.text_to_speech, 'stream'):
|
317 |
+
audio_stream_method_11l = self.elevenlabs_client_instance.text_to_speech.stream; logger.info("Using ElevenLabs SDK method: client.text_to_speech.stream()")
|
318 |
+
elif hasattr(self.elevenlabs_client_instance, 'generate_stream'):
|
319 |
+
audio_stream_method_11l = self.elevenlabs_client_instance.generate_stream; logger.info("Using ElevenLabs SDK method: client.generate_stream()")
|
320 |
+
elif hasattr(self.elevenlabs_client_instance, 'generate'):
|
321 |
+
logger.info("Using ElevenLabs SDK method: client.generate() (non-streaming).")
|
322 |
+
voice_param_11l = str(self.elevenlabs_voice_id)
|
323 |
+
if Voice and self.elevenlabs_voice_settings_obj: voice_param_11l = Voice(voice_id=str(self.elevenlabs_voice_id), settings=self.elevenlabs_voice_settings_obj)
|
324 |
+
audio_bytes_data = self.elevenlabs_client_instance.generate(text=text_to_narrate, voice=voice_param_11l, model="eleven_multilingual_v2")
|
325 |
+
with open(audio_filepath_narration, "wb") as audio_file_out: audio_file_out.write(audio_bytes_data)
|
326 |
+
logger.info(f"ElevenLabs audio (non-streamed) saved successfully to: {audio_filepath_narration}"); return audio_filepath_narration
|
327 |
+
else: logger.error("No recognized audio generation method found on the ElevenLabs client instance."); return None
|
|
|
|
|
|
|
|
|
|
|
|
|
328 |
|
329 |
+
if audio_stream_method_11l: # If a streaming method was identified
|
330 |
+
params_for_voice_stream = {"voice_id": str(self.elevenlabs_voice_id)}
|
331 |
+
if self.elevenlabs_voice_settings_obj:
|
332 |
+
if hasattr(self.elevenlabs_voice_settings_obj, 'model_dump'): params_for_voice_stream["voice_settings"] = self.elevenlabs_voice_settings_obj.model_dump()
|
333 |
+
elif hasattr(self.elevenlabs_voice_settings_obj, 'dict'): params_for_voice_stream["voice_settings"] = self.elevenlabs_voice_settings_obj.dict()
|
334 |
+
else: params_for_voice_stream["voice_settings"] = self.elevenlabs_voice_settings_obj
|
335 |
+
audio_data_iterator_11l = audio_stream_method_11l(text=text_to_narrate, model_id="eleven_multilingual_v2", **params_for_voice_stream)
|
336 |
+
with open(audio_filepath_narration, "wb") as audio_file_out_stream:
|
337 |
+
for audio_chunk_data in audio_data_iterator_11l:
|
338 |
+
if audio_chunk_data: audio_file_out_stream.write(audio_chunk_data)
|
339 |
+
logger.info(f"ElevenLabs audio (streamed) saved successfully to: {audio_filepath_narration}"); return audio_filepath_narration
|
340 |
+
except AttributeError as ae_11l_sdk: logger.error(f"AttributeError with ElevenLabs SDK client: {ae_11l_sdk}. SDK version/methods might differ.", exc_info=True); return None
|
341 |
+
except Exception as e_11l_general_audio: logger.error(f"General error during ElevenLabs audio generation: {e_11l_general_audio}", exc_info=True); return None
|
|
|
|
|
|
|
|
|
|
|
|
|
342 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
343 |
|
344 |
+
def assemble_animatic_from_assets(self, asset_data_list, overall_narration_path=None, output_filename="final_video.mp4", fps=24):
|
345 |
+
# (Keep as in the version with robust image processing, C-contiguous array, debug saves, and pix_fmt)
|
346 |
+
# ... (This extensive method is assumed to be largely correct from the previous iteration focusing on blank video issues)
|
347 |
+
if not asset_data_list: logger.warning("No assets for animatic."); return None
|
348 |
+
processed_moviepy_clips_list = []; narration_audio_clip_mvpy = None; final_video_output_clip = None
|
349 |
+
logger.info(f"Assembling from {len(asset_data_list)} assets. Target Frame: {self.video_frame_size}.")
|
350 |
+
for i_asset, asset_info_item_loop in enumerate(asset_data_list):
|
351 |
+
path_of_asset, type_of_asset, duration_for_scene = asset_info_item_loop.get('path'), asset_info_item_loop.get('type'), asset_info_item_loop.get('duration', 4.5)
|
352 |
+
num_of_scene, action_in_key = asset_info_item_loop.get('scene_num', i_asset + 1), asset_info_item_loop.get('key_action', '')
|
353 |
+
logger.info(f"S{num_of_scene}: Path='{path_of_asset}', Type='{type_of_asset}', Dur='{duration_for_scene}'s")
|
354 |
+
if not (path_of_asset and os.path.exists(path_of_asset)): logger.warning(f"S{num_of_scene}: Not found '{path_of_asset}'. Skip."); continue
|
355 |
+
if duration_for_scene <= 0: logger.warning(f"S{num_of_scene}: Invalid duration ({duration_for_scene}s). Skip."); continue
|
356 |
+
active_scene_clip = None
|
357 |
try:
|
358 |
+
if type_of_asset == 'image':
|
359 |
+
opened_pil_img = Image.open(path_of_asset); logger.debug(f"S{num_of_scene}: Loaded img. Mode:{opened_pil_img.mode}, Size:{opened_pil_img.size}")
|
360 |
+
converted_img_rgba = opened_pil_img.convert('RGBA') if opened_pil_img.mode != 'RGBA' else opened_pil_img.copy()
|
361 |
+
thumbnailed_img = converted_img_rgba.copy(); resample_f = Image.Resampling.LANCZOS if hasattr(Image.Resampling,'LANCZOS') else Image.BILINEAR; thumbnailed_img.thumbnail(self.video_frame_size,resample_f)
|
362 |
+
rgba_canvas = Image.new('RGBA',self.video_frame_size,(0,0,0,0)); pos_x,pos_y=(self.video_frame_size[0]-thumbnailed_img.width)//2,(self.video_frame_size[1]-thumbnailed_img.height)//2
|
363 |
+
rgba_canvas.paste(thumbnailed_img,(pos_x,pos_y),thumbnailed_img)
|
364 |
+
final_rgb_img_pil = Image.new("RGB",self.video_frame_size,(0,0,0)); final_rgb_img_pil.paste(rgba_canvas,mask=rgba_canvas.split()[3])
|
365 |
+
debug_path_img_pre_numpy = os.path.join(self.output_dir,f"debug_PRE_NUMPY_S{num_of_scene}.png"); final_rgb_img_pil.save(debug_path_img_pre_numpy); logger.info(f"DEBUG: Saved PRE_NUMPY_S{num_of_scene} to {debug_path_img_pre_numpy}")
|
366 |
+
numpy_frame_arr = np.array(final_rgb_img_pil,dtype=np.uint8);
|
367 |
+
if not numpy_frame_arr.flags['C_CONTIGUOUS']: numpy_frame_arr=np.ascontiguousarray(numpy_frame_arr,dtype=np.uint8)
|
368 |
+
logger.debug(f"S{num_of_scene}: NumPy for MoviePy. Shape:{numpy_frame_arr.shape}, DType:{numpy_frame_arr.dtype}, C-Contig:{numpy_frame_arr.flags['C_CONTIGUOUS']}")
|
369 |
+
if numpy_frame_arr.size==0 or numpy_frame_arr.ndim!=3 or numpy_frame_arr.shape[2]!=3: logger.error(f"S{num_of_scene}: Invalid NumPy array for MoviePy. Skip."); continue
|
370 |
+
base_image_clip = ImageClip(numpy_frame_arr,transparent=False).set_duration(duration_for_scene)
|
371 |
+
debug_path_moviepy_frame=os.path.join(self.output_dir,f"debug_MOVIEPY_FRAME_S{num_of_scene}.png"); base_image_clip.save_frame(debug_path_moviepy_frame,t=0.1); logger.info(f"DEBUG: Saved MOVIEPY_FRAME_S{num_of_scene} to {debug_path_moviepy_frame}")
|
372 |
+
fx_image_clip = base_image_clip
|
373 |
+
try: scale_end_kb=random.uniform(1.03,1.08); fx_image_clip=base_image_clip.fx(vfx.resize,lambda t_val:1+(scale_end_kb-1)*(t_val/duration_for_scene) if duration_for_scene>0 else 1).set_position('center')
|
374 |
+
except Exception as e_kb_fx: logger.error(f"S{num_of_scene} Ken Burns error: {e_kb_fx}",exc_info=False)
|
375 |
+
active_scene_clip = fx_image_clip
|
376 |
+
elif type_of_asset == 'video':
|
377 |
+
source_video_clip_obj=None
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
378 |
try:
|
379 |
+
source_video_clip_obj=VideoFileClip(path_of_asset,target_resolution=(self.video_frame_size[1],self.video_frame_size[0])if self.video_frame_size else None, audio=False)
|
380 |
+
temp_video_clip_obj_loop=source_video_clip_obj
|
381 |
+
if source_video_clip_obj.duration!=duration_for_scene:
|
382 |
+
if source_video_clip_obj.duration>duration_for_scene:temp_video_clip_obj_loop=source_video_clip_obj.subclip(0,duration_for_scene)
|
|
|
|
|
|
|
|
|
|
|
383 |
else:
|
384 |
+
if duration_for_scene/source_video_clip_obj.duration > 1.5 and source_video_clip_obj.duration>0.1:temp_video_clip_obj_loop=source_video_clip_obj.loop(duration=duration_for_scene)
|
385 |
+
else:temp_video_clip_obj_loop=source_video_clip_obj.set_duration(source_video_clip_obj.duration);logger.info(f"S{num_of_scene} Video clip ({source_video_clip_obj.duration:.2f}s) shorter than target ({duration_for_scene:.2f}s).")
|
386 |
+
active_scene_clip=temp_video_clip_obj_loop.set_duration(duration_for_scene)
|
387 |
+
if active_scene_clip.size!=list(self.video_frame_size):active_scene_clip=active_scene_clip.resize(self.video_frame_size)
|
388 |
+
except Exception as e_vid_load_loop:logger.error(f"S{num_of_scene} Video load error '{path_of_asset}':{e_vid_load_loop}",exc_info=True);continue
|
|
|
|
|
|
|
|
|
|
|
|
|
389 |
finally:
|
390 |
+
if source_video_clip_obj and source_video_clip_obj is not active_scene_clip and hasattr(source_video_clip_obj,'close'):source_video_clip_obj.close()
|
391 |
+
else: logger.warning(f"S{num_of_scene} Unknown asset type '{type_of_asset}'. Skip."); continue
|
392 |
+
if active_scene_clip and action_in_key:
|
|
|
|
|
|
|
|
|
393 |
try:
|
394 |
+
dur_text_overlay=min(active_scene_clip.duration-0.5,active_scene_clip.duration*0.8)if active_scene_clip.duration>0.5 else active_scene_clip.duration; start_text_overlay=0.25
|
395 |
+
if dur_text_overlay > 0:
|
396 |
+
text_clip_for_overlay=TextClip(f"Scene {num_of_scene}\n{action_in_key}",fontsize=self.VIDEO_OVERLAY_FONT_SIZE,color=self.VIDEO_OVERLAY_FONT_COLOR,font=self.active_moviepy_font_name,bg_color='rgba(10,10,20,0.7)',method='caption',align='West',size=(self.video_frame_size[0]*0.9,None),kerning=-1,stroke_color='black',stroke_width=1.5).set_duration(dur_text_overlay).set_start(start_text_overlay).set_position(('center',0.92),relative=True)
|
397 |
+
active_scene_clip=CompositeVideoClip([active_scene_clip,text_clip_for_overlay],size=self.video_frame_size,use_bgclip=True)
|
398 |
+
else: logger.warning(f"S{num_of_scene}: Text overlay duration zero. Skip text.")
|
399 |
+
except Exception as e_txt_comp:logger.error(f"S{num_of_scene} TextClip error:{e_txt_comp}. No text.",exc_info=True)
|
400 |
+
if active_scene_clip:processed_moviepy_clips_list.append(active_scene_clip);logger.info(f"S{num_of_scene} Processed. Dur:{active_scene_clip.duration:.2f}s.")
|
401 |
+
except Exception as e_asset_loop_main:logger.error(f"MAJOR Error processing asset for S{num_of_scene} ({path_of_asset}):{e_asset_loop_main}",exc_info=True)
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
402 |
finally:
|
403 |
+
if active_scene_clip and hasattr(active_scene_clip,'close'):
|
404 |
+
try: active_scene_clip.close()
|
405 |
+
except: pass
|
406 |
+
if not processed_moviepy_clips_list:logger.warning("No clips processed for animatic. Aborting.");return None
|
407 |
+
transition_duration_val=0.75
|
|
|
|
|
|
|
|
|
|
|
408 |
try:
|
409 |
+
logger.info(f"Concatenating {len(processed_moviepy_clips_list)} clips for final animatic.");
|
410 |
+
if len(processed_moviepy_clips_list)>1:final_video_output_clip=concatenate_videoclips(processed_moviepy_clips_list,padding=-transition_duration_val if transition_duration_val>0 else 0,method="compose")
|
411 |
+
elif processed_moviepy_clips_list:final_video_output_clip=processed_moviepy_clips_list[0]
|
412 |
+
if not final_video_output_clip:logger.error("Concatenation resulted in a None clip. Aborting.");return None
|
413 |
+
logger.info(f"Concatenated animatic duration:{final_video_output_clip.duration:.2f}s")
|
414 |
+
if transition_duration_val>0 and final_video_output_clip.duration>0:
|
415 |
+
if final_video_output_clip.duration>transition_duration_val*2:final_video_output_clip=final_video_output_clip.fx(vfx.fadein,transition_duration_val).fx(vfx.fadeout,transition_duration_val)
|
416 |
+
else:final_video_output_clip=final_video_output_clip.fx(vfx.fadein,min(transition_duration_val,final_video_output_clip.duration/2.0))
|
417 |
+
if overall_narration_path and os.path.exists(overall_narration_path) and final_video_output_clip.duration>0:
|
418 |
+
try:narration_audio_clip_mvpy=AudioFileClip(overall_narration_path);final_video_output_clip=final_video_output_clip.set_audio(narration_audio_clip_mvpy);logger.info("Overall narration added to animatic.")
|
419 |
+
except Exception as e_narr_add:logger.error(f"Error adding narration to animatic:{e_narr_add}",exc_info=True)
|
420 |
+
elif final_video_output_clip.duration<=0:logger.warning("Animatic has no duration. Audio not added.")
|
421 |
+
if final_video_output_clip and final_video_output_clip.duration>0:
|
422 |
+
final_output_path_str=os.path.join(self.output_dir,output_filename);logger.info(f"Writing final animatic video to:{final_output_path_str} (Duration:{final_video_output_clip.duration:.2f}s)")
|
423 |
+
final_video_output_clip.write_videofile(final_output_path_str,fps=fps,codec='libx264',preset='medium',audio_codec='aac',temp_audiofile=os.path.join(self.output_dir,f'temp-audio-{os.urandom(4).hex()}.m4a'),remove_temp=True,threads=os.cpu_count()or 2,logger='bar',bitrate="5000k",ffmpeg_params=["-pix_fmt", "yuv420p"])
|
424 |
+
logger.info(f"Animatic video created successfully:{final_output_path_str}");return final_output_path_str
|
425 |
+
else:logger.error("Final animatic clip is invalid or has zero duration. Cannot write video file.");return None
|
426 |
+
except Exception as e_vid_write_final:logger.error(f"Error during final animatic video file writing or composition:{e_vid_write_final}",exc_info=True);return None
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
427 |
finally:
|
428 |
+
logger.debug("Closing all MoviePy clips in `assemble_animatic_from_assets` main finally block.")
|
429 |
+
all_clips_to_close_list = processed_moviepy_clips_list + ([narration_audio_clip_mvpy] if narration_audio_clip_mvpy else []) + ([final_video_output_clip] if final_video_output_clip else [])
|
430 |
+
for clip_item_to_close in all_clips_to_close_list:
|
431 |
+
if clip_item_to_close and hasattr(clip_item_to_close, 'close'):
|
432 |
+
try: clip_item_to_close.close()
|
433 |
+
except Exception as e_final_close: logger.warning(f"Ignoring error while closing a MoviePy clip: {type(clip_item_to_close).__name__} - {e_final_close}")
|
|
|
|