Update core/visual_engine.py
Browse files- core/visual_engine.py +399 -311
core/visual_engine.py
CHANGED
@@ -1,15 +1,15 @@
|
|
1 |
# core/visual_engine.py
|
2 |
from PIL import Image, ImageDraw, ImageFont, ImageOps
|
3 |
-
|
|
|
|
|
4 |
try:
|
5 |
-
if hasattr(Image, 'Resampling') and hasattr(Image.Resampling, 'LANCZOS'):
|
6 |
if not hasattr(Image, 'ANTIALIAS'): Image.ANTIALIAS = Image.Resampling.LANCZOS
|
7 |
-
elif hasattr(Image, 'LANCZOS'):
|
8 |
if not hasattr(Image, 'ANTIALIAS'): Image.ANTIALIAS = Image.LANCZOS
|
9 |
-
elif not hasattr(Image, 'ANTIALIAS'):
|
10 |
-
|
11 |
-
except Exception as e_mp: print(f"WARNING: ANTIALIAS monkey-patch error: {e_mp}")
|
12 |
-
# --- END MONKEY PATCH ---
|
13 |
|
14 |
from moviepy.editor import (ImageClip, VideoFileClip, concatenate_videoclips, TextClip,
|
15 |
CompositeVideoClip, AudioFileClip)
|
@@ -22,11 +22,12 @@ import io
|
|
22 |
import time
|
23 |
import random
|
24 |
import logging
|
|
|
25 |
|
26 |
logger = logging.getLogger(__name__)
|
27 |
logger.setLevel(logging.INFO)
|
28 |
|
29 |
-
# ---
|
30 |
ELEVENLABS_CLIENT_IMPORTED = False; ElevenLabsAPIClient = None; Voice = None; VoiceSettings = None
|
31 |
try:
|
32 |
from elevenlabs.client import ElevenLabs as ImportedElevenLabsClient
|
@@ -35,375 +36,462 @@ try:
|
|
35 |
ELEVENLABS_CLIENT_IMPORTED = True; logger.info("ElevenLabs client components imported.")
|
36 |
except Exception as e_eleven: logger.warning(f"ElevenLabs client import failed: {e_eleven}. Audio disabled.")
|
37 |
|
38 |
-
|
39 |
-
RUNWAYML_SDK_IMPORTED = False; RunwayMLClient = None
|
40 |
try:
|
41 |
-
|
42 |
-
|
43 |
-
|
|
|
|
|
|
|
|
|
|
|
44 |
|
45 |
|
46 |
class VisualEngine:
|
47 |
def __init__(self, output_dir="temp_cinegen_media", default_elevenlabs_voice_id="Rachel"):
|
48 |
self.output_dir = output_dir
|
49 |
os.makedirs(self.output_dir, exist_ok=True)
|
50 |
-
self.font_filename = "DejaVuSans-Bold.ttf"
|
51 |
-
font_paths_to_try = [
|
52 |
-
self.font_filename,
|
53 |
-
f"/usr/share/fonts/truetype/dejavu/DejaVuSans-Bold.ttf",
|
54 |
-
f"/usr/share/fonts/truetype/liberation/LiberationSans-Bold.ttf",
|
55 |
-
f"/System/Library/Fonts/Supplemental/Arial.ttf", f"C:/Windows/Fonts/arial.ttf",
|
56 |
-
f"/usr/local/share/fonts/truetype/mycustomfonts/arial.ttf" # Previous custom path
|
57 |
-
]
|
58 |
self.font_path_pil = next((p for p in font_paths_to_try if os.path.exists(p)), None)
|
59 |
-
self.font_size_pil = 20
|
60 |
-
self.
|
61 |
-
self.video_overlay_font_color = 'white'
|
62 |
-
self.video_overlay_font = 'DejaVu-Sans-Bold' # ImageMagick name for DejaVuSans-Bold
|
63 |
-
|
64 |
try:
|
65 |
self.font = ImageFont.truetype(self.font_path_pil, self.font_size_pil) if self.font_path_pil else ImageFont.load_default()
|
66 |
-
if self.font_path_pil: logger.info(f"Pillow font
|
67 |
-
else: logger.warning("
|
68 |
-
except IOError as e_font: logger.error(f"Pillow font
|
69 |
-
|
70 |
-
self.openai_api_key = None; self.USE_AI_IMAGE_GENERATION = False
|
71 |
-
self.
|
72 |
-
|
73 |
-
self.elevenlabs_api_key = None; self.USE_ELEVENLABS = False; self.elevenlabs_client = None
|
74 |
-
self.elevenlabs_voice_id = default_elevenlabs_voice_id
|
75 |
if VoiceSettings and ELEVENLABS_CLIENT_IMPORTED: self.elevenlabs_voice_settings = VoiceSettings(stability=0.60, similarity_boost=0.80, style=0.15, use_speaker_boost=True)
|
76 |
else: self.elevenlabs_voice_settings = None
|
|
|
77 |
self.pexels_api_key = None; self.USE_PEXELS = False
|
|
|
78 |
self.runway_api_key = None; self.USE_RUNWAYML = False; self.runway_client = None
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
79 |
logger.info("VisualEngine initialized.")
|
80 |
|
81 |
def set_openai_api_key(self,k): self.openai_api_key=k; self.USE_AI_IMAGE_GENERATION=bool(k); logger.info(f"DALL-E ({self.dalle_model}) {'Ready.' if k else 'Disabled.'}")
|
82 |
def set_elevenlabs_api_key(self,api_key, voice_id_from_secret=None):
|
83 |
self.elevenlabs_api_key=api_key
|
84 |
if voice_id_from_secret: self.elevenlabs_voice_id = voice_id_from_secret
|
85 |
-
if api_key and ELEVENLABS_CLIENT_IMPORTED and ElevenLabsAPIClient:
|
86 |
try: self.elevenlabs_client = ElevenLabsAPIClient(api_key=api_key); self.USE_ELEVENLABS=bool(self.elevenlabs_client); logger.info(f"ElevenLabs Client {'Ready' if self.USE_ELEVENLABS else 'Failed Init'} (Voice ID: {self.elevenlabs_voice_id}).")
|
87 |
except Exception as e: logger.error(f"ElevenLabs client init error: {e}. Disabled.", exc_info=True); self.USE_ELEVENLABS=False
|
88 |
-
else: self.USE_ELEVENLABS=False; logger.info("ElevenLabs Disabled (no key or SDK).")
|
89 |
def set_pexels_api_key(self,k): self.pexels_api_key=k; self.USE_PEXELS=bool(k); logger.info(f"Pexels Search {'Ready.' if k else 'Disabled.'}")
|
90 |
-
|
91 |
-
|
92 |
-
|
93 |
-
|
94 |
-
|
95 |
-
|
96 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
97 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
98 |
def _get_text_dimensions(self,tc,fo): di=fo.size if hasattr(fo,'size') else self.font_size_pil; return (0,di) if not tc else (lambda b:(b[2]-b[0],b[3]-b[1] if b[3]-b[1]>0 else di))(fo.getbbox(tc)) if hasattr(fo,'getbbox') else (lambda s:(s[0],s[1] if s[1]>0 else di))(fo.getsize(tc)) if hasattr(fo,'getsize') else (int(len(tc)*di*0.6),int(di*1.2))
|
99 |
def _create_placeholder_image_content(self,td,fn,sz=None):
|
100 |
-
|
101 |
-
if
|
102 |
-
img=Image.new('RGB',sz,color=(20,20,40));d=ImageDraw.Draw(img);pd=25;mw=sz[0]-(2*pd);ls=[];
|
103 |
-
if not td: td="(Placeholder: No prompt text)"
|
104 |
ws=td.split();cl=""
|
105 |
-
for w in ws:
|
106 |
-
|
107 |
-
if
|
108 |
-
|
109 |
-
|
110 |
-
|
111 |
-
if
|
112 |
-
|
113 |
-
|
114 |
-
_,slh=self._get_text_dimensions("Ay",self.font); slh = slh if slh > 0 else self.font_size_pil + 2
|
115 |
-
mld=min(len(ls),(sz[1]-(2*pd))//(slh+2)) if slh > 0 else 1
|
116 |
-
if mld <=0: mld = 1
|
117 |
-
yts = pd + (sz[1]-(2*pd) - mld*(slh+2))/2.0
|
118 |
-
yt = yts
|
119 |
-
for i in range(mld):
|
120 |
-
lc=ls[i];lw,_=self._get_text_dimensions(lc,self.font);xt=(sz[0]-lw)/2.0
|
121 |
-
d.text((xt,yt),lc,font=self.font,fill=(200,200,180));yt+=slh+2
|
122 |
-
if i==6 and mld > 7: d.text((xt,yt),"...",font=self.font,fill=(200,200,180));break
|
123 |
fp=os.path.join(self.output_dir,fn);
|
124 |
try:img.save(fp);return fp
|
125 |
-
except Exception as e:logger.error(f"
|
126 |
-
|
127 |
def _search_pexels_image(self, q, ofnb):
|
128 |
-
|
129 |
-
|
130 |
-
|
131 |
-
|
132 |
-
|
133 |
-
|
134 |
-
|
135 |
-
|
136 |
-
|
137 |
-
|
138 |
-
pu = d["photos"][0]["src"]["large2x"]
|
139 |
-
ir = requests.get(pu, timeout=60); ir.raise_for_status()
|
140 |
-
id = Image.open(io.BytesIO(ir.content))
|
141 |
-
if id.mode != 'RGB': id = id.convert('RGB')
|
142 |
-
id.save(fp); logger.info(f"Pexels image saved: {fp}"); return fp
|
143 |
-
else: logger.info(f"No photos Pexels: '{eq}'")
|
144 |
-
except Exception as e: logger.error(f"Pexels error ('{q}'): {e}", exc_info=True)
|
145 |
-
return None
|
146 |
-
|
147 |
-
def _generate_video_clip_with_runwayml(self, pt, sifnb, tds=4, iip=None):
|
148 |
-
# ... (Keeping placeholder logic) ...
|
149 |
-
if not self.USE_RUNWAYML or not self.runway_api_key: logger.warning("RunwayML disabled."); return None
|
150 |
-
ovfn = sifnb.replace(".png", "_runway.mp4")
|
151 |
-
ovfp = os.path.join(self.output_dir, ovfn)
|
152 |
-
logger.info(f"RunwayML (Placeholder) for: {pt[:100]}... (Dur: {tds}s)")
|
153 |
-
return self._create_placeholder_video_content(f"[RunwayML Placeholder] {pt}", ovfn, duration=tds)
|
154 |
-
|
155 |
-
def _create_placeholder_video_content(self, td, fn, dur=4, sz=None):
|
156 |
-
# ... (Keeping placeholder logic) ...
|
157 |
-
if sz is None: sz = self.video_frame_size
|
158 |
-
fp = os.path.join(self.output_dir, fn)
|
159 |
-
tc = None
|
160 |
try:
|
161 |
tc = TextClip(td, fontsize=50, color='white', font=self.video_overlay_font, bg_color='black', size=sz, method='caption').set_duration(dur)
|
162 |
tc.write_videofile(fp, fps=24, codec='libx264', preset='ultrafast', logger=None, threads=2)
|
163 |
-
logger.info(f"
|
164 |
-
except Exception as e: logger.error(f"
|
165 |
finally:
|
166 |
if tc and hasattr(tc, 'close'): tc.close()
|
167 |
|
168 |
-
|
169 |
-
|
170 |
-
|
|
|
|
|
171 |
base_name, _ = os.path.splitext(scene_identifier_filename_base)
|
172 |
-
|
173 |
-
|
174 |
-
|
175 |
-
|
176 |
-
|
|
|
|
|
|
|
|
|
|
|
177 |
|
178 |
-
|
179 |
if self.USE_AI_IMAGE_GENERATION and self.openai_api_key:
|
180 |
max_r, att_n = 2, 0
|
181 |
for att_n in range(max_r):
|
182 |
try:
|
183 |
-
logger.info(f"Attempt {att_n+1} DALL-E: {
|
184 |
cl = openai.OpenAI(api_key=self.openai_api_key, timeout=90.0)
|
185 |
-
r = cl.images.generate(model=self.dalle_model, prompt=
|
186 |
iu = r.data[0].url; rp = getattr(r.data[0], 'revised_prompt', None)
|
187 |
if rp: logger.info(f"DALL-E revised: {rp[:100]}...")
|
188 |
ir = requests.get(iu, timeout=120); ir.raise_for_status()
|
189 |
-
|
190 |
-
if
|
191 |
-
|
192 |
-
|
|
|
|
|
193 |
except openai.RateLimitError as e: logger.warning(f"OpenAI Rate Limit {att_n+1}: {e}. Retry..."); time.sleep(5*(att_n+1)); asset_info['error_message']=str(e)
|
194 |
-
except Exception as e: logger.error(f"DALL-E error: {e}", exc_info=True); asset_info['error_message']=str(e); break
|
195 |
-
if asset_info['error']: logger.warning(f"DALL-E failed after {att_n+1} attempts
|
196 |
-
|
197 |
-
if self.USE_PEXELS and (asset_info['error'] or not (self.USE_AI_IMAGE_GENERATION and self.openai_api_key)):
|
198 |
-
pqt = scene_data.get('pexels_search_query_감독', f"{scene_data.get('emotional_beat','')} {scene_data.get('setting_description','')}")
|
199 |
-
pp = self._search_pexels_image(pqt, image_filename_with_ext)
|
200 |
-
if pp: return {'path': pp, 'type': 'image', 'error': False, 'prompt_used': f"Pexels: {pqt}"}
|
201 |
-
cem = asset_info.get('error_message', ""); asset_info['error_message'] = (cem + " Pexels failed.").strip()
|
202 |
-
if not asset_info['error']: logger.warning("Pexels failed (DALL-E not tried).")
|
203 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
204 |
if asset_info['error']:
|
205 |
-
logger.warning("
|
206 |
-
ppt = asset_info.get('prompt_used',
|
207 |
-
php = self._create_placeholder_image_content(f"[
|
208 |
-
if php:
|
209 |
-
else:
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
210 |
return asset_info
|
211 |
|
|
|
|
|
212 |
def generate_narration_audio(self, text_to_narrate, output_filename="narration_overall.mp3"):
|
213 |
-
|
214 |
-
|
215 |
-
|
216 |
-
|
217 |
-
|
218 |
-
|
219 |
-
|
220 |
-
|
221 |
-
|
222 |
-
|
223 |
-
|
224 |
-
|
225 |
-
|
226 |
-
|
227 |
-
|
228 |
-
|
229 |
-
|
230 |
-
|
231 |
-
|
232 |
-
|
233 |
-
|
234 |
-
adi = asm(text=text_to_narrate,model_id="eleven_multilingual_v2",**vps)
|
235 |
-
with open(afp,"wb") as f:
|
236 |
-
for chunk in adi:
|
237 |
-
if chunk: f.write(chunk)
|
238 |
-
logger.info(f"11L audio (streamed): {afp}"); return afp
|
239 |
-
except Exception as e: logger.error(f"11L audio error: {e}", exc_info=True)
|
240 |
-
return None
|
241 |
-
|
242 |
-
|
243 |
-
# =========================================================================
|
244 |
-
# ASSEMBLE ANIMATIC - FOCUS OF CORRUPTION DEBUGGING
|
245 |
-
# =========================================================================
|
246 |
def assemble_animatic_from_assets(self, asset_data_list, overall_narration_path=None, output_filename="final_video.mp4", fps=24):
|
247 |
-
if not asset_data_list:
|
248 |
-
|
249 |
-
|
250 |
-
|
251 |
-
processed_moviepy_clips = []
|
252 |
-
narration_audio_clip = None
|
253 |
-
final_composite_clip_obj = None
|
254 |
-
|
255 |
-
logger.info(f"Assembling animatic from {len(asset_data_list)} assets. Target frame: {self.video_frame_size}.")
|
256 |
|
257 |
for i, asset_info in enumerate(asset_data_list):
|
258 |
-
asset_path = asset_info.get('path')
|
259 |
-
|
260 |
-
|
261 |
-
scene_num = asset_info.get('scene_num', i + 1)
|
262 |
-
key_action = asset_info.get('key_action', '')
|
263 |
-
|
264 |
-
logger.info(f"Processing S{scene_num}: Path='{asset_path}', Type='{asset_type}', TargetDur='{target_scene_duration}'s")
|
265 |
|
266 |
-
if not (asset_path and os.path.exists(asset_path)):
|
267 |
-
|
268 |
-
if target_scene_duration <= 0:
|
269 |
-
logger.warning(f"S{scene_num}: Invalid duration ({target_scene_duration}s). Skipping."); continue
|
270 |
|
271 |
-
|
272 |
try:
|
273 |
if asset_type == 'image':
|
274 |
-
pil_img = Image.open(asset_path)
|
275 |
-
|
276 |
-
|
277 |
-
|
278 |
-
|
279 |
-
|
280 |
-
|
281 |
-
|
282 |
-
|
283 |
-
|
284 |
-
|
285 |
-
|
286 |
-
|
287 |
-
|
288 |
-
|
289 |
-
|
290 |
-
|
291 |
-
canvas_rgba.paste(img_thumbnail, (xo, yo), img_thumbnail) # Use thumbnail's alpha as mask
|
292 |
-
|
293 |
-
# 4. Convert to final RGB image (flattens alpha against black) for MoviePy
|
294 |
-
final_rgb_image_for_moviepy = Image.new("RGB", self.video_frame_size, (0, 0, 0)) # Black background
|
295 |
-
final_rgb_image_for_moviepy.paste(canvas_rgba, mask=canvas_rgba.split()[3]) # Use alpha of canvas_rgba as mask
|
296 |
-
|
297 |
-
debug_canvas_path = os.path.join(self.output_dir, f"debug_PRE_NUMPY_S{scene_num}.png")
|
298 |
-
try: final_rgb_image_for_moviepy.save(debug_canvas_path); logger.info(f"DEBUG: Saved PRE-NUMPY image for S{scene_num} to {debug_canvas_path}")
|
299 |
-
except Exception as e_save: logger.error(f"DEBUG: Error saving PRE-NUMPY image for S{scene_num}: {e_save}")
|
300 |
-
|
301 |
-
# 5. Convert to C-contiguous NumPy array, dtype uint8
|
302 |
-
frame_np = np.array(final_rgb_image_for_moviepy, dtype=np.uint8)
|
303 |
-
if not frame_np.flags['C_CONTIGUOUS']:
|
304 |
-
frame_np = np.ascontiguousarray(frame_np, dtype=np.uint8)
|
305 |
-
logger.debug(f"S{scene_num}: Ensured NumPy array is C-contiguous.")
|
306 |
-
|
307 |
-
logger.debug(f"S{scene_num}: Final NumPy for MoviePy. Shape: {frame_np.shape}, Dtype: {frame_np.dtype}, Contiguous: {frame_np.flags['C_CONTIGUOUS']}")
|
308 |
-
|
309 |
-
if frame_np.size == 0 or frame_np.ndim != 3 or frame_np.shape[2] != 3:
|
310 |
-
logger.error(f"S{scene_num}: Invalid NumPy array shape/size for ImageClip. Shape: {frame_np.shape}. Skipping."); continue
|
311 |
-
# --- End Robust Image Processing ---
|
312 |
-
|
313 |
-
current_clip_base = ImageClip(frame_np, transparent=False).set_duration(target_scene_duration)
|
314 |
-
logger.debug(f"S{scene_num}: Base ImageClip created.")
|
315 |
-
|
316 |
-
# --- DEBUG: Save frame from MoviePy ImageClip object ---
|
317 |
-
moviepy_frame_debug_path = os.path.join(self.output_dir, f"debug_MOVIEPY_FRAME_S{scene_num}.png")
|
318 |
-
try:
|
319 |
-
current_clip_base.save_frame(moviepy_frame_debug_path, t=0.1) # Save a frame at 0.1s
|
320 |
-
logger.info(f"DEBUG: Saved frame FROM MOVIEPY ImageClip for S{scene_num} to {moviepy_frame_debug_path}")
|
321 |
-
except Exception as e_save_mv_frame:
|
322 |
-
logger.error(f"DEBUG: Error saving frame FROM MOVIEPY ImageClip for S{scene_num}: {e_save_mv_frame}", exc_info=True)
|
323 |
-
# --- End DEBUG ---
|
324 |
-
|
325 |
-
current_scene_clip_with_fx = current_clip_base
|
326 |
-
try: # Ken Burns
|
327 |
-
end_scale = random.uniform(1.03, 1.08)
|
328 |
-
current_scene_clip_with_fx = current_clip_base.fx(vfx.resize, lambda t: 1 + (end_scale - 1) * (t / target_scene_duration) if target_scene_duration > 0 else 1).set_position('center')
|
329 |
-
except Exception as e_fx: logger.error(f"S{scene_num}: Ken Burns error: {e_fx}. Using static.", exc_info=False)
|
330 |
-
current_scene_clip = current_scene_clip_with_fx
|
331 |
-
|
332 |
elif asset_type == 'video':
|
333 |
-
|
334 |
-
source_video_clip = None
|
335 |
try:
|
336 |
-
|
337 |
-
|
338 |
-
if
|
339 |
-
if
|
340 |
-
else:
|
341 |
-
if
|
342 |
-
else:
|
343 |
-
|
344 |
-
if
|
345 |
-
except Exception as
|
346 |
finally:
|
347 |
-
if
|
348 |
-
|
349 |
-
else: logger.warning(f"S{scene_num}: Unknown asset type '{asset_type}'. Skipping."); continue
|
350 |
|
351 |
-
if
|
352 |
try:
|
353 |
-
|
354 |
-
|
355 |
-
|
356 |
-
|
357 |
-
|
358 |
-
|
359 |
-
|
360 |
-
|
361 |
-
|
362 |
-
|
363 |
-
|
364 |
-
|
365 |
-
|
366 |
-
|
367 |
-
|
368 |
-
|
369 |
-
if not processed_moviepy_clips: logger.warning("No clips processed. Aborting."); return None
|
370 |
-
|
371 |
-
transition_duration = 0.75
|
372 |
try:
|
373 |
-
logger.info(f"Concatenating {len(
|
374 |
-
if len(
|
375 |
-
elif
|
376 |
-
if not
|
377 |
-
logger.info(f"Concatenated
|
378 |
-
|
379 |
-
|
380 |
-
|
381 |
-
|
382 |
-
|
383 |
-
|
384 |
-
|
385 |
-
|
386 |
-
|
387 |
-
|
388 |
-
|
389 |
-
|
390 |
-
|
391 |
-
# --- Test different write parameters if corruption persists ---
|
392 |
-
final_composite_clip_obj.write_videofile(
|
393 |
-
output_path, fps=fps, codec='libx264',
|
394 |
-
preset='medium', # Changed from ultrafast for potentially better encoding
|
395 |
-
audio_codec='aac',
|
396 |
-
temp_audiofile=os.path.join(self.output_dir, f'temp-audio-{os.urandom(4).hex()}.m4a'),
|
397 |
-
remove_temp=True, threads=os.cpu_count() or 2, logger='bar', bitrate="5000k"
|
398 |
-
# ffmpeg_params=["-pix_fmt", "yuv420p"] # Potentially force pixel format if issues persist
|
399 |
-
)
|
400 |
-
logger.info(f"Video created: {output_path}"); return output_path
|
401 |
-
else: logger.error("Final clip invalid. Not writing."); return None
|
402 |
-
except Exception as e_write: logger.error(f"Video writing error: {e_write}", exc_info=True); return None
|
403 |
finally:
|
404 |
logger.debug("Closing all MoviePy clips in `assemble_animatic_from_assets` finally block.")
|
405 |
-
|
406 |
-
for clip_obj in
|
407 |
if clip_obj and hasattr(clip_obj, 'close'):
|
408 |
try: clip_obj.close()
|
409 |
-
except Exception as e_close: logger.warning(f"Ignoring error while closing a clip: {e_close}")
|
|
|
1 |
# core/visual_engine.py
|
2 |
from PIL import Image, ImageDraw, ImageFont, ImageOps
|
3 |
+
import base64 # For Data URI conversion
|
4 |
+
|
5 |
+
# --- MONKEY PATCH ---
|
6 |
try:
|
7 |
+
if hasattr(Image, 'Resampling') and hasattr(Image.Resampling, 'LANCZOS'):
|
8 |
if not hasattr(Image, 'ANTIALIAS'): Image.ANTIALIAS = Image.Resampling.LANCZOS
|
9 |
+
elif hasattr(Image, 'LANCZOS'):
|
10 |
if not hasattr(Image, 'ANTIALIAS'): Image.ANTIALIAS = Image.LANCZOS
|
11 |
+
elif not hasattr(Image, 'ANTIALIAS'): print("WARNING: Pillow ANTIALIAS/Resampling issue.")
|
12 |
+
except Exception as e_mp: print(f"WARNING: ANTIALIAS patch error: {e_mp}")
|
|
|
|
|
13 |
|
14 |
from moviepy.editor import (ImageClip, VideoFileClip, concatenate_videoclips, TextClip,
|
15 |
CompositeVideoClip, AudioFileClip)
|
|
|
22 |
import time
|
23 |
import random
|
24 |
import logging
|
25 |
+
import mimetypes # For Data URI
|
26 |
|
27 |
logger = logging.getLogger(__name__)
|
28 |
logger.setLevel(logging.INFO)
|
29 |
|
30 |
+
# --- SERVICE CLIENT IMPORTS ---
|
31 |
ELEVENLABS_CLIENT_IMPORTED = False; ElevenLabsAPIClient = None; Voice = None; VoiceSettings = None
|
32 |
try:
|
33 |
from elevenlabs.client import ElevenLabs as ImportedElevenLabsClient
|
|
|
36 |
ELEVENLABS_CLIENT_IMPORTED = True; logger.info("ElevenLabs client components imported.")
|
37 |
except Exception as e_eleven: logger.warning(f"ElevenLabs client import failed: {e_eleven}. Audio disabled.")
|
38 |
|
39 |
+
RUNWAYML_SDK_IMPORTED = False; RunwayMLAPIClient = None # Renamed for clarity
|
|
|
40 |
try:
|
41 |
+
from runwayml import RunwayML as ImportedRunwayMLClient # Actual SDK import
|
42 |
+
RunwayMLAPIClient = ImportedRunwayMLClient
|
43 |
+
RUNWAYML_SDK_IMPORTED = True
|
44 |
+
logger.info("RunwayML SDK imported successfully.")
|
45 |
+
except ImportError:
|
46 |
+
logger.warning("RunwayML SDK not found (pip install runwayml). RunwayML video generation will be disabled.")
|
47 |
+
except Exception as e_runway_sdk:
|
48 |
+
logger.warning(f"Error importing RunwayML SDK: {e_runway_sdk}. RunwayML features disabled.")
|
49 |
|
50 |
|
51 |
class VisualEngine:
|
52 |
def __init__(self, output_dir="temp_cinegen_media", default_elevenlabs_voice_id="Rachel"):
|
53 |
self.output_dir = output_dir
|
54 |
os.makedirs(self.output_dir, exist_ok=True)
|
55 |
+
self.font_filename = "DejaVuSans-Bold.ttf"
|
56 |
+
font_paths_to_try = [ self.font_filename, "/usr/share/fonts/truetype/dejavu/DejaVuSans-Bold.ttf", "/usr/share/fonts/truetype/liberation/LiberationSans-Bold.ttf", "/System/Library/Fonts/Supplemental/Arial.ttf", "C:/Windows/Fonts/arial.ttf", f"/usr/local/share/fonts/truetype/mycustomfonts/arial.ttf"]
|
|
|
|
|
|
|
|
|
|
|
|
|
57 |
self.font_path_pil = next((p for p in font_paths_to_try if os.path.exists(p)), None)
|
58 |
+
self.font_size_pil = 20; self.video_overlay_font_size = 30; self.video_overlay_font_color = 'white'
|
59 |
+
self.video_overlay_font = 'DejaVu-Sans-Bold'
|
|
|
|
|
|
|
60 |
try:
|
61 |
self.font = ImageFont.truetype(self.font_path_pil, self.font_size_pil) if self.font_path_pil else ImageFont.load_default()
|
62 |
+
if self.font_path_pil: logger.info(f"Pillow font: {self.font_path_pil}.")
|
63 |
+
else: logger.warning("Default Pillow font."); self.font_size_pil = 10
|
64 |
+
except IOError as e_font: logger.error(f"Pillow font IOError: {e_font}. Default."); self.font = ImageFont.load_default(); self.font_size_pil = 10
|
65 |
+
|
66 |
+
self.openai_api_key = None; self.USE_AI_IMAGE_GENERATION = False; self.dalle_model = "dall-e-3"; self.image_size_dalle3 = "1792x1024"
|
67 |
+
self.video_frame_size = (1280, 720) # Default, will be mapped to Runway ratio
|
68 |
+
|
69 |
+
self.elevenlabs_api_key = None; self.USE_ELEVENLABS = False; self.elevenlabs_client = None; self.elevenlabs_voice_id = default_elevenlabs_voice_id
|
|
|
70 |
if VoiceSettings and ELEVENLABS_CLIENT_IMPORTED: self.elevenlabs_voice_settings = VoiceSettings(stability=0.60, similarity_boost=0.80, style=0.15, use_speaker_boost=True)
|
71 |
else: self.elevenlabs_voice_settings = None
|
72 |
+
|
73 |
self.pexels_api_key = None; self.USE_PEXELS = False
|
74 |
+
|
75 |
self.runway_api_key = None; self.USE_RUNWAYML = False; self.runway_client = None
|
76 |
+
if RUNWAYML_SDK_IMPORTED and RunwayMLAPIClient: # Initialize if SDK is available
|
77 |
+
try:
|
78 |
+
# The SDK expects RUNWAYML_API_SECRET env var.
|
79 |
+
# If your key is passed directly, you might need to initialize differently or set the env var.
|
80 |
+
if os.getenv("RUNWAYML_API_SECRET"):
|
81 |
+
self.runway_client = RunwayMLAPIClient()
|
82 |
+
logger.info("RunwayML Client initialized using RUNWAYML_API_SECRET env var.")
|
83 |
+
else:
|
84 |
+
logger.warning("RUNWAYML_API_SECRET env var not set. RunwayML client not initialized here (will try in set_runway_api_key).")
|
85 |
+
except Exception as e_runway_init:
|
86 |
+
logger.error(f"Failed to initialize RunwayML client during __init__: {e_runway_init}", exc_info=True)
|
87 |
+
|
88 |
logger.info("VisualEngine initialized.")
|
89 |
|
90 |
def set_openai_api_key(self,k): self.openai_api_key=k; self.USE_AI_IMAGE_GENERATION=bool(k); logger.info(f"DALL-E ({self.dalle_model}) {'Ready.' if k else 'Disabled.'}")
|
91 |
def set_elevenlabs_api_key(self,api_key, voice_id_from_secret=None):
|
92 |
self.elevenlabs_api_key=api_key
|
93 |
if voice_id_from_secret: self.elevenlabs_voice_id = voice_id_from_secret
|
94 |
+
if api_key and ELEVENLABS_CLIENT_IMPORTED and ElevenLabsAPIClient: # This API key is for the client
|
95 |
try: self.elevenlabs_client = ElevenLabsAPIClient(api_key=api_key); self.USE_ELEVENLABS=bool(self.elevenlabs_client); logger.info(f"ElevenLabs Client {'Ready' if self.USE_ELEVENLABS else 'Failed Init'} (Voice ID: {self.elevenlabs_voice_id}).")
|
96 |
except Exception as e: logger.error(f"ElevenLabs client init error: {e}. Disabled.", exc_info=True); self.USE_ELEVENLABS=False
|
97 |
+
else: self.USE_ELEVENLABS=False; logger.info("ElevenLabs Disabled (no key or SDK issue).")
|
98 |
def set_pexels_api_key(self,k): self.pexels_api_key=k; self.USE_PEXELS=bool(k); logger.info(f"Pexels Search {'Ready.' if k else 'Disabled.'}")
|
99 |
+
|
100 |
+
def set_runway_api_key(self, k): # For RunwayML
|
101 |
+
self.runway_api_key = k # Store the key
|
102 |
+
if k:
|
103 |
+
if RUNWAYML_SDK_IMPORTED and RunwayMLAPIClient:
|
104 |
+
if not self.runway_client: # If not initialized in __init__
|
105 |
+
try:
|
106 |
+
# Ensure RUNWAYML_API_SECRET is set if SDK relies on it
|
107 |
+
if not os.getenv("RUNWAYML_API_SECRET") and k:
|
108 |
+
logger.info("Setting RUNWAYML_API_SECRET environment variable from provided key for SDK.")
|
109 |
+
os.environ["RUNWAYML_API_SECRET"] = k # Make key available to SDK
|
110 |
+
|
111 |
+
self.runway_client = RunwayMLAPIClient()
|
112 |
+
self.USE_RUNWAYML = True
|
113 |
+
logger.info("RunwayML Client initialized successfully via set_runway_api_key.")
|
114 |
+
except Exception as e_client_init:
|
115 |
+
logger.error(f"RunwayML Client initialization failed in set_runway_api_key: {e_client_init}", exc_info=True)
|
116 |
+
self.USE_RUNWAYML = False
|
117 |
+
else: # Client was already initialized (e.g., from env var in __init__)
|
118 |
+
self.USE_RUNWAYML = True
|
119 |
+
logger.info("RunwayML Client already initialized.")
|
120 |
+
else: # SDK not imported
|
121 |
+
logger.warning("RunwayML SDK not imported. API key set, but direct HTTP calls would be needed (not implemented).")
|
122 |
+
self.USE_RUNWAYML = False # Can't use if SDK is the only implemented path
|
123 |
+
else:
|
124 |
+
self.USE_RUNWAYML = False
|
125 |
+
logger.info("RunwayML Disabled (no API key provided to set_runway_api_key).")
|
126 |
+
|
127 |
+
|
128 |
+
def _image_to_data_uri(self, image_path):
|
129 |
+
try:
|
130 |
+
mime_type, _ = mimetypes.guess_type(image_path)
|
131 |
+
if not mime_type:
|
132 |
+
# Fallback for common image types if mimetypes fails (e.g., on some systems)
|
133 |
+
ext = os.path.splitext(image_path)[1].lower()
|
134 |
+
if ext == ".png": mime_type = "image/png"
|
135 |
+
elif ext in [".jpg", ".jpeg"]: mime_type = "image/jpeg"
|
136 |
+
else:
|
137 |
+
logger.warning(f"Could not determine MIME type for {image_path}. Defaulting to application/octet-stream.")
|
138 |
+
mime_type = "application/octet-stream" # Fallback, Runway might reject this
|
139 |
+
|
140 |
+
with open(image_path, "rb") as image_file:
|
141 |
+
encoded_string = base64.b64encode(image_file.read()).decode('utf-8')
|
142 |
+
data_uri = f"data:{mime_type};base64,{encoded_string}"
|
143 |
+
logger.debug(f"Generated data URI for {image_path} (first 100 chars): {data_uri[:100]}")
|
144 |
+
return data_uri
|
145 |
+
except Exception as e:
|
146 |
+
logger.error(f"Error converting image {image_path} to data URI: {e}", exc_info=True)
|
147 |
+
return None
|
148 |
+
|
149 |
+
def _map_resolution_to_runway_ratio(self, width, height):
|
150 |
+
# Gen-4 supports specific ratios. Find the closest supported or default.
|
151 |
+
# Example: 1280x720 -> "1280:720"
|
152 |
+
# This needs to be robust. For now, we'll assume app.py sends a valid W:H string
|
153 |
+
# or we use a default that matches self.video_frame_size if it's standard.
|
154 |
+
if width == 1280 and height == 720: return "1280:720"
|
155 |
+
if width == 720 and height == 1280: return "720:1280"
|
156 |
+
# Add more mappings based on Gen-4 supported ratios if your self.video_frame_size can vary
|
157 |
+
logger.warning(f"Unsupported resolution {width}x{height} for Runway Gen-4 mapping. Defaulting to 1280:720.")
|
158 |
+
return "1280:720" # Default
|
159 |
+
|
160 |
+
def _generate_video_clip_with_runwayml(self, text_prompt_for_motion, input_image_path, scene_identifier_filename_base, target_duration_seconds=5):
|
161 |
+
if not self.USE_RUNWAYML or not self.runway_client: # Check for initialized client
|
162 |
+
logger.warning("RunwayML not enabled or client not initialized. Cannot generate video clip.")
|
163 |
+
return None
|
164 |
+
if not input_image_path or not os.path.exists(input_image_path):
|
165 |
+
logger.error(f"Runway Gen-4 requires an input image. Path not provided or invalid: {input_image_path}")
|
166 |
+
return None
|
167 |
+
|
168 |
+
image_data_uri = self._image_to_data_uri(input_image_path)
|
169 |
+
if not image_data_uri:
|
170 |
+
return None
|
171 |
+
|
172 |
+
runway_duration = 10 if target_duration_seconds > 7 else 5 # Map to 5s or 10s
|
173 |
+
runway_ratio_str = self._map_resolution_to_runway_ratio(self.video_frame_size[0], self.video_frame_size[1])
|
174 |
+
|
175 |
+
output_video_filename = scene_identifier_filename_base.replace(".png", f"_runway_gen4_d{runway_duration}s.mp4")
|
176 |
+
output_video_filepath = os.path.join(self.output_dir, output_video_filename)
|
177 |
+
|
178 |
+
logger.info(f"Initiating Runway Gen-4 task: motion='{text_prompt_for_motion[:100]}...', image='{os.path.basename(input_image_path)}', dur={runway_duration}s, ratio='{runway_ratio_str}'")
|
179 |
+
|
180 |
+
try:
|
181 |
+
task = self.runway_client.image_to_video.create(
|
182 |
+
model='gen4_turbo',
|
183 |
+
prompt_image=image_data_uri,
|
184 |
+
prompt_text=text_prompt_for_motion,
|
185 |
+
duration=runway_duration,
|
186 |
+
ratio=runway_ratio_str, # e.g., "1280:720"
|
187 |
+
# seed=random.randint(0, 4294967295), # Optional
|
188 |
+
# Other Gen-4 params can be added here: motion_score, upscale etc.
|
189 |
+
)
|
190 |
+
logger.info(f"Runway Gen-4 task created with ID: {task.id}. Polling for completion...")
|
191 |
+
|
192 |
+
poll_interval = 10 # seconds
|
193 |
+
max_polls = 36 # Max 6 minutes (36 * 10s)
|
194 |
+
for _ in range(max_polls):
|
195 |
+
time.sleep(poll_interval)
|
196 |
+
task_details = self.runway_client.tasks.retrieve(id=task.id)
|
197 |
+
logger.info(f"Runway task {task.id} status: {task_details.status}")
|
198 |
+
if task_details.status == 'SUCCEEDED':
|
199 |
+
# The SDK docs don't explicitly show how to get the output URL from `task_details`.
|
200 |
+
# Common patterns are `task_details.output.url` or `task_details.artifacts[0].url`.
|
201 |
+
# This is a GUESS based on typical API structures. You MUST verify this.
|
202 |
+
output_url = None
|
203 |
+
if hasattr(task_details, 'output') and task_details.output and hasattr(task_details.output, 'url'):
|
204 |
+
output_url = task_details.output.url
|
205 |
+
elif hasattr(task_details, 'artifacts') and task_details.artifacts and isinstance(task_details.artifacts, list) and len(task_details.artifacts) > 0:
|
206 |
+
# Assuming the first artifact is the video and has a URL
|
207 |
+
if hasattr(task_details.artifacts[0], 'url'):
|
208 |
+
output_url = task_details.artifacts[0].url
|
209 |
+
elif hasattr(task_details.artifacts[0], 'download_url'): # Another common name
|
210 |
+
output_url = task_details.artifacts[0].download_url
|
211 |
+
|
212 |
+
|
213 |
+
if not output_url:
|
214 |
+
logger.error(f"Runway task {task.id} SUCCEEDED, but no output URL found in task details: {task_details}")
|
215 |
+
# Attempt to log the full task_details object for inspection
|
216 |
+
try: logger.error(f"Full task details: {vars(task_details)}")
|
217 |
+
except: pass
|
218 |
+
return None
|
219 |
+
|
220 |
+
logger.info(f"Runway task {task.id} SUCCEEDED. Downloading video from: {output_url}")
|
221 |
+
video_response = requests.get(output_url, stream=True, timeout=300) # 5 min timeout for download
|
222 |
+
video_response.raise_for_status()
|
223 |
+
with open(output_video_filepath, 'wb') as f:
|
224 |
+
for chunk in video_response.iter_content(chunk_size=8192):
|
225 |
+
f.write(chunk)
|
226 |
+
logger.info(f"Runway Gen-4 video successfully downloaded and saved to: {output_video_filepath}")
|
227 |
+
return output_video_filepath
|
228 |
+
|
229 |
+
elif task_details.status in ['FAILED', 'ABORTED']:
|
230 |
+
error_message = "Unknown error"
|
231 |
+
if hasattr(task_details, 'error_message') and task_details.error_message:
|
232 |
+
error_message = task_details.error_message
|
233 |
+
elif hasattr(task_details, 'output') and hasattr(task_details.output, 'error') and task_details.output.error:
|
234 |
+
error_message = task_details.output.error
|
235 |
+
logger.error(f"Runway task {task.id} status: {task_details.status}. Error: {error_message}")
|
236 |
+
return None
|
237 |
+
|
238 |
+
logger.warning(f"Runway task {task.id} timed out after {max_polls * poll_interval} seconds.")
|
239 |
+
return None
|
240 |
|
241 |
+
except AttributeError as ae: # If SDK methods are not as expected
|
242 |
+
logger.error(f"AttributeError with RunwayML SDK: {ae}. Ensure SDK is up to date and methods match.", exc_info=True)
|
243 |
+
return None
|
244 |
+
except Exception as e_runway:
|
245 |
+
logger.error(f"Error during Runway Gen-4 API call or processing: {e_runway}", exc_info=True)
|
246 |
+
return None
|
247 |
+
|
248 |
+
# --- Other helper methods (_get_text_dimensions, _create_placeholder_image_content, _search_pexels_image, _create_placeholder_video_content) ---
|
249 |
+
# --- Keep these as they were in the previous full rewrite unless they need minor adjustments for the Gen-4 workflow ---
|
250 |
def _get_text_dimensions(self,tc,fo): di=fo.size if hasattr(fo,'size') else self.font_size_pil; return (0,di) if not tc else (lambda b:(b[2]-b[0],b[3]-b[1] if b[3]-b[1]>0 else di))(fo.getbbox(tc)) if hasattr(fo,'getbbox') else (lambda s:(s[0],s[1] if s[1]>0 else di))(fo.getsize(tc)) if hasattr(fo,'getsize') else (int(len(tc)*di*0.6),int(di*1.2))
|
251 |
def _create_placeholder_image_content(self,td,fn,sz=None):
|
252 |
+
if sz is None: sz = self.video_frame_size; img=Image.new('RGB',sz,color=(20,20,40));d=ImageDraw.Draw(img);pd=25;mw=sz[0]-(2*pd);ls=[];
|
253 |
+
if not td: td="(Placeholder Image)"
|
|
|
|
|
254 |
ws=td.split();cl=""
|
255 |
+
for w in ws: tl=cl+w+" ";raw_w,_=self._get_text_dimensions(tl,self.font);check_w=raw_w if raw_w > 0 else len(tl)*(self.font_size_pil*0.6); # Corrected w to check_w
|
256 |
+
if check_w<=mw:cl=tl;else: # Corrected w to check_w
|
257 |
+
if cl:ls.append(cl.strip());cl=w+" "
|
258 |
+
if cl.strip():ls.append(cl.strip())
|
259 |
+
if not ls and td:ls.append(td[:int(mw//(self._get_text_dimensions("A",self.font)[0]or 10))]+"..." if td else "(Text too long)");elif not ls:ls.append("(Placeholder Error)")
|
260 |
+
_,slh=self._get_text_dimensions("Ay",self.font);slh=slh if slh>0 else self.font_size_pil+2;mld=min(len(ls),(sz[1]-(2*pd))//(slh+2)) if slh>0 else 1;
|
261 |
+
if mld<=0:mld=1;yts=pd+(sz[1]-(2*pd)-mld*(slh+2))/2.0;yt=yts
|
262 |
+
for i in range(mld):lc=ls[i];lw,_=self._get_text_dimensions(lc,self.font);xt=(sz[0]-lw)/2.0;d.text((xt,yt),lc,font=self.font,fill=(200,200,180));yt+=slh+2
|
263 |
+
if i==6 and mld>7:d.text((xt,yt),"...",font=self.font,fill=(200,200,180));break
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
264 |
fp=os.path.join(self.output_dir,fn);
|
265 |
try:img.save(fp);return fp
|
266 |
+
except Exception as e:logger.error(f"Save placeholder img {fp}: {e}",exc_info=True);return None
|
|
|
267 |
def _search_pexels_image(self, q, ofnb):
|
268 |
+
if not self.USE_PEXELS or not self.pexels_api_key: return None; h={"Authorization":self.pexels_api_key};p={"query":q,"per_page":1,"orientation":"landscape","size":"large2x"}
|
269 |
+
pfn=ofnb.replace(".png",f"_pexels_{random.randint(1000,9999)}.jpg").replace(".mp4",f"_pexels_{random.randint(1000,9999)}.jpg");fp=os.path.join(self.output_dir,pfn)
|
270 |
+
try: logger.info(f"Pexels search: '{q}'");eq=" ".join(q.split()[:5]);p["query"]=eq;r=requests.get("https://api.pexels.com/v1/search",headers=h,params=p,timeout=20)
|
271 |
+
r.raise_for_status();d=r.json()
|
272 |
+
if d.get("photos") and len(d["photos"])>0:pu=d["photos"][0]["src"]["large2x"];ir=requests.get(pu,timeout=60);ir.raise_for_status();id_img=Image.open(io.BytesIO(ir.content)) # Renamed id to id_img
|
273 |
+
if id_img.mode!='RGB':id_img=id_img.convert('RGB');id_img.save(fp);logger.info(f"Pexels saved: {fp}");return fp
|
274 |
+
else: logger.info(f"No Pexels for: '{eq}'")
|
275 |
+
except Exception as e:logger.error(f"Pexels error ('{q}'): {e}",exc_info=True);return None
|
276 |
+
def _create_placeholder_video_content(self, td, fn, dur=4, sz=None): # Generic placeholder
|
277 |
+
if sz is None: sz = self.video_frame_size; fp = os.path.join(self.output_dir, fn); tc = None
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
278 |
try:
|
279 |
tc = TextClip(td, fontsize=50, color='white', font=self.video_overlay_font, bg_color='black', size=sz, method='caption').set_duration(dur)
|
280 |
tc.write_videofile(fp, fps=24, codec='libx264', preset='ultrafast', logger=None, threads=2)
|
281 |
+
logger.info(f"Generic placeholder video: {fp}"); return fp
|
282 |
+
except Exception as e: logger.error(f"Generic placeholder video error {fp}: {e}", exc_info=True); return None
|
283 |
finally:
|
284 |
if tc and hasattr(tc, 'close'): tc.close()
|
285 |
|
286 |
+
|
287 |
+
# --- generate_scene_asset (Main asset generation logic) ---
|
288 |
+
def generate_scene_asset(self, image_generation_prompt_text, motion_prompt_text_for_video,
|
289 |
+
scene_data, scene_identifier_filename_base,
|
290 |
+
generate_as_video_clip=False, runway_target_duration=5):
|
291 |
base_name, _ = os.path.splitext(scene_identifier_filename_base)
|
292 |
+
# Default asset_info for error state
|
293 |
+
asset_info = {'path': None, 'type': 'none', 'error': True,
|
294 |
+
'prompt_used': image_generation_prompt_text, # Default to image prompt
|
295 |
+
'error_message': 'Asset generation not fully attempted'}
|
296 |
+
|
297 |
+
# STEP 1: Generate/acquire the base image for Runway Gen-4 or for direct image output
|
298 |
+
input_image_for_runway_path = None
|
299 |
+
# Use a distinct name for the base image if it's only an intermediate step for video
|
300 |
+
base_image_filename = base_name + ("_base_for_video.png" if generate_as_video_clip else ".png")
|
301 |
+
base_image_filepath = os.path.join(self.output_dir, base_image_filename)
|
302 |
|
303 |
+
# Try DALL-E for base image
|
304 |
if self.USE_AI_IMAGE_GENERATION and self.openai_api_key:
|
305 |
max_r, att_n = 2, 0
|
306 |
for att_n in range(max_r):
|
307 |
try:
|
308 |
+
logger.info(f"Attempt {att_n+1} DALL-E (base image): {image_generation_prompt_text[:100]}...")
|
309 |
cl = openai.OpenAI(api_key=self.openai_api_key, timeout=90.0)
|
310 |
+
r = 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")
|
311 |
iu = r.data[0].url; rp = getattr(r.data[0], 'revised_prompt', None)
|
312 |
if rp: logger.info(f"DALL-E revised: {rp[:100]}...")
|
313 |
ir = requests.get(iu, timeout=120); ir.raise_for_status()
|
314 |
+
id_img = Image.open(io.BytesIO(ir.content))
|
315 |
+
if id_img.mode != 'RGB': id_img = id_img.convert('RGB')
|
316 |
+
id_img.save(base_image_filepath); logger.info(f"DALL-E base image saved: {base_image_filepath}");
|
317 |
+
input_image_for_runway_path = base_image_filepath
|
318 |
+
asset_info = {'path': base_image_filepath, 'type': 'image', 'error': False, 'prompt_used': image_generation_prompt_text, 'revised_prompt': rp}
|
319 |
+
break # DALL-E success
|
320 |
except openai.RateLimitError as e: logger.warning(f"OpenAI Rate Limit {att_n+1}: {e}. Retry..."); time.sleep(5*(att_n+1)); asset_info['error_message']=str(e)
|
321 |
+
except Exception as e: logger.error(f"DALL-E base image error: {e}", exc_info=True); asset_info['error_message']=str(e); break
|
322 |
+
if asset_info['error']: logger.warning(f"DALL-E failed after {att_n+1} attempts for base image.")
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
323 |
|
324 |
+
# Try Pexels if DALL-E failed or not used
|
325 |
+
if asset_info['error'] and self.USE_PEXELS:
|
326 |
+
logger.info("Attempting Pexels for base image.")
|
327 |
+
pqt = scene_data.get('pexels_search_query_감독', f"{scene_data.get('emotional_beat','')} {scene_data.get('setting_description','')}")
|
328 |
+
pp = self._search_pexels_image(pqt, base_image_filename) # Pass base image filename
|
329 |
+
if pp: input_image_for_runway_path = pp; asset_info = {'path': pp, 'type': 'image', 'error': False, 'prompt_used': f"Pexels: {pqt}"}
|
330 |
+
else: current_em = asset_info.get('error_message',""); asset_info['error_message']=(current_em + " Pexels failed for base image.").strip()
|
331 |
+
|
332 |
+
# Fallback to placeholder for base image if all above failed
|
333 |
if asset_info['error']:
|
334 |
+
logger.warning("Base image (DALL-E/Pexels) failed. Using placeholder for base image.")
|
335 |
+
ppt = asset_info.get('prompt_used', image_generation_prompt_text) # Use the original image prompt
|
336 |
+
php = self._create_placeholder_image_content(f"[Base Img Placeholder] {ppt[:100]}...", base_image_filename)
|
337 |
+
if php: input_image_for_runway_path = php; asset_info = {'path': php, 'type': 'image', 'error': False, 'prompt_used': ppt}
|
338 |
+
else: current_em=asset_info.get('error_message',"");asset_info['error_message']=(current_em + " Base placeholder failed.").strip()
|
339 |
+
|
340 |
+
# STEP 2: If video clip is requested, use the generated base image with RunwayML
|
341 |
+
if generate_as_video_clip:
|
342 |
+
if not input_image_for_runway_path: # If base image generation totally failed
|
343 |
+
logger.error("Cannot generate RunwayML video: base image path is missing or generation failed.")
|
344 |
+
asset_info['error'] = True # Ensure error state is propagated
|
345 |
+
asset_info['error_message'] = (asset_info.get('error_message',"") + " Base image missing, Runway video aborted.").strip()
|
346 |
+
asset_info['type'] = 'none' # No valid asset produced
|
347 |
+
return asset_info
|
348 |
+
|
349 |
+
if self.USE_RUNWAYML:
|
350 |
+
logger.info(f"Proceeding to Runway Gen-4 video for {base_name} using base image: {input_image_for_runway_path}")
|
351 |
+
video_path = self._generate_video_clip_with_runwayml(
|
352 |
+
text_prompt_for_motion=motion_prompt_text_for_video,
|
353 |
+
input_image_path=input_image_for_runway_path,
|
354 |
+
scene_identifier_filename_base=base_name, # _runway_gen4.mp4 will be appended
|
355 |
+
target_duration_seconds=runway_target_duration
|
356 |
+
)
|
357 |
+
if video_path and os.path.exists(video_path):
|
358 |
+
# Success generating video
|
359 |
+
asset_info = {'path': video_path, 'type': 'video', 'error': False,
|
360 |
+
'prompt_used': motion_prompt_text_for_video, # This is the prompt for Runway
|
361 |
+
'base_image_path': input_image_for_runway_path}
|
362 |
+
else:
|
363 |
+
# RunwayML failed, return the base image info but mark video as failed
|
364 |
+
logger.warning(f"RunwayML video generation failed for {base_name}. Using the base image as fallback.")
|
365 |
+
asset_info['error'] = True # Video step specifically failed
|
366 |
+
asset_info['error_message'] = (asset_info.get('error_message', "Base image generated.") + " RunwayML video step failed; using base image instead.").strip()
|
367 |
+
asset_info['path'] = input_image_for_runway_path # Path of the base image
|
368 |
+
asset_info['type'] = 'image' # Fallback asset type is image
|
369 |
+
asset_info['prompt_used'] = image_generation_prompt_text # Prompt for the base image
|
370 |
+
else: # RunwayML not enabled, use base image
|
371 |
+
logger.warning("RunwayML selected but not enabled/configured. Using base image.")
|
372 |
+
asset_info['error'] = True # Mark that video wasn't generated
|
373 |
+
asset_info['error_message'] = (asset_info.get('error_message', "Base image generated.") + " RunwayML disabled; using base image.").strip()
|
374 |
+
asset_info['path'] = input_image_for_runway_path
|
375 |
+
asset_info['type'] = 'image'
|
376 |
+
asset_info['prompt_used'] = image_generation_prompt_text
|
377 |
+
# If not generate_as_video_clip, asset_info already holds the result of image generation
|
378 |
return asset_info
|
379 |
|
380 |
+
|
381 |
+
# --- generate_narration_audio (Keep as before) ---
|
382 |
def generate_narration_audio(self, text_to_narrate, output_filename="narration_overall.mp3"):
|
383 |
+
if not self.USE_ELEVENLABS or not self.elevenlabs_client or not text_to_narrate: logger.info("11L skip."); return None; afp=os.path.join(self.output_dir,output_filename)
|
384 |
+
try: logger.info(f"11L audio (Voice:{self.elevenlabs_voice_id}): {text_to_narrate[:70]}..."); asm=None
|
385 |
+
if hasattr(self.elevenlabs_client,'text_to_speech')and hasattr(self.elevenlabs_client.text_to_speech,'stream'):asm=self.elevenlabs_client.text_to_speech.stream;logger.info("Using 11L .text_to_speech.stream()")
|
386 |
+
elif hasattr(self.elevenlabs_client,'generate_stream'):asm=self.elevenlabs_client.generate_stream;logger.info("Using 11L .generate_stream()")
|
387 |
+
elif hasattr(self.elevenlabs_client,'generate'):logger.info("Using 11L .generate()");vp=Voice(voice_id=str(self.elevenlabs_voice_id),settings=self.elevenlabs_voice_settings)if Voice and self.elevenlabs_voice_settings else str(self.elevenlabs_voice_id);ab=self.elevenlabs_client.generate(text=text_to_narrate,voice=vp,model="eleven_multilingual_v2");
|
388 |
+
with open(afp,"wb")as f:f.write(ab);logger.info(f"11L audio (non-stream): {afp}");return afp
|
389 |
+
else:logger.error("No 11L audio method.");return None
|
390 |
+
if asm:vps={"voice_id":str(self.elevenlabs_voice_id)}
|
391 |
+
if self.elevenlabs_voice_settings:
|
392 |
+
if hasattr(self.elevenlabs_voice_settings,'model_dump'):vps["voice_settings"]=self.elevenlabs_voice_settings.model_dump()
|
393 |
+
elif hasattr(self.elevenlabs_voice_settings,'dict'):vps["voice_settings"]=self.elevenlabs_voice_settings.dict()
|
394 |
+
else:vps["voice_settings"]=self.elevenlabs_voice_settings
|
395 |
+
adi=asm(text=text_to_narrate,model_id="eleven_multilingual_v2",**vps)
|
396 |
+
with open(afp,"wb")as f:
|
397 |
+
for c in adi:
|
398 |
+
if c:f.write(c)
|
399 |
+
logger.info(f"11L audio (stream): {afp}");return afp
|
400 |
+
except Exception as e:logger.error(f"11L audio error: {e}",exc_info=True);return None
|
401 |
+
|
402 |
+
|
403 |
+
# --- assemble_animatic_from_assets (Keep robust image processing, C-contiguous, debug saves, pix_fmt) ---
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
404 |
def assemble_animatic_from_assets(self, asset_data_list, overall_narration_path=None, output_filename="final_video.mp4", fps=24):
|
405 |
+
if not asset_data_list: logger.warning("No assets for animatic."); return None
|
406 |
+
processed_clips = []; narration_clip = None; final_clip = None # final_composite_clip_obj renamed to final_clip
|
407 |
+
logger.info(f"Assembling from {len(asset_data_list)} assets. Frame: {self.video_frame_size}.")
|
|
|
|
|
|
|
|
|
|
|
|
|
408 |
|
409 |
for i, asset_info in enumerate(asset_data_list):
|
410 |
+
asset_path, asset_type, scene_dur = asset_info.get('path'), asset_info.get('type'), asset_info.get('duration', 4.5)
|
411 |
+
scene_num, key_action = asset_info.get('scene_num', i + 1), asset_info.get('key_action', '')
|
412 |
+
logger.info(f"S{scene_num}: Path='{asset_path}', Type='{asset_type}', Dur='{scene_dur}'s")
|
|
|
|
|
|
|
|
|
413 |
|
414 |
+
if not (asset_path and os.path.exists(asset_path)): logger.warning(f"S{scene_num}: Not found '{asset_path}'. Skip."); continue
|
415 |
+
if scene_dur <= 0: logger.warning(f"S{scene_num}: Invalid duration ({scene_dur}s). Skip."); continue
|
|
|
|
|
416 |
|
417 |
+
current_scene_mvpy_clip = None
|
418 |
try:
|
419 |
if asset_type == 'image':
|
420 |
+
pil_img = Image.open(asset_path); logger.debug(f"S{scene_num}: Loaded img. Mode:{pil_img.mode}, Size:{pil_img.size}")
|
421 |
+
img_rgba = pil_img.convert('RGBA') if pil_img.mode != 'RGBA' else pil_img.copy()
|
422 |
+
thumb = img_rgba.copy(); rf = Image.Resampling.LANCZOS if hasattr(Image.Resampling,'LANCZOS') else Image.BILINEAR; thumb.thumbnail(self.video_frame_size,rf)
|
423 |
+
cv_rgba = Image.new('RGBA',self.video_frame_size,(0,0,0,0)); xo,yo=(self.video_frame_size[0]-thumb.width)//2,(self.video_frame_size[1]-thumb.height)//2
|
424 |
+
cv_rgba.paste(thumb,(xo,yo),thumb)
|
425 |
+
final_rgb_pil = Image.new("RGB",self.video_frame_size,(0,0,0)); final_rgb_pil.paste(cv_rgba,mask=cv_rgba.split()[3])
|
426 |
+
dbg_path = os.path.join(self.output_dir,f"debug_PRE_NUMPY_S{scene_num}.png"); final_rgb_pil.save(dbg_path); logger.info(f"DEBUG: Saved PRE_NUMPY_S{scene_num} to {dbg_path}")
|
427 |
+
frame_np = np.array(final_rgb_pil,dtype=np.uint8);
|
428 |
+
if not frame_np.flags['C_CONTIGUOUS']: frame_np=np.ascontiguousarray(frame_np,dtype=np.uint8)
|
429 |
+
logger.debug(f"S{scene_num}: NumPy for MoviePy. Shape:{frame_np.shape}, DType:{frame_np.dtype}, C-Contig:{frame_np.flags['C_CONTIGUOUS']}")
|
430 |
+
if frame_np.size==0 or frame_np.ndim!=3 or frame_np.shape[2]!=3: logger.error(f"S{scene_num}: Invalid NumPy. Skip."); continue
|
431 |
+
clip_base = ImageClip(frame_np,transparent=False).set_duration(scene_dur)
|
432 |
+
mvpy_dbg_path=os.path.join(self.output_dir,f"debug_MOVIEPY_FRAME_S{scene_num}.png"); clip_base.save_frame(mvpy_dbg_path,t=0.1); logger.info(f"DEBUG: Saved MOVIEPY_FRAME_S{scene_num} to {mvpy_dbg_path}")
|
433 |
+
clip_fx = clip_base
|
434 |
+
try: es=random.uniform(1.03,1.08); clip_fx=clip_base.fx(vfx.resize,lambda t:1+(es-1)*(t/scene_dur) if scene_dur>0 else 1).set_position('center')
|
435 |
+
except Exception as e: logger.error(f"S{scene_num} Ken Burns error: {e}",exc_info=False)
|
436 |
+
current_scene_mvpy_clip = clip_fx
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
437 |
elif asset_type == 'video':
|
438 |
+
src_clip=None
|
|
|
439 |
try:
|
440 |
+
src_clip=VideoFileClip(asset_path,target_resolution=(self.video_frame_size[1],self.video_frame_size[0])if self.video_frame_size else None, audio=False) # Explicitly no audio from source video clips
|
441 |
+
tmp_clip=src_clip
|
442 |
+
if src_clip.duration!=scene_dur:
|
443 |
+
if src_clip.duration>scene_dur:tmp_clip=src_clip.subclip(0,scene_dur)
|
444 |
+
else:
|
445 |
+
if scene_dur/src_clip.duration > 1.5 and src_clip.duration>0.1:tmp_clip=src_clip.loop(duration=scene_dur)
|
446 |
+
else:tmp_clip=src_clip.set_duration(src_clip.duration);logger.info(f"S{scene_num} Video clip ({src_clip.duration:.2f}s) shorter than target ({scene_dur:.2f}s).")
|
447 |
+
current_scene_mvpy_clip=tmp_clip.set_duration(scene_dur)
|
448 |
+
if current_scene_mvpy_clip.size!=list(self.video_frame_size):current_scene_mvpy_clip=current_scene_mvpy_clip.resize(self.video_frame_size)
|
449 |
+
except Exception as e:logger.error(f"S{scene_num} Video load error '{asset_path}':{e}",exc_info=True);continue
|
450 |
finally:
|
451 |
+
if src_clip and src_clip is not current_scene_mvpy_clip and hasattr(src_clip,'close'):src_clip.close()
|
452 |
+
else: logger.warning(f"S{scene_num} Unknown asset type '{asset_type}'. Skip."); continue
|
|
|
453 |
|
454 |
+
if current_scene_mvpy_clip and key_action:
|
455 |
try:
|
456 |
+
to_dur=min(current_scene_mvpy_clip.duration-0.5,current_scene_mvpy_clip.duration*0.8)if current_scene_mvpy_clip.duration>0.5 else current_scene_mvpy_clip.duration
|
457 |
+
to_start=0.25
|
458 |
+
if to_dur > 0 : # Only add text if duration is positive
|
459 |
+
txt_c=TextClip(f"Scene {scene_num}\n{key_action}",fontsize=self.video_overlay_font_size,color=self.video_overlay_font_color,font=self.video_overlay_font,bg_color='rgba(10,10,20,0.7)',method='caption',align='West',size=(self.video_frame_size[0]*0.9,None),kerning=-1,stroke_color='black',stroke_width=1.5).set_duration(to_dur).set_start(to_start).set_position(('center',0.92),relative=True)
|
460 |
+
current_scene_mvpy_clip=CompositeVideoClip([current_scene_mvpy_clip,txt_c],size=self.video_frame_size,use_bgclip=True)
|
461 |
+
else: logger.warning(f"S{scene_num}: Text overlay duration is zero or negative. Skipping text overlay.")
|
462 |
+
except Exception as e:logger.error(f"S{scene_num} TextClip error:{e}. No text.",exc_info=True)
|
463 |
+
if current_scene_mvpy_clip:processed_clips.append(current_scene_mvpy_clip);logger.info(f"S{scene_num} Processed. Dur:{current_scene_mvpy_clip.duration:.2f}s.")
|
464 |
+
except Exception as e:logger.error(f"MAJOR Error S{scene_num} ({asset_path}):{e}",exc_info=True)
|
465 |
+
finally:
|
466 |
+
if current_scene_mvpy_clip and hasattr(current_scene_mvpy_clip,'close'): # Check if it's a VideoFileClip instance that needs closing
|
467 |
+
if hasattr(current_scene_mvpy_clip, 'reader') and current_scene_mvpy_clip.reader: current_scene_mvpy_clip.close()
|
468 |
+
elif not hasattr(current_scene_mvpy_clip, 'reader'): current_scene_mvpy_clip.close() # For ImageClip if close() is added
|
469 |
+
|
470 |
+
if not processed_clips:logger.warning("No clips processed. Abort.");return None
|
471 |
+
td=0.75
|
|
|
|
|
|
|
472 |
try:
|
473 |
+
logger.info(f"Concatenating {len(processed_clips)} clips.");
|
474 |
+
if len(processed_clips)>1:final_clip=concatenate_videoclips(processed_clips,padding=-td if td>0 else 0,method="compose")
|
475 |
+
elif processed_clips:final_clip=processed_clips[0]
|
476 |
+
if not final_clip:logger.error("Concatenation failed.");return None
|
477 |
+
logger.info(f"Concatenated dur:{final_clip.duration:.2f}s")
|
478 |
+
if td>0 and final_clip.duration>0:
|
479 |
+
if final_clip.duration>td*2:final_clip=final_clip.fx(vfx.fadein,td).fx(vfx.fadeout,td)
|
480 |
+
else:final_clip=final_clip.fx(vfx.fadein,min(td,final_clip.duration/2.0))
|
481 |
+
if overall_narration_path and os.path.exists(overall_narration_path) and final_clip.duration>0:
|
482 |
+
try:narration_clip=AudioFileClip(overall_narration_path);final_clip=final_clip.set_audio(narration_clip);logger.info("Narration added.")
|
483 |
+
except Exception as e:logger.error(f"Narration add error:{e}",exc_info=True)
|
484 |
+
elif final_clip.duration<=0:logger.warning("Video no duration. No audio.")
|
485 |
+
if final_clip and final_clip.duration>0:
|
486 |
+
op=os.path.join(self.output_dir,output_filename);logger.info(f"Writing video:{op} (Dur:{final_clip.duration:.2f}s)")
|
487 |
+
final_clip.write_videofile(op,fps=fps,codec='libx264',preset='medium',audio_codec='aac',temp_audiofile=os.path.join(self.output_dir,f'temp-audio-{os.urandom(4).hex()}.m4a'),remove_temp=True,threads=os.cpu_count()or 2,logger='bar',bitrate="5000k",ffmpeg_params=["-pix_fmt", "yuv420p"])
|
488 |
+
logger.info(f"Video created:{op}");return op
|
489 |
+
else:logger.error("Final clip invalid. No write.");return None
|
490 |
+
except Exception as e:logger.error(f"Video write error:{e}",exc_info=True);return None
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
491 |
finally:
|
492 |
logger.debug("Closing all MoviePy clips in `assemble_animatic_from_assets` finally block.")
|
493 |
+
all_clips_to_close = processed_clips + ([narration_clip] if narration_clip else []) + ([final_clip] if final_clip else [])
|
494 |
+
for clip_obj in all_clips_to_close: # Use a different name to avoid scope issues
|
495 |
if clip_obj and hasattr(clip_obj, 'close'):
|
496 |
try: clip_obj.close()
|
497 |
+
except Exception as e_close: logger.warning(f"Ignoring error while closing a clip: {type(clip_obj).__name__} - {e_close}")
|