CingenAI / core /visual_engine.py
mgbam's picture
Update core/visual_engine.py
59af6e7 verified
raw
history blame
30.3 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)
# --- 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.")
except Exception as e_eleven: logger.warning(f"ElevenLabs client import failed: {e_eleven}. Audio disabled.")
# --- RunwayML Client Import (Placeholder) ---
RUNWAYML_SDK_IMPORTED = False; RunwayMLClient = None
try:
logger.info("RunwayML SDK import is a placeholder.")
except ImportError: logger.warning("RunwayML SDK (placeholder) not found. RunwayML disabled.")
except Exception as e_runway_sdk: logger.warning(f"Error importing RunwayML SDK (placeholder): {e_runway_sdk}. RunwayML 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 = "DejaVuSans-Bold.ttf" # More standard than arial.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", f"C:/Windows/Fonts/arial.ttf",
f"/usr/local/share/fonts/truetype/mycustomfonts/arial.ttf" # Previous custom path
]
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'
self.video_overlay_font = 'DejaVu-Sans-Bold' # ImageMagick name for DejaVuSans-Bold
try:
self.font = ImageFont.truetype(self.font_path_pil, self.font_size_pil) if self.font_path_pil else ImageFont.load_default()
if self.font_path_pil: logger.info(f"Pillow font loaded: {self.font_path_pil}.")
else: logger.warning("Using default Pillow font."); self.font_size_pil = 10
except IOError as e_font: logger.error(f"Pillow font loading IOError: {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.USE_RUNWAYML = True; logger.info(f"RunwayML Client (Placeholder SDK) {'Ready.' if self.USE_RUNWAYML else 'Failed Init.'}")
except Exception as e: logger.error(f"RunwayML client (Placeholder SDK) init error: {e}. Disabled.", exc_info=True); self.USE_RUNWAYML = False
elif k: self.USE_RUNWAYML = True; logger.info("RunwayML API Key set (direct API or placeholder).")
else: self.USE_RUNWAYML = False; logger.info("RunwayML Disabled (no API key).")
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))
def _create_placeholder_image_content(self,td,fn,sz=None):
# ... (Keeping this method as it was, assuming it's not the source of video corruption) ...
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=[];
if not td: td="(Placeholder: No prompt text)"
ws=td.split();cl=""
for w in ws:
tl=cl+w+" ";
if self._get_text_dimensions(tl,self.font)[0] <= mw: cl=tl
else:
if cl: ls.append(cl.strip());
cl=w+" "
if cl.strip(): ls.append(cl.strip())
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 Text Error)")
_,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
if mld <=0: mld = 1
yts = pd + (sz[1]-(2*pd) - mld*(slh+2))/2.0
yt = yts
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
if i==6 and mld > 7: d.text((xt,yt),"...",font=self.font,fill=(200,200,180));break
fp=os.path.join(self.output_dir,fn);
try:img.save(fp);return fp
except Exception as e:logger.error(f"Saving placeholder image {fp}: {e}", exc_info=True);return None
def _search_pexels_image(self, q, ofnb):
# ... (Keeping this method as it was) ...
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"}
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)
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)
r.raise_for_status(); d = r.json()
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 = Image.open(io.BytesIO(ir.content))
if id.mode != 'RGB': id = id.convert('RGB')
id.save(fp); logger.info(f"Pexels image saved: {fp}"); return fp
else: logger.info(f"No photos Pexels: '{eq}'")
except Exception as e: logger.error(f"Pexels error ('{q}'): {e}", exc_info=True)
return None
def _generate_video_clip_with_runwayml(self, pt, sifnb, tds=4, iip=None):
# ... (Keeping placeholder logic) ...
if not self.USE_RUNWAYML or not self.runway_api_key: logger.warning("RunwayML disabled."); return None
ovfn = sifnb.replace(".png", "_runway.mp4")
ovfp = os.path.join(self.output_dir, ovfn)
logger.info(f"RunwayML (Placeholder) for: {pt[:100]}... (Dur: {tds}s)")
return self._create_placeholder_video_content(f"[RunwayML Placeholder] {pt}", ovfn, duration=tds)
def _create_placeholder_video_content(self, td, fn, dur=4, sz=None):
# ... (Keeping placeholder logic) ...
if sz is None: sz = self.video_frame_size
fp = os.path.join(self.output_dir, fn)
tc = None
try:
tc = TextClip(td, fontsize=50, color='white', font=self.video_overlay_font, bg_color='black', size=sz, method='caption').set_duration(dur)
tc.write_videofile(fp, fps=24, codec='libx264', preset='ultrafast', logger=None, threads=2)
logger.info(f"Placeholder video: {fp}"); return fp
except Exception as e: logger.error(f"Placeholder video error {fp}: {e}", exc_info=True); return None
finally:
if tc and hasattr(tc, 'close'): tc.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):
# ... (Keeping this method as it was, it calls the above helpers) ...
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:
video_path = self._generate_video_clip_with_runwayml(image_prompt_text, base_name, runway_target_duration, input_image_for_runway)
if video_path and os.path.exists(video_path): return {'path': video_path, 'type': 'video', 'error': False, 'prompt_used': image_prompt_text}
else: logger.warning(f"RunwayML failed for {base_name}. Fallback to image."); asset_info['error_message'] = "RunwayML 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_r, att_n = 2, 0
for att_n in range(max_r):
try:
logger.info(f"Attempt {att_n+1} DALL-E: {image_prompt_text[:100]}...")
cl = openai.OpenAI(api_key=self.openai_api_key, timeout=90.0)
r = cl.images.generate(model=self.dalle_model, prompt=image_prompt_text, n=1, size=self.image_size_dalle3, quality="hd", response_format="url", style="vivid")
iu = r.data[0].url; rp = getattr(r.data[0], 'revised_prompt', None)
if rp: logger.info(f"DALL-E revised: {rp[:100]}...")
ir = requests.get(iu, timeout=120); ir.raise_for_status()
id = Image.open(io.BytesIO(ir.content));
if id.mode != 'RGB': id = id.convert('RGB')
id.save(filepath); logger.info(f"DALL-E saved: {filepath}");
return {'path': filepath, 'type': 'image', 'error': False, 'prompt_used': image_prompt_text, 'revised_prompt': rp}
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)
except Exception as e: logger.error(f"DALL-E error: {e}", exc_info=True); asset_info['error_message']=str(e); break
if asset_info['error']: logger.warning(f"DALL-E failed after {att_n+1} attempts. Pexels fallback...")
if self.USE_PEXELS and (asset_info['error'] or not (self.USE_AI_IMAGE_GENERATION and self.openai_api_key)):
pqt = scene_data.get('pexels_search_query_감독', f"{scene_data.get('emotional_beat','')} {scene_data.get('setting_description','')}")
pp = self._search_pexels_image(pqt, image_filename_with_ext)
if pp: return {'path': pp, 'type': 'image', 'error': False, 'prompt_used': f"Pexels: {pqt}"}
cem = asset_info.get('error_message', ""); asset_info['error_message'] = (cem + " Pexels failed.").strip()
if not asset_info['error']: logger.warning("Pexels failed (DALL-E not tried).")
if asset_info['error']:
logger.warning("All methods failed. Placeholder image.")
ppt = asset_info.get('prompt_used', image_prompt_text)
php = self._create_placeholder_image_content(f"[Fallback Placeholder] {ppt[:100]}...", image_filename_with_ext)
if php: return {'path': php, 'type': 'image', 'error': False, 'prompt_used': ppt}
else: cem=asset_info.get('error_message',"");asset_info['error_message']=(cem + " Placeholder failed.").strip()
return asset_info
def generate_narration_audio(self, text_to_narrate, output_filename="narration_overall.mp3"):
# ... (Keeping this method as it was - robust enough) ...
if not self.USE_ELEVENLABS or not self.elevenlabs_client or not text_to_narrate: logger.info("ElevenLabs conditions not met. Skip audio."); return None
afp = os.path.join(self.output_dir, output_filename)
try:
logger.info(f"ElevenLabs audio (Voice: {self.elevenlabs_voice_id}) for: {text_to_narrate[:70]}...")
asm = None
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()")
elif hasattr(self.elevenlabs_client,'generate_stream'): asm=self.elevenlabs_client.generate_stream; logger.info("Using 11L .generate_stream()")
elif hasattr(self.elevenlabs_client,'generate'):
logger.info("Using 11L .generate() (non-streaming).")
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")
with open(afp,"wb") as f: f.write(ab)
logger.info(f"11L audio (non-streamed): {afp}"); return afp
else: logger.error("No recognized 11L audio gen method."); return None
if asm:
vps = {"voice_id":str(self.elevenlabs_voice_id)}
if self.elevenlabs_voice_settings:
if hasattr(self.elevenlabs_voice_settings,'model_dump'): vps["voice_settings"]=self.elevenlabs_voice_settings.model_dump()
elif hasattr(self.elevenlabs_voice_settings,'dict'): vps["voice_settings"]=self.elevenlabs_voice_settings.dict()
else: vps["voice_settings"]=self.elevenlabs_voice_settings
adi = asm(text=text_to_narrate,model_id="eleven_multilingual_v2",**vps)
with open(afp,"wb") as f:
for chunk in adi:
if chunk: f.write(chunk)
logger.info(f"11L audio (streamed): {afp}"); return afp
except Exception as e: logger.error(f"11L audio error: {e}", exc_info=True)
return None
# =========================================================================
# ASSEMBLE ANIMATIC - FOCUS OF CORRUPTION DEBUGGING
# =========================================================================
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)
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
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}")
# --- Robust Image Processing Pipeline for MoviePy ---
# 1. Convert to RGBA for consistent alpha handling
img_rgba_source = pil_img.convert('RGBA') if pil_img.mode != 'RGBA' else pil_img.copy()
# 2. Thumbnail
img_thumbnail = img_rgba_source.copy()
resample_filter = Image.Resampling.LANCZOS if hasattr(Image.Resampling, 'LANCZOS') 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 RGBA canvas and paste image onto it (centers and handles transparency)
canvas_rgba = Image.new('RGBA', self.video_frame_size, (0, 0, 0, 0)) # Transparent background
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 thumbnail's alpha as mask
# 4. Convert to final RGB image (flattens alpha against black) for MoviePy
final_rgb_image_for_moviepy = Image.new("RGB", self.video_frame_size, (0, 0, 0)) # Black background
final_rgb_image_for_moviepy.paste(canvas_rgba, mask=canvas_rgba.split()[3]) # Use alpha of canvas_rgba as mask
debug_canvas_path = os.path.join(self.output_dir, f"debug_PRE_NUMPY_S{scene_num}.png")
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}")
except Exception as e_save: logger.error(f"DEBUG: Error saving PRE-NUMPY image for S{scene_num}: {e_save}")
# 5. Convert to C-contiguous NumPy array, dtype uint8
frame_np = np.array(final_rgb_image_for_moviepy, dtype=np.uint8)
if not frame_np.flags['C_CONTIGUOUS']:
frame_np = np.ascontiguousarray(frame_np, dtype=np.uint8)
logger.debug(f"S{scene_num}: Ensured NumPy array is C-contiguous.")
logger.debug(f"S{scene_num}: Final NumPy for MoviePy. Shape: {frame_np.shape}, Dtype: {frame_np.dtype}, Contiguous: {frame_np.flags['C_CONTIGUOUS']}")
if frame_np.size == 0 or frame_np.ndim != 3 or frame_np.shape[2] != 3:
logger.error(f"S{scene_num}: Invalid NumPy array shape/size for ImageClip. Shape: {frame_np.shape}. Skipping."); continue
# --- End Robust Image Processing ---
current_clip_base = ImageClip(frame_np, transparent=False).set_duration(target_scene_duration)
logger.debug(f"S{scene_num}: Base ImageClip created.")
# --- DEBUG: Save frame from MoviePy ImageClip object ---
moviepy_frame_debug_path = os.path.join(self.output_dir, f"debug_MOVIEPY_FRAME_S{scene_num}.png")
try:
current_clip_base.save_frame(moviepy_frame_debug_path, t=0.1) # Save a frame at 0.1s
logger.info(f"DEBUG: Saved frame FROM MOVIEPY ImageClip for S{scene_num} to {moviepy_frame_debug_path}")
except Exception as e_save_mv_frame:
logger.error(f"DEBUG: Error saving frame FROM MOVIEPY ImageClip for S{scene_num}: {e_save_mv_frame}", exc_info=True)
# --- End DEBUG ---
current_scene_clip_with_fx = current_clip_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')
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':
# ... (Video processing logic - keep as in previous good version) ...
source_video_clip = None
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 = source_video_clip
if source_video_clip.duration != target_scene_duration:
if source_video_clip.duration > target_scene_duration: temp_clip = 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 = source_video_clip.loop(duration=target_scene_duration)
else: temp_clip = 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 target ({target_scene_duration:.2f}s).")
current_scene_clip = temp_clip.set_duration(target_scene_duration)
if current_scene_clip.size != list(self.video_frame_size): current_scene_clip = current_scene_clip.resize(self.video_frame_size)
except Exception as e_vid_load: logger.error(f"S{scene_num}: Error loading/processing video '{asset_path}': {e_vid_load}", exc_info=True); continue
finally:
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
if current_scene_clip and key_action: # Add text overlay
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(min(current_scene_clip.duration - 0.5, current_scene_clip.duration * 0.8) if current_scene_clip.duration > 0.5 else current_scene_clip.duration).set_start(0.25).set_position(('center', 0.92), relative=True)
current_scene_clip = CompositeVideoClip([current_scene_clip, txt_clip], size=self.video_frame_size, use_bgclip=True)
except Exception as e_txt: logger.error(f"S{scene_num}: Error with TextClip: {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 processed. Clip duration: {current_scene_clip.duration:.2f}s.")
except Exception as e_asset_proc: logger.error(f"MAJOR Error S{scene_num} ({asset_path}): {e_asset_proc}", exc_info=True)
finally: # Close individual clips if an error occurred during their specific processing
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 clips processed. Aborting."); return None
transition_duration = 0.75
try:
logger.info(f"Concatenating {len(processed_moviepy_clips)} 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 failed."); return None
logger.info(f"Concatenated clip duration: {final_composite_clip_obj.duration:.2f}s")
if transition_duration > 0 and final_composite_clip_obj.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)
else: final_composite_clip_obj = final_composite_clip_obj.fx(vfx.fadein, min(transition_duration, final_composite_clip_obj.duration/2.0))
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); final_composite_clip_obj = final_composite_clip_obj.set_audio(narration_audio_clip); logger.info("Narration added.")
except Exception as e_audio: logger.error(f"Adding narration error: {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"Writing final video: {output_path} (Duration: {final_composite_clip_obj.duration:.2f}s)")
# --- Test different write parameters if corruption persists ---
final_composite_clip_obj.write_videofile(
output_path, fps=fps, codec='libx264',
preset='medium', # Changed from ultrafast for potentially better encoding
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"] # Potentially force pixel format if issues persist
)
logger.info(f"Video created: {output_path}"); return output_path
else: logger.error("Final clip invalid. Not writing."); return None
except Exception as e_write: logger.error(f"Video writing error: {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}")