Update core/visual_engine.py
Browse files- core/visual_engine.py +206 -256
core/visual_engine.py
CHANGED
@@ -1,7 +1,7 @@
|
|
1 |
# core/visual_engine.py
|
2 |
from PIL import Image, ImageDraw, ImageFont, ImageOps
|
3 |
import base64
|
4 |
-
import mimetypes
|
5 |
import numpy as np
|
6 |
import os
|
7 |
import openai # OpenAI v1.x.x+
|
@@ -11,42 +11,36 @@ import time
|
|
11 |
import random
|
12 |
import logging
|
13 |
|
14 |
-
# --- MoviePy Imports ---
|
15 |
from moviepy.editor import (ImageClip, VideoFileClip, concatenate_videoclips, TextClip,
|
16 |
CompositeVideoClip, AudioFileClip)
|
17 |
import moviepy.video.fx.all as vfx
|
18 |
|
19 |
-
#
|
20 |
-
|
21 |
-
if hasattr(Image, 'Resampling') and hasattr(Image.Resampling, 'LANCZOS'): # Pillow 9+
|
22 |
if not hasattr(Image, 'ANTIALIAS'): Image.ANTIALIAS = Image.Resampling.LANCZOS
|
23 |
-
elif hasattr(Image, 'LANCZOS'):
|
24 |
if not hasattr(Image, 'ANTIALIAS'): Image.ANTIALIAS = Image.LANCZOS
|
25 |
elif not hasattr(Image, 'ANTIALIAS'):
|
26 |
-
print("WARNING: Pillow version lacks common Resampling
|
27 |
-
except Exception as
|
28 |
-
print(f"WARNING: An unexpected error occurred during Pillow ANTIALIAS monkey-patch: {e_monkey_patch}")
|
29 |
|
30 |
logger = logging.getLogger(__name__)
|
31 |
-
# logger.setLevel(logging.DEBUG) # Uncomment for
|
32 |
|
33 |
-
# --- External Service Client Imports ---
|
34 |
ELEVENLABS_CLIENT_IMPORTED = False; ElevenLabsAPIClient = None; Voice = None; VoiceSettings = None
|
35 |
try:
|
36 |
from elevenlabs.client import ElevenLabs as ImportedElevenLabsClient
|
37 |
from elevenlabs import Voice as ImportedVoice, VoiceSettings as ImportedVoiceSettings
|
38 |
ElevenLabsAPIClient = ImportedElevenLabsClient; Voice = ImportedVoice; VoiceSettings = ImportedVoiceSettings
|
39 |
-
ELEVENLABS_CLIENT_IMPORTED = True; logger.info("ElevenLabs client components
|
40 |
-
except
|
41 |
-
except Exception as e_eleven_import_general: logger.warning(f"General error importing ElevenLabs client components: {e_eleven_import_general}. Audio generation disabled.")
|
42 |
|
43 |
RUNWAYML_SDK_IMPORTED = False; RunwayMLAPIClientClass = None
|
44 |
try:
|
45 |
from runwayml import RunwayML as ImportedRunwayMLAPIClientClass
|
46 |
RunwayMLAPIClientClass = ImportedRunwayMLAPIClientClass; RUNWAYML_SDK_IMPORTED = True
|
47 |
-
logger.info("RunwayML SDK
|
48 |
-
except
|
49 |
-
except Exception as e_runway_sdk_import_general: logger.warning(f"General error importing RunwayML SDK: {e_runway_sdk_import_general}. RunwayML features disabled.")
|
50 |
|
51 |
|
52 |
class VisualEngine:
|
@@ -57,12 +51,12 @@ class VisualEngine:
|
|
57 |
def __init__(self, output_dir="temp_cinegen_media", default_elevenlabs_voice_id="Rachel"):
|
58 |
self.output_dir = output_dir; os.makedirs(self.output_dir, exist_ok=True)
|
59 |
self.font_filename_pil_preference = "DejaVuSans-Bold.ttf"
|
60 |
-
|
61 |
-
self.resolved_font_path_pil = next((p for p in
|
62 |
self.active_font_pil = ImageFont.load_default(); self.active_font_size_pil = self.DEFAULT_FONT_SIZE_PIL; self.active_moviepy_font_name = self.DEFAULT_MOVIEPY_FONT
|
63 |
if self.resolved_font_path_pil:
|
64 |
try: self.active_font_pil = ImageFont.truetype(self.resolved_font_path_pil, self.PREFERRED_FONT_SIZE_PIL); self.active_font_size_pil = self.PREFERRED_FONT_SIZE_PIL; logger.info(f"Pillow font: {self.resolved_font_path_pil} sz {self.active_font_size_pil}."); self.active_moviepy_font_name = 'DejaVu-Sans-Bold' if "dejavu" in self.resolved_font_path_pil.lower() else ('Liberation-Sans-Bold' if "liberation" in self.resolved_font_path_pil.lower() else self.DEFAULT_MOVIEPY_FONT)
|
65 |
-
except IOError as
|
66 |
else: logger.warning("Preferred Pillow font not found. Default.")
|
67 |
self.openai_api_key = None; self.USE_AI_IMAGE_GENERATION = False; self.dalle_model = "dall-e-3"; self.image_size_dalle3 = "1792x1024"
|
68 |
self.video_frame_size = (1280, 720)
|
@@ -73,274 +67,230 @@ class VisualEngine:
|
|
73 |
self.runway_api_key = None; self.USE_RUNWAYML = False; self.runway_ml_sdk_client_instance = None
|
74 |
if RUNWAYML_SDK_IMPORTED and RunwayMLAPIClientClass and os.getenv("RUNWAYML_API_SECRET"):
|
75 |
try: self.runway_ml_sdk_client_instance = RunwayMLAPIClientClass(); self.USE_RUNWAYML = True; logger.info("RunwayML Client init from env var at startup.")
|
76 |
-
except Exception as
|
77 |
logger.info("VisualEngine initialized.")
|
78 |
|
79 |
-
def set_openai_api_key(self,
|
80 |
-
def set_elevenlabs_api_key(self,
|
81 |
-
self.elevenlabs_api_key
|
82 |
-
if
|
83 |
-
if
|
84 |
-
try: self.elevenlabs_client_instance = ElevenLabsAPIClient(api_key=
|
85 |
-
except Exception as
|
86 |
else: self.USE_ELEVENLABS = False; logger.info(f"11L Disabled (key/SDK).")
|
87 |
-
def set_pexels_api_key(self,
|
88 |
-
def set_runway_api_key(self,
|
89 |
-
self.runway_api_key =
|
90 |
-
if
|
91 |
if RUNWAYML_SDK_IMPORTED and RunwayMLAPIClientClass:
|
92 |
if not self.runway_ml_sdk_client_instance:
|
93 |
try:
|
94 |
-
|
95 |
-
if not
|
96 |
-
self.runway_ml_sdk_client_instance
|
97 |
-
if not
|
98 |
-
except Exception as
|
99 |
-
else: self.USE_RUNWAYML
|
100 |
-
else: logger.warning("RunwayML SDK not imported.
|
101 |
-
else: self.USE_RUNWAYML
|
102 |
|
103 |
-
def _image_to_data_uri(self,
|
104 |
-
# <<< CORRECTED METHOD >>>
|
105 |
try:
|
106 |
-
|
107 |
-
if not
|
108 |
-
|
109 |
-
|
110 |
-
|
111 |
-
|
112 |
-
|
113 |
-
|
114 |
-
with open(image_path, "rb") as image_file:
|
115 |
-
encoded_string = base64.b64encode(image_file.read()).decode('utf-8')
|
116 |
-
|
117 |
-
data_uri = f"data:{mime_type};base64,{encoded_string}"
|
118 |
-
logger.debug(f"Generated data URI for {os.path.basename(image_path)} (MIME: {mime_type}, first 100 chars): {data_uri[:100]}...")
|
119 |
-
return data_uri
|
120 |
-
except FileNotFoundError:
|
121 |
-
logger.error(f"Image file not found at path: {image_path} during data URI conversion.")
|
122 |
-
return None
|
123 |
-
except Exception as e_data_uri:
|
124 |
-
logger.error(f"Error converting image '{image_path}' to data URI: {e_data_uri}", exc_info=True)
|
125 |
-
return None
|
126 |
|
127 |
-
def _map_resolution_to_runway_ratio(self,
|
128 |
-
|
129 |
-
|
130 |
-
|
131 |
-
logger.warning(f"Res {ratio_str} not in Gen-4 list. Default 1280:720.");return "1280:720"
|
132 |
|
133 |
-
def _get_text_dimensions(self,
|
134 |
-
|
135 |
-
|
136 |
-
if not text_content:return 0,dch
|
137 |
try:
|
138 |
-
if hasattr(
|
139 |
-
elif hasattr(
|
140 |
-
else:return int(len(
|
141 |
-
except Exception as
|
142 |
|
143 |
-
def _create_placeholder_image_content(self,
|
144 |
-
# (Corrected
|
145 |
-
if
|
146 |
-
|
147 |
-
|
148 |
-
|
149 |
-
|
150 |
-
|
151 |
-
|
152 |
-
|
153 |
-
current_w_text, _ = self._get_text_dimensions(test_line_candidate, self.active_font_pil)
|
154 |
-
if current_w_text == 0 and test_line_candidate.strip(): current_w_text = len(test_line_candidate) * (self.active_font_size_pil * 0.6)
|
155 |
-
if current_w_text <= max_w: current_line_buffer = test_line_candidate
|
156 |
else:
|
157 |
-
if
|
158 |
-
|
159 |
-
if
|
160 |
-
if not
|
161 |
-
|
162 |
-
|
163 |
-
|
164 |
-
|
165 |
-
|
166 |
-
|
167 |
-
|
168 |
-
|
169 |
-
|
170 |
-
|
171 |
-
|
172 |
-
|
173 |
-
|
174 |
-
|
175 |
-
|
176 |
-
|
177 |
-
|
178 |
-
|
179 |
-
|
180 |
-
except Exception as e_save: logger.error(f"Saving placeholder image '{filepath_placeholder}' error: {e_save}", exc_info=True); return None
|
181 |
|
182 |
-
def _search_pexels_image(self,
|
183 |
-
# (Corrected
|
184 |
if not self.USE_PEXELS or not self.pexels_api_key: return None
|
185 |
-
|
186 |
-
|
187 |
-
base_name_px, _ = os.path.splitext(output_fn_base)
|
188 |
-
pexels_fn_str = base_name_px + f"_pexels_{random.randint(1000,9999)}.jpg"
|
189 |
-
file_path_px = os.path.join(self.output_dir, pexels_fn_str)
|
190 |
try:
|
191 |
-
logger.info(f"Pexels:
|
192 |
-
|
193 |
-
http_params["query"] = eff_query_px
|
194 |
-
response_px = requests.get("https://api.pexels.com/v1/search", headers=http_headers, params=http_params, timeout=20)
|
195 |
-
response_px.raise_for_status()
|
196 |
-
data_px = response_px.json()
|
197 |
if data_px.get("photos") and len(data_px["photos"]) > 0:
|
198 |
-
|
199 |
-
|
200 |
-
|
201 |
-
|
202 |
-
|
203 |
-
|
204 |
-
|
205 |
-
|
206 |
-
except requests.exceptions.RequestException as e_req_px: logger.error(f"Pexels: RequestException for '{query_str}': {e_req_px}", exc_info=False); return None
|
207 |
-
except Exception as e_px_gen: logger.error(f"Pexels: General error for '{query_str}': {e_px_gen}", exc_info=True); return None
|
208 |
|
209 |
-
def _generate_video_clip_with_runwayml(self,
|
210 |
-
# (Updated RunwayML integration
|
211 |
-
if not self.USE_RUNWAYML or not self.runway_ml_sdk_client_instance: logger.warning("RunwayML
|
212 |
-
if not
|
213 |
-
|
214 |
-
if not
|
215 |
-
|
216 |
-
|
217 |
-
|
218 |
-
output_vid_fp = os.path.join(self.output_dir, output_vid_fn)
|
219 |
-
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}'")
|
220 |
try:
|
221 |
-
|
222 |
-
|
223 |
-
|
224 |
-
while time.time()
|
225 |
-
time.sleep(
|
226 |
-
logger.info(f"Runway task {
|
227 |
-
if
|
228 |
-
|
229 |
-
|
230 |
-
|
231 |
-
|
232 |
-
|
233 |
-
|
234 |
-
|
235 |
-
|
236 |
-
|
237 |
-
|
238 |
-
|
239 |
-
|
240 |
-
|
241 |
-
except AttributeError as ae_sdk: logger.error(f"RunwayML SDK AttrError: {ae_sdk}. SDK/methods changed?", exc_info=True); return None
|
242 |
-
except Exception as e_runway_gen: logger.error(f"Runway Gen-4 API error: {e_runway_gen}", exc_info=True); return None
|
243 |
|
244 |
-
def _create_placeholder_video_content(self,
|
245 |
-
#
|
246 |
-
if
|
247 |
-
|
248 |
-
|
249 |
try:
|
250 |
-
|
251 |
-
bg_color='black', size=
|
252 |
-
|
253 |
-
logger.info(f"Generic placeholder video created: {
|
254 |
-
return
|
255 |
-
except Exception as
|
256 |
-
logger.error(f"Failed to create generic placeholder video '{
|
257 |
return None
|
258 |
finally:
|
259 |
-
if
|
260 |
-
try:
|
261 |
-
except Exception as
|
262 |
|
263 |
-
def generate_scene_asset(self,
|
264 |
-
|
265 |
-
|
266 |
-
|
267 |
-
base_name_asset, _ = os.path.splitext(scene_identifier_fn_base)
|
268 |
-
asset_info_result = {'path': None, 'type': 'none', 'error': True, 'prompt_used': image_generation_prompt_text, 'error_message': 'Asset generation init failed'}
|
269 |
-
path_for_input_image_runway = None
|
270 |
-
fn_for_base_image = base_name_asset + ("_base_for_video.png" if generate_as_video_clip_flag else ".png")
|
271 |
-
fp_for_base_image = os.path.join(self.output_dir, fn_for_base_image)
|
272 |
if self.USE_AI_IMAGE_GENERATION and self.openai_api_key:
|
273 |
-
|
274 |
-
for
|
275 |
-
|
276 |
-
try:
|
277 |
-
logger.info(f"Att {
|
278 |
-
if
|
279 |
-
|
280 |
-
if
|
281 |
-
|
282 |
-
except openai.RateLimitError as
|
283 |
-
except openai.APIError as
|
284 |
-
except requests.exceptions.RequestException as
|
285 |
-
except Exception as
|
286 |
-
if
|
287 |
-
if
|
288 |
-
logger.info("Trying Pexels for base img.");
|
289 |
-
if
|
290 |
-
else:
|
291 |
-
if
|
292 |
-
logger.warning("Base img (DALL-E/Pexels) failed. Using placeholder.");
|
293 |
-
if
|
294 |
-
else:
|
295 |
-
if
|
296 |
-
if not
|
297 |
if self.USE_RUNWAYML:
|
298 |
-
|
299 |
-
if
|
300 |
-
else:logger.warning(f"RunwayML video failed for {
|
301 |
-
else:logger.warning("RunwayML selected but disabled. Use base img.");
|
302 |
-
return
|
303 |
|
304 |
-
def generate_narration_audio(self,
|
305 |
-
#
|
306 |
-
if not self.USE_ELEVENLABS or not self.elevenlabs_client_instance or not
|
307 |
-
|
308 |
-
return None
|
309 |
-
audio_filepath_narration = os.path.join(self.output_dir, output_filename)
|
310 |
try:
|
311 |
-
logger.info(f"
|
312 |
-
|
313 |
-
if hasattr(self.elevenlabs_client_instance,
|
314 |
-
|
315 |
-
elif hasattr(self.elevenlabs_client_instance,
|
316 |
-
|
317 |
-
|
318 |
-
|
319 |
-
|
320 |
-
|
321 |
-
|
322 |
-
|
323 |
-
logger.info(f"ElevenLabs audio (non-streamed) saved successfully to: {audio_filepath_narration}"); return audio_filepath_narration
|
324 |
-
else: logger.error("No recognized audio generation method found on the ElevenLabs client instance."); return None
|
325 |
-
|
326 |
-
if audio_stream_method_11l:
|
327 |
-
params_for_voice_stream = {"voice_id": str(self.elevenlabs_voice_id)}
|
328 |
if self.elevenlabs_voice_settings_obj:
|
329 |
-
if hasattr(self.elevenlabs_voice_settings_obj,
|
330 |
-
elif hasattr(self.elevenlabs_voice_settings_obj,
|
331 |
-
else:
|
332 |
-
|
333 |
-
with open(
|
334 |
-
for
|
335 |
-
if
|
336 |
-
logger.info(f"
|
337 |
-
except AttributeError as
|
338 |
-
except Exception as
|
339 |
|
340 |
def assemble_animatic_from_assets(self, asset_data_list, overall_narration_path=None, output_filename="final_video.mp4", fps=24):
|
341 |
-
# (Keep
|
|
|
342 |
if not asset_data_list: logger.warning("No assets for animatic."); return None
|
343 |
-
|
344 |
logger.info(f"Assembling from {len(asset_data_list)} assets. Target Frame: {self.video_frame_size}.")
|
345 |
for i_asset, asset_info_item_loop in enumerate(asset_data_list):
|
346 |
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)
|
|
|
1 |
# core/visual_engine.py
|
2 |
from PIL import Image, ImageDraw, ImageFont, ImageOps
|
3 |
import base64
|
4 |
+
import mimetypes
|
5 |
import numpy as np
|
6 |
import os
|
7 |
import openai # OpenAI v1.x.x+
|
|
|
11 |
import random
|
12 |
import logging
|
13 |
|
|
|
14 |
from moviepy.editor import (ImageClip, VideoFileClip, concatenate_videoclips, TextClip,
|
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'):
|
|
|
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: print(f"WARNING: ANTIALIAS monkey-patch error: {e_mp}")
|
|
|
26 |
|
27 |
logger = logging.getLogger(__name__)
|
28 |
+
# logger.setLevel(logging.DEBUG) # Uncomment for maximum verbosity
|
29 |
|
|
|
30 |
ELEVENLABS_CLIENT_IMPORTED = False; ElevenLabsAPIClient = None; Voice = None; VoiceSettings = None
|
31 |
try:
|
32 |
from elevenlabs.client import ElevenLabs as ImportedElevenLabsClient
|
33 |
from elevenlabs import Voice as ImportedVoice, VoiceSettings as ImportedVoiceSettings
|
34 |
ElevenLabsAPIClient = ImportedElevenLabsClient; Voice = ImportedVoice; VoiceSettings = ImportedVoiceSettings
|
35 |
+
ELEVENLABS_CLIENT_IMPORTED = True; logger.info("ElevenLabs client components imported.")
|
36 |
+
except Exception as e_11l_imp: logger.warning(f"ElevenLabs client import failed: {e_11l_imp}. Audio disabled.")
|
|
|
37 |
|
38 |
RUNWAYML_SDK_IMPORTED = False; RunwayMLAPIClientClass = None
|
39 |
try:
|
40 |
from runwayml import RunwayML as ImportedRunwayMLAPIClientClass
|
41 |
RunwayMLAPIClientClass = ImportedRunwayMLAPIClientClass; RUNWAYML_SDK_IMPORTED = True
|
42 |
+
logger.info("RunwayML SDK imported.")
|
43 |
+
except Exception as e_rwy_imp: logger.warning(f"RunwayML SDK import failed: {e_rwy_imp}. RunwayML disabled.")
|
|
|
44 |
|
45 |
|
46 |
class VisualEngine:
|
|
|
51 |
def __init__(self, output_dir="temp_cinegen_media", default_elevenlabs_voice_id="Rachel"):
|
52 |
self.output_dir = output_dir; os.makedirs(self.output_dir, exist_ok=True)
|
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 |
self.active_font_pil = ImageFont.load_default(); self.active_font_size_pil = self.DEFAULT_FONT_SIZE_PIL; self.active_moviepy_font_name = self.DEFAULT_MOVIEPY_FONT
|
57 |
if self.resolved_font_path_pil:
|
58 |
try: self.active_font_pil = ImageFont.truetype(self.resolved_font_path_pil, self.PREFERRED_FONT_SIZE_PIL); self.active_font_size_pil = self.PREFERRED_FONT_SIZE_PIL; logger.info(f"Pillow font: {self.resolved_font_path_pil} sz {self.active_font_size_pil}."); self.active_moviepy_font_name = 'DejaVu-Sans-Bold' if "dejavu" in self.resolved_font_path_pil.lower() else ('Liberation-Sans-Bold' if "liberation" in self.resolved_font_path_pil.lower() else self.DEFAULT_MOVIEPY_FONT)
|
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)
|
|
|
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 |
logger.info("VisualEngine initialized.")
|
72 |
|
73 |
+
def set_openai_api_key(self, k): self.openai_api_key=k; self.USE_AI_IMAGE_GENERATION=bool(k); logger.info(f"DALL-E: {'Ready' if self.USE_AI_IMAGE_GENERATION else 'Disabled'}")
|
74 |
+
def set_elevenlabs_api_key(self, k, vid=None):
|
75 |
+
self.elevenlabs_api_key=k;
|
76 |
+
if vid: self.elevenlabs_voice_id = vid
|
77 |
+
if k and ELEVENLABS_CLIENT_IMPORTED and ElevenLabsAPIClient:
|
78 |
+
try: self.elevenlabs_client_instance = ElevenLabsAPIClient(api_key=k); self.USE_ELEVENLABS=True; logger.info(f"11L Client: Ready (Voice:{self.elevenlabs_voice_id})")
|
79 |
+
except Exception as e: logger.error(f"11L client init err: {e}. 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, k): self.pexels_api_key=k; self.USE_PEXELS=bool(k); logger.info(f"Pexels: {'Ready' if self.USE_PEXELS else 'Disabled'}")
|
82 |
+
def set_runway_api_key(self, k):
|
83 |
+
self.runway_api_key = k
|
84 |
+
if k:
|
85 |
if RUNWAYML_SDK_IMPORTED and RunwayMLAPIClientClass:
|
86 |
if not self.runway_ml_sdk_client_instance:
|
87 |
try:
|
88 |
+
orig_secret = os.getenv("RUNWAYML_API_SECRET")
|
89 |
+
if not orig_secret: os.environ["RUNWAYML_API_SECRET"]=k; 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_key.")
|
91 |
+
if not orig_secret: del os.environ["RUNWAYML_API_SECRET"]; logger.info("Cleared temp RUNWAYML_API_SECRET.")
|
92 |
+
except Exception as e: logger.error(f"RunwayML Client init in set_key fail: {e}", 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. Disabled."); self.USE_RUNWAYML=False
|
95 |
+
else: self.USE_RUNWAYML=False; self.runway_ml_sdk_client_instance=None; logger.info("RunwayML Disabled (no key).")
|
96 |
|
97 |
+
def _image_to_data_uri(self, img_path):
|
|
|
98 |
try:
|
99 |
+
mime, _ = mimetypes.guess_type(img_path)
|
100 |
+
if not mime: ext=os.path.splitext(img_path)[1].lower(); mime_map={".png":"image/png",".jpg":"image/jpeg",".jpeg":"image/jpeg",".webp":"image/webp"}; mime=mime_map.get(ext,"application/octet-stream");
|
101 |
+
if mime=="application/octet-stream": logger.warning(f"Unknown MIME for {img_path}, using {mime}.")
|
102 |
+
with open(img_path,"rb") as f_img: enc_str=base64.b64encode(f_img.read()).decode('utf-8')
|
103 |
+
uri=f"data:{mime};base64,{enc_str}"; logger.debug(f"Data URI for {os.path.basename(img_path)} (MIME:{mime}): {uri[:100]}..."); return uri
|
104 |
+
except FileNotFoundError: logger.error(f"Img not found {img_path} for data URI."); return None
|
105 |
+
except Exception as e: logger.error(f"Error converting {img_path} to data URI:{e}",exc_info=True); return None
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
106 |
|
107 |
+
def _map_resolution_to_runway_ratio(self, w, h):
|
108 |
+
r_str=f"{w}:{h}"; supp_r=["1280:720","720:1280","1104:832","832:1104","960:960","1584:672"];
|
109 |
+
if r_str in supp_r: return r_str
|
110 |
+
logger.warning(f"Res {r_str} not in Gen-4 list. Default 1280:720."); return "1280:720"
|
|
|
111 |
|
112 |
+
def _get_text_dimensions(self, txt, font):
|
113 |
+
dh=getattr(font,'size',self.active_font_size_pil);
|
114 |
+
if not txt: return 0,dh
|
|
|
115 |
try:
|
116 |
+
if hasattr(font,'getbbox'):b=font.getbbox(txt);w=b[2]-b[0];h=b[3]-b[1];return w,h if h>0 else dh
|
117 |
+
elif hasattr(font,'getsize'):w,h=font.getsize(txt);return w,h if h>0 else dh
|
118 |
+
else: return int(len(txt)*dh*0.6),int(dh*1.2)
|
119 |
+
except Exception as e:logger.warning(f"Err _get_text_dimensions:{e}");return int(len(txt)*self.active_font_size_pil*0.6),int(self.active_font_size_pil*1.2)
|
120 |
|
121 |
+
def _create_placeholder_image_content(self, desc, fname, sz=None):
|
122 |
+
# (Corrected and robust placeholder generation)
|
123 |
+
if sz is None: sz=self.video_frame_size; img=Image.new('RGB',sz,color=(20,20,40));drw=ImageDraw.Draw(img);pad=25;maxw=sz[0]-(2*pad);lns=[]
|
124 |
+
if not desc: desc="(Placeholder)"
|
125 |
+
wds=desc.split();curr_ln=""
|
126 |
+
for idx,w in enumerate(wds):
|
127 |
+
prosp_add=w+(" "if idx<len(wds)-1 else"");test_ln=curr_ln+prosp_add
|
128 |
+
curr_w,_=self._get_text_dimensions(test_ln,self.active_font_pil)
|
129 |
+
if curr_w==0 and test_ln.strip():curr_w=len(test_ln)*(self.active_font_size_pil*0.6)
|
130 |
+
if curr_w<=maxw:curr_ln=test_ln
|
|
|
|
|
|
|
131 |
else:
|
132 |
+
if curr_ln.strip():lns.append(curr_ln.strip())
|
133 |
+
curr_ln=prosp_add
|
134 |
+
if curr_ln.strip():lns.append(curr_ln.strip())
|
135 |
+
if not lns and desc:
|
136 |
+
avg_cw,_=self._get_text_dimensions("W",self.active_font_pil);avg_cw=avg_cw or(self.active_font_size_pil*0.6)
|
137 |
+
cpl=int(maxw/avg_cw)if avg_cw>0 else 20;lns.append(desc[:cpl]+("..."if len(desc)>cpl else""))
|
138 |
+
elif not lns:lns.append("(PH Error)")
|
139 |
+
_,slh=self._get_text_dimensions("Ay",self.active_font_pil);slh=slh if slh>0 else self.active_font_size_pil+2
|
140 |
+
maxl=min(len(lns),(sz[1]-(2*pad))//(slh+2))if slh>0 else 1;maxl=max(1,maxl)
|
141 |
+
yp=pad+(sz[1]-(2*pad)-maxl*(slh+2))/2.0
|
142 |
+
for i in range(maxl):
|
143 |
+
lt=lns[i];lw,_=self._get_text_dimensions(lt,self.active_font_pil)
|
144 |
+
if lw==0 and lt.strip():lw=len(lt)*(self.active_font_size_pil*0.6)
|
145 |
+
xp=(sz[0]-lw)/2.0
|
146 |
+
try:drw.text((xp,yp),lt,font=self.active_font_pil,fill=(200,200,180))
|
147 |
+
except Exception as e:logger.error(f"Pillow d.text err:{e} for '{lt}'")
|
148 |
+
yp+=slh+2
|
149 |
+
if i==6 and maxl>7:
|
150 |
+
try:drw.text((xp,yp),"...",font=self.active_font_pil,fill=(200,200,180))
|
151 |
+
except Exception as e:logger.error(f"Pillow ellipsis err:{e}");break
|
152 |
+
fpath=os.path.join(self.output_dir,fname)
|
153 |
+
try:img.save(fpath);return fpath
|
154 |
+
except Exception as e:logger.error(f"Save PH img '{fpath}' err:{e}",exc_info=True);return None
|
|
|
155 |
|
156 |
+
def _search_pexels_image(self, q_str, out_fn_base):
|
157 |
+
# (Corrected from before)
|
158 |
if not self.USE_PEXELS or not self.pexels_api_key: return None
|
159 |
+
h={"Authorization":self.pexels_api_key};p={"query":q_str,"per_page":1,"orientation":"landscape","size":"large2x"}
|
160 |
+
base_n_px,_=os.path.splitext(out_fn_base);px_fn=base_n_px+f"_pexels_{random.randint(1000,9999)}.jpg";fp_px=os.path.join(self.output_dir,px_fn)
|
|
|
|
|
|
|
161 |
try:
|
162 |
+
logger.info(f"Pexels: Search '{q_str}'");eff_q=" ".join(q_str.split()[:5]);p["query"]=eff_q
|
163 |
+
resp_px=requests.get("https://api.pexels.com/v1/search",headers=h,params=p,timeout=20);resp_px.raise_for_status();data_px=resp_px.json()
|
|
|
|
|
|
|
|
|
164 |
if data_px.get("photos") and len(data_px["photos"]) > 0:
|
165 |
+
ph_det=data_px["photos"][0];ph_url=ph_det.get("src",{}).get("large2x")
|
166 |
+
if not ph_url:logger.warning(f"Pexels: 'large2x' URL missing for '{eff_q}'.");return None
|
167 |
+
img_resp=requests.get(ph_url,timeout=60);img_resp.raise_for_status();img_pil=Image.open(io.BytesIO(img_resp.content))
|
168 |
+
if img_pil.mode!='RGB':img_pil=img_pil.convert('RGB')
|
169 |
+
img_pil.save(fp_px);logger.info(f"Pexels: Saved to {fp_px}");return fp_px
|
170 |
+
else:logger.info(f"Pexels: No photos for '{eff_q}'.");return None
|
171 |
+
except requests.exceptions.RequestException as e:logger.error(f"Pexels ReqExc '{q_str}':{e}",exc_info=False);return None
|
172 |
+
except Exception as e:logger.error(f"Pexels GenErr '{q_str}':{e}",exc_info=True);return None
|
|
|
|
|
173 |
|
174 |
+
def _generate_video_clip_with_runwayml(self, motion_prompt, input_img_path, scene_id_base_fn, duration_s=5):
|
175 |
+
# (Updated RunwayML integration logic)
|
176 |
+
if not self.USE_RUNWAYML or not self.runway_ml_sdk_client_instance: logger.warning("RunwayML skip: Not enabled/client not init."); return None
|
177 |
+
if not input_img_path or not os.path.exists(input_img_path): logger.error(f"Runway Gen-4 needs input img. Invalid: {input_img_path}"); return None
|
178 |
+
img_data_uri = self._image_to_data_uri(input_img_path)
|
179 |
+
if not img_data_uri: return None
|
180 |
+
rwy_dur = 10 if duration_s >= 8 else 5; rwy_ratio = self._map_resolution_to_runway_ratio(self.video_frame_size[0],self.video_frame_size[1])
|
181 |
+
rwy_base_name,_=os.path.splitext(scene_id_base_fn);rwy_out_fn=rwy_base_name+f"_runway_gen4_d{rwy_dur}s.mp4";rwy_out_fp=os.path.join(self.output_dir,rwy_out_fn)
|
182 |
+
logger.info(f"Runway Gen-4 task: motion='{motion_prompt[:70]}...', img='{os.path.basename(input_img_path)}', dur={rwy_dur}s, ratio='{rwy_ratio}'")
|
|
|
|
|
183 |
try:
|
184 |
+
rwy_task_sub = self.runway_ml_sdk_client_instance.image_to_video.create(model='gen4_turbo',prompt_image=img_data_uri,prompt_text=motion_prompt,duration=rwy_dur,ratio=rwy_ratio)
|
185 |
+
rwy_task_id = rwy_task_sub.id; logger.info(f"Runway task ID: {rwy_task_id}. Polling...")
|
186 |
+
poll_s=10;max_p_count=36;poll_t_start=time.time()
|
187 |
+
while time.time()-poll_t_start < max_p_count*poll_s:
|
188 |
+
time.sleep(poll_s);rwy_task_det=self.runway_ml_sdk_client_instance.tasks.retrieve(id=rwy_task_id)
|
189 |
+
logger.info(f"Runway task {rwy_task_id} status: {rwy_task_det.status}")
|
190 |
+
if rwy_task_det.status=='SUCCEEDED':
|
191 |
+
rwy_out_url=getattr(getattr(rwy_task_det,'output',None),'url',None) or (getattr(rwy_task_det,'artifacts',None)and rwy_task_det.artifacts and hasattr(rwy_task_det.artifacts[0],'url')and rwy_task_det.artifacts[0].url) or (getattr(rwy_task_det,'artifacts',None)and rwy_task_det.artifacts and hasattr(rwy_task_det.artifacts[0],'download_url')and rwy_task_det.artifacts[0].download_url)
|
192 |
+
if not rwy_out_url:logger.error(f"Runway task {rwy_task_id} SUCCEEDED, no output URL. Details:{vars(rwy_task_det)if hasattr(rwy_task_det,'__dict__')else rwy_task_det}");return None
|
193 |
+
logger.info(f"Runway task {rwy_task_id} SUCCEEDED. Downloading: {rwy_out_url}")
|
194 |
+
vid_resp=requests.get(rwy_out_url,stream=True,timeout=300);vid_resp.raise_for_status()
|
195 |
+
with open(rwy_out_fp,'wb')as f:
|
196 |
+
for chk in vid_resp.iter_content(chunk_size=8192):f.write(chk)
|
197 |
+
logger.info(f"Runway Gen-4 video saved: {rwy_out_fp}");return rwy_out_fp
|
198 |
+
elif rwy_task_det.status in['FAILED','ABORTED','ERROR']:
|
199 |
+
rwy_err_msg=getattr(rwy_task_det,'error_message',None)or getattr(getattr(rwy_task_det,'output',None),'error',"Unknown Runway error.")
|
200 |
+
logger.error(f"Runway task {rwy_task_id} status:{rwy_task_det.status}. Error:{rwy_err_msg}");return None
|
201 |
+
logger.warning(f"Runway task {rwy_task_id} timed out.");return None
|
202 |
+
except AttributeError as e:logger.error(f"RunwayML SDK AttrError:{e}. SDK methods changed?",exc_info=True);return None
|
203 |
+
except Exception as e:logger.error(f"Runway Gen-4 API error:{e}",exc_info=True);return None
|
|
|
|
|
204 |
|
205 |
+
def _create_placeholder_video_content(self, text_desc, fname, duration=4, size=None):
|
206 |
+
# (Corrected from previous)
|
207 |
+
if size is None: size = self.video_frame_size
|
208 |
+
fpath_ph_vid = os.path.join(self.output_dir, fname) # Renamed
|
209 |
+
txt_clip_ph_vid = None # Renamed
|
210 |
try:
|
211 |
+
txt_clip_ph_vid = TextClip(text_desc, fontsize=50, color='white', font=self.video_overlay_font,
|
212 |
+
bg_color='black', size=size, method='caption').set_duration(duration)
|
213 |
+
txt_clip_ph_vid.write_videofile(fpath_ph_vid, fps=24, codec='libx264', preset='ultrafast', logger=None, threads=2)
|
214 |
+
logger.info(f"Generic placeholder video created: {fpath_ph_vid}")
|
215 |
+
return fpath_ph_vid
|
216 |
+
except Exception as e_phv: # Renamed
|
217 |
+
logger.error(f"Failed to create generic placeholder video '{fpath_ph_vid}': {e_phv}", exc_info=True)
|
218 |
return None
|
219 |
finally:
|
220 |
+
if txt_clip_ph_vid and hasattr(txt_clip_ph_vid, 'close'):
|
221 |
+
try: txt_clip_ph_vid.close()
|
222 |
+
except Exception as e_cl_phv: logger.warning(f"Ignoring error closing placeholder TextClip: {e_cl_phv}")
|
223 |
|
224 |
+
def generate_scene_asset(self, img_prompt, motion_prompt, scene_dict, scene_id_fn_base, gen_as_vid=False, rwy_dur=5):
|
225 |
+
# (Corrected DALL-E loop from previous, renamed variables for clarity)
|
226 |
+
asset_base_name,_=os.path.splitext(scene_id_fn_base); asset_info_obj={'path':None,'type':'none','error':True,'prompt_used':img_prompt,'error_message':'Asset gen init failed'}; base_img_path_for_rwy=None
|
227 |
+
base_img_fn = asset_base_name + ("_base_for_video.png" if gen_as_vid else ".png"); base_img_fp = os.path.join(self.output_dir, base_img_fn)
|
|
|
|
|
|
|
|
|
|
|
228 |
if self.USE_AI_IMAGE_GENERATION and self.openai_api_key:
|
229 |
+
max_r,att_c=2,0
|
230 |
+
for att_idx in range(max_r): # Renamed att_n_dalle to att_idx
|
231 |
+
att_c=att_idx+1
|
232 |
+
try:
|
233 |
+
logger.info(f"Att {att_c} DALL-E (base img): {img_prompt[:70]}...");oai_client=openai.OpenAI(api_key=self.openai_api_key,timeout=90.0);oai_resp=oai_client.images.generate(model=self.dalle_model,prompt=img_prompt,n=1,size=self.image_size_dalle3,quality="hd",response_format="url",style="vivid");oai_url=oai_resp.data[0].url;oai_rev_p=getattr(oai_resp.data[0],'revised_prompt',None)
|
234 |
+
if oai_rev_p:logger.info(f"DALL-E revised: {oai_rev_p[:70]}...")
|
235 |
+
oai_img_get_resp=requests.get(oai_url,timeout=120);oai_img_get_resp.raise_for_status();oai_pil_img=Image.open(io.BytesIO(oai_img_get_resp.content))
|
236 |
+
if oai_pil_img.mode!='RGB':oai_pil_img=oai_pil_img.convert('RGB')
|
237 |
+
oai_pil_img.save(base_img_fp);logger.info(f"DALL-E base img saved: {base_img_fp}");base_img_path_for_rwy=base_img_fp;asset_info_obj={'path':base_img_fp,'type':'image','error':False,'prompt_used':img_prompt,'revised_prompt':oai_rev_p};break
|
238 |
+
except openai.RateLimitError as e:logger.warning(f"OpenAI RateLimit Att {att_c}:{e}.Retry...");time.sleep(5*att_c);asset_info_obj['error_message']=str(e)
|
239 |
+
except openai.APIError as e:logger.error(f"OpenAI APIError Att {att_c}:{e}");asset_info_obj['error_message']=str(e);break
|
240 |
+
except requests.exceptions.RequestException as e:logger.error(f"Requests Err DALL-E Att {att_c}:{e}");asset_info_obj['error_message']=str(e);break
|
241 |
+
except Exception as e:logger.error(f"General DALL-E Err Att {att_c}:{e}",exc_info=True);asset_info_obj['error_message']=str(e);break
|
242 |
+
if asset_info_obj['error']:logger.warning(f"DALL-E failed after {att_c} attempts for base img.")
|
243 |
+
if asset_info_obj['error'] and self.USE_PEXELS:
|
244 |
+
logger.info("Trying Pexels for base img.");px_q=scene_dict.get('pexels_search_query_감독',f"{scene_dict.get('emotional_beat','')} {scene_dict.get('setting_description','')}");px_p=self._search_pexels_image(px_q,base_img_fn)
|
245 |
+
if px_p:base_img_path_for_rwy=px_p;asset_info_obj={'path':px_p,'type':'image','error':False,'prompt_used':f"Pexels:{px_q}"}
|
246 |
+
else:curr_err=asset_info_obj.get('error_message',"");asset_info_obj['error_message']=(curr_err+" Pexels failed for base.").strip()
|
247 |
+
if asset_info_obj['error']:
|
248 |
+
logger.warning("Base img (DALL-E/Pexels) failed. Using placeholder.");ph_p_txt=asset_info_obj.get('prompt_used',img_prompt);ph_img_p=self._create_placeholder_image_content(f"[Base Placeholder]{ph_p_txt[:70]}...",base_img_fn)
|
249 |
+
if ph_img_p:base_img_path_for_rwy=ph_img_p;asset_info_obj={'path':ph_img_p,'type':'image','error':False,'prompt_used':ph_p_txt}
|
250 |
+
else:curr_err=asset_info_obj.get('error_message',"");asset_info_obj['error_message']=(curr_err+" Base placeholder failed.").strip()
|
251 |
+
if gen_as_vid:
|
252 |
+
if not base_img_path_for_rwy:logger.error("RunwayML video: base img failed.");asset_info_obj['error']=True;asset_info_obj['error_message']=(asset_info_obj.get('error_message',"")+" Base img miss, Runway abort.").strip();asset_info_obj['type']='none';return asset_info_obj
|
253 |
if self.USE_RUNWAYML:
|
254 |
+
rwy_vid_p=self._generate_video_clip_with_runwayml(motion_prompt,base_img_path_for_rwy,asset_base_name,rwy_dur)
|
255 |
+
if rwy_vid_p and os.path.exists(rwy_vid_p):asset_info_obj={'path':rwy_vid_p,'type':'video','error':False,'prompt_used':motion_prompt,'base_image_path':base_img_path_for_rwy}
|
256 |
+
else:logger.warning(f"RunwayML video failed for {asset_base_name}. Fallback to base img.");asset_info_obj['error']=True;asset_info_obj['error_message']=(asset_info_obj.get('error_message',"Base img ok.")+" RunwayML video fail; use base img.").strip();asset_info_obj['path']=base_img_path_for_rwy;asset_info_obj['type']='image';asset_info_obj['prompt_used']=img_prompt
|
257 |
+
else:logger.warning("RunwayML selected but disabled. Use base img.");asset_info_obj['error']=True;asset_info_obj['error_message']=(asset_info_obj.get('error_message',"Base img ok.")+" RunwayML disabled; use base img.").strip();asset_info_obj['path']=base_img_path_for_rwy;asset_info_obj['type']='image';asset_info_obj['prompt_used']=img_prompt
|
258 |
+
return asset_info_obj
|
259 |
|
260 |
+
def generate_narration_audio(self, narration_text, output_fn="narration_overall.mp3"):
|
261 |
+
# (Corrected version from previous response)
|
262 |
+
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
|
263 |
+
narration_fp = os.path.join(self.output_dir, output_fn)
|
|
|
|
|
264 |
try:
|
265 |
+
logger.info(f"11L audio (Voice:{self.elevenlabs_voice_id}): \"{narration_text[:70]}...\"")
|
266 |
+
stream_method = None
|
267 |
+
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()")
|
268 |
+
elif hasattr(self.elevenlabs_client_instance,'generate_stream'): stream_method=self.elevenlabs_client_instance.generate_stream; logger.info("Using 11L .generate_stream()")
|
269 |
+
elif hasattr(self.elevenlabs_client_instance,'generate'):
|
270 |
+
logger.info("Using 11L .generate() (non-streaming).")
|
271 |
+
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)
|
272 |
+
audio_b = self.elevenlabs_client_instance.generate(text=narration_text,voice=voice_p,model="eleven_multilingual_v2")
|
273 |
+
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
|
274 |
+
else: logger.error("No recognized 11L audio method."); return None
|
275 |
+
if stream_method:
|
276 |
+
voice_stream_params={"voice_id":str(self.elevenlabs_voice_id)}
|
|
|
|
|
|
|
|
|
|
|
277 |
if self.elevenlabs_voice_settings_obj:
|
278 |
+
if hasattr(self.elevenlabs_voice_settings_obj,'model_dump'): voice_stream_params["voice_settings"]=self.elevenlabs_voice_settings_obj.model_dump()
|
279 |
+
elif hasattr(self.elevenlabs_voice_settings_obj,'dict'): voice_stream_params["voice_settings"]=self.elevenlabs_voice_settings_obj.dict()
|
280 |
+
else: voice_stream_params["voice_settings"]=self.elevenlabs_voice_settings_obj
|
281 |
+
audio_iter = stream_method(text=narration_text,model_id="eleven_multilingual_v2",**voice_stream_params)
|
282 |
+
with open(narration_fp,"wb") as f_audio_stream:
|
283 |
+
for chunk_item in audio_iter:
|
284 |
+
if chunk_item: f_audio_stream.write(chunk_item)
|
285 |
+
logger.info(f"11L audio (stream): {narration_fp}"); return narration_fp
|
286 |
+
except AttributeError as e_11l_attr: logger.error(f"11L SDK AttrError: {e_11l_attr}. SDK/methods changed?", exc_info=True); return None
|
287 |
+
except Exception as e_11l_gen: logger.error(f"11L audio gen error: {e_11l_gen}", exc_info=True); return None
|
288 |
|
289 |
def assemble_animatic_from_assets(self, asset_data_list, overall_narration_path=None, output_filename="final_video.mp4", fps=24):
|
290 |
+
# (Keep the version with robust image processing, C-contiguous array, debug saves, and pix_fmt)
|
291 |
+
# ... (This extensive method from the previous full rewrite is assumed to be mostly correct for the "blank video" debugging)
|
292 |
if not asset_data_list: logger.warning("No assets for animatic."); return None
|
293 |
+
processed_clips_list = []; narration_audio_clip_mvpy = None; final_video_output_clip = None
|
294 |
logger.info(f"Assembling from {len(asset_data_list)} assets. Target Frame: {self.video_frame_size}.")
|
295 |
for i_asset, asset_info_item_loop in enumerate(asset_data_list):
|
296 |
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)
|