Update core/visual_engine.py
Browse files- core/visual_engine.py +66 -91
core/visual_engine.py
CHANGED
|
@@ -1,5 +1,5 @@
|
|
| 1 |
# core/visual_engine.py
|
| 2 |
-
from PIL import Image, ImageDraw, ImageFont, ImageOps
|
| 3 |
from moviepy.editor import (ImageClip, concatenate_videoclips, TextClip,
|
| 4 |
CompositeVideoClip, AudioFileClip)
|
| 5 |
import moviepy.video.fx.all as vfx
|
|
@@ -16,12 +16,26 @@ import logging
|
|
| 16 |
logger = logging.getLogger(__name__)
|
| 17 |
logger.setLevel(logging.INFO)
|
| 18 |
|
| 19 |
-
# ---
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 20 |
ELEVENLABS_CLIENT_IMPORTED = False
|
| 21 |
ElevenLabsAPIClient = None
|
| 22 |
Voice = None
|
| 23 |
VoiceSettings = None
|
| 24 |
-
|
| 25 |
try:
|
| 26 |
from elevenlabs.client import ElevenLabs as ImportedElevenLabsClient
|
| 27 |
from elevenlabs import Voice as ImportedVoice, VoiceSettings as ImportedVoiceSettings
|
|
@@ -29,53 +43,31 @@ try:
|
|
| 29 |
Voice = ImportedVoice
|
| 30 |
VoiceSettings = ImportedVoiceSettings
|
| 31 |
ELEVENLABS_CLIENT_IMPORTED = True
|
| 32 |
-
logger.info("Successfully imported ElevenLabs client components
|
| 33 |
-
except ImportError as e_eleven:
|
| 34 |
-
|
| 35 |
-
except Exception as e_gen_eleven:
|
| 36 |
-
logger.warning(f"General error importing ElevenLabs: {e_gen_eleven}. ElevenLabs audio will be disabled.")
|
| 37 |
-
|
| 38 |
|
| 39 |
class VisualEngine:
|
| 40 |
def __init__(self, output_dir="temp_cinegen_media"):
|
| 41 |
-
self.output_dir = output_dir
|
| 42 |
-
|
|
|
|
|
|
|
|
|
|
| 43 |
|
| 44 |
-
self.font_filename = "arial.ttf"
|
| 45 |
-
self.font_path_in_container = f"/usr/local/share/fonts/truetype/mycustomfonts/{self.font_filename}"
|
| 46 |
-
self.font_size_pil = 20
|
| 47 |
-
self.video_overlay_font_size = 30
|
| 48 |
-
self.video_overlay_font_color = 'white'
|
| 49 |
-
self.video_overlay_font = 'Liberation-Sans-Bold' # More likely to be found by ImageMagick on Linux
|
| 50 |
-
|
| 51 |
-
try:
|
| 52 |
-
self.font = ImageFont.truetype(self.font_path_in_container, self.font_size_pil)
|
| 53 |
-
logger.info(f"Placeholder font loaded: {self.font_path_in_container}.")
|
| 54 |
-
except IOError:
|
| 55 |
-
logger.warning(f"Placeholder font '{self.font_path_in_container}' not found. Using default.")
|
| 56 |
-
self.font = ImageFont.load_default()
|
| 57 |
-
self.font_size_pil = 10
|
| 58 |
-
|
| 59 |
self.openai_api_key = None; self.USE_AI_IMAGE_GENERATION = False
|
| 60 |
-
self.dalle_model = "dall-e-3"; self.image_size_dalle3 = "1792x1024"
|
| 61 |
-
self.
|
| 62 |
-
|
| 63 |
-
|
| 64 |
-
self.
|
| 65 |
-
self.elevenlabs_voice_id = "Rachel"
|
| 66 |
if VoiceSettings and ELEVENLABS_CLIENT_IMPORTED:
|
| 67 |
-
self.elevenlabs_voice_settings = VoiceSettings(
|
| 68 |
-
stability=0.60, similarity_boost=0.80,
|
| 69 |
-
style=0.15, use_speaker_boost=True
|
| 70 |
-
)
|
| 71 |
else: self.elevenlabs_voice_settings = None
|
| 72 |
self.pexels_api_key = None; self.USE_PEXELS = False
|
| 73 |
logger.info("VisualEngine initialized.")
|
| 74 |
|
| 75 |
-
def set_openai_api_key(self,k):
|
| 76 |
-
self.openai_api_key=k; self.USE_AI_IMAGE_GENERATION=bool(k)
|
| 77 |
-
logger.info(f"DALL-E ({self.dalle_model}) {'Ready.' if k else 'Disabled (no API key).'}")
|
| 78 |
-
|
| 79 |
def set_elevenlabs_api_key(self,api_key):
|
| 80 |
self.elevenlabs_api_key=api_key
|
| 81 |
if api_key and ELEVENLABS_CLIENT_IMPORTED and ElevenLabsAPIClient:
|
|
@@ -83,19 +75,12 @@ class VisualEngine:
|
|
| 83 |
self.elevenlabs_client = ElevenLabsAPIClient(api_key=api_key)
|
| 84 |
if self.elevenlabs_client: self.USE_ELEVENLABS=True; logger.info("ElevenLabs Client Ready.")
|
| 85 |
else: self.USE_ELEVENLABS=False; logger.warning("ElevenLabs client is None post-init.")
|
| 86 |
-
except Exception as e:
|
| 87 |
-
|
| 88 |
-
|
| 89 |
-
|
| 90 |
-
self.USE_ELEVENLABS=False; self.elevenlabs_client = None
|
| 91 |
-
if not (ELEVENLABS_CLIENT_IMPORTED and ElevenLabsAPIClient): pass # Logged at import
|
| 92 |
-
else: logger.info("ElevenLabs API Key not provided. Disabled.")
|
| 93 |
-
|
| 94 |
-
def set_pexels_api_key(self,k):
|
| 95 |
-
self.pexels_api_key=k; self.USE_PEXELS=bool(k)
|
| 96 |
-
logger.info(f"Pexels Search {'Ready.' if k else 'Disabled (no API key).'}")
|
| 97 |
|
| 98 |
-
def _get_text_dimensions(self,text_content,font_obj): #
|
| 99 |
if not text_content: return 0,self.font_size_pil
|
| 100 |
try:
|
| 101 |
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 self.font_size_pil
|
|
@@ -103,7 +88,7 @@ class VisualEngine:
|
|
| 103 |
else: return int(len(text_content)*self.font_size_pil*0.6),int(self.font_size_pil*1.2 if self.font_size_pil*1.2>0 else self.font_size_pil)
|
| 104 |
except: return int(len(text_content)*self.font_size_pil*0.6),int(self.font_size_pil*1.2)
|
| 105 |
|
| 106 |
-
def _create_placeholder_image_content(self,text_description,filename,size=None): #
|
| 107 |
if size is None: size = self.video_frame_size
|
| 108 |
img=Image.new('RGB',size,color=(20,20,40));d=ImageDraw.Draw(img);padding=25;max_w=size[0]-(2*padding);lines=[];
|
| 109 |
if not text_description: text_description="(Placeholder: No prompt text)"
|
|
@@ -126,7 +111,7 @@ class VisualEngine:
|
|
| 126 |
try:img.save(filepath);return filepath
|
| 127 |
except Exception as e:logger.error(f"Saving placeholder image {filepath}: {e}", exc_info=True);return None
|
| 128 |
|
| 129 |
-
def _search_pexels_image(self, query, output_filename_base): #
|
| 130 |
if not self.USE_PEXELS or not self.pexels_api_key: return None
|
| 131 |
headers = {"Authorization": self.pexels_api_key}; params = {"query": query, "per_page": 1, "orientation": "landscape", "size": "large"}
|
| 132 |
pexels_filename = output_filename_base.replace(".png", f"_pexels_{random.randint(1000,9999)}.jpg")
|
|
@@ -145,7 +130,7 @@ class VisualEngine:
|
|
| 145 |
except Exception as e: logger.error(f"Pexels search/download for query '{query}': {e}", exc_info=True)
|
| 146 |
return None
|
| 147 |
|
| 148 |
-
def generate_image_visual(self, image_prompt_text, scene_data, scene_identifier_filename): #
|
| 149 |
filepath = os.path.join(self.output_dir, scene_identifier_filename)
|
| 150 |
if self.USE_AI_IMAGE_GENERATION and self.openai_api_key:
|
| 151 |
max_retries = 2
|
|
@@ -183,44 +168,34 @@ class VisualEngine:
|
|
| 183 |
|
| 184 |
audio_filepath = os.path.join(self.output_dir, output_filename)
|
| 185 |
try:
|
| 186 |
-
logger.info(f"Generating ElevenLabs audio (Voice: {self.elevenlabs_voice_id}) for: {text_to_narrate[:70]}...")
|
| 187 |
|
| 188 |
-
#
|
| 189 |
-
voice_param = self.elevenlabs_voice_id
|
| 190 |
-
if Voice and self.elevenlabs_voice_settings: # Check if Voice & VoiceSettings were imported
|
| 191 |
-
voice_param = Voice(
|
| 192 |
-
voice_id=self.elevenlabs_voice_id, # This voice_id must be a valid ID string or a known name
|
| 193 |
-
settings=self.elevenlabs_voice_settings
|
| 194 |
-
)
|
| 195 |
-
|
| 196 |
-
# Use the text_to_speech.stream() method for newer SDK
|
| 197 |
if hasattr(self.elevenlabs_client, 'text_to_speech') and hasattr(self.elevenlabs_client.text_to_speech, 'stream'):
|
| 198 |
logger.info("Using elevenlabs_client.text_to_speech.stream()")
|
|
|
|
| 199 |
audio_data_iterator = self.elevenlabs_client.text_to_speech.stream(
|
| 200 |
text=text_to_narrate,
|
| 201 |
-
voice_id=self.elevenlabs_voice_id, #
|
| 202 |
-
model_id="eleven_multilingual_v2" #
|
| 203 |
-
|
| 204 |
-
# Fallback to direct .generate() if text_to_speech.stream isn't there (might be an older v1 client or different structure)
|
| 205 |
-
elif hasattr(self.elevenlabs_client, 'generate'):
|
| 206 |
-
logger.info("Using elevenlabs_client.generate() as fallback.")
|
| 207 |
-
audio_data_iterator = self.elevenlabs_client.generate(
|
| 208 |
-
text=text_to_narrate,
|
| 209 |
-
voice=voice_param, # This might take the Voice object or just the ID string
|
| 210 |
-
model="eleven_multilingual_v2"
|
| 211 |
)
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 212 |
else:
|
| 213 |
-
logger.error("No recognized audio generation method
|
| 214 |
return None
|
| 215 |
|
| 216 |
with open(audio_filepath, "wb") as f:
|
| 217 |
for chunk in audio_data_iterator:
|
| 218 |
if chunk: f.write(chunk)
|
| 219 |
-
|
| 220 |
logger.info(f"ElevenLabs audio saved: {audio_filepath}")
|
| 221 |
return audio_filepath
|
| 222 |
except AttributeError as ae:
|
| 223 |
-
logger.error(f"AttributeError with ElevenLabs client: {ae}.
|
| 224 |
except Exception as e:
|
| 225 |
logger.error(f"Error generating ElevenLabs audio: {e}", exc_info=True)
|
| 226 |
return None
|
|
@@ -228,39 +203,39 @@ class VisualEngine:
|
|
| 228 |
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):
|
| 229 |
if not image_data_list: logger.warning("No image data for video."); return None
|
| 230 |
processed_clips = []; narration_audio_clip = None; final_video_clip_obj = None
|
|
|
|
| 231 |
|
| 232 |
-
logger.info(f"Preparing {len(image_data_list)} clips for video. Target frame size: {self.video_frame_size}")
|
| 233 |
for i, data in enumerate(image_data_list):
|
| 234 |
img_path, scene_num, key_action = data.get('path'), data.get('scene_num', i+1), data.get('key_action', '')
|
| 235 |
-
if not (img_path and os.path.exists(img_path)): logger.warning(f"Img not found
|
| 236 |
try:
|
| 237 |
pil_img = Image.open(img_path)
|
| 238 |
if pil_img.mode != 'RGB': pil_img = pil_img.convert('RGB')
|
| 239 |
|
| 240 |
-
# Resize and letterbox/pillarbox
|
| 241 |
img_copy = pil_img.copy()
|
| 242 |
-
# Use Image.Resampling.LANCZOS
|
| 243 |
img_copy.thumbnail(self.video_frame_size, Image.Resampling.LANCZOS)
|
| 244 |
|
| 245 |
canvas = Image.new('RGB', self.video_frame_size, (random.randint(0,5), random.randint(0,5), random.randint(0,5)))
|
| 246 |
xo, yo = (self.video_frame_size[0]-img_copy.width)//2, (self.video_frame_size[1]-img_copy.height)//2
|
| 247 |
canvas.paste(img_copy, (xo,yo))
|
| 248 |
-
frame_np = np.array(canvas)
|
| 249 |
|
| 250 |
-
|
| 251 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 252 |
|
| 253 |
-
end_scale = random.uniform(1.03, 1.08)
|
| 254 |
-
img_clip = img_clip.fx(vfx.resize, lambda t: 1 + (end_scale - 1) * (t / duration_per_image))
|
| 255 |
-
img_clip = img_clip.set_position('center')
|
| 256 |
-
|
| 257 |
if key_action:
|
| 258 |
txt_clip = TextClip(f"Scene {scene_num}\n{key_action}", fontsize=self.video_overlay_font_size,
|
| 259 |
color=self.video_overlay_font_color, font=self.video_overlay_font,
|
| 260 |
bg_color='rgba(10,10,20,0.8)', method='caption', align='West',
|
| 261 |
size=(self.video_frame_size[0]*0.9, None), kerning=-1, stroke_color='black', stroke_width=1.5
|
| 262 |
).set_duration(duration_per_image - 1.0).set_start(0.5).set_position(('center', 0.92), relative=True)
|
| 263 |
-
final_scene_clip = CompositeVideoClip([img_clip, txt_clip], size=self.video_frame_size, use_bgclip=True, bg_color=(0,0,0))
|
| 264 |
else: final_scene_clip = img_clip
|
| 265 |
processed_clips.append(final_scene_clip)
|
| 266 |
except Exception as e: logger.error(f"Creating video clip for {img_path}: {e}", exc_info=True)
|
|
@@ -290,7 +265,7 @@ class VisualEngine:
|
|
| 290 |
remove_temp=True, threads=os.cpu_count() or 2, logger='bar', bitrate="5000k")
|
| 291 |
logger.info(f"Video successfully created: {output_path}"); return output_path
|
| 292 |
except Exception as e: logger.error(f"Writing video file: {e}", exc_info=True); return None
|
| 293 |
-
finally:
|
| 294 |
for c_item in processed_clips:
|
| 295 |
if hasattr(c_item, 'close'): c_item.close()
|
| 296 |
if narration_audio_clip and hasattr(narration_audio_clip, 'close'): narration_audio_clip.close()
|
|
|
|
| 1 |
# core/visual_engine.py
|
| 2 |
+
from PIL import Image, ImageDraw, ImageFont, ImageOps
|
| 3 |
from moviepy.editor import (ImageClip, concatenate_videoclips, TextClip,
|
| 4 |
CompositeVideoClip, AudioFileClip)
|
| 5 |
import moviepy.video.fx.all as vfx
|
|
|
|
| 16 |
logger = logging.getLogger(__name__)
|
| 17 |
logger.setLevel(logging.INFO)
|
| 18 |
|
| 19 |
+
# --- MONKEY PATCH FOR Image.ANTIALIAS (LAST RESORT) ---
|
| 20 |
+
# Uncomment this section ONLY if updating MoviePy/Pillow and removing Ken Burns vfx.resize doesn't work.
|
| 21 |
+
# This is a hack to make old MoviePy code that calls Image.ANTIALIAS work with newer Pillow.
|
| 22 |
+
# if hasattr(Image, 'Resampling') and hasattr(Image.Resampling, 'LANCZOS'): # Pillow 9+
|
| 23 |
+
# if not hasattr(Image, 'ANTIALIAS'):
|
| 24 |
+
# logger.warning("PIL.Image.ANTIALIAS not found. Monkey-patching with Image.Resampling.LANCZOS.")
|
| 25 |
+
# Image.ANTIALIAS = Image.Resampling.LANCZOS
|
| 26 |
+
# elif hasattr(Image, 'LANCZOS'): # Pillow 8 used Image.LANCZOS directly
|
| 27 |
+
# if not hasattr(Image, 'ANTIALIAS'):
|
| 28 |
+
# logger.warning("PIL.Image.ANTIALIAS not found. Monkey-patching with Image.LANCZOS.")
|
| 29 |
+
# Image.ANTIALIAS = Image.LANCZOS
|
| 30 |
+
# else:
|
| 31 |
+
# logger.warning("Pillow version is too old or Resampling attributes not found for ANTIALIAS monkey-patch.")
|
| 32 |
+
# --- END MONKEY PATCH ---
|
| 33 |
+
|
| 34 |
+
|
| 35 |
ELEVENLABS_CLIENT_IMPORTED = False
|
| 36 |
ElevenLabsAPIClient = None
|
| 37 |
Voice = None
|
| 38 |
VoiceSettings = None
|
|
|
|
| 39 |
try:
|
| 40 |
from elevenlabs.client import ElevenLabs as ImportedElevenLabsClient
|
| 41 |
from elevenlabs import Voice as ImportedVoice, VoiceSettings as ImportedVoiceSettings
|
|
|
|
| 43 |
Voice = ImportedVoice
|
| 44 |
VoiceSettings = ImportedVoiceSettings
|
| 45 |
ELEVENLABS_CLIENT_IMPORTED = True
|
| 46 |
+
logger.info("Successfully imported ElevenLabs client components.")
|
| 47 |
+
except ImportError as e_eleven: logger.warning(f"ElevenLabs client import failed: {e_eleven}. Audio disabled.")
|
| 48 |
+
except Exception as e_gen_eleven: logger.warning(f"General ElevenLabs import error: {e_gen_eleven}. Audio disabled.")
|
|
|
|
|
|
|
|
|
|
| 49 |
|
| 50 |
class VisualEngine:
|
| 51 |
def __init__(self, output_dir="temp_cinegen_media"):
|
| 52 |
+
self.output_dir = output_dir; os.makedirs(self.output_dir, exist_ok=True)
|
| 53 |
+
self.font_filename = "arial.ttf"; self.font_path_in_container = f"/usr/local/share/fonts/truetype/mycustomfonts/{self.font_filename}"
|
| 54 |
+
self.font_size_pil = 20; self.video_overlay_font_size = 30; self.video_overlay_font_color = 'white'; self.video_overlay_font = 'Liberation-Sans-Bold'
|
| 55 |
+
try: self.font = ImageFont.truetype(self.font_path_in_container, self.font_size_pil); logger.info(f"Placeholder font: {self.font_path_in_container}.")
|
| 56 |
+
except IOError: logger.warning(f"Placeholder font '{self.font_path_in_container}' fail. Default."); self.font = ImageFont.load_default(); self.font_size_pil = 10
|
| 57 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 58 |
self.openai_api_key = None; self.USE_AI_IMAGE_GENERATION = False
|
| 59 |
+
self.dalle_model = "dall-e-3"; self.image_size_dalle3 = "1792x1024"; self.video_frame_size = (1280, 720)
|
| 60 |
+
self.elevenlabs_api_key = None; self.USE_ELEVENLABS = False; self.elevenlabs_client = None
|
| 61 |
+
# IMPORTANT: Replace with a VALID Voice ID from your ElevenLabs account for the model you use.
|
| 62 |
+
# Common pre-made voices might work by name, but IDs are more reliable.
|
| 63 |
+
self.elevenlabs_voice_id = "Rachel" # E.g., "21m00Tcm4TlvDq8ikWAM" or another valid ID
|
|
|
|
| 64 |
if VoiceSettings and ELEVENLABS_CLIENT_IMPORTED:
|
| 65 |
+
self.elevenlabs_voice_settings = VoiceSettings(stability=0.60, similarity_boost=0.80, style=0.15, use_speaker_boost=True)
|
|
|
|
|
|
|
|
|
|
| 66 |
else: self.elevenlabs_voice_settings = None
|
| 67 |
self.pexels_api_key = None; self.USE_PEXELS = False
|
| 68 |
logger.info("VisualEngine initialized.")
|
| 69 |
|
| 70 |
+
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.'}")
|
|
|
|
|
|
|
|
|
|
| 71 |
def set_elevenlabs_api_key(self,api_key):
|
| 72 |
self.elevenlabs_api_key=api_key
|
| 73 |
if api_key and ELEVENLABS_CLIENT_IMPORTED and ElevenLabsAPIClient:
|
|
|
|
| 75 |
self.elevenlabs_client = ElevenLabsAPIClient(api_key=api_key)
|
| 76 |
if self.elevenlabs_client: self.USE_ELEVENLABS=True; logger.info("ElevenLabs Client Ready.")
|
| 77 |
else: self.USE_ELEVENLABS=False; logger.warning("ElevenLabs client is None post-init.")
|
| 78 |
+
except Exception as e: logger.error(f"Error init ElevenLabs client: {e}. Disabled.", exc_info=True); self.USE_ELEVENLABS=False; self.elevenlabs_client = None
|
| 79 |
+
else: self.USE_ELEVENLABS=False; self.elevenlabs_client = None
|
| 80 |
+
|
| 81 |
+
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.'}")
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 82 |
|
| 83 |
+
def _get_text_dimensions(self,text_content,font_obj): # Same
|
| 84 |
if not text_content: return 0,self.font_size_pil
|
| 85 |
try:
|
| 86 |
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 self.font_size_pil
|
|
|
|
| 88 |
else: return int(len(text_content)*self.font_size_pil*0.6),int(self.font_size_pil*1.2 if self.font_size_pil*1.2>0 else self.font_size_pil)
|
| 89 |
except: return int(len(text_content)*self.font_size_pil*0.6),int(self.font_size_pil*1.2)
|
| 90 |
|
| 91 |
+
def _create_placeholder_image_content(self,text_description,filename,size=None): # Same
|
| 92 |
if size is None: size = self.video_frame_size
|
| 93 |
img=Image.new('RGB',size,color=(20,20,40));d=ImageDraw.Draw(img);padding=25;max_w=size[0]-(2*padding);lines=[];
|
| 94 |
if not text_description: text_description="(Placeholder: No prompt text)"
|
|
|
|
| 111 |
try:img.save(filepath);return filepath
|
| 112 |
except Exception as e:logger.error(f"Saving placeholder image {filepath}: {e}", exc_info=True);return None
|
| 113 |
|
| 114 |
+
def _search_pexels_image(self, query, output_filename_base): # Same
|
| 115 |
if not self.USE_PEXELS or not self.pexels_api_key: return None
|
| 116 |
headers = {"Authorization": self.pexels_api_key}; params = {"query": query, "per_page": 1, "orientation": "landscape", "size": "large"}
|
| 117 |
pexels_filename = output_filename_base.replace(".png", f"_pexels_{random.randint(1000,9999)}.jpg")
|
|
|
|
| 130 |
except Exception as e: logger.error(f"Pexels search/download for query '{query}': {e}", exc_info=True)
|
| 131 |
return None
|
| 132 |
|
| 133 |
+
def generate_image_visual(self, image_prompt_text, scene_data, scene_identifier_filename): # Same
|
| 134 |
filepath = os.path.join(self.output_dir, scene_identifier_filename)
|
| 135 |
if self.USE_AI_IMAGE_GENERATION and self.openai_api_key:
|
| 136 |
max_retries = 2
|
|
|
|
| 168 |
|
| 169 |
audio_filepath = os.path.join(self.output_dir, output_filename)
|
| 170 |
try:
|
| 171 |
+
logger.info(f"Generating ElevenLabs audio (Voice ID: {self.elevenlabs_voice_id}) for: {text_to_narrate[:70]}...")
|
| 172 |
|
| 173 |
+
# Using client.text_to_speech.stream()
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 174 |
if hasattr(self.elevenlabs_client, 'text_to_speech') and hasattr(self.elevenlabs_client.text_to_speech, 'stream'):
|
| 175 |
logger.info("Using elevenlabs_client.text_to_speech.stream()")
|
| 176 |
+
# For text_to_speech.stream, voice_id must be a string. VoiceSettings are passed to client or model.
|
| 177 |
audio_data_iterator = self.elevenlabs_client.text_to_speech.stream(
|
| 178 |
text=text_to_narrate,
|
| 179 |
+
voice_id=str(self.elevenlabs_voice_id), # Ensure it's a string
|
| 180 |
+
model_id="eleven_multilingual_v2", # Or "eleven_monolingual_v1"
|
| 181 |
+
# voice_settings=self.elevenlabs_voice_settings # Pass settings if API supports it here
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 182 |
)
|
| 183 |
+
elif hasattr(self.elevenlabs_client, 'generate') and Voice and self.elevenlabs_voice_settings:
|
| 184 |
+
logger.info("Using elevenlabs_client.generate() with Voice object.")
|
| 185 |
+
voice_param = Voice(voice_id=self.elevenlabs_voice_id, settings=self.elevenlabs_voice_settings)
|
| 186 |
+
audio_data_iterator = self.elevenlabs_client.generate(
|
| 187 |
+
text=text_to_narrate, voice=voice_param, model="eleven_multilingual_v2")
|
| 188 |
else:
|
| 189 |
+
logger.error("No recognized audio generation method found on ElevenLabs client. Update logic or check SDK.")
|
| 190 |
return None
|
| 191 |
|
| 192 |
with open(audio_filepath, "wb") as f:
|
| 193 |
for chunk in audio_data_iterator:
|
| 194 |
if chunk: f.write(chunk)
|
|
|
|
| 195 |
logger.info(f"ElevenLabs audio saved: {audio_filepath}")
|
| 196 |
return audio_filepath
|
| 197 |
except AttributeError as ae:
|
| 198 |
+
logger.error(f"AttributeError with ElevenLabs client: {ae}. SDK method/structure might be different.", exc_info=True)
|
| 199 |
except Exception as e:
|
| 200 |
logger.error(f"Error generating ElevenLabs audio: {e}", exc_info=True)
|
| 201 |
return None
|
|
|
|
| 203 |
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):
|
| 204 |
if not image_data_list: logger.warning("No image data for video."); return None
|
| 205 |
processed_clips = []; narration_audio_clip = None; final_video_clip_obj = None
|
| 206 |
+
logger.info(f"Preparing {len(image_data_list)} clips. Target frame: {self.video_frame_size}. Duration/img: {duration_per_image}s.")
|
| 207 |
|
|
|
|
| 208 |
for i, data in enumerate(image_data_list):
|
| 209 |
img_path, scene_num, key_action = data.get('path'), data.get('scene_num', i+1), data.get('key_action', '')
|
| 210 |
+
if not (img_path and os.path.exists(img_path)): logger.warning(f"Img not found: {img_path}"); continue
|
| 211 |
try:
|
| 212 |
pil_img = Image.open(img_path)
|
| 213 |
if pil_img.mode != 'RGB': pil_img = pil_img.convert('RGB')
|
| 214 |
|
|
|
|
| 215 |
img_copy = pil_img.copy()
|
| 216 |
+
# Use modern Image.Resampling.LANCZOS
|
| 217 |
img_copy.thumbnail(self.video_frame_size, Image.Resampling.LANCZOS)
|
| 218 |
|
| 219 |
canvas = Image.new('RGB', self.video_frame_size, (random.randint(0,5), random.randint(0,5), random.randint(0,5)))
|
| 220 |
xo, yo = (self.video_frame_size[0]-img_copy.width)//2, (self.video_frame_size[1]-img_copy.height)//2
|
| 221 |
canvas.paste(img_copy, (xo,yo))
|
| 222 |
+
frame_np = np.array(canvas)
|
| 223 |
|
| 224 |
+
img_clip_base = ImageClip(frame_np).set_duration(duration_per_image)
|
| 225 |
+
|
| 226 |
+
# TEST: Remove Ken Burns effect to isolate ANTIALIAS error source
|
| 227 |
+
# end_scale = random.uniform(1.03, 1.08)
|
| 228 |
+
# img_clip = img_clip_base.fx(vfx.resize, lambda t: 1 + (end_scale - 1) * (t / duration_per_image))
|
| 229 |
+
# img_clip = img_clip.set_position('center')
|
| 230 |
+
img_clip = img_clip_base # Use base clip without resize effect for now
|
| 231 |
|
|
|
|
|
|
|
|
|
|
|
|
|
| 232 |
if key_action:
|
| 233 |
txt_clip = TextClip(f"Scene {scene_num}\n{key_action}", fontsize=self.video_overlay_font_size,
|
| 234 |
color=self.video_overlay_font_color, font=self.video_overlay_font,
|
| 235 |
bg_color='rgba(10,10,20,0.8)', method='caption', align='West',
|
| 236 |
size=(self.video_frame_size[0]*0.9, None), kerning=-1, stroke_color='black', stroke_width=1.5
|
| 237 |
).set_duration(duration_per_image - 1.0).set_start(0.5).set_position(('center', 0.92), relative=True)
|
| 238 |
+
final_scene_clip = CompositeVideoClip([img_clip, txt_clip], size=self.video_frame_size, use_bgclip=True, bg_color=(0,0,0))
|
| 239 |
else: final_scene_clip = img_clip
|
| 240 |
processed_clips.append(final_scene_clip)
|
| 241 |
except Exception as e: logger.error(f"Creating video clip for {img_path}: {e}", exc_info=True)
|
|
|
|
| 265 |
remove_temp=True, threads=os.cpu_count() or 2, logger='bar', bitrate="5000k")
|
| 266 |
logger.info(f"Video successfully created: {output_path}"); return output_path
|
| 267 |
except Exception as e: logger.error(f"Writing video file: {e}", exc_info=True); return None
|
| 268 |
+
finally:
|
| 269 |
for c_item in processed_clips:
|
| 270 |
if hasattr(c_item, 'close'): c_item.close()
|
| 271 |
if narration_audio_clip and hasattr(narration_audio_clip, 'close'): narration_audio_clip.close()
|