mgbam commited on
Commit
3313da9
·
verified ·
1 Parent(s): 63525c7

Update core/visual_engine.py

Browse files
Files changed (1) hide show
  1. core/visual_engine.py +212 -170
core/visual_engine.py CHANGED
@@ -61,37 +61,40 @@ class VisualEngine:
61
  self.output_dir = output_dir
62
  os.makedirs(self.output_dir, exist_ok=True)
63
 
64
- self.font_filename = "arial.ttf"
65
  font_paths_to_try = [
66
  self.font_filename,
67
- f"/usr/share/fonts/truetype/dejavu/DejaVuSans-Bold.ttf", # Common on Linux
68
- f"/usr/share/fonts/truetype/liberation/LiberationSans-Bold.ttf", # Common on Linux
69
  f"/System/Library/Fonts/Supplemental/Arial.ttf", # macOS
70
  f"C:/Windows/Fonts/arial.ttf", # Windows
71
- f"/usr/local/share/fonts/truetype/mycustomfonts/{self.font_filename}" # Custom container path
72
  ]
73
  self.font_path_pil = next((p for p in font_paths_to_try if os.path.exists(p)), None)
74
  self.font_size_pil = 20
75
  self.video_overlay_font_size = 30
76
  self.video_overlay_font_color = 'white'
77
- self.video_overlay_font = 'Liberation-Sans-Bold' # For MoviePy TextClip (ImageMagick name)
 
 
 
78
 
79
  try:
80
  if self.font_path_pil:
81
  self.font = ImageFont.truetype(self.font_path_pil, self.font_size_pil)
82
  logger.info(f"Pillow font loaded: {self.font_path_pil}.")
83
- else: # Fallback to default if no path found
84
  self.font = ImageFont.load_default()
85
- logger.warning("Custom Pillow font not found from paths. Using default. Text rendering might be basic.")
86
- self.font_size_pil = 10 # Default font is smaller
87
- except IOError as e_font: # Catch specific IOError for font loading
88
- logger.error(f"Pillow font loading IOError for '{self.font_path_pil if self.font_path_pil else 'default'}': {e_font}. Using default.")
89
  self.font = ImageFont.load_default()
90
  self.font_size_pil = 10
91
 
92
  self.openai_api_key = None; self.USE_AI_IMAGE_GENERATION = False
93
  self.dalle_model = "dall-e-3"; self.image_size_dalle3 = "1792x1024"
94
- self.video_frame_size = (1280, 720) # Standard HD 16:9
95
 
96
  self.elevenlabs_api_key = None; self.USE_ELEVENLABS = False
97
  self.elevenlabs_client = None
@@ -108,7 +111,7 @@ class VisualEngine:
108
 
109
  def set_openai_api_key(self,k):
110
  self.openai_api_key=k; self.USE_AI_IMAGE_GENERATION=bool(k)
111
- logger.info(f"DALL-E ({self.dalle_model}) {'Ready.' if k else 'Disabled (no API key).'}")
112
 
113
  def set_elevenlabs_api_key(self,api_key, voice_id_from_secret=None):
114
  self.elevenlabs_api_key=api_key
@@ -119,39 +122,38 @@ class VisualEngine:
119
  self.USE_ELEVENLABS=bool(self.elevenlabs_client)
120
  logger.info(f"ElevenLabs Client {'Ready' if self.USE_ELEVENLABS else 'Failed Init'} (Voice ID: {self.elevenlabs_voice_id}).")
121
  except Exception as e: logger.error(f"ElevenLabs client init error: {e}. Disabled.", exc_info=True); self.USE_ELEVENLABS=False
122
- else: self.USE_ELEVENLABS=False; logger.info("ElevenLabs Disabled (no API key or SDK issue).")
123
 
124
  def set_pexels_api_key(self,k):
125
  self.pexels_api_key=k; self.USE_PEXELS=bool(k)
126
- logger.info(f"Pexels Search {'Ready.' if k else 'Disabled (no API key).'}")
127
 
128
  def set_runway_api_key(self, k):
129
  self.runway_api_key = k
130
  if k and RUNWAYML_SDK_IMPORTED and RunwayMLClient:
131
  try:
132
  # self.runway_client = RunwayMLClient(api_key=k) # Actual initialization
133
- self.USE_RUNWAYML = True # Assume success for placeholder with hypothetical SDK
134
  logger.info(f"RunwayML Client (Placeholder with SDK) {'Ready.' if self.USE_RUNWAYML else 'Failed Init.'}")
135
  except Exception as e: logger.error(f"RunwayML client (Placeholder with SDK) init error: {e}. Disabled.", exc_info=True); self.USE_RUNWAYML = False
136
- elif k: # API key provided, but SDK might not be used/imported (e.g., direct HTTP)
137
  self.USE_RUNWAYML = True
138
  logger.info("RunwayML API Key set. Using direct API calls or placeholder (SDK not fully integrated/imported).")
139
  else: self.USE_RUNWAYML = False; logger.info("RunwayML Disabled (no API key).")
140
 
141
  def _get_text_dimensions(self,text_content,font_obj):
142
- if not text_content: return 0,self.font_size_pil
143
  try:
144
  if hasattr(font_obj,'getbbox'):
145
  bbox=font_obj.getbbox(text_content);w=bbox[2]-bbox[0];h=bbox[3]-bbox[1]
146
- return w, h if h > 0 else self.font_size_pil
147
  elif hasattr(font_obj,'getsize'):
148
  w,h=font_obj.getsize(text_content)
149
- return w, h if h > 0 else self.font_size_pil
150
- else: return int(len(text_content)*self.font_size_pil*0.6),int(self.font_size_pil*1.2 if self.font_size_pil*1.2>0 else self.font_size_pil)
151
  except Exception as e: logger.warning(f"Error in _get_text_dimensions for '{text_content[:20]}...': {e}"); return int(len(text_content)*self.font_size_pil*0.6),int(self.font_size_pil*1.2)
152
 
153
  def _create_placeholder_image_content(self,text_description,filename,size=None):
154
- # (No significant changes from your previous correct version)
155
  if size is None: size = self.video_frame_size
156
  img=Image.new('RGB',size,color=(20,20,40));d=ImageDraw.Draw(img);padding=25;max_w=size[0]-(2*padding);lines=[];
157
  if not text_description: text_description="(Placeholder: No prompt text)"
@@ -163,7 +165,7 @@ class VisualEngine:
163
  if current_line: lines.append(current_line.strip());
164
  current_line=word+" "
165
  if current_line.strip(): lines.append(current_line.strip())
166
- if not lines and text_description: lines.append(text_description[:int(max_w//(self.font_size_pil*0.6 +1))]+"..." if text_description else "(Text too long)")
167
  elif not lines: lines.append("(Placeholder Text Error)")
168
  _,single_line_h=self._get_text_dimensions("Ay",self.font); single_line_h = single_line_h if single_line_h > 0 else self.font_size_pil + 2
169
  max_lines_to_display=min(len(lines),(size[1]-(2*padding))//(single_line_h+2)) if single_line_h > 0 else 1
@@ -179,9 +181,8 @@ class VisualEngine:
179
  except Exception as e:logger.error(f"Saving placeholder image {filepath}: {e}", exc_info=True);return None
180
 
181
  def _search_pexels_image(self, query, output_filename_base):
182
- # (No significant changes from your previous correct version)
183
  if not self.USE_PEXELS or not self.pexels_api_key: return None
184
- headers = {"Authorization": self.pexels_api_key}; params = {"query": query, "per_page": 1, "orientation": "landscape", "size": "large"}
185
  pexels_filename = output_filename_base.replace(".png", f"_pexels_{random.randint(1000,9999)}.jpg").replace(".mp4", f"_pexels_{random.randint(1000,9999)}.jpg")
186
  filepath = os.path.join(self.output_dir, pexels_filename)
187
  try:
@@ -202,11 +203,20 @@ class VisualEngine:
202
  if not self.USE_RUNWAYML or not self.runway_api_key:
203
  logger.warning("RunwayML not enabled or API key missing. Cannot generate video clip.")
204
  return None
205
- output_video_filename = scene_identifier_filename_base.replace(".png", ".mp4") # Ensure .mp4 extension
206
  output_video_filepath = os.path.join(self.output_dir, output_video_filename)
207
  logger.info(f"Attempting RunwayML video generation for: {prompt_text[:100]}... (Target duration: {target_duration_seconds}s)")
208
  # --- START ACTUAL RUNWAYML API INTERACTION (HYPOTHETICAL - NEEDS IMPLEMENTATION) ---
209
- # ... (Your actual RunwayML API call logic would go here) ...
 
 
 
 
 
 
 
 
 
210
  # --- END ACTUAL RUNWAYML API INTERACTION (HYPOTHETICAL) ---
211
  logger.warning("Using PLACEHOLDER video generation for RunwayML as actual API calls are not implemented.")
212
  return self._create_placeholder_video_content(f"[RunwayML Placeholder] {prompt_text}", output_video_filename, duration=target_duration_seconds)
@@ -214,15 +224,16 @@ class VisualEngine:
214
  def _create_placeholder_video_content(self, text_description, filename, duration=4, size=None):
215
  if size is None: size = self.video_frame_size
216
  filepath = os.path.join(self.output_dir, filename)
217
- txt_clip = TextClip(text_description, fontsize=50, color='white', font=self.video_overlay_font,
218
- bg_color='black', size=size, method='caption').set_duration(duration)
219
  try:
220
- txt_clip.write_videofile(filepath, fps=24, codec='libx264', preset='ultrafast', logger=None)
 
 
221
  logger.info(f"Placeholder video saved: {filepath}")
222
  return filepath
223
  except Exception as e: logger.error(f"Failed to create placeholder video {filepath}: {e}", exc_info=True); return None
224
  finally:
225
- if hasattr(txt_clip, 'close'): txt_clip.close()
226
 
227
  def generate_scene_asset(self, image_prompt_text, scene_data, scene_identifier_filename_base,
228
  generate_as_video_clip=False, runway_target_duration=4, input_image_for_runway=None):
@@ -238,22 +249,18 @@ class VisualEngine:
238
  )
239
  if video_path and os.path.exists(video_path):
240
  asset_info = {'path': video_path, 'type': 'video', 'error': False, 'prompt_used': image_prompt_text}
241
- return asset_info # Successfully generated video
242
- else:
243
- logger.warning(f"RunwayML video clip generation failed for {base_name}. Falling back to image.")
244
- asset_info['error_message'] = "RunwayML video generation failed."
245
- # Fall through to image generation
246
 
247
- # Image Generation (DALL-E, Pexels, Placeholder)
248
- image_filename_with_ext = base_name + ".png" # Ensure .png for image
249
  filepath = os.path.join(self.output_dir, image_filename_with_ext)
250
- asset_info['type'] = 'image' # Tentatively set type to image for this path
251
 
252
  if self.USE_AI_IMAGE_GENERATION and self.openai_api_key:
253
- max_retries = 2
254
- for attempt in range(max_retries):
255
  try:
256
- logger.info(f"Attempt {attempt+1}: DALL-E ({self.dalle_model}) for: {image_prompt_text[:100]}...")
257
  client = openai.OpenAI(api_key=self.openai_api_key, timeout=90.0)
258
  response = client.images.generate(model=self.dalle_model, prompt=image_prompt_text, n=1, size=self.image_size_dalle3, quality="hd", response_format="url", style="vivid")
259
  image_url = response.data[0].url; revised_prompt = getattr(response.data[0], 'revised_prompt', None)
@@ -263,39 +270,37 @@ class VisualEngine:
263
  if img_data.mode != 'RGB': img_data = img_data.convert('RGB')
264
  img_data.save(filepath); logger.info(f"AI Image (DALL-E) saved: {filepath}");
265
  asset_info = {'path': filepath, 'type': 'image', 'error': False, 'prompt_used': image_prompt_text, 'revised_prompt': revised_prompt}
266
- return asset_info
267
- except openai.RateLimitError as e_rate: logger.warning(f"OpenAI Rate Limit: {e_rate}. Retrying..."); time.sleep(5 * (attempt + 1)); asset_info['error_message'] = str(e_rate)
268
  except openai.APIError as e_api: logger.error(f"OpenAI API Error: {e_api}"); asset_info['error_message'] = str(e_api); break
269
  except requests.exceptions.RequestException as e_req: logger.error(f"Requests Error (DALL-E download): {e_req}"); asset_info['error_message'] = str(e_req); break
270
  except Exception as e_gen: logger.error(f"Generic error (DALL-E gen): {e_gen}", exc_info=True); asset_info['error_message'] = str(e_gen); break
271
- if attempt == max_retries - 1: logger.error("Max retries for DALL-E RateLimitError."); break
272
- if asset_info['error']: logger.warning("DALL-E generation failed. Trying Pexels fallback...")
273
 
274
- if self.USE_PEXELS and (asset_info['error'] or not (self.USE_AI_IMAGE_GENERATION and self.openai_api_key)): # Try Pexels if DALL-E failed or disabled
275
  pexels_query_text = scene_data.get('pexels_search_query_감독', f"{scene_data.get('emotional_beat','')} {scene_data.get('setting_description','')}")
276
  pexels_path = self._search_pexels_image(pexels_query_text, image_filename_with_ext)
277
  if pexels_path:
278
  asset_info = {'path': pexels_path, 'type': 'image', 'error': False, 'prompt_used': f"Pexels: {pexels_query_text}"}
279
  return asset_info
280
- asset_info['error_message'] = (asset_info.get('error_message', "") + " Pexels search also failed or disabled.").strip()
281
- if not asset_info['error']: logger.warning("Pexels search failed or disabled.") # If DALL-E wasn't even tried
 
282
 
283
- # Fallback to placeholder if all else fails
284
- if asset_info['error']: # Only create placeholder if previous steps failed
285
- logger.warning("All generation methods failed. Using placeholder image.")
286
- placeholder_prompt_text = asset_info.get('prompt_used', image_prompt_text) # Use the prompt that was attempted
287
  placeholder_path = self._create_placeholder_image_content(f"[Fallback Placeholder] {placeholder_prompt_text[:100]}...", image_filename_with_ext)
288
  if placeholder_path:
289
  asset_info = {'path': placeholder_path, 'type': 'image', 'error': False, 'prompt_used': placeholder_prompt_text}
290
- return asset_info
291
- else: # Final failure
292
- asset_info['error_message'] = (asset_info.get('error_message', "") + " Placeholder creation also failed.").strip()
293
- return asset_info # Return whatever state asset_info is in (could be error=True)
294
 
295
  def generate_narration_audio(self, text_to_narrate, output_filename="narration_overall.mp3"):
296
- # (No significant changes from your previous correct version, ensure error handling is robust)
297
  if not self.USE_ELEVENLABS or not self.elevenlabs_client or not text_to_narrate:
298
- logger.info("ElevenLabs conditions not met (API key, client init, or text). Skipping audio.")
299
  return None
300
  audio_filepath = os.path.join(self.output_dir, output_filename)
301
  try:
@@ -312,13 +317,12 @@ class VisualEngine:
312
  logger.info(f"ElevenLabs audio (non-streamed) saved: {audio_filepath}"); return audio_filepath
313
  else: logger.error("No recognized audio generation method found on ElevenLabs client."); return None
314
 
315
- if audio_stream_method:
316
  voice_param_for_stream = {"voice_id": str(self.elevenlabs_voice_id)}
317
- if self.elevenlabs_voice_settings and hasattr(self.elevenlabs_voice_settings, 'model_dump'): # Pydantic v2 for elevenlabs sdk >=1.0
318
- voice_param_for_stream["voice_settings"] = self.elevenlabs_voice_settings.model_dump()
319
- elif self.elevenlabs_voice_settings and hasattr(self.elevenlabs_voice_settings, 'dict'): # Pydantic v1 for elevenlabs sdk <1.0
320
- voice_param_for_stream["voice_settings"] = self.elevenlabs_voice_settings.dict()
321
- elif self.elevenlabs_voice_settings : voice_param_for_stream["voice_settings"] = self.elevenlabs_voice_settings
322
 
323
  audio_data_iterator = audio_stream_method(text=text_to_narrate, model_id="eleven_multilingual_v2", **voice_param_for_stream)
324
  with open(audio_filepath, "wb") as f:
@@ -336,153 +340,191 @@ class VisualEngine:
336
 
337
  processed_moviepy_clips = []
338
  narration_audio_clip = None
339
- final_composite_clip = None # Renamed to avoid conflict in finally block
340
- total_video_duration_from_assets = sum(item.get('duration', 4.5) for item in asset_data_list)
341
- logger.info(f"Assembling animatic from {len(asset_data_list)} assets. Target frame: {self.video_frame_size}. Approx total duration: {total_video_duration_from_assets:.2f}s.")
342
 
343
  for i, asset_info in enumerate(asset_data_list):
344
  asset_path = asset_info.get('path')
345
  asset_type = asset_info.get('type')
346
- target_scene_duration = asset_info.get('duration', 4.5)
347
  scene_num = asset_info.get('scene_num', i + 1)
348
  key_action = asset_info.get('key_action', '')
349
 
350
- logger.info(f"Processing Scene {scene_num}: Path='{asset_path}', Type='{asset_type}', Target Duration='{target_scene_duration}'s")
351
 
352
  if not (asset_path and os.path.exists(asset_path)):
353
- logger.warning(f"Asset not found for Scene {scene_num}: {asset_path}. Skipping.")
354
- continue
355
  if target_scene_duration <= 0:
356
- logger.warning(f"Scene {scene_num} has invalid duration ({target_scene_duration}s). Skipping.")
357
- continue
358
 
359
- current_clip_for_scene = None
360
  try:
361
  if asset_type == 'image':
362
- logger.debug(f"S{scene_num}: Loading image asset from {asset_path}")
363
  pil_img = Image.open(asset_path)
364
- logger.debug(f"S{scene_num}: Image loaded. Mode: {pil_img.mode}, Size: {pil_img.size}")
365
 
366
- # Ensure image is RGBA for consistent pasting, then convert to RGB for MoviePy
367
- if pil_img.mode != 'RGBA':
368
- pil_img = pil_img.convert('RGBA') # Convert to RGBA to handle transparency uniformly
369
 
370
- img_copy = pil_img.copy()
 
371
  resample_filter = Image.Resampling.LANCZOS if hasattr(Image.Resampling, 'LANCZOS') else (Image.ANTIALIAS if hasattr(Image, 'ANTIALIAS') else Image.BILINEAR)
372
- img_copy.thumbnail(self.video_frame_size, resample_filter)
373
- logger.debug(f"S{scene_num}: Image thumbnailed to: {img_copy.size}")
374
-
375
- # Create an RGBA canvas, paste the (potentially RGBA) image onto it
376
- canvas_rgba = Image.new('RGBA', self.video_frame_size, (0, 0, 0, 0)) # Fully transparent
377
- xo, yo = (self.video_frame_size[0] - img_copy.width) // 2, (self.video_frame_size[1] - img_copy.height) // 2
378
- canvas_rgba.paste(img_copy, (xo, yo), img_copy) # Paste using image's own alpha
379
- logger.debug(f"S{scene_num}: Image pasted onto RGBA canvas.")
380
-
381
- # Now create a final RGB canvas and paste the RGBA canvas onto it, effectively blending alpha
382
- final_rgb_canvas = Image.new("RGB", self.video_frame_size, (random.randint(0,5), random.randint(0,5), random.randint(0,5))) # Dark background
383
- final_rgb_canvas.paste(canvas_rgba, mask=canvas_rgba.split()[3]) # Use alpha channel of canvas_rgba as mask
384
-
385
- debug_canvas_path = os.path.join(self.output_dir, f"debug_final_rgb_canvas_scene_{scene_num}.png")
386
- try: final_rgb_canvas.save(debug_canvas_path); logger.info(f"DEBUG: Saved final RGB canvas for scene {scene_num} to {debug_canvas_path}")
387
- except Exception as e_save_canvas: logger.error(f"DEBUG: Failed to save final RGB canvas for scene {scene_num}: {e_save_canvas}")
388
 
389
- frame_np = np.array(final_rgb_canvas)
390
- logger.debug(f"S{scene_num}: Final RGB canvas to NumPy. Shape: {frame_np.shape}, Dtype: {frame_np.dtype}")
391
- if frame_np.size == 0: logger.error(f"S{scene_num}: NumPy array for ImageClip is empty! Skipping."); continue
392
 
393
- current_clip_base = ImageClip(frame_np, transparent=False, ismask=False).set_duration(target_scene_duration)
394
- logger.debug(f"S{scene_num}: Base ImageClip created.")
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
395
 
396
- current_clip_for_scene = current_clip_base
 
 
 
397
  try: # Ken Burns
398
  end_scale = random.uniform(1.03, 1.08)
399
- current_clip_for_scene = current_clip_base.fx(vfx.resize, lambda t: 1 + (end_scale - 1) * (t / target_scene_duration)).set_position('center')
400
  logger.debug(f"S{scene_num}: Ken Burns effect applied.")
401
- except Exception as e_fx: logger.error(f"S{scene_num}: Ken Burns error: {e_fx}. Using static.", exc_info=False); current_clip_for_scene = current_clip_base
 
 
402
 
403
  elif asset_type == 'video':
404
  logger.debug(f"S{scene_num}: Loading video asset from {asset_path}")
405
- # Ensure target_resolution is (height, width) for VideoFileClip resizing parameter
406
- source_video_clip = VideoFileClip(asset_path, target_resolution=(self.video_frame_size[1], self.video_frame_size[0]) if self.video_frame_size else None)
407
-
408
- temp_clip = source_video_clip # Work with a temporary variable
409
- if source_video_clip.duration > target_scene_duration:
410
- temp_clip = source_video_clip.subclip(0, target_scene_duration)
411
- elif source_video_clip.duration < target_scene_duration:
412
- if target_scene_duration / source_video_clip.duration > 1.5 and source_video_clip.duration > 0.1:
413
- temp_clip = source_video_clip.loop(duration=target_scene_duration)
414
- else: # Play once, MoviePy will pad if needed during concatenation if durations differ
415
- temp_clip = source_video_clip.set_duration(source_video_clip.duration) # Keep its own duration
416
- logger.info(f"Video clip for S{scene_num} ({source_video_clip.duration:.2f}s) is shorter than target animatic duration ({target_scene_duration:.2f}s). It will play once at its native length.")
417
-
418
- # Crucially, ensure the clip used in concatenation has the target_scene_duration
419
- current_clip_for_scene = temp_clip.set_duration(target_scene_duration)
 
 
 
 
 
 
 
 
 
 
 
 
 
 
420
 
421
- if current_clip_for_scene.size != list(self.video_frame_size):
422
- logger.debug(f"S{scene_num}: Resizing video clip from {current_clip_for_scene.size} to {self.video_frame_size}")
423
- current_clip_for_scene = current_clip_for_scene.resize(self.video_frame_size)
424
-
425
- # Only close source_video_clip if it's different from what we are keeping (e.g., after subclip)
426
- # And if it's not the same object as current_clip_for_scene
427
- if source_video_clip is not current_clip_for_scene and hasattr(source_video_clip, 'close'):
428
- source_video_clip.close()
429
- logger.debug(f"S{scene_num}: Video asset processed. Final duration for scene: {current_clip_for_scene.duration:.2f}s")
430
 
431
  else: logger.warning(f"S{scene_num}: Unknown asset type '{asset_type}'. Skipping."); continue
432
-
433
- if current_clip_for_scene and key_action: # Add text overlay
 
434
  logger.debug(f"S{scene_num}: Adding text overlay: '{key_action}'")
435
  text_overlay_duration = min(target_scene_duration - 0.5, target_scene_duration * 0.8) if target_scene_duration > 0.5 else target_scene_duration
436
  text_overlay_start = (target_scene_duration - text_overlay_duration) / 2.0
437
  if text_overlay_duration > 0:
438
- txt_clip = TextClip(f"Scene {scene_num}\n{key_action}",
439
- fontsize=self.video_overlay_font_size, color=self.video_overlay_font_color,
440
- font=self.video_overlay_font, bg_color='rgba(10,10,20,0.7)',
441
- method='caption', align='West', size=(self.video_frame_size[0] * 0.9, None),
442
- kerning=-1, stroke_color='black', stroke_width=1.5
443
- ).set_duration(text_overlay_duration).set_start(text_overlay_start).set_position(('center', 0.92), relative=True)
444
- current_clip_for_scene = CompositeVideoClip([current_clip_for_scene, txt_clip], size=self.video_frame_size, use_bgclip=True)
445
- logger.debug(f"S{scene_num}: Text overlay composited.")
 
 
446
 
447
- if current_clip_for_scene: processed_moviepy_clips.append(current_clip_for_scene); logger.info(f"S{scene_num}: Asset successfully processed and added to final list.")
448
- except Exception as e: logger.error(f"Error processing asset for Scene {scene_num} ({asset_path}): {e}", exc_info=True)
449
- finally: # Ensure individual clips are closed if they were opened and an error occurred mid-processing
450
- if current_clip_for_scene and asset_type == 'video' and hasattr(current_clip_for_scene, 'reader') and current_clip_for_scene.reader:
451
- if hasattr(current_clip_for_scene, 'close'): current_clip_for_scene.close()
452
-
453
-
454
- if not processed_moviepy_clips: logger.warning("No MoviePy clips processed. Aborting animatic assembly."); return None
 
 
 
 
 
455
 
456
  transition_duration = 0.75
457
  try:
458
- if len(processed_moviepy_clips) > 1: final_composite_clip = concatenate_videoclips(processed_moviepy_clips, padding=-transition_duration, method="compose")
459
- elif processed_moviepy_clips: final_composite_clip = processed_moviepy_clips[0]
460
- else: logger.error("No clips for final concatenation."); return None
 
 
 
 
 
461
 
462
- if final_composite_clip.duration > transition_duration * 2: final_composite_clip = final_composite_clip.fx(vfx.fadein, transition_duration).fx(vfx.fadeout, transition_duration)
463
- elif final_composite_clip.duration > 0: final_composite_clip = final_composite_clip.fx(vfx.fadein, min(transition_duration, final_composite_clip.duration/2.0))
 
 
 
 
464
 
465
- if overall_narration_path and os.path.exists(overall_narration_path) and final_composite_clip.duration > 0:
466
  try:
467
  narration_audio_clip = AudioFileClip(overall_narration_path)
468
- if narration_audio_clip.duration < final_composite_clip.duration:
469
- logger.info(f"Narration ({narration_audio_clip.duration:.2f}s) shorter than visuals ({final_composite_clip.duration:.2f}s). Trimming video.")
470
- final_composite_clip = final_composite_clip.subclip(0, narration_audio_clip.duration)
471
- final_composite_clip = final_composite_clip.set_audio(narration_audio_clip); logger.info("Overall narration added.")
472
- except Exception as e: logger.error(f"Adding narration error: {e}", exc_info=True)
473
- elif final_composite_clip.duration <= 0 : logger.warning("Video has no duration. Audio not added.")
474
 
475
- if final_composite_clip and final_composite_clip.duration > 0:
476
  output_path = os.path.join(self.output_dir, output_filename)
477
- logger.info(f"Writing final animatic: {output_path} (Duration: {final_composite_clip.duration:.2f}s)")
478
- final_composite_clip.write_videofile(output_path, fps=fps, codec='libx264', preset='medium', audio_codec='aac',
479
- temp_audiofile=os.path.join(self.output_dir, f'temp-audio-{os.urandom(4).hex()}.m4a'),
480
- remove_temp=True, threads=os.cpu_count() or 2, logger='bar', bitrate="5000k")
481
- logger.info(f"Animatic created: {output_path}"); return output_path
482
- else: logger.error("Final animatic clip invalid. Not writing file."); return None
483
- except Exception as e: logger.error(f"Animatic writing error: {e}", exc_info=True); return None
 
 
 
 
 
484
  finally:
485
- for clip_obj in processed_moviepy_clips:
486
- if hasattr(clip_obj, 'close'): clip_obj.close()
487
- if narration_audio_clip and hasattr(narration_audio_clip, 'close'): narration_audio_clip.close()
488
- if final_composite_clip and hasattr(final_composite_clip, 'close'): final_composite_clip.close()
 
 
 
61
  self.output_dir = output_dir
62
  os.makedirs(self.output_dir, exist_ok=True)
63
 
64
+ self.font_filename = "arial.ttf" # Or a more reliably found font like "DejaVuSans-Bold.ttf"
65
  font_paths_to_try = [
66
  self.font_filename,
67
+ f"/usr/share/fonts/truetype/dejavu/DejaVuSans-Bold.ttf",
68
+ f"/usr/share/fonts/truetype/liberation/LiberationSans-Bold.ttf",
69
  f"/System/Library/Fonts/Supplemental/Arial.ttf", # macOS
70
  f"C:/Windows/Fonts/arial.ttf", # Windows
71
+ f"/usr/local/share/fonts/truetype/mycustomfonts/{self.font_filename}"
72
  ]
73
  self.font_path_pil = next((p for p in font_paths_to_try if os.path.exists(p)), None)
74
  self.font_size_pil = 20
75
  self.video_overlay_font_size = 30
76
  self.video_overlay_font_color = 'white'
77
+ # For MoviePy TextClip, use font names ImageMagick knows. Check with `convert -list font`.
78
+ # 'Liberation-Sans-Bold' is a good default if available.
79
+ self.video_overlay_font = 'DejaVuSans-Bold' if 'dejavu' in (self.font_path_pil or '').lower() else 'Liberation-Sans-Bold'
80
+
81
 
82
  try:
83
  if self.font_path_pil:
84
  self.font = ImageFont.truetype(self.font_path_pil, self.font_size_pil)
85
  logger.info(f"Pillow font loaded: {self.font_path_pil}.")
86
+ else:
87
  self.font = ImageFont.load_default()
88
+ logger.warning("Custom Pillow font not found. Using default. Text rendering for placeholders might be basic.")
89
+ self.font_size_pil = 10 # Default Pillow font is small
90
+ except IOError as e_font:
91
+ logger.error(f"Pillow font loading IOError for '{self.font_path_pil or 'default'}': {e_font}. Using default.")
92
  self.font = ImageFont.load_default()
93
  self.font_size_pil = 10
94
 
95
  self.openai_api_key = None; self.USE_AI_IMAGE_GENERATION = False
96
  self.dalle_model = "dall-e-3"; self.image_size_dalle3 = "1792x1024"
97
+ self.video_frame_size = (1280, 720)
98
 
99
  self.elevenlabs_api_key = None; self.USE_ELEVENLABS = False
100
  self.elevenlabs_client = None
 
111
 
112
  def set_openai_api_key(self,k):
113
  self.openai_api_key=k; self.USE_AI_IMAGE_GENERATION=bool(k)
114
+ logger.info(f"DALL-E ({self.dalle_model}) {'Ready.' if k else 'Disabled.'}")
115
 
116
  def set_elevenlabs_api_key(self,api_key, voice_id_from_secret=None):
117
  self.elevenlabs_api_key=api_key
 
122
  self.USE_ELEVENLABS=bool(self.elevenlabs_client)
123
  logger.info(f"ElevenLabs Client {'Ready' if self.USE_ELEVENLABS else 'Failed Init'} (Voice ID: {self.elevenlabs_voice_id}).")
124
  except Exception as e: logger.error(f"ElevenLabs client init error: {e}. Disabled.", exc_info=True); self.USE_ELEVENLABS=False
125
+ else: self.USE_ELEVENLABS=False; logger.info("ElevenLabs Disabled (no key or SDK).")
126
 
127
  def set_pexels_api_key(self,k):
128
  self.pexels_api_key=k; self.USE_PEXELS=bool(k)
129
+ logger.info(f"Pexels Search {'Ready.' if k else 'Disabled.'}")
130
 
131
  def set_runway_api_key(self, k):
132
  self.runway_api_key = k
133
  if k and RUNWAYML_SDK_IMPORTED and RunwayMLClient:
134
  try:
135
  # self.runway_client = RunwayMLClient(api_key=k) # Actual initialization
136
+ self.USE_RUNWAYML = True
137
  logger.info(f"RunwayML Client (Placeholder with SDK) {'Ready.' if self.USE_RUNWAYML else 'Failed Init.'}")
138
  except Exception as e: logger.error(f"RunwayML client (Placeholder with SDK) init error: {e}. Disabled.", exc_info=True); self.USE_RUNWAYML = False
139
+ elif k:
140
  self.USE_RUNWAYML = True
141
  logger.info("RunwayML API Key set. Using direct API calls or placeholder (SDK not fully integrated/imported).")
142
  else: self.USE_RUNWAYML = False; logger.info("RunwayML Disabled (no API key).")
143
 
144
  def _get_text_dimensions(self,text_content,font_obj):
145
+ if not text_content: return 0, (self.font.size if hasattr(self.font, 'size') else self.font_size_pil)
146
  try:
147
  if hasattr(font_obj,'getbbox'):
148
  bbox=font_obj.getbbox(text_content);w=bbox[2]-bbox[0];h=bbox[3]-bbox[1]
149
+ return w, h if h > 0 else font_obj.size
150
  elif hasattr(font_obj,'getsize'):
151
  w,h=font_obj.getsize(text_content)
152
+ return w, h if h > 0 else font_obj.size
153
+ else: return int(len(text_content)*font_obj.size*0.6), int(font_obj.size*1.2)
154
  except Exception as e: logger.warning(f"Error in _get_text_dimensions for '{text_content[:20]}...': {e}"); return int(len(text_content)*self.font_size_pil*0.6),int(self.font_size_pil*1.2)
155
 
156
  def _create_placeholder_image_content(self,text_description,filename,size=None):
 
157
  if size is None: size = self.video_frame_size
158
  img=Image.new('RGB',size,color=(20,20,40));d=ImageDraw.Draw(img);padding=25;max_w=size[0]-(2*padding);lines=[];
159
  if not text_description: text_description="(Placeholder: No prompt text)"
 
165
  if current_line: lines.append(current_line.strip());
166
  current_line=word+" "
167
  if current_line.strip(): lines.append(current_line.strip())
168
+ if not lines and text_description: lines.append(text_description[:int(max_w//(self._get_text_dimensions("A",self.font)[0] or 10))]+"..." if text_description else "(Text too long)")
169
  elif not lines: lines.append("(Placeholder Text Error)")
170
  _,single_line_h=self._get_text_dimensions("Ay",self.font); single_line_h = single_line_h if single_line_h > 0 else self.font_size_pil + 2
171
  max_lines_to_display=min(len(lines),(size[1]-(2*padding))//(single_line_h+2)) if single_line_h > 0 else 1
 
181
  except Exception as e:logger.error(f"Saving placeholder image {filepath}: {e}", exc_info=True);return None
182
 
183
  def _search_pexels_image(self, query, output_filename_base):
 
184
  if not self.USE_PEXELS or not self.pexels_api_key: return None
185
+ headers = {"Authorization": self.pexels_api_key}; params = {"query": query, "per_page": 1, "orientation": "landscape", "size": "large2x"} # Request higher quality
186
  pexels_filename = output_filename_base.replace(".png", f"_pexels_{random.randint(1000,9999)}.jpg").replace(".mp4", f"_pexels_{random.randint(1000,9999)}.jpg")
187
  filepath = os.path.join(self.output_dir, pexels_filename)
188
  try:
 
203
  if not self.USE_RUNWAYML or not self.runway_api_key:
204
  logger.warning("RunwayML not enabled or API key missing. Cannot generate video clip.")
205
  return None
206
+ output_video_filename = scene_identifier_filename_base.replace(".png", "_runway.mp4") # More specific extension
207
  output_video_filepath = os.path.join(self.output_dir, output_video_filename)
208
  logger.info(f"Attempting RunwayML video generation for: {prompt_text[:100]}... (Target duration: {target_duration_seconds}s)")
209
  # --- START ACTUAL RUNWAYML API INTERACTION (HYPOTHETICAL - NEEDS IMPLEMENTATION) ---
210
+ # Example:
211
+ # if self.runway_client:
212
+ # try:
213
+ # # result = self.runway_client.generate(text=prompt_text, duration=target_duration_seconds, seed_image=input_image_path)
214
+ # # result.save(output_video_filepath)
215
+ # # return output_video_filepath
216
+ # except Exception as e_runway:
217
+ # logger.error(f"Actual RunwayML generation error: {e_runway}", exc_info=True)
218
+ # return None
219
+ # else: logger.warning("RunwayML client not initialized (placeholder).")
220
  # --- END ACTUAL RUNWAYML API INTERACTION (HYPOTHETICAL) ---
221
  logger.warning("Using PLACEHOLDER video generation for RunwayML as actual API calls are not implemented.")
222
  return self._create_placeholder_video_content(f"[RunwayML Placeholder] {prompt_text}", output_video_filename, duration=target_duration_seconds)
 
224
  def _create_placeholder_video_content(self, text_description, filename, duration=4, size=None):
225
  if size is None: size = self.video_frame_size
226
  filepath = os.path.join(self.output_dir, filename)
227
+ txt_clip = None # Initialize
 
228
  try:
229
+ txt_clip = TextClip(text_description, fontsize=50, color='white', font=self.video_overlay_font,
230
+ bg_color='black', size=size, method='caption').set_duration(duration)
231
+ txt_clip.write_videofile(filepath, fps=24, codec='libx264', preset='ultrafast', logger=None, threads=2)
232
  logger.info(f"Placeholder video saved: {filepath}")
233
  return filepath
234
  except Exception as e: logger.error(f"Failed to create placeholder video {filepath}: {e}", exc_info=True); return None
235
  finally:
236
+ if txt_clip and hasattr(txt_clip, 'close'): txt_clip.close()
237
 
238
  def generate_scene_asset(self, image_prompt_text, scene_data, scene_identifier_filename_base,
239
  generate_as_video_clip=False, runway_target_duration=4, input_image_for_runway=None):
 
249
  )
250
  if video_path and os.path.exists(video_path):
251
  asset_info = {'path': video_path, 'type': 'video', 'error': False, 'prompt_used': image_prompt_text}
252
+ return asset_info
253
+ else: logger.warning(f"RunwayML video clip generation failed for {base_name}. Falling back to image."); asset_info['error_message'] = "RunwayML video generation failed."
 
 
 
254
 
255
+ image_filename_with_ext = base_name + ".png"
 
256
  filepath = os.path.join(self.output_dir, image_filename_with_ext)
257
+ asset_info['type'] = 'image'
258
 
259
  if self.USE_AI_IMAGE_GENERATION and self.openai_api_key:
260
+ max_retries = 2; attempt_num = 0
261
+ for attempt_num in range(max_retries):
262
  try:
263
+ logger.info(f"Attempt {attempt_num+1}: DALL-E ({self.dalle_model}) for: {image_prompt_text[:100]}...")
264
  client = openai.OpenAI(api_key=self.openai_api_key, timeout=90.0)
265
  response = client.images.generate(model=self.dalle_model, prompt=image_prompt_text, n=1, size=self.image_size_dalle3, quality="hd", response_format="url", style="vivid")
266
  image_url = response.data[0].url; revised_prompt = getattr(response.data[0], 'revised_prompt', None)
 
270
  if img_data.mode != 'RGB': img_data = img_data.convert('RGB')
271
  img_data.save(filepath); logger.info(f"AI Image (DALL-E) saved: {filepath}");
272
  asset_info = {'path': filepath, 'type': 'image', 'error': False, 'prompt_used': image_prompt_text, 'revised_prompt': revised_prompt}
273
+ return asset_info # Success
274
+ except openai.RateLimitError as e_rate: logger.warning(f"OpenAI Rate Limit on attempt {attempt_num+1}: {e_rate}. Retrying..."); time.sleep(5 * (attempt_num + 1)); asset_info['error_message'] = str(e_rate)
275
  except openai.APIError as e_api: logger.error(f"OpenAI API Error: {e_api}"); asset_info['error_message'] = str(e_api); break
276
  except requests.exceptions.RequestException as e_req: logger.error(f"Requests Error (DALL-E download): {e_req}"); asset_info['error_message'] = str(e_req); break
277
  except Exception as e_gen: logger.error(f"Generic error (DALL-E gen): {e_gen}", exc_info=True); asset_info['error_message'] = str(e_gen); break
278
+ if asset_info['error']: logger.warning(f"DALL-E generation failed after {attempt_num+1} attempts. Trying Pexels fallback...")
 
279
 
280
+ if self.USE_PEXELS and (asset_info['error'] or not (self.USE_AI_IMAGE_GENERATION and self.openai_api_key)):
281
  pexels_query_text = scene_data.get('pexels_search_query_감독', f"{scene_data.get('emotional_beat','')} {scene_data.get('setting_description','')}")
282
  pexels_path = self._search_pexels_image(pexels_query_text, image_filename_with_ext)
283
  if pexels_path:
284
  asset_info = {'path': pexels_path, 'type': 'image', 'error': False, 'prompt_used': f"Pexels: {pexels_query_text}"}
285
  return asset_info
286
+ current_error_msg = asset_info.get('error_message', "")
287
+ asset_info['error_message'] = (current_error_msg + " Pexels search also failed or disabled.").strip()
288
+ if not asset_info['error']: logger.warning("Pexels search failed or was disabled (DALL-E not attempted).")
289
 
290
+ if asset_info['error']:
291
+ logger.warning("All primary generation methods failed. Using placeholder image.")
292
+ placeholder_prompt_text = asset_info.get('prompt_used', image_prompt_text)
 
293
  placeholder_path = self._create_placeholder_image_content(f"[Fallback Placeholder] {placeholder_prompt_text[:100]}...", image_filename_with_ext)
294
  if placeholder_path:
295
  asset_info = {'path': placeholder_path, 'type': 'image', 'error': False, 'prompt_used': placeholder_prompt_text}
296
+ else:
297
+ current_error_msg = asset_info.get('error_message', "")
298
+ asset_info['error_message'] = (current_error_msg + " Placeholder creation also failed.").strip()
299
+ return asset_info
300
 
301
  def generate_narration_audio(self, text_to_narrate, output_filename="narration_overall.mp3"):
 
302
  if not self.USE_ELEVENLABS or not self.elevenlabs_client or not text_to_narrate:
303
+ logger.info("ElevenLabs conditions not met. Skipping audio generation.")
304
  return None
305
  audio_filepath = os.path.join(self.output_dir, output_filename)
306
  try:
 
317
  logger.info(f"ElevenLabs audio (non-streamed) saved: {audio_filepath}"); return audio_filepath
318
  else: logger.error("No recognized audio generation method found on ElevenLabs client."); return None
319
 
320
+ if audio_stream_method: # Streaming logic
321
  voice_param_for_stream = {"voice_id": str(self.elevenlabs_voice_id)}
322
+ if self.elevenlabs_voice_settings:
323
+ if hasattr(self.elevenlabs_voice_settings, 'model_dump'): voice_param_for_stream["voice_settings"] = self.elevenlabs_voice_settings.model_dump() # Pydantic v2
324
+ elif hasattr(self.elevenlabs_voice_settings, 'dict'): voice_param_for_stream["voice_settings"] = self.elevenlabs_voice_settings.dict() # Pydantic v1
325
+ else: voice_param_for_stream["voice_settings"] = self.elevenlabs_voice_settings
 
326
 
327
  audio_data_iterator = audio_stream_method(text=text_to_narrate, model_id="eleven_multilingual_v2", **voice_param_for_stream)
328
  with open(audio_filepath, "wb") as f:
 
340
 
341
  processed_moviepy_clips = []
342
  narration_audio_clip = None
343
+ final_composite_clip_obj = None
344
+
345
+ logger.info(f"Assembling animatic from {len(asset_data_list)} assets. Target frame: {self.video_frame_size}.")
346
 
347
  for i, asset_info in enumerate(asset_data_list):
348
  asset_path = asset_info.get('path')
349
  asset_type = asset_info.get('type')
350
+ target_scene_duration = asset_info.get('duration', 4.5) # Duration for this scene in the animatic
351
  scene_num = asset_info.get('scene_num', i + 1)
352
  key_action = asset_info.get('key_action', '')
353
 
354
+ logger.info(f"Processing S{scene_num}: Path='{asset_path}', Type='{asset_type}', TargetDur='{target_scene_duration}'s")
355
 
356
  if not (asset_path and os.path.exists(asset_path)):
357
+ logger.warning(f"S{scene_num}: Asset not found at '{asset_path}'. Skipping."); continue
 
358
  if target_scene_duration <= 0:
359
+ logger.warning(f"S{scene_num}: Invalid duration ({target_scene_duration}s). Skipping."); continue
 
360
 
361
+ current_scene_clip = None # The final MoviePy clip for this scene
362
  try:
363
  if asset_type == 'image':
 
364
  pil_img = Image.open(asset_path)
365
+ logger.debug(f"S{scene_num}: Loaded image. Mode: {pil_img.mode}, Size: {pil_img.size}")
366
 
367
+ # 1. Ensure image is RGBA for consistent alpha handling during processing
368
+ img_rgba_source = pil_img.convert('RGBA') if pil_img.mode != 'RGBA' else pil_img.copy()
 
369
 
370
+ # 2. Thumbnail the RGBA image
371
+ img_thumbnail = img_rgba_source.copy() # Work on a copy
372
  resample_filter = Image.Resampling.LANCZOS if hasattr(Image.Resampling, 'LANCZOS') else (Image.ANTIALIAS if hasattr(Image, 'ANTIALIAS') else Image.BILINEAR)
373
+ img_thumbnail.thumbnail(self.video_frame_size, resample_filter)
374
+ logger.debug(f"S{scene_num}: Thumbnailed to: {img_thumbnail.size}")
 
 
 
 
 
 
 
 
 
 
 
 
 
 
375
 
376
+ # 3. Create a target-sized RGBA canvas (fully transparent)
377
+ canvas_rgba = Image.new('RGBA', self.video_frame_size, (0, 0, 0, 0))
 
378
 
379
+ # 4. Paste the thumbnailed image (with its alpha) onto the center of the RGBA canvas
380
+ xo = (self.video_frame_size[0] - img_thumbnail.width) // 2
381
+ yo = (self.video_frame_size[1] - img_thumbnail.height) // 2
382
+ canvas_rgba.paste(img_thumbnail, (xo, yo), img_thumbnail) # Use img_thumbnail's alpha as mask
383
+ logger.debug(f"S{scene_num}: Image pasted onto transparent RGBA canvas.")
384
+
385
+ # 5. Create a final RGB image by pasting the RGBA canvas onto an opaque background
386
+ # This flattens transparency and ensures an RGB image for MoviePy.
387
+ final_rgb_image_for_moviepy = Image.new("RGB", self.video_frame_size, (0, 0, 0)) # Opaque black background
388
+ final_rgb_image_for_moviepy.paste(canvas_rgba, mask=canvas_rgba.split()[3]) # Paste using alpha from canvas_rgba
389
+
390
+ # --- CRITICAL DEBUG STEP: Save the image that will be fed to MoviePy ---
391
+ debug_canvas_path = os.path.join(self.output_dir, f"debug_final_rgb_FOR_MOVIEPY_scene_{scene_num}.png")
392
+ try:
393
+ final_rgb_image_for_moviepy.save(debug_canvas_path)
394
+ logger.info(f"DEBUG: Saved final RGB image for MoviePy (S{scene_num}) to {debug_canvas_path}")
395
+ except Exception as e_save_canvas:
396
+ logger.error(f"DEBUG: Failed to save final_rgb_image_for_moviepy (S{scene_num}): {e_save_canvas}")
397
+
398
+ frame_np = np.array(final_rgb_image_for_moviepy) # Should be (H, W, 3) dtype uint8
399
+ logger.debug(f"S{scene_num}: Converted to NumPy. Shape: {frame_np.shape}, Dtype: {frame_np.dtype}, Size: {frame_np.size}")
400
+
401
+ if frame_np.size == 0: logger.error(f"S{scene_num}: NumPy array is EMPTY. Skipping."); continue
402
+ if frame_np.ndim != 3 or frame_np.shape[2] != 3: logger.error(f"S{scene_num}: NumPy array has unexpected shape {frame_np.shape}. Skipping."); continue
403
+ if frame_np.dtype != np.uint8: frame_np = frame_np.astype(np.uint8); logger.warning(f"S{scene_num}: Converted NumPy array dtype to uint8.")
404
 
405
+ current_clip_base = ImageClip(frame_np, transparent=False).set_duration(target_scene_duration)
406
+ logger.debug(f"S{scene_num}: Base ImageClip created from NumPy array.")
407
+
408
+ current_scene_clip_with_fx = current_clip_base # Start with base
409
  try: # Ken Burns
410
  end_scale = random.uniform(1.03, 1.08)
411
+ 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')
412
  logger.debug(f"S{scene_num}: Ken Burns effect applied.")
413
+ except Exception as e_fx: logger.error(f"S{scene_num}: Ken Burns error: {e_fx}. Using static.", exc_info=False)
414
+
415
+ current_scene_clip = current_scene_clip_with_fx
416
 
417
  elif asset_type == 'video':
418
  logger.debug(f"S{scene_num}: Loading video asset from {asset_path}")
419
+ source_video_clip = None # Initialize
420
+ try:
421
+ source_video_clip = VideoFileClip(asset_path, target_resolution=(self.video_frame_size[1], self.video_frame_size[0]) if self.video_frame_size else None)
422
+
423
+ temp_clip_for_video_asset = source_video_clip
424
+ if source_video_clip.duration != target_scene_duration:
425
+ if source_video_clip.duration > target_scene_duration:
426
+ temp_clip_for_video_asset = source_video_clip.subclip(0, target_scene_duration)
427
+ else: # Source is shorter
428
+ if target_scene_duration / source_video_clip.duration > 1.5 and source_video_clip.duration > 0.1:
429
+ temp_clip_for_video_asset = source_video_clip.loop(duration=target_scene_duration)
430
+ else: # Let it play its native length, will be set to target_scene_duration for concat
431
+ temp_clip_for_video_asset = source_video_clip.set_duration(source_video_clip.duration)
432
+ logger.info(f"S{scene_num}: Video clip ({source_video_clip.duration:.2f}s) shorter than scene target ({target_scene_duration:.2f}s).")
433
+
434
+ current_scene_clip = temp_clip_for_video_asset.set_duration(target_scene_duration)
435
+
436
+ if current_scene_clip.size != list(self.video_frame_size):
437
+ logger.debug(f"S{scene_num}: Resizing video clip from {current_scene_clip.size} to {self.video_frame_size}")
438
+ current_scene_clip = current_scene_clip.resize(self.video_frame_size)
439
+
440
+ logger.debug(f"S{scene_num}: Video asset processed. Final duration for scene: {current_scene_clip.duration:.2f}s")
441
+ except Exception as e_vid_load:
442
+ logger.error(f"S{scene_num}: Error loading/processing video file '{asset_path}': {e_vid_load}", exc_info=True)
443
+ if source_video_clip and hasattr(source_video_clip, 'close'): source_video_clip.close()
444
+ continue # Skip this asset
445
+ finally: # Close original source if it was opened and different from the final clip
446
+ if source_video_clip and source_video_clip is not current_scene_clip and hasattr(source_video_clip, 'close'):
447
+ source_video_clip.close()
448
 
 
 
 
 
 
 
 
 
 
449
 
450
  else: logger.warning(f"S{scene_num}: Unknown asset type '{asset_type}'. Skipping."); continue
451
+
452
+ # Add text overlay (common to both image and video assets)
453
+ if current_scene_clip and key_action:
454
  logger.debug(f"S{scene_num}: Adding text overlay: '{key_action}'")
455
  text_overlay_duration = min(target_scene_duration - 0.5, target_scene_duration * 0.8) if target_scene_duration > 0.5 else target_scene_duration
456
  text_overlay_start = (target_scene_duration - text_overlay_duration) / 2.0
457
  if text_overlay_duration > 0:
458
+ try:
459
+ txt_clip = TextClip(f"Scene {scene_num}\n{key_action}",
460
+ fontsize=self.video_overlay_font_size, color=self.video_overlay_font_color,
461
+ font=self.video_overlay_font, bg_color='rgba(10,10,20,0.7)',
462
+ method='caption', align='West', size=(self.video_frame_size[0] * 0.9, None),
463
+ kerning=-1, stroke_color='black', stroke_width=1.5
464
+ ).set_duration(text_overlay_duration).set_start(text_overlay_start).set_position(('center', 0.92), relative=True)
465
+ current_scene_clip = CompositeVideoClip([current_scene_clip, txt_clip], size=self.video_frame_size, use_bgclip=True)
466
+ logger.debug(f"S{scene_num}: Text overlay composited.")
467
+ except Exception as e_txt: logger.error(f"S{scene_num}: Error creating TextClip or CompositeVideoClip for text: {e_txt}. Using clip without text.", exc_info=True)
468
 
469
+ if current_scene_clip:
470
+ processed_moviepy_clips.append(current_scene_clip)
471
+ logger.info(f"S{scene_num}: Asset successfully processed. Clip duration: {current_scene_clip.duration:.2f}s, Added to final list.")
472
+
473
+ except Exception as e_asset_proc:
474
+ logger.error(f"MAJOR Error processing asset for Scene {scene_num} ({asset_path}): {e_asset_proc}", exc_info=True)
475
+ # Ensure clip is closed if it was partially created
476
+ if current_scene_clip and hasattr(current_scene_clip, 'reader') and current_scene_clip.reader:
477
+ if hasattr(current_scene_clip, 'close'): current_scene_clip.close()
478
+ elif current_scene_clip and hasattr(current_scene_clip, 'close'):
479
+ current_scene_clip.close()
480
+
481
+ if not processed_moviepy_clips: logger.warning("No MoviePy clips were successfully processed. Aborting animatic assembly."); return None
482
 
483
  transition_duration = 0.75
484
  try:
485
+ if not processed_moviepy_clips: logger.error("No clips to concatenate after processing loop."); return None
486
+ logger.info(f"Concatenating {len(processed_moviepy_clips)} processed clips.")
487
+ if len(processed_moviepy_clips) > 1:
488
+ final_composite_clip_obj = concatenate_videoclips(processed_moviepy_clips, padding = -transition_duration if transition_duration > 0 else 0, method="compose")
489
+ elif processed_moviepy_clips: final_composite_clip_obj = processed_moviepy_clips[0]
490
+
491
+ if not final_composite_clip_obj: logger.error("Concatenation resulted in a None clip."); return None
492
+ logger.info(f"Concatenated clip duration: {final_composite_clip_obj.duration:.2f}s")
493
 
494
+ if transition_duration > 0:
495
+ if final_composite_clip_obj.duration > transition_duration * 2:
496
+ final_composite_clip_obj = final_composite_clip_obj.fx(vfx.fadein, transition_duration).fx(vfx.fadeout, transition_duration)
497
+ elif final_composite_clip_obj.duration > 0:
498
+ final_composite_clip_obj = final_composite_clip_obj.fx(vfx.fadein, min(transition_duration, final_composite_clip_obj.duration/2.0))
499
+ logger.debug("Applied fade in/out effects.")
500
 
501
+ if overall_narration_path and os.path.exists(overall_narration_path) and final_composite_clip_obj.duration > 0:
502
  try:
503
  narration_audio_clip = AudioFileClip(overall_narration_path)
504
+ logger.info(f"Adding narration. Video dur: {final_composite_clip_obj.duration:.2f}s, Audio dur: {narration_audio_clip.duration:.2f}s")
505
+ final_composite_clip_obj = final_composite_clip_obj.set_audio(narration_audio_clip) # Audio will be cut/padded to video duration
506
+ logger.info("Overall narration added to video.")
507
+ except Exception as e_audio: logger.error(f"Error adding overall narration: {e_audio}", exc_info=True)
508
+ elif final_composite_clip_obj.duration <= 0 : logger.warning("Video has no duration. Audio not added.")
 
509
 
510
+ if final_composite_clip_obj and final_composite_clip_obj.duration > 0:
511
  output_path = os.path.join(self.output_dir, output_filename)
512
+ logger.info(f"Attempting to write final animatic: {output_path} (Duration: {final_composite_clip_obj.duration:.2f}s)")
513
+ moviepy_logger_setting = 'bar' # Default to progress bar
514
+
515
+ final_composite_clip_obj.write_videofile(
516
+ output_path, fps=fps, codec='libx264', preset='medium', audio_codec='aac',
517
+ temp_audiofile=os.path.join(self.output_dir, f'temp-audio-{os.urandom(4).hex()}.m4a'),
518
+ remove_temp=True, threads=os.cpu_count() or 2, logger=moviepy_logger_setting, bitrate="5000k"
519
+ )
520
+ logger.info(f"Animatic video successfully created: {output_path}")
521
+ return output_path
522
+ else: logger.error("Final animatic clip is invalid or has zero duration. Cannot write file."); return None
523
+ except Exception as e_write: logger.error(f"Error during video file writing or final composition: {e_write}", exc_info=True); return None
524
  finally:
525
+ logger.debug("Closing all MoviePy clips in `assemble_animatic_from_assets` finally block.")
526
+ clips_to_close = processed_moviepy_clips + ([narration_audio_clip] if narration_audio_clip else []) + ([final_composite_clip_obj] if final_composite_clip_obj else [])
527
+ for clip_obj in clips_to_close:
528
+ if clip_obj and hasattr(clip_obj, 'close'):
529
+ try: clip_obj.close()
530
+ except Exception as e_close: logger.warning(f"Ignoring error while closing a clip: {e_close}")