Update core/visual_engine.py
Browse files- core/visual_engine.py +235 -200
core/visual_engine.py
CHANGED
@@ -15,16 +15,18 @@ 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 |
|
26 |
logger = logging.getLogger(__name__)
|
27 |
-
# logger.setLevel(logging.DEBUG)
|
28 |
|
29 |
ELEVENLABS_CLIENT_IMPORTED = False; ElevenLabsAPIClient = None; Voice = None; VoiceSettings = None
|
30 |
try:
|
@@ -68,216 +70,247 @@ class VisualEngine:
|
|
68 |
except Exception as e_rwy_init: logger.error(f"Initial RunwayML client init failed: {e_rwy_init}"); self.USE_RUNWAYML = False
|
69 |
logger.info("VisualEngine initialized.")
|
70 |
|
71 |
-
def set_openai_api_key(self,
|
72 |
-
def set_elevenlabs_api_key(self,
|
73 |
-
self.elevenlabs_api_key=
|
74 |
-
if
|
75 |
-
if
|
76 |
-
try: self.elevenlabs_client_instance = ElevenLabsAPIClient(api_key=
|
77 |
-
except Exception as
|
78 |
else: self.USE_ELEVENLABS = False; logger.info(f"11L Disabled (key/SDK).")
|
79 |
-
def set_pexels_api_key(self,
|
80 |
-
def set_runway_api_key(self,
|
81 |
-
self.runway_api_key =
|
82 |
-
if
|
83 |
if RUNWAYML_SDK_IMPORTED and RunwayMLAPIClientClass:
|
84 |
if not self.runway_ml_sdk_client_instance:
|
85 |
try:
|
86 |
-
|
87 |
-
if not
|
88 |
-
self.runway_ml_sdk_client_instance=RunwayMLAPIClientClass(); self.USE_RUNWAYML=True; logger.info("RunwayML Client init via
|
89 |
-
if not
|
90 |
-
except Exception as
|
91 |
-
else: self.USE_RUNWAYML=True; logger.info("RunwayML Client already init.")
|
92 |
-
else: logger.warning("RunwayML SDK not imported.
|
93 |
-
else: self.USE_RUNWAYML=False; self.runway_ml_sdk_client_instance=None; logger.info("RunwayML Disabled (no key).")
|
94 |
|
95 |
-
def _image_to_data_uri(self,
|
96 |
try:
|
97 |
-
|
98 |
-
if not
|
99 |
-
|
100 |
-
|
101 |
-
|
102 |
-
|
103 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
104 |
|
105 |
-
def _map_resolution_to_runway_ratio(self,
|
106 |
-
|
107 |
-
if
|
108 |
-
logger.warning(f"Res {
|
109 |
|
110 |
-
def _get_text_dimensions(self,
|
111 |
-
|
112 |
-
if not
|
113 |
try:
|
114 |
-
if hasattr(
|
115 |
-
elif hasattr(
|
116 |
-
else: return int(len(
|
117 |
-
except Exception as
|
118 |
|
119 |
-
def _create_placeholder_image_content(self,
|
120 |
-
|
121 |
-
|
122 |
-
|
123 |
-
|
124 |
-
|
125 |
-
|
126 |
-
|
127 |
-
|
128 |
-
|
|
|
|
|
129 |
else:
|
130 |
-
if
|
131 |
-
|
132 |
-
if
|
133 |
-
if not
|
134 |
-
|
135 |
-
|
136 |
-
|
137 |
-
|
138 |
-
|
139 |
-
|
140 |
-
|
141 |
-
|
142 |
-
|
143 |
-
|
144 |
-
|
145 |
-
|
146 |
-
|
147 |
-
|
148 |
-
|
149 |
-
|
150 |
-
|
151 |
-
|
152 |
-
|
|
|
153 |
|
154 |
-
def _search_pexels_image(self,
|
155 |
-
# (Keep robust Pexels logic from before)
|
156 |
if not self.USE_PEXELS or not self.pexels_api_key: return None
|
157 |
-
|
158 |
-
|
|
|
|
|
|
|
159 |
try:
|
160 |
-
logger.info(f"Pexels:
|
161 |
-
|
|
|
|
|
|
|
|
|
162 |
if data_px.get("photos") and len(data_px["photos"]) > 0:
|
163 |
-
|
164 |
-
|
165 |
-
|
166 |
-
|
167 |
-
|
168 |
-
|
169 |
-
|
170 |
-
|
|
|
|
|
171 |
|
172 |
-
def _generate_video_clip_with_runwayml(self,
|
173 |
-
|
174 |
-
if not
|
175 |
-
|
176 |
-
|
177 |
-
if
|
178 |
-
|
179 |
-
|
180 |
-
|
|
|
181 |
try:
|
182 |
-
|
183 |
-
|
184 |
-
|
185 |
-
while time.time()-
|
186 |
-
time.sleep(
|
187 |
-
logger.info(f"Runway task {
|
188 |
-
if
|
189 |
-
|
190 |
-
|
191 |
-
|
192 |
-
|
193 |
-
|
194 |
-
|
195 |
-
|
196 |
-
|
197 |
-
|
198 |
-
|
199 |
-
|
200 |
-
|
201 |
-
|
|
|
|
|
202 |
|
203 |
-
def _create_placeholder_video_content(self,
|
204 |
-
|
205 |
-
|
206 |
-
|
207 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
208 |
finally:
|
209 |
-
if
|
210 |
-
try:
|
211 |
except Exception as e_cl_phv: logger.warning(f"Ignoring error closing placeholder TextClip: {e_cl_phv}")
|
212 |
|
213 |
-
def generate_scene_asset(self,
|
214 |
-
|
215 |
-
|
216 |
-
|
|
|
|
|
|
|
|
|
217 |
if self.USE_AI_IMAGE_GENERATION and self.openai_api_key:
|
218 |
-
|
219 |
-
for
|
220 |
-
|
221 |
-
try:
|
222 |
-
logger.info(f"Att {
|
223 |
-
if
|
224 |
-
|
225 |
-
if
|
226 |
-
|
227 |
-
except openai.RateLimitError as
|
228 |
-
except openai.APIError as
|
229 |
-
except requests.exceptions.RequestException as
|
230 |
-
except Exception as
|
231 |
-
if
|
232 |
-
if
|
233 |
-
logger.info("Trying Pexels for base img.");
|
234 |
-
if
|
235 |
-
else:
|
236 |
-
if
|
237 |
-
logger.warning("Base img (DALL-E/Pexels) failed. Using placeholder.");
|
238 |
-
if
|
239 |
-
else:
|
240 |
-
if
|
241 |
-
if not
|
242 |
if self.USE_RUNWAYML:
|
243 |
-
|
244 |
-
if
|
245 |
-
else:logger.warning(f"RunwayML video failed for {
|
246 |
-
else:logger.warning("RunwayML selected but disabled. Use base img.");
|
247 |
-
return
|
248 |
|
249 |
-
def generate_narration_audio(self,
|
250 |
-
|
251 |
-
|
252 |
-
narration_fp = os.path.join(self.output_dir, output_fn)
|
253 |
try:
|
254 |
-
logger.info(f"11L audio (Voice:{self.elevenlabs_voice_id}): \"{
|
255 |
-
|
256 |
-
if hasattr(self.elevenlabs_client_instance,'text_to_speech') and hasattr(self.elevenlabs_client_instance.text_to_speech,'stream'):
|
257 |
-
elif hasattr(self.elevenlabs_client_instance,'generate_stream'):
|
258 |
-
elif hasattr(self.elevenlabs_client_instance,'generate'):
|
259 |
-
logger.info("Using 11L .generate() (non-streaming).")
|
260 |
-
|
261 |
-
|
262 |
-
|
263 |
-
|
264 |
-
|
265 |
-
|
|
|
|
|
266 |
if self.elevenlabs_voice_settings_obj:
|
267 |
-
if hasattr(self.elevenlabs_voice_settings_obj,'model_dump'):
|
268 |
-
elif hasattr(self.elevenlabs_voice_settings_obj,'dict'):
|
269 |
-
else:
|
270 |
-
|
271 |
-
with open(
|
272 |
-
for
|
273 |
-
if
|
274 |
-
logger.info(f"11L audio (
|
275 |
-
except AttributeError as
|
276 |
-
except Exception as
|
277 |
|
278 |
def assemble_animatic_from_assets(self, asset_data_list, overall_narration_path=None, output_filename="final_video.mp4", fps=24):
|
279 |
-
# (Keep the version with robust image processing, C-contiguous array, debug saves, and pix_fmt)
|
280 |
-
# This is the most critical part for your "blank/corrupted video" issue.
|
281 |
if not asset_data_list: logger.warning("No assets for animatic."); return None
|
282 |
processed_moviepy_clips_list = []; narration_audio_clip_mvpy = None; final_video_output_clip = None
|
283 |
logger.info(f"Assembling from {len(asset_data_list)} assets. Target Frame: {self.video_frame_size}.")
|
@@ -290,7 +323,7 @@ class VisualEngine:
|
|
290 |
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
|
291 |
if duration_for_scene <= 0: logger.warning(f"S{num_of_scene}: Invalid duration ({duration_for_scene}s). Skip."); continue
|
292 |
|
293 |
-
active_scene_clip = None
|
294 |
try:
|
295 |
if type_of_asset == 'image':
|
296 |
pil_img_original = Image.open(path_of_asset)
|
@@ -314,28 +347,32 @@ class VisualEngine:
|
|
314 |
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}")
|
315 |
canvas_for_compositing_rgba.save(os.path.join(self.output_dir,f"debug_3_COMPOSITED_RGBA_S{num_of_scene}.png"))
|
316 |
|
317 |
-
final_rgb_image_for_pil = Image.new("RGB", self.video_frame_size, (0, 0, 0))
|
318 |
-
if canvas_for_compositing_rgba.mode == 'RGBA':
|
319 |
-
final_rgb_image_for_pil.paste(canvas_for_compositing_rgba, mask=canvas_for_compositing_rgba.split()[3])
|
320 |
else: final_rgb_image_for_pil.paste(canvas_for_compositing_rgba)
|
321 |
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}")
|
322 |
|
323 |
debug_path_img_pre_numpy = os.path.join(self.output_dir,f"debug_4_PRE_NUMPY_RGB_S{num_of_scene}.png");
|
324 |
final_rgb_image_for_pil.save(debug_path_img_pre_numpy);
|
325 |
-
logger.info(f"CRITICAL DEBUG: Saved PRE_NUMPY_RGB_S{num_of_scene}
|
326 |
|
327 |
numpy_frame_arr = np.array(final_rgb_image_for_pil, dtype=np.uint8)
|
328 |
if not numpy_frame_arr.flags['C_CONTIGUOUS']: numpy_frame_arr = np.ascontiguousarray(numpy_frame_arr, dtype=np.uint8)
|
329 |
-
logger.debug(f"S{num_of_scene} (5-NumPy): Final NumPy
|
330 |
-
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
|
331 |
|
332 |
base_image_clip_mvpy = ImageClip(numpy_frame_arr, transparent=False, ismask=False).set_duration(duration_for_scene)
|
333 |
logger.debug(f"S{num_of_scene} (6-ImageClip): Base ImageClip created. Duration: {base_image_clip_mvpy.duration}")
|
334 |
|
335 |
debug_path_moviepy_frame = os.path.join(self.output_dir,f"debug_7_MOVIEPY_FRAME_S{num_of_scene}.png")
|
336 |
-
|
337 |
-
|
338 |
-
|
|
|
|
|
|
|
|
|
|
|
339 |
|
340 |
fx_image_clip_mvpy = base_image_clip_mvpy
|
341 |
try:
|
@@ -345,7 +382,6 @@ class VisualEngine:
|
|
345 |
except Exception as e_kb_fx_loop: logger.error(f"S{num_of_scene} Ken Burns error: {e_kb_fx_loop}", exc_info=False)
|
346 |
active_scene_clip = fx_image_clip_mvpy
|
347 |
elif type_of_asset == 'video':
|
348 |
-
# (Video processing logic as before)
|
349 |
source_video_clip_obj=None
|
350 |
try:
|
351 |
logger.debug(f"S{num_of_scene}: Loading VIDEO asset: {path_of_asset}")
|
@@ -365,7 +401,6 @@ class VisualEngine:
|
|
365 |
try: source_video_clip_obj.close()
|
366 |
except Exception as e_close_src_vid: logger.warning(f"S{num_of_scene}: Error closing source VideoFileClip: {e_close_src_vid}")
|
367 |
else: logger.warning(f"S{num_of_scene} Unknown asset type '{type_of_asset}'. Skipping."); continue
|
368 |
-
|
369 |
if active_scene_clip and action_in_key:
|
370 |
try:
|
371 |
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; start_text_overlay_val=0.25
|
@@ -381,7 +416,7 @@ class VisualEngine:
|
|
381 |
if active_scene_clip and hasattr(active_scene_clip,'close'):
|
382 |
try: active_scene_clip.close()
|
383 |
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}")
|
384 |
-
continue
|
385 |
if not processed_moviepy_clips_list: logger.warning("No MoviePy clips were successfully processed. Aborting animatic assembly before concatenation."); return None
|
386 |
transition_duration_val=0.75
|
387 |
try:
|
|
|
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 |
+
if not hasattr(Image, 'ANTIALIAS'): Image.ANTIALIAS = Image.LANCZOS
|
23 |
+
elif not hasattr(Image, 'ANTIALIAS'):
|
24 |
+
print("WARNING: Pillow version lacks common Resampling or ANTIALIAS. MoviePy effects might fail.")
|
25 |
+
except Exception as e_mp:
|
26 |
+
print(f"WARNING: ANTIALIAS monkey-patch error: {e_mp}")
|
27 |
|
28 |
logger = logging.getLogger(__name__)
|
29 |
+
# logger.setLevel(logging.DEBUG) # Uncomment for very verbose debugging
|
30 |
|
31 |
ELEVENLABS_CLIENT_IMPORTED = False; ElevenLabsAPIClient = None; Voice = None; VoiceSettings = None
|
32 |
try:
|
|
|
70 |
except Exception as e_rwy_init: logger.error(f"Initial RunwayML client init failed: {e_rwy_init}"); self.USE_RUNWAYML = False
|
71 |
logger.info("VisualEngine initialized.")
|
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 |
+
def set_elevenlabs_api_key(self, api_key_value, voice_id_from_secret=None):
|
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} via set_elevenlabs_api_key.")
|
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/SDK).")
|
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("Temp set RUNWAYML_API_SECRET for SDK.")
|
90 |
+
self.runway_ml_sdk_client_instance = RunwayMLAPIClientClass(); self.USE_RUNWAYML = True; logger.info("RunwayML Client init via set_runway_api_key.")
|
91 |
+
if not original_env_secret: del os.environ["RUNWAYML_API_SECRET"]; logger.info("Cleared temp RUNWAYML_API_SECRET.")
|
92 |
+
except Exception as e_runway_setkey_init: logger.error(f"RunwayML Client init in set_runway_api_key fail: {e_runway_setkey_init}", exc_info=True); self.USE_RUNWAYML=False;self.runway_ml_sdk_client_instance=None
|
93 |
+
else: self.USE_RUNWAYML = True; logger.info("RunwayML Client already init.")
|
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 |
+
ext = os.path.splitext(image_path)[1].lower()
|
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 |
+
logger.debug(f"Generated data URI for {os.path.basename(image_path)} (MIME: {mime_type}). Data URI starts with: {data_uri_string[:100]}...")
|
109 |
+
return data_uri_string
|
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 |
+
default_h = getattr(font_object_pil, 'size', self.active_font_size_pil)
|
120 |
+
if not text_content: return 0, default_h
|
121 |
try:
|
122 |
+
if hasattr(font_object_pil,'getbbox'):bbox=font_object_pil.getbbox(text_content);w=bbox[2]-bbox[0];h=bbox[3]-bbox[1]; return w, h if h > 0 else default_h
|
123 |
+
elif hasattr(font_object_pil,'getsize'):w,h=font_object_pil.getsize(text_content); return w, h if h > 0 else default_h
|
124 |
+
else: return int(len(text_content)*default_h*0.6),int(default_h*1.2)
|
125 |
+
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)
|
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)); d = ImageDraw.Draw(img); padding = 25
|
130 |
+
max_w = size[0] - (2 * padding); lines_for_placeholder = []
|
131 |
+
if not text_description: text_description = "(Placeholder Image)"
|
132 |
+
words_list = text_description.split(); current_line_buffer = ""
|
133 |
+
for word_idx, word_item in enumerate(words_list):
|
134 |
+
prospective_addition = word_item + (" " if word_idx < len(words_list) - 1 else "")
|
135 |
+
test_line_candidate = current_line_buffer + prospective_addition
|
136 |
+
current_w_text, _ = self._get_text_dimensions(test_line_candidate, self.active_font_pil)
|
137 |
+
if current_w_text == 0 and test_line_candidate.strip(): current_w_text = len(test_line_candidate) * (self.active_font_size_pil * 0.6)
|
138 |
+
if current_w_text <= max_w: current_line_buffer = test_line_candidate
|
139 |
else:
|
140 |
+
if current_line_buffer.strip(): lines_for_placeholder.append(current_line_buffer.strip())
|
141 |
+
current_line_buffer = prospective_addition
|
142 |
+
if current_line_buffer.strip(): lines_for_placeholder.append(current_line_buffer.strip())
|
143 |
+
if not lines_for_placeholder and text_description:
|
144 |
+
avg_char_w_est, _ = self._get_text_dimensions("W", self.active_font_pil); avg_char_w_est = avg_char_w_est or (self.active_font_size_pil * 0.6)
|
145 |
+
chars_per_line_est = int(max_w / avg_char_w_est) if avg_char_w_est > 0 else 20
|
146 |
+
lines_for_placeholder.append(text_description[:chars_per_line_est] + ("..." if len(text_description) > chars_per_line_est else ""))
|
147 |
+
elif not lines_for_placeholder: lines_for_placeholder.append("(Placeholder Error)")
|
148 |
+
_, single_h = self._get_text_dimensions("Ay", self.active_font_pil); single_h = single_h if single_h > 0 else self.active_font_size_pil + 2
|
149 |
+
max_l = min(len(lines_for_placeholder), (size[1] - (2 * padding)) // (single_h + 2)) if single_h > 0 else 1; max_l = max(1, max_l)
|
150 |
+
y_p = padding + (size[1] - (2 * padding) - max_l * (single_h + 2)) / 2.0
|
151 |
+
for i_line in range(max_l):
|
152 |
+
line_txt_content = lines_for_placeholder[i_line]; line_w_val, _ = self._get_text_dimensions(line_txt_content, self.active_font_pil)
|
153 |
+
if line_w_val == 0 and line_txt_content.strip(): line_w_val = len(line_txt_content) * (self.active_font_size_pil * 0.6)
|
154 |
+
x_p = (size[0] - line_w_val) / 2.0
|
155 |
+
try: d.text((x_p, y_p), line_txt_content, font=self.active_font_pil, fill=(200, 200, 180))
|
156 |
+
except Exception as e_draw: logger.error(f"Pillow d.text error: {e_draw} for '{line_txt_content}'")
|
157 |
+
y_p += single_h + 2
|
158 |
+
if i_line == 6 and max_l > 7:
|
159 |
+
try: d.text((x_p, y_p), "...", font=self.active_font_pil, fill=(200, 200, 180))
|
160 |
+
except Exception as e_elip: logger.error(f"Pillow d.text ellipsis error: {e_elip}"); break
|
161 |
+
filepath_placeholder = os.path.join(self.output_dir, filename)
|
162 |
+
try: img.save(filepath_placeholder); return filepath_placeholder
|
163 |
+
except Exception as e_save: logger.error(f"Saving placeholder image '{filepath_placeholder}' error: {e_save}", exc_info=True); return None
|
164 |
|
165 |
+
def _search_pexels_image(self, query_str, output_fn_base):
|
|
|
166 |
if not self.USE_PEXELS or not self.pexels_api_key: return None
|
167 |
+
http_headers = {"Authorization": self.pexels_api_key}
|
168 |
+
http_params = {"query": query_str, "per_page": 1, "orientation": "landscape", "size": "large2x"}
|
169 |
+
base_name_px, _ = os.path.splitext(output_fn_base)
|
170 |
+
pexels_fn_str = base_name_px + f"_pexels_{random.randint(1000,9999)}.jpg"
|
171 |
+
file_path_px = os.path.join(self.output_dir, pexels_fn_str)
|
172 |
try:
|
173 |
+
logger.info(f"Pexels: Searching for '{query_str}'")
|
174 |
+
eff_query_px = " ".join(query_str.split()[:5])
|
175 |
+
http_params["query"] = eff_query_px
|
176 |
+
response_px = requests.get("https://api.pexels.com/v1/search", headers=http_headers, params=http_params, timeout=20)
|
177 |
+
response_px.raise_for_status()
|
178 |
+
data_px = response_px.json()
|
179 |
if data_px.get("photos") and len(data_px["photos"]) > 0:
|
180 |
+
photo_details_px = data_px["photos"][0]
|
181 |
+
photo_url_px = photo_details_px.get("src", {}).get("large2x")
|
182 |
+
if not photo_url_px: logger.warning(f"Pexels: 'large2x' URL missing for '{eff_query_px}'. Details: {photo_details_px}"); return None
|
183 |
+
image_response_px = requests.get(photo_url_px, timeout=60); image_response_px.raise_for_status()
|
184 |
+
img_pil_data_px = Image.open(io.BytesIO(image_response_px.content))
|
185 |
+
if img_pil_data_px.mode != 'RGB': img_pil_data_px = img_pil_data_px.convert('RGB')
|
186 |
+
img_pil_data_px.save(file_path_px); logger.info(f"Pexels: Image saved to {file_path_px}"); return file_path_px
|
187 |
+
else: logger.info(f"Pexels: No photos for '{eff_query_px}'."); return None
|
188 |
+
except requests.exceptions.RequestException as e_req_px: logger.error(f"Pexels: RequestException for '{query_str}': {e_req_px}", exc_info=False); return None
|
189 |
+
except Exception as e_px_gen: logger.error(f"Pexels: General error for '{query_str}': {e_px_gen}", exc_info=True); return None
|
190 |
|
191 |
+
def _generate_video_clip_with_runwayml(self, text_prompt_for_motion, input_image_path, scene_identifier_filename_base, target_duration_seconds=5):
|
192 |
+
if not self.USE_RUNWAYML or not self.runway_ml_sdk_client_instance: logger.warning("RunwayML not enabled/client not init. Skip video."); return None
|
193 |
+
if not input_image_path or not os.path.exists(input_image_path): logger.error(f"Runway Gen-4 needs input image. Path invalid: {input_image_path}"); return None
|
194 |
+
image_data_uri_str = self._image_to_data_uri(input_image_path)
|
195 |
+
if not image_data_uri_str: return None
|
196 |
+
runway_dur = 10 if target_duration_seconds >= 8 else 5
|
197 |
+
runway_ratio = self._map_resolution_to_runway_ratio(self.video_frame_size[0], self.video_frame_size[1])
|
198 |
+
base_name_for_runway_vid, _ = os.path.splitext(scene_identifier_filename_base); output_vid_fn = base_name_for_runway_vid + f"_runway_gen4_d{runway_dur}s.mp4"
|
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 |
+
task_submitted_runway = self.runway_ml_sdk_client_instance.image_to_video.create(model='gen4_turbo', prompt_image=image_data_uri_str, prompt_text=text_prompt_for_motion, duration=runway_dur, ratio=runway_ratio)
|
203 |
+
task_id_runway = task_submitted_runway.id; logger.info(f"Runway Gen-4 task ID: {task_id_runway}. Polling...")
|
204 |
+
poll_sec=10; max_poll_count=36; poll_start_time = time.time()
|
205 |
+
while time.time() - poll_start_time < max_poll_count * poll_sec:
|
206 |
+
time.sleep(poll_sec); task_details_runway = self.runway_ml_sdk_client_instance.tasks.retrieve(id=task_id_runway)
|
207 |
+
logger.info(f"Runway task {task_id_runway} status: {task_details_runway.status}")
|
208 |
+
if task_details_runway.status == 'SUCCEEDED':
|
209 |
+
output_url_runway = getattr(getattr(task_details_runway,'output',None),'url',None) or \
|
210 |
+
(getattr(task_details_runway,'artifacts',None) and task_details_runway.artifacts and hasattr(task_details_runway.artifacts[0],'url')and task_details_runway.artifacts[0].url) or \
|
211 |
+
(getattr(task_details_runway,'artifacts',None) and task_details_runway.artifacts and hasattr(task_details_runway.artifacts[0],'download_url')and task_details_runway.artifacts[0].download_url)
|
212 |
+
if not output_url_runway: logger.error(f"Runway task {task_id_runway} SUCCEEDED, but no output URL. Details: {vars(task_details_runway) if hasattr(task_details_runway,'__dict__') else task_details_runway}"); return None
|
213 |
+
logger.info(f"Runway task {task_id_runway} SUCCEEDED. Downloading: {output_url_runway}")
|
214 |
+
video_resp_get = requests.get(output_url_runway, stream=True, timeout=300); video_resp_get.raise_for_status()
|
215 |
+
with open(output_vid_fp,'wb') as f_vid:
|
216 |
+
for chunk_data in video_resp_get.iter_content(chunk_size=8192): f_vid.write(chunk_data)
|
217 |
+
logger.info(f"Runway Gen-4 video saved: {output_vid_fp}"); return output_vid_fp
|
218 |
+
elif task_details_runway.status in ['FAILED','ABORTED','ERROR']:
|
219 |
+
err_msg_runway = getattr(task_details_runway,'error_message',None) or getattr(getattr(task_details_runway,'output',None),'error',"Unknown Runway error.")
|
220 |
+
logger.error(f"Runway task {task_id_runway} status: {task_details_runway.status}. Error: {err_msg_runway}"); return None
|
221 |
+
logger.warning(f"Runway task {task_id_runway} timed out."); return None
|
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, text_desc_ph, filename_ph, duration_ph=4, size_ph=None):
|
226 |
+
if size_ph is None: size_ph = self.video_frame_size
|
227 |
+
filepath_ph = os.path.join(self.output_dir, filename_ph)
|
228 |
+
text_clip_ph = None
|
229 |
+
try:
|
230 |
+
text_clip_ph = TextClip(text_desc_ph, fontsize=50, color='white', font=self.video_overlay_font,
|
231 |
+
bg_color='black', size=size_ph, method='caption').set_duration(duration_ph)
|
232 |
+
text_clip_ph.write_videofile(filepath_ph, fps=24, codec='libx264', preset='ultrafast', logger=None, threads=2)
|
233 |
+
logger.info(f"Generic placeholder video created: {filepath_ph}")
|
234 |
+
return filepath_ph
|
235 |
+
except Exception as e_ph_vid:
|
236 |
+
logger.error(f"Failed to create generic placeholder video '{filepath_ph}': {e_ph_vid}", exc_info=True)
|
237 |
+
return None
|
238 |
finally:
|
239 |
+
if text_clip_ph and hasattr(text_clip_ph, 'close'):
|
240 |
+
try: text_clip_ph.close()
|
241 |
except Exception as e_cl_phv: logger.warning(f"Ignoring error closing placeholder TextClip: {e_cl_phv}")
|
242 |
|
243 |
+
def generate_scene_asset(self, image_generation_prompt_text, motion_prompt_text_for_video,
|
244 |
+
scene_data_dict, scene_identifier_fn_base,
|
245 |
+
generate_as_video_clip_flag=False, runway_target_dur_val=5):
|
246 |
+
base_name_asset, _ = os.path.splitext(scene_identifier_fn_base)
|
247 |
+
asset_info_result = {'path': None, 'type': 'none', 'error': True, 'prompt_used': image_generation_prompt_text, 'error_message': 'Asset generation init failed'}
|
248 |
+
path_for_input_image_runway = None
|
249 |
+
fn_for_base_image = base_name_asset + ("_base_for_video.png" if generate_as_video_clip_flag else ".png")
|
250 |
+
fp_for_base_image = os.path.join(self.output_dir, fn_for_base_image)
|
251 |
if self.USE_AI_IMAGE_GENERATION and self.openai_api_key:
|
252 |
+
max_r_dalle, attempt_count_dalle = 2,0;
|
253 |
+
for att_n_dalle in range(max_r_dalle):
|
254 |
+
attempt_count_dalle = att_n_dalle + 1
|
255 |
+
try:
|
256 |
+
logger.info(f"Att {attempt_count_dalle} DALL-E (base img): {image_generation_prompt_text[:70]}..."); oai_cl = openai.OpenAI(api_key=self.openai_api_key,timeout=90.0); oai_r = oai_cl.images.generate(model=self.dalle_model,prompt=image_generation_prompt_text,n=1,size=self.image_size_dalle3,quality="hd",response_format="url",style="vivid"); oai_iu = oai_r.data[0].url; oai_rp = getattr(oai_r.data[0],'revised_prompt',None);
|
257 |
+
if oai_rp: logger.info(f"DALL-E revised: {oai_rp[:70]}...")
|
258 |
+
oai_ir = requests.get(oai_iu,timeout=120); oai_ir.raise_for_status(); oai_id = Image.open(io.BytesIO(oai_ir.content));
|
259 |
+
if oai_id.mode!='RGB': oai_id=oai_id.convert('RGB')
|
260 |
+
oai_id.save(fp_for_base_image); logger.info(f"DALL-E base img saved: {fp_for_base_image}"); path_for_input_image_runway=fp_for_base_image; asset_info_result={'path':fp_for_base_image,'type':'image','error':False,'prompt_used':image_generation_prompt_text,'revised_prompt':oai_rp}; break
|
261 |
+
except openai.RateLimitError as e_oai_rl: logger.warning(f"OpenAI RateLimit Att {attempt_count_dalle}:{e_oai_rl}.Retry...");time.sleep(5*attempt_count_dalle);asset_info_result['error_message']=str(e_oai_rl)
|
262 |
+
except openai.APIError as e_oai_api: logger.error(f"OpenAI APIError Att {attempt_count_dalle}:{e_oai_api}");asset_info_result['error_message']=str(e_oai_api);break
|
263 |
+
except requests.exceptions.RequestException as e_oai_req: logger.error(f"Requests Err DALL-E Att {attempt_count_dalle}:{e_oai_req}");asset_info_result['error_message']=str(e_oai_req);break
|
264 |
+
except Exception as e_oai_gen: logger.error(f"General DALL-E Err Att {attempt_count_dalle}:{e_oai_gen}",exc_info=True);asset_info_result['error_message']=str(e_oai_gen);break
|
265 |
+
if asset_info_result['error']: logger.warning(f"DALL-E failed after {attempt_count_dalle} attempts for base img.")
|
266 |
+
if asset_info_result['error'] and self.USE_PEXELS:
|
267 |
+
logger.info("Trying Pexels for base img.");px_qt=scene_data_dict.get('pexels_search_query_감독',f"{scene_data_dict.get('emotional_beat','')} {scene_data_dict.get('setting_description','')}");px_pp=self._search_pexels_image(px_qt,fn_for_base_image);
|
268 |
+
if px_pp:path_for_input_image_runway=px_pp;asset_info_result={'path':px_pp,'type':'image','error':False,'prompt_used':f"Pexels:{px_qt}"}
|
269 |
+
else:current_em_px=asset_info_result.get('error_message',"");asset_info_result['error_message']=(current_em_px+" Pexels failed for base.").strip()
|
270 |
+
if asset_info_result['error']:
|
271 |
+
logger.warning("Base img (DALL-E/Pexels) failed. Using placeholder.");ph_ppt=asset_info_result.get('prompt_used',image_generation_prompt_text);php=self._create_placeholder_image_content(f"[Base Placeholder]{ph_ppt[:70]}...",fn_for_base_image);
|
272 |
+
if php:path_for_input_image_runway=php;asset_info_result={'path':php,'type':'image','error':False,'prompt_used':ph_ppt}
|
273 |
+
else:current_em_ph=asset_info_result.get('error_message',"");asset_info_result['error_message']=(current_em_ph+" Base placeholder failed.").strip()
|
274 |
+
if generate_as_video_clip_flag:
|
275 |
+
if not path_for_input_image_runway:logger.error("RunwayML video: base img failed.");asset_info_result['error']=True;asset_info_result['error_message']=(asset_info_result.get('error_message',"")+" Base img miss, Runway abort.").strip();asset_info_result['type']='none';return asset_info_result
|
276 |
if self.USE_RUNWAYML:
|
277 |
+
runway_video_p=self._generate_video_clip_with_runwayml(motion_prompt_text_for_video,path_for_input_image_runway,base_name_asset,runway_target_dur_val)
|
278 |
+
if runway_video_p and os.path.exists(runway_video_p):asset_info_result={'path':runway_video_p,'type':'video','error':False,'prompt_used':motion_prompt_text_for_video,'base_image_path':path_for_input_image_runway}
|
279 |
+
else:logger.warning(f"RunwayML video failed for {base_name_asset}. Fallback to base img.");asset_info_result['error']=True;asset_info_result['error_message']=(asset_info_result.get('error_message',"Base img ok.")+" RunwayML video fail; use base img.").strip();asset_info_result['path']=path_for_input_image_runway;asset_info_result['type']='image';asset_info_result['prompt_used']=image_generation_prompt_text
|
280 |
+
else:logger.warning("RunwayML selected but disabled. Use base img.");asset_info_result['error']=True;asset_info_result['error_message']=(asset_info_result.get('error_message',"Base img ok.")+" RunwayML disabled; use base img.").strip();asset_info_result['path']=path_for_input_image_runway;asset_info_result['type']='image';asset_info_result['prompt_used']=image_generation_prompt_text
|
281 |
+
return asset_info_result
|
282 |
|
283 |
+
def generate_narration_audio(self, text_to_narrate, output_filename="narration_overall.mp3"):
|
284 |
+
if not self.USE_ELEVENLABS or not self.elevenlabs_client_instance or not text_to_narrate: logger.info("11L conditions not met. Skip audio."); return None
|
285 |
+
audio_filepath_narration = os.path.join(self.output_dir, output_filename)
|
|
|
286 |
try:
|
287 |
+
logger.info(f"Generating 11L audio (Voice ID: {self.elevenlabs_voice_id}) for text: \"{text_to_narrate[:70]}...\"")
|
288 |
+
audio_stream_method_11l = None
|
289 |
+
if hasattr(self.elevenlabs_client_instance, 'text_to_speech') and hasattr(self.elevenlabs_client_instance.text_to_speech, 'stream'): audio_stream_method_11l = self.elevenlabs_client_instance.text_to_speech.stream; logger.info("Using 11L SDK: client.text_to_speech.stream()")
|
290 |
+
elif hasattr(self.elevenlabs_client_instance, 'generate_stream'): audio_stream_method_11l = self.elevenlabs_client_instance.generate_stream; logger.info("Using 11L SDK: client.generate_stream()")
|
291 |
+
elif hasattr(self.elevenlabs_client_instance, 'generate'):
|
292 |
+
logger.info("Using 11L SDK: client.generate() (non-streaming).")
|
293 |
+
voice_param_11l = str(self.elevenlabs_voice_id);
|
294 |
+
if Voice and self.elevenlabs_voice_settings_obj: voice_param_11l = Voice(voice_id=str(self.elevenlabs_voice_id), settings=self.elevenlabs_voice_settings_obj)
|
295 |
+
audio_bytes_data = self.elevenlabs_client_instance.generate(text=text_to_narrate, voice=voice_param_11l, model="eleven_multilingual_v2")
|
296 |
+
with open(audio_filepath_narration, "wb") as audio_file_out: audio_file_out.write(audio_bytes_data)
|
297 |
+
logger.info(f"11L audio (non-streamed) saved to: {audio_filepath_narration}"); return audio_filepath_narration
|
298 |
+
else: logger.error("No recognized audio generation method on 11L client."); return None
|
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, 'model_dump'): params_for_voice_stream["voice_settings"] = self.elevenlabs_voice_settings_obj.model_dump()
|
303 |
+
elif hasattr(self.elevenlabs_voice_settings_obj, 'dict'): params_for_voice_stream["voice_settings"] = self.elevenlabs_voice_settings_obj.dict()
|
304 |
+
else: params_for_voice_stream["voice_settings"] = self.elevenlabs_voice_settings_obj
|
305 |
+
audio_data_iterator_11l = audio_stream_method_11l(text=text_to_narrate, model_id="eleven_multilingual_v2", **params_for_voice_stream)
|
306 |
+
with open(audio_filepath_narration, "wb") as audio_file_out_stream:
|
307 |
+
for audio_chunk_data in audio_data_iterator_11l:
|
308 |
+
if audio_chunk_data: audio_file_out_stream.write(audio_chunk_data)
|
309 |
+
logger.info(f"11L audio (streamed) saved to: {audio_filepath_narration}"); return audio_filepath_narration
|
310 |
+
except AttributeError as ae_11l_sdk: logger.error(f"AttributeError with 11L SDK client: {ae_11l_sdk}. SDK version/methods might differ.", exc_info=True); return None
|
311 |
+
except Exception as e_11l_general_audio: logger.error(f"General error during 11L audio generation: {e_11l_general_audio}", exc_info=True); return None
|
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}.")
|
|
|
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 |
pil_img_original = Image.open(path_of_asset)
|
|
|
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 |
debug_path_img_pre_numpy = os.path.join(self.output_dir,f"debug_4_PRE_NUMPY_RGB_S{num_of_scene}.png");
|
356 |
final_rgb_image_for_pil.save(debug_path_img_pre_numpy);
|
357 |
+
logger.info(f"CRITICAL DEBUG: Saved PRE_NUMPY_RGB_S{num_of_scene} to {debug_path_img_pre_numpy}")
|
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 |
debug_path_moviepy_frame = os.path.join(self.output_dir,f"debug_7_MOVIEPY_FRAME_S{num_of_scene}.png")
|
368 |
+
# <<< CORRECTED TRY-EXCEPT BLOCK FOR save_frame >>>
|
369 |
+
try:
|
370 |
+
save_frame_time = min(0.1, base_image_clip_mvpy.duration / 2 if base_image_clip_mvpy.duration > 0 else 0.1)
|
371 |
+
base_image_clip_mvpy.save_frame(debug_path_moviepy_frame, t=save_frame_time)
|
372 |
+
logger.info(f"CRITICAL DEBUG: Saved frame FROM MOVIEPY ImageClip S{num_of_scene} to {debug_path_moviepy_frame}")
|
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 |
fx_image_clip_mvpy = base_image_clip_mvpy
|
378 |
try:
|
|
|
382 |
except Exception as e_kb_fx_loop: logger.error(f"S{num_of_scene} Ken Burns error: {e_kb_fx_loop}", exc_info=False)
|
383 |
active_scene_clip = fx_image_clip_mvpy
|
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 |
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 |
if active_scene_clip and action_in_key:
|
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; start_text_overlay_val=0.25
|
|
|
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 |
+
# Continue was removed to ensure loop proceeds, error is logged above. If continue is desired, it must be inside the try.
|
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:
|