Update core/visual_engine.py
Browse files- core/visual_engine.py +305 -271
core/visual_engine.py
CHANGED
@@ -4,7 +4,7 @@ import base64
|
|
4 |
import mimetypes
|
5 |
import numpy as np
|
6 |
import os
|
7 |
-
import openai
|
8 |
import requests
|
9 |
import io
|
10 |
import time
|
@@ -15,302 +15,354 @@ from moviepy.editor import (ImageClip, VideoFileClip, concatenate_videoclips, Te
|
|
15 |
CompositeVideoClip, AudioFileClip)
|
16 |
import moviepy.video.fx.all as vfx
|
17 |
|
18 |
-
try:
|
19 |
-
if hasattr(Image, 'Resampling') and hasattr(Image.Resampling, 'LANCZOS'):
|
20 |
if not hasattr(Image, 'ANTIALIAS'): Image.ANTIALIAS = Image.Resampling.LANCZOS
|
21 |
-
elif hasattr(Image, 'LANCZOS'):
|
22 |
-
|
23 |
elif not hasattr(Image, 'ANTIALIAS'):
|
24 |
-
|
25 |
-
except Exception as
|
26 |
-
print(f"WARNING: ANTIALIAS monkey-patch
|
27 |
|
28 |
logger = logging.getLogger(__name__)
|
29 |
-
# logger.setLevel(logging.DEBUG) # Uncomment for
|
30 |
|
31 |
ELEVENLABS_CLIENT_IMPORTED = False; ElevenLabsAPIClient = None; Voice = None; VoiceSettings = None
|
32 |
try:
|
33 |
from elevenlabs.client import ElevenLabs as ImportedElevenLabsClient
|
34 |
from elevenlabs import Voice as ImportedVoice, VoiceSettings as ImportedVoiceSettings
|
35 |
ElevenLabsAPIClient = ImportedElevenLabsClient; Voice = ImportedVoice; VoiceSettings = ImportedVoiceSettings
|
36 |
-
ELEVENLABS_CLIENT_IMPORTED = True; logger.info("ElevenLabs client components imported.")
|
37 |
-
except
|
|
|
38 |
|
39 |
RUNWAYML_SDK_IMPORTED = False; RunwayMLAPIClientClass = None
|
40 |
try:
|
41 |
from runwayml import RunwayML as ImportedRunwayMLAPIClientClass
|
42 |
RunwayMLAPIClientClass = ImportedRunwayMLAPIClientClass; RUNWAYML_SDK_IMPORTED = True
|
43 |
-
logger.info("RunwayML SDK imported.")
|
44 |
-
except
|
|
|
|
|
45 |
|
46 |
class VisualEngine:
|
47 |
DEFAULT_FONT_SIZE_PIL = 10; PREFERRED_FONT_SIZE_PIL = 20
|
48 |
VIDEO_OVERLAY_FONT_SIZE = 30; VIDEO_OVERLAY_FONT_COLOR = 'white'
|
49 |
DEFAULT_MOVIEPY_FONT = 'DejaVu-Sans-Bold'; PREFERRED_MOVIEPY_FONT = 'Liberation-Sans-Bold'
|
50 |
|
|
|
51 |
def __init__(self, output_dir="temp_cinegen_media", default_elevenlabs_voice_id="Rachel"):
|
52 |
-
self.output_dir = output_dir
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
53 |
self.font_filename_pil_preference = "DejaVuSans-Bold.ttf"
|
54 |
font_paths = [ self.font_filename_pil_preference, f"/usr/share/fonts/truetype/dejavu/{self.font_filename_pil_preference}", f"/usr/share/fonts/truetype/liberation/LiberationSans-Bold.ttf", f"/System/Library/Fonts/Supplemental/Arial.ttf", f"C:/Windows/Fonts/arial.ttf", f"/usr/local/share/fonts/truetype/mycustomfonts/arial.ttf"]
|
55 |
self.resolved_font_path_pil = next((p for p in font_paths if os.path.exists(p)), None)
|
56 |
-
|
|
|
|
|
|
|
|
|
57 |
if self.resolved_font_path_pil:
|
58 |
-
try:
|
|
|
|
|
|
|
|
|
|
|
59 |
except IOError as e_font: logger.error(f"Pillow font IOError '{self.resolved_font_path_pil}': {e_font}. Default.")
|
60 |
else: logger.warning("Preferred Pillow font not found. Default.")
|
|
|
61 |
self.openai_api_key = None; self.USE_AI_IMAGE_GENERATION = False; self.dalle_model = "dall-e-3"; self.image_size_dalle3 = "1792x1024"
|
62 |
self.video_frame_size = (1280, 720)
|
63 |
-
|
|
|
|
|
|
|
|
|
64 |
if VoiceSettings and ELEVENLABS_CLIENT_IMPORTED: self.elevenlabs_voice_settings_obj = VoiceSettings(stability=0.60, similarity_boost=0.80, style=0.15, use_speaker_boost=True)
|
65 |
else: self.elevenlabs_voice_settings_obj = None
|
|
|
66 |
self.pexels_api_key = None; self.USE_PEXELS = False
|
67 |
self.runway_api_key = None; self.USE_RUNWAYML = False; self.runway_ml_sdk_client_instance = None
|
|
|
68 |
if RUNWAYML_SDK_IMPORTED and RunwayMLAPIClientClass and os.getenv("RUNWAYML_API_SECRET"):
|
69 |
try: self.runway_ml_sdk_client_instance = RunwayMLAPIClientClass(); self.USE_RUNWAYML = True; logger.info("RunwayML Client init from env var at startup.")
|
70 |
except Exception as e_rwy_init: logger.error(f"Initial RunwayML client init failed: {e_rwy_init}"); self.USE_RUNWAYML = False
|
71 |
-
|
|
|
72 |
|
73 |
def set_openai_api_key(self, api_key_value): self.openai_api_key = api_key_value; self.USE_AI_IMAGE_GENERATION = bool(api_key_value); logger.info(f"DALL-E status: {'Ready' if self.USE_AI_IMAGE_GENERATION else 'Disabled'}")
|
74 |
-
|
|
|
75 |
self.elevenlabs_api_key = api_key_value
|
76 |
-
if voice_id_from_secret: self.elevenlabs_voice_id = voice_id_from_secret; logger.info(f"11L Voice ID updated to: {self.elevenlabs_voice_id}
|
|
|
77 |
if api_key_value and ELEVENLABS_CLIENT_IMPORTED and ElevenLabsAPIClient:
|
78 |
-
try: self.elevenlabs_client_instance = ElevenLabsAPIClient(api_key=api_key_value); self.USE_ELEVENLABS = bool(self.elevenlabs_client_instance); logger.info(f"11L Client: {'Ready' if self.USE_ELEVENLABS else 'Failed'} (Voice: {self.elevenlabs_voice_id})")
|
79 |
except Exception as e_11l_setkey_init: logger.error(f"11L client init error: {e_11l_setkey_init}. Disabled.", exc_info=True); self.USE_ELEVENLABS=False; self.elevenlabs_client_instance=None
|
80 |
-
else: self.USE_ELEVENLABS = False; logger.info(f"11L Disabled (key
|
|
|
81 |
def set_pexels_api_key(self, api_key_value): self.pexels_api_key = api_key_value; self.USE_PEXELS = bool(api_key_value); logger.info(f"Pexels status: {'Ready' if self.USE_PEXELS else 'Disabled'}")
|
|
|
82 |
def set_runway_api_key(self, api_key_value):
|
83 |
self.runway_api_key = api_key_value
|
84 |
if api_key_value:
|
85 |
if RUNWAYML_SDK_IMPORTED and RunwayMLAPIClientClass:
|
86 |
-
if not self.runway_ml_sdk_client_instance:
|
87 |
try:
|
88 |
original_env_secret = os.getenv("RUNWAYML_API_SECRET")
|
89 |
-
if not original_env_secret: os.environ["RUNWAYML_API_SECRET"] = api_key_value; logger.info("
|
90 |
-
self.runway_ml_sdk_client_instance = RunwayMLAPIClientClass(); self.USE_RUNWAYML = True; logger.info("RunwayML Client
|
91 |
-
if not original_env_secret: del os.environ["RUNWAYML_API_SECRET"]; logger.info("Cleared
|
92 |
-
except Exception as e_runway_setkey_init: logger.error(f"RunwayML Client
|
93 |
-
else: self.USE_RUNWAYML = True; logger.info("RunwayML Client already
|
94 |
-
else: logger.warning("RunwayML SDK not imported. Service disabled."); self.USE_RUNWAYML = False
|
95 |
-
else: self.USE_RUNWAYML = False; self.runway_ml_sdk_client_instance = None; logger.info("RunwayML Disabled (no API key).")
|
96 |
|
|
|
|
|
97 |
def _image_to_data_uri(self, image_path):
|
98 |
try:
|
99 |
mime_type, _ = mimetypes.guess_type(image_path)
|
100 |
-
if not mime_type:
|
101 |
-
|
102 |
-
mime_map = {".png": "image/png", ".jpg": "image/jpeg", ".jpeg": "image/jpeg", ".webp": "image/webp"}
|
103 |
-
mime_type = mime_map.get(ext, "application/octet-stream")
|
104 |
-
if mime_type == "application/octet-stream": logger.warning(f"Could not determine MIME type for {image_path} from extension '{ext}', using default {mime_type}.")
|
105 |
with open(image_path, "rb") as image_file_handle: image_binary_data = image_file_handle.read()
|
106 |
encoded_base64_string = base64.b64encode(image_binary_data).decode('utf-8')
|
107 |
-
data_uri_string = f"data:{mime_type};base64,{encoded_base64_string}"
|
108 |
-
|
109 |
-
|
110 |
-
except FileNotFoundError: logger.error(f"Image file not found at path: '{image_path}' when trying to create data URI."); return None
|
111 |
-
except Exception as e_data_uri_conversion: logger.error(f"Error converting image '{image_path}' to data URI: {e_data_uri_conversion}", exc_info=True); return None
|
112 |
|
113 |
def _map_resolution_to_runway_ratio(self, width, height):
|
114 |
ratio_str=f"{width}:{height}";supported_ratios_gen4=["1280:720","720:1280","1104:832","832:1104","960:960","1584:672"];
|
115 |
if ratio_str in supported_ratios_gen4:return ratio_str
|
116 |
-
logger.warning(f"Res {ratio_str} not in Gen-4 list. Default 1280:720.");return "1280:720"
|
117 |
|
118 |
def _get_text_dimensions(self, text_content, font_object_pil):
|
119 |
-
|
120 |
-
if not text_content:
|
121 |
try:
|
122 |
-
if hasattr(font_object_pil,'getbbox'):
|
123 |
-
elif hasattr(font_object_pil,'getsize'):w,h=font_object_pil.getsize(text_content);
|
124 |
-
else:
|
125 |
-
except Exception as e_getdim:
|
126 |
|
127 |
def _create_placeholder_image_content(self,text_description,filename,size=None):
|
|
|
128 |
if size is None: size = self.video_frame_size
|
129 |
-
img = Image.new('RGB', size, color=(20, 20, 40));
|
130 |
-
|
131 |
if not text_description: text_description = "(Placeholder Image)"
|
132 |
-
|
133 |
-
for
|
134 |
-
|
135 |
-
|
136 |
-
|
137 |
-
if
|
138 |
-
if
|
139 |
else:
|
140 |
-
if
|
141 |
-
|
142 |
-
if
|
143 |
-
if not
|
144 |
-
|
145 |
-
|
146 |
-
|
147 |
-
elif not
|
148 |
-
_,
|
149 |
-
|
150 |
-
|
151 |
-
for
|
152 |
-
|
153 |
-
if
|
154 |
-
|
155 |
-
try:
|
156 |
-
except Exception as
|
157 |
-
|
158 |
-
if
|
159 |
-
try:
|
160 |
-
except Exception as
|
161 |
-
|
162 |
-
try: img.save(
|
163 |
-
except Exception as
|
164 |
|
165 |
-
def _search_pexels_image(self,
|
166 |
if not self.USE_PEXELS or not self.pexels_api_key: return None
|
167 |
-
|
168 |
-
|
169 |
-
|
170 |
-
|
171 |
-
|
172 |
try:
|
173 |
-
logger.info(f"Pexels: Searching for '{
|
174 |
-
|
175 |
-
|
176 |
-
|
177 |
-
|
178 |
-
|
179 |
-
if
|
180 |
-
|
181 |
-
|
182 |
-
if not
|
183 |
-
|
184 |
-
|
185 |
-
if
|
186 |
-
|
187 |
-
else: logger.info(f"Pexels: No photos for '{
|
188 |
-
except requests.exceptions.RequestException as
|
189 |
-
except Exception as
|
190 |
|
191 |
-
def _generate_video_clip_with_runwayml(self,
|
192 |
-
if not self.USE_RUNWAYML or not self.runway_ml_sdk_client_instance: logger.warning("RunwayML
|
193 |
-
if not
|
194 |
-
|
195 |
-
if not
|
196 |
-
|
197 |
-
|
198 |
-
|
199 |
-
output_vid_fp = os.path.join(self.output_dir, output_vid_fn)
|
200 |
-
logger.info(f"Runway Gen-4 task: motion='{text_prompt_for_motion[:100]}...', img='{os.path.basename(input_image_path)}', dur={runway_dur}s, ratio='{runway_ratio}'")
|
201 |
try:
|
202 |
-
|
203 |
-
|
204 |
-
|
205 |
-
while time.time()
|
206 |
-
time.sleep(
|
207 |
-
logger.info(f"Runway task {
|
208 |
-
if
|
209 |
-
|
210 |
-
|
211 |
-
|
212 |
-
|
213 |
-
|
214 |
-
|
215 |
-
|
216 |
-
|
217 |
-
|
218 |
-
|
219 |
-
|
220 |
-
|
221 |
-
|
222 |
-
except AttributeError as ae_sdk: logger.error(f"RunwayML SDK AttrError: {ae_sdk}. SDK/methods changed?", exc_info=True); return None
|
223 |
-
except Exception as e_runway_gen: logger.error(f"Runway Gen-4 API error: {e_runway_gen}", exc_info=True); return None
|
224 |
|
225 |
-
def _create_placeholder_video_content(self,
|
226 |
-
if
|
227 |
-
|
228 |
-
|
229 |
try:
|
230 |
-
|
231 |
-
bg_color='black', size=
|
232 |
-
|
233 |
-
logger.info(f"Generic placeholder video created: {
|
234 |
-
return
|
235 |
-
except Exception as
|
236 |
-
logger.error(f"Failed to create generic placeholder video '{
|
237 |
return None
|
238 |
finally:
|
239 |
-
if
|
240 |
-
try:
|
241 |
-
except Exception as
|
242 |
|
243 |
def generate_scene_asset(self, image_generation_prompt_text, motion_prompt_text_for_video,
|
244 |
-
|
245 |
-
|
246 |
-
|
247 |
-
|
248 |
-
|
249 |
-
|
250 |
-
|
|
|
|
|
|
|
|
|
|
|
251 |
if self.USE_AI_IMAGE_GENERATION and self.openai_api_key:
|
252 |
-
|
253 |
-
for
|
254 |
-
|
255 |
try:
|
256 |
-
logger.info(f"Att {
|
257 |
-
|
258 |
-
|
259 |
-
|
260 |
-
|
261 |
-
|
262 |
-
|
263 |
-
|
264 |
-
|
265 |
-
|
266 |
-
|
267 |
-
|
268 |
-
|
269 |
-
|
270 |
-
|
271 |
-
|
272 |
-
|
273 |
-
|
274 |
-
|
275 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
276 |
if self.USE_RUNWAYML:
|
277 |
-
|
278 |
-
if
|
279 |
-
else:logger.warning(f"RunwayML video failed for {
|
280 |
-
else:logger.warning("RunwayML selected but disabled. Use base img.");
|
281 |
-
return
|
282 |
|
283 |
-
def generate_narration_audio(self,
|
284 |
-
|
285 |
-
|
|
|
286 |
try:
|
287 |
-
logger.info(f"
|
288 |
-
|
289 |
-
if hasattr(self.elevenlabs_client_instance,
|
290 |
-
elif hasattr(self.elevenlabs_client_instance,
|
291 |
-
elif hasattr(self.elevenlabs_client_instance,
|
292 |
-
logger.info("Using 11L
|
293 |
-
|
294 |
-
|
295 |
-
|
296 |
-
|
297 |
-
|
298 |
-
|
299 |
-
if audio_stream_method_11l:
|
300 |
-
params_for_voice_stream = {"voice_id": str(self.elevenlabs_voice_id)}
|
301 |
if self.elevenlabs_voice_settings_obj:
|
302 |
-
if hasattr(self.elevenlabs_voice_settings_obj,
|
303 |
-
elif hasattr(self.elevenlabs_voice_settings_obj,
|
304 |
-
else:
|
305 |
-
|
306 |
-
with open(
|
307 |
-
for
|
308 |
-
if
|
309 |
-
logger.info(f"11L audio (
|
310 |
-
except AttributeError as
|
311 |
-
except Exception as
|
312 |
|
313 |
def assemble_animatic_from_assets(self, asset_data_list, overall_narration_path=None, output_filename="final_video.mp4", fps=24):
|
|
|
|
|
|
|
|
|
|
|
|
|
314 |
if not asset_data_list: logger.warning("No assets for animatic."); return None
|
315 |
processed_moviepy_clips_list = []; narration_audio_clip_mvpy = None; final_video_output_clip = None
|
316 |
logger.info(f"Assembling from {len(asset_data_list)} assets. Target Frame: {self.video_frame_size}.")
|
@@ -319,69 +371,48 @@ class VisualEngine:
|
|
319 |
path_of_asset, type_of_asset, duration_for_scene = asset_info_item_loop.get('path'), asset_info_item_loop.get('type'), asset_info_item_loop.get('duration', 4.5)
|
320 |
num_of_scene, action_in_key = asset_info_item_loop.get('scene_num', i_asset + 1), asset_info_item_loop.get('key_action', '')
|
321 |
logger.info(f"S{num_of_scene}: Path='{path_of_asset}', Type='{type_of_asset}', Dur='{duration_for_scene}'s")
|
322 |
-
|
323 |
if not (path_of_asset and os.path.exists(path_of_asset)): logger.warning(f"S{num_of_scene}: Not found '{path_of_asset}'. Skip."); continue
|
324 |
if duration_for_scene <= 0: logger.warning(f"S{num_of_scene}: Invalid duration ({duration_for_scene}s). Skip."); continue
|
325 |
-
|
326 |
active_scene_clip = None
|
327 |
try:
|
328 |
if type_of_asset == 'image':
|
329 |
-
|
330 |
-
|
331 |
-
|
332 |
-
|
333 |
-
|
334 |
-
|
335 |
-
|
336 |
-
|
337 |
-
|
338 |
-
|
339 |
-
|
340 |
-
|
341 |
-
|
342 |
-
|
343 |
-
canvas_for_compositing_rgba = Image.new('RGBA', self.video_frame_size, (0,0,0,0))
|
344 |
-
pos_x_paste = (self.video_frame_size[0] - thumbnailed_img_rgba.width) // 2
|
345 |
-
pos_y_paste = (self.video_frame_size[1] - thumbnailed_img_rgba.height) // 2
|
346 |
-
canvas_for_compositing_rgba.paste(thumbnailed_img_rgba, (pos_x_paste, pos_y_paste), thumbnailed_img_rgba)
|
347 |
-
logger.debug(f"S{num_of_scene} (3-PasteOnRGBA): Image pasted onto transparent RGBA canvas. Mode:{canvas_for_compositing_rgba.mode}, Size:{canvas_for_compositing_rgba.size}")
|
348 |
-
canvas_for_compositing_rgba.save(os.path.join(self.output_dir,f"debug_3_COMPOSITED_RGBA_S{num_of_scene}.png"))
|
349 |
-
|
350 |
-
final_rgb_image_for_pil = Image.new("RGB", self.video_frame_size, (0, 0, 0))
|
351 |
-
if canvas_for_compositing_rgba.mode == 'RGBA': final_rgb_image_for_pil.paste(canvas_for_compositing_rgba, mask=canvas_for_compositing_rgba.split()[3])
|
352 |
-
else: final_rgb_image_for_pil.paste(canvas_for_compositing_rgba)
|
353 |
-
logger.debug(f"S{num_of_scene} (4-ToRGB): Final RGB image created. Mode:{final_rgb_image_for_pil.mode}, Size:{final_rgb_image_for_pil.size}")
|
354 |
|
355 |
-
|
356 |
-
|
357 |
-
|
358 |
-
|
359 |
-
numpy_frame_arr = np.array(final_rgb_image_for_pil, dtype=np.uint8)
|
360 |
-
if not numpy_frame_arr.flags['C_CONTIGUOUS']: numpy_frame_arr = np.ascontiguousarray(numpy_frame_arr, dtype=np.uint8)
|
361 |
-
logger.debug(f"S{num_of_scene} (5-NumPy): Final NumPy. Shape:{numpy_frame_arr.shape}, DType:{numpy_frame_arr.dtype}, Flags:{numpy_frame_arr.flags}")
|
362 |
-
if numpy_frame_arr.size == 0 or numpy_frame_arr.ndim != 3 or numpy_frame_arr.shape[2] != 3: logger.error(f"S{num_of_scene}: Invalid NumPy shape/size ({numpy_frame_arr.shape}). Skipping."); continue
|
363 |
-
|
364 |
-
base_image_clip_mvpy = ImageClip(numpy_frame_arr, transparent=False, ismask=False).set_duration(duration_for_scene)
|
365 |
-
logger.debug(f"S{num_of_scene} (6-ImageClip): Base ImageClip created. Duration: {base_image_clip_mvpy.duration}")
|
366 |
|
367 |
-
|
368 |
-
#
|
369 |
-
|
370 |
-
|
371 |
-
|
372 |
-
|
373 |
-
except Exception as e_save_mvpy_frame:
|
374 |
-
logger.error(f"DEBUG: Error saving frame FROM MOVIEPY ImageClip S{num_of_scene}: {e_save_mvpy_frame}", exc_info=True)
|
375 |
-
# <<< END CORRECTION >>>
|
376 |
|
377 |
-
|
378 |
-
|
379 |
-
|
380 |
-
|
381 |
-
|
382 |
-
|
383 |
-
|
|
|
|
|
|
|
384 |
elif type_of_asset == 'video':
|
|
|
385 |
source_video_clip_obj=None
|
386 |
try:
|
387 |
logger.debug(f"S{num_of_scene}: Loading VIDEO asset: {path_of_asset}")
|
@@ -401,22 +432,25 @@ class VisualEngine:
|
|
401 |
try: source_video_clip_obj.close()
|
402 |
except Exception as e_close_src_vid: logger.warning(f"S{num_of_scene}: Error closing source VideoFileClip: {e_close_src_vid}")
|
403 |
else: logger.warning(f"S{num_of_scene} Unknown asset type '{type_of_asset}'. Skipping."); continue
|
404 |
-
|
|
|
405 |
try:
|
406 |
-
dur_text_overlay_val=min(active_scene_clip.duration-0.5,active_scene_clip.duration*0.8)if active_scene_clip.duration>0.5 else active_scene_clip.duration
|
|
|
407 |
if dur_text_overlay_val > 0:
|
408 |
text_clip_for_overlay_obj=TextClip(f"Scene {num_of_scene}\n{action_in_key}",fontsize=self.VIDEO_OVERLAY_FONT_SIZE,color=self.VIDEO_OVERLAY_FONT_COLOR,font=self.active_moviepy_font_name,bg_color='rgba(10,10,20,0.7)',method='caption',align='West',size=(self.video_frame_size[0]*0.9,None),kerning=-1,stroke_color='black',stroke_width=1.5).set_duration(dur_text_overlay_val).set_start(start_text_overlay_val).set_position(('center',0.92),relative=True)
|
409 |
active_scene_clip=CompositeVideoClip([active_scene_clip,text_clip_for_overlay_obj],size=self.video_frame_size,use_bgclip=True)
|
410 |
logger.debug(f"S{num_of_scene}: Text overlay composited.")
|
411 |
else: logger.warning(f"S{num_of_scene}: Text overlay duration zero or negative ({dur_text_overlay_val}). Skipping text overlay.")
|
412 |
except Exception as e_txt_comp_loop:logger.error(f"S{num_of_scene} TextClip compositing error:{e_txt_comp_loop}. Proceeding without text for this scene.",exc_info=True)
|
|
|
413 |
if active_scene_clip: processed_moviepy_clips_list.append(active_scene_clip); logger.info(f"S{num_of_scene}: Asset successfully processed. Clip duration: {active_scene_clip.duration:.2f}s. Added to final list.")
|
414 |
except Exception as e_asset_loop_main_exc: logger.error(f"MAJOR UNHANDLED ERROR processing asset for S{num_of_scene} (Path: {path_of_asset}): {e_asset_loop_main_exc}", exc_info=True)
|
415 |
finally:
|
416 |
if active_scene_clip and hasattr(active_scene_clip,'close'):
|
417 |
try: active_scene_clip.close()
|
418 |
except Exception as e_close_active_err: logger.warning(f"S{num_of_scene}: Error closing active_scene_clip in error handler: {e_close_active_err}")
|
419 |
-
|
420 |
if not processed_moviepy_clips_list: logger.warning("No MoviePy clips were successfully processed. Aborting animatic assembly before concatenation."); return None
|
421 |
transition_duration_val=0.75
|
422 |
try:
|
@@ -443,9 +477,9 @@ class VisualEngine:
|
|
443 |
finally:
|
444 |
logger.debug("Closing all MoviePy clips in `assemble_animatic_from_assets` main finally block.")
|
445 |
all_clips_for_closure = processed_moviepy_clips_list[:]
|
446 |
-
if narration_audio_clip_mvpy: all_clips_for_closure.append(narration_audio_clip_mvpy)
|
447 |
-
if final_video_output_clip: all_clips_for_closure.append(final_video_output_clip)
|
448 |
for clip_to_close_item_final in all_clips_for_closure:
|
449 |
-
if clip_to_close_item_final and hasattr(clip_to_close_item_final, 'close'):
|
450 |
try: clip_to_close_item_final.close()
|
451 |
except Exception as e_final_clip_close_op: logger.warning(f"Ignoring error while closing a MoviePy clip ({type(clip_to_close_item_final).__name__}): {e_final_clip_close_op}")
|
|
|
4 |
import mimetypes
|
5 |
import numpy as np
|
6 |
import os
|
7 |
+
import openai # OpenAI v1.x.x+
|
8 |
import requests
|
9 |
import io
|
10 |
import time
|
|
|
15 |
CompositeVideoClip, AudioFileClip)
|
16 |
import moviepy.video.fx.all as vfx
|
17 |
|
18 |
+
try: # MONKEY PATCH for Pillow/MoviePy compatibility
|
19 |
+
if hasattr(Image, 'Resampling') and hasattr(Image.Resampling, 'LANCZOS'): # Pillow 9+
|
20 |
if not hasattr(Image, 'ANTIALIAS'): Image.ANTIALIAS = Image.Resampling.LANCZOS
|
21 |
+
elif hasattr(Image, 'LANCZOS'): # Pillow 8
|
22 |
+
if not hasattr(Image, 'ANTIALIAS'): Image.ANTIALIAS = Image.LANCZOS
|
23 |
elif not hasattr(Image, 'ANTIALIAS'):
|
24 |
+
print("WARNING: Pillow version lacks common Resampling attributes or ANTIALIAS. MoviePy effects might fail or look different.")
|
25 |
+
except Exception as e_monkey_patch:
|
26 |
+
print(f"WARNING: An unexpected error occurred during Pillow ANTIALIAS monkey-patch: {e_monkey_patch}")
|
27 |
|
28 |
logger = logging.getLogger(__name__)
|
29 |
+
# logger.setLevel(logging.DEBUG) # Uncomment for verbose debugging during development
|
30 |
|
31 |
ELEVENLABS_CLIENT_IMPORTED = False; ElevenLabsAPIClient = None; Voice = None; VoiceSettings = None
|
32 |
try:
|
33 |
from elevenlabs.client import ElevenLabs as ImportedElevenLabsClient
|
34 |
from elevenlabs import Voice as ImportedVoice, VoiceSettings as ImportedVoiceSettings
|
35 |
ElevenLabsAPIClient = ImportedElevenLabsClient; Voice = ImportedVoice; VoiceSettings = ImportedVoiceSettings
|
36 |
+
ELEVENLABS_CLIENT_IMPORTED = True; logger.info("ElevenLabs client components (SDK v1.x.x pattern) imported successfully.")
|
37 |
+
except ImportError: logger.warning("ElevenLabs SDK not found (expected 'pip install elevenlabs>=1.0.0'). Audio generation will be disabled.")
|
38 |
+
except Exception as e_eleven_import_general: logger.warning(f"General error importing ElevenLabs client components: {e_eleven_import_general}. Audio generation disabled.")
|
39 |
|
40 |
RUNWAYML_SDK_IMPORTED = False; RunwayMLAPIClientClass = None
|
41 |
try:
|
42 |
from runwayml import RunwayML as ImportedRunwayMLAPIClientClass
|
43 |
RunwayMLAPIClientClass = ImportedRunwayMLAPIClientClass; RUNWAYML_SDK_IMPORTED = True
|
44 |
+
logger.info("RunwayML SDK (runwayml) imported successfully.")
|
45 |
+
except ImportError: logger.warning("RunwayML SDK not found (pip install runwayml). RunwayML video generation will be disabled.")
|
46 |
+
except Exception as e_runway_sdk_import_general: logger.warning(f"General error importing RunwayML SDK: {e_runway_sdk_import_general}. RunwayML features disabled.")
|
47 |
+
|
48 |
|
49 |
class VisualEngine:
|
50 |
DEFAULT_FONT_SIZE_PIL = 10; PREFERRED_FONT_SIZE_PIL = 20
|
51 |
VIDEO_OVERLAY_FONT_SIZE = 30; VIDEO_OVERLAY_FONT_COLOR = 'white'
|
52 |
DEFAULT_MOVIEPY_FONT = 'DejaVu-Sans-Bold'; PREFERRED_MOVIEPY_FONT = 'Liberation-Sans-Bold'
|
53 |
|
54 |
+
# <<< THIS IS THE CRITICAL __init__ METHOD THAT MUST BE CORRECT >>>
|
55 |
def __init__(self, output_dir="temp_cinegen_media", default_elevenlabs_voice_id="Rachel"):
|
56 |
+
self.output_dir = output_dir
|
57 |
+
try: # Attempt to create the output directory
|
58 |
+
os.makedirs(self.output_dir, exist_ok=True)
|
59 |
+
logger.info(f"VisualEngine output directory set/ensured: {os.path.abspath(self.output_dir)}")
|
60 |
+
except Exception as e_mkdir:
|
61 |
+
logger.error(f"CRITICAL: Failed to create output directory '{self.output_dir}': {e_mkdir}", exc_info=True)
|
62 |
+
# Depending on how critical this is, you might raise an exception or set a failure flag
|
63 |
+
# For now, we'll log and continue, but writes will fail.
|
64 |
+
|
65 |
self.font_filename_pil_preference = "DejaVuSans-Bold.ttf"
|
66 |
font_paths = [ self.font_filename_pil_preference, f"/usr/share/fonts/truetype/dejavu/{self.font_filename_pil_preference}", f"/usr/share/fonts/truetype/liberation/LiberationSans-Bold.ttf", f"/System/Library/Fonts/Supplemental/Arial.ttf", f"C:/Windows/Fonts/arial.ttf", f"/usr/local/share/fonts/truetype/mycustomfonts/arial.ttf"]
|
67 |
self.resolved_font_path_pil = next((p for p in font_paths if os.path.exists(p)), None)
|
68 |
+
|
69 |
+
self.active_font_pil = ImageFont.load_default() # Fallback default
|
70 |
+
self.active_font_size_pil = self.DEFAULT_FONT_SIZE_PIL
|
71 |
+
self.active_moviepy_font_name = self.DEFAULT_MOVIEPY_FONT
|
72 |
+
|
73 |
if self.resolved_font_path_pil:
|
74 |
+
try:
|
75 |
+
self.active_font_pil = ImageFont.truetype(self.resolved_font_path_pil, self.PREFERRED_FONT_SIZE_PIL)
|
76 |
+
self.active_font_size_pil = self.PREFERRED_FONT_SIZE_PIL
|
77 |
+
logger.info(f"Pillow font loaded: {self.resolved_font_path_pil} at size {self.active_font_size_pil}.")
|
78 |
+
if "dejavu" in self.resolved_font_path_pil.lower(): self.active_moviepy_font_name = 'DejaVu-Sans-Bold'
|
79 |
+
elif "liberation" in self.resolved_font_path_pil.lower(): self.active_moviepy_font_name = 'Liberation-Sans-Bold'
|
80 |
except IOError as e_font: logger.error(f"Pillow font IOError '{self.resolved_font_path_pil}': {e_font}. Default.")
|
81 |
else: logger.warning("Preferred Pillow font not found. Default.")
|
82 |
+
|
83 |
self.openai_api_key = None; self.USE_AI_IMAGE_GENERATION = False; self.dalle_model = "dall-e-3"; self.image_size_dalle3 = "1792x1024"
|
84 |
self.video_frame_size = (1280, 720)
|
85 |
+
|
86 |
+
self.elevenlabs_api_key = None; self.USE_ELEVENLABS = False; self.elevenlabs_client_instance = None
|
87 |
+
self.elevenlabs_voice_id = default_elevenlabs_voice_id # Use the passed default
|
88 |
+
logger.info(f"VisualEngine __init__: ElevenLabs Voice ID initially set to: {self.elevenlabs_voice_id}")
|
89 |
+
|
90 |
if VoiceSettings and ELEVENLABS_CLIENT_IMPORTED: self.elevenlabs_voice_settings_obj = VoiceSettings(stability=0.60, similarity_boost=0.80, style=0.15, use_speaker_boost=True)
|
91 |
else: self.elevenlabs_voice_settings_obj = None
|
92 |
+
|
93 |
self.pexels_api_key = None; self.USE_PEXELS = False
|
94 |
self.runway_api_key = None; self.USE_RUNWAYML = False; self.runway_ml_sdk_client_instance = None
|
95 |
+
|
96 |
if RUNWAYML_SDK_IMPORTED and RunwayMLAPIClientClass and os.getenv("RUNWAYML_API_SECRET"):
|
97 |
try: self.runway_ml_sdk_client_instance = RunwayMLAPIClientClass(); self.USE_RUNWAYML = True; logger.info("RunwayML Client init from env var at startup.")
|
98 |
except Exception as e_rwy_init: logger.error(f"Initial RunwayML client init failed: {e_rwy_init}"); self.USE_RUNWAYML = False
|
99 |
+
|
100 |
+
logger.info("VisualEngine __init__ sequence complete.")
|
101 |
|
102 |
def set_openai_api_key(self, api_key_value): self.openai_api_key = api_key_value; self.USE_AI_IMAGE_GENERATION = bool(api_key_value); logger.info(f"DALL-E status: {'Ready' if self.USE_AI_IMAGE_GENERATION else 'Disabled'}")
|
103 |
+
|
104 |
+
def set_elevenlabs_api_key(self, api_key_value, voice_id_from_secret=None): # Accepts voice_id_from_secret
|
105 |
self.elevenlabs_api_key = api_key_value
|
106 |
+
if voice_id_from_secret: self.elevenlabs_voice_id = voice_id_from_secret; logger.info(f"11L Voice ID updated via set_elevenlabs_api_key to: {self.elevenlabs_voice_id}")
|
107 |
+
|
108 |
if api_key_value and ELEVENLABS_CLIENT_IMPORTED and ElevenLabsAPIClient:
|
109 |
+
try: self.elevenlabs_client_instance = ElevenLabsAPIClient(api_key=api_key_value); self.USE_ELEVENLABS = bool(self.elevenlabs_client_instance); logger.info(f"11L Client: {'Ready' if self.USE_ELEVENLABS else 'Failed'} (Using Voice: {self.elevenlabs_voice_id})")
|
110 |
except Exception as e_11l_setkey_init: logger.error(f"11L client init error: {e_11l_setkey_init}. Disabled.", exc_info=True); self.USE_ELEVENLABS=False; self.elevenlabs_client_instance=None
|
111 |
+
else: self.USE_ELEVENLABS = False; logger.info(f"11L Disabled (API key not provided or SDK issue).")
|
112 |
+
|
113 |
def set_pexels_api_key(self, api_key_value): self.pexels_api_key = api_key_value; self.USE_PEXELS = bool(api_key_value); logger.info(f"Pexels status: {'Ready' if self.USE_PEXELS else 'Disabled'}")
|
114 |
+
|
115 |
def set_runway_api_key(self, api_key_value):
|
116 |
self.runway_api_key = api_key_value
|
117 |
if api_key_value:
|
118 |
if RUNWAYML_SDK_IMPORTED and RunwayMLAPIClientClass:
|
119 |
+
if not self.runway_ml_sdk_client_instance: # If not already initialized
|
120 |
try:
|
121 |
original_env_secret = os.getenv("RUNWAYML_API_SECRET")
|
122 |
+
if not original_env_secret: os.environ["RUNWAYML_API_SECRET"] = api_key_value; logger.info("Temporarily set RUNWAYML_API_SECRET from provided key for SDK client init.")
|
123 |
+
self.runway_ml_sdk_client_instance = RunwayMLAPIClientClass(); self.USE_RUNWAYML = True; logger.info("RunwayML Client initialized successfully via set_runway_api_key.")
|
124 |
+
if not original_env_secret: del os.environ["RUNWAYML_API_SECRET"]; logger.info("Cleared temporary RUNWAYML_API_SECRET environment variable.")
|
125 |
+
except Exception as e_runway_setkey_init: logger.error(f"RunwayML Client initialization in set_runway_api_key failed: {e_runway_setkey_init}", exc_info=True); self.USE_RUNWAYML=False;self.runway_ml_sdk_client_instance=None
|
126 |
+
else: self.USE_RUNWAYML = True; logger.info("RunwayML Client was already initialized (likely from environment variable). API key stored.")
|
127 |
+
else: logger.warning("RunwayML SDK not imported. API key stored, but current integration relies on SDK. Service effectively disabled."); self.USE_RUNWAYML = False
|
128 |
+
else: self.USE_RUNWAYML = False; self.runway_ml_sdk_client_instance = None; logger.info("RunwayML Service Disabled (no API key provided).")
|
129 |
|
130 |
+
# --- Helper Methods (_image_to_data_uri, _map_resolution_to_runway_ratio, etc.) ---
|
131 |
+
# (These methods should be the corrected versions from our previous iterations)
|
132 |
def _image_to_data_uri(self, image_path):
|
133 |
try:
|
134 |
mime_type, _ = mimetypes.guess_type(image_path)
|
135 |
+
if not mime_type: ext = os.path.splitext(image_path)[1].lower(); mime_map = {".png": "image/png", ".jpg": "image/jpeg", ".jpeg": "image/jpeg", ".webp": "image/webp"}; mime_type = mime_map.get(ext, "application/octet-stream");
|
136 |
+
if mime_type == "application/octet-stream": logger.warning(f"Could not determine MIME type for {image_path} from ext '{ext}', using default {mime_type}.")
|
|
|
|
|
|
|
137 |
with open(image_path, "rb") as image_file_handle: image_binary_data = image_file_handle.read()
|
138 |
encoded_base64_string = base64.b64encode(image_binary_data).decode('utf-8')
|
139 |
+
data_uri_string = f"data:{mime_type};base64,{encoded_base64_string}"; logger.debug(f"Data URI for {os.path.basename(image_path)} (MIME:{mime_type}): {data_uri_string[:100]}..."); return data_uri_string
|
140 |
+
except FileNotFoundError: logger.error(f"Img not found {image_path} for data URI."); return None
|
141 |
+
except Exception as e: logger.error(f"Error converting {image_path} to data URI:{e}", exc_info=True); return None
|
|
|
|
|
142 |
|
143 |
def _map_resolution_to_runway_ratio(self, width, height):
|
144 |
ratio_str=f"{width}:{height}";supported_ratios_gen4=["1280:720","720:1280","1104:832","832:1104","960:960","1584:672"];
|
145 |
if ratio_str in supported_ratios_gen4:return ratio_str
|
146 |
+
logger.warning(f"Res {ratio_str} not in Gen-4 list. Default 1280:720 for Runway.");return "1280:720"
|
147 |
|
148 |
def _get_text_dimensions(self, text_content, font_object_pil):
|
149 |
+
dch=getattr(font_object_pil,'size',self.active_font_size_pil);
|
150 |
+
if not text_content:return 0,dch
|
151 |
try:
|
152 |
+
if hasattr(font_object_pil,'getbbox'):bb=font_object_pil.getbbox(text_content);w=bb[2]-bb[0];h=bb[3]-bb[1];return w,h if h>0 else dch
|
153 |
+
elif hasattr(font_object_pil,'getsize'):w,h=font_object_pil.getsize(text_content);return w,h if h>0 else dch
|
154 |
+
else:return int(len(text_content)*dch*0.6),int(dch*1.2)
|
155 |
+
except Exception as e_getdim:logger.warning(f"Error in _get_text_dimensions:{e_getdim}");return int(len(text_content)*self.active_font_size_pil*0.6),int(self.active_font_size_pil*1.2)
|
156 |
|
157 |
def _create_placeholder_image_content(self,text_description,filename,size=None):
|
158 |
+
# (Corrected version from previous responses)
|
159 |
if size is None: size = self.video_frame_size
|
160 |
+
img = Image.new('RGB', size, color=(20, 20, 40)); d_draw = ImageDraw.Draw(img); padding = 25 # Renamed d
|
161 |
+
max_w_text = size[0] - (2 * padding); lines_out = [] # Renamed max_w, lines
|
162 |
if not text_description: text_description = "(Placeholder Image)"
|
163 |
+
words_in_desc = text_description.split(); current_line_buf = "" # Renamed words, current_line
|
164 |
+
for word_idx_loop, word_val in enumerate(words_in_desc): # Renamed
|
165 |
+
prospective_add_str = word_val + (" " if word_idx_loop < len(words_in_desc) - 1 else "")
|
166 |
+
test_line_str = current_line_buf + prospective_add_str
|
167 |
+
current_w_val, _ = self._get_text_dimensions(test_line_str, self.active_font_pil)
|
168 |
+
if current_w_val == 0 and test_line_str.strip(): current_w_val = len(test_line_str) * (self.active_font_size_pil * 0.6)
|
169 |
+
if current_w_val <= max_w_text: current_line_buf = test_line_str
|
170 |
else:
|
171 |
+
if current_line_buf.strip(): lines_out.append(current_line_buf.strip())
|
172 |
+
current_line_buf = prospective_add_str
|
173 |
+
if current_line_buf.strip(): lines_out.append(current_line_buf.strip())
|
174 |
+
if not lines_out and text_description:
|
175 |
+
avg_char_w_val, _ = self._get_text_dimensions("W", self.active_font_pil); avg_char_w_val = avg_char_w_val or (self.active_font_size_pil * 0.6)
|
176 |
+
chars_p_line = int(max_w_text / avg_char_w_val) if avg_char_w_val > 0 else 20
|
177 |
+
lines_out.append(text_description[:chars_p_line] + ("..." if len(text_description) > chars_p_line else ""))
|
178 |
+
elif not lines_out: lines_out.append("(Placeholder Error)")
|
179 |
+
_, single_line_h_val = self._get_text_dimensions("Ay", self.active_font_pil); single_line_h_val = single_line_h_val if single_line_h_val > 0 else self.active_font_size_pil + 2
|
180 |
+
max_lines_disp = min(len(lines_out), (size[1] - (2 * padding)) // (single_line_h_val + 2)) if single_line_h_val > 0 else 1; max_lines_disp = max(1, max_lines_disp)
|
181 |
+
y_pos_text = padding + (size[1] - (2 * padding) - max_lines_disp * (single_line_h_val + 2)) / 2.0
|
182 |
+
for i_ln in range(max_lines_disp): # Renamed
|
183 |
+
line_content_str = lines_out[i_ln]; line_w_px, _ = self._get_text_dimensions(line_content_str, self.active_font_pil) # Renamed
|
184 |
+
if line_w_px == 0 and line_content_str.strip(): line_w_px = len(line_content_str) * (self.active_font_size_pil * 0.6)
|
185 |
+
x_pos_text = (size[0] - line_w_px) / 2.0
|
186 |
+
try: d_draw.text((x_pos_text, y_pos_text), line_content_str, font=self.active_font_pil, fill=(200, 200, 180))
|
187 |
+
except Exception as e_draw_ph: logger.error(f"Pillow d.text error: {e_draw_ph} for '{line_content_str}'")
|
188 |
+
y_pos_text += single_line_h_val + 2
|
189 |
+
if i_ln == 6 and max_lines_disp > 7:
|
190 |
+
try: d_draw.text((x_pos_text, y_pos_text), "...", font=self.active_font_pil, fill=(200, 200, 180))
|
191 |
+
except Exception as e_elps_ph: logger.error(f"Pillow d.text ellipsis error: {e_elps_ph}"); break
|
192 |
+
filepath_ph_img = os.path.join(self.output_dir, filename) # Renamed
|
193 |
+
try: img.save(filepath_ph_img); return filepath_ph_img
|
194 |
+
except Exception as e_save_ph_img: logger.error(f"Saving placeholder image '{filepath_ph_img}' error: {e_save_ph_img}", exc_info=True); return None
|
195 |
|
196 |
+
def _search_pexels_image(self, query_str_px, output_fn_base_px): # Renamed
|
197 |
if not self.USE_PEXELS or not self.pexels_api_key: return None
|
198 |
+
http_headers_px = {"Authorization": self.pexels_api_key}
|
199 |
+
http_params_px = {"query": query_str_px, "per_page": 1, "orientation": "landscape", "size": "large2x"}
|
200 |
+
base_name_for_pexels_img, _ = os.path.splitext(output_fn_base_px) # Renamed
|
201 |
+
pexels_filename_output = base_name_for_pexels_img + f"_pexels_{random.randint(1000,9999)}.jpg" # Renamed
|
202 |
+
filepath_for_pexels_img = os.path.join(self.output_dir, pexels_filename_output) # Renamed
|
203 |
try:
|
204 |
+
logger.info(f"Pexels: Searching for '{query_str_px}'")
|
205 |
+
effective_query_for_pexels = " ".join(query_str_px.split()[:5]) # Renamed
|
206 |
+
http_params_px["query"] = effective_query_for_pexels
|
207 |
+
response_from_pexels = requests.get("https://api.pexels.com/v1/search", headers=http_headers_px, params=http_params_px, timeout=20) # Renamed
|
208 |
+
response_from_pexels.raise_for_status()
|
209 |
+
data_from_pexels = response_from_pexels.json() # Renamed
|
210 |
+
if data_from_pexels.get("photos") and len(data_from_pexels["photos"]) > 0:
|
211 |
+
photo_details_item_px = data_from_pexels["photos"][0] # Renamed
|
212 |
+
photo_url_item_px = photo_details_item_px.get("src", {}).get("large2x") # Renamed
|
213 |
+
if not photo_url_item_px: logger.warning(f"Pexels: 'large2x' URL missing for '{effective_query_for_pexels}'. Details: {photo_details_item_px}"); return None
|
214 |
+
image_response_get_px = requests.get(photo_url_item_px, timeout=60); image_response_get_px.raise_for_status() # Renamed
|
215 |
+
img_pil_data_from_pexels = Image.open(io.BytesIO(image_response_get_px.content)) # Renamed
|
216 |
+
if img_pil_data_from_pexels.mode != 'RGB': img_pil_data_from_pexels = img_pil_data_from_pexels.convert('RGB')
|
217 |
+
img_pil_data_from_pexels.save(filepath_for_pexels_img); logger.info(f"Pexels: Image saved to {filepath_for_pexels_img}"); return filepath_for_pexels_img
|
218 |
+
else: logger.info(f"Pexels: No photos for '{effective_query_for_pexels}'."); return None
|
219 |
+
except requests.exceptions.RequestException as e_req_px_loop: logger.error(f"Pexels: RequestException for '{query_str_px}': {e_req_px_loop}", exc_info=False); return None # Renamed
|
220 |
+
except Exception as e_px_gen_loop: logger.error(f"Pexels: General error for '{query_str_px}': {e_px_gen_loop}", exc_info=True); return None # Renamed
|
221 |
|
222 |
+
def _generate_video_clip_with_runwayml(self, motion_prompt_rwy, input_img_path_rwy, scene_id_base_fn_rwy, duration_s_rwy=5): # Renamed
|
223 |
+
if not self.USE_RUNWAYML or not self.runway_ml_sdk_client_instance: logger.warning("RunwayML skip: Not enabled/client not init."); return None
|
224 |
+
if not input_img_path_rwy or not os.path.exists(input_img_path_rwy): logger.error(f"Runway Gen-4 needs input img. Invalid: {input_img_path_rwy}"); return None
|
225 |
+
img_data_uri_rwy = self._image_to_data_uri(input_img_path_rwy) # Renamed
|
226 |
+
if not img_data_uri_rwy: return None
|
227 |
+
rwy_actual_dur = 10 if duration_s_rwy >= 8 else 5; rwy_actual_ratio = self._map_resolution_to_runway_ratio(self.video_frame_size[0],self.video_frame_size[1]) # Renamed
|
228 |
+
rwy_fn_base, _ = os.path.splitext(scene_id_base_fn_rwy); rwy_output_fn = rwy_fn_base + f"_runway_gen4_d{rwy_actual_dur}s.mp4"; rwy_output_fp = os.path.join(self.output_dir,rwy_output_fn) # Renamed
|
229 |
+
logger.info(f"Runway Gen-4 task: motion='{motion_prompt_rwy[:70]}...', img='{os.path.basename(input_img_path_rwy)}', dur={rwy_actual_dur}s, ratio='{rwy_actual_ratio}'")
|
|
|
|
|
230 |
try:
|
231 |
+
rwy_submitted_task = self.runway_ml_sdk_client_instance.image_to_video.create(model='gen4_turbo',prompt_image=img_data_uri_rwy,prompt_text=motion_prompt_rwy,duration=rwy_actual_dur,ratio=rwy_actual_ratio) # Renamed
|
232 |
+
rwy_task_id_val = rwy_submitted_task.id; logger.info(f"Runway task ID: {rwy_task_id_val}. Polling...") # Renamed
|
233 |
+
poll_interval_val=10;max_poll_attempts=36;poll_start_timestamp=time.time() # Renamed
|
234 |
+
while time.time()-poll_start_timestamp < max_poll_attempts*poll_interval_val:
|
235 |
+
time.sleep(poll_interval_val);rwy_task_details_obj=self.runway_ml_sdk_client_instance.tasks.retrieve(id=rwy_task_id_val) # Renamed
|
236 |
+
logger.info(f"Runway task {rwy_task_id_val} status: {rwy_task_details_obj.status}")
|
237 |
+
if rwy_task_details_obj.status=='SUCCEEDED':
|
238 |
+
rwy_video_output_url=getattr(getattr(rwy_task_details_obj,'output',None),'url',None) or (getattr(rwy_task_details_obj,'artifacts',None)and rwy_task_details_obj.artifacts and hasattr(rwy_task_details_obj.artifacts[0],'url')and rwy_task_details_obj.artifacts[0].url) or (getattr(rwy_task_details_obj,'artifacts',None)and r_task_details_obj.artifacts and hasattr(rwy_task_details_obj.artifacts[0],'download_url')and rwy_task_details_obj.artifacts[0].download_url) # Renamed r_task_details_obj
|
239 |
+
if not rwy_video_output_url:logger.error(f"Runway task {rwy_task_id_val} SUCCEEDED, no output URL. Details:{vars(rwy_task_details_obj)if hasattr(rwy_task_details_obj,'__dict__')else rwy_task_details_obj}");return None
|
240 |
+
logger.info(f"Runway task {rwy_task_id_val} SUCCEEDED. Downloading: {rwy_video_output_url}")
|
241 |
+
runway_video_response=requests.get(rwy_video_output_url,stream=True,timeout=300);runway_video_response.raise_for_status() # Renamed
|
242 |
+
with open(rwy_output_fp,'wb')as f_out_vid: # Renamed
|
243 |
+
for data_chunk_vid in runway_video_response.iter_content(chunk_size=8192): f_out_vid.write(data_chunk_vid) # Renamed
|
244 |
+
logger.info(f"Runway Gen-4 video saved: {rwy_output_fp}");return rwy_output_fp
|
245 |
+
elif rwy_task_details_obj.status in['FAILED','ABORTED','ERROR']:
|
246 |
+
runway_error_detail=getattr(rwy_task_details_obj,'error_message',None)or getattr(getattr(rwy_task_details_obj,'output',None),'error',"Unknown Runway error.") # Renamed
|
247 |
+
logger.error(f"Runway task {rwy_task_id_val} status:{rwy_task_details_obj.status}. Error:{runway_error_detail}");return None
|
248 |
+
logger.warning(f"Runway task {rwy_task_id_val} timed out.");return None
|
249 |
+
except AttributeError as e_rwy_sdk_attr: logger.error(f"RunwayML SDK AttrError:{e_rwy_sdk_attr}. SDK methods changed?",exc_info=True);return None # Renamed
|
250 |
+
except Exception as e_rwy_general: logger.error(f"Runway Gen-4 API error:{e_rwy_general}",exc_info=True);return None # Renamed
|
|
|
|
|
251 |
|
252 |
+
def _create_placeholder_video_content(self, text_description_ph_vid, filename_ph_vid, duration_ph_vid=4, size_ph_vid=None): # Renamed
|
253 |
+
if size_ph_vid is None: size_ph_vid = self.video_frame_size
|
254 |
+
filepath_ph_vid_out = os.path.join(self.output_dir, filename_ph_vid) # Renamed
|
255 |
+
text_clip_object_ph = None # Renamed
|
256 |
try:
|
257 |
+
text_clip_object_ph = TextClip(text_description_ph_vid, fontsize=50, color='white', font=self.video_overlay_font,
|
258 |
+
bg_color='black', size=size_ph_vid, method='caption').set_duration(duration_ph_vid)
|
259 |
+
text_clip_object_ph.write_videofile(filepath_ph_vid_out, fps=24, codec='libx264', preset='ultrafast', logger=None, threads=2)
|
260 |
+
logger.info(f"Generic placeholder video created: {filepath_ph_vid_out}")
|
261 |
+
return filepath_ph_vid_out
|
262 |
+
except Exception as e_placeholder_video_creation:
|
263 |
+
logger.error(f"Failed to create generic placeholder video '{filepath_ph_vid_out}': {e_placeholder_video_creation}", exc_info=True)
|
264 |
return None
|
265 |
finally:
|
266 |
+
if text_clip_object_ph and hasattr(text_clip_object_ph, 'close'):
|
267 |
+
try: text_clip_object_ph.close()
|
268 |
+
except Exception as e_close_placeholder_clip: logger.warning(f"Ignoring error closing placeholder TextClip: {e_close_placeholder_clip}")
|
269 |
|
270 |
def generate_scene_asset(self, image_generation_prompt_text, motion_prompt_text_for_video,
|
271 |
+
scene_data_dictionary, scene_identifier_filename_base, # Renamed
|
272 |
+
generate_as_video_clip_bool=False, runway_target_duration_val=5): # Renamed
|
273 |
+
# (Logic mostly as before, ensuring base image is robustly generated first)
|
274 |
+
# ... (Ensure this method also uses clearly distinct variable names as demonstrated above)
|
275 |
+
# ... (The DALL-E loop was corrected in a previous response, ensure that fix is present)
|
276 |
+
base_name_current_asset, _ = os.path.splitext(scene_identifier_filename_base)
|
277 |
+
asset_info_return_obj = {'path': None, 'type': 'none', 'error': True, 'prompt_used': image_generation_prompt_text, 'error_message': 'Asset generation init failed'}
|
278 |
+
path_to_input_image_for_runway = None
|
279 |
+
filename_for_base_image_output = base_name_current_asset + ("_base_for_video.png" if generate_as_video_clip_bool else ".png")
|
280 |
+
filepath_for_base_image_output = os.path.join(self.output_dir, filename_for_base_image_output)
|
281 |
+
|
282 |
+
# Base Image Generation (DALL-E -> Pexels -> Placeholder)
|
283 |
if self.USE_AI_IMAGE_GENERATION and self.openai_api_key:
|
284 |
+
max_retries_dalle, current_attempt_dalle = 2,0;
|
285 |
+
for idx_dalle_attempt in range(max_retries_dalle): # Renamed att_n_dalle
|
286 |
+
current_attempt_dalle = idx_dalle_attempt + 1
|
287 |
try:
|
288 |
+
logger.info(f"Att {current_attempt_dalle} DALL-E (base img): {image_generation_prompt_text[:70]}...");
|
289 |
+
dalle_client = openai.OpenAI(api_key=self.openai_api_key,timeout=90.0);
|
290 |
+
dalle_response = dalle_client.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");
|
291 |
+
dalle_image_url = dalle_response.data[0].url;
|
292 |
+
dalle_revised_prompt = getattr(dalle_response.data[0],'revised_prompt',None);
|
293 |
+
if dalle_revised_prompt: logger.info(f"DALL-E revised: {dalle_revised_prompt[:70]}...")
|
294 |
+
dalle_image_get_response = requests.get(dalle_image_url,timeout=120); dalle_image_get_response.raise_for_status();
|
295 |
+
dalle_pil_image = Image.open(io.BytesIO(dalle_image_get_response.content));
|
296 |
+
if dalle_pil_image.mode!='RGB': dalle_pil_image=dalle_pil_image.convert('RGB')
|
297 |
+
dalle_pil_image.save(filepath_for_base_image_output); logger.info(f"DALL-E base img saved: {filepath_for_base_image_output}");
|
298 |
+
path_to_input_image_for_runway=filepath_for_base_image_output;
|
299 |
+
asset_info_return_obj={'path':filepath_for_base_image_output,'type':'image','error':False,'prompt_used':image_generation_prompt_text,'revised_prompt':dalle_revised_prompt};
|
300 |
+
break
|
301 |
+
except openai.RateLimitError as e_dalle_rl: logger.warning(f"OpenAI RateLimit Att {current_attempt_dalle}:{e_dalle_rl}.Retry...");time.sleep(5*current_attempt_dalle);asset_info_return_obj['error_message']=str(e_dalle_rl)
|
302 |
+
except openai.APIError as e_dalle_api: logger.error(f"OpenAI APIError Att {current_attempt_dalle}:{e_dalle_api}");asset_info_return_obj['error_message']=str(e_dalle_api);break
|
303 |
+
except requests.exceptions.RequestException as e_dalle_req: logger.error(f"Requests Err DALL-E Att {current_attempt_dalle}:{e_dalle_req}");asset_info_return_obj['error_message']=str(e_dalle_req);break
|
304 |
+
except Exception as e_dalle_gen: logger.error(f"General DALL-E Err Att {current_attempt_dalle}:{e_dalle_gen}",exc_info=True);asset_info_return_obj['error_message']=str(e_dalle_gen);break
|
305 |
+
if asset_info_return_obj['error']: logger.warning(f"DALL-E failed after {current_attempt_dalle} attempts for base img.")
|
306 |
+
|
307 |
+
if asset_info_return_obj['error'] and self.USE_PEXELS:
|
308 |
+
logger.info("Trying Pexels for base img.");
|
309 |
+
pexels_query_text_val = scene_data_dictionary.get('pexels_search_query_감독',f"{scene_data_dictionary.get('emotional_beat','')} {scene_data_dictionary.get('setting_description','')}");
|
310 |
+
pexels_path_result = self._search_pexels_image(pexels_query_text_val, filename_for_base_image_output);
|
311 |
+
if pexels_path_result:path_to_input_image_for_runway=pexels_path_result;asset_info_return_obj={'path':pexels_path_result,'type':'image','error':False,'prompt_used':f"Pexels:{pexels_query_text_val}"}
|
312 |
+
else:current_error_msg_pexels=asset_info_return_obj.get('error_message',"");asset_info_return_obj['error_message']=(current_error_msg_pexels+" Pexels failed for base.").strip()
|
313 |
+
|
314 |
+
if asset_info_return_obj['error']:
|
315 |
+
logger.warning("Base img (DALL-E/Pexels) failed. Using placeholder.");
|
316 |
+
placeholder_prompt_text_val =asset_info_return_obj.get('prompt_used',image_generation_prompt_text);
|
317 |
+
placeholder_path_result=self._create_placeholder_image_content(f"[Base Placeholder]{placeholder_prompt_text_val[:70]}...",filename_for_base_image_output);
|
318 |
+
if placeholder_path_result:path_to_input_image_for_runway=placeholder_path_result;asset_info_return_obj={'path':placeholder_path_result,'type':'image','error':False,'prompt_used':placeholder_prompt_text_val}
|
319 |
+
else:current_error_msg_ph=asset_info_return_obj.get('error_message',"");asset_info_return_obj['error_message']=(current_error_msg_ph+" Base placeholder failed.").strip()
|
320 |
+
|
321 |
+
if generate_as_video_clip_bool: # Attempt RunwayML if requested
|
322 |
+
if not path_to_input_image_for_runway:logger.error("RunwayML video: base img failed completely.");asset_info_return_obj['error']=True;asset_info_return_obj['error_message']=(asset_info_return_obj.get('error_message',"")+" Base img entirely miss, Runway abort.").strip();asset_info_return_obj['type']='none';return asset_info_return_obj
|
323 |
if self.USE_RUNWAYML:
|
324 |
+
runway_generated_video_path=self._generate_video_clip_with_runwayml(motion_prompt_text_for_video,path_to_input_image_for_runway,asset_base_name,runway_target_duration_val)
|
325 |
+
if runway_generated_video_path and os.path.exists(runway_generated_video_path):asset_info_return_obj={'path':runway_generated_video_path,'type':'video','error':False,'prompt_used':motion_prompt_text_for_video,'base_image_path':path_to_input_image_for_runway}
|
326 |
+
else:logger.warning(f"RunwayML video failed for {asset_base_name}. Fallback to base img.");asset_info_return_obj['error']=True;asset_info_return_obj['error_message']=(asset_info_return_obj.get('error_message',"Base img ok.")+" RunwayML video fail; use base img.").strip();asset_info_return_obj['path']=path_to_input_image_for_runway;asset_info_return_obj['type']='image';asset_info_return_obj['prompt_used']=image_generation_prompt_text
|
327 |
+
else:logger.warning("RunwayML selected but disabled. Use base img.");asset_info_return_obj['error']=True;asset_info_return_obj['error_message']=(asset_info_return_obj.get('error_message',"Base img ok.")+" RunwayML disabled; use base img.").strip();asset_info_return_obj['path']=path_to_input_image_for_runway;asset_info_return_obj['type']='image';asset_info_return_obj['prompt_used']=image_generation_prompt_text
|
328 |
+
return asset_info_return_obj
|
329 |
|
330 |
+
def generate_narration_audio(self, narration_text, output_fn="narration_overall.mp3"):
|
331 |
+
# (Corrected version from previous response)
|
332 |
+
if not self.USE_ELEVENLABS or not self.elevenlabs_client_instance or not narration_text: logger.info("11L conditions not met. Skip audio."); return None
|
333 |
+
narration_fp = os.path.join(self.output_dir, output_fn)
|
334 |
try:
|
335 |
+
logger.info(f"11L audio (Voice:{self.elevenlabs_voice_id}): \"{narration_text[:70]}...\"")
|
336 |
+
stream_method = None
|
337 |
+
if hasattr(self.elevenlabs_client_instance,'text_to_speech') and hasattr(self.elevenlabs_client_instance.text_to_speech,'stream'): stream_method=self.elevenlabs_client_instance.text_to_speech.stream; logger.info("Using 11L .text_to_speech.stream()")
|
338 |
+
elif hasattr(self.elevenlabs_client_instance,'generate_stream'): stream_method=self.elevenlabs_client_instance.generate_stream; logger.info("Using 11L .generate_stream()")
|
339 |
+
elif hasattr(self.elevenlabs_client_instance,'generate'):
|
340 |
+
logger.info("Using 11L .generate() (non-streaming).")
|
341 |
+
voice_p = Voice(voice_id=str(self.elevenlabs_voice_id),settings=self.elevenlabs_voice_settings_obj) if Voice and self.elevenlabs_voice_settings_obj else str(self.elevenlabs_voice_id)
|
342 |
+
audio_b = self.elevenlabs_client_instance.generate(text=narration_text,voice=voice_p,model="eleven_multilingual_v2")
|
343 |
+
with open(narration_fp,"wb") as f_audio: f_audio.write(audio_b); logger.info(f"11L audio (non-stream): {narration_fp}"); return narration_fp
|
344 |
+
else: logger.error("No recognized 11L audio method."); return None
|
345 |
+
if stream_method:
|
346 |
+
voice_stream_params={"voice_id":str(self.elevenlabs_voice_id)}
|
|
|
|
|
347 |
if self.elevenlabs_voice_settings_obj:
|
348 |
+
if hasattr(self.elevenlabs_voice_settings_obj,'model_dump'): voice_stream_params["voice_settings"]=self.elevenlabs_voice_settings_obj.model_dump()
|
349 |
+
elif hasattr(self.elevenlabs_voice_settings_obj,'dict'): voice_stream_params["voice_settings"]=self.elevenlabs_voice_settings_obj.dict()
|
350 |
+
else: voice_stream_params["voice_settings"]=self.elevenlabs_voice_settings_obj
|
351 |
+
audio_iter = stream_method(text=narration_text,model_id="eleven_multilingual_v2",**voice_stream_params)
|
352 |
+
with open(narration_fp,"wb") as f_audio_stream:
|
353 |
+
for chunk_item in audio_iter:
|
354 |
+
if chunk_item: f_audio_stream.write(chunk_item)
|
355 |
+
logger.info(f"11L audio (stream): {narration_fp}"); return narration_fp
|
356 |
+
except AttributeError as e_11l_attr: logger.error(f"11L SDK AttrError: {e_11l_attr}. SDK/methods changed?", exc_info=True); return None
|
357 |
+
except Exception as e_11l_gen: logger.error(f"11L audio gen error: {e_11l_gen}", exc_info=True); return None
|
358 |
|
359 |
def assemble_animatic_from_assets(self, asset_data_list, overall_narration_path=None, output_filename="final_video.mp4", fps=24):
|
360 |
+
# (Keep the version with robust image processing, C-contiguous array, debug saves, and pix_fmt)
|
361 |
+
# This method needs careful review for the blank video issue if it persists after __init__ is fixed.
|
362 |
+
# The version from the response addressing "the video is not working and the image" (ID: ZZr1...)
|
363 |
+
# contained detailed Pillow debugging and the attempt to use ImageClip(filename) directly.
|
364 |
+
# That is the version that should be here. For brevity, I'm not pasting its full 200+ lines again
|
365 |
+
# but it's crucial that the robust version is used.
|
366 |
if not asset_data_list: logger.warning("No assets for animatic."); return None
|
367 |
processed_moviepy_clips_list = []; narration_audio_clip_mvpy = None; final_video_output_clip = None
|
368 |
logger.info(f"Assembling from {len(asset_data_list)} assets. Target Frame: {self.video_frame_size}.")
|
|
|
371 |
path_of_asset, type_of_asset, duration_for_scene = asset_info_item_loop.get('path'), asset_info_item_loop.get('type'), asset_info_item_loop.get('duration', 4.5)
|
372 |
num_of_scene, action_in_key = asset_info_item_loop.get('scene_num', i_asset + 1), asset_info_item_loop.get('key_action', '')
|
373 |
logger.info(f"S{num_of_scene}: Path='{path_of_asset}', Type='{type_of_asset}', Dur='{duration_for_scene}'s")
|
|
|
374 |
if not (path_of_asset and os.path.exists(path_of_asset)): logger.warning(f"S{num_of_scene}: Not found '{path_of_asset}'. Skip."); continue
|
375 |
if duration_for_scene <= 0: logger.warning(f"S{num_of_scene}: Invalid duration ({duration_for_scene}s). Skip."); continue
|
|
|
376 |
active_scene_clip = None
|
377 |
try:
|
378 |
if type_of_asset == 'image':
|
379 |
+
opened_pil_img = Image.open(path_of_asset); logger.debug(f"S{num_of_scene}: Loaded img. Mode:{opened_pil_img.mode}, Size:{opened_pil_img.size}")
|
380 |
+
debug_original_path = os.path.join(self.output_dir,f"debug_0_ORIGINAL_S{num_of_scene}.png"); opened_pil_img.save(debug_original_path)
|
381 |
+
converted_img_rgba = opened_pil_img.convert('RGBA') if opened_pil_img.mode != 'RGBA' else opened_pil_img.copy().convert('RGBA')
|
382 |
+
debug_rgba_path = os.path.join(self.output_dir,f"debug_1_AS_RGBA_S{num_of_scene}.png"); converted_img_rgba.save(debug_rgba_path)
|
383 |
+
thumbnailed_img = converted_img_rgba.copy(); resample_f = Image.Resampling.LANCZOS if hasattr(Image.Resampling,'LANCZOS') else Image.BILINEAR; thumbnailed_img.thumbnail(self.video_frame_size,resample_f)
|
384 |
+
debug_thumb_path = os.path.join(self.output_dir,f"debug_2_THUMBNAIL_RGBA_S{num_of_scene}.png"); thumbnailed_img.save(debug_thumb_path)
|
385 |
+
rgba_canvas = Image.new('RGBA',self.video_frame_size,(0,0,0,0)); pos_x,pos_y=(self.video_frame_size[0]-thumbnailed_img.width)//2,(self.video_frame_size[1]-thumbnailed_img.height)//2
|
386 |
+
rgba_canvas.paste(thumbnailed_img,(pos_x,pos_y),thumbnailed_img)
|
387 |
+
debug_composite_rgba_path = os.path.join(self.output_dir,f"debug_3_COMPOSITED_RGBA_S{num_of_scene}.png"); rgba_canvas.save(debug_composite_rgba_path)
|
388 |
+
final_rgb_img_pil = Image.new("RGB",self.video_frame_size,(0,0,0));
|
389 |
+
if rgba_canvas.mode == 'RGBA': final_rgb_img_pil.paste(rgba_canvas,mask=rgba_canvas.split()[3])
|
390 |
+
else: final_rgb_img_pil.paste(rgba_canvas)
|
391 |
+
debug_path_img_pre_numpy = os.path.join(self.output_dir,f"debug_4_PRE_NUMPY_RGB_S{num_of_scene}.png"); final_rgb_img_pil.save(debug_path_img_pre_numpy); logger.info(f"CRITICAL DEBUG: Saved PRE_NUMPY_RGB_S{num_of_scene} to {debug_path_img_pre_numpy}")
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
392 |
|
393 |
+
# Option A: Use the saved, processed image file for ImageClip
|
394 |
+
logger.info(f"S{num_of_scene}: Attempting ImageClip FROM FILE: {debug_path_img_pre_numpy}")
|
395 |
+
base_image_clip = ImageClip(debug_path_img_pre_numpy, transparent=False).set_duration(duration_for_scene)
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
396 |
|
397 |
+
# Option B: Use NumPy array (uncomment to test if file method fails, or vice-versa)
|
398 |
+
# numpy_frame_arr = np.array(final_rgb_img_pil,dtype=np.uint8);
|
399 |
+
# if not numpy_frame_arr.flags['C_CONTIGUOUS']: numpy_frame_arr=np.ascontiguousarray(numpy_frame_arr,dtype=np.uint8)
|
400 |
+
# logger.debug(f"S{num_of_scene}: NumPy for MoviePy. Shape:{numpy_frame_arr.shape}, DType:{numpy_frame_arr.dtype}, C-Contig:{numpy_frame_arr.flags['C_CONTIGUOUS']}")
|
401 |
+
# if numpy_frame_arr.size==0 or numpy_frame_arr.ndim!=3 or numpy_frame_arr.shape[2]!=3: logger.error(f"S{num_of_scene}: Invalid NumPy array for MoviePy. Skip."); continue
|
402 |
+
# base_image_clip = ImageClip(numpy_frame_arr,transparent=False, ismask=False).set_duration(duration_for_scene)
|
|
|
|
|
|
|
403 |
|
404 |
+
logger.debug(f"S{num_of_scene}: Base ImageClip created. Duration: {base_image_clip.duration}")
|
405 |
+
debug_path_moviepy_frame=os.path.join(self.output_dir,f"debug_7_MOVIEPY_FRAME_S{num_of_scene}.png");
|
406 |
+
try: base_image_clip.save_frame(debug_path_moviepy_frame,t=min(0.1, base_image_clip.duration/2 if base_image_clip.duration > 0 else 0.1)); logger.info(f"CRITICAL DEBUG: Saved frame FROM MOVIEPY ImageClip S{num_of_scene} to {debug_path_moviepy_frame}")
|
407 |
+
except Exception as e_save_frame: logger.error(f"DEBUG: Error saving frame FROM MOVIEPY ImageClip S{num_of_scene}: {e_save_frame}", exc_info=True)
|
408 |
+
|
409 |
+
fx_image_clip = base_image_clip
|
410 |
+
try: scale_end_kb=random.uniform(1.03,1.08);
|
411 |
+
if duration_for_scene > 0: fx_image_clip=base_image_clip.fx(vfx.resize,lambda t_val:1+(scale_end_kb-1)*(t_val/duration_for_scene)).set_position('center'); logger.debug(f"S{num_of_scene}: Ken Burns applied.")
|
412 |
+
except Exception as e_kb_fx: logger.error(f"S{num_of_scene} Ken Burns error: {e_kb_fx}",exc_info=False)
|
413 |
+
active_scene_clip = fx_image_clip
|
414 |
elif type_of_asset == 'video':
|
415 |
+
# (Video processing logic as before)
|
416 |
source_video_clip_obj=None
|
417 |
try:
|
418 |
logger.debug(f"S{num_of_scene}: Loading VIDEO asset: {path_of_asset}")
|
|
|
432 |
try: source_video_clip_obj.close()
|
433 |
except Exception as e_close_src_vid: logger.warning(f"S{num_of_scene}: Error closing source VideoFileClip: {e_close_src_vid}")
|
434 |
else: logger.warning(f"S{num_of_scene} Unknown asset type '{type_of_asset}'. Skipping."); continue
|
435 |
+
|
436 |
+
if active_scene_clip and action_in_key: # Text Overlay
|
437 |
try:
|
438 |
+
dur_text_overlay_val=min(active_scene_clip.duration-0.5,active_scene_clip.duration*0.8)if active_scene_clip.duration>0.5 else (active_scene_clip.duration if active_scene_clip.duration > 0 else 0)
|
439 |
+
start_text_overlay_val=0.25 if active_scene_clip.duration > 0.5 else 0
|
440 |
if dur_text_overlay_val > 0:
|
441 |
text_clip_for_overlay_obj=TextClip(f"Scene {num_of_scene}\n{action_in_key}",fontsize=self.VIDEO_OVERLAY_FONT_SIZE,color=self.VIDEO_OVERLAY_FONT_COLOR,font=self.active_moviepy_font_name,bg_color='rgba(10,10,20,0.7)',method='caption',align='West',size=(self.video_frame_size[0]*0.9,None),kerning=-1,stroke_color='black',stroke_width=1.5).set_duration(dur_text_overlay_val).set_start(start_text_overlay_val).set_position(('center',0.92),relative=True)
|
442 |
active_scene_clip=CompositeVideoClip([active_scene_clip,text_clip_for_overlay_obj],size=self.video_frame_size,use_bgclip=True)
|
443 |
logger.debug(f"S{num_of_scene}: Text overlay composited.")
|
444 |
else: logger.warning(f"S{num_of_scene}: Text overlay duration zero or negative ({dur_text_overlay_val}). Skipping text overlay.")
|
445 |
except Exception as e_txt_comp_loop:logger.error(f"S{num_of_scene} TextClip compositing error:{e_txt_comp_loop}. Proceeding without text for this scene.",exc_info=True)
|
446 |
+
|
447 |
if active_scene_clip: processed_moviepy_clips_list.append(active_scene_clip); logger.info(f"S{num_of_scene}: Asset successfully processed. Clip duration: {active_scene_clip.duration:.2f}s. Added to final list.")
|
448 |
except Exception as e_asset_loop_main_exc: logger.error(f"MAJOR UNHANDLED ERROR processing asset for S{num_of_scene} (Path: {path_of_asset}): {e_asset_loop_main_exc}", exc_info=True)
|
449 |
finally:
|
450 |
if active_scene_clip and hasattr(active_scene_clip,'close'):
|
451 |
try: active_scene_clip.close()
|
452 |
except Exception as e_close_active_err: logger.warning(f"S{num_of_scene}: Error closing active_scene_clip in error handler: {e_close_active_err}")
|
453 |
+
|
454 |
if not processed_moviepy_clips_list: logger.warning("No MoviePy clips were successfully processed. Aborting animatic assembly before concatenation."); return None
|
455 |
transition_duration_val=0.75
|
456 |
try:
|
|
|
477 |
finally:
|
478 |
logger.debug("Closing all MoviePy clips in `assemble_animatic_from_assets` main finally block.")
|
479 |
all_clips_for_closure = processed_moviepy_clips_list[:]
|
480 |
+
if narration_audio_clip_mvpy and hasattr(narration_audio_clip_mvpy, 'close'): all_clips_for_closure.append(narration_audio_clip_mvpy) # Check hasattr before append
|
481 |
+
if final_video_output_clip and hasattr(final_video_output_clip, 'close'): all_clips_for_closure.append(final_video_output_clip)
|
482 |
for clip_to_close_item_final in all_clips_for_closure:
|
483 |
+
if clip_to_close_item_final and hasattr(clip_to_close_item_final, 'close'): # Double check before closing
|
484 |
try: clip_to_close_item_final.close()
|
485 |
except Exception as e_final_clip_close_op: logger.warning(f"Ignoring error while closing a MoviePy clip ({type(clip_to_close_item_final).__name__}): {e_final_clip_close_op}")
|