Update core/visual_engine.py
Browse files- core/visual_engine.py +253 -193
core/visual_engine.py
CHANGED
@@ -60,7 +60,8 @@ class VisualEngine:
|
|
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 |
-
self.elevenlabs_api_key = None; self.USE_ELEVENLABS = False; self.elevenlabs_client_instance = None
|
|
|
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
|
@@ -70,227 +71,286 @@ class VisualEngine:
|
|
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,
|
74 |
-
|
75 |
-
|
76 |
-
|
77 |
-
|
78 |
-
|
79 |
-
|
80 |
-
|
81 |
-
|
82 |
-
|
83 |
-
|
84 |
-
if
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
85 |
if RUNWAYML_SDK_IMPORTED and RunwayMLAPIClientClass:
|
86 |
if not self.runway_ml_sdk_client_instance:
|
87 |
try:
|
88 |
-
|
89 |
-
if not
|
90 |
-
self.runway_ml_sdk_client_instance=RunwayMLAPIClientClass(); self.USE_RUNWAYML=True; logger.info("RunwayML Client init via
|
91 |
-
if not
|
92 |
-
except Exception as
|
93 |
-
else: self.USE_RUNWAYML=True; logger.info("RunwayML Client already init.")
|
94 |
-
else: logger.warning("RunwayML SDK not imported.
|
95 |
-
else: self.USE_RUNWAYML=False; self.runway_ml_sdk_client_instance=None; logger.info("RunwayML Disabled (no key).")
|
96 |
|
97 |
-
|
98 |
-
|
99 |
-
|
100 |
-
|
101 |
-
|
102 |
-
|
103 |
-
|
104 |
-
|
105 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
106 |
|
107 |
-
def _map_resolution_to_runway_ratio(self,
|
108 |
-
|
109 |
-
|
110 |
-
|
|
|
111 |
|
112 |
-
def _get_text_dimensions(self,
|
113 |
-
|
114 |
-
|
|
|
115 |
try:
|
116 |
-
if hasattr(
|
117 |
-
elif hasattr(
|
118 |
-
else:
|
119 |
-
except Exception as
|
120 |
|
121 |
-
def _create_placeholder_image_content(self,
|
122 |
-
# (Corrected
|
123 |
-
if
|
124 |
-
|
125 |
-
|
126 |
-
|
127 |
-
|
128 |
-
|
129 |
-
if
|
130 |
-
|
|
|
|
|
|
|
131 |
else:
|
132 |
-
if
|
133 |
-
|
134 |
-
if
|
135 |
-
if not
|
136 |
-
|
137 |
-
|
138 |
-
|
139 |
-
|
140 |
-
|
141 |
-
|
142 |
-
|
143 |
-
|
144 |
-
|
145 |
-
|
146 |
-
|
147 |
-
|
148 |
-
|
149 |
-
|
150 |
-
|
151 |
-
|
152 |
-
|
153 |
-
|
154 |
-
|
|
|
155 |
|
156 |
-
def _search_pexels_image(self,
|
157 |
-
# (Corrected from
|
158 |
if not self.USE_PEXELS or not self.pexels_api_key: return None
|
159 |
-
|
160 |
-
|
|
|
|
|
|
|
161 |
try:
|
162 |
-
logger.info(f"Pexels:
|
163 |
-
|
|
|
|
|
|
|
|
|
164 |
if data_px.get("photos") and len(data_px["photos"]) > 0:
|
165 |
-
|
166 |
-
|
167 |
-
|
168 |
-
|
169 |
-
|
170 |
-
|
171 |
-
|
172 |
-
|
|
|
|
|
173 |
|
174 |
-
def _generate_video_clip_with_runwayml(self,
|
175 |
-
# (Updated RunwayML integration
|
176 |
-
if not self.USE_RUNWAYML or not self.runway_ml_sdk_client_instance: logger.warning("RunwayML
|
177 |
-
if not
|
178 |
-
|
179 |
-
if not
|
180 |
-
|
181 |
-
|
182 |
-
|
|
|
|
|
183 |
try:
|
184 |
-
|
185 |
-
|
186 |
-
|
187 |
-
while time.time()-
|
188 |
-
time.sleep(
|
189 |
-
logger.info(f"Runway task {
|
190 |
-
if
|
191 |
-
|
192 |
-
|
193 |
-
|
194 |
-
|
195 |
-
|
196 |
-
|
197 |
-
|
198 |
-
|
199 |
-
|
200 |
-
|
201 |
-
|
202 |
-
|
203 |
-
|
|
|
|
|
204 |
|
205 |
-
def _create_placeholder_video_content(self,
|
206 |
-
# (Corrected from previous)
|
207 |
-
if
|
208 |
-
|
209 |
-
|
210 |
try:
|
211 |
-
|
212 |
-
bg_color='black', size=
|
213 |
-
|
214 |
-
logger.info(f"Generic placeholder video created: {
|
215 |
-
return
|
216 |
-
except Exception as
|
217 |
-
logger.error(f"Failed to create generic placeholder video '{
|
218 |
return None
|
219 |
finally:
|
220 |
-
if
|
221 |
-
try:
|
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,
|
225 |
-
|
226 |
-
|
227 |
-
|
|
|
|
|
|
|
|
|
|
|
228 |
if self.USE_AI_IMAGE_GENERATION and self.openai_api_key:
|
229 |
-
|
230 |
-
for
|
231 |
-
|
232 |
-
try:
|
233 |
-
logger.info(f"Att {
|
234 |
-
if
|
235 |
-
|
236 |
-
if
|
237 |
-
|
238 |
-
except openai.RateLimitError as
|
239 |
-
except openai.APIError as
|
240 |
-
except requests.exceptions.RequestException as
|
241 |
-
except Exception as
|
242 |
-
if
|
243 |
-
if
|
244 |
-
logger.info("Trying Pexels for base img.");
|
245 |
-
if
|
246 |
-
else:
|
247 |
-
if
|
248 |
-
logger.warning("Base img (DALL-E/Pexels) failed. Using placeholder.");
|
249 |
-
if
|
250 |
-
else:
|
251 |
-
if
|
252 |
-
if not
|
253 |
if self.USE_RUNWAYML:
|
254 |
-
|
255 |
-
if
|
256 |
-
else:logger.warning(f"RunwayML video failed for {
|
257 |
-
else:logger.warning("RunwayML selected but disabled. Use base img.");
|
258 |
-
return
|
259 |
|
260 |
-
def generate_narration_audio(self,
|
261 |
-
#
|
262 |
-
if not self.USE_ELEVENLABS or not self.elevenlabs_client_instance or not
|
263 |
-
|
|
|
|
|
264 |
try:
|
265 |
-
logger.info(f"
|
266 |
-
|
267 |
-
if hasattr(self.elevenlabs_client_instance,'text_to_speech') and hasattr(self.elevenlabs_client_instance.text_to_speech,'stream'):
|
268 |
-
|
269 |
-
elif hasattr(self.elevenlabs_client_instance,'
|
270 |
-
logger.info("Using
|
271 |
-
|
272 |
-
|
273 |
-
|
274 |
-
|
275 |
-
|
276 |
-
|
|
|
|
|
|
|
|
|
|
|
277 |
if self.elevenlabs_voice_settings_obj:
|
278 |
-
if hasattr(self.elevenlabs_voice_settings_obj,'model_dump'):
|
279 |
-
elif hasattr(self.elevenlabs_voice_settings_obj,'dict'):
|
280 |
-
else:
|
281 |
-
|
282 |
-
with open(
|
283 |
-
for
|
284 |
-
if
|
285 |
-
logger.info(f"
|
286 |
-
except AttributeError as
|
287 |
-
except Exception as
|
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 |
-
|
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)
|
|
|
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 |
+
self.elevenlabs_api_key = None; self.USE_ELEVENLABS = False; self.elevenlabs_client_instance = None
|
64 |
+
self.elevenlabs_voice_id = default_elevenlabs_voice_id # Set initial voice ID from constructor
|
65 |
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)
|
66 |
else: self.elevenlabs_voice_settings_obj = None
|
67 |
self.pexels_api_key = None; self.USE_PEXELS = False
|
|
|
71 |
except Exception as e_rwy_init: logger.error(f"Initial RunwayML client init failed: {e_rwy_init}"); self.USE_RUNWAYML = False
|
72 |
logger.info("VisualEngine initialized.")
|
73 |
|
74 |
+
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'}")
|
75 |
+
|
76 |
+
# <<< CORRECTED METHOD SIGNATURE AND LOGIC >>>
|
77 |
+
def set_elevenlabs_api_key(self, api_key_value, voice_id_from_secret=None):
|
78 |
+
self.elevenlabs_api_key = api_key_value # Store the API key
|
79 |
+
|
80 |
+
if voice_id_from_secret: # If a specific voice ID is passed, update the instance's default
|
81 |
+
self.elevenlabs_voice_id = voice_id_from_secret
|
82 |
+
logger.info(f"ElevenLabs Voice ID updated to: {self.elevenlabs_voice_id} via set_elevenlabs_api_key.")
|
83 |
+
# If voice_id_from_secret is None, self.elevenlabs_voice_id retains the value from __init__
|
84 |
+
|
85 |
+
if api_key_value and ELEVENLABS_CLIENT_IMPORTED and ElevenLabsAPIClient:
|
86 |
+
try:
|
87 |
+
self.elevenlabs_client_instance = ElevenLabsAPIClient(api_key=api_key_value)
|
88 |
+
self.USE_ELEVENLABS = bool(self.elevenlabs_client_instance)
|
89 |
+
logger.info(f"ElevenLabs Client service status: {'Ready' if self.USE_ELEVENLABS else 'Failed Initialization'} (Using Voice ID: {self.elevenlabs_voice_id})")
|
90 |
+
except Exception as e_11l_setkey_init:
|
91 |
+
logger.error(f"ElevenLabs client initialization error during set_elevenlabs_api_key: {e_11l_setkey_init}. Service Disabled.", exc_info=True)
|
92 |
+
self.USE_ELEVENLABS = False
|
93 |
+
self.elevenlabs_client_instance = None
|
94 |
+
else:
|
95 |
+
self.USE_ELEVENLABS = False
|
96 |
+
self.elevenlabs_client_instance = None
|
97 |
+
if not api_key_value: logger.info(f"ElevenLabs Service Disabled (API key not provided).")
|
98 |
+
elif not (ELEVENLABS_CLIENT_IMPORTED and ElevenLabsAPIClient): logger.info(f"ElevenLabs Service Disabled (SDK issue).")
|
99 |
+
|
100 |
+
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'}")
|
101 |
+
def set_runway_api_key(self, api_key_value):
|
102 |
+
self.runway_api_key = api_key_value
|
103 |
+
if api_key_value:
|
104 |
if RUNWAYML_SDK_IMPORTED and RunwayMLAPIClientClass:
|
105 |
if not self.runway_ml_sdk_client_instance:
|
106 |
try:
|
107 |
+
original_env_secret = os.getenv("RUNWAYML_API_SECRET")
|
108 |
+
if not original_env_secret: os.environ["RUNWAYML_API_SECRET"] = api_key_value; logger.info("Temp set RUNWAYML_API_SECRET for SDK.")
|
109 |
+
self.runway_ml_sdk_client_instance = RunwayMLAPIClientClass(); self.USE_RUNWAYML = True; logger.info("RunwayML Client init via set_runway_api_key.")
|
110 |
+
if not original_env_secret: del os.environ["RUNWAYML_API_SECRET"]; logger.info("Cleared temp RUNWAYML_API_SECRET.")
|
111 |
+
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
|
112 |
+
else: self.USE_RUNWAYML = True; logger.info("RunwayML Client already init.")
|
113 |
+
else: logger.warning("RunwayML SDK not imported. Service disabled."); self.USE_RUNWAYML = False
|
114 |
+
else: self.USE_RUNWAYML = False; self.runway_ml_sdk_client_instance = None; logger.info("RunwayML Disabled (no API key).")
|
115 |
|
116 |
+
# ... (Rest of the methods: _image_to_data_uri, _map_resolution_to_runway_ratio, _get_text_dimensions,
|
117 |
+
# _create_placeholder_image_content, _search_pexels_image, _generate_video_clip_with_runwayml,
|
118 |
+
# _create_placeholder_video_content, generate_scene_asset, generate_narration_audio,
|
119 |
+
# assemble_animatic_from_assets - keep these as they were in the last fully corrected version
|
120 |
+
# that addressed the previous syntax errors and had robust image processing for MoviePy)
|
121 |
+
|
122 |
+
# For brevity, I'm re-pasting only the corrected _create_placeholder_image_content and _search_pexels_image
|
123 |
+
# and assuming the other long methods like generate_scene_asset and assemble_animatic_from_assets
|
124 |
+
# are taken from the previous "expertly crafted" full version which already had robust logic.
|
125 |
+
# Make sure to use the complete, most up-to-date versions of ALL methods.
|
126 |
+
|
127 |
+
def _image_to_data_uri(self, image_path):
|
128 |
+
# (Implementation from before)
|
129 |
+
try: mime_type,_=mimetypes.guess_type(image_path)
|
130 |
+
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");
|
131 |
+
if mime_type=="application/octet-stream":logger.warning(f"Unknown MIME for {image_path}, using {mime_type}.")
|
132 |
+
with open(image_path,"rb")as image_file:encoded_string=base64.b64encode(image_file.read()).decode('utf-8')
|
133 |
+
data_uri=f"data:{mime_type};base64,{encoded_string}";logger.debug(f"Data URI for {os.path.basename(image_path)} (MIME:{mime_type}): {data_uri[:100]}...");return data_uri
|
134 |
+
except FileNotFoundError:logger.error(f"Img not found {image_path} for data URI.");return None
|
135 |
+
except Exception as e:logger.error(f"Error converting {image_path} to data URI:{e}",exc_info=True);return None
|
136 |
|
137 |
+
def _map_resolution_to_runway_ratio(self, width, height):
|
138 |
+
# (Implementation from before)
|
139 |
+
ratio_str=f"{width}:{height}";supported_ratios_gen4=["1280:720","720:1280","1104:832","832:1104","960:960","1584:672"];
|
140 |
+
if ratio_str in supported_ratios_gen4:return ratio_str
|
141 |
+
logger.warning(f"Res {ratio_str} not in Gen-4 list. Default 1280:720.");return "1280:720"
|
142 |
|
143 |
+
def _get_text_dimensions(self, text_content, font_object_pil):
|
144 |
+
# (Implementation from before)
|
145 |
+
dch=getattr(font_object_pil,'size',self.active_font_size_pil);
|
146 |
+
if not text_content:return 0,dch
|
147 |
try:
|
148 |
+
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
|
149 |
+
elif hasattr(font_object_pil,'getsize'):w,h=font_object_pil.getsize(text_content);return w,h if h>0 else dch
|
150 |
+
else:return int(len(text_content)*dch*0.6),int(dch*1.2)
|
151 |
+
except Exception as e_getdim_inner:logger.warning(f"Error in _get_text_dimensions:{e_getdim_inner}");return int(len(text_content)*self.active_font_size_pil*0.6),int(self.active_font_size_pil*1.2)
|
152 |
|
153 |
+
def _create_placeholder_image_content(self,text_description,filename,size=None):
|
154 |
+
# (Corrected version from previous response)
|
155 |
+
if size is None: size = self.video_frame_size
|
156 |
+
img = Image.new('RGB', size, color=(20, 20, 40)); d = ImageDraw.Draw(img); padding = 25
|
157 |
+
max_w = size[0] - (2 * padding); lines_for_placeholder = []
|
158 |
+
if not text_description: text_description = "(Placeholder Image)"
|
159 |
+
words_list = text_description.split(); current_line_buffer = ""
|
160 |
+
for word_idx, word_item in enumerate(words_list):
|
161 |
+
prospective_addition = word_item + (" " if word_idx < len(words_list) - 1 else "")
|
162 |
+
test_line_candidate = current_line_buffer + prospective_addition
|
163 |
+
current_w_text, _ = self._get_text_dimensions(test_line_candidate, self.active_font_pil)
|
164 |
+
if current_w_text == 0 and test_line_candidate.strip(): current_w_text = len(test_line_candidate) * (self.active_font_size_pil * 0.6)
|
165 |
+
if current_w_text <= max_w: current_line_buffer = test_line_candidate
|
166 |
else:
|
167 |
+
if current_line_buffer.strip(): lines_for_placeholder.append(current_line_buffer.strip())
|
168 |
+
current_line_buffer = prospective_addition
|
169 |
+
if current_line_buffer.strip(): lines_for_placeholder.append(current_line_buffer.strip())
|
170 |
+
if not lines_for_placeholder and text_description:
|
171 |
+
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)
|
172 |
+
chars_per_line_est = int(max_w / avg_char_w_est) if avg_char_w_est > 0 else 20
|
173 |
+
lines_for_placeholder.append(text_description[:chars_per_line_est] + ("..." if len(text_description) > chars_per_line_est else ""))
|
174 |
+
elif not lines_for_placeholder: lines_for_placeholder.append("(Placeholder Error)")
|
175 |
+
_, 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
|
176 |
+
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)
|
177 |
+
y_p = padding + (size[1] - (2 * padding) - max_l * (single_h + 2)) / 2.0
|
178 |
+
for i_line in range(max_l):
|
179 |
+
line_txt_content = lines_for_placeholder[i_line]; line_w_val, _ = self._get_text_dimensions(line_txt_content, self.active_font_pil)
|
180 |
+
if line_w_val == 0 and line_txt_content.strip(): line_w_val = len(line_txt_content) * (self.active_font_size_pil * 0.6)
|
181 |
+
x_p = (size[0] - line_w_val) / 2.0
|
182 |
+
try: d.text((x_p, y_p), line_txt_content, font=self.active_font_pil, fill=(200, 200, 180))
|
183 |
+
except Exception as e_draw: logger.error(f"Pillow d.text error: {e_draw} for '{line_txt_content}'")
|
184 |
+
y_p += single_h + 2
|
185 |
+
if i_line == 6 and max_l > 7:
|
186 |
+
try: d.text((x_p, y_p), "...", font=self.active_font_pil, fill=(200, 200, 180))
|
187 |
+
except Exception as e_elip: logger.error(f"Pillow d.text ellipsis error: {e_elip}"); break
|
188 |
+
filepath_placeholder = os.path.join(self.output_dir, filename)
|
189 |
+
try: img.save(filepath_placeholder); return filepath_placeholder
|
190 |
+
except Exception as e_save: logger.error(f"Saving placeholder image '{filepath_placeholder}' error: {e_save}", exc_info=True); return None
|
191 |
|
192 |
+
def _search_pexels_image(self, query_str, output_fn_base):
|
193 |
+
# (Corrected version from previous response)
|
194 |
if not self.USE_PEXELS or not self.pexels_api_key: return None
|
195 |
+
http_headers = {"Authorization": self.pexels_api_key}
|
196 |
+
http_params = {"query": query_str, "per_page": 1, "orientation": "landscape", "size": "large2x"}
|
197 |
+
base_name_px, _ = os.path.splitext(output_fn_base)
|
198 |
+
pexels_fn_str = base_name_px + f"_pexels_{random.randint(1000,9999)}.jpg"
|
199 |
+
file_path_px = os.path.join(self.output_dir, pexels_fn_str)
|
200 |
try:
|
201 |
+
logger.info(f"Pexels: Searching for '{query_str}'")
|
202 |
+
eff_query_px = " ".join(query_str.split()[:5])
|
203 |
+
http_params["query"] = eff_query_px
|
204 |
+
response_px = requests.get("https://api.pexels.com/v1/search", headers=http_headers, params=http_params, timeout=20)
|
205 |
+
response_px.raise_for_status()
|
206 |
+
data_px = response_px.json()
|
207 |
if data_px.get("photos") and len(data_px["photos"]) > 0:
|
208 |
+
photo_details_px = data_px["photos"][0]
|
209 |
+
photo_url_px = photo_details_px.get("src", {}).get("large2x")
|
210 |
+
if not photo_url_px: logger.warning(f"Pexels: 'large2x' URL missing for '{eff_query_px}'. Details: {photo_details_px}"); return None
|
211 |
+
image_response_px = requests.get(photo_url_px, timeout=60); image_response_px.raise_for_status()
|
212 |
+
img_pil_data_px = Image.open(io.BytesIO(image_response_px.content))
|
213 |
+
if img_pil_data_px.mode != 'RGB': img_pil_data_px = img_pil_data_px.convert('RGB')
|
214 |
+
img_pil_data_px.save(file_path_px); logger.info(f"Pexels: Image saved to {file_path_px}"); return file_path_px
|
215 |
+
else: logger.info(f"Pexels: No photos for '{eff_query_px}'."); return None
|
216 |
+
except requests.exceptions.RequestException as e_req_px: logger.error(f"Pexels: RequestException for '{query_str}': {e_req_px}", exc_info=False); return None
|
217 |
+
except Exception as e_px_gen: logger.error(f"Pexels: General error for '{query_str}': {e_px_gen}", exc_info=True); return None
|
218 |
|
219 |
+
def _generate_video_clip_with_runwayml(self, text_prompt_for_motion, input_image_path, scene_identifier_filename_base, target_duration_seconds=5):
|
220 |
+
# (Updated RunwayML integration from before)
|
221 |
+
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
|
222 |
+
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
|
223 |
+
image_data_uri_str = self._image_to_data_uri(input_image_path)
|
224 |
+
if not image_data_uri_str: return None
|
225 |
+
runway_dur = 10 if target_duration_seconds >= 8 else 5
|
226 |
+
runway_ratio = self._map_resolution_to_runway_ratio(self.video_frame_size[0], self.video_frame_size[1])
|
227 |
+
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"
|
228 |
+
output_vid_fp = os.path.join(self.output_dir, output_vid_fn)
|
229 |
+
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}'")
|
230 |
try:
|
231 |
+
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)
|
232 |
+
task_id_runway = task_submitted_runway.id; logger.info(f"Runway Gen-4 task ID: {task_id_runway}. Polling...")
|
233 |
+
poll_sec=10; max_poll_count=36; poll_start_time = time.time()
|
234 |
+
while time.time() - poll_start_time < max_poll_count * poll_sec:
|
235 |
+
time.sleep(poll_sec); task_details_runway = self.runway_ml_sdk_client_instance.tasks.retrieve(id=task_id_runway)
|
236 |
+
logger.info(f"Runway task {task_id_runway} status: {task_details_runway.status}")
|
237 |
+
if task_details_runway.status == 'SUCCEEDED':
|
238 |
+
output_url_runway = getattr(getattr(task_details_runway,'output',None),'url',None) or \
|
239 |
+
(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 \
|
240 |
+
(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)
|
241 |
+
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
|
242 |
+
logger.info(f"Runway task {task_id_runway} SUCCEEDED. Downloading: {output_url_runway}")
|
243 |
+
video_resp_get = requests.get(output_url_runway, stream=True, timeout=300); video_resp_get.raise_for_status()
|
244 |
+
with open(output_vid_fp,'wb') as f_vid:
|
245 |
+
for chunk_data in video_resp_get.iter_content(chunk_size=8192): f_vid.write(chunk_data)
|
246 |
+
logger.info(f"Runway Gen-4 video saved: {output_vid_fp}"); return output_vid_fp
|
247 |
+
elif task_details_runway.status in ['FAILED','ABORTED','ERROR']:
|
248 |
+
err_msg_runway = getattr(task_details_runway,'error_message',None) or getattr(getattr(task_details_runway,'output',None),'error',"Unknown Runway error.")
|
249 |
+
logger.error(f"Runway task {task_id_runway} status: {task_details_runway.status}. Error: {err_msg_runway}"); return None
|
250 |
+
logger.warning(f"Runway task {task_id_runway} timed out."); return None
|
251 |
+
except AttributeError as ae_sdk: logger.error(f"RunwayML SDK AttrError: {ae_sdk}. SDK/methods changed?", exc_info=True); return None
|
252 |
+
except Exception as e_runway_gen: logger.error(f"Runway Gen-4 API error: {e_runway_gen}", exc_info=True); return None
|
253 |
|
254 |
+
def _create_placeholder_video_content(self, text_desc_ph, filename_ph, duration_ph=4, size_ph=None):
|
255 |
+
# (Corrected from previous response)
|
256 |
+
if size_ph is None: size_ph = self.video_frame_size
|
257 |
+
filepath_ph = os.path.join(self.output_dir, filename_ph)
|
258 |
+
text_clip_ph = None
|
259 |
try:
|
260 |
+
text_clip_ph = TextClip(text_desc_ph, fontsize=50, color='white', font=self.video_overlay_font,
|
261 |
+
bg_color='black', size=size_ph, method='caption').set_duration(duration_ph)
|
262 |
+
text_clip_ph.write_videofile(filepath_ph, fps=24, codec='libx264', preset='ultrafast', logger=None, threads=2)
|
263 |
+
logger.info(f"Generic placeholder video created: {filepath_ph}")
|
264 |
+
return filepath_ph
|
265 |
+
except Exception as e_ph_vid:
|
266 |
+
logger.error(f"Failed to create generic placeholder video '{filepath_ph}': {e_ph_vid}", exc_info=True)
|
267 |
return None
|
268 |
finally:
|
269 |
+
if text_clip_ph and hasattr(text_clip_ph, 'close'):
|
270 |
+
try: text_clip_ph.close()
|
271 |
except Exception as e_cl_phv: logger.warning(f"Ignoring error closing placeholder TextClip: {e_cl_phv}")
|
272 |
|
273 |
+
def generate_scene_asset(self, image_generation_prompt_text, motion_prompt_text_for_video,
|
274 |
+
scene_data_dict, scene_identifier_fn_base, # Changed scene_data to scene_data_dict
|
275 |
+
generate_as_video_clip_flag=False, runway_target_dur_val=5):
|
276 |
+
# (Corrected DALL-E loop from previous response)
|
277 |
+
base_name_asset, _ = os.path.splitext(scene_identifier_fn_base)
|
278 |
+
asset_info_result = {'path': None, 'type': 'none', 'error': True, 'prompt_used': image_generation_prompt_text, 'error_message': 'Asset generation init failed'}
|
279 |
+
path_for_input_image_runway = None
|
280 |
+
fn_for_base_image = base_name_asset + ("_base_for_video.png" if generate_as_video_clip_flag else ".png")
|
281 |
+
fp_for_base_image = os.path.join(self.output_dir, fn_for_base_image)
|
282 |
if self.USE_AI_IMAGE_GENERATION and self.openai_api_key:
|
283 |
+
max_r_dalle, attempt_count_dalle = 2,0;
|
284 |
+
for att_n_dalle in range(max_r_dalle):
|
285 |
+
attempt_count_dalle = att_n_dalle + 1
|
286 |
+
try:
|
287 |
+
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);
|
288 |
+
if oai_rp: logger.info(f"DALL-E revised: {oai_rp[:70]}...")
|
289 |
+
oai_ir = requests.get(oai_iu,timeout=120); oai_ir.raise_for_status(); oai_id = Image.open(io.BytesIO(oai_ir.content));
|
290 |
+
if oai_id.mode!='RGB': oai_id=oai_id.convert('RGB')
|
291 |
+
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
|
292 |
+
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)
|
293 |
+
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
|
294 |
+
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
|
295 |
+
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
|
296 |
+
if asset_info_result['error']: logger.warning(f"DALL-E failed after {attempt_count_dalle} attempts for base img.")
|
297 |
+
if asset_info_result['error'] and self.USE_PEXELS:
|
298 |
+
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);
|
299 |
+
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}"}
|
300 |
+
else:current_em_px=asset_info_result.get('error_message',"");asset_info_result['error_message']=(current_em_px+" Pexels failed for base.").strip()
|
301 |
+
if asset_info_result['error']:
|
302 |
+
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);
|
303 |
+
if php:path_for_input_image_runway=php;asset_info_result={'path':php,'type':'image','error':False,'prompt_used':ph_ppt}
|
304 |
+
else:current_em_ph=asset_info_result.get('error_message',"");asset_info_result['error_message']=(current_em_ph+" Base placeholder failed.").strip()
|
305 |
+
if generate_as_video_clip_flag:
|
306 |
+
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
|
307 |
if self.USE_RUNWAYML:
|
308 |
+
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)
|
309 |
+
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}
|
310 |
+
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
|
311 |
+
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
|
312 |
+
return asset_info_result
|
313 |
|
314 |
+
def generate_narration_audio(self, text_to_narrate, output_filename="narration_overall.mp3"):
|
315 |
+
# <<< CORRECTED VERSION OF THIS METHOD >>>
|
316 |
+
if not self.USE_ELEVENLABS or not self.elevenlabs_client_instance or not text_to_narrate:
|
317 |
+
logger.info("ElevenLabs conditions not met (service disabled, client not init, or no text). Skipping audio generation.")
|
318 |
+
return None
|
319 |
+
audio_filepath_narration = os.path.join(self.output_dir, output_filename)
|
320 |
try:
|
321 |
+
logger.info(f"Generating ElevenLabs audio (Voice ID: {self.elevenlabs_voice_id}) for text: \"{text_to_narrate[:70]}...\"")
|
322 |
+
audio_stream_method_11l = None
|
323 |
+
if hasattr(self.elevenlabs_client_instance, 'text_to_speech') and hasattr(self.elevenlabs_client_instance.text_to_speech, 'stream'):
|
324 |
+
audio_stream_method_11l = self.elevenlabs_client_instance.text_to_speech.stream; logger.info("Using ElevenLabs SDK method: client.text_to_speech.stream()")
|
325 |
+
elif hasattr(self.elevenlabs_client_instance, 'generate_stream'):
|
326 |
+
audio_stream_method_11l = self.elevenlabs_client_instance.generate_stream; logger.info("Using ElevenLabs SDK method: client.generate_stream()")
|
327 |
+
elif hasattr(self.elevenlabs_client_instance, 'generate'):
|
328 |
+
logger.info("Using ElevenLabs SDK method: client.generate() (non-streaming).")
|
329 |
+
voice_param_11l = str(self.elevenlabs_voice_id)
|
330 |
+
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)
|
331 |
+
audio_bytes_data = self.elevenlabs_client_instance.generate(text=text_to_narrate, voice=voice_param_11l, model="eleven_multilingual_v2")
|
332 |
+
with open(audio_filepath_narration, "wb") as audio_file_out: audio_file_out.write(audio_bytes_data)
|
333 |
+
logger.info(f"ElevenLabs audio (non-streamed) saved successfully to: {audio_filepath_narration}"); return audio_filepath_narration
|
334 |
+
else: logger.error("No recognized audio generation method found on the ElevenLabs client instance."); return None
|
335 |
+
|
336 |
+
if audio_stream_method_11l:
|
337 |
+
params_for_voice_stream = {"voice_id": str(self.elevenlabs_voice_id)}
|
338 |
if self.elevenlabs_voice_settings_obj:
|
339 |
+
if hasattr(self.elevenlabs_voice_settings_obj, 'model_dump'): params_for_voice_stream["voice_settings"] = self.elevenlabs_voice_settings_obj.model_dump()
|
340 |
+
elif hasattr(self.elevenlabs_voice_settings_obj, 'dict'): params_for_voice_stream["voice_settings"] = self.elevenlabs_voice_settings_obj.dict()
|
341 |
+
else: params_for_voice_stream["voice_settings"] = self.elevenlabs_voice_settings_obj
|
342 |
+
audio_data_iterator_11l = audio_stream_method_11l(text=text_to_narrate, model_id="eleven_multilingual_v2", **params_for_voice_stream)
|
343 |
+
with open(audio_filepath_narration, "wb") as audio_file_out_stream:
|
344 |
+
for audio_chunk_data in audio_data_iterator_11l:
|
345 |
+
if audio_chunk_data: audio_file_out_stream.write(audio_chunk_data)
|
346 |
+
logger.info(f"ElevenLabs audio (streamed) saved successfully to: {audio_filepath_narration}"); return audio_filepath_narration
|
347 |
+
except AttributeError as ae_11l_sdk: logger.error(f"AttributeError with ElevenLabs SDK client: {ae_11l_sdk}. SDK version/methods might differ.", exc_info=True); return None
|
348 |
+
except Exception as e_11l_general_audio: logger.error(f"General error during ElevenLabs audio generation: {e_11l_general_audio}", exc_info=True); return None
|
349 |
|
350 |
def assemble_animatic_from_assets(self, asset_data_list, overall_narration_path=None, output_filename="final_video.mp4", fps=24):
|
351 |
+
# (Keep as in the version with robust image processing, C-contiguous array, debug saves, and pix_fmt)
|
|
|
352 |
if not asset_data_list: logger.warning("No assets for animatic."); return None
|
353 |
+
processed_moviepy_clips_list = []; narration_audio_clip_mvpy = None; final_video_output_clip = None
|
354 |
logger.info(f"Assembling from {len(asset_data_list)} assets. Target Frame: {self.video_frame_size}.")
|
355 |
for i_asset, asset_info_item_loop in enumerate(asset_data_list):
|
356 |
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)
|