File size: 32,450 Bytes
e7b8e7e
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
# =========================================================================
#                          MODULES / MOD_VIDEO.PY
#   Universal Motion Graphics Engine (60 FPS) + PyCairo Anti-Aliased Canvas
#   + Safe-Proxy Canvas + Live Audio-Reactive Energy + FluidSynth SoundFont
# =========================================================================

import os
import base64
import io
from pathlib import Path
import sys
import re
import uuid
import math
import time
import inspect
import random
import colorsys
import wave
import shutil
import subprocess
import asyncio
import concurrent.futures
import builtins
import numpy as np
import cv2
import cairo
from modules.client import call_gemini
import config

# -------------------------------------------------------------------------
# 0. БЕЗОПАСНАЯ ОБЕРТКА ДЛЯ CAIRO.CONTEXT (ЗАЩИТА ОТ ОПЕЧАТОК И CANVAS API)
# -------------------------------------------------------------------------
class SafeCairoContext:
    """Безопасный прокси над cairo.Context: переводит вызовы HTML5 Canvas в PyCairo."""
    def __init__(self, raw_ctx):
        self._ctx = raw_ctx

    def begin_path(self): 
        return self._ctx.new_path()
        
    def beginPath(self): 
        return self._ctx.new_path()
        
    def close_path(self): 
        return self._ctx.close_path()
        
    def closePath(self): 
        return self._ctx.close_path()

    def circle(self, cx, cy, r):
        return self._ctx.arc(cx, cy, r, 0, 2 * math.pi)

    def ellipse(self, cx, cy, rx, ry):
        self._ctx.save()
        self._ctx.translate(cx, cy)
        self._ctx.scale(rx, ry)
        self._ctx.arc(0, 0, 1.0, 0, 2 * math.pi)
        self._ctx.restore()

    def round_rect(self, x, y, w, h, r):
        r = min(r, w / 2.0, h / 2.0)
        self._ctx.move_to(x + r, y)
        self._ctx.line_to(x + w - r, y)
        self._ctx.arc(x + w - r, y + r, r, -math.pi / 2, 0)
        self._ctx.line_to(x + w, y + h - r)
        self._ctx.arc(x + w - r, y + h - r, r, 0, math.pi / 2)
        self._ctx.line_to(x + r, y + h)
        self._ctx.arc(x + r, y + h - r, r, math.pi / 2, math.pi)
        self._ctx.line_to(x, y + r)
        self._ctx.arc(x + r, y + r, r, math.pi, 3 * math.pi / 2)
        self._ctx.close_path()

    def __getattr__(self, name):
        return getattr(self._ctx, name)


# Внедрение математических функций в глобальный scope Python
builtins.math = math
builtins.sin = math.sin
builtins.cos = math.cos
builtins.tan = math.tan
builtins.atan2 = math.atan2
builtins.pi = math.pi
builtins.sqrt = math.sqrt
builtins.np = np
builtins.random = random
builtins.colorsys = colorsys

from modules.live_config import VOICE_PRESETS, LIVE_ACTING_PROMPT, get_live_credentials

def get_soundfont_path():
    candidates = [config.SOUNDFONT_PATH, "GeneralUser_GS.sf2",
                  "/usr/share/sounds/sf2/FluidR3_GM.sf2"]
    return next((path for path in candidates if path and os.path.isfile(path)), None)


def resample_audio(pcm_data: np.ndarray, orig_sr: int = 24000, target_sr: int = 44100) -> np.ndarray:
    if len(pcm_data) == 0: return np.zeros(0, dtype=np.float32)
    try:
        from scipy.signal import resample_poly
        divisor = math.gcd(orig_sr, target_sr)
        return resample_poly(pcm_data, target_sr // divisor, orig_sr // divisor).astype(np.float32)
    except Exception:
        target_len = int(len(pcm_data) * (target_sr / float(orig_sr)))
        return np.interp(
            np.linspace(0, len(pcm_data), target_len, endpoint=False),
            np.arange(len(pcm_data)),
            pcm_data
        ).astype(np.float32)


def time_stretch_preserve_pitch(signal: np.ndarray, speed: float = 1.0, sr: int = 44100) -> np.ndarray:
    speed = float(speed or 1.0)
    if abs(speed - 1.0) < 0.03 or len(signal) < 2048: return signal

    win_size = int(sr * 0.025)
    if win_size % 2 != 0: win_size += 1
    hop_syn = win_size // 2
    hop_ana = int(hop_syn * speed)
    if hop_ana <= 0 or win_size >= len(signal): return signal

    window = np.hanning(win_size).astype(np.float32)
    num_frames = (len(signal) - win_size) // hop_ana
    if num_frames <= 1: return signal

    out_len = num_frames * hop_syn + win_size
    output = np.zeros(out_len, dtype=np.float32)
    norm = np.zeros(out_len, dtype=np.float32)
    search_range = win_size // 4

    for i in range(num_frames):
        ana_pos = i * hop_ana
        syn_pos = i * hop_syn
        best_pos = ana_pos
        if i > 0 and (ana_pos - search_range >= 0) and (ana_pos + win_size + search_range < len(signal)):
            ref = output[syn_pos : syn_pos + win_size]
            candidates = np.array([
                signal[ana_pos + d : ana_pos + d + win_size] * window
                for d in range(-search_range, search_range, 2)
            ])
            corrs = np.dot(candidates, ref)
            best_idx = int(np.argmax(corrs))
            best_pos = ana_pos + (-search_range + best_idx * 2)

        if best_pos + win_size > len(signal): break
        frame = signal[best_pos : best_pos + win_size] * window
        output[syn_pos : syn_pos + win_size] += frame
        norm[syn_pos : syn_pos + win_size] += window

    valid = norm > 1e-3
    output[valid] /= norm[valid]
    return output


# -------------------------------------------------------------------------
# 3. СИНТЕЗАТОР ГОЛОСА GEMINI LIVE API
# -------------------------------------------------------------------------
async def _fetch_gemini_live_pcm(text_prompt: str, voice_name: str, char_instruction: str) -> np.ndarray:
    from google import genai
    from google.genai import types

    keys, proxy_url, model = get_live_credentials()
    if not keys: return np.zeros(0, dtype=np.float32)

    full_instruction = f"{char_instruction}\n\n{LIVE_ACTING_PROMPT}".strip()
    sys_inst = types.Content(parts=[types.Part.from_text(text=full_instruction)])

    live_config = types.LiveConnectConfig(
        response_modalities=["AUDIO"],
        speech_config=types.SpeechConfig(
            voice_config=types.VoiceConfig(
                prebuilt_voice_config=types.PrebuiltVoiceConfig(voice_name=voice_name)
            )
        ),
        system_instruction=sys_inst
    )

    http_opts = {"api_version": "v1beta"}
    if proxy_url: http_opts["base_url"] = proxy_url

    clean_text = text_prompt.strip()
    command_prompt = f"Perform and speak aloud ONLY this dialogue line. Express emotions naturally, never read stage direction words out loud: {clean_text}"

    for key in keys:
        try:
            client = genai.Client(http_options=http_opts, api_key=key)
            audio_chunks = []
            async with client.aio.live.connect(model=model, config=live_config) as session:
                await session.send_realtime_input(text=command_prompt)

                async for response in session.receive():
                    if data := getattr(response, "data", None):
                        audio_chunks.append(data)
                    server_content = getattr(response, "server_content", None)
                    if server_content and getattr(server_content, "turn_complete", False):
                        break

            if audio_chunks:
                raw_bytes = b"".join(audio_chunks)
                int16_arr = np.frombuffer(raw_bytes, dtype=np.int16)
                return (int16_arr.astype(np.float32) / 32768.0)
        except Exception as e:
            print(f"[!] Gemini Live ({voice_name}): {type(e).__name__}")
            continue

    return np.zeros(0, dtype=np.float32)


def generate_live_voice_audio(text_prompt: str, voice_or_preset: str = "female_leda", custom_instruction: str = None) -> np.ndarray:
    preset = VOICE_PRESETS.get(voice_or_preset, {})
    voice_name = preset.get("voice", voice_or_preset)
    instruction = custom_instruction or preset.get("instruction", "Speak clearly, dynamically and concisely with natural emotion.")

    def _thread_runner():
        new_loop = asyncio.new_event_loop()
        asyncio.set_event_loop(new_loop)
        try:
            return new_loop.run_until_complete(asyncio.wait_for(
                _fetch_gemini_live_pcm(text_prompt, voice_name, instruction), timeout=30
            ))
        finally:
            try:
                pending = asyncio.all_tasks(new_loop)
                if pending:
                    for task in pending: task.cancel()
                    new_loop.run_until_complete(asyncio.gather(*pending, return_exceptions=True))
                new_loop.close()
            except Exception: pass

    try:
        with concurrent.futures.ThreadPoolExecutor(max_workers=1) as executor:
            future = executor.submit(_thread_runner)
            return future.result(timeout=35.0)
    except Exception as e:
        print(f"[!] Сбой синтеза речи Gemini Live: {e}")
        return np.zeros(0, dtype=np.float32)


# -------------------------------------------------------------------------
# 4. ТОЧНЫЙ И НЕУБИВАЕМЫЙ ЗВУКОВОЙ ДВИЖОК FLUIDSYNTH
# -------------------------------------------------------------------------
NOTE_MAP = {
    'c': 0, 'c#': 1, 'db': 1, 'd': 2, 'd#': 3, 'eb': 3, 'e': 4,
    'f': 5, 'f#': 6, 'gb': 6, 'g': 7, 'g#': 8, 'ab': 8, 'a': 9,
    'a#': 10, 'bb': 10, 'b': 11
}

def parse_note_to_midi(val) -> int:
    if isinstance(val, (int, float)):
        return int(np.clip(val, 0, 127))
    if isinstance(val, str):
        s = val.strip().lower()
        m = re.match(r'([a-g][#b]?)(-?\d+)', s)
        if m:
            name, oct_v = m.group(1), int(m.group(2))
            return int(np.clip(12 * (oct_v + 1) + NOTE_MAP.get(name, 9), 0, 127))
        try: return int(float(val))
        except Exception: return 60
    return 60


class SoundStudio:
    """Универсальная студия: точные программы FluidSynth (0-127) + ударные + Gemini Voice."""
    def __init__(self, duration: float = 15.0, sample_rate: int = 44100):
        self.duration = float(duration)
        self.sample_rate = int(sample_rate)
        self.total_samples = int(self.duration * self.sample_rate)
        self.master_buffer = np.zeros((self.total_samples, 2), dtype=np.float32)
        self.midi_events = []
        self.channel_programs = {}

    def voice(self, *args, **kwargs):
        """Синтез живой актерской речи."""
        start = float(args[0] if len(args) > 0 else kwargs.get("start", kwargs.get("time", kwargs.get("t", 0.0))))
        text = str(args[1] if len(args) > 1 else kwargs.get("text", kwargs.get("prompt", kwargs.get("line", ""))))
        voice = str(args[2] if len(args) > 2 else kwargs.get("voice", kwargs.get("speaker", "female_leda")))
        instruction = kwargs.get("instruction", None)
        speed = float(kwargs.get("speed", kwargs.get("rate", 1.15)))
        vol = float(kwargs.get("vol", kwargs.get("volume", kwargs.get("gain", 1.0))))
        pan = float(kwargs.get("pan", 0.0))

        start_idx = int(max(0.0, start) * self.sample_rate)
        if start_idx >= self.total_samples or not text.strip(): return

        pcm_24k = generate_live_voice_audio(text, voice_or_preset=voice, custom_instruction=instruction)
        if len(pcm_24k) == 0:
            raise RuntimeError(f"Gemini Live не вернул озвучку для голоса {voice}.")

        v_peak = np.max(np.abs(pcm_24k))
        if v_peak > 0.001: pcm_24k = (pcm_24k / v_peak) * 0.90

        resampled_voice = resample_audio(pcm_24k, orig_sr=24000, target_sr=self.sample_rate)
        speed_val = max(0.6, min(2.5, speed))
        resampled_voice = time_stretch_preserve_pitch(resampled_voice, speed=speed_val, sr=self.sample_rate)

        abs_v = np.abs(resampled_voice)
        gate_mask = np.clip((abs_v - 0.008) / 0.015, 0.0, 1.0)
        smooth_k = int(self.sample_rate * 0.005)
        if smooth_k > 1:
            k = np.ones(smooth_k) / smooth_k
            gate_mask = np.convolve(gate_mask, k, mode='same')
        resampled_voice = resampled_voice * gate_mask

        end_idx = min(self.total_samples, start_idx + len(resampled_voice))
        actual_len = end_idx - start_idx
        if actual_len <= 0: return

        voice_gain = vol * 1.6
        pan_val = max(-1.0, min(1.0, pan))
        left_gain = math.cos((pan_val + 1.0) * math.pi / 4.0) * voice_gain
        right_gain = math.sin((pan_val + 1.0) * math.pi / 4.0) * voice_gain

        self.master_buffer[start_idx:end_idx, 0] += resampled_voice[:actual_len] * left_gain
        self.master_buffer[start_idx:end_idx, 1] += resampled_voice[:actual_len] * right_gain

    def voice_clip(self, start: float, asset: str, volume: float = 1.0):
        """Place verified Gemini Live WAV data without calling any API."""
        if not re.fullmatch(r"voice-clips/[a-zA-Z0-9_-]+\.wav\.b64", asset):
            raise ValueError("Voice clips belong in voice-clips/ as .wav.b64 files.")
        path = Path(asset).resolve(strict=True)
        if not path.is_relative_to(Path("voice-clips").resolve()):
            raise ValueError("Voice clip resolves outside voice-clips/.")
        start = float(start)
        volume = float(volume)
        if not math.isfinite(start) or not 0 <= start < self.duration:
            raise ValueError("Voice clip start must be inside the scene.")
        if not math.isfinite(volume) or not 0 < volume <= 2:
            raise ValueError("Voice clip volume must be between 0 and 2.")
        encoded = path.read_bytes().strip()
        if not 0 < len(encoded) <= 4_000_000:
            raise ValueError("Voice clip data is empty or too large.")
        with wave.open(io.BytesIO(base64.b64decode(encoded, validate=True)), "rb") as clip:
            if (clip.getnchannels(), clip.getsampwidth(), clip.getframerate()) != (1, 2, 24000):
                raise ValueError("Expected a 24 kHz mono 16-bit PCM WAV.")
            frame_count = clip.getnframes()
            pcm = np.frombuffer(clip.readframes(frame_count), dtype="<i2")
        if not frame_count or len(pcm) != frame_count or not np.any(pcm):
            raise ValueError("Voice clip is empty, silent or truncated.")
        signal = resample_audio(pcm.astype(np.float32) / 32768.0, 24000, self.sample_rate)
        begin = round(start * self.sample_rate)
        end = begin + len(signal)
        if end > self.total_samples:
            raise ValueError("Voice clip exceeds scene duration. Extend the scene or start earlier.")
        self.master_buffer[begin:end] += (signal * volume / math.sqrt(2))[:, None]

    def play(self, *args, **kwargs):
        """Воспроизведение нот/сэмплов по точному номеру инструмента General MIDI."""
        start = float(args[0] if len(args) > 0 else kwargs.get("start", kwargs.get("time", kwargs.get("t", 0.0))))
        duration = float(args[1] if len(args) > 1 else kwargs.get("duration", kwargs.get("dur", kwargs.get("d", 0.5))))
        pitch = args[2] if len(args) > 2 else kwargs.get("pitch", kwargs.get("note", kwargs.get("key", 60)))
        program = int(kwargs.get("program", kwargs.get("prog", kwargs.get("instrument", 0))))
        vol = int(kwargs.get("vol", kwargs.get("volume", kwargs.get("velocity", 90))))
        channel = int(kwargs.get("channel", kwargs.get("ch", 0)))
        bank = int(kwargs.get("bank", 0))

        t_start = max(0.0, start)
        dur = max(0.05, duration)
        t_end = min(self.duration, t_start + dur)
        ch = channel % 16
        if ch == 9: ch = 0

        self.channel_programs[ch] = (bank, program)
        pitches = pitch if isinstance(pitch, (list, tuple)) else [pitch]
        for p in pitches:
            midi_p = parse_note_to_midi(p)
            v = int(np.clip(vol, 1, 127))
            self.midi_events.append((t_start, "on", ch, midi_p, v))
            self.midi_events.append((t_end, "off", ch, midi_p, 0))

    def note(self, *args, **kwargs):
        self.play(*args, **kwargs)

    def chord(self, *args, **kwargs):
        start = float(args[0] if len(args) > 0 else kwargs.get("start", kwargs.get("t", 0.0)))
        duration = float(args[1] if len(args) > 1 else kwargs.get("duration", kwargs.get("dur", 1.5)))
        pitches = kwargs.get("pitches", kwargs.get("chord", kwargs.get("notes", ["C4", "E4", "G4"])))
        if "pitch" in kwargs: pitches = kwargs["pitch"]
        program = int(kwargs.get("program", kwargs.get("prog", 48)))
        vol = int(kwargs.get("vol", kwargs.get("volume", kwargs.get("velocity", 80))))
        self.play(start=start, duration=duration, pitch=pitches, program=program, vol=vol, channel=1)

    def drum(self, *args, **kwargs):
        """Ударные и перкуссия (Channel 9): 36:Kick, 38:Snare, 42:HiHat, 75:Claves, 80:Triangle."""
        start = float(args[0] if len(args) > 0 else kwargs.get("start", kwargs.get("t", 0.0)))
        drum_type = int(args[1] if len(args) > 1 else kwargs.get("drum_type", kwargs.get("type", kwargs.get("note", 36))))
        vol = int(kwargs.get("vol", kwargs.get("volume", kwargs.get("velocity", 100))))

        t_start = max(0.0, start)
        t_end = min(self.duration, t_start + 0.3)
        self.channel_programs[9] = (128, 0)
        p = int(drum_type)
        v = int(np.clip(vol, 1, 127))
        self.midi_events.append((t_start, "on", 9, p, v))
        self.midi_events.append((t_end, "off", 9, p, 0))

    def _render_fluidsynth(self):
        if not self.midi_events:
            return
        soundfont = get_soundfont_path()
        if soundfont is None:
            raise RuntimeError("Укажите SOUNDFONT_PATH для музыки FluidSynth.")
        try:
            import fluidsynth
            fs = fluidsynth.Synth(samplerate=float(self.sample_rate), gain=0.50)
            sfid = fs.sfload(soundfont)
            if sfid < 0:
                raise RuntimeError("FluidSynth не загрузил SoundFont.")

            for ch, (b, p) in self.channel_programs.items():
                fs.program_select(ch, sfid, b, p)
                fs.cc(ch, 7, 75)

            self.midi_events.sort(key=lambda x: (x[0], 0 if x[1] == "off" else 1))
            chunks = []
            cur_t = 0.0

            for ev_t, ev_type, ch, p, v in self.midi_events:
                if ev_t >= self.duration: break
                dt = ev_t - cur_t
                if dt > 0:
                    samples_cnt = int(dt * self.sample_rate)
                    if samples_cnt > 0:
                        chunks.append(fs.get_samples(samples_cnt))
                        cur_t += dt

                if ev_type == "on": fs.noteon(ch, p, v)
                else: fs.noteoff(ch, p)

            if cur_t < self.duration:
                remaining_samples = int((self.duration - cur_t) * self.sample_rate)
                if remaining_samples > 0: chunks.append(fs.get_samples(remaining_samples))

            fs.delete()

            if chunks:
                raw_audio = np.concatenate(chunks).astype(np.float32).reshape(-1, 2)
                raw_audio = raw_audio / 32768.0
                act_len = min(self.total_samples, len(raw_audio))
                self.master_buffer[:act_len] += raw_audio[:act_len]

        except Exception as e:
            raise RuntimeError(f"Ошибка FluidSynth: {e}") from e

    def export_wav(self, out_path: str):
        self._render_fluidsynth()
        peak = np.max(np.abs(self.master_buffer))
        if peak > 0.001: mastered = self.master_buffer * (0.95 / max(peak, 0.95))
        else: mastered = self.master_buffer

        norm = (np.clip(mastered, -1.0, 1.0) * 32767.0).astype(np.int16)
        with wave.open(out_path, "wb") as wf:
            wf.setnchannels(2)
            wf.setsampwidth(2)
            wf.setframerate(self.sample_rate)
            wf.writeframes(norm.tobytes())

UniversalSound = SoundStudio


# -------------------------------------------------------------------------
# 5. СИСТЕМНЫЙ ПРОМПТ
# -------------------------------------------------------------------------
def detect_video_dimensions(prompt: str) -> tuple[int, int]:
    p = str(prompt).lower()
    if any(w in p for w in ["shorts", "шортс", "reels", "рилс", "tiktok", "тикток", "вертикал", "vertical", "9:16", "9/16"]):
        return 1080, 1920
    if any(w in p for w in ["квадрат", "square", "1:1", "1/1"]):
        return 1080, 1080
    return 1920, 1080


SYS_PROMPT_VIDEO = """
You are an ELITE 2D Animator (PyCairo) and Sound Producer.
Write high-performance Python code creating an animated scene with synchronized audio, multi-character voice acting, and FluidSynth instruments.

ENTRYPOINTS REQUIRED IN YOUR CODE:
1. `def draw_frame(ctx: cairo.Context, t: float, w: int, h: int, audio_level: float = 0.0) -> None:`
   - `t`: current time in seconds.
   - `ctx`: PyCairo drawing context (with anti-aliasing).
   - `audio_level`: Dynamic audio volume energy (0.0 to 1.5+). Use it to scale visualizers, pulse steam, or add organic motion.

2. `def build_audio(sound: SoundStudio) -> None:`
   - Compose music, Foley SFX, and dialogue lines (`sound.voice`).

CRITICAL CINEMATIC FRAMING & CHARACTER GUIDELINES:
1. PROPER CAMERA FRAMING (NO TINY MICROSCOPIC FIGURES!):
   - Use Medium Shot / Close-up framing! Main characters must occupy 40% to 70% of screen height.
   - Do NOT leave 90% of the screen empty. Fill the scene with cozy environment details (e.g. detailed table in foreground, steaming bowl, wallpaper/window/trees in background).

2. EXPRESSIVE 2D STORYBOOK ANATOMY & ACTING:
   - NEVER draw raw geometric stickmen or single-pixel lines!
   - Draw stylized illustrated bodies with clothing & silhouette:
     * Grandma: Shawl/cardigan, apron, glasses with glint, grey bun hair, arm extending with spoon animated via `sin(t)`.
     * Grandson: Hoodie/t-shirt, expressive hands held up in refusal, head turning/leaning back ("I can't eat anymore!").
     * Limbs: Draw arms with thick rounded strokes (`ctx.set_line_cap(cairo.LINE_CAP_ROUND)`, `line_width=16-24px`) with natural elbow bends.
     * Table & Props: Large soup bowl with rising animated steam curves (`ctx.curve_to`), shiny spoon, bread/mugs.

3. MULTI-CHARACTER VOICE ACTING:
   - For dialogues, switch voices appropriately:
     * `sound.voice(start=0.5, text="...", voice="grandma")`
     * `sound.voice(start=5.0, text="...", voice="female_leda")` (or 'male_fast' / young voice)
     * `sound.voice(start=10.0, text="...", voice="grandma")`
   - NEVER put stage directions or asterisks like `*усмехнулась*` in the voice text string.
   - Match 100% of spoken text and on-screen subtitles to the user's prompt language.

4. FLUIDSYNTH INSTRUMENTS (USE EXACT NUMBERS):
   - Birds / Forest: `sound.play(start=0.0, duration=4.0, pitch=60, program=123, vol=75)` (123: Bird Tweet)
   - Water / Ocean: `sound.play(start=0.0, duration=5.0, pitch=60, program=122, vol=70)` (122: Seashore/Water)
   - Spoon clink / Dishes: `sound.play(start=t, duration=0.2, pitch=84, program=9, vol=60)` (9: Glockenspiel) or `sound.drum(start=t, drum_type=80, vol=65)` (80: Triangle)
   - Steps / Wood knock: `sound.drum(start=t, drum_type=75, vol=65)` (75: Claves)
   - Acoustic Guitar: `program=24` | Flute: `program=73` | Strings: `program=48` | Accordion: `program=21`
   - Synth Lead: `program=80` | Bass: `program=33` | Piano: `program=0`

PYCAIRO API RULES:
- Use `ctx.new_path()`, `ctx.close_path()`, `ctx.arc()`, `ctx.curve_to()`.

CRITICAL RULES:
- Output ONLY pure executable Python code without markdown tags.
"""

def extract_code_block(text: str) -> str:
    """Безопасно извлекает чистый Python-код из любого ответа модели."""
    text = text.strip()
    match = re.search(r"```(?:python)?\s*([\s\S]*?)\s*```", text, flags=re.IGNORECASE)
    if match:
        return match.group(1).strip()
    clean = re.sub(r"^```(?:python)?\s*", "", text, flags=re.IGNORECASE)
    clean = re.sub(r"\s*```$", "", clean).strip()
    return clean

def sanitize_code(code_text: str) -> str:
    clean = extract_code_block(code_text)
    clean = re.sub(r'\bmath\.abs\b', 'abs', clean)
    clean = re.sub(r'\bmath\.min\b', 'min', clean)
    clean = re.sub(r'\bmath\.max\b', 'max', clean)
    clean = re.sub(r'\bmath\.round\b', 'round', clean)
    return clean

def get_ffmpeg_binary():
    if shutil.which("ffmpeg"): return "ffmpeg"
    try:
        import imageio_ffmpeg
        return imageio_ffmpeg.get_ffmpeg_exe()
    except Exception: pass
    return None


# -------------------------------------------------------------------------
# 6. КОНВЕЙЕР ГЕНЕРАЦИИ ВИДЕО (60 FPS + H.264 / AAC)
# -------------------------------------------------------------------------
def generate_video_scene(prompt: str, model: str = None, thinking: bool = True, images: list = None, *, scene_code: str | None = None, scene_name: str = "<scene>", strict_frames: bool = False) -> dict:
    duration = float(getattr(config, "VIDEO_DURATION", 15.0))
    fps = int(getattr(config, "VIDEO_FPS", 60))
    sr = int(getattr(config, "AUDIO_SAMPLE_RATE", 44100))
    total_frames = int(duration * fps)

    target_w, target_h = detect_video_dimensions(prompt)
    aspect_desc = "Vertical 9:16 (1080x1920)" if target_h > target_w else ("Square 1:1 (1080x1080)" if target_w == target_h else "Horizontal 16:9 (1920x1080)")

    enriched_prompt = (
        f"USER PROMPT: {prompt}\n"
        f"TARGET ASPECT RATIO: {aspect_desc}\n"
        f"CANVAS_WIDTH = {target_w}, CANVAS_HEIGHT = {target_h}, DURATION = {duration}s.\n"
        f"CRITICAL: Keep 100% of spoken text and on-screen typography strictly in the language of the USER PROMPT. "
        f"Use Medium Shot framing (characters occupy 50-70% height). Switch voices for multi-character dialogue."
    )

    if scene_code is None:
        scene_code = call_gemini(SYS_PROMPT_VIDEO, enriched_prompt, model=model, thinking=thinking, images=images)
    clean_code = sanitize_code(scene_code)

    auto_imports = (
        "import math\n"
        "from math import sin, cos, tan, pi, sqrt, atan2, radians, degrees, floor, ceil\n"
        "import numpy as np\n"
        "import random\n"
        "import time\n"
        "import colorsys\n"
        "import cairo\n\n"
    )
    if not clean_code.startswith("import math") and "import cairo" not in clean_code:
        clean_code = auto_imports + clean_code

    exec_scope = {
        "cairo": cairo,
        "math": math, "sin": math.sin, "cos": math.cos, "tan": math.tan,
        "pi": math.pi, "sqrt": math.sqrt, "atan2": math.atan2,
        "radians": math.radians, "degrees": math.degrees,
        "floor": math.floor, "ceil": math.ceil,
        "abs": abs, "min": min, "max": max, "round": round,
        "np": np, "numpy": np, "random": random, "time": time, "colorsys": colorsys,
        "SoundStudio": SoundStudio,
        "UniversalSound": SoundStudio,
        "SoundEngine": SoundStudio,
        "CANVAS_WIDTH": target_w,
        "CANVAS_HEIGHT": target_h,
        "DURATION": duration
    }

    try:
        exec(compile(clean_code, scene_name, "exec"), exec_scope)
    except Exception as e:
        raise ValueError(f"Ошибка компиляции видео:\n{e}\n\nКод:\n{clean_code[:400]}")

    draw_frame = exec_scope.get("draw_frame")
    if not draw_frame or not callable(draw_frame):
        raise ValueError("В коде отсутствует функция draw_frame(ctx, t, w, h)!")
    build_audio = exec_scope.get("build_audio")

    w = int(exec_scope.get("CANVAS_WIDTH", target_w))
    h = int(exec_scope.get("CANVAS_HEIGHT", target_h))

    if not (16 <= w <= 4096 and 16 <= h <= 4096 and w % 2 == h % 2 == 0):
        raise ValueError("Размер кадра должен быть чётным и от 16 до 4096 пикселей.")
    if total_frames < 1:
        raise ValueError("Длительность слишком мала для выбранного FPS.")
    ffmpeg_bin = get_ffmpeg_binary()
    if not ffmpeg_bin:
        raise RuntimeError("FFmpeg не найден.")

    base_out = getattr(config, "OUTPUT_DIR", getattr(config, "OUTPUT_FOLDER", "output"))
    out_dir = os.path.join(base_out, "video")
    os.makedirs(out_dir, exist_ok=True)
    uid = uuid.uuid4().hex[:6]

    temp_v = os.path.join(out_dir, f"raw_{uid}.mp4")
    temp_a = os.path.join(out_dir, f"raw_{uid}.wav")
    final_mp4 = os.path.join(out_dir, f"video_{uid}.mp4")

    # 1. РЕНДЕРИНГ АУДИО
    sound = SoundStudio(duration=duration, sample_rate=sr)
    if build_audio and callable(build_audio):
        build_audio(sound)

    sound.export_wav(temp_a)

    audio_mono = np.mean(sound.master_buffer, axis=1) if len(sound.master_buffer) > 0 else np.zeros(1, dtype=np.float32)
    samples_per_frame = int(sr / fps)
    frame_energies = []

    for i in range(total_frames):
        s_start = i * samples_per_frame
        s_end = min(len(audio_mono), s_start + samples_per_frame)
        if s_end > s_start:
            chunk = audio_mono[s_start:s_end]
            rms = float(np.sqrt(np.mean(chunk**2))) * 4.2
            frame_energies.append(min(rms, 2.5))
        else:
            frame_energies.append(0.0)

    # 2. РЕНДЕРИНГ КАДРОВ
    fourcc = cv2.VideoWriter_fourcc(*'mp4v')
    vw = cv2.VideoWriter(temp_v, fourcc, fps, (w, h))

    if not vw.isOpened():
        raise RuntimeError("OpenCV не смог открыть MP4 для записи.")

    surface = cairo.ImageSurface(cairo.FORMAT_ARGB32, w, h)
    raw_ctx = cairo.Context(surface)
    raw_ctx.set_antialias(cairo.ANTIALIAS_BEST)
    safe_ctx = SafeCairoContext(raw_ctx)

    accepts_audio_param = False
    try:
        sig = inspect.signature(draw_frame)
        accepts_audio_param = (len(sig.parameters) >= 5) or any(
            p.name == "audio_level" for p in sig.parameters.values()
        )
    except Exception:
        accepts_audio_param = True

    last_valid_bgr = np.zeros((h, w, 3), dtype=np.uint8)
    error_logged = 0
    first_frame_error = None
    valid_frames = 0

    for i in range(total_frames):
        t = (i / float(fps)) % duration
        current_energy = frame_energies[i] if i < len(frame_energies) else 0.0

        try:
            raw_ctx.identity_matrix()
            raw_ctx.new_path()
            if accepts_audio_param:
                if strict_frames:
                    draw_frame(safe_ctx, t, w, h, current_energy)
                else:
                    try: draw_frame(safe_ctx, t, w, h, current_energy)
                    except TypeError: draw_frame(safe_ctx, t, w, h)
            else:
                draw_frame(safe_ctx, t, w, h)

            surface.flush()
            buf = surface.get_data()
            frame_bgra = np.ndarray(shape=(h, w, 4), dtype=np.uint8, buffer=buf)
            last_valid_bgr = frame_bgra[:, :, :3].copy()
            valid_frames += 1
        except Exception as e:
            if strict_frames:
                first_frame_error = (i, t, e)
                break
            if error_logged < 3:
                print(f"[!] Ошибка draw_frame на t={t:.2f}s: {e}")
                error_logged += 1

        vw.write(last_valid_bgr)

    vw.release()
    surface.finish()

    try:
        if first_frame_error is not None:
            frame, timestamp, exc = first_frame_error
            raise RuntimeError(f"Frame {frame} at {timestamp:.3f}s failed: {exc}") from exc
        if valid_frames == 0:
            raise RuntimeError("Сцена не смогла нарисовать ни одного кадра.")
        subprocess.run(
            [ffmpeg_bin, "-loglevel", "error", "-y", "-i", temp_v, "-i", temp_a,
             "-c:v", "libx264", "-preset", "ultrafast", "-pix_fmt", "yuv420p",
             "-c:a", "aac", "-b:a", "192k", "-shortest", final_mp4],
            check=True,
        )
    except Exception:
        if os.path.isfile(final_mp4):
            os.remove(final_mp4)
        raise
    finally:
        for temporary in (temp_v, temp_a):
            if os.path.isfile(temporary):
                os.remove(temporary)

    return {
        "type": "video",
        "video_path": final_mp4,
        "resolution": f"{w}x{h}",
        "duration": f"{duration:.1f}s",
        "fps": fps
    }