File size: 38,328 Bytes
e22eb13
e0b9b11
4da81e5
e22eb13
990e23e
92cb699
 
 
 
 
5089920
92cb699
200c5c4
e22eb13
3084a6c
 
e22eb13
f13d4b2
e22eb13
a219e07
3084a6c
 
 
 
 
 
e22eb13
3084a6c
e22eb13
 
3084a6c
e22eb13
 
a219e07
 
 
 
f13d4b2
5089920
f13d4b2
a219e07
 
 
 
e22eb13
 
3084a6c
e22eb13
3084a6c
5089920
a219e07
3084a6c
5089920
3084a6c
cb93f9c
 
 
 
3084a6c
e22eb13
3084a6c
4c2220b
f13d4b2
287c9ca
3084a6c
 
e22eb13
3084a6c
 
 
e22eb13
3084a6c
e0b9b11
 
3084a6c
 
 
 
e22eb13
3084a6c
 
 
 
d44d308
3084a6c
 
 
 
 
 
 
 
200c5c4
09d5c67
3084a6c
a219e07
 
3084a6c
d44d308
3084a6c
 
 
 
e22eb13
3084a6c
e22eb13
cb93f9c
3084a6c
cb93f9c
e22eb13
3084a6c
 
 
 
 
 
 
cb93f9c
 
3084a6c
 
 
 
 
 
 
 
cb93f9c
 
3084a6c
 
 
 
d44d308
e22eb13
3084a6c
 
 
d44d308
3084a6c
 
 
 
 
 
 
 
 
 
 
 
d44d308
e22eb13
 
 
3084a6c
e22eb13
3084a6c
4da81e5
3084a6c
 
 
e22eb13
d44d308
3084a6c
e22eb13
3084a6c
 
e22eb13
3084a6c
 
 
 
e22eb13
 
3084a6c
 
e22eb13
3084a6c
 
e22eb13
 
3084a6c
 
a219e07
3084a6c
 
cb93f9c
4da81e5
3084a6c
 
4da81e5
 
e22eb13
 
4da81e5
 
e22eb13
4da81e5
 
3084a6c
4da81e5
 
 
e22eb13
 
3084a6c
 
e22eb13
3084a6c
 
 
 
 
 
 
 
 
 
cb93f9c
3084a6c
 
 
 
cb93f9c
3084a6c
cb93f9c
3084a6c
 
 
 
 
e22eb13
3084a6c
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
5089920
3084a6c
e22eb13
3084a6c
 
 
 
5089920
3084a6c
 
 
cb93f9c
 
 
3084a6c
4da81e5
3084a6c
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
d73d823
4da81e5
3084a6c
d73d823
3084a6c
 
 
 
4da81e5
cb93f9c
e0b9b11
3084a6c
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
cb93f9c
3084a6c
 
 
 
 
 
 
8583908
3084a6c
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
3313da9
3084a6c
 
 
 
cb93f9c
3084a6c
 
 
 
 
59af6e7
3084a6c
 
 
 
59af6e7
3084a6c
 
 
 
 
 
 
 
 
cb93f9c
3084a6c
 
 
a219e07
3084a6c
 
b97795f
3084a6c
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
754c854
3313da9
3084a6c
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
# core/visual_engine.py
from PIL import Image, ImageDraw, ImageFont, ImageOps
import base64
import mimetypes
import numpy as np
import os
import openai
import requests
import io
import time
import random
import logging

# --- MoviePy Imports ---
from moviepy.editor import (ImageClip, VideoFileClip, concatenate_videoclips, TextClip,
                            CompositeVideoClip, AudioFileClip)
import moviepy.video.fx.all as vfx

# --- MONKEY PATCH for Pillow/MoviePy compatibility ---
try:
    if hasattr(Image, 'Resampling') and hasattr(Image.Resampling, 'LANCZOS'): # Pillow 9+
        if not hasattr(Image, 'ANTIALIAS'): Image.ANTIALIAS = Image.Resampling.LANCZOS
    elif hasattr(Image, 'LANCZOS'): # Pillow 8
         if not hasattr(Image, 'ANTIALIAS'): Image.ANTIALIAS = Image.LANCZOS
    elif not hasattr(Image, 'ANTIALIAS'):
             print("WARNING: Pillow version lacks common Resampling attributes or ANTIALIAS. MoviePy effects might fail or look different.")
except Exception as e_monkey_patch:
    print(f"WARNING: An unexpected error occurred during Pillow ANTIALIAS monkey-patch: {e_monkey_patch}")

logger = logging.getLogger(__name__)
# logger.setLevel(logging.DEBUG) # Uncomment for very verbose debugging

# --- External Service Client Imports ---
ELEVENLABS_CLIENT_IMPORTED = False
ElevenLabsAPIClient = None
Voice = None
VoiceSettings = None
try:
    from elevenlabs.client import ElevenLabs as ImportedElevenLabsClient
    from elevenlabs import Voice as ImportedVoice, VoiceSettings as ImportedVoiceSettings
    ElevenLabsAPIClient = ImportedElevenLabsClient
    Voice = ImportedVoice
    VoiceSettings = ImportedVoiceSettings
    ELEVENLABS_CLIENT_IMPORTED = True
    logger.info("ElevenLabs client components imported successfully.")
except ImportError:
    logger.warning("ElevenLabs SDK not found (pip install elevenlabs). Audio generation will be disabled.")
except Exception as e_eleven_import:
    logger.warning(f"Error importing ElevenLabs client components: {e_eleven_import}. Audio generation disabled.")

RUNWAYML_SDK_IMPORTED = False
RunwayMLAPIClient = None
try:
    from runwayml import RunwayML as ImportedRunwayMLClient
    RunwayMLAPIClient = ImportedRunwayMLClient
    RUNWAYML_SDK_IMPORTED = True
    logger.info("RunwayML SDK imported successfully.")
except ImportError:
    logger.warning("RunwayML SDK not found (pip install runwayml). RunwayML video generation will be disabled.")
except Exception as e_runway_sdk_import:
    logger.warning(f"Error importing RunwayML SDK: {e_runway_sdk_import}. RunwayML features disabled.")


class VisualEngine:
    DEFAULT_FONT_SIZE_PIL = 10
    PREFERRED_FONT_SIZE_PIL = 20
    VIDEO_OVERLAY_FONT_SIZE = 30
    VIDEO_OVERLAY_FONT_COLOR = 'white'
    DEFAULT_MOVIEPY_FONT = 'DejaVu-Sans-Bold'
    PREFERRED_MOVIEPY_FONT = 'Liberation-Sans-Bold'

    def __init__(self, output_dir="temp_cinegen_media", default_elevenlabs_voice_id="Rachel"):
        self.output_dir = output_dir
        os.makedirs(self.output_dir, exist_ok=True)
        self.font_filename_pil = "DejaVuSans-Bold.ttf"
        font_paths_to_try = [ self.font_filename_pil, f"/usr/share/fonts/truetype/dejavu/{self.font_filename_pil}", f"/usr/share/fonts/truetype/liberation/LiberationSans-Bold.ttf", f"/System/Library/Fonts/Supplemental/Arial.ttf", f"C:/Windows/Fonts/arial.ttf", f"/usr/local/share/fonts/truetype/mycustomfonts/arial.ttf"]
        self.font_path_pil_resolved = next((p for p in font_paths_to_try if os.path.exists(p)), None)
        self.font_pil = ImageFont.load_default(); self.current_font_size_pil = self.DEFAULT_FONT_SIZE_PIL
        if self.font_path_pil_resolved:
            try: self.font_pil = ImageFont.truetype(self.font_path_pil_resolved, self.PREFERRED_FONT_SIZE_PIL); self.current_font_size_pil = self.PREFERRED_FONT_SIZE_PIL; logger.info(f"Pillow font: {self.font_path_pil_resolved} sz {self.current_font_size_pil}."); self.video_overlay_font = 'DejaVu-Sans-Bold' if "dejavu" in self.font_path_pil_resolved.lower() else ('Liberation-Sans-Bold' if "liberation" in self.font_path_pil_resolved.lower() else self.DEFAULT_MOVIEPY_FONT)
            except IOError as e_font_load: logger.error(f"Pillow font IOError '{self.font_path_pil_resolved}': {e_font_load}. Default.")
        else: logger.warning("Custom Pillow font not found. Default.")
        self.openai_api_key = None; self.USE_AI_IMAGE_GENERATION = False; self.dalle_model = "dall-e-3"; self.image_size_dalle3 = "1792x1024"
        self.video_frame_size = (1280, 720)
        self.elevenlabs_api_key = None; self.USE_ELEVENLABS = False; self.elevenlabs_client = None; self.elevenlabs_voice_id = default_elevenlabs_voice_id
        if VoiceSettings and ELEVENLABS_CLIENT_IMPORTED: self.elevenlabs_voice_settings = VoiceSettings(stability=0.60, similarity_boost=0.80, style=0.15, use_speaker_boost=True)
        else: self.elevenlabs_voice_settings = None
        self.pexels_api_key = None; self.USE_PEXELS = False
        self.runway_api_key = None; self.USE_RUNWAYML = False; self.runway_ml_client_instance = None
        if RUNWAYML_SDK_IMPORTED and RunwayMLAPIClient and os.getenv("RUNWAYML_API_SECRET"):
            try: self.runway_ml_client_instance = RunwayMLAPIClient(); self.USE_RUNWAYML = True; logger.info("RunwayML Client init from env var at startup.")
            except Exception as e_runway_init_startup: logger.error(f"Initial RunwayML client init failed: {e_runway_init_startup}"); self.USE_RUNWAYML = False
        logger.info("VisualEngine initialized.")

    def set_openai_api_key(self, api_key): self.openai_api_key = api_key; self.USE_AI_IMAGE_GENERATION = bool(api_key); logger.info(f"DALL-E status: {'Ready' if self.USE_AI_IMAGE_GENERATION else 'Disabled'}")
    def set_elevenlabs_api_key(self, api_key, voice_id_from_secret=None):
        self.elevenlabs_api_key = api_key
        if voice_id_from_secret: self.elevenlabs_voice_id = voice_id_from_secret
        if api_key and ELEVENLABS_CLIENT_IMPORTED and ElevenLabsAPIClient:
            try: self.elevenlabs_client = ElevenLabsAPIClient(api_key=api_key); self.USE_ELEVENLABS = bool(self.elevenlabs_client); logger.info(f"11L Client: {'Ready' if self.USE_ELEVENLABS else 'Failed'} (Voice: {self.elevenlabs_voice_id})")
            except Exception as e: logger.error(f"11L client init error: {e}. Disabled.", exc_info=True); self.USE_ELEVENLABS=False; self.elevenlabs_client=None
        else: self.USE_ELEVENLABS = False; logger.info(f"11L Disabled (key/SDK).")
    def set_pexels_api_key(self, api_key): self.pexels_api_key = api_key; self.USE_PEXELS = bool(api_key); logger.info(f"Pexels status: {'Ready' if self.USE_PEXELS else 'Disabled'}")
    def set_runway_api_key(self, api_key):
        self.runway_api_key = api_key
        if api_key:
            if RUNWAYML_SDK_IMPORTED and RunwayMLAPIClient:
                if not self.runway_ml_client_instance:
                    try:
                        original_env_secret = os.getenv("RUNWAYML_API_SECRET")
                        if not original_env_secret: os.environ["RUNWAYML_API_SECRET"] = api_key; logger.info("Temp set RUNWAYML_API_SECRET for SDK.")
                        self.runway_ml_client_instance = RunwayMLAPIClient(); self.USE_RUNWAYML = True; logger.info("RunwayML Client init via set_runway_api_key.")
                        if not original_env_secret: del os.environ["RUNWAYML_API_SECRET"]; logger.info("Cleared temp RUNWAYML_API_SECRET.")
                    except Exception as e: logger.error(f"RunwayML Client init in set_runway_api_key fail: {e}", exc_info=True); self.USE_RUNWAYML=False;self.runway_ml_client_instance=None
                else: self.USE_RUNWAYML = True; logger.info("RunwayML Client already init.")
            else: logger.warning("RunwayML SDK not imported. Service disabled."); self.USE_RUNWAYML = False
        else: self.USE_RUNWAYML = False; self.runway_ml_client_instance = None; logger.info("RunwayML Disabled (no API key).")

    def _image_to_data_uri(self, image_path):
        # (Implementation from before)
        try: mime_type,_=mimetypes.guess_type(image_path)
        if not mime_type:ext=os.path.splitext(image_path)[1].lower();mime_map={".png":"image/png",".jpg":"image/jpeg",".jpeg":"image/jpeg"};mime_type=mime_map.get(ext,"application/octet-stream");
        if mime_type=="application/octet-stream":logger.warning(f"Unknown MIME for {image_path}, using {mime_type}.")
        with open(image_path,"rb")as image_file:encoded_string=base64.b64encode(image_file.read()).decode('utf-8')
        data_uri=f"data:{mime_type};base64,{encoded_string}";logger.debug(f"Data URI for {os.path.basename(image_path)} (start): {data_uri[:100]}...");return data_uri
        except FileNotFoundError:logger.error(f"Img not found {image_path} for data URI.");return None
        except Exception as e:logger.error(f"Error converting {image_path} to data URI:{e}",exc_info=True);return None

    def _map_resolution_to_runway_ratio(self, width, height):
        # (Implementation from before)
        ratio_str=f"{width}:{height}";supported_ratios_gen4=["1280:720","720:1280","1104:832","832:1104","960:960","1584:672"];
        if ratio_str in supported_ratios_gen4:return ratio_str
        logger.warning(f"Res {ratio_str} not in Gen-4 list. Default 1280:720.");return "1280:720"

    def _get_text_dimensions(self, text_content, font_object):
        # (Implementation from before)
        dch=getattr(font_object,'size',self.current_font_size_pil);
        if not text_content:return 0,dch
        try:
            if hasattr(font_object,'getbbox'):bb=font_object.getbbox(text_content);w=bb[2]-bb[0];h=bb[3]-bb[1];return w,h if h>0 else dch
            elif hasattr(font_object,'getsize'):w,h=font_object.getsize(text_content);return w,h if h>0 else dch
            else:return int(len(text_content)*dch*0.6),int(dch*1.2)
        except Exception as e:logger.warning(f"Error in _get_text_dimensions:{e}");return int(len(text_content)*self.current_font_size_pil*0.6),int(self.current_font_size_pil*1.2)

    def _create_placeholder_image_content(self,text_description,filename,size=None):
        # <<< CORRECTED VERSION OF THIS METHOD >>>
        if size is None: size = self.video_frame_size
        img = Image.new('RGB', size, color=(20, 20, 40)); d = ImageDraw.Draw(img); padding = 25
        max_w = size[0] - (2 * padding); lines = []
        if not text_description: text_description = "(Placeholder Image)"
        words = text_description.split(); current_line_text = ""
        for word_idx, word in enumerate(words):
            prospective_addition = word + (" " if word_idx < len(words) - 1 else "")
            test_line_text = current_line_text + prospective_addition
            current_w, _ = self._get_text_dimensions(test_line_text, self.font_pil)
            if current_w == 0 and test_line_text.strip(): current_w = len(test_line_text) * (self.current_font_size_pil * 0.6)

            if current_w <= max_w: current_line_text = test_line_text
            else:
                if current_line_text.strip(): lines.append(current_line_text.strip())
                current_line_text = prospective_addition
        if current_line_text.strip(): lines.append(current_line_text.strip())

        if not lines and text_description:
            avg_char_w, _ = self._get_text_dimensions("W", self.font_pil); avg_char_w = avg_char_w or (self.current_font_size_pil * 0.6)
            chars_per_line = int(max_w / avg_char_w) if avg_char_w > 0 else 20
            lines.append(text_description[:chars_per_line] + ("..." if len(text_description) > chars_per_line else ""))
        elif not lines: lines.append("(Placeholder Error)")

        _, single_line_h = self._get_text_dimensions("Ay", self.font_pil); single_line_h = single_line_h if single_line_h > 0 else self.current_font_size_pil + 2
        max_lines = min(len(lines), (size[1] - (2 * padding)) // (single_line_h + 2)) if single_line_h > 0 else 1
        max_lines = max(1, max_lines)
        
        y_pos = padding + (size[1] - (2 * padding) - max_lines * (single_line_h + 2)) / 2.0
        for i in range(max_lines):
            line_text = lines[i]; line_w, _ = self._get_text_dimensions(line_text, self.font_pil)
            if line_w == 0 and line_text.strip(): line_w = len(line_text) * (self.current_font_size_pil * 0.6)
            x_pos = (size[0] - line_w) / 2.0
            try: d.text((x_pos, y_pos), line_text, font=self.font_pil, fill=(200, 200, 180))
            except Exception as e_draw: logger.error(f"Pillow d.text error: {e_draw} for '{line_text}'")
            y_pos += single_line_h + 2
            if i == 6 and max_lines > 7:
                try: d.text((x_pos, y_pos), "...", font=self.font_pil, fill=(200, 200, 180))
                except Exception as e_elip: logger.error(f"Pillow d.text ellipsis error: {e_elip}"); break
        filepath = os.path.join(self.output_dir, filename)
        try: img.save(filepath); return filepath
        except Exception as e_save: logger.error(f"Saving placeholder image '{filepath}' error: {e_save}", exc_info=True); return None

    def _search_pexels_image(self, query, output_filename_base):
        # <<< CORRECTED VERSION OF THIS METHOD >>>
        if not self.USE_PEXELS or not self.pexels_api_key: return None
        headers = {"Authorization": self.pexels_api_key}
        params = {"query": query, "per_page": 1, "orientation": "landscape", "size": "large2x"}
        base_name_for_pexels, _ = os.path.splitext(output_filename_base)
        pexels_filename = base_name_for_pexels + f"_pexels_{random.randint(1000,9999)}.jpg"
        filepath = os.path.join(self.output_dir, pexels_filename)
        try:
            logger.info(f"Pexels: Searching for '{query}'")
            effective_query = " ".join(query.split()[:5])
            params["query"] = effective_query
            response = requests.get("https://api.pexels.com/v1/search", headers=headers, params=params, timeout=20)
            response.raise_for_status()
            data = response.json()
            if data.get("photos") and len(data["photos"]) > 0:
                photo_details = data["photos"][0]
                photo_url = photo_details.get("src", {}).get("large2x")
                if not photo_url: logger.warning(f"Pexels: 'large2x' URL missing for '{effective_query}'. Details: {photo_details}"); return None
                image_response = requests.get(photo_url, timeout=60); image_response.raise_for_status()
                img_data_pil = Image.open(io.BytesIO(image_response.content))
                if img_data_pil.mode != 'RGB': img_data_pil = img_data_pil.convert('RGB')
                img_data_pil.save(filepath); logger.info(f"Pexels: Image saved to {filepath}"); return filepath
            else: logger.info(f"Pexels: No photos for '{effective_query}'."); return None
        except requests.exceptions.RequestException as e_req: logger.error(f"Pexels: RequestException for '{query}': {e_req}", exc_info=False); return None
        except Exception as e: logger.error(f"Pexels: General error for '{query}': {e}", exc_info=True); return None

    def _generate_video_clip_with_runwayml(self, text_prompt_for_motion, input_image_path, scene_identifier_filename_base, target_duration_seconds=5):
        # (Implementation from previous response, with Runway SDK calls)
        if not self.USE_RUNWAYML or not self.runway_ml_client_instance: logger.warning("RunwayML not enabled/client not init. Skip video."); return None
        if not input_image_path or not os.path.exists(input_image_path): logger.error(f"Runway Gen-4 needs input image. Path invalid: {input_image_path}"); return None
        image_data_uri = self._image_to_data_uri(input_image_path)
        if not image_data_uri: return None
        runway_duration = 10 if target_duration_seconds >= 8 else 5
        runway_ratio_str = self._map_resolution_to_runway_ratio(self.video_frame_size[0], self.video_frame_size[1])
        base_name_runway, _ = os.path.splitext(scene_identifier_filename_base); output_video_filename = base_name_runway + f"_runway_gen4_d{runway_duration}s.mp4" # Corrected base name usage
        output_video_filepath = os.path.join(self.output_dir, output_video_filename)
        logger.info(f"Runway Gen-4 task: motion='{text_prompt_for_motion[:100]}...', img='{os.path.basename(input_image_path)}', dur={runway_duration}s, ratio='{runway_ratio_str}'")
        try:
            task_submission = self.runway_ml_client_instance.image_to_video.create(model='gen4_turbo', prompt_image=image_data_uri, prompt_text=text_prompt_for_motion, duration=runway_duration, ratio=runway_ratio_str)
            task_id = task_submission.id; logger.info(f"Runway Gen-4 task ID: {task_id}. Polling...")
            poll_interval=10; max_polls=36; start_poll_time = time.time()
            while time.time() - start_poll_time < max_polls * poll_interval:
                time.sleep(poll_interval); task_details = self.runway_ml_client_instance.tasks.retrieve(id=task_id)
                logger.info(f"Runway task {task_id} status: {task_details.status}")
                if task_details.status == 'SUCCEEDED':
                    output_url = getattr(getattr(task_details,'output',None),'url',None) or (getattr(task_details,'artifacts',None) and task_details.artifacts[0].url if task_details.artifacts and hasattr(task_details.artifacts[0],'url') else None) or (getattr(task_details,'artifacts',None) and task_details.artifacts[0].download_url if task_details.artifacts and hasattr(task_details.artifacts[0],'download_url') else None)
                    if not output_url: logger.error(f"Runway task {task_id} SUCCEEDED, but no output URL. Details: {vars(task_details) if hasattr(task_details,'__dict__') else task_details}"); return None
                    logger.info(f"Runway task {task_id} SUCCEEDED. Downloading: {output_url}")
                    video_response = requests.get(output_url, stream=True, timeout=300); video_response.raise_for_status()
                    with open(output_video_filepath,'wb') as f:
                        for chunk in video_response.iter_content(chunk_size=8192): f.write(chunk)
                    logger.info(f"Runway Gen-4 video saved: {output_video_filepath}"); return output_video_filepath
                elif task_details.status in ['FAILED','ABORTED','ERROR']:
                    em = getattr(task_details,'error_message',None) or getattr(getattr(task_details,'output',None),'error',"Unknown Runway error.")
                    logger.error(f"Runway task {task_id} status: {task_details.status}. Error: {em}"); return None
            logger.warning(f"Runway task {task_id} timed out."); return None
        except AttributeError as ae: logger.error(f"RunwayML SDK AttrError: {ae}. SDK/methods changed?", exc_info=True); return None
        except Exception as e: logger.error(f"Runway Gen-4 API error: {e}", exc_info=True); return None

    def _create_placeholder_video_content(self, td, fn, dur=4, sz=None):
        # (Keep as before)
        if sz is None: sz = self.video_frame_size; fp = os.path.join(self.output_dir, fn); tc = None
        try: tc = TextClip(td, fontsize=50, color='white', font=self.video_overlay_font, bg_color='black', size=sz, method='caption').set_duration(dur); tc.write_videofile(fp, fps=24, codec='libx264', preset='ultrafast', logger=None, threads=2); logger.info(f"Generic placeholder video: {fp}"); return fp
        except Exception as e: logger.error(f"Generic placeholder video error {fp}: {e}", exc_info=True); return None
        finally:
            if tc and hasattr(tc, 'close'): tc.close()

    def generate_scene_asset(self, image_generation_prompt_text, motion_prompt_text_for_video,
                             scene_data, scene_identifier_filename_base,
                             generate_as_video_clip=False, runway_target_duration=5):
        # <<< THIS IS THE CORRECTED METHOD with fixed DALL-E loop >>>
        base_name, _ = os.path.splitext(scene_identifier_filename_base)
        asset_info = {'path': None, 'type': 'none', 'error': True,
                      'prompt_used': image_generation_prompt_text,
                      'error_message': 'Asset generation init failed'}
        input_image_for_runway_path = None
        base_image_filename = base_name + ("_base_for_video.png" if generate_as_video_clip else ".png")
        base_image_filepath = os.path.join(self.output_dir, base_image_filename)
        
        if self.USE_AI_IMAGE_GENERATION and self.openai_api_key:
            max_retries = 2; attempt_count_dalle = 0
            for attempt_num_dalle in range(max_retries):
                attempt_count_dalle = attempt_num_dalle + 1
                try: # DALL-E attempt try block
                    logger.info(f"Attempt {attempt_count_dalle} DALL-E (base img): {image_generation_prompt_text[:70]}...")
                    client_oai = openai.OpenAI(api_key=self.openai_api_key, timeout=90.0)
                    response_oai = client_oai.images.generate(model=self.dalle_model,prompt=image_generation_prompt_text,n=1,size=self.image_size_dalle3,quality="hd",response_format="url",style="vivid")
                    img_url_oai = response_oai.data[0].url
                    revised_prompt_oai = getattr(response_oai.data[0],'revised_prompt',None)
                    if revised_prompt_oai: logger.info(f"DALL-E revised: {revised_prompt_oai[:70]}...")
                    img_response_get = requests.get(img_url_oai,timeout=120); img_response_get.raise_for_status()
                    pil_img_oai = Image.open(io.BytesIO(img_response_get.content))
                    if pil_img_oai.mode!='RGB': pil_img_oai=pil_img_oai.convert('RGB')
                    pil_img_oai.save(base_image_filepath); logger.info(f"DALL-E base img saved: {base_image_filepath}")
                    input_image_for_runway_path=base_image_filepath
                    asset_info={'path':base_image_filepath,'type':'image','error':False,'prompt_used':image_generation_prompt_text,'revised_prompt':revised_prompt_oai}
                    break # Success, exit loop
                except openai.RateLimitError as e_rl: logger.warning(f"OpenAI RateLimit Att {attempt_count_dalle}:{e_rl}.Retry...");time.sleep(5*attempt_count_dalle);asset_info['error_message']=str(e_rl)
                except openai.APIError as e_api_oai: logger.error(f"OpenAI APIError Att {attempt_count_dalle}:{e_api_oai}");asset_info['error_message']=str(e_api_oai);break
                except requests.exceptions.RequestException as e_req_oai: logger.error(f"Requests Err DALL-E Att {attempt_count_dalle}:{e_req_oai}");asset_info['error_message']=str(e_req_oai);break
                except Exception as e_gen_oai: logger.error(f"General DALL-E Err Att {attempt_count_dalle}:{e_gen_oai}",exc_info=True);asset_info['error_message']=str(e_gen_oai);break
            if asset_info['error']: logger.warning(f"DALL-E failed after {attempt_count_dalle} attempts for base img.")
        
        if asset_info['error'] and self.USE_PEXELS:
            logger.info("Trying Pexels for base img.");pqt=scene_data.get('pexels_search_query_๊ฐ๋…',f"{scene_data.get('emotional_beat','')} {scene_data.get('setting_description','')}");pp=self._search_pexels_image(pqt,base_image_filename);
            if pp:input_image_for_runway_path=pp;asset_info={'path':pp,'type':'image','error':False,'prompt_used':f"Pexels:{pqt}"}
            else:current_em=asset_info.get('error_message',"");asset_info['error_message']=(current_em+" Pexels failed for base.").strip()

        if asset_info['error']:
            logger.warning("Base img (DALL-E/Pexels) failed. Using placeholder.");ppt=asset_info.get('prompt_used',image_generation_prompt_text);php=self._create_placeholder_image_content(f"[Base Placeholder]{ppt[:70]}...",base_image_filename);
            if php:input_image_for_runway_path=php;asset_info={'path':php,'type':'image','error':False,'prompt_used':ppt}
            else:current_em=asset_info.get('error_message',"");asset_info['error_message']=(current_em+" Base placeholder failed.").strip()

        if generate_as_video_clip:
            if not input_image_for_runway_path:logger.error("RunwayML video: base img failed.");asset_info['error']=True;asset_info['error_message']=(asset_info.get('error_message',"")+" Base img miss, Runway abort.").strip();asset_info['type']='none';return asset_info
            if self.USE_RUNWAYML:
                video_path=self._generate_video_clip_with_runwayml(motion_prompt_text_for_video,input_image_for_runway_path,base_name,runway_target_duration)
                if video_path and os.path.exists(video_path):asset_info={'path':video_path,'type':'video','error':False,'prompt_used':motion_prompt_text_for_video,'base_image_path':input_image_for_runway_path}
                else:logger.warning(f"RunwayML video failed for {base_name}. Fallback to base img.");asset_info['error']=True;asset_info['error_message']=(asset_info.get('error_message',"Base img ok.")+" RunwayML video fail; use base img.").strip();asset_info['path']=input_image_for_runway_path;asset_info['type']='image';asset_info['prompt_used']=image_generation_prompt_text
            else:logger.warning("RunwayML selected but disabled. Use base img.");asset_info['error']=True;asset_info['error_message']=(asset_info.get('error_message',"Base img ok.")+" RunwayML disabled; use base img.").strip();asset_info['path']=input_image_for_runway_path;asset_info['type']='image';asset_info['prompt_used']=image_generation_prompt_text
        return asset_info

    def generate_narration_audio(self, text_to_narrate, output_filename="narration_overall.mp3"):
        # (Keep as before)
        if not self.USE_ELEVENLABS or not self.elevenlabs_client or not text_to_narrate: logger.info("11L skip."); return None; afp=os.path.join(self.output_dir,output_filename)
        try: logger.info(f"11L audio (Voice:{self.elevenlabs_voice_id}): {text_to_narrate[:70]}..."); asm=None
        if hasattr(self.elevenlabs_client,'text_to_speech')and hasattr(self.elevenlabs_client.text_to_speech,'stream'):asm=self.elevenlabs_client.text_to_speech.stream;logger.info("Using 11L .text_to_speech.stream()")
        elif hasattr(self.elevenlabs_client,'generate_stream'):asm=self.elevenlabs_client.generate_stream;logger.info("Using 11L .generate_stream()")
        elif hasattr(self.elevenlabs_client,'generate'):logger.info("Using 11L .generate()");vp=Voice(voice_id=str(self.elevenlabs_voice_id),settings=self.elevenlabs_voice_settings)if Voice and self.elevenlabs_voice_settings else str(self.elevenlabs_voice_id);ab=self.elevenlabs_client.generate(text=text_to_narrate,voice=vp,model="eleven_multilingual_v2");
        with open(afp,"wb")as f:f.write(ab);logger.info(f"11L audio (non-stream): {afp}");return afp
        else:logger.error("No 11L audio method.");return None
        if asm:vps={"voice_id":str(self.elevenlabs_voice_id)}
        if self.elevenlabs_voice_settings:
            if hasattr(self.elevenlabs_voice_settings,'model_dump'):vps["voice_settings"]=self.elevenlabs_voice_settings.model_dump()
            elif hasattr(self.elevenlabs_voice_settings,'dict'):vps["voice_settings"]=self.elevenlabs_voice_settings.dict()
            else:vps["voice_settings"]=self.elevenlabs_voice_settings
        adi=asm(text=text_to_narrate,model_id="eleven_multilingual_v2",**vps)
        with open(afp,"wb")as f:
            for c_chunk in adi: # Renamed c to c_chunk
                if c_chunk:f.write(c_chunk)
        logger.info(f"11L audio (stream): {afp}");return afp
        except Exception as e_11l:logger.error(f"11L audio error: {e_11l}",exc_info=True);return None # Renamed e to e_11l

    def assemble_animatic_from_assets(self, asset_data_list, overall_narration_path=None, output_filename="final_video.mp4", fps=24):
        # (Keep as in the version with robust image processing, C-contiguous array, debug saves, and pix_fmt)
        if not asset_data_list: logger.warning("No assets for animatic."); return None
        processed_clips = []; narration_clip_mvpy = None; final_composite_video_clip = None # Renamed variables
        logger.info(f"Assembling from {len(asset_data_list)} assets. Frame: {self.video_frame_size}.")
        for i, asset_info_dict in enumerate(asset_data_list): # Renamed asset_info to asset_info_dict
            asset_p, asset_t, scene_d = asset_info_dict.get('path'), asset_info_dict.get('type'), asset_info_dict.get('duration', 4.5)
            scene_n, key_act = asset_info_dict.get('scene_num', i + 1), asset_info_dict.get('key_action', '')
            logger.info(f"S{scene_n}: Path='{asset_p}', Type='{asset_t}', Dur='{scene_d}'s")
            if not (asset_p and os.path.exists(asset_p)): logger.warning(f"S{scene_n}: Not found '{asset_p}'. Skip."); continue
            if scene_d <= 0: logger.warning(f"S{scene_n}: Invalid duration ({scene_d}s). Skip."); continue
            current_scene_clip_mvpy = None # Renamed current_scene_mvpy_clip
            try:
                if asset_t == 'image':
                    # ... (Robust image processing logic from previous full version) ...
                    pil_img_opened = Image.open(asset_p); logger.debug(f"S{scene_n}: Loaded img. Mode:{pil_img_opened.mode}, Size:{pil_img_opened.size}")
                    img_rgba_converted = pil_img_opened.convert('RGBA') if pil_img_opened.mode != 'RGBA' else pil_img_opened.copy()
                    thumb_img = img_rgba_converted.copy(); res_filter = Image.Resampling.LANCZOS if hasattr(Image.Resampling,'LANCZOS') else Image.BILINEAR; thumb_img.thumbnail(self.video_frame_size,res_filter)
                    canvas_for_rgba = Image.new('RGBA',self.video_frame_size,(0,0,0,0)); x_offset,y_offset=(self.video_frame_size[0]-thumb_img.width)//2,(self.video_frame_size[1]-thumb_img.height)//2
                    canvas_for_rgba.paste(thumb_img,(x_offset,y_offset),thumb_img)
                    final_rgb_for_pil = Image.new("RGB",self.video_frame_size,(0,0,0)); final_rgb_for_pil.paste(canvas_for_rgba,mask=canvas_for_rgba.split()[3])
                    debug_path_pre_numpy = os.path.join(self.output_dir,f"debug_PRE_NUMPY_S{scene_n}.png"); final_rgb_for_pil.save(debug_path_pre_numpy); logger.info(f"DEBUG: Saved PRE_NUMPY_S{scene_n} to {debug_path_pre_numpy}")
                    numpy_frame = np.array(final_rgb_for_pil,dtype=np.uint8);
                    if not numpy_frame.flags['C_CONTIGUOUS']: numpy_frame=np.ascontiguousarray(numpy_frame,dtype=np.uint8)
                    logger.debug(f"S{scene_n}: NumPy for MoviePy. Shape:{numpy_frame.shape}, DType:{numpy_frame.dtype}, C-Contig:{numpy_frame.flags['C_CONTIGUOUS']}")
                    if numpy_frame.size==0 or numpy_frame.ndim!=3 or numpy_frame.shape[2]!=3: logger.error(f"S{scene_n}: Invalid NumPy. Skip."); continue
                    image_clip_base = ImageClip(numpy_frame,transparent=False).set_duration(scene_d)
                    moviepy_debug_frame_save_path=os.path.join(self.output_dir,f"debug_MOVIEPY_FRAME_S{scene_n}.png"); image_clip_base.save_frame(moviepy_debug_frame_save_path,t=0.1); logger.info(f"DEBUG: Saved MOVIEPY_FRAME_S{scene_n} to {moviepy_debug_frame_save_path}")
                    image_clip_with_fx = image_clip_base
                    try: end_scale_kb=random.uniform(1.03,1.08); image_clip_with_fx=image_clip_base.fx(vfx.resize,lambda time_t:1+(end_scale_kb-1)*(time_t/scene_d) if scene_d>0 else 1).set_position('center')
                    except Exception as e_kb: logger.error(f"S{scene_n} Ken Burns error: {e_kb}",exc_info=False)
                    current_scene_mvpy_clip = image_clip_with_fx
                elif asset_t == 'video':
                    # ... (Video processing logic from previous full version) ...
                    source_video_file_clip=None
                    try:
                        source_video_file_clip=VideoFileClip(asset_p,target_resolution=(self.video_frame_size[1],self.video_frame_size[0])if self.video_frame_size else None, audio=False)
                        temp_video_clip_obj=source_video_file_clip
                        if source_video_file_clip.duration!=scene_d:
                            if source_video_file_clip.duration>scene_d:temp_video_clip_obj=source_video_file_clip.subclip(0,scene_d)
                            else:
                                if scene_d/source_video_file_clip.duration > 1.5 and source_video_file_clip.duration>0.1:temp_video_clip_obj=source_video_file_clip.loop(duration=scene_d)
                                else:temp_video_clip_obj=source_video_file_clip.set_duration(source_video_file_clip.duration);logger.info(f"S{scene_n} Video clip ({source_video_file_clip.duration:.2f}s) shorter than target ({scene_d:.2f}s).")
                        current_scene_mvpy_clip=temp_video_clip_obj.set_duration(scene_d)
                        if current_scene_mvpy_clip.size!=list(self.video_frame_size):current_scene_mvpy_clip=current_scene_mvpy_clip.resize(self.video_frame_size)
                    except Exception as e_vidload:logger.error(f"S{scene_n} Video load error '{asset_p}':{e_vidload}",exc_info=True);continue
                    finally:
                        if source_video_file_clip and source_video_file_clip is not current_scene_mvpy_clip and hasattr(source_video_file_clip,'close'):source_video_file_clip.close()
                else: logger.warning(f"S{scene_n} Unknown asset type '{asset_t}'. Skip."); continue
                
                if current_scene_mvpy_clip and key_act: # Text Overlay
                    try:
                        text_overlay_dur=min(current_scene_mvpy_clip.duration-0.5,current_scene_mvpy_clip.duration*0.8)if current_scene_mvpy_clip.duration>0.5 else current_scene_mvpy_clip.duration
                        text_overlay_s_time=0.25
                        if text_overlay_dur > 0:
                            text_clip_obj=TextClip(f"Scene {scene_n}\n{key_act}",fontsize=self.VIDEO_OVERLAY_FONT_SIZE,color=self.VIDEO_OVERLAY_FONT_COLOR,font=self.video_overlay_font,bg_color='rgba(10,10,20,0.7)',method='caption',align='West',size=(self.video_frame_size[0]*0.9,None),kerning=-1,stroke_color='black',stroke_width=1.5).set_duration(text_overlay_dur).set_start(text_overlay_s_time).set_position(('center',0.92),relative=True)
                            current_scene_mvpy_clip=CompositeVideoClip([current_scene_mvpy_clip,text_clip_obj],size=self.video_frame_size,use_bgclip=True)
                        else: logger.warning(f"S{scene_n}: Text overlay duration zero. Skip text.")
                    except Exception as e_txtclip:logger.error(f"S{scene_n} TextClip error:{e_txtclip}. No text.",exc_info=True)
                if current_scene_mvpy_clip:processed_clips.append(current_scene_mvpy_clip);logger.info(f"S{scene_n} Processed. Dur:{current_scene_mvpy_clip.duration:.2f}s.")
            except Exception as e_asset_loop:logger.error(f"MAJOR Error S{scene_n} ({asset_p}):{e_asset_loop}",exc_info=True)
            finally:
                if current_scene_mvpy_clip and hasattr(current_scene_mvpy_clip,'close'):
                    try: current_scene_mvpy_clip.close()
                    except: pass

        if not processed_clips:logger.warning("No clips processed. Abort.");return None
        transition_val=0.75
        try:
            logger.info(f"Concatenating {len(processed_clips)} clips.");
            if len(processed_clips)>1:final_composite_video_clip=concatenate_videoclips(processed_clips,padding=-transition_val if transition_val>0 else 0,method="compose")
            elif processed_clips:final_composite_video_clip=processed_clips[0]
            if not final_composite_video_clip:logger.error("Concatenation failed.");return None
            logger.info(f"Concatenated dur:{final_composite_video_clip.duration:.2f}s")
            if transition_val>0 and final_composite_video_clip.duration>0:
                if final_composite_video_clip.duration>transition_val*2:final_composite_video_clip=final_composite_video_clip.fx(vfx.fadein,transition_val).fx(vfx.fadeout,transition_val)
                else:final_composite_video_clip=final_composite_video_clip.fx(vfx.fadein,min(transition_val,final_composite_video_clip.duration/2.0))
            if overall_narration_path and os.path.exists(overall_narration_path) and final_composite_video_clip.duration>0:
                try:narration_clip_mvpy=AudioFileClip(overall_narration_path);final_composite_video_clip=final_composite_video_clip.set_audio(narration_clip_mvpy);logger.info("Narration added.")
                except Exception as e_narr:logger.error(f"Narration add error:{e_narr}",exc_info=True)
            elif final_composite_video_clip.duration<=0:logger.warning("Video no duration. No audio.")
            if final_composite_video_clip and final_composite_video_clip.duration>0:
                output_vid_path=os.path.join(self.output_dir,output_filename);logger.info(f"Writing video:{output_vid_path} (Dur:{final_composite_video_clip.duration:.2f}s)")
                final_composite_video_clip.write_videofile(output_vid_path,fps=fps,codec='libx264',preset='medium',audio_codec='aac',temp_audiofile=os.path.join(self.output_dir,f'temp-audio-{os.urandom(4).hex()}.m4a'),remove_temp=True,threads=os.cpu_count()or 2,logger='bar',bitrate="5000k",ffmpeg_params=["-pix_fmt", "yuv420p"])
                logger.info(f"Video created:{output_vid_path}");return output_vid_path
            else:logger.error("Final clip invalid. No write.");return None
        except Exception as e_vid_write:logger.error(f"Video write error:{e_vid_write}",exc_info=True);return None
        finally:
            logger.debug("Closing all MoviePy clips in `assemble_animatic_from_assets` finally block.")
            all_clips_to_close_list = processed_clips + ([narration_clip_mvpy] if narration_clip_mvpy else []) + ([final_composite_video_clip] if final_composite_video_clip else [])
            for clip_to_close_item in all_clips_to_close_list:
                if clip_to_close_item and hasattr(clip_to_close_item, 'close'):
                    try: clip_to_close_item.close()
                    except Exception as e_final_close: logger.warning(f"Ignoring error while closing a clip: {type(clip_to_close_item).__name__} - {e_final_close}")