Update core/visual_engine.py
Browse files- core/visual_engine.py +118 -155
core/visual_engine.py
CHANGED
@@ -1,266 +1,229 @@
|
|
1 |
# core/visual_engine.py
|
2 |
-
|
|
|
3 |
from moviepy.editor import (ImageClip, concatenate_videoclips, TextClip,
|
4 |
CompositeVideoClip, AudioFileClip)
|
5 |
import moviepy.video.fx.all as vfx
|
6 |
import numpy as np
|
7 |
-
import os
|
8 |
-
import openai
|
9 |
-
import requests
|
10 |
-
import io
|
11 |
-
import time
|
12 |
-
import random
|
13 |
-
import subprocess
|
14 |
-
import logging
|
15 |
|
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
|
42 |
-
ElevenLabsAPIClient = ImportedElevenLabsClient
|
43 |
-
|
44 |
-
|
45 |
-
|
46 |
-
|
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 |
-
|
54 |
-
self.
|
55 |
-
|
|
|
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 |
-
|
61 |
-
|
62 |
-
|
63 |
-
self.elevenlabs_voice_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):
|
71 |
-
|
|
|
|
|
|
|
72 |
self.elevenlabs_api_key=api_key
|
|
|
|
|
|
|
|
|
73 |
if api_key and ELEVENLABS_CLIENT_IMPORTED and ElevenLabsAPIClient:
|
74 |
try:
|
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:
|
79 |
-
|
80 |
-
|
81 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
82 |
|
83 |
-
|
84 |
-
|
|
|
|
|
85 |
try:
|
86 |
-
if hasattr(
|
87 |
-
elif hasattr(
|
88 |
-
else: return int(len(
|
89 |
-
except: return int(len(
|
90 |
|
91 |
-
def _create_placeholder_image_content(self,
|
92 |
-
if
|
93 |
-
img=Image.new('RGB',
|
94 |
-
if not
|
95 |
-
|
96 |
-
for
|
97 |
-
|
98 |
-
if self._get_text_dimensions(
|
99 |
else:
|
100 |
-
if
|
101 |
-
if
|
102 |
-
if not
|
103 |
_,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
|
104 |
-
|
105 |
-
|
106 |
-
for i in range(
|
107 |
-
|
108 |
-
d.text((
|
109 |
-
if i==6 and
|
110 |
-
|
111 |
-
try:img.save(
|
112 |
-
except Exception as e:logger.error(f"Saving placeholder image {
|
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")
|
118 |
-
|
119 |
try:
|
120 |
-
logger.info(f"Searching Pexels for: '{query}'");
|
121 |
-
|
122 |
-
|
123 |
if data.get("photos") and len(data["photos"]) > 0:
|
124 |
-
|
125 |
-
|
126 |
-
|
127 |
-
if
|
128 |
-
|
129 |
-
else: logger.info(f"No photos
|
130 |
-
except Exception as e: logger.error(f"Pexels
|
131 |
return None
|
132 |
|
133 |
def generate_image_visual(self, image_prompt_text, scene_data, scene_identifier_filename): # Same
|
134 |
-
|
135 |
if self.USE_AI_IMAGE_GENERATION and self.openai_api_key:
|
136 |
-
|
137 |
-
for attempt in range(
|
138 |
try:
|
139 |
logger.info(f"Attempt {attempt+1}: DALL-E ({self.dalle_model}) for: {image_prompt_text[:100]}...")
|
140 |
client = openai.OpenAI(api_key=self.openai_api_key, timeout=90.0)
|
141 |
-
|
142 |
-
|
143 |
-
if
|
144 |
-
|
145 |
-
|
146 |
-
if
|
147 |
-
|
148 |
except openai.RateLimitError as e:
|
149 |
logger.warning(f"OpenAI Rate Limit: {e}. Retrying after {5*(attempt+1)}s..."); time.sleep(5 * (attempt + 1))
|
150 |
-
if attempt ==
|
151 |
else: continue
|
152 |
except openai.APIError as e: logger.error(f"OpenAI API Error: {e}"); break
|
153 |
except requests.exceptions.RequestException as e: logger.error(f"Requests Error (DALL-E download): {e}"); break
|
154 |
except Exception as e: logger.error(f"Generic error (DALL-E gen): {e}", exc_info=True); break
|
155 |
-
logger.warning("DALL-E
|
156 |
-
|
157 |
-
|
158 |
-
if
|
159 |
logger.warning("Pexels also failed/disabled. Using placeholder.")
|
160 |
return self._create_placeholder_image_content(f"[AI/Pexels Failed] {image_prompt_text[:100]}...", scene_identifier_filename)
|
161 |
else:
|
162 |
return self._create_placeholder_image_content(image_prompt_text, scene_identifier_filename)
|
163 |
|
164 |
-
def generate_narration_audio(self, text_to_narrate, output_filename="narration_overall.mp3"):
|
165 |
if not self.USE_ELEVENLABS or not self.elevenlabs_client or not text_to_narrate:
|
166 |
logger.info("ElevenLabs conditions not met. Skipping audio generation.")
|
167 |
return None
|
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
|
180 |
-
model_id="eleven_multilingual_v2",
|
181 |
-
# voice_settings=self.elevenlabs_voice_settings # Pass settings if API supports it here
|
182 |
)
|
183 |
-
elif hasattr(self.elevenlabs_client, 'generate') and Voice
|
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
|
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 |
-
|
199 |
-
except Exception as e:
|
200 |
-
logger.error(f"Error generating ElevenLabs audio: {e}", exc_info=True)
|
201 |
return None
|
202 |
|
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
|
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,
|
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 |
-
|
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 |
-
|
235 |
-
|
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)
|
242 |
-
|
243 |
if not processed_clips: logger.warning("No clips processed for video."); return None
|
244 |
-
|
245 |
transition = 0.75
|
246 |
try:
|
247 |
final_video_clip_obj = concatenate_videoclips(processed_clips, padding=-transition, method="compose")
|
248 |
-
if final_video_clip_obj.duration > transition*2:
|
249 |
-
final_video_clip_obj = final_video_clip_obj.fx(vfx.fadein, transition).fx(vfx.fadeout, transition)
|
250 |
-
|
251 |
if overall_narration_path and os.path.exists(overall_narration_path):
|
252 |
try:
|
253 |
narration_audio_clip = AudioFileClip(overall_narration_path)
|
254 |
-
if narration_audio_clip.duration < final_video_clip_obj.duration:
|
255 |
-
|
256 |
-
final_video_clip_obj = final_video_clip_obj.set_audio(narration_audio_clip)
|
257 |
-
logger.info("Overall narration added to video.")
|
258 |
except Exception as e: logger.error(f"Adding overall narration: {e}", exc_info=True)
|
259 |
-
|
260 |
-
output_path =
|
261 |
-
logger.info(f"Writing final video to: {output_path}")
|
262 |
-
final_video_clip_obj.write_videofile(output_path, fps=fps, codec='libx264', preset='medium',
|
263 |
-
audio_codec='aac',
|
264 |
temp_audiofile=os.path.join(self.output_dir, f'temp-audio-{os.urandom(4).hex()}.m4a'),
|
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
|
|
|
1 |
# core/visual_engine.py
|
2 |
+
# ... (imports remain the same as the last full version) ...
|
3 |
+
from PIL import Image, ImageDraw, ImageFont, ImageOps
|
4 |
from moviepy.editor import (ImageClip, concatenate_videoclips, TextClip,
|
5 |
CompositeVideoClip, AudioFileClip)
|
6 |
import moviepy.video.fx.all as vfx
|
7 |
import numpy as np
|
8 |
+
import os, openai, requests, io, time, random, subprocess, logging
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
9 |
|
10 |
logger = logging.getLogger(__name__)
|
11 |
logger.setLevel(logging.INFO)
|
12 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
13 |
ELEVENLABS_CLIENT_IMPORTED = False
|
14 |
+
ElevenLabsAPIClient = None; Voice = None; VoiceSettings = None
|
|
|
|
|
15 |
try:
|
16 |
from elevenlabs.client import ElevenLabs as ImportedElevenLabsClient
|
17 |
from elevenlabs import Voice as ImportedVoice, VoiceSettings as ImportedVoiceSettings
|
18 |
+
ElevenLabsAPIClient = ImportedElevenLabsClient; Voice = ImportedVoice; VoiceSettings = ImportedVoiceSettings
|
19 |
+
ELEVENLABS_CLIENT_IMPORTED = True; logger.info("Successfully imported ElevenLabs client components.")
|
20 |
+
except ImportError as e: logger.warning(f"ElevenLabs client import failed: {e}. Audio disabled.")
|
21 |
+
except Exception as e: logger.warning(f"General ElevenLabs import error: {e}. Audio disabled.")
|
22 |
+
|
|
|
|
|
23 |
|
24 |
class VisualEngine:
|
25 |
+
def __init__(self, output_dir="temp_cinegen_media", default_elevenlabs_voice_id="Rachel"): # Added default
|
26 |
self.output_dir = output_dir; os.makedirs(self.output_dir, exist_ok=True)
|
27 |
+
# ... (font setup, OpenAI, Pexels init - same as previous) ...
|
28 |
+
self.font_filename="arial.ttf"; self.font_path_in_container=f"/usr/local/share/fonts/truetype/mycustomfonts/{self.font_filename}"
|
29 |
+
self.font_size_pil=20; self.video_overlay_font_size=30; self.video_overlay_font_color='white'; self.video_overlay_font='Liberation-Sans-Bold'
|
30 |
+
try: self.font = ImageFont.truetype(self.font_path_in_container, self.font_size_pil); # logger.info(f"Placeholder font: {self.font_path_in_container}.")
|
31 |
except IOError: logger.warning(f"Placeholder font '{self.font_path_in_container}' fail. Default."); self.font = ImageFont.load_default(); self.font_size_pil = 10
|
32 |
|
33 |
self.openai_api_key = None; self.USE_AI_IMAGE_GENERATION = False
|
34 |
self.dalle_model = "dall-e-3"; self.image_size_dalle3 = "1792x1024"; self.video_frame_size = (1280, 720)
|
35 |
+
|
36 |
+
self.elevenlabs_api_key = None; self.USE_ELEVENLABS = False
|
37 |
+
self.elevenlabs_client = None
|
38 |
+
self.elevenlabs_voice_id = default_elevenlabs_voice_id # Use passed default or "Rachel"
|
39 |
if VoiceSettings and ELEVENLABS_CLIENT_IMPORTED:
|
40 |
self.elevenlabs_voice_settings = VoiceSettings(stability=0.60, similarity_boost=0.80, style=0.15, use_speaker_boost=True)
|
41 |
else: self.elevenlabs_voice_settings = None
|
42 |
self.pexels_api_key = None; self.USE_PEXELS = False
|
43 |
logger.info("VisualEngine initialized.")
|
44 |
|
45 |
+
def set_openai_api_key(self,k): # Same
|
46 |
+
self.openai_api_key=k; self.USE_AI_IMAGE_GENERATION=bool(k)
|
47 |
+
logger.info(f"DALL-E ({self.dalle_model}) {'Ready.' if k else 'Disabled.'}")
|
48 |
+
|
49 |
+
def set_elevenlabs_api_key(self, api_key, voice_id_from_secret=None): # Modified to accept voice_id
|
50 |
self.elevenlabs_api_key=api_key
|
51 |
+
if voice_id_from_secret: # Prioritize voice ID from secret if provided
|
52 |
+
self.elevenlabs_voice_id = voice_id_from_secret
|
53 |
+
logger.info(f"ElevenLabs Voice ID set from secret/config: {self.elevenlabs_voice_id}")
|
54 |
+
|
55 |
if api_key and ELEVENLABS_CLIENT_IMPORTED and ElevenLabsAPIClient:
|
56 |
try:
|
57 |
self.elevenlabs_client = ElevenLabsAPIClient(api_key=api_key)
|
58 |
+
if self.elevenlabs_client: self.USE_ELEVENLABS=True; logger.info(f"ElevenLabs Client Ready (Voice: {self.elevenlabs_voice_id}).")
|
59 |
else: self.USE_ELEVENLABS=False; logger.warning("ElevenLabs client is None post-init.")
|
60 |
+
except Exception as e:
|
61 |
+
logger.error(f"Error initializing ElevenLabs client: {e}. Disabled.", exc_info=True);
|
62 |
+
self.USE_ELEVENLABS=False; self.elevenlabs_client = None
|
63 |
+
else:
|
64 |
+
self.USE_ELEVENLABS=False; self.elevenlabs_client = None
|
65 |
+
if not (ELEVENLABS_CLIENT_IMPORTED and ElevenLabsAPIClient):pass
|
66 |
+
else: logger.info("ElevenLabs API Key not provided. Disabled.")
|
67 |
+
|
68 |
+
def set_pexels_api_key(self,k): # Same
|
69 |
+
self.pexels_api_key=k; self.USE_PEXELS=bool(k)
|
70 |
+
logger.info(f"Pexels Search {'Ready.' if k else 'Disabled.'}")
|
71 |
|
72 |
+
# _get_text_dimensions, _create_placeholder_image_content, _search_pexels_image, generate_image_visual
|
73 |
+
# remain the same as the last full version.
|
74 |
+
def _get_text_dimensions(self,t,f): # Same
|
75 |
+
if not t: return 0,self.font_size_pil
|
76 |
try:
|
77 |
+
if hasattr(f,'getbbox'): bb=f.getbbox(t);w=bb[2]-bb[0];h=bb[3]-bb[1];return w, h if h > 0 else self.font_size_pil
|
78 |
+
elif hasattr(f,'getsize'): w,h=f.getsize(t);return w, h if h > 0 else self.font_size_pil
|
79 |
+
else: return int(len(t)*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)
|
80 |
+
except: return int(len(t)*self.font_size_pil*0.6),int(self.font_size_pil*1.2)
|
81 |
|
82 |
+
def _create_placeholder_image_content(self,td,fn,s=None): # Same
|
83 |
+
if s is None: s = self.video_frame_size
|
84 |
+
img=Image.new('RGB',s,color=(20,20,40));d=ImageDraw.Draw(img);p=25;max_w=s[0]-(2*p);ls=[];
|
85 |
+
if not td: td="(Placeholder: No prompt text)"
|
86 |
+
ws=td.split();cl=""
|
87 |
+
for w in ws:
|
88 |
+
tl=cl+w+" ";
|
89 |
+
if self._get_text_dimensions(tl,self.font)[0] <= max_w: cl=tl
|
90 |
else:
|
91 |
+
if cl: ls.append(cl.strip()); cl=w+" "
|
92 |
+
if cl: ls.append(cl.strip())
|
93 |
+
if not ls: ls.append("(Text error or too long for placeholder)")
|
94 |
_,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
|
95 |
+
max_ls=min(len(ls),(s[1]-(2*p))//(single_line_h+2))
|
96 |
+
yt=p + (s[1]-(2*p) - max_ls*(single_line_h+2))/2.0
|
97 |
+
for i in range(max_ls):
|
98 |
+
line=ls[i];line_w,_=self._get_text_dimensions(line,self.font);xt=(s[0]-line_w)/2.0
|
99 |
+
d.text((xt,yt),line,font=self.font,fill=(200,200,180));yt+=single_line_h+2
|
100 |
+
if i==6 and max_ls > 7: d.text((xt,yt),"...",font=self.font,fill=(200,200,180));break
|
101 |
+
fp=os.path.join(self.output_dir,fn);
|
102 |
+
try:img.save(fp);return fp
|
103 |
+
except Exception as e:logger.error(f"Saving placeholder image {fp}: {e}", exc_info=True);return None
|
104 |
|
105 |
def _search_pexels_image(self, query, output_filename_base): # Same
|
106 |
if not self.USE_PEXELS or not self.pexels_api_key: return None
|
107 |
headers = {"Authorization": self.pexels_api_key}; params = {"query": query, "per_page": 1, "orientation": "landscape", "size": "large"}
|
108 |
pexels_filename = output_filename_base.replace(".png", f"_pexels_{random.randint(1000,9999)}.jpg")
|
109 |
+
fp = os.path.join(self.output_dir, pexels_filename)
|
110 |
try:
|
111 |
+
logger.info(f"Searching Pexels for: '{query}'"); eff_q = " ".join(query.split()[:5]); params["query"] = eff_q
|
112 |
+
r = requests.get("https://api.pexels.com/v1/search", headers=headers, params=params, timeout=20)
|
113 |
+
r.raise_for_status(); data = r.json()
|
114 |
if data.get("photos") and len(data["photos"]) > 0:
|
115 |
+
url = data["photos"][0]["src"]["large2x"]
|
116 |
+
img_r = requests.get(url, timeout=60); img_r.raise_for_status()
|
117 |
+
img_d = Image.open(io.BytesIO(img_r.content))
|
118 |
+
if img_d.mode != 'RGB': img_d = img_d.convert('RGB')
|
119 |
+
img_d.save(fp); logger.info(f"Pexels image saved: {fp}"); return fp
|
120 |
+
else: logger.info(f"No photos on Pexels for: '{eff_q}'")
|
121 |
+
except Exception as e: logger.error(f"Pexels error for '{query}': {e}", exc_info=True)
|
122 |
return None
|
123 |
|
124 |
def generate_image_visual(self, image_prompt_text, scene_data, scene_identifier_filename): # Same
|
125 |
+
fp = os.path.join(self.output_dir, scene_identifier_filename)
|
126 |
if self.USE_AI_IMAGE_GENERATION and self.openai_api_key:
|
127 |
+
retries = 2
|
128 |
+
for attempt in range(retries):
|
129 |
try:
|
130 |
logger.info(f"Attempt {attempt+1}: DALL-E ({self.dalle_model}) for: {image_prompt_text[:100]}...")
|
131 |
client = openai.OpenAI(api_key=self.openai_api_key, timeout=90.0)
|
132 |
+
resp = 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")
|
133 |
+
img_url = resp.data[0].url; rev_prompt = getattr(resp.data[0], 'revised_prompt', None)
|
134 |
+
if rev_prompt: logger.info(f"DALL-E 3 revised_prompt: {rev_prompt[:100]}...")
|
135 |
+
img_resp = requests.get(img_url, timeout=120); img_resp.raise_for_status()
|
136 |
+
img_d = Image.open(io.BytesIO(img_resp.content));
|
137 |
+
if img_d.mode != 'RGB': img_d = img_d.convert('RGB')
|
138 |
+
img_d.save(fp); logger.info(f"AI Image (DALL-E) saved: {fp}"); return fp
|
139 |
except openai.RateLimitError as e:
|
140 |
logger.warning(f"OpenAI Rate Limit: {e}. Retrying after {5*(attempt+1)}s..."); time.sleep(5 * (attempt + 1))
|
141 |
+
if attempt == retries - 1: logger.error("Max retries for RateLimitError."); break
|
142 |
else: continue
|
143 |
except openai.APIError as e: logger.error(f"OpenAI API Error: {e}"); break
|
144 |
except requests.exceptions.RequestException as e: logger.error(f"Requests Error (DALL-E download): {e}"); break
|
145 |
except Exception as e: logger.error(f"Generic error (DALL-E gen): {e}", exc_info=True); break
|
146 |
+
logger.warning("DALL-E failed. Trying Pexels fallback...")
|
147 |
+
pexels_q_text = scene_data.get('pexels_search_query_감독', f"{scene_data.get('emotional_beat','')} {scene_data.get('setting_description','')}")
|
148 |
+
pexels_p = self._search_pexels_image(pexels_q_text, scene_identifier_filename)
|
149 |
+
if pexels_p: return pexels_p
|
150 |
logger.warning("Pexels also failed/disabled. Using placeholder.")
|
151 |
return self._create_placeholder_image_content(f"[AI/Pexels Failed] {image_prompt_text[:100]}...", scene_identifier_filename)
|
152 |
else:
|
153 |
return self._create_placeholder_image_content(image_prompt_text, scene_identifier_filename)
|
154 |
|
155 |
+
def generate_narration_audio(self, text_to_narrate, output_filename="narration_overall.mp3"): # Uses self.elevenlabs_voice_id
|
156 |
if not self.USE_ELEVENLABS or not self.elevenlabs_client or not text_to_narrate:
|
157 |
logger.info("ElevenLabs conditions not met. Skipping audio generation.")
|
158 |
return None
|
159 |
|
160 |
audio_filepath = os.path.join(self.output_dir, output_filename)
|
161 |
try:
|
162 |
+
# self.elevenlabs_voice_id is now set during set_elevenlabs_api_key or by UI
|
163 |
logger.info(f"Generating ElevenLabs audio (Voice ID: {self.elevenlabs_voice_id}) for: {text_to_narrate[:70]}...")
|
164 |
|
|
|
165 |
if hasattr(self.elevenlabs_client, 'text_to_speech') and hasattr(self.elevenlabs_client.text_to_speech, 'stream'):
|
166 |
logger.info("Using elevenlabs_client.text_to_speech.stream()")
|
|
|
167 |
audio_data_iterator = self.elevenlabs_client.text_to_speech.stream(
|
168 |
text=text_to_narrate,
|
169 |
+
voice_id=str(self.elevenlabs_voice_id), # Ensure voice_id is a string
|
170 |
+
model_id="eleven_multilingual_v2",
|
|
|
171 |
)
|
172 |
+
elif hasattr(self.elevenlabs_client, 'generate') and Voice: # Fallback, ensure Voice is imported
|
173 |
logger.info("Using elevenlabs_client.generate() with Voice object.")
|
174 |
+
voice_param = Voice(voice_id=str(self.elevenlabs_voice_id), settings=self.elevenlabs_voice_settings if self.elevenlabs_voice_settings else None)
|
175 |
audio_data_iterator = self.elevenlabs_client.generate(
|
176 |
text=text_to_narrate, voice=voice_param, model="eleven_multilingual_v2")
|
177 |
else:
|
178 |
+
logger.error("No recognized audio generation method on ElevenLabs client."); return None
|
|
|
179 |
|
180 |
with open(audio_filepath, "wb") as f:
|
181 |
for chunk in audio_data_iterator:
|
182 |
if chunk: f.write(chunk)
|
183 |
logger.info(f"ElevenLabs audio saved: {audio_filepath}")
|
184 |
return audio_filepath
|
185 |
+
except AttributeError as ae: logger.error(f"AttributeError with ElevenLabs client: {ae}.", exc_info=True)
|
186 |
+
except Exception as e: logger.error(f"Error generating ElevenLabs audio: {e}", exc_info=True)
|
|
|
|
|
187 |
return None
|
188 |
|
189 |
+
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): # Same as previous
|
190 |
if not image_data_list: logger.warning("No image data for video."); return None
|
191 |
+
processed_clips=[]; narration_audio_clip=None; final_video_clip_obj=None
|
192 |
logger.info(f"Preparing {len(image_data_list)} clips. Target frame: {self.video_frame_size}. Duration/img: {duration_per_image}s.")
|
|
|
193 |
for i, data in enumerate(image_data_list):
|
194 |
img_path, scene_num, key_action = data.get('path'), data.get('scene_num', i+1), data.get('key_action', '')
|
195 |
if not (img_path and os.path.exists(img_path)): logger.warning(f"Img not found: {img_path}"); continue
|
196 |
try:
|
197 |
+
pil_img = Image.open(img_path);
|
198 |
if pil_img.mode != 'RGB': pil_img = pil_img.convert('RGB')
|
199 |
+
img_copy = pil_img.copy(); img_copy.thumbnail(self.video_frame_size, Image.Resampling.LANCZOS)
|
|
|
|
|
|
|
|
|
200 |
canvas = Image.new('RGB', self.video_frame_size, (random.randint(0,5), random.randint(0,5), random.randint(0,5)))
|
201 |
+
xo,yo=(self.video_frame_size[0]-img_copy.width)//2, (self.video_frame_size[1]-img_copy.height)//2
|
202 |
+
canvas.paste(img_copy, (xo,yo)); frame_np = np.array(canvas)
|
|
|
|
|
203 |
img_clip_base = ImageClip(frame_np).set_duration(duration_per_image)
|
204 |
+
# img_clip = img_clip_base # Test: No Ken Burns if ANTIALIAS error persists
|
205 |
+
end_scale = random.uniform(1.03, 1.08); img_clip = img_clip_base.fx(vfx.resize, lambda t: 1+(end_scale-1)*(t/duration_per_image)); img_clip = img_clip.set_position('center')
|
|
|
|
|
|
|
|
|
|
|
206 |
if key_action:
|
207 |
+
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,
|
208 |
+
bg_color='rgba(10,10,20,0.8)', method='caption', align='West', size=(self.video_frame_size[0]*0.9, None), kerning=-1, stroke_color='black', stroke_width=1.5
|
209 |
+
).set_duration(duration_per_image-1.0).set_start(0.5).set_position(('center',0.92),relative=True)
|
|
|
|
|
210 |
final_scene_clip = CompositeVideoClip([img_clip, txt_clip], size=self.video_frame_size, use_bgclip=True, bg_color=(0,0,0))
|
211 |
else: final_scene_clip = img_clip
|
212 |
processed_clips.append(final_scene_clip)
|
213 |
except Exception as e: logger.error(f"Creating video clip for {img_path}: {e}", exc_info=True)
|
|
|
214 |
if not processed_clips: logger.warning("No clips processed for video."); return None
|
|
|
215 |
transition = 0.75
|
216 |
try:
|
217 |
final_video_clip_obj = concatenate_videoclips(processed_clips, padding=-transition, method="compose")
|
218 |
+
if final_video_clip_obj.duration > transition*2: final_video_clip_obj = final_video_clip_obj.fx(vfx.fadein, transition).fx(vfx.fadeout, transition)
|
|
|
|
|
219 |
if overall_narration_path and os.path.exists(overall_narration_path):
|
220 |
try:
|
221 |
narration_audio_clip = AudioFileClip(overall_narration_path)
|
222 |
+
if narration_audio_clip.duration < final_video_clip_obj.duration: final_video_clip_obj = final_video_clip_obj.subclip(0, narration_audio_clip.duration)
|
223 |
+
final_video_clip_obj = final_video_clip_obj.set_audio(narration_audio_clip); logger.info("Overall narration added.")
|
|
|
|
|
224 |
except Exception as e: logger.error(f"Adding overall narration: {e}", exc_info=True)
|
225 |
+
output_path = os.path.join(self.output_dir, output_filename); logger.info(f"Writing final video to: {output_path}")
|
226 |
+
final_video_clip_obj.write_videofile(output_path, fps=fps, codec='libx264', preset='medium', audio_codec='aac',
|
|
|
|
|
|
|
227 |
temp_audiofile=os.path.join(self.output_dir, f'temp-audio-{os.urandom(4).hex()}.m4a'),
|
228 |
remove_temp=True, threads=os.cpu_count() or 2, logger='bar', bitrate="5000k")
|
229 |
logger.info(f"Video successfully created: {output_path}"); return output_path
|