Update core/visual_engine.py
Browse files- core/visual_engine.py +390 -698
core/visual_engine.py
CHANGED
@@ -1,9 +1,7 @@
|
|
|
|
1 |
from PIL import Image, ImageDraw, ImageFont, ImageOps
|
2 |
import base64
|
3 |
-
import
|
4 |
-
from moviepy.editor import (ImageClip, VideoFileClip, concatenate_videoclips, TextClip,
|
5 |
-
CompositeVideoClip, AudioFileClip)
|
6 |
-
import moviepy.video.fx.all as vfx
|
7 |
import numpy as np
|
8 |
import os
|
9 |
import openai
|
@@ -12,25 +10,28 @@ import io
|
|
12 |
import time
|
13 |
import random
|
14 |
import logging
|
15 |
-
import mimetypes
|
16 |
|
17 |
-
|
18 |
-
|
|
|
|
|
19 |
|
20 |
-
# --- MONKEY PATCH ---
|
21 |
try:
|
22 |
-
if hasattr(Image, 'Resampling') and hasattr(Image.Resampling, 'LANCZOS'):
|
23 |
-
if not hasattr(Image, 'ANTIALIAS'):
|
24 |
-
|
25 |
-
|
26 |
-
|
27 |
-
|
28 |
-
|
29 |
-
|
30 |
-
|
31 |
-
|
32 |
-
|
33 |
-
#
|
|
|
|
|
34 |
ELEVENLABS_CLIENT_IMPORTED = False
|
35 |
ElevenLabsAPIClient = None
|
36 |
Voice = None
|
@@ -42,827 +43,518 @@ try:
|
|
42 |
Voice = ImportedVoice
|
43 |
VoiceSettings = ImportedVoiceSettings
|
44 |
ELEVENLABS_CLIENT_IMPORTED = True
|
45 |
-
logger.info("ElevenLabs client components imported.")
|
46 |
-
except
|
47 |
-
logger.warning(
|
|
|
|
|
48 |
|
49 |
RUNWAYML_SDK_IMPORTED = False
|
50 |
-
RunwayMLAPIClient = None
|
51 |
try:
|
52 |
-
from runwayml import RunwayML as ImportedRunwayMLClient
|
53 |
RunwayMLAPIClient = ImportedRunwayMLClient
|
54 |
RUNWAYML_SDK_IMPORTED = True
|
55 |
logger.info("RunwayML SDK imported successfully.")
|
56 |
except ImportError:
|
57 |
logger.warning("RunwayML SDK not found (pip install runwayml). RunwayML video generation will be disabled.")
|
58 |
-
except Exception as
|
59 |
-
logger.warning(f"Error importing RunwayML SDK: {
|
60 |
|
61 |
|
62 |
class VisualEngine:
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
63 |
def __init__(self, output_dir="temp_cinegen_media", default_elevenlabs_voice_id="Rachel"):
|
64 |
self.output_dir = output_dir
|
65 |
os.makedirs(self.output_dir, exist_ok=True)
|
66 |
-
|
|
|
67 |
font_paths_to_try = [
|
68 |
-
self.
|
69 |
-
"/usr/share/fonts/truetype/dejavu/
|
70 |
-
"/usr/share/fonts/truetype/liberation/LiberationSans-Bold.ttf",
|
71 |
-
"/System/Library/Fonts/Supplemental/Arial.ttf",
|
72 |
-
"C:/Windows/Fonts/arial.ttf",
|
73 |
-
"/usr/local/share/fonts/truetype/mycustomfonts/arial.ttf"
|
74 |
]
|
75 |
-
self.
|
76 |
-
|
77 |
-
self.
|
78 |
-
self.
|
79 |
-
|
80 |
-
|
81 |
-
|
82 |
-
self.
|
83 |
-
|
84 |
-
|
85 |
-
|
86 |
-
|
87 |
-
|
88 |
-
|
89 |
-
|
90 |
-
|
91 |
-
|
92 |
-
|
93 |
-
|
94 |
-
|
95 |
-
|
96 |
-
|
|
|
|
|
97 |
self.video_frame_size = (1280, 720)
|
98 |
|
99 |
-
self.elevenlabs_api_key = None
|
100 |
-
self.USE_ELEVENLABS = False
|
101 |
-
self.elevenlabs_client = None
|
102 |
self.elevenlabs_voice_id = default_elevenlabs_voice_id
|
103 |
if VoiceSettings and ELEVENLABS_CLIENT_IMPORTED:
|
104 |
-
self.elevenlabs_voice_settings = VoiceSettings(
|
105 |
-
|
106 |
-
similarity_boost=0.80,
|
107 |
-
style=0.15,
|
108 |
-
use_speaker_boost=True
|
109 |
-
)
|
110 |
-
else:
|
111 |
-
self.elevenlabs_voice_settings = None
|
112 |
|
113 |
-
self.pexels_api_key = None
|
114 |
-
self.
|
115 |
|
116 |
-
|
117 |
-
|
118 |
-
self.runway_client = None
|
119 |
-
if RUNWAYML_SDK_IMPORTED and RunwayMLAPIClient:
|
120 |
try:
|
121 |
-
|
122 |
-
|
123 |
-
|
124 |
-
except Exception as
|
125 |
-
logger.error(f"
|
126 |
-
|
|
|
127 |
logger.info("VisualEngine initialized.")
|
128 |
|
129 |
-
|
130 |
-
|
131 |
-
self.USE_AI_IMAGE_GENERATION = bool(
|
132 |
-
logger.info(f"DALL-E ({self.dalle_model}) {'Ready
|
133 |
|
134 |
def set_elevenlabs_api_key(self, api_key, voice_id_from_secret=None):
|
135 |
self.elevenlabs_api_key = api_key
|
136 |
-
if voice_id_from_secret:
|
137 |
-
self.elevenlabs_voice_id = voice_id_from_secret
|
138 |
if api_key and ELEVENLABS_CLIENT_IMPORTED and ElevenLabsAPIClient:
|
139 |
try:
|
140 |
self.elevenlabs_client = ElevenLabsAPIClient(api_key=api_key)
|
141 |
self.USE_ELEVENLABS = bool(self.elevenlabs_client)
|
142 |
-
logger.info(f"ElevenLabs Client {'Ready' if self.USE_ELEVENLABS else 'Failed
|
143 |
except Exception as e:
|
144 |
-
logger.error(f"ElevenLabs client
|
145 |
-
self.USE_ELEVENLABS = False
|
146 |
else:
|
147 |
self.USE_ELEVENLABS = False
|
148 |
-
logger.info("ElevenLabs Disabled (
|
149 |
|
150 |
-
def set_pexels_api_key(self,
|
151 |
-
self.pexels_api_key =
|
152 |
-
self.USE_PEXELS
|
153 |
-
logger.info(f"Pexels Search {'Ready.' if k else 'Disabled.'}")
|
154 |
|
155 |
-
def set_runway_api_key(self,
|
156 |
-
self.runway_api_key =
|
157 |
-
if
|
158 |
if RUNWAYML_SDK_IMPORTED and RunwayMLAPIClient:
|
159 |
-
if not self.
|
160 |
try:
|
161 |
-
|
162 |
-
|
163 |
-
|
164 |
-
|
165 |
-
|
166 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
167 |
except Exception as e_client_init:
|
168 |
-
logger.error(f"RunwayML Client
|
169 |
-
self.USE_RUNWAYML = False
|
170 |
-
else:
|
171 |
self.USE_RUNWAYML = True
|
172 |
-
logger.info("RunwayML Client was already initialized.")
|
173 |
-
else:
|
174 |
-
logger.warning("RunwayML SDK not imported. API key
|
175 |
self.USE_RUNWAYML = False
|
176 |
-
else:
|
177 |
-
self.USE_RUNWAYML = False
|
178 |
-
logger.info("RunwayML Disabled (no API key).")
|
179 |
|
|
|
180 |
def _image_to_data_uri(self, image_path):
|
181 |
try:
|
182 |
mime_type, _ = mimetypes.guess_type(image_path)
|
183 |
if not mime_type:
|
184 |
ext = os.path.splitext(image_path)[1].lower()
|
185 |
-
|
186 |
-
|
187 |
-
|
188 |
-
|
189 |
-
else:
|
190 |
-
mime_type = "application/octet-stream"
|
191 |
-
logger.warning(f"Unknown MIME for {image_path}, using {mime_type}.")
|
192 |
with open(image_path, "rb") as image_file:
|
193 |
encoded_string = base64.b64encode(image_file.read()).decode('utf-8')
|
194 |
data_uri = f"data:{mime_type};base64,{encoded_string}"
|
195 |
-
logger.debug(f"
|
196 |
return data_uri
|
|
|
|
|
|
|
197 |
except Exception as e:
|
198 |
-
logger.error(f"Error converting {image_path} to data URI: {e}", exc_info=True)
|
199 |
return None
|
200 |
|
201 |
def _map_resolution_to_runway_ratio(self, width, height):
|
202 |
ratio_str = f"{width}:{height}"
|
203 |
-
|
204 |
-
|
|
|
205 |
return ratio_str
|
206 |
-
|
|
|
207 |
return "1280:720"
|
208 |
|
209 |
-
def _get_text_dimensions(self, text_content,
|
210 |
-
|
211 |
-
|
212 |
-
|
213 |
try:
|
214 |
-
if hasattr(
|
215 |
-
bbox
|
216 |
-
w = bbox[2] - bbox[0]
|
217 |
-
h = bbox[3] - bbox[1]
|
218 |
return w, h if h > 0 else default_char_height
|
219 |
-
elif hasattr(
|
220 |
-
w,
|
221 |
return w, h if h > 0 else default_char_height
|
222 |
-
else:
|
223 |
-
|
224 |
-
except Exception as e:
|
225 |
-
logger.warning(f"Error in _get_text_dimensions: {e}")
|
226 |
-
return int(len(text_content) * self.font_size_pil * 0.6), int(self.font_size_pil * 1.2)
|
227 |
|
228 |
def _create_placeholder_image_content(self, text_description, filename, size=None):
|
229 |
-
|
230 |
-
|
231 |
-
img = Image.new('RGB', size, color=(20, 20, 40))
|
232 |
-
|
233 |
-
|
234 |
-
|
235 |
-
lines = []
|
236 |
-
if not text_description:
|
237 |
-
text_description = "(Placeholder Image)"
|
238 |
-
words = text_description.split()
|
239 |
-
current_line = ""
|
240 |
for word_idx, word in enumerate(words):
|
241 |
-
|
242 |
-
|
243 |
-
|
244 |
-
if
|
245 |
-
|
246 |
-
if
|
247 |
-
current_line = test_line
|
248 |
else:
|
249 |
-
if
|
250 |
-
|
251 |
-
|
252 |
-
|
253 |
-
lines.append(current_line.strip())
|
254 |
if not lines and text_description:
|
255 |
-
|
256 |
-
if
|
257 |
-
avg_char_width = self.font_size_pil * 0.6
|
258 |
-
chars_per_line = int(max_w / avg_char_width) if avg_char_width > 0 else 20
|
259 |
lines.append(text_description[:chars_per_line] + ("..." if len(text_description) > chars_per_line else ""))
|
260 |
-
elif not lines:
|
261 |
-
|
262 |
-
_, single_line_h = self._get_text_dimensions("Ay", self.
|
263 |
-
|
264 |
-
|
265 |
-
|
266 |
-
|
267 |
-
|
268 |
-
|
269 |
-
|
270 |
-
|
271 |
-
|
272 |
-
|
273 |
-
|
274 |
-
|
275 |
-
|
276 |
-
|
277 |
-
except Exception as e_draw:
|
278 |
-
logger.error(f"Pillow d.text error: {e_draw} for line '{line_content}'")
|
279 |
-
y_text += single_line_h + 2
|
280 |
-
if i == 6 and max_lines_to_display > 7:
|
281 |
-
try:
|
282 |
-
d.text((x_text, y_text), "...", font=self.font, fill=(200, 200, 180))
|
283 |
-
except Exception as e_ellipsis:
|
284 |
-
logger.error(f"Pillow d.text ellipsis error: {e_ellipsis}")
|
285 |
-
break
|
286 |
filepath = os.path.join(self.output_dir, filename)
|
287 |
-
try:
|
288 |
-
|
289 |
-
return filepath
|
290 |
-
except Exception as e:
|
291 |
-
logger.error(f"Saving placeholder image {filepath}: {e}", exc_info=True)
|
292 |
-
return None
|
293 |
|
294 |
def _search_pexels_image(self, query, output_filename_base):
|
295 |
-
# <<< CORRECTED METHOD >>>
|
296 |
-
if not self.USE_PEXELS or not self.pexels_api_key:
|
297 |
-
return None
|
298 |
headers = {"Authorization": self.pexels_api_key}
|
299 |
params = {"query": query, "per_page": 1, "orientation": "landscape", "size": "large2x"}
|
300 |
-
|
301 |
-
|
302 |
filepath = os.path.join(self.output_dir, pexels_filename)
|
303 |
try:
|
304 |
-
logger.info(f"Pexels
|
305 |
effective_query = " ".join(query.split()[:5])
|
306 |
params["query"] = effective_query
|
307 |
response = requests.get("https://api.pexels.com/v1/search", headers=headers, params=params, timeout=20)
|
308 |
response.raise_for_status()
|
309 |
data = response.json()
|
310 |
if data.get("photos") and len(data["photos"]) > 0:
|
311 |
-
|
312 |
-
|
313 |
-
|
314 |
-
|
315 |
-
|
316 |
-
|
317 |
-
|
318 |
-
|
319 |
-
|
320 |
-
|
321 |
-
|
322 |
-
|
323 |
-
|
324 |
-
|
325 |
-
|
326 |
-
logger.error(f"Pexels JSON decode error for query '{query}': {e_json}", exc_info=True)
|
327 |
-
except IOError as e_io:
|
328 |
-
logger.error(f"Pexels image save error for query '{query}': {e_io}", exc_info=True)
|
329 |
-
except Exception as e:
|
330 |
-
logger.error(f"Unexpected Pexels error for query '{query}': {e}", exc_info=True)
|
331 |
-
return None
|
332 |
-
|
333 |
-
def _generate_video_clip_with_runwayml(self, text_prompt_for_motion, input_image_path,
|
334 |
-
scene_identifier_filename_base, target_duration_seconds=5):
|
335 |
-
if not self.USE_RUNWAYML or not self.runway_client:
|
336 |
-
logger.warning("RunwayML not enabled/client not init. Skip video.")
|
337 |
return None
|
338 |
if not input_image_path or not os.path.exists(input_image_path):
|
339 |
-
logger.error(f"Runway Gen-4
|
340 |
return None
|
|
|
341 |
image_data_uri = self._image_to_data_uri(input_image_path)
|
342 |
-
if not image_data_uri:
|
343 |
-
|
344 |
-
runway_duration = 10 if target_duration_seconds
|
345 |
-
runway_ratio_str = self._map_resolution_to_runway_ratio(
|
346 |
-
|
347 |
-
|
348 |
-
|
349 |
-
|
350 |
-
)
|
351 |
output_video_filepath = os.path.join(self.output_dir, output_video_filename)
|
352 |
-
|
353 |
-
|
354 |
try:
|
355 |
-
|
|
|
356 |
model='gen4_turbo',
|
357 |
prompt_image=image_data_uri,
|
358 |
-
prompt_text=text_prompt_for_motion,
|
359 |
duration=runway_duration,
|
360 |
-
ratio=runway_ratio_str
|
|
|
|
|
361 |
)
|
362 |
-
|
363 |
-
|
364 |
-
|
365 |
-
|
366 |
-
|
367 |
-
|
368 |
-
|
|
|
|
|
|
|
|
|
|
|
369 |
if task_details.status == 'SUCCEEDED':
|
370 |
-
|
371 |
-
|
372 |
-
|
373 |
-
|
374 |
-
|
375 |
-
|
376 |
-
|
377 |
-
)
|
378 |
-
|
379 |
-
getattr(task_details, 'artifacts', None)
|
380 |
-
and task_details.artifacts[0].download_url
|
381 |
-
if task_details.artifacts and hasattr(task_details.artifacts[0], 'download_url')
|
382 |
-
else None
|
383 |
-
)
|
384 |
-
)
|
385 |
if not output_url:
|
386 |
-
logger.error(
|
387 |
-
f"Runway task {task.id} SUCCEEDED, but no output URL in details: "
|
388 |
-
f"{vars(task_details) if hasattr(task_details, '__dict__') else task_details}"
|
389 |
-
)
|
390 |
return None
|
391 |
-
|
|
|
392 |
video_response = requests.get(output_url, stream=True, timeout=300)
|
393 |
video_response.raise_for_status()
|
394 |
with open(output_video_filepath, 'wb') as f:
|
395 |
-
for chunk in video_response.iter_content(chunk_size=8192):
|
396 |
-
|
397 |
-
logger.info(f"Runway Gen-4 video saved: {output_video_filepath}")
|
398 |
return output_video_filepath
|
399 |
-
|
400 |
-
|
401 |
-
|
402 |
-
|
403 |
-
)
|
404 |
-
logger.error(f"Runway task {task.id} status: {task_details.status}. Error: {em}")
|
405 |
return None
|
406 |
-
|
|
|
407 |
return None
|
408 |
-
|
409 |
-
|
|
|
410 |
return None
|
411 |
-
except Exception as
|
412 |
-
logger.error(f"Runway Gen-4 API
|
413 |
return None
|
414 |
|
415 |
-
def _create_placeholder_video_content(self,
|
416 |
-
|
417 |
-
|
418 |
-
|
419 |
-
|
420 |
-
try:
|
421 |
-
tc = TextClip(
|
422 |
-
td,
|
423 |
-
fontsize=50,
|
424 |
-
color='white',
|
425 |
-
font=self.video_overlay_font,
|
426 |
-
bg_color='black',
|
427 |
-
size=sz,
|
428 |
-
method='caption'
|
429 |
-
).set_duration(dur)
|
430 |
-
tc.write_videofile(fp, fps=24, codec='libx264', preset='ultrafast', logger=None, threads=2)
|
431 |
-
logger.info(f"Generic placeholder video: {fp}")
|
432 |
-
return fp
|
433 |
-
except Exception as e:
|
434 |
-
logger.error(f"Generic placeholder video error {fp}: {e}", exc_info=True)
|
435 |
-
return None
|
436 |
finally:
|
437 |
-
if tc and hasattr(tc, 'close'):
|
438 |
-
|
439 |
-
|
440 |
-
def generate_scene_asset(
|
441 |
-
|
442 |
-
|
443 |
-
|
444 |
-
scene_data,
|
445 |
-
scene_identifier_filename_base,
|
446 |
-
generate_as_video_clip=False,
|
447 |
-
runway_target_duration=5
|
448 |
-
):
|
449 |
base_name, _ = os.path.splitext(scene_identifier_filename_base)
|
450 |
-
asset_info = {
|
451 |
-
'path': None,
|
452 |
-
'type': 'none',
|
453 |
-
'error': True,
|
454 |
-
'prompt_used': image_generation_prompt_text,
|
455 |
-
'error_message': 'Asset generation init failed'
|
456 |
-
}
|
457 |
input_image_for_runway_path = None
|
|
|
458 |
base_image_filename = base_name + ("_base_for_video.png" if generate_as_video_clip else ".png")
|
459 |
base_image_filepath = os.path.join(self.output_dir, base_image_filename)
|
460 |
-
|
|
|
|
|
461 |
if self.USE_AI_IMAGE_GENERATION and self.openai_api_key:
|
462 |
-
|
|
|
463 |
for att_n in range(max_r):
|
464 |
-
try:
|
465 |
-
|
466 |
-
|
467 |
-
|
468 |
-
|
469 |
-
|
470 |
-
|
471 |
-
|
472 |
-
|
473 |
-
|
474 |
-
|
475 |
-
|
476 |
-
|
477 |
-
|
478 |
-
|
479 |
-
|
480 |
-
|
481 |
-
|
482 |
-
id_img = Image.open(io.BytesIO(ir.content))
|
483 |
-
if id_img.mode != 'RGB':
|
484 |
-
id_img = id_img.convert('RGB')
|
485 |
-
id_img.save(base_image_filepath)
|
486 |
-
logger.info(f"DALL-E base img saved: {base_image_filepath}")
|
487 |
-
input_image_for_runway_path = base_image_filepath
|
488 |
-
asset_info = {
|
489 |
-
'path': base_image_filepath,
|
490 |
-
'type': 'image',
|
491 |
-
'error': False,
|
492 |
-
'prompt_used': image_generation_prompt_text,
|
493 |
-
'revised_prompt': rp
|
494 |
-
}
|
495 |
-
break
|
496 |
-
except openai.RateLimitError as e:
|
497 |
-
logger.warning(f"OpenAI RateLimit {att_n+1}:{e}. Retry...")
|
498 |
-
time.sleep(5 * (att_n + 1))
|
499 |
-
asset_info['error_message'] = str(e)
|
500 |
-
except Exception as e:
|
501 |
-
logger.error(f"DALL-E base img error: {e}", exc_info=True)
|
502 |
-
asset_info['error_message'] = str(e)
|
503 |
-
break
|
504 |
-
if asset_info['error']:
|
505 |
-
logger.warning(f"DALL-E failed after {att_n+1} attempts for base img.")
|
506 |
-
|
507 |
-
if asset_info['error'] and self.USE_PEXELS:
|
508 |
-
logger.info("Trying Pexels for base img.")
|
509 |
-
pqt = scene_data.get('pexels_search_query_감독', f"{scene_data.get('emotional_beat','')} {scene_data.get('setting_description','')}")
|
510 |
-
pp = self._search_pexels_image(pqt, base_image_filename)
|
511 |
-
if pp:
|
512 |
-
input_image_for_runway_path = pp
|
513 |
-
asset_info = {
|
514 |
-
'path': pp,
|
515 |
-
'type': 'image',
|
516 |
-
'error': False,
|
517 |
-
'prompt_used': f"Pexels:{pqt}"
|
518 |
-
}
|
519 |
-
else:
|
520 |
-
current_em = asset_info.get('error_message', "")
|
521 |
-
asset_info['error_message'] = (current_em + " Pexels failed for base.").strip()
|
522 |
-
|
523 |
-
if asset_info['error']:
|
524 |
-
logger.warning("Base img (DALL-E/Pexels) failed. Using placeholder.")
|
525 |
-
ppt = asset_info.get('prompt_used', image_generation_prompt_text)
|
526 |
-
php = self._create_placeholder_image_content(f"[Base Placeholder]{ppt[:70]}...", base_image_filename)
|
527 |
-
if php:
|
528 |
-
input_image_for_runway_path = php
|
529 |
-
asset_info = {
|
530 |
-
'path': php,
|
531 |
-
'type': 'image',
|
532 |
-
'error': False,
|
533 |
-
'prompt_used': ppt
|
534 |
-
}
|
535 |
-
else:
|
536 |
-
current_em = asset_info.get('error_message', "")
|
537 |
-
asset_info['error_message'] = (current_em + " Base placeholder failed.").strip()
|
538 |
-
|
539 |
if generate_as_video_clip:
|
540 |
if not input_image_for_runway_path:
|
541 |
-
logger.error("RunwayML video: base img failed.")
|
542 |
-
|
543 |
-
|
544 |
-
asset_info
|
545 |
-
|
546 |
-
|
547 |
-
logger.info(f"Runway Gen-4 video for {base_name} using base: {input_image_for_runway_path}")
|
548 |
-
video_path = self._generate_video_clip_with_runwayml(
|
549 |
-
motion_prompt_text_for_video,
|
550 |
-
input_image_for_runway_path,
|
551 |
-
base_name,
|
552 |
-
runway_target_duration
|
553 |
-
)
|
554 |
-
if video_path and os.path.exists(video_path):
|
555 |
-
asset_info = {
|
556 |
-
'path': video_path,
|
557 |
-
'type': 'video',
|
558 |
-
'error': False,
|
559 |
-
'prompt_used': motion_prompt_text_for_video,
|
560 |
-
'base_image_path': input_image_for_runway_path
|
561 |
-
}
|
562 |
-
else:
|
563 |
-
logger.warning(f"RunwayML video failed for {base_name}. Fallback to base img.")
|
564 |
-
asset_info['error'] = True
|
565 |
-
asset_info['error_message'] = (
|
566 |
-
asset_info.get('error_message', "Base img ok.") +
|
567 |
-
" RunwayML video fail; use base img."
|
568 |
-
).strip()
|
569 |
-
asset_info['path'] = input_image_for_runway_path
|
570 |
-
asset_info['type'] = 'image'
|
571 |
-
asset_info['prompt_used'] = image_generation_prompt_text
|
572 |
-
else:
|
573 |
-
logger.warning("RunwayML selected but disabled. Use base img.")
|
574 |
-
asset_info['error'] = True
|
575 |
-
asset_info['error_message'] = (
|
576 |
-
asset_info.get('error_message', "Base img ok.") +
|
577 |
-
" RunwayML disabled; use base img."
|
578 |
-
).strip()
|
579 |
-
asset_info['path'] = input_image_for_runway_path
|
580 |
-
asset_info['type'] = 'image'
|
581 |
-
asset_info['prompt_used'] = image_generation_prompt_text
|
582 |
-
|
583 |
return asset_info
|
584 |
|
585 |
def generate_narration_audio(self, text_to_narrate, output_filename="narration_overall.mp3"):
|
586 |
-
|
587 |
-
|
588 |
-
|
589 |
-
|
590 |
-
|
591 |
-
|
592 |
-
|
593 |
-
|
594 |
-
|
595 |
-
|
596 |
-
|
597 |
-
|
598 |
-
|
599 |
-
|
600 |
-
|
601 |
-
|
602 |
-
|
603 |
-
|
604 |
-
|
605 |
-
|
606 |
-
|
607 |
-
logger.info("Using 11L .generate()")
|
608 |
-
if Voice and self.elevenlabs_voice_settings:
|
609 |
-
vp = Voice(
|
610 |
-
voice_id=str(self.elevenlabs_voice_id),
|
611 |
-
settings=self.elevenlabs_voice_settings
|
612 |
-
)
|
613 |
-
else:
|
614 |
-
vp = str(self.elevenlabs_voice_id)
|
615 |
-
|
616 |
-
ab = self.elevenlabs_client.generate(
|
617 |
-
text=text_to_narrate,
|
618 |
-
voice=vp,
|
619 |
-
model="eleven_multilingual_v2"
|
620 |
-
)
|
621 |
-
|
622 |
-
with open(afp, "wb") as f:
|
623 |
-
f.write(ab)
|
624 |
-
|
625 |
-
logger.info(f"11L audio (non-stream): {afp}")
|
626 |
-
return afp
|
627 |
-
|
628 |
-
else:
|
629 |
-
logger.error("No 11L audio method.")
|
630 |
-
return None
|
631 |
-
|
632 |
-
# If a streaming method is available:
|
633 |
-
if asm:
|
634 |
-
vps = {"voice_id": str(self.elevenlabs_voice_id)}
|
635 |
-
if self.elevenlabs_voice_settings:
|
636 |
-
if hasattr(self.elevenlabs_voice_settings, 'model_dump'):
|
637 |
-
vps["voice_settings"] = self.elevenlabs_voice_settings.model_dump()
|
638 |
-
elif hasattr(self.elevenlabs_voice_settings, 'dict'):
|
639 |
-
vps["voice_settings"] = self.elevenlabs_voice_settings.dict()
|
640 |
-
else:
|
641 |
-
vps["voice_settings"] = self.elevenlabs_voice_settings
|
642 |
-
|
643 |
-
adi = asm(
|
644 |
-
text=text_to_narrate,
|
645 |
-
model_id="eleven_multilingual_v2",
|
646 |
-
**vps
|
647 |
-
)
|
648 |
-
|
649 |
-
with open(afp, "wb") as f:
|
650 |
-
for c in adi:
|
651 |
-
if c:
|
652 |
-
f.write(c)
|
653 |
-
|
654 |
-
logger.info(f"11L audio (stream): {afp}")
|
655 |
-
return afp
|
656 |
-
|
657 |
-
except Exception as e:
|
658 |
-
logger.error(f"11L audio error: {e}", exc_info=True)
|
659 |
-
return None
|
660 |
-
|
661 |
def assemble_animatic_from_assets(self, asset_data_list, overall_narration_path=None, output_filename="final_video.mp4", fps=24):
|
662 |
-
|
663 |
-
|
664 |
-
|
665 |
-
|
666 |
-
processed_clips = []
|
667 |
-
narration_clip = None
|
668 |
-
final_clip = None
|
669 |
logger.info(f"Assembling from {len(asset_data_list)} assets. Frame: {self.video_frame_size}.")
|
670 |
|
671 |
for i, asset_info in enumerate(asset_data_list):
|
672 |
-
asset_path = asset_info.get('path')
|
673 |
-
|
674 |
-
scene_dur = asset_info.get('duration', 4.5)
|
675 |
-
scene_num = asset_info.get('scene_num', i + 1)
|
676 |
-
key_action = asset_info.get('key_action', '')
|
677 |
logger.info(f"S{scene_num}: Path='{asset_path}', Type='{asset_type}', Dur='{scene_dur}'s")
|
678 |
|
679 |
-
if not (asset_path and os.path.exists(asset_path)):
|
680 |
-
|
681 |
-
continue
|
682 |
-
if scene_dur <= 0:
|
683 |
-
logger.warning(f"S{scene_num}: Invalid duration ({scene_dur}s). Skip.")
|
684 |
-
continue
|
685 |
|
686 |
current_scene_mvpy_clip = None
|
687 |
try:
|
688 |
if asset_type == 'image':
|
689 |
-
pil_img = Image.open(asset_path)
|
690 |
-
logger.debug(f"S{scene_num}: Loaded img. Mode:{pil_img.mode}, Size:{pil_img.size}")
|
691 |
img_rgba = pil_img.convert('RGBA') if pil_img.mode != 'RGBA' else pil_img.copy()
|
692 |
-
thumb = img_rgba.copy()
|
693 |
-
|
694 |
-
|
695 |
-
|
696 |
-
|
697 |
-
|
698 |
-
|
699 |
-
cv_rgba.paste(thumb, (xo, yo), thumb)
|
700 |
-
final_rgb_pil = Image.new("RGB", self.video_frame_size, (0, 0, 0))
|
701 |
-
final_rgb_pil.paste(cv_rgba, mask=cv_rgba.split()[3])
|
702 |
-
|
703 |
-
dbg_path = os.path.join(self.output_dir, f"debug_PRE_NUMPY_S{scene_num}.png")
|
704 |
-
final_rgb_pil.save(dbg_path)
|
705 |
-
logger.info(f"DEBUG: Saved PRE_NUMPY_S{scene_num} to {dbg_path}")
|
706 |
-
|
707 |
-
frame_np = np.array(final_rgb_pil, dtype=np.uint8)
|
708 |
-
if not frame_np.flags['C_CONTIGUOUS']:
|
709 |
-
frame_np = np.ascontiguousarray(frame_np, dtype=np.uint8)
|
710 |
logger.debug(f"S{scene_num}: NumPy for MoviePy. Shape:{frame_np.shape}, DType:{frame_np.dtype}, C-Contig:{frame_np.flags['C_CONTIGUOUS']}")
|
711 |
-
|
712 |
-
|
713 |
-
|
714 |
-
continue
|
715 |
-
|
716 |
-
clip_base = ImageClip(frame_np, transparent=False).set_duration(scene_dur)
|
717 |
-
mvpy_dbg_path = os.path.join(self.output_dir, f"debug_MOVIEPY_FRAME_S{scene_num}.png")
|
718 |
-
clip_base.save_frame(mvpy_dbg_path, t=0.1)
|
719 |
-
logger.info(f"DEBUG: Saved MOVIEPY_FRAME_S{scene_num} to {mvpy_dbg_path}")
|
720 |
-
|
721 |
clip_fx = clip_base
|
722 |
-
try:
|
723 |
-
|
724 |
-
clip_fx = clip_base.fx(
|
725 |
-
vfx.resize,
|
726 |
-
lambda t: 1 + (es - 1) * (t / scene_dur) if scene_dur > 0 else 1
|
727 |
-
).set_position('center')
|
728 |
-
except Exception as e:
|
729 |
-
logger.error(f"S{scene_num} Ken Burns error: {e}", exc_info=False)
|
730 |
-
|
731 |
current_scene_mvpy_clip = clip_fx
|
732 |
-
|
733 |
elif asset_type == 'video':
|
734 |
-
src_clip
|
735 |
try:
|
736 |
-
src_clip
|
737 |
-
|
738 |
-
|
739 |
-
|
740 |
-
)
|
741 |
-
tmp_clip = src_clip
|
742 |
-
if src_clip.duration != scene_dur:
|
743 |
-
if src_clip.duration > scene_dur:
|
744 |
-
tmp_clip = src_clip.subclip(0, scene_dur)
|
745 |
else:
|
746 |
-
if scene_dur
|
747 |
-
|
748 |
-
|
749 |
-
|
750 |
-
|
751 |
-
current_scene_mvpy_clip = tmp_clip.set_duration(scene_dur)
|
752 |
-
if current_scene_mvpy_clip.size != list(self.video_frame_size):
|
753 |
-
current_scene_mvpy_clip = current_scene_mvpy_clip.resize(self.video_frame_size)
|
754 |
-
except Exception as e:
|
755 |
-
logger.error(f"S{scene_num} Video load error '{asset_path}': {e}", exc_info=True)
|
756 |
-
continue
|
757 |
finally:
|
758 |
-
if src_clip and src_clip is not current_scene_mvpy_clip and hasattr(src_clip,
|
759 |
-
|
760 |
-
|
761 |
-
logger.warning(f"S{scene_num} Unknown asset type '{asset_type}'. Skip.")
|
762 |
-
continue
|
763 |
-
|
764 |
if current_scene_mvpy_clip and key_action:
|
765 |
try:
|
766 |
-
to_dur
|
767 |
-
|
768 |
-
to_start = 0.25
|
769 |
if to_dur > 0:
|
770 |
-
txt_c
|
771 |
-
|
772 |
-
|
773 |
-
|
774 |
-
|
775 |
-
|
776 |
-
method='caption',
|
777 |
-
align='West',
|
778 |
-
size=(self.video_frame_size[0] * 0.9, None),
|
779 |
-
kerning=-1,
|
780 |
-
stroke_color='black',
|
781 |
-
stroke_width=1.5
|
782 |
-
).set_duration(to_dur).set_start(to_start).set_position(('center', 0.92), relative=True)
|
783 |
-
current_scene_mvpy_clip = CompositeVideoClip(
|
784 |
-
[current_scene_mvpy_clip, txt_c],
|
785 |
-
size=self.video_frame_size,
|
786 |
-
use_bgclip=True
|
787 |
-
)
|
788 |
-
else:
|
789 |
-
logger.warning(f"S{scene_num}: Text overlay duration is zero. Skip text.")
|
790 |
-
except Exception as e:
|
791 |
-
logger.error(f"S{scene_num} TextClip error: {e}. No text.", exc_info=True)
|
792 |
-
|
793 |
-
if current_scene_mvpy_clip:
|
794 |
-
processed_clips.append(current_scene_mvpy_clip)
|
795 |
-
logger.info(f"S{scene_num} Processed. Dur:{current_scene_mvpy_clip.duration:.2f}s.")
|
796 |
-
except Exception as e:
|
797 |
-
logger.error(f"MAJOR Error S{scene_num} ({asset_path}): {e}", exc_info=True)
|
798 |
finally:
|
799 |
-
if current_scene_mvpy_clip and hasattr(current_scene_mvpy_clip,
|
800 |
-
try:
|
801 |
-
|
802 |
-
except Exception:
|
803 |
-
pass
|
804 |
-
|
805 |
-
if not processed_clips:
|
806 |
-
logger.warning("No clips processed. Abort.")
|
807 |
-
return None
|
808 |
|
809 |
-
|
|
|
810 |
try:
|
811 |
-
logger.info(f"Concatenating {len(processed_clips)} clips.")
|
812 |
-
if len(processed_clips) >
|
813 |
-
|
814 |
-
|
815 |
-
final_clip = processed_clips[0]
|
816 |
-
if not final_clip:
|
817 |
-
logger.error("Concatenation failed.")
|
818 |
-
return None
|
819 |
logger.info(f"Concatenated dur:{final_clip.duration:.2f}s")
|
820 |
-
if td
|
821 |
-
if final_clip.duration
|
822 |
-
|
823 |
-
|
824 |
-
|
825 |
-
|
826 |
-
|
827 |
-
|
828 |
-
|
829 |
-
|
830 |
-
|
831 |
-
|
832 |
-
|
833 |
-
logger.warning("Video no duration. No audio.")
|
834 |
-
if final_clip and final_clip.duration > 0:
|
835 |
-
op = os.path.join(self.output_dir, output_filename)
|
836 |
-
logger.info(f"Writing video:{op} (Dur:{final_clip.duration:.2f}s)")
|
837 |
-
final_clip.write_videofile(
|
838 |
-
op,
|
839 |
-
fps=fps,
|
840 |
-
codec='libx264',
|
841 |
-
preset='medium',
|
842 |
-
audio_codec='aac',
|
843 |
-
temp_audiofile=os.path.join(
|
844 |
-
self.output_dir, f'temp-audio-{os.urandom(4).hex()}.m4a'
|
845 |
-
),
|
846 |
-
remove_temp=True,
|
847 |
-
threads=os.cpu_count() or 2,
|
848 |
-
logger='bar',
|
849 |
-
bitrate="5000k",
|
850 |
-
ffmpeg_params=["-pix_fmt", "yuv420p"]
|
851 |
-
)
|
852 |
-
logger.info(f"Video created:{op}")
|
853 |
-
return op
|
854 |
-
else:
|
855 |
-
logger.error("Final clip invalid. No write.")
|
856 |
-
return None
|
857 |
-
except Exception as e:
|
858 |
-
logger.error(f"Video write error: {e}", exc_info=True)
|
859 |
-
return None
|
860 |
finally:
|
861 |
logger.debug("Closing all MoviePy clips in `assemble_animatic_from_assets` finally block.")
|
862 |
all_clips_to_close = processed_clips + ([narration_clip] if narration_clip else []) + ([final_clip] if final_clip else [])
|
863 |
for clip_obj_to_close in all_clips_to_close:
|
864 |
if clip_obj_to_close and hasattr(clip_obj_to_close, 'close'):
|
865 |
-
try:
|
866 |
-
|
867 |
-
except Exception as e_close:
|
868 |
-
logger.warning(f"Ignoring error while closing a clip: {type(clip_obj_to_close).__name__} - {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
|
|
|
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'): # Fallback if no common resampling attributes found
|
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 |
+
# Consider setting level in main app if not already configured:
|
32 |
+
# logger.setLevel(logging.DEBUG) # For very verbose output during debugging
|
33 |
+
|
34 |
+
# --- External Service Client Imports ---
|
35 |
ELEVENLABS_CLIENT_IMPORTED = False
|
36 |
ElevenLabsAPIClient = None
|
37 |
Voice = None
|
|
|
43 |
Voice = ImportedVoice
|
44 |
VoiceSettings = ImportedVoiceSettings
|
45 |
ELEVENLABS_CLIENT_IMPORTED = True
|
46 |
+
logger.info("ElevenLabs client components imported successfully.")
|
47 |
+
except ImportError:
|
48 |
+
logger.warning("ElevenLabs SDK not found (pip install elevenlabs). Audio generation will be disabled.")
|
49 |
+
except Exception as e_eleven_import:
|
50 |
+
logger.warning(f"Error importing ElevenLabs client components: {e_eleven_import}. Audio generation disabled.")
|
51 |
|
52 |
RUNWAYML_SDK_IMPORTED = False
|
53 |
+
RunwayMLAPIClient = None # Using a more specific name for the client class
|
54 |
try:
|
55 |
+
from runwayml import RunwayML as ImportedRunwayMLClient # Actual SDK import
|
56 |
RunwayMLAPIClient = ImportedRunwayMLClient
|
57 |
RUNWAYML_SDK_IMPORTED = True
|
58 |
logger.info("RunwayML SDK imported successfully.")
|
59 |
except ImportError:
|
60 |
logger.warning("RunwayML SDK not found (pip install runwayml). RunwayML video generation will be disabled.")
|
61 |
+
except Exception as e_runway_sdk_import:
|
62 |
+
logger.warning(f"Error importing RunwayML SDK: {e_runway_sdk_import}. RunwayML features disabled.")
|
63 |
|
64 |
|
65 |
class VisualEngine:
|
66 |
+
DEFAULT_FONT_SIZE_PIL = 10 # For default Pillow font
|
67 |
+
PREFERRED_FONT_SIZE_PIL = 20 # For custom font
|
68 |
+
VIDEO_OVERLAY_FONT_SIZE = 30
|
69 |
+
VIDEO_OVERLAY_FONT_COLOR = 'white'
|
70 |
+
# Standard font names ImageMagick (used by TextClip) is likely to find in Linux containers
|
71 |
+
DEFAULT_MOVIEPY_FONT = 'DejaVu-Sans-Bold'
|
72 |
+
PREFERRED_MOVIEPY_FONT = 'Liberation-Sans-Bold' # Often available
|
73 |
+
|
74 |
def __init__(self, output_dir="temp_cinegen_media", default_elevenlabs_voice_id="Rachel"):
|
75 |
self.output_dir = output_dir
|
76 |
os.makedirs(self.output_dir, exist_ok=True)
|
77 |
+
|
78 |
+
self.font_filename_pil = "DejaVuSans-Bold.ttf" # A more standard Linux font
|
79 |
font_paths_to_try = [
|
80 |
+
self.font_filename_pil, # If in working dir or PATH
|
81 |
+
f"/usr/share/fonts/truetype/dejavu/{self.font_filename_pil}",
|
82 |
+
f"/usr/share/fonts/truetype/liberation/LiberationSans-Bold.ttf", # Alternative
|
83 |
+
f"/System/Library/Fonts/Supplemental/Arial.ttf", # macOS fallback
|
84 |
+
f"C:/Windows/Fonts/arial.ttf", # Windows fallback
|
85 |
+
f"/usr/local/share/fonts/truetype/mycustomfonts/arial.ttf" # User's previous custom path
|
86 |
]
|
87 |
+
self.font_path_pil_resolved = next((p for p in font_paths_to_try if os.path.exists(p)), None)
|
88 |
+
|
89 |
+
self.font_pil = ImageFont.load_default() # Default
|
90 |
+
self.current_font_size_pil = self.DEFAULT_FONT_SIZE_PIL
|
91 |
+
|
92 |
+
if self.font_path_pil_resolved:
|
93 |
+
try:
|
94 |
+
self.font_pil = ImageFont.truetype(self.font_path_pil_resolved, self.PREFERRED_FONT_SIZE_PIL)
|
95 |
+
self.current_font_size_pil = self.PREFERRED_FONT_SIZE_PIL
|
96 |
+
logger.info(f"Pillow font loaded: {self.font_path_pil_resolved} at size {self.current_font_size_pil}.")
|
97 |
+
# Determine MoviePy font based on loaded PIL font
|
98 |
+
if "dejavu" in self.font_path_pil_resolved.lower():
|
99 |
+
self.video_overlay_font = 'DejaVu-Sans-Bold'
|
100 |
+
elif "liberation" in self.font_path_pil_resolved.lower():
|
101 |
+
self.video_overlay_font = 'Liberation-Sans-Bold'
|
102 |
+
else: # Fallback if custom font doesn't have an obvious ImageMagick name
|
103 |
+
self.video_overlay_font = self.DEFAULT_MOVIEPY_FONT
|
104 |
+
except IOError as e_font_load:
|
105 |
+
logger.error(f"Pillow font loading IOError for '{self.font_path_pil_resolved}': {e_font_load}. Using default.")
|
106 |
+
else:
|
107 |
+
logger.warning("Custom Pillow font not found. Using default.")
|
108 |
+
|
109 |
+
self.openai_api_key = None; self.USE_AI_IMAGE_GENERATION = False
|
110 |
+
self.dalle_model = "dall-e-3"; self.image_size_dalle3 = "1792x1024"
|
111 |
self.video_frame_size = (1280, 720)
|
112 |
|
113 |
+
self.elevenlabs_api_key = None; self.USE_ELEVENLABS = False; self.elevenlabs_client = None
|
|
|
|
|
114 |
self.elevenlabs_voice_id = default_elevenlabs_voice_id
|
115 |
if VoiceSettings and ELEVENLABS_CLIENT_IMPORTED:
|
116 |
+
self.elevenlabs_voice_settings = VoiceSettings(stability=0.60, similarity_boost=0.80, style=0.15, use_speaker_boost=True)
|
117 |
+
else: self.elevenlabs_voice_settings = None
|
|
|
|
|
|
|
|
|
|
|
|
|
118 |
|
119 |
+
self.pexels_api_key = None; self.USE_PEXELS = False
|
120 |
+
self.runway_api_key = None; self.USE_RUNWAYML = False; self.runway_ml_client_instance = None # More specific name
|
121 |
|
122 |
+
# Attempt to initialize Runway client if SDK is present and env var might be set
|
123 |
+
if RUNWAYML_SDK_IMPORTED and RunwayMLAPIClient and os.getenv("RUNWAYML_API_SECRET"):
|
|
|
|
|
124 |
try:
|
125 |
+
self.runway_ml_client_instance = RunwayMLAPIClient() # SDK uses env var
|
126 |
+
self.USE_RUNWAYML = True # Assume enabled if client initializes
|
127 |
+
logger.info("RunwayML Client initialized from RUNWAYML_API_SECRET env var at startup.")
|
128 |
+
except Exception as e_runway_init_startup:
|
129 |
+
logger.error(f"Initial RunwayML client init failed (env var RUNWAYML_API_SECRET might be invalid): {e_runway_init_startup}")
|
130 |
+
self.USE_RUNWAYML = False
|
131 |
+
|
132 |
logger.info("VisualEngine initialized.")
|
133 |
|
134 |
+
# --- API Key Setters ---
|
135 |
+
def set_openai_api_key(self, api_key):
|
136 |
+
self.openai_api_key = api_key; self.USE_AI_IMAGE_GENERATION = bool(api_key)
|
137 |
+
logger.info(f"DALL-E ({self.dalle_model}) status: {'Ready' if self.USE_AI_IMAGE_GENERATION else 'Disabled'}")
|
138 |
|
139 |
def set_elevenlabs_api_key(self, api_key, voice_id_from_secret=None):
|
140 |
self.elevenlabs_api_key = api_key
|
141 |
+
if voice_id_from_secret: self.elevenlabs_voice_id = voice_id_from_secret
|
|
|
142 |
if api_key and ELEVENLABS_CLIENT_IMPORTED and ElevenLabsAPIClient:
|
143 |
try:
|
144 |
self.elevenlabs_client = ElevenLabsAPIClient(api_key=api_key)
|
145 |
self.USE_ELEVENLABS = bool(self.elevenlabs_client)
|
146 |
+
logger.info(f"ElevenLabs Client status: {'Ready' if self.USE_ELEVENLABS else 'Failed Initialization'} (Using Voice ID: {self.elevenlabs_voice_id})")
|
147 |
except Exception as e:
|
148 |
+
logger.error(f"ElevenLabs client initialization error: {e}. Service Disabled.", exc_info=True)
|
149 |
+
self.USE_ELEVENLABS = False; self.elevenlabs_client = None
|
150 |
else:
|
151 |
self.USE_ELEVENLABS = False
|
152 |
+
logger.info(f"ElevenLabs Service Disabled (API key not provided or SDK import issue).")
|
153 |
|
154 |
+
def set_pexels_api_key(self, api_key):
|
155 |
+
self.pexels_api_key = api_key; self.USE_PEXELS = bool(api_key)
|
156 |
+
logger.info(f"Pexels Search status: {'Ready' if self.USE_PEXELS else 'Disabled'}")
|
|
|
157 |
|
158 |
+
def set_runway_api_key(self, api_key):
|
159 |
+
self.runway_api_key = api_key # Store key regardless for potential direct HTTP use
|
160 |
+
if api_key:
|
161 |
if RUNWAYML_SDK_IMPORTED and RunwayMLAPIClient:
|
162 |
+
if not self.runway_ml_client_instance: # If not already initialized by env var
|
163 |
try:
|
164 |
+
# The RunwayML Python SDK expects the API key via the RUNWAYML_API_SECRET env var.
|
165 |
+
# If it's not set, we set it temporarily for client initialization.
|
166 |
+
original_env_secret = os.getenv("RUNWAYML_API_SECRET")
|
167 |
+
if not original_env_secret:
|
168 |
+
logger.info("Temporarily setting RUNWAYML_API_SECRET from provided key for SDK client init.")
|
169 |
+
os.environ["RUNWAYML_API_SECRET"] = api_key
|
170 |
+
|
171 |
+
self.runway_ml_client_instance = RunwayMLAPIClient()
|
172 |
+
self.USE_RUNWAYML = True # SDK client successfully initialized
|
173 |
+
logger.info("RunwayML Client initialized successfully using provided API key.")
|
174 |
+
|
175 |
+
if not original_env_secret: # Clean up if we set it
|
176 |
+
del os.environ["RUNWAYML_API_SECRET"]
|
177 |
+
logger.info("Cleared temporary RUNWAYML_API_SECRET env var.")
|
178 |
+
|
179 |
except Exception as e_client_init:
|
180 |
+
logger.error(f"RunwayML Client initialization via set_runway_api_key failed: {e_client_init}", exc_info=True)
|
181 |
+
self.USE_RUNWAYML = False; self.runway_ml_client_instance = None
|
182 |
+
else: # Client was already initialized (likely via env var during __init__)
|
183 |
self.USE_RUNWAYML = True
|
184 |
+
logger.info("RunwayML Client was already initialized (likely from env var). API key stored.")
|
185 |
+
else: # SDK not imported
|
186 |
+
logger.warning("RunwayML SDK not imported. API key stored, but integration requires SDK. Service effectively disabled.")
|
187 |
self.USE_RUNWAYML = False
|
188 |
+
else: # No API key provided
|
189 |
+
self.USE_RUNWAYML = False; self.runway_ml_client_instance = None
|
190 |
+
logger.info("RunwayML Service Disabled (no API key provided).")
|
191 |
|
192 |
+
# --- Helper Methods ---
|
193 |
def _image_to_data_uri(self, image_path):
|
194 |
try:
|
195 |
mime_type, _ = mimetypes.guess_type(image_path)
|
196 |
if not mime_type:
|
197 |
ext = os.path.splitext(image_path)[1].lower()
|
198 |
+
mime_map = {".png": "image/png", ".jpg": "image/jpeg", ".jpeg": "image/jpeg"}
|
199 |
+
mime_type = mime_map.get(ext, "application/octet-stream")
|
200 |
+
if mime_type == "application/octet-stream": logger.warning(f"Could not determine MIME type for {image_path}, using default.")
|
201 |
+
|
|
|
|
|
|
|
202 |
with open(image_path, "rb") as image_file:
|
203 |
encoded_string = base64.b64encode(image_file.read()).decode('utf-8')
|
204 |
data_uri = f"data:{mime_type};base64,{encoded_string}"
|
205 |
+
logger.debug(f"Generated data URI for {os.path.basename(image_path)} (first 100 chars): {data_uri[:100]}...")
|
206 |
return data_uri
|
207 |
+
except FileNotFoundError:
|
208 |
+
logger.error(f"Image file not found at {image_path} for data URI conversion.")
|
209 |
+
return None
|
210 |
except Exception as e:
|
211 |
+
logger.error(f"Error converting image {image_path} to data URI: {e}", exc_info=True)
|
212 |
return None
|
213 |
|
214 |
def _map_resolution_to_runway_ratio(self, width, height):
|
215 |
ratio_str = f"{width}:{height}"
|
216 |
+
# Gen-4 supports: "1280:720", "720:1280", "1104:832", "832:1104", "960:960", "1584:672"
|
217 |
+
supported_ratios_gen4 = ["1280:720", "720:1280", "1104:832", "832:1104", "960:960", "1584:672"]
|
218 |
+
if ratio_str in supported_ratios_gen4:
|
219 |
return ratio_str
|
220 |
+
# Fallback or find closest - for now, strict matching or default
|
221 |
+
logger.warning(f"Resolution {ratio_str} not directly in Gen-4 supported list. Defaulting to 1280:720.")
|
222 |
return "1280:720"
|
223 |
|
224 |
+
def _get_text_dimensions(self, text_content, font_object):
|
225 |
+
# (Robust version from before)
|
226 |
+
default_char_height = getattr(font_object, 'size', self.current_font_size_pil)
|
227 |
+
if not text_content: return 0, default_char_height
|
228 |
try:
|
229 |
+
if hasattr(font_object,'getbbox'):
|
230 |
+
bbox=font_object.getbbox(text_content);w=bbox[2]-bbox[0];h=bbox[3]-bbox[1]
|
|
|
|
|
231 |
return w, h if h > 0 else default_char_height
|
232 |
+
elif hasattr(font_object,'getsize'):
|
233 |
+
w,h=font_object.getsize(text_content)
|
234 |
return w, h if h > 0 else default_char_height
|
235 |
+
else: return int(len(text_content)*default_char_height*0.6),int(default_char_height*1.2)
|
236 |
+
except Exception as e: logger.warning(f"Error in _get_text_dimensions: {e}"); return int(len(text_content)*self.current_font_size_pil*0.6),int(self.current_font_size_pil*1.2)
|
|
|
|
|
|
|
237 |
|
238 |
def _create_placeholder_image_content(self, text_description, filename, size=None):
|
239 |
+
# (Corrected version from previous response)
|
240 |
+
if size is None: size = self.video_frame_size
|
241 |
+
img = Image.new('RGB', size, color=(20, 20, 40)); d = ImageDraw.Draw(img); padding = 25
|
242 |
+
max_w = size[0] - (2 * padding); lines = []
|
243 |
+
if not text_description: text_description = "(Placeholder Image)"
|
244 |
+
words = text_description.split(); current_line_text = ""
|
|
|
|
|
|
|
|
|
|
|
245 |
for word_idx, word in enumerate(words):
|
246 |
+
prospective_addition = word + (" " if word_idx < len(words) - 1 else "")
|
247 |
+
test_line_text = current_line_text + prospective_addition
|
248 |
+
current_w, _ = self._get_text_dimensions(test_line_text, self.font_pil)
|
249 |
+
if current_w == 0 and test_line_text.strip(): current_w = len(test_line_text) * (self.current_font_size_pil * 0.6) # Estimate
|
250 |
+
|
251 |
+
if current_w <= max_w: current_line_text = test_line_text
|
|
|
252 |
else:
|
253 |
+
if current_line_text.strip(): lines.append(current_line_text.strip())
|
254 |
+
current_line_text = prospective_addition # Start new line
|
255 |
+
if current_line_text.strip(): lines.append(current_line_text.strip())
|
256 |
+
|
|
|
257 |
if not lines and text_description:
|
258 |
+
avg_char_w, _ = self._get_text_dimensions("W", self.font_pil); avg_char_w = avg_char_w or (self.current_font_size_pil * 0.6)
|
259 |
+
chars_per_line = int(max_w / avg_char_w) if avg_char_w > 0 else 20
|
|
|
|
|
260 |
lines.append(text_description[:chars_per_line] + ("..." if len(text_description) > chars_per_line else ""))
|
261 |
+
elif not lines: lines.append("(Placeholder Error)")
|
262 |
+
|
263 |
+
_, single_line_h = self._get_text_dimensions("Ay", self.font_pil); single_line_h = single_line_h if single_line_h > 0 else self.current_font_size_pil + 2
|
264 |
+
max_lines = min(len(lines), (size[1] - (2 * padding)) // (single_line_h + 2)) if single_line_h > 0 else 1
|
265 |
+
max_lines = max(1, max_lines) # Ensure at least one line
|
266 |
+
|
267 |
+
y_pos = padding + (size[1] - (2 * padding) - max_lines * (single_line_h + 2)) / 2.0
|
268 |
+
for i in range(max_lines):
|
269 |
+
line_text = lines[i]; line_w, _ = self._get_text_dimensions(line_text, self.font_pil)
|
270 |
+
if line_w == 0 and line_text.strip(): line_w = len(line_text) * (self.current_font_size_pil * 0.6)
|
271 |
+
x_pos = (size[0] - line_w) / 2.0
|
272 |
+
try: d.text((x_pos, y_pos), line_text, font=self.font_pil, fill=(200, 200, 180))
|
273 |
+
except Exception as e_draw: logger.error(f"Pillow d.text error: {e_draw} for '{line_text}'")
|
274 |
+
y_pos += single_line_h + 2
|
275 |
+
if i == 6 and max_lines > 7:
|
276 |
+
try: d.text((x_pos, y_pos), "...", font=self.font_pil, fill=(200, 200, 180))
|
277 |
+
except Exception as e_elip: logger.error(f"Pillow d.text ellipsis error: {e_elip}"); break
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
278 |
filepath = os.path.join(self.output_dir, filename)
|
279 |
+
try: img.save(filepath); return filepath
|
280 |
+
except Exception as e_save: logger.error(f"Saving placeholder image '{filepath}' error: {e_save}", exc_info=True); return None
|
|
|
|
|
|
|
|
|
281 |
|
282 |
def _search_pexels_image(self, query, output_filename_base):
|
283 |
+
# <<< THIS IS THE CORRECTED METHOD >>>
|
284 |
+
if not self.USE_PEXELS or not self.pexels_api_key: return None
|
|
|
285 |
headers = {"Authorization": self.pexels_api_key}
|
286 |
params = {"query": query, "per_page": 1, "orientation": "landscape", "size": "large2x"}
|
287 |
+
base_name_for_pexels, _ = os.path.splitext(output_filename_base)
|
288 |
+
pexels_filename = base_name_for_pexels + f"_pexels_{random.randint(1000,9999)}.jpg"
|
289 |
filepath = os.path.join(self.output_dir, pexels_filename)
|
290 |
try:
|
291 |
+
logger.info(f"Pexels: Searching for '{query}'")
|
292 |
effective_query = " ".join(query.split()[:5])
|
293 |
params["query"] = effective_query
|
294 |
response = requests.get("https://api.pexels.com/v1/search", headers=headers, params=params, timeout=20)
|
295 |
response.raise_for_status()
|
296 |
data = response.json()
|
297 |
if data.get("photos") and len(data["photos"]) > 0:
|
298 |
+
photo_details = data["photos"][0]
|
299 |
+
photo_url = photo_details.get("src", {}).get("large2x")
|
300 |
+
if not photo_url: logger.warning(f"Pexels: 'large2x' URL missing for '{effective_query}'. Details: {photo_details}"); return None
|
301 |
+
image_response = requests.get(photo_url, timeout=60); image_response.raise_for_status()
|
302 |
+
img_data_pil = Image.open(io.BytesIO(image_response.content))
|
303 |
+
if img_data_pil.mode != 'RGB': img_data_pil = img_data_pil.convert('RGB')
|
304 |
+
img_data_pil.save(filepath); logger.info(f"Pexels: Image saved to {filepath}"); return filepath
|
305 |
+
else: logger.info(f"Pexels: No photos for '{effective_query}'."); return None
|
306 |
+
except requests.exceptions.RequestException as e_req: logger.error(f"Pexels: RequestException for '{query}': {e_req}", exc_info=False); return None # Less verbose for network
|
307 |
+
except Exception as e: logger.error(f"Pexels: General error for '{query}': {e}", exc_info=True); return None
|
308 |
+
|
309 |
+
# --- RunwayML Video Generation (Gen-4 Aligned with SDK) ---
|
310 |
+
def _generate_video_clip_with_runwayml(self, text_prompt_for_motion, input_image_path, scene_identifier_filename_base, target_duration_seconds=5):
|
311 |
+
if not self.USE_RUNWAYML or not self.runway_ml_client_instance:
|
312 |
+
logger.warning("RunwayML not enabled or client not initialized. Cannot generate video clip.")
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
313 |
return None
|
314 |
if not input_image_path or not os.path.exists(input_image_path):
|
315 |
+
logger.error(f"Runway Gen-4 requires an input image. Path not provided or invalid: {input_image_path}")
|
316 |
return None
|
317 |
+
|
318 |
image_data_uri = self._image_to_data_uri(input_image_path)
|
319 |
+
if not image_data_uri: return None
|
320 |
+
|
321 |
+
runway_duration = 10 if target_duration_seconds >= 8 else 5 # Map to 5s or 10s for Gen-4
|
322 |
+
runway_ratio_str = self._map_resolution_to_runway_ratio(self.video_frame_size[0], self.video_frame_size[1])
|
323 |
+
|
324 |
+
# Use a more descriptive output filename for Runway videos
|
325 |
+
base_name_for_runway, _ = os.path.splitext(scene_identifier_filename_base)
|
326 |
+
output_video_filename = base_name_for_runway + f"_runway_gen4_d{runway_duration}s.mp4"
|
|
|
327 |
output_video_filepath = os.path.join(self.output_dir, output_video_filename)
|
328 |
+
|
329 |
+
logger.info(f"Initiating Runway Gen-4 task: motion='{text_prompt_for_motion[:100]}...', image='{os.path.basename(input_image_path)}', dur={runway_duration}s, ratio='{runway_ratio_str}'")
|
330 |
try:
|
331 |
+
# Using the RunwayML Python SDK structure
|
332 |
+
task_submission = self.runway_ml_client_instance.image_to_video.create(
|
333 |
model='gen4_turbo',
|
334 |
prompt_image=image_data_uri,
|
335 |
+
prompt_text=text_prompt_for_motion, # This is the motion prompt
|
336 |
duration=runway_duration,
|
337 |
+
ratio=runway_ratio_str,
|
338 |
+
# seed=random.randint(0, 4294967295), # Optional: for reproducibility
|
339 |
+
# Other Gen-4 params (motion_score, upscale, watermark etc. can be added here if available in SDK)
|
340 |
)
|
341 |
+
task_id = task_submission.id
|
342 |
+
logger.info(f"Runway Gen-4 task created with ID: {task_id}. Polling for completion...")
|
343 |
+
|
344 |
+
poll_interval_seconds = 10
|
345 |
+
max_polling_duration_seconds = 6 * 60 # 6 minutes
|
346 |
+
start_time = time.time()
|
347 |
+
|
348 |
+
while time.time() - start_time < max_polling_duration_seconds:
|
349 |
+
time.sleep(poll_interval_seconds)
|
350 |
+
task_details = self.runway_ml_client_instance.tasks.retrieve(id=task_id)
|
351 |
+
logger.info(f"Runway task {task_id} status: {task_details.status}")
|
352 |
+
|
353 |
if task_details.status == 'SUCCEEDED':
|
354 |
+
# Determine output URL (this structure might vary based on SDK version)
|
355 |
+
output_url = None
|
356 |
+
if hasattr(task_details, 'output') and task_details.output and hasattr(task_details.output, 'url'):
|
357 |
+
output_url = task_details.output.url
|
358 |
+
elif hasattr(task_details, 'artifacts') and task_details.artifacts and isinstance(task_details.artifacts, list) and len(task_details.artifacts) > 0:
|
359 |
+
first_artifact = task_details.artifacts[0]
|
360 |
+
if hasattr(first_artifact, 'url'): output_url = first_artifact.url
|
361 |
+
elif hasattr(first_artifact, 'download_url'): output_url = first_artifact.download_url
|
362 |
+
|
|
|
|
|
|
|
|
|
|
|
|
|
363 |
if not output_url:
|
364 |
+
logger.error(f"Runway task {task_id} SUCCEEDED, but no output URL found. Details: {vars(task_details) if hasattr(task_details,'__dict__') else str(task_details)}")
|
|
|
|
|
|
|
365 |
return None
|
366 |
+
|
367 |
+
logger.info(f"Runway task {task_id} SUCCEEDED. Downloading video from: {output_url}")
|
368 |
video_response = requests.get(output_url, stream=True, timeout=300)
|
369 |
video_response.raise_for_status()
|
370 |
with open(output_video_filepath, 'wb') as f:
|
371 |
+
for chunk in video_response.iter_content(chunk_size=8192): f.write(chunk)
|
372 |
+
logger.info(f"Runway Gen-4 video successfully downloaded to: {output_video_filepath}")
|
|
|
373 |
return output_video_filepath
|
374 |
+
|
375 |
+
elif task_details.status in ['FAILED', 'ABORTED', 'ERROR']: # Added ERROR
|
376 |
+
error_msg = getattr(task_details,'error_message',None) or getattr(getattr(task_details,'output',None),'error', "Unknown error from Runway task.")
|
377 |
+
logger.error(f"Runway task {task_id} final status: {task_details.status}. Error: {error_msg}")
|
|
|
|
|
378 |
return None
|
379 |
+
|
380 |
+
logger.warning(f"Runway task {task_id} timed out polling after {max_polling_duration_seconds} seconds.")
|
381 |
return None
|
382 |
+
|
383 |
+
except AttributeError as ae: # If SDK methods are not as expected
|
384 |
+
logger.error(f"AttributeError with RunwayML SDK: {ae}. Ensure SDK is up to date and methods/attributes match documentation.", exc_info=True)
|
385 |
return None
|
386 |
+
except Exception as e_runway_call:
|
387 |
+
logger.error(f"General error during Runway Gen-4 API call or processing: {e_runway_call}", exc_info=True)
|
388 |
return None
|
389 |
|
390 |
+
def _create_placeholder_video_content(self, text_description, filename, duration=4, size=None):
|
391 |
+
# (Keeping as before)
|
392 |
+
if size is None: size = self.video_frame_size; fp = os.path.join(self.output_dir, filename); tc = None
|
393 |
+
try: tc = TextClip(text_description, fontsize=50, color='white', font=self.video_overlay_font, bg_color='black', size=size, method='caption').set_duration(duration); tc.write_videofile(fp, fps=24, codec='libx264', preset='ultrafast', logger=None, threads=2); logger.info(f"Generic placeholder video: {fp}"); return fp
|
394 |
+
except Exception as e: logger.error(f"Generic placeholder video error {fp}: {e}", exc_info=True); return None
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
395 |
finally:
|
396 |
+
if tc and hasattr(tc, 'close'): tc.close()
|
397 |
+
|
398 |
+
# --- generate_scene_asset (Main asset generation logic using Runway Gen-4 workflow) ---
|
399 |
+
def generate_scene_asset(self, image_generation_prompt_text, motion_prompt_text_for_video,
|
400 |
+
scene_data, scene_identifier_filename_base,
|
401 |
+
generate_as_video_clip=False, runway_target_duration=5):
|
402 |
+
# (Logic updated for Runway Gen-4 workflow)
|
|
|
|
|
|
|
|
|
|
|
403 |
base_name, _ = os.path.splitext(scene_identifier_filename_base)
|
404 |
+
asset_info = {'path': None, 'type': 'none', 'error': True, 'prompt_used': image_generation_prompt_text, 'error_message': 'Asset generation init failed'}
|
|
|
|
|
|
|
|
|
|
|
|
|
405 |
input_image_for_runway_path = None
|
406 |
+
# Use a distinct name for the base image if it's only an intermediate step for video
|
407 |
base_image_filename = base_name + ("_base_for_video.png" if generate_as_video_clip else ".png")
|
408 |
base_image_filepath = os.path.join(self.output_dir, base_image_filename)
|
409 |
+
|
410 |
+
# STEP 1: Generate/acquire the base image
|
411 |
+
# Try DALL-E
|
412 |
if self.USE_AI_IMAGE_GENERATION and self.openai_api_key:
|
413 |
+
# ... (DALL-E logic as in previous full rewrite - condensed for brevity here)
|
414 |
+
max_r, att_n = 2,0;
|
415 |
for att_n in range(max_r):
|
416 |
+
try:logger.info(f"Att {att_n+1} DALL-E (base img): {image_generation_prompt_text[:70]}...");cl=openai.OpenAI(api_key=self.openai_api_key,timeout=90.0);r=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");iu=r.data[0].url;rp=getattr(r.data[0],'revised_prompt',None);
|
417 |
+
if rp:logger.info(f"DALL-E revised: {rp[:70]}...");ir=requests.get(iu,timeout=120);ir.raise_for_status();id_img=Image.open(io.BytesIO(ir.content));
|
418 |
+
if id_img.mode!='RGB':id_img=id_img.convert('RGB');id_img.save(base_image_filepath);logger.info(f"DALL-E base img saved: {base_image_filepath}");input_image_for_runway_path=base_image_filepath;asset_info={'path':base_image_filepath,'type':'image','error':False,'prompt_used':image_generation_prompt_text,'revised_prompt':rp};break
|
419 |
+
except openai.RateLimitError as e:logger.warning(f"OpenAI RateLimit {att_n+1}:{e}.Retry...");time.sleep(5*(att_n+1));asset_info['error_message']=str(e)
|
420 |
+
except Exception as e:logger.error(f"DALL-E base img error:{e}",exc_info=True);asset_info['error_message']=str(e);break
|
421 |
+
if asset_info['error']:logger.warning(f"DALL-E failed after {att_n+1} attempts for base img.")
|
422 |
+
|
423 |
+
if asset_info['error'] and self.USE_PEXELS: # Pexels Fallback
|
424 |
+
logger.info("Trying Pexels for base img.");pqt=scene_data.get('pexels_search_query_감독',f"{scene_data.get('emotional_beat','')} {scene_data.get('setting_description','')}");pp=self._search_pexels_image(pqt,base_image_filename); # Use base_image_filename
|
425 |
+
if pp:input_image_for_runway_path=pp;asset_info={'path':pp,'type':'image','error':False,'prompt_used':f"Pexels:{pqt}"}
|
426 |
+
else:current_em=asset_info.get('error_message',"");asset_info['error_message']=(current_em+" Pexels failed for base.").strip()
|
427 |
+
|
428 |
+
if asset_info['error']: # Placeholder Fallback
|
429 |
+
logger.warning("Base img (DALL-E/Pexels) failed. Using placeholder.");ppt=asset_info.get('prompt_used',image_generation_prompt_text);php=self._create_placeholder_image_content(f"[Base Placeholder]{ppt[:70]}...",base_image_filename); # Use base_image_filename
|
430 |
+
if php:input_image_for_runway_path=php;asset_info={'path':php,'type':'image','error':False,'prompt_used':ppt}
|
431 |
+
else:current_em=asset_info.get('error_message',"");asset_info['error_message']=(current_em+" Base placeholder failed.").strip()
|
432 |
+
|
433 |
+
# STEP 2: If video clip is requested, use the generated base image with RunwayML
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
434 |
if generate_as_video_clip:
|
435 |
if not input_image_for_runway_path:
|
436 |
+
logger.error("RunwayML video: base image generation failed entirely. Cannot proceed.");asset_info['error']=True;asset_info['error_message']=(asset_info.get('error_message',"")+" Base img completely failed, Runway abort.").strip();asset_info['type']='none';return asset_info
|
437 |
+
if self.USE_RUNWAYML: # This check is now more about if the service is generally enabled
|
438 |
+
video_path=self._generate_video_clip_with_runwayml(motion_prompt_text_for_video,input_image_for_runway_path,base_name,runway_target_duration) # Pass base_name for runway output filename
|
439 |
+
if video_path and os.path.exists(video_path):asset_info={'path':video_path,'type':'video','error':False,'prompt_used':motion_prompt_text_for_video,'base_image_path':input_image_for_runway_path}
|
440 |
+
else:logger.warning(f"RunwayML video failed for {base_name}. Fallback to base img.");asset_info['error']=True;asset_info['error_message']=(asset_info.get('error_message',"Base img ok.")+" RunwayML video step failed; use base img.").strip();asset_info['path']=input_image_for_runway_path;asset_info['type']='image';asset_info['prompt_used']=image_generation_prompt_text
|
441 |
+
else:logger.warning("RunwayML selected but not enabled/client not ready. Use base img.");asset_info['error']=True;asset_info['error_message']=(asset_info.get('error_message',"Base img ok.")+" RunwayML disabled; use base img.").strip();asset_info['path']=input_image_for_runway_path;asset_info['type']='image';asset_info['prompt_used']=image_generation_prompt_text
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
442 |
return asset_info
|
443 |
|
444 |
def generate_narration_audio(self, text_to_narrate, output_filename="narration_overall.mp3"):
|
445 |
+
# (Keep as before - robust enough)
|
446 |
+
if not self.USE_ELEVENLABS or not self.elevenlabs_client or not text_to_narrate: logger.info("11L skip."); return None; afp=os.path.join(self.output_dir,output_filename)
|
447 |
+
try: logger.info(f"11L audio (Voice:{self.elevenlabs_voice_id}): {text_to_narrate[:70]}..."); asm=None
|
448 |
+
if hasattr(self.elevenlabs_client,'text_to_speech')and hasattr(self.elevenlabs_client.text_to_speech,'stream'):asm=self.elevenlabs_client.text_to_speech.stream;logger.info("Using 11L .text_to_speech.stream()")
|
449 |
+
elif hasattr(self.elevenlabs_client,'generate_stream'):asm=self.elevenlabs_client.generate_stream;logger.info("Using 11L .generate_stream()")
|
450 |
+
elif hasattr(self.elevenlabs_client,'generate'):logger.info("Using 11L .generate()");vp=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);ab=self.elevenlabs_client.generate(text=text_to_narrate,voice=vp,model="eleven_multilingual_v2");
|
451 |
+
with open(afp,"wb")as f:f.write(ab);logger.info(f"11L audio (non-stream): {afp}");return afp
|
452 |
+
else:logger.error("No 11L audio method.");return None
|
453 |
+
if asm:vps={"voice_id":str(self.elevenlabs_voice_id)}
|
454 |
+
if self.elevenlabs_voice_settings:
|
455 |
+
if hasattr(self.elevenlabs_voice_settings,'model_dump'):vps["voice_settings"]=self.elevenlabs_voice_settings.model_dump()
|
456 |
+
elif hasattr(self.elevenlabs_voice_settings,'dict'):vps["voice_settings"]=self.elevenlabs_voice_settings.dict()
|
457 |
+
else:vps["voice_settings"]=self.elevenlabs_voice_settings
|
458 |
+
adi=asm(text=text_to_narrate,model_id="eleven_multilingual_v2",**vps)
|
459 |
+
with open(afp,"wb")as f:
|
460 |
+
for c in adi:
|
461 |
+
if c:f.write(c)
|
462 |
+
logger.info(f"11L audio (stream): {afp}");return afp
|
463 |
+
except Exception as e:logger.error(f"11L audio error: {e}",exc_info=True);return None
|
464 |
+
|
465 |
+
# --- assemble_animatic_from_assets (Still contains crucial debug saves for blank video issue) ---
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
466 |
def assemble_animatic_from_assets(self, asset_data_list, overall_narration_path=None, output_filename="final_video.mp4", fps=24):
|
467 |
+
# (Keep the version with robust image processing, C-contiguous arrays, debug saves, and pix_fmt)
|
468 |
+
if not asset_data_list: logger.warning("No assets for animatic."); return None
|
469 |
+
processed_clips = []; narration_clip = None; final_clip = None
|
|
|
|
|
|
|
|
|
470 |
logger.info(f"Assembling from {len(asset_data_list)} assets. Frame: {self.video_frame_size}.")
|
471 |
|
472 |
for i, asset_info in enumerate(asset_data_list):
|
473 |
+
asset_path, asset_type, scene_dur = asset_info.get('path'), asset_info.get('type'), asset_info.get('duration', 4.5)
|
474 |
+
scene_num, key_action = asset_info.get('scene_num', i + 1), asset_info.get('key_action', '')
|
|
|
|
|
|
|
475 |
logger.info(f"S{scene_num}: Path='{asset_path}', Type='{asset_type}', Dur='{scene_dur}'s")
|
476 |
|
477 |
+
if not (asset_path and os.path.exists(asset_path)): logger.warning(f"S{scene_num}: Not found '{asset_path}'. Skip."); continue
|
478 |
+
if scene_dur <= 0: logger.warning(f"S{scene_num}: Invalid duration ({scene_dur}s). Skip."); continue
|
|
|
|
|
|
|
|
|
479 |
|
480 |
current_scene_mvpy_clip = None
|
481 |
try:
|
482 |
if asset_type == 'image':
|
483 |
+
pil_img = Image.open(asset_path); logger.debug(f"S{scene_num}: Loaded img. Mode:{pil_img.mode}, Size:{pil_img.size}")
|
|
|
484 |
img_rgba = pil_img.convert('RGBA') if pil_img.mode != 'RGBA' else pil_img.copy()
|
485 |
+
thumb = img_rgba.copy(); rf = Image.Resampling.LANCZOS if hasattr(Image.Resampling,'LANCZOS') else Image.BILINEAR; thumb.thumbnail(self.video_frame_size,rf)
|
486 |
+
cv_rgba = Image.new('RGBA',self.video_frame_size,(0,0,0,0)); xo,yo=(self.video_frame_size[0]-thumb.width)//2,(self.video_frame_size[1]-thumb.height)//2
|
487 |
+
cv_rgba.paste(thumb,(xo,yo),thumb)
|
488 |
+
final_rgb_pil = Image.new("RGB",self.video_frame_size,(0,0,0)); final_rgb_pil.paste(cv_rgba,mask=cv_rgba.split()[3])
|
489 |
+
dbg_path = os.path.join(self.output_dir,f"debug_PRE_NUMPY_S{scene_num}.png"); final_rgb_pil.save(dbg_path); logger.info(f"DEBUG: Saved PRE_NUMPY_S{scene_num} to {dbg_path}")
|
490 |
+
frame_np = np.array(final_rgb_pil,dtype=np.uint8);
|
491 |
+
if not frame_np.flags['C_CONTIGUOUS']: frame_np=np.ascontiguousarray(frame_np,dtype=np.uint8)
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
492 |
logger.debug(f"S{scene_num}: NumPy for MoviePy. Shape:{frame_np.shape}, DType:{frame_np.dtype}, C-Contig:{frame_np.flags['C_CONTIGUOUS']}")
|
493 |
+
if frame_np.size==0 or frame_np.ndim!=3 or frame_np.shape[2]!=3: logger.error(f"S{scene_num}: Invalid NumPy. Skip."); continue
|
494 |
+
clip_base = ImageClip(frame_np,transparent=False).set_duration(scene_dur)
|
495 |
+
mvpy_dbg_path=os.path.join(self.output_dir,f"debug_MOVIEPY_FRAME_S{scene_num}.png"); clip_base.save_frame(mvpy_dbg_path,t=0.1); logger.info(f"DEBUG: Saved MOVIEPY_FRAME_S{scene_num} to {mvpy_dbg_path}")
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
496 |
clip_fx = clip_base
|
497 |
+
try: es=random.uniform(1.03,1.08); clip_fx=clip_base.fx(vfx.resize,lambda t:1+(es-1)*(t/scene_dur) if scene_dur>0 else 1).set_position('center')
|
498 |
+
except Exception as e: logger.error(f"S{scene_num} Ken Burns error: {e}",exc_info=False)
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
499 |
current_scene_mvpy_clip = clip_fx
|
|
|
500 |
elif asset_type == 'video':
|
501 |
+
src_clip=None
|
502 |
try:
|
503 |
+
src_clip=VideoFileClip(asset_path,target_resolution=(self.video_frame_size[1],self.video_frame_size[0])if self.video_frame_size else None, audio=False)
|
504 |
+
tmp_clip=src_clip
|
505 |
+
if src_clip.duration!=scene_dur:
|
506 |
+
if src_clip.duration>scene_dur:tmp_clip=src_clip.subclip(0,scene_dur)
|
|
|
|
|
|
|
|
|
|
|
507 |
else:
|
508 |
+
if scene_dur/src_clip.duration > 1.5 and src_clip.duration>0.1:tmp_clip=src_clip.loop(duration=scene_dur)
|
509 |
+
else:tmp_clip=src_clip.set_duration(src_clip.duration);logger.info(f"S{scene_num} Video clip ({src_clip.duration:.2f}s) shorter than target ({scene_dur:.2f}s).")
|
510 |
+
current_scene_mvpy_clip=tmp_clip.set_duration(scene_dur)
|
511 |
+
if current_scene_mvpy_clip.size!=list(self.video_frame_size):current_scene_mvpy_clip=current_scene_mvpy_clip.resize(self.video_frame_size)
|
512 |
+
except Exception as e:logger.error(f"S{scene_num} Video load error '{asset_path}':{e}",exc_info=True);continue
|
|
|
|
|
|
|
|
|
|
|
|
|
513 |
finally:
|
514 |
+
if src_clip and src_clip is not current_scene_mvpy_clip and hasattr(src_clip,'close'):src_clip.close()
|
515 |
+
else: logger.warning(f"S{scene_num} Unknown asset type '{asset_type}'. Skip."); continue
|
516 |
+
|
|
|
|
|
|
|
517 |
if current_scene_mvpy_clip and key_action:
|
518 |
try:
|
519 |
+
to_dur=min(current_scene_mvpy_clip.duration-0.5,current_scene_mvpy_clip.duration*0.8)if current_scene_mvpy_clip.duration>0.5 else current_scene_mvpy_clip.duration
|
520 |
+
to_start=0.25
|
|
|
521 |
if to_dur > 0:
|
522 |
+
txt_c=TextClip(f"Scene {scene_num}\n{key_action}",fontsize=self.video_overlay_font_size,color=self.video_overlay_font_color,font=self.video_overlay_font,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(to_dur).set_start(to_start).set_position(('center',0.92),relative=True)
|
523 |
+
current_scene_mvpy_clip=CompositeVideoClip([current_scene_mvpy_clip,txt_c],size=self.video_frame_size,use_bgclip=True)
|
524 |
+
else: logger.warning(f"S{scene_num}: Text overlay duration is zero. Skip text.")
|
525 |
+
except Exception as e:logger.error(f"S{scene_num} TextClip error:{e}. No text.",exc_info=True)
|
526 |
+
if current_scene_mvpy_clip:processed_clips.append(current_scene_mvpy_clip);logger.info(f"S{scene_num} Processed. Dur:{current_scene_mvpy_clip.duration:.2f}s.")
|
527 |
+
except Exception as e:logger.error(f"MAJOR Error S{scene_num} ({asset_path}):{e}",exc_info=True)
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
528 |
finally:
|
529 |
+
if current_scene_mvpy_clip and hasattr(current_scene_mvpy_clip,'close'):
|
530 |
+
try: current_scene_mvpy_clip.close()
|
531 |
+
except: pass
|
|
|
|
|
|
|
|
|
|
|
|
|
532 |
|
533 |
+
if not processed_clips:logger.warning("No clips processed. Abort.");return None
|
534 |
+
td=0.75
|
535 |
try:
|
536 |
+
logger.info(f"Concatenating {len(processed_clips)} clips.");
|
537 |
+
if len(processed_clips)>1:final_clip=concatenate_videoclips(processed_clips,padding=-td if td>0 else 0,method="compose")
|
538 |
+
elif processed_clips:final_clip=processed_clips[0]
|
539 |
+
if not final_clip:logger.error("Concatenation failed.");return None
|
|
|
|
|
|
|
|
|
540 |
logger.info(f"Concatenated dur:{final_clip.duration:.2f}s")
|
541 |
+
if td>0 and final_clip.duration>0:
|
542 |
+
if final_clip.duration>td*2:final_clip=final_clip.fx(vfx.fadein,td).fx(vfx.fadeout,td)
|
543 |
+
else:final_clip=final_clip.fx(vfx.fadein,min(td,final_clip.duration/2.0))
|
544 |
+
if overall_narration_path and os.path.exists(overall_narration_path) and final_clip.duration>0:
|
545 |
+
try:narration_clip=AudioFileClip(overall_narration_path);final_clip=final_clip.set_audio(narration_clip);logger.info("Narration added.")
|
546 |
+
except Exception as e:logger.error(f"Narration add error:{e}",exc_info=True)
|
547 |
+
elif final_clip.duration<=0:logger.warning("Video no duration. No audio.")
|
548 |
+
if final_clip and final_clip.duration>0:
|
549 |
+
op=os.path.join(self.output_dir,output_filename);logger.info(f"Writing video:{op} (Dur:{final_clip.duration:.2f}s)")
|
550 |
+
final_clip.write_videofile(op,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"])
|
551 |
+
logger.info(f"Video created:{op}");return op
|
552 |
+
else:logger.error("Final clip invalid. No write.");return None
|
553 |
+
except Exception as e:logger.error(f"Video write error:{e}",exc_info=True);return None
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
554 |
finally:
|
555 |
logger.debug("Closing all MoviePy clips in `assemble_animatic_from_assets` finally block.")
|
556 |
all_clips_to_close = processed_clips + ([narration_clip] if narration_clip else []) + ([final_clip] if final_clip else [])
|
557 |
for clip_obj_to_close in all_clips_to_close:
|
558 |
if clip_obj_to_close and hasattr(clip_obj_to_close, 'close'):
|
559 |
+
try: clip_obj_to_close.close()
|
560 |
+
except Exception as e_close: logger.warning(f"Ignoring error while closing a clip: {type(clip_obj_to_close).__name__} - {e_close}")
|
|
|
|