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