Update core/visual_engine.py
Browse files- core/visual_engine.py +697 -229
core/visual_engine.py
CHANGED
@@ -1,16 +1,6 @@
|
|
1 |
-
# core/visual_engine.py
|
2 |
from PIL import Image, ImageDraw, ImageFont, ImageOps
|
3 |
import base64
|
4 |
-
|
5 |
-
# --- MONKEY PATCH ---
|
6 |
-
try:
|
7 |
-
if hasattr(Image, 'Resampling') and hasattr(Image.Resampling, 'LANCZOS'):
|
8 |
-
if not hasattr(Image, 'ANTIALIAS'): Image.ANTIALIAS = Image.Resampling.LANCZOS
|
9 |
-
elif hasattr(Image, 'LANCZOS'):
|
10 |
-
if not hasattr(Image, 'ANTIALIAS'): Image.ANTIALIAS = Image.LANCZOS
|
11 |
-
elif not hasattr(Image, 'ANTIALIAS'): print("WARNING: Pillow ANTIALIAS/Resampling issue.")
|
12 |
-
except Exception as e_mp: print(f"WARNING: ANTIALIAS patch error: {e_mp}")
|
13 |
-
|
14 |
from moviepy.editor import (ImageClip, VideoFileClip, concatenate_videoclips, TextClip,
|
15 |
CompositeVideoClip, AudioFileClip)
|
16 |
import moviepy.video.fx.all as vfx
|
@@ -27,16 +17,37 @@ import mimetypes
|
|
27 |
logger = logging.getLogger(__name__)
|
28 |
logger.setLevel(logging.INFO)
|
29 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
30 |
# --- SERVICE CLIENT IMPORTS ---
|
31 |
-
ELEVENLABS_CLIENT_IMPORTED = False
|
|
|
|
|
|
|
32 |
try:
|
33 |
from elevenlabs.client import ElevenLabs as ImportedElevenLabsClient
|
34 |
from elevenlabs import Voice as ImportedVoice, VoiceSettings as ImportedVoiceSettings
|
35 |
-
ElevenLabsAPIClient = ImportedElevenLabsClient
|
36 |
-
|
37 |
-
|
|
|
|
|
|
|
|
|
38 |
|
39 |
-
RUNWAYML_SDK_IMPORTED = False
|
|
|
40 |
try:
|
41 |
from runwayml import RunwayML as ImportedRunwayMLClient
|
42 |
RunwayMLAPIClient = ImportedRunwayMLClient
|
@@ -53,129 +64,241 @@ class VisualEngine:
|
|
53 |
self.output_dir = output_dir
|
54 |
os.makedirs(self.output_dir, exist_ok=True)
|
55 |
self.font_filename = "DejaVuSans-Bold.ttf"
|
56 |
-
font_paths_to_try = [
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
57 |
self.font_path_pil = next((p for p in font_paths_to_try if os.path.exists(p)), None)
|
58 |
-
self.font_size_pil = 20
|
|
|
|
|
59 |
self.video_overlay_font = 'DejaVu-Sans-Bold'
|
60 |
try:
|
61 |
-
|
62 |
-
|
63 |
-
|
64 |
-
|
65 |
-
|
66 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
67 |
self.video_frame_size = (1280, 720)
|
68 |
-
|
69 |
-
self.elevenlabs_api_key = None
|
70 |
-
|
71 |
-
|
72 |
-
|
73 |
-
|
74 |
-
|
75 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
76 |
if RUNWAYML_SDK_IMPORTED and RunwayMLAPIClient:
|
77 |
try:
|
78 |
-
if os.getenv("RUNWAYML_API_SECRET"):
|
79 |
-
|
80 |
-
|
|
|
|
|
|
|
81 |
logger.info("VisualEngine initialized.")
|
82 |
|
83 |
-
def set_openai_api_key(self,k):
|
84 |
-
|
85 |
-
self.
|
86 |
-
|
|
|
|
|
|
|
|
|
|
|
87 |
if api_key and ELEVENLABS_CLIENT_IMPORTED and ElevenLabsAPIClient:
|
88 |
-
try:
|
89 |
-
|
90 |
-
|
91 |
-
|
92 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
93 |
def set_runway_api_key(self, k):
|
94 |
self.runway_api_key = k
|
95 |
if k:
|
96 |
if RUNWAYML_SDK_IMPORTED and RunwayMLAPIClient:
|
97 |
if not self.runway_client:
|
98 |
try:
|
99 |
-
if not os.getenv("RUNWAYML_API_SECRET"):
|
100 |
-
|
101 |
-
|
102 |
-
|
103 |
-
|
104 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
105 |
|
106 |
def _image_to_data_uri(self, image_path):
|
107 |
try:
|
108 |
mime_type, _ = mimetypes.guess_type(image_path)
|
109 |
if not mime_type:
|
110 |
ext = os.path.splitext(image_path)[1].lower()
|
111 |
-
if ext == ".png":
|
112 |
-
|
113 |
-
|
114 |
-
|
|
|
|
|
|
|
|
|
|
|
115 |
data_uri = f"data:{mime_type};base64,{encoded_string}"
|
116 |
-
logger.debug(f"Data URI for {image_path} (first 100): {data_uri[:100]}")
|
117 |
-
|
|
|
|
|
|
|
118 |
|
119 |
def _map_resolution_to_runway_ratio(self, width, height):
|
120 |
-
ratio_str = f"{width}:{height}"
|
121 |
-
|
122 |
-
|
|
|
|
|
|
|
123 |
|
124 |
-
def _get_text_dimensions(self,text_content,font_obj):
|
125 |
default_char_height = getattr(font_obj, 'size', self.font_size_pil)
|
126 |
-
if not text_content:
|
|
|
127 |
try:
|
128 |
-
if hasattr(font_obj,'getbbox'):
|
129 |
-
|
130 |
-
|
131 |
-
|
132 |
-
|
133 |
-
|
134 |
-
|
135 |
-
|
136 |
-
|
137 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
138 |
for word_idx, word in enumerate(words):
|
139 |
prospective_line_addition = word + (" " if word_idx < len(words) - 1 else "")
|
140 |
test_line = current_line + prospective_line_addition
|
141 |
current_line_width, _ = self._get_text_dimensions(test_line, self.font)
|
142 |
-
if current_line_width == 0 and test_line.strip():
|
143 |
-
|
|
|
|
|
144 |
else:
|
145 |
-
if current_line.strip():
|
|
|
146 |
current_line = prospective_line_addition
|
147 |
-
if current_line.strip():
|
|
|
148 |
if not lines and text_description:
|
149 |
avg_char_width, _ = self._get_text_dimensions("W", self.font)
|
150 |
-
if avg_char_width == 0:
|
|
|
151 |
chars_per_line = int(max_w / avg_char_width) if avg_char_width > 0 else 20
|
152 |
lines.append(text_description[:chars_per_line] + ("..." if len(text_description) > chars_per_line else ""))
|
153 |
-
elif not lines:
|
154 |
-
|
155 |
-
|
156 |
-
if
|
157 |
-
|
|
|
|
|
|
|
|
|
158 |
for i in range(max_lines_to_display):
|
159 |
-
line_content=lines[i]
|
160 |
-
|
161 |
-
|
162 |
-
|
163 |
-
|
164 |
-
|
165 |
-
|
166 |
-
|
167 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
168 |
break
|
169 |
-
filepath=os.path.join(self.output_dir,filename)
|
170 |
-
try:
|
171 |
-
|
|
|
|
|
|
|
|
|
172 |
|
173 |
def _search_pexels_image(self, query, output_filename_base):
|
174 |
# <<< CORRECTED METHOD >>>
|
175 |
-
if not self.USE_PEXELS or not self.pexels_api_key:
|
|
|
176 |
headers = {"Authorization": self.pexels_api_key}
|
177 |
params = {"query": query, "per_page": 1, "orientation": "landscape", "size": "large2x"}
|
178 |
-
pexels_filename = output_filename_base.replace(".png", f"_pexels_{random.randint(1000,9999)}.jpg")
|
|
|
179 |
filepath = os.path.join(self.output_dir, pexels_filename)
|
180 |
try:
|
181 |
logger.info(f"Pexels search: '{query}'")
|
@@ -196,7 +319,7 @@ class VisualEngine:
|
|
196 |
return filepath
|
197 |
else:
|
198 |
logger.info(f"No photos found on Pexels for query: '{effective_query}'")
|
199 |
-
return None
|
200 |
except requests.exceptions.RequestException as e_req:
|
201 |
logger.error(f"Pexels request error for query '{query}': {e_req}", exc_info=True)
|
202 |
except json.JSONDecodeError as e_json:
|
@@ -205,196 +328,541 @@ class VisualEngine:
|
|
205 |
logger.error(f"Pexels image save error for query '{query}': {e_io}", exc_info=True)
|
206 |
except Exception as e:
|
207 |
logger.error(f"Unexpected Pexels error for query '{query}': {e}", exc_info=True)
|
208 |
-
return None
|
209 |
|
210 |
-
def _generate_video_clip_with_runwayml(self, text_prompt_for_motion, input_image_path,
|
211 |
-
|
212 |
-
if not
|
|
|
|
|
|
|
|
|
|
|
213 |
image_data_uri = self._image_to_data_uri(input_image_path)
|
214 |
-
if not image_data_uri:
|
|
|
215 |
runway_duration = 10 if target_duration_seconds > 7 else 5
|
216 |
-
runway_ratio_str = self._map_resolution_to_runway_ratio(
|
217 |
-
|
|
|
|
|
|
|
|
|
218 |
output_video_filepath = os.path.join(self.output_dir, output_video_filename)
|
219 |
-
logger.info(f"Runway Gen-4 task: motion='{text_prompt_for_motion[:100]}...',
|
|
|
220 |
try:
|
221 |
-
task = self.runway_client.image_to_video.create(
|
|
|
|
|
|
|
|
|
|
|
|
|
222 |
logger.info(f"Runway Gen-4 task ID: {task.id}. Polling...")
|
223 |
-
poll_interval=10
|
|
|
224 |
for _ in range(max_polls):
|
225 |
-
time.sleep(poll_interval)
|
|
|
226 |
logger.info(f"Runway task {task.id} status: {task_details.status}")
|
227 |
if task_details.status == 'SUCCEEDED':
|
228 |
-
output_url =
|
229 |
-
|
230 |
-
|
231 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
232 |
logger.info(f"Runway task {task.id} SUCCEEDED. Downloading from: {output_url}")
|
233 |
-
video_response = requests.get(output_url, stream=True, timeout=300)
|
|
|
234 |
with open(output_video_filepath, 'wb') as f:
|
235 |
-
for chunk in video_response.iter_content(chunk_size=8192):
|
236 |
-
|
|
|
|
|
237 |
elif task_details.status in ['FAILED', 'ABORTED']:
|
238 |
-
em =
|
239 |
-
|
240 |
-
|
241 |
-
|
242 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
243 |
|
244 |
def _create_placeholder_video_content(self, td, fn, dur=4, sz=None):
|
245 |
-
if sz is None:
|
246 |
-
|
247 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
248 |
finally:
|
249 |
-
if tc and hasattr(tc, 'close'):
|
|
|
250 |
|
251 |
-
def generate_scene_asset(
|
252 |
-
|
253 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
254 |
base_name, _ = os.path.splitext(scene_identifier_filename_base)
|
255 |
-
asset_info = {
|
|
|
|
|
|
|
|
|
|
|
|
|
256 |
input_image_for_runway_path = None
|
257 |
base_image_filename = base_name + ("_base_for_video.png" if generate_as_video_clip else ".png")
|
258 |
base_image_filepath = os.path.join(self.output_dir, base_image_filename)
|
259 |
-
|
260 |
if self.USE_AI_IMAGE_GENERATION and self.openai_api_key:
|
261 |
-
max_r
|
262 |
for att_n in range(max_r):
|
263 |
-
try:
|
264 |
-
|
265 |
-
|
266 |
-
|
267 |
-
|
268 |
-
|
269 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
270 |
if asset_info['error'] and self.USE_PEXELS:
|
271 |
-
logger.info("Trying Pexels for base img.")
|
272 |
-
|
273 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
274 |
|
275 |
if asset_info['error']:
|
276 |
-
logger.warning("Base img (DALL-E/Pexels) failed. Using placeholder.")
|
277 |
-
|
278 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
279 |
|
280 |
if generate_as_video_clip:
|
281 |
-
if not input_image_for_runway_path:
|
|
|
|
|
|
|
|
|
|
|
282 |
if self.USE_RUNWAYML:
|
283 |
logger.info(f"Runway Gen-4 video for {base_name} using base: {input_image_for_runway_path}")
|
284 |
-
video_path=self._generate_video_clip_with_runwayml(
|
285 |
-
|
286 |
-
|
287 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
288 |
return asset_info
|
289 |
|
290 |
def generate_narration_audio(self, text_to_narrate, output_filename="narration_overall.mp3"):
|
291 |
-
if not self.USE_ELEVENLABS or not self.elevenlabs_client or not text_to_narrate:
|
292 |
-
|
293 |
-
|
294 |
-
|
295 |
-
|
296 |
-
|
297 |
-
|
298 |
-
|
299 |
-
|
300 |
-
|
301 |
-
|
302 |
-
|
303 |
-
|
304 |
-
|
305 |
-
|
306 |
-
|
307 |
-
|
308 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
309 |
|
310 |
def assemble_animatic_from_assets(self, asset_data_list, overall_narration_path=None, output_filename="final_video.mp4", fps=24):
|
311 |
-
if not asset_data_list:
|
312 |
-
|
|
|
|
|
|
|
|
|
|
|
313 |
logger.info(f"Assembling from {len(asset_data_list)} assets. Frame: {self.video_frame_size}.")
|
|
|
314 |
for i, asset_info in enumerate(asset_data_list):
|
315 |
-
asset_path
|
316 |
-
|
|
|
|
|
|
|
317 |
logger.info(f"S{scene_num}: Path='{asset_path}', Type='{asset_type}', Dur='{scene_dur}'s")
|
318 |
-
|
319 |
-
if
|
|
|
|
|
|
|
|
|
|
|
|
|
320 |
current_scene_mvpy_clip = None
|
321 |
try:
|
322 |
if asset_type == 'image':
|
323 |
-
pil_img = Image.open(asset_path)
|
|
|
324 |
img_rgba = pil_img.convert('RGBA') if pil_img.mode != 'RGBA' else pil_img.copy()
|
325 |
-
thumb = img_rgba.copy()
|
326 |
-
|
327 |
-
|
328 |
-
|
329 |
-
|
330 |
-
|
331 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
332 |
logger.debug(f"S{scene_num}: NumPy for MoviePy. Shape:{frame_np.shape}, DType:{frame_np.dtype}, C-Contig:{frame_np.flags['C_CONTIGUOUS']}")
|
333 |
-
|
334 |
-
|
335 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
336 |
clip_fx = clip_base
|
337 |
-
try:
|
338 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
339 |
current_scene_mvpy_clip = clip_fx
|
|
|
340 |
elif asset_type == 'video':
|
341 |
-
src_clip=None
|
342 |
try:
|
343 |
-
src_clip=VideoFileClip(
|
344 |
-
|
345 |
-
|
346 |
-
|
|
|
|
|
|
|
|
|
|
|
347 |
else:
|
348 |
-
if scene_dur/src_clip.duration > 1.5 and src_clip.duration>0.1:
|
349 |
-
|
350 |
-
|
351 |
-
|
352 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
353 |
finally:
|
354 |
-
if src_clip and src_clip is not current_scene_mvpy_clip and hasattr(src_clip,'close'):
|
355 |
-
|
356 |
-
|
|
|
|
|
|
|
357 |
if current_scene_mvpy_clip and key_action:
|
358 |
try:
|
359 |
-
to_dur=min(current_scene_mvpy_clip.duration-0.5,
|
360 |
-
|
|
|
361 |
if to_dur > 0:
|
362 |
-
txt_c=TextClip(
|
363 |
-
|
364 |
-
|
365 |
-
|
366 |
-
|
367 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
368 |
finally:
|
369 |
-
if current_scene_mvpy_clip and hasattr(current_scene_mvpy_clip,'close'):
|
370 |
-
try:
|
371 |
-
|
|
|
|
|
372 |
|
373 |
-
if not processed_clips:
|
374 |
-
|
|
|
|
|
|
|
375 |
try:
|
376 |
-
logger.info(f"Concatenating {len(processed_clips)} clips.")
|
377 |
-
if len(processed_clips)>1:
|
378 |
-
|
379 |
-
|
|
|
|
|
|
|
|
|
380 |
logger.info(f"Concatenated dur:{final_clip.duration:.2f}s")
|
381 |
-
if td>0 and final_clip.duration>0:
|
382 |
-
if final_clip.duration>td*2:
|
383 |
-
|
384 |
-
|
385 |
-
|
386 |
-
|
387 |
-
|
388 |
-
|
389 |
-
|
390 |
-
|
391 |
-
|
392 |
-
|
393 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
394 |
finally:
|
395 |
logger.debug("Closing all MoviePy clips in `assemble_animatic_from_assets` finally block.")
|
396 |
all_clips_to_close = processed_clips + ([narration_clip] if narration_clip else []) + ([final_clip] if final_clip else [])
|
397 |
for clip_obj_to_close in all_clips_to_close:
|
398 |
if clip_obj_to_close and hasattr(clip_obj_to_close, 'close'):
|
399 |
-
try:
|
400 |
-
|
|
|
|
|
|
|
|
1 |
from PIL import Image, ImageDraw, ImageFont, ImageOps
|
2 |
import base64
|
3 |
+
import json
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
4 |
from moviepy.editor import (ImageClip, VideoFileClip, concatenate_videoclips, TextClip,
|
5 |
CompositeVideoClip, AudioFileClip)
|
6 |
import moviepy.video.fx.all as vfx
|
|
|
17 |
logger = logging.getLogger(__name__)
|
18 |
logger.setLevel(logging.INFO)
|
19 |
|
20 |
+
# --- MONKEY PATCH ---
|
21 |
+
try:
|
22 |
+
if hasattr(Image, 'Resampling') and hasattr(Image.Resampling, 'LANCZOS'):
|
23 |
+
if not hasattr(Image, 'ANTIALIAS'):
|
24 |
+
Image.ANTIALIAS = Image.Resampling.LANCZOS
|
25 |
+
elif hasattr(Image, 'LANCZOS'):
|
26 |
+
if not hasattr(Image, 'ANTIALIAS'):
|
27 |
+
Image.ANTIALIAS = Image.LANCZOS
|
28 |
+
elif not hasattr(Image, 'ANTIALIAS'):
|
29 |
+
print("WARNING: Pillow ANTIALIAS/Resampling issue.")
|
30 |
+
except Exception as e_mp:
|
31 |
+
print(f"WARNING: ANTIALIAS patch error: {e_mp}")
|
32 |
+
|
33 |
# --- 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
|
41 |
+
ElevenLabsAPIClient = ImportedElevenLabsClient
|
42 |
+
Voice = ImportedVoice
|
43 |
+
VoiceSettings = ImportedVoiceSettings
|
44 |
+
ELEVENLABS_CLIENT_IMPORTED = True
|
45 |
+
logger.info("ElevenLabs client components imported.")
|
46 |
+
except Exception as e_eleven:
|
47 |
+
logger.warning(f"ElevenLabs client import failed: {e_eleven}. Audio disabled.")
|
48 |
|
49 |
+
RUNWAYML_SDK_IMPORTED = False
|
50 |
+
RunwayMLAPIClient = None
|
51 |
try:
|
52 |
from runwayml import RunwayML as ImportedRunwayMLClient
|
53 |
RunwayMLAPIClient = ImportedRunwayMLClient
|
|
|
64 |
self.output_dir = output_dir
|
65 |
os.makedirs(self.output_dir, exist_ok=True)
|
66 |
self.font_filename = "DejaVuSans-Bold.ttf"
|
67 |
+
font_paths_to_try = [
|
68 |
+
self.font_filename,
|
69 |
+
"/usr/share/fonts/truetype/dejavu/DejaVuSans-Bold.ttf",
|
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.font_path_pil = next((p for p in font_paths_to_try if os.path.exists(p)), None)
|
76 |
+
self.font_size_pil = 20
|
77 |
+
self.video_overlay_font_size = 30
|
78 |
+
self.video_overlay_font_color = 'white'
|
79 |
self.video_overlay_font = 'DejaVu-Sans-Bold'
|
80 |
try:
|
81 |
+
if self.font_path_pil:
|
82 |
+
self.font = ImageFont.truetype(self.font_path_pil, self.font_size_pil)
|
83 |
+
logger.info(f"Pillow font: {self.font_path_pil}.")
|
84 |
+
else:
|
85 |
+
self.font = ImageFont.load_default()
|
86 |
+
logger.warning("Default Pillow font.")
|
87 |
+
self.font_size_pil = 10
|
88 |
+
except IOError as e_font:
|
89 |
+
logger.error(f"Pillow font IOError: {e_font}. Default.")
|
90 |
+
self.font = ImageFont.load_default()
|
91 |
+
self.font_size_pil = 10
|
92 |
+
|
93 |
+
self.openai_api_key = None
|
94 |
+
self.USE_AI_IMAGE_GENERATION = False
|
95 |
+
self.dalle_model = "dall-e-3"
|
96 |
+
self.image_size_dalle3 = "1792x1024"
|
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 |
+
stability=0.60,
|
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.USE_PEXELS = False
|
115 |
+
|
116 |
+
self.runway_api_key = None
|
117 |
+
self.USE_RUNWAYML = False
|
118 |
+
self.runway_client = None
|
119 |
if RUNWAYML_SDK_IMPORTED and RunwayMLAPIClient:
|
120 |
try:
|
121 |
+
if os.getenv("RUNWAYML_API_SECRET"):
|
122 |
+
self.runway_client = RunwayMLAPIClient()
|
123 |
+
logger.info("RunwayML Client initialized using RUNWAYML_API_SECRET env var.")
|
124 |
+
except Exception as e_runway_init:
|
125 |
+
logger.error(f"Failed to initialize RunwayML client during __init__: {e_runway_init}", exc_info=True)
|
126 |
+
|
127 |
logger.info("VisualEngine initialized.")
|
128 |
|
129 |
+
def set_openai_api_key(self, k):
|
130 |
+
self.openai_api_key = k
|
131 |
+
self.USE_AI_IMAGE_GENERATION = bool(k)
|
132 |
+
logger.info(f"DALL-E ({self.dalle_model}) {'Ready.' if k else 'Disabled.'}")
|
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 Init'} (Voice ID: {self.elevenlabs_voice_id}).")
|
143 |
+
except Exception as e:
|
144 |
+
logger.error(f"ElevenLabs client init error: {e}. Disabled.", exc_info=True)
|
145 |
+
self.USE_ELEVENLABS = False
|
146 |
+
else:
|
147 |
+
self.USE_ELEVENLABS = False
|
148 |
+
logger.info("ElevenLabs Disabled (no key or SDK issue).")
|
149 |
+
|
150 |
+
def set_pexels_api_key(self, k):
|
151 |
+
self.pexels_api_key = k
|
152 |
+
self.USE_PEXELS = bool(k)
|
153 |
+
logger.info(f"Pexels Search {'Ready.' if k else 'Disabled.'}")
|
154 |
+
|
155 |
def set_runway_api_key(self, k):
|
156 |
self.runway_api_key = k
|
157 |
if k:
|
158 |
if RUNWAYML_SDK_IMPORTED and RunwayMLAPIClient:
|
159 |
if not self.runway_client:
|
160 |
try:
|
161 |
+
if not os.getenv("RUNWAYML_API_SECRET"):
|
162 |
+
os.environ["RUNWAYML_API_SECRET"] = k
|
163 |
+
logger.info("Setting RUNWAYML_API_SECRET env var from provided key.")
|
164 |
+
self.runway_client = RunwayMLAPIClient()
|
165 |
+
self.USE_RUNWAYML = True
|
166 |
+
logger.info("RunwayML Client initialized successfully via set_runway_api_key.")
|
167 |
+
except Exception as e_client_init:
|
168 |
+
logger.error(f"RunwayML Client init failed in set_runway_api_key: {e_client_init}", exc_info=True)
|
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 set, but integration requires SDK.")
|
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 |
+
if ext == ".png":
|
186 |
+
mime_type = "image/png"
|
187 |
+
elif ext in [".jpg", ".jpeg"]:
|
188 |
+
mime_type = "image/jpeg"
|
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"Data URI for {image_path} (first 100): {data_uri[:100]}")
|
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 |
+
supported_ratios = ["1280:720", "720:1280", "1104:832", "832:1104", "960:960", "1584:672"]
|
204 |
+
if ratio_str in supported_ratios:
|
205 |
+
return ratio_str
|
206 |
+
logger.warning(f"Res {ratio_str} not directly Gen-4 supported. Default 1280:720.")
|
207 |
+
return "1280:720"
|
208 |
|
209 |
+
def _get_text_dimensions(self, text_content, font_obj):
|
210 |
default_char_height = getattr(font_obj, 'size', self.font_size_pil)
|
211 |
+
if not text_content:
|
212 |
+
return 0, default_char_height
|
213 |
try:
|
214 |
+
if hasattr(font_obj, 'getbbox'):
|
215 |
+
bbox = font_obj.getbbox(text_content)
|
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(font_obj, 'getsize'):
|
220 |
+
w, h = font_obj.getsize(text_content)
|
221 |
+
return w, h if h > 0 else default_char_height
|
222 |
+
else:
|
223 |
+
return int(len(text_content) * default_char_height * 0.6), int(default_char_height * 1.2)
|
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 |
+
if size is None:
|
230 |
+
size = self.video_frame_size
|
231 |
+
img = Image.new('RGB', size, color=(20, 20, 40))
|
232 |
+
d = ImageDraw.Draw(img)
|
233 |
+
padding = 25
|
234 |
+
max_w = size[0] - (2 * padding)
|
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 |
prospective_line_addition = word + (" " if word_idx < len(words) - 1 else "")
|
242 |
test_line = current_line + prospective_line_addition
|
243 |
current_line_width, _ = self._get_text_dimensions(test_line, self.font)
|
244 |
+
if current_line_width == 0 and test_line.strip():
|
245 |
+
current_line_width = len(test_line) * (self.font_size_pil * 0.6)
|
246 |
+
if current_line_width <= max_w:
|
247 |
+
current_line = test_line
|
248 |
else:
|
249 |
+
if current_line.strip():
|
250 |
+
lines.append(current_line.strip())
|
251 |
current_line = prospective_line_addition
|
252 |
+
if current_line.strip():
|
253 |
+
lines.append(current_line.strip())
|
254 |
if not lines and text_description:
|
255 |
avg_char_width, _ = self._get_text_dimensions("W", self.font)
|
256 |
+
if avg_char_width == 0:
|
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 |
+
lines.append("(Placeholder Error)")
|
262 |
+
_, single_line_h = self._get_text_dimensions("Ay", self.font)
|
263 |
+
single_line_h = single_line_h if single_line_h > 0 else self.font_size_pil + 2
|
264 |
+
max_lines_to_display = min(len(lines), (size[1] - (2 * padding)) // (single_line_h + 2)) if single_line_h > 0 else 1
|
265 |
+
if max_lines_to_display <= 0:
|
266 |
+
max_lines_to_display = 1
|
267 |
+
y_text_start = padding + (size[1] - (2 * padding) - max_lines_to_display * (single_line_h + 2)) / 2.0
|
268 |
+
y_text = y_text_start
|
269 |
for i in range(max_lines_to_display):
|
270 |
+
line_content = lines[i]
|
271 |
+
line_w, _ = self._get_text_dimensions(line_content, self.font)
|
272 |
+
if line_w == 0 and line_content.strip():
|
273 |
+
line_w = len(line_content) * (self.font_size_pil * 0.6)
|
274 |
+
x_text = (size[0] - line_w) / 2.0
|
275 |
+
try:
|
276 |
+
d.text((x_text, y_text), line_content, font=self.font, fill=(200, 200, 180))
|
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 |
+
img.save(filepath)
|
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 |
+
pexels_filename = output_filename_base.replace(".png", f"_pexels_{random.randint(1000,9999)}.jpg")\
|
301 |
+
.replace(".mp4", f"_pexels_{random.randint(1000,9999)}.jpg")
|
302 |
filepath = os.path.join(self.output_dir, pexels_filename)
|
303 |
try:
|
304 |
logger.info(f"Pexels search: '{query}'")
|
|
|
319 |
return filepath
|
320 |
else:
|
321 |
logger.info(f"No photos found on Pexels for query: '{effective_query}'")
|
322 |
+
return None
|
323 |
except requests.exceptions.RequestException as e_req:
|
324 |
logger.error(f"Pexels request error for query '{query}': {e_req}", exc_info=True)
|
325 |
except json.JSONDecodeError as e_json:
|
|
|
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 needs input image. Path invalid: {input_image_path}")
|
340 |
+
return None
|
341 |
image_data_uri = self._image_to_data_uri(input_image_path)
|
342 |
+
if not image_data_uri:
|
343 |
+
return None
|
344 |
runway_duration = 10 if target_duration_seconds > 7 else 5
|
345 |
+
runway_ratio_str = self._map_resolution_to_runway_ratio(
|
346 |
+
self.video_frame_size[0], self.video_frame_size[1]
|
347 |
+
)
|
348 |
+
output_video_filename = scene_identifier_filename_base.replace(
|
349 |
+
".png", f"_runway_gen4_d{runway_duration}s.mp4"
|
350 |
+
)
|
351 |
output_video_filepath = os.path.join(self.output_dir, output_video_filename)
|
352 |
+
logger.info(f"Runway Gen-4 task: motion='{text_prompt_for_motion[:100]}...', "
|
353 |
+
f"img='{os.path.basename(input_image_path)}', dur={runway_duration}s, ratio='{runway_ratio_str}'")
|
354 |
try:
|
355 |
+
task = self.runway_client.image_to_video.create(
|
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 |
logger.info(f"Runway Gen-4 task ID: {task.id}. Polling...")
|
363 |
+
poll_interval = 10
|
364 |
+
max_polls = 36
|
365 |
for _ in range(max_polls):
|
366 |
+
time.sleep(poll_interval)
|
367 |
+
task_details = self.runway_client.tasks.retrieve(id=task.id)
|
368 |
logger.info(f"Runway task {task.id} status: {task_details.status}")
|
369 |
if task_details.status == 'SUCCEEDED':
|
370 |
+
output_url = (
|
371 |
+
getattr(getattr(task_details, 'output', None), 'url', None)
|
372 |
+
or (
|
373 |
+
getattr(task_details, 'artifacts', None)
|
374 |
+
and task_details.artifacts[0].url
|
375 |
+
if task_details.artifacts and hasattr(task_details.artifacts[0], 'url')
|
376 |
+
else None
|
377 |
+
)
|
378 |
+
or (
|
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 |
logger.info(f"Runway task {task.id} SUCCEEDED. Downloading from: {output_url}")
|
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 |
+
f.write(chunk)
|
397 |
+
logger.info(f"Runway Gen-4 video saved: {output_video_filepath}")
|
398 |
+
return output_video_filepath
|
399 |
elif task_details.status in ['FAILED', 'ABORTED']:
|
400 |
+
em = (
|
401 |
+
getattr(task_details, 'error_message', None)
|
402 |
+
or getattr(getattr(task_details, 'output', None), 'error', "Unknown error")
|
403 |
+
)
|
404 |
+
logger.error(f"Runway task {task.id} status: {task_details.status}. Error: {em}")
|
405 |
+
return None
|
406 |
+
logger.warning(f"Runway task {task.id} timed out.")
|
407 |
+
return None
|
408 |
+
except AttributeError as ae:
|
409 |
+
logger.error(f"RunwayML SDK AttributeError: {ae}. SDK/methods might differ.", exc_info=True)
|
410 |
+
return None
|
411 |
+
except Exception as e:
|
412 |
+
logger.error(f"Runway Gen-4 API error: {e}", exc_info=True)
|
413 |
+
return None
|
414 |
|
415 |
def _create_placeholder_video_content(self, td, fn, dur=4, sz=None):
|
416 |
+
if sz is None:
|
417 |
+
sz = self.video_frame_size
|
418 |
+
fp = os.path.join(self.output_dir, fn)
|
419 |
+
tc = None
|
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 |
+
tc.close()
|
439 |
|
440 |
+
def generate_scene_asset(
|
441 |
+
self,
|
442 |
+
image_generation_prompt_text,
|
443 |
+
motion_prompt_text_for_video,
|
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 |
+
max_r = 2
|
463 |
for att_n in range(max_r):
|
464 |
+
try:
|
465 |
+
logger.info(f"Att {att_n+1} DALL-E (base img): {image_generation_prompt_text[:70]}...")
|
466 |
+
cl = openai.OpenAI(api_key=self.openai_api_key, timeout=90.0)
|
467 |
+
r = cl.images.generate(
|
468 |
+
model=self.dalle_model,
|
469 |
+
prompt=image_generation_prompt_text,
|
470 |
+
n=1,
|
471 |
+
size=self.image_size_dalle3,
|
472 |
+
quality="hd",
|
473 |
+
response_format="url",
|
474 |
+
style="vivid"
|
475 |
+
)
|
476 |
+
iu = r.data[0].url
|
477 |
+
rp = getattr(r.data[0], 'revised_prompt', None)
|
478 |
+
if rp:
|
479 |
+
logger.info(f"DALL-E revised: {rp[:70]}...")
|
480 |
+
ir = requests.get(iu, timeout=120)
|
481 |
+
ir.raise_for_status()
|
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 |
+
asset_info['error'] = True
|
543 |
+
asset_info['error_message'] = (asset_info.get('error_message', "") + " Base img miss, Runway abort.").strip()
|
544 |
+
asset_info['type'] = 'none'
|
545 |
+
return asset_info
|
546 |
if self.USE_RUNWAYML:
|
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 |
+
if not self.USE_ELEVENLABS or not self.elevenlabs_client or not text_to_narrate:
|
587 |
+
logger.info("11L skip.")
|
588 |
+
return None
|
589 |
+
|
590 |
+
afp = os.path.join(self.output_dir, output_filename)
|
591 |
+
|
592 |
+
try:
|
593 |
+
logger.info(f"11L audio (Voice:{self.elevenlabs_voice_id}): {text_to_narrate[:70]}...")
|
594 |
+
asm = None
|
595 |
+
|
596 |
+
# Determine which ElevenLabs streaming/non-streaming method to use
|
597 |
+
if hasattr(self.elevenlabs_client, 'text_to_speech') and \
|
598 |
+
hasattr(self.elevenlabs_client.text_to_speech, 'stream'):
|
599 |
+
asm = self.elevenlabs_client.text_to_speech.stream
|
600 |
+
logger.info("Using 11L .text_to_speech.stream()")
|
601 |
+
|
602 |
+
elif hasattr(self.elevenlabs_client, 'generate_stream'):
|
603 |
+
asm = self.elevenlabs_client.generate_stream
|
604 |
+
logger.info("Using 11L .generate_stream()")
|
605 |
+
|
606 |
+
elif hasattr(self.elevenlabs_client, 'generate'):
|
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 |
+
if not asset_data_list:
|
663 |
+
logger.warning("No assets for animatic.")
|
664 |
+
return None
|
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 |
+
asset_type = asset_info.get('type')
|
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 |
+
logger.warning(f"S{scene_num}: Not found '{asset_path}'. Skip.")
|
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 |
+
rf = Image.Resampling.LANCZOS if hasattr(Image.Resampling, 'LANCZOS') else Image.BILINEAR
|
694 |
+
thumb.thumbnail(self.video_frame_size, rf)
|
695 |
+
|
696 |
+
cv_rgba = Image.new('RGBA', self.video_frame_size, (0, 0, 0, 0))
|
697 |
+
xo = (self.video_frame_size[0] - thumb.width) // 2
|
698 |
+
yo = (self.video_frame_size[1] - thumb.height) // 2
|
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 |
+
if frame_np.size == 0 or frame_np.ndim != 3 or frame_np.shape[2] != 3:
|
713 |
+
logger.error(f"S{scene_num}: Invalid NumPy. Skip.")
|
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 |
+
es = random.uniform(1.03, 1.08)
|
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 = None
|
735 |
try:
|
736 |
+
src_clip = VideoFileClip(
|
737 |
+
asset_path,
|
738 |
+
target_resolution=(self.video_frame_size[1], self.video_frame_size[0]) if self.video_frame_size else None,
|
739 |
+
audio=False
|
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 / src_clip.duration > 1.5 and src_clip.duration > 0.1:
|
747 |
+
tmp_clip = src_clip.loop(duration=scene_dur)
|
748 |
+
else:
|
749 |
+
tmp_clip = src_clip.set_duration(src_clip.duration)
|
750 |
+
logger.info(f"S{scene_num} Video clip ({src_clip.duration:.2f}s) shorter than target ({scene_dur:.2f}s).")
|
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, 'close'):
|
759 |
+
src_clip.close()
|
760 |
+
else:
|
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 = min(current_scene_mvpy_clip.duration - 0.5,
|
767 |
+
current_scene_mvpy_clip.duration * 0.8) if current_scene_mvpy_clip.duration > 0.5 else current_scene_mvpy_clip.duration
|
768 |
+
to_start = 0.25
|
769 |
if to_dur > 0:
|
770 |
+
txt_c = TextClip(
|
771 |
+
f"Scene {scene_num}\n{key_action}",
|
772 |
+
fontsize=self.video_overlay_font_size,
|
773 |
+
color=self.video_overlay_font_color,
|
774 |
+
font=self.video_overlay_font,
|
775 |
+
bg_color='rgba(10,10,20,0.7)',
|
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, 'close'):
|
800 |
+
try:
|
801 |
+
current_scene_mvpy_clip.close()
|
802 |
+
except Exception:
|
803 |
+
pass
|
804 |
|
805 |
+
if not processed_clips:
|
806 |
+
logger.warning("No clips processed. Abort.")
|
807 |
+
return None
|
808 |
+
|
809 |
+
td = 0.75
|
810 |
try:
|
811 |
+
logger.info(f"Concatenating {len(processed_clips)} clips.")
|
812 |
+
if len(processed_clips) > 1:
|
813 |
+
final_clip = concatenate_videoclips(processed_clips, padding=-td if td > 0 else 0, method="compose")
|
814 |
+
elif processed_clips:
|
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 > 0 and final_clip.duration > 0:
|
821 |
+
if final_clip.duration > td * 2:
|
822 |
+
final_clip = final_clip.fx(vfx.fadein, td).fx(vfx.fadeout, td)
|
823 |
+
else:
|
824 |
+
final_clip = final_clip.fx(vfx.fadein, min(td, final_clip.duration / 2.0))
|
825 |
+
if overall_narration_path and os.path.exists(overall_narration_path) and final_clip.duration > 0:
|
826 |
+
try:
|
827 |
+
narration_clip = AudioFileClip(overall_narration_path)
|
828 |
+
final_clip = final_clip.set_audio(narration_clip)
|
829 |
+
logger.info("Narration added.")
|
830 |
+
except Exception as e:
|
831 |
+
logger.error(f"Narration add error: {e}", exc_info=True)
|
832 |
+
elif final_clip.duration <= 0:
|
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 |
+
clip_obj_to_close.close()
|
867 |
+
except Exception as e_close:
|
868 |
+
logger.warning(f"Ignoring error while closing a clip: {type(clip_obj_to_close).__name__} - {e_close}")
|