mgbam commited on
Commit
5089920
·
verified ·
1 Parent(s): 733c176

Update core/visual_engine.py

Browse files
Files changed (1) hide show
  1. core/visual_engine.py +448 -194
core/visual_engine.py CHANGED
@@ -1,188 +1,211 @@
1
  # core/visual_engine.py
2
  from PIL import Image, ImageDraw, ImageFont, ImageOps
3
  # --- MONKEY PATCH FOR Image.ANTIALIAS ---
4
- # This is applied at module load time.
5
- # Attempting to make MoviePy's internal calls to Image.ANTIALIAS work with Pillow 10+
6
  try:
7
  if hasattr(Image, 'Resampling') and hasattr(Image.Resampling, 'LANCZOS'): # Pillow 9+
8
- if not hasattr(Image, 'ANTIALIAS'):
9
- Image.ANTIALIAS = Image.Resampling.LANCZOS
10
- print("INFO: Monkey-patched PIL.Image.ANTIALIAS with Image.Resampling.LANCZOS for MoviePy compatibility.")
11
- elif hasattr(Image, 'LANCZOS'): # Pillow 8 used Image.LANCZOS directly
12
- if not hasattr(Image, 'ANTIALIAS'):
13
- Image.ANTIALIAS = Image.LANCZOS # Pillow 8 had Image.LANCZOS
14
- print("INFO: Monkey-patched PIL.Image.ANTIALIAS with Image.LANCZOS for MoviePy compatibility.")
15
- else:
16
- # This case means Pillow is too old, or an unexpected version.
17
- # If ANTIALIAS is already present, no action needed.
18
- if not hasattr(Image, 'ANTIALIAS'):
19
- print("WARNING: Pillow version does not have common Resampling attributes or ANTIALIAS. Video effects might fail if MoviePy relies on ANTIALIAS.")
20
- except AttributeError:
21
- print("WARNING: Could not perform ANTIALIAS monkey-patch due to AttributeError (Image module might be incomplete).")
22
- except Exception as e_mp:
23
- print(f"WARNING: An unexpected error occurred during ANTIALIAS monkey-patch: {e_mp}")
24
  # --- END MONKEY PATCH ---
25
 
26
- from moviepy.editor import (ImageClip, concatenate_videoclips, TextClip,
27
  CompositeVideoClip, AudioFileClip)
28
- import moviepy.video.fx.all as vfx
29
  import numpy as np
30
  import os
31
  import openai
32
  import requests
33
  import io
34
  import time
35
- import random
36
- import subprocess
37
  import logging
38
 
39
  logger = logging.getLogger(__name__)
40
- logger.setLevel(logging.INFO) # Ensure logs from this module are visible
41
 
 
42
  ELEVENLABS_CLIENT_IMPORTED = False
43
- ElevenLabsAPIClient = None
44
- Voice = None
45
- VoiceSettings = None
46
  try:
47
- from elevenlabs.client import ElevenLabs as ImportedElevenLabsClient
48
  from elevenlabs import Voice as ImportedVoice, VoiceSettings as ImportedVoiceSettings
49
- ElevenLabsAPIClient = ImportedElevenLabsClient
50
  Voice = ImportedVoice
51
  VoiceSettings = ImportedVoiceSettings
52
  ELEVENLABS_CLIENT_IMPORTED = True
53
- logger.info("Successfully imported ElevenLabs client components (SDK v1.x.x pattern).")
54
- except ImportError as e_eleven:
55
- logger.warning(f"Could not import ElevenLabs client components: {e_eleven}. ElevenLabs audio will be disabled.")
56
- except Exception as e_gen_eleven:
57
- logger.warning(f"General error importing ElevenLabs: {e_gen_eleven}. ElevenLabs audio will be disabled.")
 
 
 
 
 
 
 
 
 
 
 
 
 
58
 
59
 
60
  class VisualEngine:
61
  def __init__(self, output_dir="temp_cinegen_media", default_elevenlabs_voice_id="Rachel"):
62
  self.output_dir = output_dir
63
  os.makedirs(self.output_dir, exist_ok=True)
64
-
65
- self.font_filename = "arial.ttf"
66
- self.font_path_in_container = f"/usr/local/share/fonts/truetype/mycustomfonts/{self.font_filename}"
67
- self.font_size_pil = 20
68
- self.video_overlay_font_size = 30
 
 
 
 
 
 
 
 
69
  self.video_overlay_font_color = 'white'
70
- self.video_overlay_font = 'Liberation-Sans-Bold' # More likely to be found by ImageMagick on Linux
71
 
72
  try:
73
- self.font = ImageFont.truetype(self.font_path_in_container, self.font_size_pil)
74
- logger.info(f"Placeholder font loaded: {self.font_path_in_container}.")
 
75
  except IOError:
76
- logger.warning(f"Placeholder font '{self.font_path_in_container}' not found. Using default.")
77
- self.font = ImageFont.load_default()
78
- self.font_size_pil = 10
79
 
80
  self.openai_api_key = None; self.USE_AI_IMAGE_GENERATION = False
81
- self.dalle_model = "dall-e-3"; self.image_size_dalle3 = "1792x1024"
82
- self.video_frame_size = (1280, 720)
83
 
84
  self.elevenlabs_api_key = None; self.USE_ELEVENLABS = False
85
- self.elevenlabs_client = None
86
  self.elevenlabs_voice_id = default_elevenlabs_voice_id
87
- if VoiceSettings and ELEVENLABS_CLIENT_IMPORTED:
88
- self.elevenlabs_voice_settings = VoiceSettings(
89
- stability=0.60, similarity_boost=0.80,
90
- style=0.15, use_speaker_boost=True
91
- )
92
- else:
93
- self.elevenlabs_voice_settings = None
94
 
95
  self.pexels_api_key = None; self.USE_PEXELS = False
 
 
 
 
 
 
96
  logger.info("VisualEngine initialized.")
97
 
98
- def set_openai_api_key(self,k):
99
  self.openai_api_key=k; self.USE_AI_IMAGE_GENERATION=bool(k)
100
- logger.info(f"DALL-E ({self.dalle_model}) {'Ready.' if k else 'Disabled (no API key).'}")
101
 
102
  def set_elevenlabs_api_key(self,api_key, voice_id_from_secret=None):
103
  self.elevenlabs_api_key=api_key
104
- if voice_id_from_secret:
105
- self.elevenlabs_voice_id = voice_id_from_secret
106
- logger.info(f"ElevenLabs Voice ID set from config: {self.elevenlabs_voice_id}")
107
-
108
- if api_key and ELEVENLABS_CLIENT_IMPORTED and ElevenLabsAPIClient:
109
- try:
110
- self.elevenlabs_client = ElevenLabsAPIClient(api_key=api_key)
111
- if self.elevenlabs_client:
112
- self.USE_ELEVENLABS=True
113
- logger.info(f"ElevenLabs Client Ready (Using Voice ID: {self.elevenlabs_voice_id}).")
114
- else:
115
- self.USE_ELEVENLABS=False; logger.warning("ElevenLabs client is None after initialization attempt.")
116
- except Exception as e:
117
- logger.error(f"Error initializing ElevenLabs client: {e}. ElevenLabs Disabled.", exc_info=True);
118
- self.USE_ELEVENLABS=False; self.elevenlabs_client = None
119
- else:
120
- self.USE_ELEVENLABS=False; self.elevenlabs_client = None
121
- if not (ELEVENLABS_CLIENT_IMPORTED and ElevenLabsAPIClient):
122
- pass # Already logged at import time if client class itself failed to import
123
- else: # Client class imported, but API key was not provided
124
- logger.info("ElevenLabs API Key not provided. ElevenLabs Disabled.")
125
-
126
  def set_pexels_api_key(self,k):
127
  self.pexels_api_key=k; self.USE_PEXELS=bool(k)
128
- logger.info(f"Pexels Search {'Ready.' if k else 'Disabled (no API key).'}")
129
-
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
130
  def _get_text_dimensions(self,text_content,font_obj):
131
- if not text_content: return 0,self.font_size_pil
 
132
  try:
133
- if hasattr(font_obj,'getbbox'):
134
  bbox=font_obj.getbbox(text_content);w=bbox[2]-bbox[0];h=bbox[3]-bbox[1]
135
  return w, h if h > 0 else self.font_size_pil
136
- elif hasattr(font_obj,'getsize'):
137
  w,h=font_obj.getsize(text_content)
138
  return w, h if h > 0 else self.font_size_pil
139
- else:
140
  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)
141
  except Exception as e:
142
  logger.warning(f"Error in _get_text_dimensions for '{text_content[:20]}...': {e}")
143
  return int(len(text_content)*self.font_size_pil*0.6),int(self.font_size_pil*1.2) # Fallback
144
-
 
145
  def _create_placeholder_image_content(self,text_description,filename,size=None):
 
146
  if size is None: size = self.video_frame_size
147
  img=Image.new('RGB',size,color=(20,20,40));d=ImageDraw.Draw(img);padding=25;max_w=size[0]-(2*padding);lines=[];
148
  if not text_description: text_description="(Placeholder: No prompt text)"
149
  words=text_description.split();current_line=""
150
  for word in words:
151
- test_line=current_line+word+" ";
152
  if self._get_text_dimensions(test_line,self.font)[0] <= max_w: current_line=test_line
153
  else:
154
- if current_line: lines.append(current_line.strip());
155
  current_line=word+" "
156
  if current_line.strip(): lines.append(current_line.strip()) # Add last line
157
- if not lines and text_description: lines.append(text_description[:max_w//int(self.font_size_pil*0.6 +1)]+"..." if text_description else "(Text too long)") # Handle single very long word
158
  elif not lines: lines.append("(Placeholder Text Error)")
159
 
160
  _,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
161
-
162
  max_lines_to_display=min(len(lines),(size[1]-(2*padding))//(single_line_h+2)) if single_line_h > 0 else 1
163
  if max_lines_to_display <=0: max_lines_to_display = 1 # Ensure at least one line can be attempted
164
 
165
- y_text=padding + (size[1]-(2*padding) - max_lines_to_display*(single_line_h+2))/2.0
 
166
 
167
  for i in range(max_lines_to_display):
168
  line_content=lines[i];line_w,_=self._get_text_dimensions(line_content,self.font);x_text=(size[0]-line_w)/2.0
169
  d.text((x_text,y_text),line_content,font=self.font,fill=(200,200,180));y_text+=single_line_h+2
170
  if i==6 and max_lines_to_display > 7: d.text((x_text,y_text),"...",font=self.font,fill=(200,200,180));break
171
- filepath=os.path.join(self.output_dir,filename);
172
  try:img.save(filepath);return filepath
173
  except Exception as e:logger.error(f"Saving placeholder image {filepath}: {e}", exc_info=True);return None
174
 
 
175
  def _search_pexels_image(self, query, output_filename_base):
 
176
  if not self.USE_PEXELS or not self.pexels_api_key: return None
177
  headers = {"Authorization": self.pexels_api_key}; params = {"query": query, "per_page": 1, "orientation": "landscape", "size": "large"}
178
- pexels_filename = output_filename_base.replace(".png", f"_pexels_{random.randint(1000,9999)}.jpg")
 
179
  filepath = os.path.join(self.output_dir, pexels_filename)
180
  try:
181
  logger.info(f"Searching Pexels for: '{query}'"); effective_query = " ".join(query.split()[:5]); params["query"] = effective_query
182
  response = requests.get("https://api.pexels.com/v1/search", headers=headers, params=params, timeout=20)
183
  response.raise_for_status(); data = response.json()
184
  if data.get("photos") and len(data["photos"]) > 0:
185
- photo_url = data["photos"][0]["src"]["large2x"]
186
  image_response = requests.get(photo_url, timeout=60); image_response.raise_for_status()
187
  img_data = Image.open(io.BytesIO(image_response.content))
188
  if img_data.mode != 'RGB': img_data = img_data.convert('RGB')
@@ -191,151 +214,382 @@ class VisualEngine:
191
  except Exception as e: logger.error(f"Pexels search/download for query '{query}': {e}", exc_info=True)
192
  return None
193
 
194
- def generate_image_visual(self, image_prompt_text, scene_data, scene_identifier_filename):
195
- filepath = os.path.join(self.output_dir, scene_identifier_filename)
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
196
  if self.USE_AI_IMAGE_GENERATION and self.openai_api_key:
197
  max_retries = 2
198
  for attempt in range(max_retries):
199
  try:
 
200
  logger.info(f"Attempt {attempt+1}: DALL-E ({self.dalle_model}) for: {image_prompt_text[:100]}...")
201
- client = openai.OpenAI(api_key=self.openai_api_key, timeout=90.0)
202
  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")
203
  image_url = response.data[0].url; revised_prompt = getattr(response.data[0], 'revised_prompt', None)
204
  if revised_prompt: logger.info(f"DALL-E 3 revised_prompt: {revised_prompt[:100]}...")
205
  image_response = requests.get(image_url, timeout=120); image_response.raise_for_status()
206
- img_data = Image.open(io.BytesIO(image_response.content));
207
  if img_data.mode != 'RGB': img_data = img_data.convert('RGB')
208
- img_data.save(filepath); logger.info(f"AI Image (DALL-E) saved: {filepath}"); return filepath
209
- except openai.RateLimitError as e:
 
210
  logger.warning(f"OpenAI Rate Limit: {e}. Retrying after {5*(attempt+1)}s..."); time.sleep(5 * (attempt + 1))
211
  if attempt == max_retries - 1: logger.error("Max retries for RateLimitError."); break
212
- else: continue
213
- except openai.APIError as e: logger.error(f"OpenAI API Error: {e}"); break
214
  except requests.exceptions.RequestException as e: logger.error(f"Requests Error (DALL-E download): {e}"); break
215
  except Exception as e: logger.error(f"Generic error (DALL-E gen): {e}", exc_info=True); break
216
  logger.warning("DALL-E generation failed. Trying Pexels fallback...")
 
 
 
217
  pexels_query_text = scene_data.get('pexels_search_query_감독', f"{scene_data.get('emotional_beat','')} {scene_data.get('setting_description','')}")
218
- pexels_path = self._search_pexels_image(pexels_query_text, scene_identifier_filename)
219
- if pexels_path: return pexels_path
220
- logger.warning("Pexels also failed/disabled. Using placeholder.")
221
- return self._create_placeholder_image_content(f"[AI/Pexels Failed] {image_prompt_text[:100]}...", scene_identifier_filename)
222
- else:
223
- return self._create_placeholder_image_content(image_prompt_text, scene_identifier_filename)
 
 
 
 
 
 
 
224
 
225
  def generate_narration_audio(self, text_to_narrate, output_filename="narration_overall.mp3"):
 
226
  if not self.USE_ELEVENLABS or not self.elevenlabs_client or not text_to_narrate:
227
  logger.info("ElevenLabs conditions not met (API key, client init, or text). Skipping audio.")
228
  return None
229
-
230
  audio_filepath = os.path.join(self.output_dir, output_filename)
231
  try:
232
  logger.info(f"Generating ElevenLabs audio (Voice ID: {self.elevenlabs_voice_id}) for: {text_to_narrate[:70]}...")
233
-
234
- # Using client.text_to_speech.stream() for newer SDKs (e.g., elevenlabs >= 1.0)
235
  if hasattr(self.elevenlabs_client, 'text_to_speech') and hasattr(self.elevenlabs_client.text_to_speech, 'stream'):
 
236
  logger.info("Using elevenlabs_client.text_to_speech.stream()")
237
- audio_data_iterator = self.elevenlabs_client.text_to_speech.stream(
 
 
 
 
 
 
 
238
  text=text_to_narrate,
239
- voice_id=str(self.elevenlabs_voice_id),
240
- model_id="eleven_multilingual_v2",
241
- # voice_settings=self.elevenlabs_voice_settings # Pass VoiceSettings object if supported by stream
242
  )
243
- # Fallback to direct .generate() if text_to_speech.stream isn't there
244
- # AND Voice/VoiceSettings were successfully imported
245
- elif hasattr(self.elevenlabs_client, 'generate') and Voice and self.elevenlabs_voice_settings:
246
- logger.info("Using elevenlabs_client.generate() with Voice object as fallback.")
247
- voice_param = Voice(voice_id=str(self.elevenlabs_voice_id), settings=self.elevenlabs_voice_settings)
248
- audio_data_iterator = self.elevenlabs_client.generate(
249
- text=text_to_narrate, voice=voice_param, model="eleven_multilingual_v2")
250
  else:
251
- logger.error("No recognized audio generation method found on ElevenLabs client or Voice/VoiceSettings not imported.")
252
  return None
253
-
254
- with open(audio_filepath, "wb") as f:
255
- for chunk in audio_data_iterator:
256
- if chunk: f.write(chunk)
257
- logger.info(f"ElevenLabs audio saved: {audio_filepath}")
258
- return audio_filepath
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
259
  except AttributeError as ae:
260
- logger.error(f"AttributeError with ElevenLabs client: {ae}. SDK method might be different.", exc_info=True)
261
  except Exception as e:
262
  logger.error(f"Error generating ElevenLabs audio: {e}", exc_info=True)
263
  return None
264
 
265
- def create_video_from_images(self, image_data_list, overall_narration_path=None, output_filename="final_video.mp4", fps=24, duration_per_image=4.5):
266
- if not image_data_list: logger.warning("No image data for video."); return None
267
- processed_clips=[]; narration_audio_clip=None; final_video_clip_obj=None
268
- logger.info(f"Preparing {len(image_data_list)} clips. Target frame: {self.video_frame_size}. Duration/img: {duration_per_image}s.")
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
269
 
270
- for i, data in enumerate(image_data_list):
271
- img_path, scene_num, key_action = data.get('path'), data.get('scene_num', i+1), data.get('key_action', '')
272
- if not (img_path and os.path.exists(img_path)): logger.warning(f"Img not found: {img_path}"); continue
 
 
 
 
 
273
  try:
274
- pil_img = Image.open(img_path)
275
- if pil_img.mode != 'RGB': pil_img = pil_img.convert('RGB')
276
-
277
- img_copy = pil_img.copy()
278
- img_copy.thumbnail(self.video_frame_size, Image.Resampling.LANCZOS)
279
-
280
- canvas = Image.new('RGB', self.video_frame_size, (random.randint(0,5), random.randint(0,5), random.randint(0,5)))
281
- xo, yo = (self.video_frame_size[0]-img_copy.width)//2, (self.video_frame_size[1]-img_copy.height)//2
282
- canvas.paste(img_copy, (xo,yo))
283
- frame_np = np.array(canvas)
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
284
 
285
- img_clip_base = ImageClip(frame_np).set_duration(duration_per_image)
 
286
 
287
- # Ken Burns Effect (vfx.resize)
288
- # The monkey patch at the top of this file should address Image.ANTIALIAS
289
- img_clip = img_clip_base # Start with base
290
- try:
291
- end_scale = random.uniform(1.03, 1.08);
292
- img_clip = img_clip_base.fx(vfx.resize, lambda t: 1+(end_scale-1)*(t/duration_per_image))
293
- img_clip = img_clip.set_position('center')
294
- except AttributeError as e_alias:
295
- if 'ANTIALIAS' in str(e_alias): logger.error(f"ANTIALIAS error in vfx.resize for {img_path}. Ken Burns disabled for this clip. Error: {e_alias}")
296
- else: raise # Re-raise other AttributeErrors
297
- except Exception as e_fx: logger.error(f"Error in vfx.resize for {img_path}: {e_fx}. Ken Burns disabled for this clip.")
298
-
299
- if key_action:
300
- txt_clip = TextClip(f"Scene {scene_num}\n{key_action}", fontsize=self.video_overlay_font_size,
301
- color=self.video_overlay_font_color, font=self.video_overlay_font,
302
- bg_color='rgba(10,10,20,0.8)', method='caption', align='West',
303
- size=(self.video_frame_size[0]*0.9, None), kerning=-1, stroke_color='black', stroke_width=1.5
304
- ).set_duration(duration_per_image-1.0).set_start(0.5).set_position(('center',0.92),relative=True)
305
- final_scene_clip = CompositeVideoClip([img_clip, txt_clip], size=self.video_frame_size, use_bgclip=True, bg_color=(0,0,0))
306
- else: final_scene_clip = img_clip
307
- processed_clips.append(final_scene_clip)
308
- except Exception as e: logger.error(f"Creating video clip for {img_path}: {e}", exc_info=True)
309
-
310
- if not processed_clips: logger.warning("No clips processed for video."); return None
311
-
312
- transition = 0.75
313
  try:
314
- final_video_clip_obj = concatenate_videoclips(processed_clips, padding=-transition, method="compose")
315
- if final_video_clip_obj.duration > transition*2:
316
- final_video_clip_obj = final_video_clip_obj.fx(vfx.fadein, transition).fx(vfx.fadeout, transition)
317
-
 
 
 
 
 
 
 
 
 
 
318
  if overall_narration_path and os.path.exists(overall_narration_path):
319
  try:
320
  narration_audio_clip = AudioFileClip(overall_narration_path)
321
- # Adjust video duration to match audio if audio is shorter.
322
- # If audio is longer, MoviePy's set_audio will truncate audio to video length.
323
- if narration_audio_clip.duration < final_video_clip_obj.duration:
324
- logger.info(f"Narration shorter than visuals. Trimming video to {narration_audio_clip.duration}s.")
325
- final_video_clip_obj = final_video_clip_obj.subclip(0, narration_audio_clip.duration)
326
 
327
- final_video_clip_obj = final_video_clip_obj.set_audio(narration_audio_clip); logger.info("Overall narration added.")
328
- except Exception as e: logger.error(f"Adding overall narration: {e}", exc_info=True)
 
 
329
 
330
- output_path = os.path.join(self.output_dir, output_filename); logger.info(f"Writing final video to: {output_path}")
331
- final_video_clip_obj.write_videofile(output_path, fps=fps, codec='libx264', preset='medium',
332
- audio_codec='aac',
333
- temp_audiofile=os.path.join(self.output_dir, f'temp-audio-{os.urandom(4).hex()}.m4a'),
334
- remove_temp=True, threads=os.cpu_count() or 2, logger='bar', bitrate="5000k")
335
- logger.info(f"Video successfully created: {output_path}"); return output_path
336
- except Exception as e: logger.error(f"Writing video file: {e}", exc_info=True); return None
 
 
 
 
337
  finally:
338
- for c_item in processed_clips:
339
- if hasattr(c_item, 'close'): c_item.close()
340
  if narration_audio_clip and hasattr(narration_audio_clip, 'close'): narration_audio_clip.close()
341
- if final_video_clip_obj and hasattr(final_video_clip_obj, 'close'): final_video_clip_obj.close()
 
1
  # core/visual_engine.py
2
  from PIL import Image, ImageDraw, ImageFont, ImageOps
3
  # --- MONKEY PATCH FOR Image.ANTIALIAS ---
 
 
4
  try:
5
  if hasattr(Image, 'Resampling') and hasattr(Image.Resampling, 'LANCZOS'): # Pillow 9+
6
+ if not hasattr(Image, 'ANTIALIAS'): Image.ANTIALIAS = Image.Resampling.LANCZOS
7
+ elif hasattr(Image, 'LANCZOS'): # Pillow 8
8
+ if not hasattr(Image, 'ANTIALIAS'): Image.ANTIALIAS = Image.LANCZOS
9
+ elif not hasattr(Image, 'ANTIALIAS'):
10
+ print("WARNING: Pillow version lacks common Resampling attributes or ANTIALIAS. Video effects might fail.")
11
+ except Exception as e_mp: print(f"WARNING: ANTIALIAS monkey-patch error: {e_mp}")
 
 
 
 
 
 
 
 
 
 
12
  # --- END MONKEY PATCH ---
13
 
14
+ from moviepy.editor import (ImageClip, VideoFileClip, concatenate_videoclips, TextClip,
15
  CompositeVideoClip, AudioFileClip)
16
+ import moviepy.video.fx.all as vfx
17
  import numpy as np
18
  import os
19
  import openai
20
  import requests
21
  import io
22
  import time
23
+ import random
 
24
  import logging
25
 
26
  logger = logging.getLogger(__name__)
27
+ logger.setLevel(logging.INFO)
28
 
29
+ # --- ElevenLabs Client Import ---
30
  ELEVENLABS_CLIENT_IMPORTED = False
31
+ ElevenLabsAPIClient = None
32
+ Voice = None
33
+ VoiceSettings = None
34
  try:
35
+ from elevenlabs.client import ElevenLabs as ImportedElevenLabsClient
36
  from elevenlabs import Voice as ImportedVoice, VoiceSettings as ImportedVoiceSettings
37
+ ElevenLabsAPIClient = ImportedElevenLabsClient
38
  Voice = ImportedVoice
39
  VoiceSettings = ImportedVoiceSettings
40
  ELEVENLABS_CLIENT_IMPORTED = True
41
+ logger.info("ElevenLabs client components imported.")
42
+ except Exception as e_eleven:
43
+ logger.warning(f"ElevenLabs client import failed: {e_eleven}. Audio generation disabled.")
44
+
45
+ # --- RunwayML Client Import (Placeholder) ---
46
+ RUNWAYML_SDK_IMPORTED = False
47
+ RunwayMLClient = None # Placeholder for the actual RunwayML client class
48
+ try:
49
+ # This is a hypothetical import. Replace with actual RunwayML SDK import if available.
50
+ # Example: from runwayml import RunwayClient as ImportedRunwayMLClient
51
+ # RunwayMLClient = ImportedRunwayMLClient
52
+ # RUNWAYML_SDK_IMPORTED = True
53
+ # logger.info("RunwayML SDK (placeholder) imported.")
54
+ logger.info("RunwayML SDK import is a placeholder. Actual SDK needed for Runway features.")
55
+ except ImportError:
56
+ logger.warning("RunwayML SDK (placeholder) not found. RunwayML video generation will be disabled.")
57
+ except Exception as e_runway_sdk:
58
+ logger.warning(f"Error importing RunwayML SDK (placeholder): {e_runway_sdk}. RunwayML features disabled.")
59
 
60
 
61
  class VisualEngine:
62
  def __init__(self, output_dir="temp_cinegen_media", default_elevenlabs_voice_id="Rachel"):
63
  self.output_dir = output_dir
64
  os.makedirs(self.output_dir, exist_ok=True)
65
+
66
+ self.font_filename = "arial.ttf"
67
+ font_paths_to_try = [
68
+ self.font_filename,
69
+ f"/usr/share/fonts/truetype/dejavu/DejaVuSans-Bold.ttf",
70
+ f"/usr/share/fonts/truetype/liberation/LiberationSans-Bold.ttf",
71
+ f"/System/Library/Fonts/Supplemental/Arial.ttf",
72
+ f"C:/Windows/Fonts/arial.ttf",
73
+ f"/usr/local/share/fonts/truetype/mycustomfonts/{self.font_filename}"
74
+ ]
75
+ self.font_path_pil = next((p for p in font_paths_to_try if os.path.exists(p)), None)
76
+ self.font_size_pil = 20
77
+ self.video_overlay_font_size = 30
78
  self.video_overlay_font_color = 'white'
79
+ self.video_overlay_font = 'Liberation-Sans-Bold' # For MoviePy TextClip
80
 
81
  try:
82
+ self.font = ImageFont.truetype(self.font_path_pil, self.font_size_pil) if self.font_path_pil else ImageFont.load_default()
83
+ if self.font_path_pil: logger.info(f"Pillow font loaded: {self.font_path_pil}.")
84
+ else: logger.warning("Using default Pillow font."); self.font_size_pil = 10
85
  except IOError:
86
+ logger.warning("Pillow font error. Using default."); self.font = ImageFont.load_default(); self.font_size_pil = 10
 
 
87
 
88
  self.openai_api_key = None; self.USE_AI_IMAGE_GENERATION = False
89
+ self.dalle_model = "dall-e-3"; self.image_size_dalle3 = "1792x1024"
90
+ self.video_frame_size = (1280, 720)
91
 
92
  self.elevenlabs_api_key = None; self.USE_ELEVENLABS = False
93
+ self.elevenlabs_client = None
94
  self.elevenlabs_voice_id = default_elevenlabs_voice_id
95
+ if VoiceSettings and ELEVENLABS_CLIENT_IMPORTED:
96
+ self.elevenlabs_voice_settings = VoiceSettings(stability=0.60, similarity_boost=0.80, style=0.15, use_speaker_boost=True)
97
+ else: self.elevenlabs_voice_settings = None
 
 
 
 
98
 
99
  self.pexels_api_key = None; self.USE_PEXELS = False
100
+
101
+ # <<< RUNWAYML START >>>
102
+ self.runway_api_key = None; self.USE_RUNWAYML = False
103
+ self.runway_client = None # Placeholder for the actual RunwayML client instance
104
+ # <<< RUNWAYML END >>>
105
+
106
  logger.info("VisualEngine initialized.")
107
 
108
+ def set_openai_api_key(self,k):
109
  self.openai_api_key=k; self.USE_AI_IMAGE_GENERATION=bool(k)
110
+ logger.info(f"DALL-E ({self.dalle_model}) {'Ready.' if k else 'Disabled.'}")
111
 
112
  def set_elevenlabs_api_key(self,api_key, voice_id_from_secret=None):
113
  self.elevenlabs_api_key=api_key
114
+ if voice_id_from_secret: self.elevenlabs_voice_id = voice_id_from_secret
115
+ if api_key and ELEVENLABS_CLIENT_IMPORTED and ElevenLabsAPIClient:
116
+ try:
117
+ self.elevenlabs_client = ElevenLabsAPIClient(api_key=api_key)
118
+ self.USE_ELEVENLABS=bool(self.elevenlabs_client)
119
+ logger.info(f"ElevenLabs Client {'Ready' if self.USE_ELEVENLABS else 'Failed Init'} (Voice ID: {self.elevenlabs_voice_id}).")
120
+ except Exception as e: logger.error(f"ElevenLabs client init error: {e}. Disabled.", exc_info=True); self.USE_ELEVENLABS=False
121
+ else: self.USE_ELEVENLABS=False; logger.info("ElevenLabs Disabled (no key or SDK).")
122
+
 
 
 
 
 
 
 
 
 
 
 
 
 
123
  def set_pexels_api_key(self,k):
124
  self.pexels_api_key=k; self.USE_PEXELS=bool(k)
125
+ logger.info(f"Pexels Search {'Ready.' if k else 'Disabled.'}")
126
+
127
+ # <<< RUNWAYML START >>>
128
+ def set_runway_api_key(self, k):
129
+ self.runway_api_key = k
130
+ if k and RUNWAYML_SDK_IMPORTED and RunwayMLClient: # Assuming RunwayMLClient is the SDK's client class
131
+ try:
132
+ # self.runway_client = RunwayMLClient(api_key=k) # Actual initialization
133
+ self.USE_RUNWAYML = True # Assume success for placeholder
134
+ logger.info(f"RunwayML Client (Placeholder) {'Ready.' if self.USE_RUNWAYML else 'Failed Init.'}")
135
+ except Exception as e:
136
+ logger.error(f"RunwayML client (Placeholder) init error: {e}. Disabled.", exc_info=True)
137
+ self.USE_RUNWAYML = False
138
+ elif k and not (RUNWAYML_SDK_IMPORTED and RunwayMLClient):
139
+ self.USE_RUNWAYML = True # Allow use with direct HTTP requests if SDK isn't used/available
140
+ logger.info("RunwayML API Key set. SDK (Placeholder) not imported/used. Direct API calls would be needed.")
141
+ else:
142
+ self.USE_RUNWAYML = False
143
+ logger.info("RunwayML Disabled (no API key or SDK issue).")
144
+ # <<< RUNWAYML END >>>
145
+
146
  def _get_text_dimensions(self,text_content,font_obj):
147
+ # ... (no changes from your previous version)
148
+ if not text_content: return 0,self.font_size_pil
149
  try:
150
+ if hasattr(font_obj,'getbbox'): # Pillow 8.0.0+
151
  bbox=font_obj.getbbox(text_content);w=bbox[2]-bbox[0];h=bbox[3]-bbox[1]
152
  return w, h if h > 0 else self.font_size_pil
153
+ elif hasattr(font_obj,'getsize'): # Older Pillow
154
  w,h=font_obj.getsize(text_content)
155
  return w, h if h > 0 else self.font_size_pil
156
+ else: # Should not happen with standard ImageFont objects
157
  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)
158
  except Exception as e:
159
  logger.warning(f"Error in _get_text_dimensions for '{text_content[:20]}...': {e}")
160
  return int(len(text_content)*self.font_size_pil*0.6),int(self.font_size_pil*1.2) # Fallback
161
+
162
+
163
  def _create_placeholder_image_content(self,text_description,filename,size=None):
164
+ # ... (no changes from your previous version, ensure filename includes extension e.g. .png)
165
  if size is None: size = self.video_frame_size
166
  img=Image.new('RGB',size,color=(20,20,40));d=ImageDraw.Draw(img);padding=25;max_w=size[0]-(2*padding);lines=[];
167
  if not text_description: text_description="(Placeholder: No prompt text)"
168
  words=text_description.split();current_line=""
169
  for word in words:
170
+ test_line=current_line+word+" ";
171
  if self._get_text_dimensions(test_line,self.font)[0] <= max_w: current_line=test_line
172
  else:
173
+ if current_line: lines.append(current_line.strip());
174
  current_line=word+" "
175
  if current_line.strip(): lines.append(current_line.strip()) # Add last line
176
+ 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)") # Handle single very long word
177
  elif not lines: lines.append("(Placeholder Text Error)")
178
 
179
  _,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
180
+
181
  max_lines_to_display=min(len(lines),(size[1]-(2*padding))//(single_line_h+2)) if single_line_h > 0 else 1
182
  if max_lines_to_display <=0: max_lines_to_display = 1 # Ensure at least one line can be attempted
183
 
184
+ y_text_start = padding + (size[1]-(2*padding) - max_lines_to_display*(single_line_h+2))/2.0
185
+ y_text = y_text_start
186
 
187
  for i in range(max_lines_to_display):
188
  line_content=lines[i];line_w,_=self._get_text_dimensions(line_content,self.font);x_text=(size[0]-line_w)/2.0
189
  d.text((x_text,y_text),line_content,font=self.font,fill=(200,200,180));y_text+=single_line_h+2
190
  if i==6 and max_lines_to_display > 7: d.text((x_text,y_text),"...",font=self.font,fill=(200,200,180));break
191
+ filepath=os.path.join(self.output_dir,filename);
192
  try:img.save(filepath);return filepath
193
  except Exception as e:logger.error(f"Saving placeholder image {filepath}: {e}", exc_info=True);return None
194
 
195
+
196
  def _search_pexels_image(self, query, output_filename_base):
197
+ # ... (no changes from your previous version, ensure output_filename_base has .png for consistency, it will be replaced)
198
  if not self.USE_PEXELS or not self.pexels_api_key: return None
199
  headers = {"Authorization": self.pexels_api_key}; params = {"query": query, "per_page": 1, "orientation": "landscape", "size": "large"}
200
+ # Use a more unique filename for Pexels images to avoid clashes if query is similar
201
+ pexels_filename = output_filename_base.replace(".png", f"_pexels_{random.randint(1000,9999)}.jpg").replace(".mp4", f"_pexels_{random.randint(1000,9999)}.jpg")
202
  filepath = os.path.join(self.output_dir, pexels_filename)
203
  try:
204
  logger.info(f"Searching Pexels for: '{query}'"); effective_query = " ".join(query.split()[:5]); params["query"] = effective_query
205
  response = requests.get("https://api.pexels.com/v1/search", headers=headers, params=params, timeout=20)
206
  response.raise_for_status(); data = response.json()
207
  if data.get("photos") and len(data["photos"]) > 0:
208
+ photo_url = data["photos"][0]["src"]["large2x"] # Using large2x for better quality
209
  image_response = requests.get(photo_url, timeout=60); image_response.raise_for_status()
210
  img_data = Image.open(io.BytesIO(image_response.content))
211
  if img_data.mode != 'RGB': img_data = img_data.convert('RGB')
 
214
  except Exception as e: logger.error(f"Pexels search/download for query '{query}': {e}", exc_info=True)
215
  return None
216
 
217
+
218
+ # <<< RUNWAYML START >>>
219
+ def _generate_video_clip_with_runwayml(self, prompt_text, scene_identifier_filename_base, target_duration_seconds=4, input_image_path=None):
220
+ """
221
+ Placeholder for generating a video clip using RunwayML.
222
+ This needs to be implemented with the actual RunwayML SDK or API.
223
+ """
224
+ if not self.USE_RUNWAYML or not self.runway_api_key:
225
+ logger.warning("RunwayML not enabled or API key missing. Cannot generate video clip.")
226
+ return None
227
+
228
+ output_video_filename = scene_identifier_filename_base.replace(".png", ".mp4") # Ensure .mp4 extension
229
+ output_video_filepath = os.path.join(self.output_dir, output_video_filename)
230
+
231
+ logger.info(f"Attempting RunwayML video generation for: {prompt_text[:100]}... (Target duration: {target_duration_seconds}s)")
232
+ logger.info(f"RunwayML Output (Placeholder): {output_video_filepath}")
233
+
234
+ # --- START ACTUAL RUNWAYML API INTERACTION (HYPOTHETICAL) ---
235
+ # This section is highly dependent on RunwayML's specific API/SDK.
236
+ # Example using a hypothetical SDK:
237
+ # try:
238
+ # if not self.runway_client:
239
+ # # self.runway_client = RunwayMLClient(api_key=self.runway_api_key) # Or however it's initialized
240
+ # logger.warning("RunwayML client not initialized (Placeholder).")
241
+ # # For placeholder, simulate creating a dummy video file
242
+ # return self._create_placeholder_video_content(prompt_text, output_video_filename, duration=target_duration_seconds)
243
+
244
+
245
+ # generation_params = {
246
+ # "text_prompt": prompt_text,
247
+ # "duration_seconds": target_duration_seconds,
248
+ # "width": self.video_frame_size[0], # Or Runway's supported sizes
249
+ # "height": self.video_frame_size[1],
250
+ # # Add other params like seed, motion scale, etc.
251
+ # }
252
+ # if input_image_path and os.path.exists(input_image_path):
253
+ # generation_params["input_image_path"] = input_image_path # For image-to-video
254
+ # logger.info(f"Using input image for RunwayML: {input_image_path}")
255
+
256
+ # task_id = self.runway_client.submit_video_generation_task(**generation_params) # Hypothetical
257
+ # logger.info(f"RunwayML task submitted: {task_id}. Polling for completion...")
258
+
259
+ # while True:
260
+ # status = self.runway_client.get_task_status(task_id) # Hypothetical
261
+ # if status == "completed":
262
+ # video_url = self.runway_client.get_video_url(task_id) # Hypothetical
263
+ # video_response = requests.get(video_url, stream=True, timeout=300)
264
+ # video_response.raise_for_status()
265
+ # with open(output_video_filepath, 'wb') as f:
266
+ # for chunk in video_response.iter_content(chunk_size=8192):
267
+ # f.write(chunk)
268
+ # logger.info(f"RunwayML video downloaded and saved: {output_video_filepath}")
269
+ # return output_video_filepath
270
+ # elif status in ["failed", "error"]:
271
+ # logger.error(f"RunwayML task {task_id} failed.")
272
+ # return None
273
+ # time.sleep(10) # Poll interval
274
+
275
+ # except Exception as e:
276
+ # logger.error(f"Error during RunwayML video generation: {e}", exc_info=True)
277
+ # return None
278
+ # --- END ACTUAL RUNWAYML API INTERACTION (HYPOTHETICAL) ---
279
+
280
+ # For now, as a placeholder, create a dummy MP4 file with MoviePy
281
+ # This allows the rest of the pipeline to be tested.
282
+ # **REPLACE THIS WITH ACTUAL RUNWAYML CALLS**
283
+ logger.warning("Using PLACEHOLDER video generation for RunwayML.")
284
+ return self._create_placeholder_video_content(f"[RunwayML Placeholder] {prompt_text}", output_video_filename, duration=target_duration_seconds)
285
+
286
+ def _create_placeholder_video_content(self, text_description, filename, duration=4, size=None):
287
+ """Creates a short video clip with text as a placeholder."""
288
+ if size is None: size = self.video_frame_size
289
+ filepath = os.path.join(self.output_dir, filename)
290
+
291
+ # Create a simple text clip
292
+ txt_clip = TextClip(text_description, fontsize=50, color='white', font=self.video_overlay_font,
293
+ bg_color='black', size=size, method='caption').set_duration(duration)
294
+
295
+ try:
296
+ txt_clip.write_videofile(filepath, fps=24, codec='libx264', preset='ultrafast', logger=None)
297
+ logger.info(f"Placeholder video saved: {filepath}")
298
+ return filepath
299
+ except Exception as e:
300
+ logger.error(f"Failed to create placeholder video {filepath}: {e}", exc_info=True)
301
+ return None
302
+ finally:
303
+ if hasattr(txt_clip, 'close'): txt_clip.close()
304
+ # <<< RUNWAYML END >>>
305
+
306
+
307
+ def generate_scene_asset(self, image_prompt_text, scene_data, scene_identifier_filename_base,
308
+ generate_as_video_clip=False, runway_target_duration=4, input_image_for_runway=None):
309
+ """
310
+ Generates either an image or a video clip for a scene.
311
+ Returns a dictionary: {'path': asset_path, 'type': 'image'/'video', 'error': bool}
312
+ """
313
+ # Ensure scene_identifier_filename_base does not have an extension yet, or handle it
314
+ base_name, _ = os.path.splitext(scene_identifier_filename_base)
315
+
316
+ if generate_as_video_clip and self.USE_RUNWAYML:
317
+ logger.info(f"Attempting RunwayML video clip generation for {base_name}")
318
+ video_path = self._generate_video_clip_with_runwayml(
319
+ image_prompt_text, # Use DALL-E prompt also for Runway text-to-video
320
+ base_name, # Pass base name, function will add .mp4
321
+ target_duration_seconds=runway_target_duration,
322
+ input_image_path=input_image_for_runway
323
+ )
324
+ if video_path and os.path.exists(video_path):
325
+ return {'path': video_path, 'type': 'video', 'error': False, 'prompt_used': image_prompt_text}
326
+ else:
327
+ logger.warning(f"RunwayML video clip generation failed for {base_name}. Falling back to image.")
328
+ # Fall through to image generation
329
+
330
+ # Image Generation (DALL-E, Pexels, Placeholder)
331
+ # Ensure image filename has .png
332
+ image_filename_with_ext = base_name + ".png"
333
+ filepath = os.path.join(self.output_dir, image_filename_with_ext)
334
+
335
  if self.USE_AI_IMAGE_GENERATION and self.openai_api_key:
336
  max_retries = 2
337
  for attempt in range(max_retries):
338
  try:
339
+ # ... (DALL-E generation logic - no changes from your previous version) ...
340
  logger.info(f"Attempt {attempt+1}: DALL-E ({self.dalle_model}) for: {image_prompt_text[:100]}...")
341
+ client = openai.OpenAI(api_key=self.openai_api_key, timeout=90.0)
342
  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")
343
  image_url = response.data[0].url; revised_prompt = getattr(response.data[0], 'revised_prompt', None)
344
  if revised_prompt: logger.info(f"DALL-E 3 revised_prompt: {revised_prompt[:100]}...")
345
  image_response = requests.get(image_url, timeout=120); image_response.raise_for_status()
346
+ img_data = Image.open(io.BytesIO(image_response.content));
347
  if img_data.mode != 'RGB': img_data = img_data.convert('RGB')
348
+ img_data.save(filepath); logger.info(f"AI Image (DALL-E) saved: {filepath}");
349
+ return {'path': filepath, 'type': 'image', 'error': False, 'prompt_used': image_prompt_text, 'revised_prompt': revised_prompt}
350
+ except openai.RateLimitError as e:
351
  logger.warning(f"OpenAI Rate Limit: {e}. Retrying after {5*(attempt+1)}s..."); time.sleep(5 * (attempt + 1))
352
  if attempt == max_retries - 1: logger.error("Max retries for RateLimitError."); break
353
+ except openai.APIError as e: logger.error(f"OpenAI API Error: {e}"); break
 
354
  except requests.exceptions.RequestException as e: logger.error(f"Requests Error (DALL-E download): {e}"); break
355
  except Exception as e: logger.error(f"Generic error (DALL-E gen): {e}", exc_info=True); break
356
  logger.warning("DALL-E generation failed. Trying Pexels fallback...")
357
+
358
+ # Pexels or Placeholder if DALL-E failed or disabled
359
+ if self.USE_PEXELS:
360
  pexels_query_text = scene_data.get('pexels_search_query_감독', f"{scene_data.get('emotional_beat','')} {scene_data.get('setting_description','')}")
361
+ pexels_path = self._search_pexels_image(pexels_query_text, image_filename_with_ext) # Pass filename with extension
362
+ if pexels_path:
363
+ return {'path': pexels_path, 'type': 'image', 'error': False, 'prompt_used': f"Pexels: {pexels_query_text}"}
364
+ logger.warning("Pexels also failed/disabled. Using placeholder image.")
365
+
366
+ placeholder_path = self._create_placeholder_image_content(
367
+ f"[AI/Pexels Failed] {image_prompt_text[:100]}...", image_filename_with_ext
368
+ )
369
+ if placeholder_path:
370
+ return {'path': placeholder_path, 'type': 'image', 'error': False, 'prompt_used': image_prompt_text}
371
+ else:
372
+ return {'path': None, 'type': 'none', 'error': True, 'prompt_used': image_prompt_text}
373
+
374
 
375
  def generate_narration_audio(self, text_to_narrate, output_filename="narration_overall.mp3"):
376
+ # ... (no changes from your previous version) ...
377
  if not self.USE_ELEVENLABS or not self.elevenlabs_client or not text_to_narrate:
378
  logger.info("ElevenLabs conditions not met (API key, client init, or text). Skipping audio.")
379
  return None
380
+
381
  audio_filepath = os.path.join(self.output_dir, output_filename)
382
  try:
383
  logger.info(f"Generating ElevenLabs audio (Voice ID: {self.elevenlabs_voice_id}) for: {text_to_narrate[:70]}...")
384
+
385
+ audio_stream_method = None
386
  if hasattr(self.elevenlabs_client, 'text_to_speech') and hasattr(self.elevenlabs_client.text_to_speech, 'stream'):
387
+ audio_stream_method = self.elevenlabs_client.text_to_speech.stream
388
  logger.info("Using elevenlabs_client.text_to_speech.stream()")
389
+ elif hasattr(self.elevenlabs_client, 'generate_stream') : # Older SDK might have this
390
+ audio_stream_method = self.elevenlabs_client.generate_stream
391
+ logger.info("Using elevenlabs_client.generate_stream()")
392
+ elif hasattr(self.elevenlabs_client, 'generate'): # Fallback to non-streaming
393
+ logger.info("Using elevenlabs_client.generate() (non-streaming).")
394
+ # This one doesn't return a stream, it returns bytes directly
395
+ 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)
396
+ audio_bytes = self.elevenlabs_client.generate(
397
  text=text_to_narrate,
398
+ voice=voice_param,
399
+ model="eleven_multilingual_v2" # or other suitable model
 
400
  )
401
+ with open(audio_filepath, "wb") as f:
402
+ f.write(audio_bytes)
403
+ logger.info(f"ElevenLabs audio (non-streamed) saved: {audio_filepath}")
404
+ return audio_filepath
 
 
 
405
  else:
406
+ logger.error("No recognized audio generation method found on ElevenLabs client.")
407
  return None
408
+
409
+ # If we have a streaming method
410
+ if audio_stream_method:
411
+ voice_param_for_stream = {"voice_id": str(self.elevenlabs_voice_id)}
412
+ # For Pydantic v1 style for elevenlabs sdk <1.0
413
+ # if self.elevenlabs_voice_settings and hasattr(self.elevenlabs_voice_settings, 'dict'):
414
+ # voice_param_for_stream["voice_settings"] = self.elevenlabs_voice_settings.dict()
415
+ # For Pydantic v2 style for elevenlabs skd >=1.0
416
+ if self.elevenlabs_voice_settings and hasattr(self.elevenlabs_voice_settings, 'model_dump'):
417
+ voice_param_for_stream["voice_settings"] = self.elevenlabs_voice_settings.model_dump()
418
+ elif self.elevenlabs_voice_settings : # If not a pydantic model, pass as is if supported
419
+ voice_param_for_stream["voice_settings"] = self.elevenlabs_voice_settings
420
+
421
+ audio_data_iterator = audio_stream_method(
422
+ text=text_to_narrate,
423
+ model_id="eleven_multilingual_v2",
424
+ **voice_param_for_stream
425
+ )
426
+ with open(audio_filepath, "wb") as f:
427
+ for chunk in audio_data_iterator:
428
+ if chunk: f.write(chunk)
429
+ logger.info(f"ElevenLabs audio (streamed) saved: {audio_filepath}")
430
+ return audio_filepath
431
+
432
  except AttributeError as ae:
433
+ logger.error(f"AttributeError with ElevenLabs client: {ae}. SDK method/params might be different.", exc_info=True)
434
  except Exception as e:
435
  logger.error(f"Error generating ElevenLabs audio: {e}", exc_info=True)
436
  return None
437
 
438
+ def assemble_animatic_from_assets(self, asset_data_list, overall_narration_path=None, output_filename="final_video.mp4", fps=24):
439
+ """
440
+ Assembles the final video from a list of assets (images or video clips).
441
+ Each item in asset_data_list should be a dict like:
442
+ {'path': 'path/to/asset', 'type': 'image'|'video', 'duration': desired_scene_duration_in_animatic,
443
+ 'scene_num': num, 'key_action': 'text'}
444
+ """
445
+ if not asset_data_list:
446
+ logger.warning("No asset data provided for animatic assembly.")
447
+ return None
448
+
449
+ processed_moviepy_clips = []
450
+ narration_audio_clip = None
451
+ final_composite_clip = None
452
+ total_video_duration_from_assets = sum(item.get('duration', 4.5) for item in asset_data_list)
453
+ 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.")
454
+
455
+ for i, asset_info in enumerate(asset_data_list):
456
+ asset_path = asset_info.get('path')
457
+ asset_type = asset_info.get('type')
458
+ # This 'duration' is the desired display duration of THIS scene in the final animatic
459
+ target_scene_duration = asset_info.get('duration', 4.5) # Default if not specified
460
+ scene_num = asset_info.get('scene_num', i + 1)
461
+ key_action = asset_info.get('key_action', '')
462
 
463
+ if not (asset_path and os.path.exists(asset_path)):
464
+ logger.warning(f"Asset not found for Scene {scene_num}: {asset_path}. Skipping.")
465
+ continue
466
+ if target_scene_duration <= 0:
467
+ logger.warning(f"Scene {scene_num} has invalid duration ({target_scene_duration}s). Skipping.")
468
+ continue
469
+
470
+ current_clip = None
471
  try:
472
+ if asset_type == 'image':
473
+ pil_img = Image.open(asset_path)
474
+ if pil_img.mode != 'RGB': pil_img = pil_img.convert('RGB')
475
+ img_copy = pil_img.copy()
476
+ resample_filter = Image.Resampling.LANCZOS if hasattr(Image.Resampling, 'LANCZOS') else (Image.ANTIALIAS if hasattr(Image, 'ANTIALIAS') else Image.BILINEAR)
477
+ img_copy.thumbnail(self.video_frame_size, resample_filter)
478
+ canvas = Image.new('RGB', self.video_frame_size, (random.randint(0,10), random.randint(0,10), random.randint(0,10)))
479
+ xo, yo = (self.video_frame_size[0] - img_copy.width) // 2, (self.video_frame_size[1] - img_copy.height) // 2
480
+ canvas.paste(img_copy, (xo, yo))
481
+ frame_np = np.array(canvas)
482
+ current_clip_base = ImageClip(frame_np).set_duration(target_scene_duration)
483
+
484
+ # Ken Burns for ImageClips
485
+ try:
486
+ end_scale = random.uniform(1.03, 1.08)
487
+ current_clip = current_clip_base.fx(vfx.resize, lambda t: 1 + (end_scale - 1) * (t / target_scene_duration)).set_position('center')
488
+ except Exception as e_fx:
489
+ logger.error(f"Ken Burns error for image {asset_path}: {e_fx}. Using static image.")
490
+ current_clip = current_clip_base
491
+
492
+ elif asset_type == 'video':
493
+ source_video_clip = VideoFileClip(asset_path, target_resolution=(self.video_frame_size[1], self.video_frame_size[0]))
494
+ # Fit video into target_scene_duration:
495
+ # If source is shorter, it will play once. If longer, it will be cut.
496
+ # For more complex looping/speed adjustments, more logic is needed.
497
+ if source_video_clip.duration > target_scene_duration:
498
+ current_clip = source_video_clip.subclip(0, target_scene_duration)
499
+ elif source_video_clip.duration < target_scene_duration:
500
+ # Simple loop if significantly shorter, or just play once if close
501
+ if target_scene_duration / source_video_clip.duration > 1.5 and source_video_clip.duration > 0.1 : # Loop if target is >150% of source
502
+ current_clip = source_video_clip.loop(duration=target_scene_duration)
503
+ else: # Play once, duration will be its own, MoviePy handles concatenation padding
504
+ current_clip = source_video_clip.set_duration(source_video_clip.duration) # Explicitly set
505
+ logger.info(f"Runway clip for S{scene_num} ({source_video_clip.duration:.2f}s) shorter than target ({target_scene_duration:.2f}s), will play once.")
506
+ else: # Durations match
507
+ current_clip = source_video_clip
508
+
509
+ # Ensure the clip has the target duration for consistent concatenation
510
+ if current_clip.duration != target_scene_duration:
511
+ current_clip = current_clip.set_duration(target_scene_duration)
512
+
513
+
514
+ # Resize if necessary (MoviePy does this on CompositeVideoClip too, but explicit can be good)
515
+ if current_clip.size != list(self.video_frame_size):
516
+ current_clip = current_clip.resize(self.video_frame_size)
517
+
518
+ # Close the original source_video_clip if it's different from current_clip (e.g., after subclip)
519
+ if current_clip != source_video_clip and hasattr(source_video_clip, 'close'):
520
+ source_video_clip.close()
521
+
522
+
523
+ else:
524
+ logger.warning(f"Unknown asset type '{asset_type}' for Scene {scene_num}. Skipping.")
525
+ continue
526
+
527
+ # Add text overlay
528
+ if current_clip and key_action:
529
+ text_overlay_duration = min(target_scene_duration - 0.5, target_scene_duration * 0.8) if target_scene_duration > 0.5 else target_scene_duration
530
+ text_overlay_start = (target_scene_duration - text_overlay_duration) / 2.0
531
+ if text_overlay_duration > 0:
532
+ txt_clip = TextClip(f"Scene {scene_num}\n{key_action}",
533
+ fontsize=self.video_overlay_font_size, color=self.video_overlay_font_color,
534
+ font=self.video_overlay_font, bg_color='rgba(10,10,20,0.7)',
535
+ method='caption', align='West', size=(self.video_frame_size[0] * 0.9, None),
536
+ kerning=-1, stroke_color='black', stroke_width=1.5
537
+ ).set_duration(text_overlay_duration).set_start(text_overlay_start).set_position(('center', 0.92), relative=True)
538
+ current_clip = CompositeVideoClip([current_clip, txt_clip], size=self.video_frame_size, use_bgclip=True, bg_color=(0,0,0))
539
 
540
+ if current_clip:
541
+ processed_moviepy_clips.append(current_clip)
542
 
543
+ except Exception as e:
544
+ logger.error(f"Error processing asset for Scene {scene_num} ({asset_path}): {e}", exc_info=True)
545
+ if current_clip and hasattr(current_clip, 'close'): current_clip.close() # Ensure closure on error
546
+
547
+ if not processed_moviepy_clips:
548
+ logger.warning("No MoviePy clips successfully processed. Aborting animatic assembly.")
549
+ return None
550
+
551
+ transition_duration = 0.75
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
552
  try:
553
+ if len(processed_moviepy_clips) > 1:
554
+ final_composite_clip = concatenate_videoclips(processed_moviepy_clips, padding=-transition_duration, method="compose")
555
+ elif processed_moviepy_clips:
556
+ final_composite_clip = processed_moviepy_clips[0]
557
+ else: # Should have been caught above, but defensive
558
+ logger.error("No clips available for final concatenation.")
559
+ return None
560
+
561
+
562
+ if final_composite_clip.duration > transition_duration * 2:
563
+ final_composite_clip = final_composite_clip.fx(vfx.fadein, transition_duration).fx(vfx.fadeout, transition_duration)
564
+ elif final_composite_clip.duration > 0:
565
+ final_composite_clip = final_composite_clip.fx(vfx.fadein, min(transition_duration, final_composite_clip.duration/2.0))
566
+
567
  if overall_narration_path and os.path.exists(overall_narration_path):
568
  try:
569
  narration_audio_clip = AudioFileClip(overall_narration_path)
570
+ if final_composite_clip.duration > 0 and narration_audio_clip.duration < final_composite_clip.duration:
571
+ logger.info(f"Narration ({narration_audio_clip.duration:.2f}s) shorter than visuals ({final_composite_clip.duration:.2f}s). Trimming video.")
572
+ final_composite_clip = final_composite_clip.subclip(0, narration_audio_clip.duration)
573
+ elif final_composite_clip.duration <= 0: logger.warning("Video has no duration. Audio not added.")
 
574
 
575
+ if narration_audio_clip and final_composite_clip.duration > 0: # Check again
576
+ final_composite_clip = final_composite_clip.set_audio(narration_audio_clip)
577
+ logger.info("Overall narration added.")
578
+ except Exception as e: logger.error(f"Adding narration error: {e}", exc_info=True)
579
 
580
+ if final_composite_clip and final_composite_clip.duration > 0:
581
+ output_path = os.path.join(self.output_dir, output_filename)
582
+ logger.info(f"Writing final animatic: {output_path} (Duration: {final_composite_clip.duration:.2f}s)")
583
+ final_composite_clip.write_videofile(
584
+ output_path, fps=fps, codec='libx264', preset='medium', audio_codec='aac',
585
+ temp_audiofile=os.path.join(self.output_dir, f'temp-audio-{os.urandom(4).hex()}.m4a'),
586
+ remove_temp=True, threads=os.cpu_count() or 2, logger='bar', bitrate="5000k"
587
+ )
588
+ logger.info(f"Animatic created: {output_path}"); return output_path
589
+ else: logger.error("Final animatic clip invalid or has no duration. Not writing file."); return None
590
+ except Exception as e: logger.error(f"Animatic writing error: {e}", exc_info=True); return None
591
  finally:
592
+ for clip in processed_moviepy_clips:
593
+ if hasattr(clip, 'close'): clip.close()
594
  if narration_audio_clip and hasattr(narration_audio_clip, 'close'): narration_audio_clip.close()
595
+ if final_composite_clip and hasattr(final_composite_clip, 'close'): final_composite_clip.close()