CingenAI / core /visual_engine.py
mgbam's picture
Update core/visual_engine.py
3313da9 verified
raw
history blame
37.7 kB
# core/visual_engine.py
from PIL import Image, ImageDraw, ImageFont, ImageOps
# --- MONKEY PATCH FOR Image.ANTIALIAS ---
try:
if hasattr(Image, 'Resampling') and hasattr(Image.Resampling, 'LANCZOS'): # Pillow 9+
if not hasattr(Image, 'ANTIALIAS'): Image.ANTIALIAS = Image.Resampling.LANCZOS
elif hasattr(Image, 'LANCZOS'): # Pillow 8
if not hasattr(Image, 'ANTIALIAS'): Image.ANTIALIAS = Image.LANCZOS
elif not hasattr(Image, 'ANTIALIAS'):
print("WARNING: Pillow version lacks common Resampling attributes or ANTIALIAS. Video effects might fail.")
except Exception as e_mp: print(f"WARNING: ANTIALIAS monkey-patch error: {e_mp}")
# --- END MONKEY PATCH ---
from moviepy.editor import (ImageClip, VideoFileClip, concatenate_videoclips, TextClip,
CompositeVideoClip, AudioFileClip)
import moviepy.video.fx.all as vfx
import numpy as np
import os
import openai
import requests
import io
import time
import random
import logging
logger = logging.getLogger(__name__)
logger.setLevel(logging.INFO) # Set default logging level for this module
# --- ElevenLabs Client Import ---
ELEVENLABS_CLIENT_IMPORTED = False
ElevenLabsAPIClient = None
Voice = None
VoiceSettings = None
try:
from elevenlabs.client import ElevenLabs as ImportedElevenLabsClient
from elevenlabs import Voice as ImportedVoice, VoiceSettings as ImportedVoiceSettings
ElevenLabsAPIClient = ImportedElevenLabsClient
Voice = ImportedVoice
VoiceSettings = ImportedVoiceSettings
ELEVENLABS_CLIENT_IMPORTED = True
logger.info("ElevenLabs client components imported successfully.")
except Exception as e_eleven:
logger.warning(f"ElevenLabs client import failed: {e_eleven}. Audio generation will be disabled.")
# --- RunwayML Client Import (Placeholder) ---
RUNWAYML_SDK_IMPORTED = False
RunwayMLClient = None # Placeholder for the actual RunwayML client class
try:
# Example: from runwayml import RunwayClient as ImportedRunwayMLClient
# RunwayMLClient = ImportedRunwayMLClient
# RUNWAYML_SDK_IMPORTED = True
logger.info("RunwayML SDK import is a placeholder. Actual SDK needed for Runway features.")
except ImportError:
logger.warning("RunwayML SDK (placeholder) not found. RunwayML video generation will be disabled.")
except Exception as e_runway_sdk:
logger.warning(f"Error importing RunwayML SDK (placeholder): {e_runway_sdk}. RunwayML features disabled.")
class VisualEngine:
def __init__(self, output_dir="temp_cinegen_media", default_elevenlabs_voice_id="Rachel"):
self.output_dir = output_dir
os.makedirs(self.output_dir, exist_ok=True)
self.font_filename = "arial.ttf" # Or a more reliably found font like "DejaVuSans-Bold.ttf"
font_paths_to_try = [
self.font_filename,
f"/usr/share/fonts/truetype/dejavu/DejaVuSans-Bold.ttf",
f"/usr/share/fonts/truetype/liberation/LiberationSans-Bold.ttf",
f"/System/Library/Fonts/Supplemental/Arial.ttf", # macOS
f"C:/Windows/Fonts/arial.ttf", # Windows
f"/usr/local/share/fonts/truetype/mycustomfonts/{self.font_filename}"
]
self.font_path_pil = next((p for p in font_paths_to_try if os.path.exists(p)), None)
self.font_size_pil = 20
self.video_overlay_font_size = 30
self.video_overlay_font_color = 'white'
# For MoviePy TextClip, use font names ImageMagick knows. Check with `convert -list font`.
# 'Liberation-Sans-Bold' is a good default if available.
self.video_overlay_font = 'DejaVuSans-Bold' if 'dejavu' in (self.font_path_pil or '').lower() else 'Liberation-Sans-Bold'
try:
if self.font_path_pil:
self.font = ImageFont.truetype(self.font_path_pil, self.font_size_pil)
logger.info(f"Pillow font loaded: {self.font_path_pil}.")
else:
self.font = ImageFont.load_default()
logger.warning("Custom Pillow font not found. Using default. Text rendering for placeholders might be basic.")
self.font_size_pil = 10 # Default Pillow font is small
except IOError as e_font:
logger.error(f"Pillow font loading IOError for '{self.font_path_pil or 'default'}': {e_font}. Using default.")
self.font = ImageFont.load_default()
self.font_size_pil = 10
self.openai_api_key = None; self.USE_AI_IMAGE_GENERATION = False
self.dalle_model = "dall-e-3"; self.image_size_dalle3 = "1792x1024"
self.video_frame_size = (1280, 720)
self.elevenlabs_api_key = None; self.USE_ELEVENLABS = False
self.elevenlabs_client = None
self.elevenlabs_voice_id = default_elevenlabs_voice_id
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)
else: self.elevenlabs_voice_settings = None
self.pexels_api_key = None; self.USE_PEXELS = False
self.runway_api_key = None; self.USE_RUNWAYML = False
self.runway_client = None
logger.info("VisualEngine initialized.")
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.'}")
def set_elevenlabs_api_key(self,api_key, voice_id_from_secret=None):
self.elevenlabs_api_key=api_key
if voice_id_from_secret: self.elevenlabs_voice_id = voice_id_from_secret
if api_key and ELEVENLABS_CLIENT_IMPORTED and ElevenLabsAPIClient:
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}).")
except Exception as e: logger.error(f"ElevenLabs client init error: {e}. Disabled.", exc_info=True); self.USE_ELEVENLABS=False
else: self.USE_ELEVENLABS=False; logger.info("ElevenLabs Disabled (no key or SDK).")
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.'}")
def set_runway_api_key(self, k):
self.runway_api_key = k
if k and RUNWAYML_SDK_IMPORTED and RunwayMLClient:
try:
# self.runway_client = RunwayMLClient(api_key=k) # Actual initialization
self.USE_RUNWAYML = True
logger.info(f"RunwayML Client (Placeholder with SDK) {'Ready.' if self.USE_RUNWAYML else 'Failed Init.'}")
except Exception as e: logger.error(f"RunwayML client (Placeholder with SDK) init error: {e}. Disabled.", exc_info=True); self.USE_RUNWAYML = False
elif k:
self.USE_RUNWAYML = True
logger.info("RunwayML API Key set. Using direct API calls or placeholder (SDK not fully integrated/imported).")
else: self.USE_RUNWAYML = False; logger.info("RunwayML Disabled (no API key).")
def _get_text_dimensions(self,text_content,font_obj):
if not text_content: return 0, (self.font.size if hasattr(self.font, 'size') else self.font_size_pil)
try:
if hasattr(font_obj,'getbbox'):
bbox=font_obj.getbbox(text_content);w=bbox[2]-bbox[0];h=bbox[3]-bbox[1]
return w, h if h > 0 else font_obj.size
elif hasattr(font_obj,'getsize'):
w,h=font_obj.getsize(text_content)
return w, h if h > 0 else font_obj.size
else: return int(len(text_content)*font_obj.size*0.6), int(font_obj.size*1.2)
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)
def _create_placeholder_image_content(self,text_description,filename,size=None):
if size is None: size = self.video_frame_size
img=Image.new('RGB',size,color=(20,20,40));d=ImageDraw.Draw(img);padding=25;max_w=size[0]-(2*padding);lines=[];
if not text_description: text_description="(Placeholder: No prompt text)"
words=text_description.split();current_line=""
for word in words:
test_line=current_line+word+" ";
if self._get_text_dimensions(test_line,self.font)[0] <= max_w: current_line=test_line
else:
if current_line: lines.append(current_line.strip());
current_line=word+" "
if current_line.strip(): lines.append(current_line.strip())
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)")
elif not lines: lines.append("(Placeholder Text Error)")
_,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
max_lines_to_display=min(len(lines),(size[1]-(2*padding))//(single_line_h+2)) if single_line_h > 0 else 1
if max_lines_to_display <=0: max_lines_to_display = 1
y_text_start = padding + (size[1]-(2*padding) - max_lines_to_display*(single_line_h+2))/2.0
y_text = y_text_start
for i in range(max_lines_to_display):
line_content=lines[i];line_w,_=self._get_text_dimensions(line_content,self.font);x_text=(size[0]-line_w)/2.0
d.text((x_text,y_text),line_content,font=self.font,fill=(200,200,180));y_text+=single_line_h+2
if i==6 and max_lines_to_display > 7: d.text((x_text,y_text),"...",font=self.font,fill=(200,200,180));break
filepath=os.path.join(self.output_dir,filename);
try:img.save(filepath);return filepath
except Exception as e:logger.error(f"Saving placeholder image {filepath}: {e}", exc_info=True);return None
def _search_pexels_image(self, query, output_filename_base):
if not self.USE_PEXELS or not self.pexels_api_key: return None
headers = {"Authorization": self.pexels_api_key}; params = {"query": query, "per_page": 1, "orientation": "landscape", "size": "large2x"} # Request higher quality
pexels_filename = output_filename_base.replace(".png", f"_pexels_{random.randint(1000,9999)}.jpg").replace(".mp4", f"_pexels_{random.randint(1000,9999)}.jpg")
filepath = os.path.join(self.output_dir, pexels_filename)
try:
logger.info(f"Searching Pexels for: '{query}'"); effective_query = " ".join(query.split()[:5]); params["query"] = effective_query
response = requests.get("https://api.pexels.com/v1/search", headers=headers, params=params, timeout=20)
response.raise_for_status(); data = response.json()
if data.get("photos") and len(data["photos"]) > 0:
photo_url = data["photos"][0]["src"]["large2x"]
image_response = requests.get(photo_url, timeout=60); image_response.raise_for_status()
img_data = Image.open(io.BytesIO(image_response.content))
if img_data.mode != 'RGB': img_data = img_data.convert('RGB')
img_data.save(filepath); logger.info(f"Pexels image saved: {filepath}"); return filepath
else: logger.info(f"No photos found on Pexels for query: '{effective_query}'")
except Exception as e: logger.error(f"Pexels search/download for query '{query}': {e}", exc_info=True)
return None
def _generate_video_clip_with_runwayml(self, prompt_text, scene_identifier_filename_base, target_duration_seconds=4, input_image_path=None):
if not self.USE_RUNWAYML or not self.runway_api_key:
logger.warning("RunwayML not enabled or API key missing. Cannot generate video clip.")
return None
output_video_filename = scene_identifier_filename_base.replace(".png", "_runway.mp4") # More specific extension
output_video_filepath = os.path.join(self.output_dir, output_video_filename)
logger.info(f"Attempting RunwayML video generation for: {prompt_text[:100]}... (Target duration: {target_duration_seconds}s)")
# --- START ACTUAL RUNWAYML API INTERACTION (HYPOTHETICAL - NEEDS IMPLEMENTATION) ---
# Example:
# if self.runway_client:
# try:
# # result = self.runway_client.generate(text=prompt_text, duration=target_duration_seconds, seed_image=input_image_path)
# # result.save(output_video_filepath)
# # return output_video_filepath
# except Exception as e_runway:
# logger.error(f"Actual RunwayML generation error: {e_runway}", exc_info=True)
# return None
# else: logger.warning("RunwayML client not initialized (placeholder).")
# --- END ACTUAL RUNWAYML API INTERACTION (HYPOTHETICAL) ---
logger.warning("Using PLACEHOLDER video generation for RunwayML as actual API calls are not implemented.")
return self._create_placeholder_video_content(f"[RunwayML Placeholder] {prompt_text}", output_video_filename, duration=target_duration_seconds)
def _create_placeholder_video_content(self, text_description, filename, duration=4, size=None):
if size is None: size = self.video_frame_size
filepath = os.path.join(self.output_dir, filename)
txt_clip = None # Initialize
try:
txt_clip = TextClip(text_description, fontsize=50, color='white', font=self.video_overlay_font,
bg_color='black', size=size, method='caption').set_duration(duration)
txt_clip.write_videofile(filepath, fps=24, codec='libx264', preset='ultrafast', logger=None, threads=2)
logger.info(f"Placeholder video saved: {filepath}")
return filepath
except Exception as e: logger.error(f"Failed to create placeholder video {filepath}: {e}", exc_info=True); return None
finally:
if txt_clip and hasattr(txt_clip, 'close'): txt_clip.close()
def generate_scene_asset(self, image_prompt_text, scene_data, scene_identifier_filename_base,
generate_as_video_clip=False, runway_target_duration=4, input_image_for_runway=None):
base_name, _ = os.path.splitext(scene_identifier_filename_base)
asset_info = {'path': None, 'type': 'none', 'error': True, 'prompt_used': image_prompt_text, 'error_message': 'Generation not attempted'}
if generate_as_video_clip and self.USE_RUNWAYML:
logger.info(f"Attempting RunwayML video clip generation for {base_name}")
video_path = self._generate_video_clip_with_runwayml(
image_prompt_text, base_name,
target_duration_seconds=runway_target_duration,
input_image_path=input_image_for_runway
)
if video_path and os.path.exists(video_path):
asset_info = {'path': video_path, 'type': 'video', 'error': False, 'prompt_used': image_prompt_text}
return asset_info
else: logger.warning(f"RunwayML video clip generation failed for {base_name}. Falling back to image."); asset_info['error_message'] = "RunwayML video generation failed."
image_filename_with_ext = base_name + ".png"
filepath = os.path.join(self.output_dir, image_filename_with_ext)
asset_info['type'] = 'image'
if self.USE_AI_IMAGE_GENERATION and self.openai_api_key:
max_retries = 2; attempt_num = 0
for attempt_num in range(max_retries):
try:
logger.info(f"Attempt {attempt_num+1}: DALL-E ({self.dalle_model}) for: {image_prompt_text[:100]}...")
client = openai.OpenAI(api_key=self.openai_api_key, timeout=90.0)
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")
image_url = response.data[0].url; revised_prompt = getattr(response.data[0], 'revised_prompt', None)
if revised_prompt: logger.info(f"DALL-E 3 revised_prompt: {revised_prompt[:100]}...")
image_response = requests.get(image_url, timeout=120); image_response.raise_for_status()
img_data = Image.open(io.BytesIO(image_response.content));
if img_data.mode != 'RGB': img_data = img_data.convert('RGB')
img_data.save(filepath); logger.info(f"AI Image (DALL-E) saved: {filepath}");
asset_info = {'path': filepath, 'type': 'image', 'error': False, 'prompt_used': image_prompt_text, 'revised_prompt': revised_prompt}
return asset_info # Success
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)
except openai.APIError as e_api: logger.error(f"OpenAI API Error: {e_api}"); asset_info['error_message'] = str(e_api); break
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
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
if asset_info['error']: logger.warning(f"DALL-E generation failed after {attempt_num+1} attempts. Trying Pexels fallback...")
if self.USE_PEXELS and (asset_info['error'] or not (self.USE_AI_IMAGE_GENERATION and self.openai_api_key)):
pexels_query_text = scene_data.get('pexels_search_query_감독', f"{scene_data.get('emotional_beat','')} {scene_data.get('setting_description','')}")
pexels_path = self._search_pexels_image(pexels_query_text, image_filename_with_ext)
if pexels_path:
asset_info = {'path': pexels_path, 'type': 'image', 'error': False, 'prompt_used': f"Pexels: {pexels_query_text}"}
return asset_info
current_error_msg = asset_info.get('error_message', "")
asset_info['error_message'] = (current_error_msg + " Pexels search also failed or disabled.").strip()
if not asset_info['error']: logger.warning("Pexels search failed or was disabled (DALL-E not attempted).")
if asset_info['error']:
logger.warning("All primary generation methods failed. Using placeholder image.")
placeholder_prompt_text = asset_info.get('prompt_used', image_prompt_text)
placeholder_path = self._create_placeholder_image_content(f"[Fallback Placeholder] {placeholder_prompt_text[:100]}...", image_filename_with_ext)
if placeholder_path:
asset_info = {'path': placeholder_path, 'type': 'image', 'error': False, 'prompt_used': placeholder_prompt_text}
else:
current_error_msg = asset_info.get('error_message', "")
asset_info['error_message'] = (current_error_msg + " Placeholder creation also failed.").strip()
return asset_info
def generate_narration_audio(self, text_to_narrate, output_filename="narration_overall.mp3"):
if not self.USE_ELEVENLABS or not self.elevenlabs_client or not text_to_narrate:
logger.info("ElevenLabs conditions not met. Skipping audio generation.")
return None
audio_filepath = os.path.join(self.output_dir, output_filename)
try:
logger.info(f"Generating ElevenLabs audio (Voice ID: {self.elevenlabs_voice_id}) for: {text_to_narrate[:70]}...")
audio_stream_method = None
if hasattr(self.elevenlabs_client, 'text_to_speech') and hasattr(self.elevenlabs_client.text_to_speech, 'stream'):
audio_stream_method = self.elevenlabs_client.text_to_speech.stream; logger.info("Using elevenlabs_client.text_to_speech.stream()")
elif hasattr(self.elevenlabs_client, 'generate_stream') : audio_stream_method = self.elevenlabs_client.generate_stream; logger.info("Using elevenlabs_client.generate_stream()")
elif hasattr(self.elevenlabs_client, 'generate'):
logger.info("Using elevenlabs_client.generate() (non-streaming).")
voice_param = 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)
audio_bytes = self.elevenlabs_client.generate(text=text_to_narrate, voice=voice_param, model="eleven_multilingual_v2")
with open(audio_filepath, "wb") as f: f.write(audio_bytes)
logger.info(f"ElevenLabs audio (non-streamed) saved: {audio_filepath}"); return audio_filepath
else: logger.error("No recognized audio generation method found on ElevenLabs client."); return None
if audio_stream_method: # Streaming logic
voice_param_for_stream = {"voice_id": str(self.elevenlabs_voice_id)}
if self.elevenlabs_voice_settings:
if hasattr(self.elevenlabs_voice_settings, 'model_dump'): voice_param_for_stream["voice_settings"] = self.elevenlabs_voice_settings.model_dump() # Pydantic v2
elif hasattr(self.elevenlabs_voice_settings, 'dict'): voice_param_for_stream["voice_settings"] = self.elevenlabs_voice_settings.dict() # Pydantic v1
else: voice_param_for_stream["voice_settings"] = self.elevenlabs_voice_settings
audio_data_iterator = audio_stream_method(text=text_to_narrate, model_id="eleven_multilingual_v2", **voice_param_for_stream)
with open(audio_filepath, "wb") as f:
for chunk in audio_data_iterator:
if chunk: f.write(chunk)
logger.info(f"ElevenLabs audio (streamed) saved: {audio_filepath}"); return audio_filepath
except AttributeError as ae: logger.error(f"AttributeError with ElevenLabs client: {ae}. SDK method/params might be different.", exc_info=True)
except Exception as e: logger.error(f"Error generating ElevenLabs audio: {e}", exc_info=True)
return None
def assemble_animatic_from_assets(self, asset_data_list, overall_narration_path=None, output_filename="final_video.mp4", fps=24):
if not asset_data_list:
logger.warning("No asset data provided for animatic assembly.")
return None
processed_moviepy_clips = []
narration_audio_clip = None
final_composite_clip_obj = None
logger.info(f"Assembling animatic from {len(asset_data_list)} assets. Target frame: {self.video_frame_size}.")
for i, asset_info in enumerate(asset_data_list):
asset_path = asset_info.get('path')
asset_type = asset_info.get('type')
target_scene_duration = asset_info.get('duration', 4.5) # Duration for this scene in the animatic
scene_num = asset_info.get('scene_num', i + 1)
key_action = asset_info.get('key_action', '')
logger.info(f"Processing S{scene_num}: Path='{asset_path}', Type='{asset_type}', TargetDur='{target_scene_duration}'s")
if not (asset_path and os.path.exists(asset_path)):
logger.warning(f"S{scene_num}: Asset not found at '{asset_path}'. Skipping."); continue
if target_scene_duration <= 0:
logger.warning(f"S{scene_num}: Invalid duration ({target_scene_duration}s). Skipping."); continue
current_scene_clip = None # The final MoviePy clip for this scene
try:
if asset_type == 'image':
pil_img = Image.open(asset_path)
logger.debug(f"S{scene_num}: Loaded image. Mode: {pil_img.mode}, Size: {pil_img.size}")
# 1. Ensure image is RGBA for consistent alpha handling during processing
img_rgba_source = pil_img.convert('RGBA') if pil_img.mode != 'RGBA' else pil_img.copy()
# 2. Thumbnail the RGBA image
img_thumbnail = img_rgba_source.copy() # Work on a copy
resample_filter = Image.Resampling.LANCZOS if hasattr(Image.Resampling, 'LANCZOS') else (Image.ANTIALIAS if hasattr(Image, 'ANTIALIAS') else Image.BILINEAR)
img_thumbnail.thumbnail(self.video_frame_size, resample_filter)
logger.debug(f"S{scene_num}: Thumbnailed to: {img_thumbnail.size}")
# 3. Create a target-sized RGBA canvas (fully transparent)
canvas_rgba = Image.new('RGBA', self.video_frame_size, (0, 0, 0, 0))
# 4. Paste the thumbnailed image (with its alpha) onto the center of the RGBA canvas
xo = (self.video_frame_size[0] - img_thumbnail.width) // 2
yo = (self.video_frame_size[1] - img_thumbnail.height) // 2
canvas_rgba.paste(img_thumbnail, (xo, yo), img_thumbnail) # Use img_thumbnail's alpha as mask
logger.debug(f"S{scene_num}: Image pasted onto transparent RGBA canvas.")
# 5. Create a final RGB image by pasting the RGBA canvas onto an opaque background
# This flattens transparency and ensures an RGB image for MoviePy.
final_rgb_image_for_moviepy = Image.new("RGB", self.video_frame_size, (0, 0, 0)) # Opaque black background
final_rgb_image_for_moviepy.paste(canvas_rgba, mask=canvas_rgba.split()[3]) # Paste using alpha from canvas_rgba
# --- CRITICAL DEBUG STEP: Save the image that will be fed to MoviePy ---
debug_canvas_path = os.path.join(self.output_dir, f"debug_final_rgb_FOR_MOVIEPY_scene_{scene_num}.png")
try:
final_rgb_image_for_moviepy.save(debug_canvas_path)
logger.info(f"DEBUG: Saved final RGB image for MoviePy (S{scene_num}) to {debug_canvas_path}")
except Exception as e_save_canvas:
logger.error(f"DEBUG: Failed to save final_rgb_image_for_moviepy (S{scene_num}): {e_save_canvas}")
frame_np = np.array(final_rgb_image_for_moviepy) # Should be (H, W, 3) dtype uint8
logger.debug(f"S{scene_num}: Converted to NumPy. Shape: {frame_np.shape}, Dtype: {frame_np.dtype}, Size: {frame_np.size}")
if frame_np.size == 0: logger.error(f"S{scene_num}: NumPy array is EMPTY. Skipping."); continue
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
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.")
current_clip_base = ImageClip(frame_np, transparent=False).set_duration(target_scene_duration)
logger.debug(f"S{scene_num}: Base ImageClip created from NumPy array.")
current_scene_clip_with_fx = current_clip_base # Start with base
try: # Ken Burns
end_scale = random.uniform(1.03, 1.08)
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')
logger.debug(f"S{scene_num}: Ken Burns effect applied.")
except Exception as e_fx: logger.error(f"S{scene_num}: Ken Burns error: {e_fx}. Using static.", exc_info=False)
current_scene_clip = current_scene_clip_with_fx
elif asset_type == 'video':
logger.debug(f"S{scene_num}: Loading video asset from {asset_path}")
source_video_clip = None # Initialize
try:
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)
temp_clip_for_video_asset = source_video_clip
if source_video_clip.duration != target_scene_duration:
if source_video_clip.duration > target_scene_duration:
temp_clip_for_video_asset = source_video_clip.subclip(0, target_scene_duration)
else: # Source is shorter
if target_scene_duration / source_video_clip.duration > 1.5 and source_video_clip.duration > 0.1:
temp_clip_for_video_asset = source_video_clip.loop(duration=target_scene_duration)
else: # Let it play its native length, will be set to target_scene_duration for concat
temp_clip_for_video_asset = source_video_clip.set_duration(source_video_clip.duration)
logger.info(f"S{scene_num}: Video clip ({source_video_clip.duration:.2f}s) shorter than scene target ({target_scene_duration:.2f}s).")
current_scene_clip = temp_clip_for_video_asset.set_duration(target_scene_duration)
if current_scene_clip.size != list(self.video_frame_size):
logger.debug(f"S{scene_num}: Resizing video clip from {current_scene_clip.size} to {self.video_frame_size}")
current_scene_clip = current_scene_clip.resize(self.video_frame_size)
logger.debug(f"S{scene_num}: Video asset processed. Final duration for scene: {current_scene_clip.duration:.2f}s")
except Exception as e_vid_load:
logger.error(f"S{scene_num}: Error loading/processing video file '{asset_path}': {e_vid_load}", exc_info=True)
if source_video_clip and hasattr(source_video_clip, 'close'): source_video_clip.close()
continue # Skip this asset
finally: # Close original source if it was opened and different from the final clip
if source_video_clip and source_video_clip is not current_scene_clip and hasattr(source_video_clip, 'close'):
source_video_clip.close()
else: logger.warning(f"S{scene_num}: Unknown asset type '{asset_type}'. Skipping."); continue
# Add text overlay (common to both image and video assets)
if current_scene_clip and key_action:
logger.debug(f"S{scene_num}: Adding text overlay: '{key_action}'")
text_overlay_duration = min(target_scene_duration - 0.5, target_scene_duration * 0.8) if target_scene_duration > 0.5 else target_scene_duration
text_overlay_start = (target_scene_duration - text_overlay_duration) / 2.0
if text_overlay_duration > 0:
try:
txt_clip = 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(text_overlay_duration).set_start(text_overlay_start).set_position(('center', 0.92), relative=True)
current_scene_clip = CompositeVideoClip([current_scene_clip, txt_clip], size=self.video_frame_size, use_bgclip=True)
logger.debug(f"S{scene_num}: Text overlay composited.")
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)
if current_scene_clip:
processed_moviepy_clips.append(current_scene_clip)
logger.info(f"S{scene_num}: Asset successfully processed. Clip duration: {current_scene_clip.duration:.2f}s, Added to final list.")
except Exception as e_asset_proc:
logger.error(f"MAJOR Error processing asset for Scene {scene_num} ({asset_path}): {e_asset_proc}", exc_info=True)
# Ensure clip is closed if it was partially created
if current_scene_clip and hasattr(current_scene_clip, 'reader') and current_scene_clip.reader:
if hasattr(current_scene_clip, 'close'): current_scene_clip.close()
elif current_scene_clip and hasattr(current_scene_clip, 'close'):
current_scene_clip.close()
if not processed_moviepy_clips: logger.warning("No MoviePy clips were successfully processed. Aborting animatic assembly."); return None
transition_duration = 0.75
try:
if not processed_moviepy_clips: logger.error("No clips to concatenate after processing loop."); return None
logger.info(f"Concatenating {len(processed_moviepy_clips)} processed clips.")
if len(processed_moviepy_clips) > 1:
final_composite_clip_obj = concatenate_videoclips(processed_moviepy_clips, padding = -transition_duration if transition_duration > 0 else 0, method="compose")
elif processed_moviepy_clips: final_composite_clip_obj = processed_moviepy_clips[0]
if not final_composite_clip_obj: logger.error("Concatenation resulted in a None clip."); return None
logger.info(f"Concatenated clip duration: {final_composite_clip_obj.duration:.2f}s")
if transition_duration > 0:
if final_composite_clip_obj.duration > transition_duration * 2:
final_composite_clip_obj = final_composite_clip_obj.fx(vfx.fadein, transition_duration).fx(vfx.fadeout, transition_duration)
elif final_composite_clip_obj.duration > 0:
final_composite_clip_obj = final_composite_clip_obj.fx(vfx.fadein, min(transition_duration, final_composite_clip_obj.duration/2.0))
logger.debug("Applied fade in/out effects.")
if overall_narration_path and os.path.exists(overall_narration_path) and final_composite_clip_obj.duration > 0:
try:
narration_audio_clip = AudioFileClip(overall_narration_path)
logger.info(f"Adding narration. Video dur: {final_composite_clip_obj.duration:.2f}s, Audio dur: {narration_audio_clip.duration:.2f}s")
final_composite_clip_obj = final_composite_clip_obj.set_audio(narration_audio_clip) # Audio will be cut/padded to video duration
logger.info("Overall narration added to video.")
except Exception as e_audio: logger.error(f"Error adding overall narration: {e_audio}", exc_info=True)
elif final_composite_clip_obj.duration <= 0 : logger.warning("Video has no duration. Audio not added.")
if final_composite_clip_obj and final_composite_clip_obj.duration > 0:
output_path = os.path.join(self.output_dir, output_filename)
logger.info(f"Attempting to write final animatic: {output_path} (Duration: {final_composite_clip_obj.duration:.2f}s)")
moviepy_logger_setting = 'bar' # Default to progress bar
final_composite_clip_obj.write_videofile(
output_path, 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=moviepy_logger_setting, bitrate="5000k"
)
logger.info(f"Animatic video successfully created: {output_path}")
return output_path
else: logger.error("Final animatic clip is invalid or has zero duration. Cannot write file."); return None
except Exception as e_write: logger.error(f"Error during video file writing or final composition: {e_write}", exc_info=True); return None
finally:
logger.debug("Closing all MoviePy clips in `assemble_animatic_from_assets` finally block.")
clips_to_close = processed_moviepy_clips + ([narration_audio_clip] if narration_audio_clip else []) + ([final_composite_clip_obj] if final_composite_clip_obj else [])
for clip_obj in clips_to_close:
if clip_obj and hasattr(clip_obj, 'close'):
try: clip_obj.close()
except Exception as e_close: logger.warning(f"Ignoring error while closing a clip: {e_close}")