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
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
from __future__ import annotations

import math
import uuid

import moviepy.editor as mpe
import numpy as np
from PIL import Image, ImageDraw, ImageFont, ImageColor

# ----------------------------
# Шрыфты
# ----------------------------
AVAILABLE_FONTS = {
    "DejaVuSans-Bold": "/usr/share/fonts/truetype/dejavu/DejaVuSans-Bold.ttf",
    "DejaVuSans": "/usr/share/fonts/truetype/dejavu/DejaVuSans.ttf",
    "LiberationSerif-Bold": "/usr/share/fonts/truetype/liberation/LiberationSerif-Bold.ttf",
    "BadScript-Regular": "fonts/Bad_Script/BadScript-Regular.ttf",
    "Gidole-Regular": "fonts/Gidole/Gidole-Regular.ttf",
    "GreatVibes-Regular": "fonts/Great_Vibes/GreatVibes-Regular.ttf",
    "OpenSans-Variable": "fonts/Open_Sans/OpenSans-VariableFont_wdth,wght.ttf",
    "OpenSans-Italic-Variable": "fonts/Open_Sans/OpenSans-Italic-VariableFont_wdth,wght.ttf",
    "Roboto-Variable": "fonts/Roboto/Roboto-VariableFont_wdth,wght.ttf",
    "Roboto-Italic-Variable": "fonts/Roboto/Roboto-Italic-VariableFont_wdth,wght.ttf",
    "SourceCodePro-Variable": "fonts/Source_Code_Pro/SourceCodePro-VariableFont_wght.ttf",
    "SourceCodePro-Italic-Variable": "fonts/Source_Code_Pro/SourceCodePro-Italic-VariableFont_wght.ttf",
    "Tektur-Variable": "fonts/Tektur/Tektur-VariableFont_wdth,wght.ttf",
    "Ponomar-Regular": "fonts/Ponomar/Ponomar-Regular.ttf",
}


# ----------------------------
# Колер -> RGB
# ----------------------------
def hex_to_rgb(color_str: str):
    try:
        return ImageColor.getrgb(color_str)
    except Exception:
        pass

    lower = (color_str or "").lower()
    if lower.startswith("rgba") or lower.startswith("rgb"):
        inside = color_str[color_str.find("(") + 1 : color_str.rfind(")")]
        parts = [p.strip() for p in inside.split(",")]
        if len(parts) >= 3:
            try:
                r, g, b = [int(float(parts[i])) for i in range(3)]
                return (r, g, b)
            except Exception:
                pass

    c = (color_str or "#FFFFFF").lstrip("#")
    if len(c) == 3:
        c = "".join([ch * 2 for ch in c])
    return tuple(int(c[i : i + 2], 16) for i in (0, 2, 4))


# ----------------------------
# SRT-парсінг
# ----------------------------
def srt_time_to_sec(time_str):
    t = time_str.strip().replace(".", ",")
    if "," not in t:
        t += ",000"
    h, m, s_ms = t.split(":")
    s, ms = s_ms.split(",")
    return int(h) * 3600 + int(m) * 60 + int(s) + int(ms) / 1000


def parse_srt_from_text(srt_text):
    subs = []
    normalized = (srt_text or "").replace("\r\n", "\n").replace("\r", "\n")
    for block in normalized.strip().split("\n\n"):
        lines = block.splitlines()
        if len(lines) < 3:
            continue
        times = lines[1]
        try:
            start_str, end_str = times.split("-->")
            start = srt_time_to_sec(start_str)
            end = srt_time_to_sec(end_str)
            text = "\n".join(lines[2:]).strip()  # захоўваем пераносы
            subs.append({"start": start, "end": end, "text": text})
        except Exception:
            continue
    return subs


# ----------------------------
# Wrap: аўтаматычны перанос радкоў па шырыні кадра
# ----------------------------
def _line_width_px(draw: ImageDraw.ImageDraw, line: str, font: ImageFont.ImageFont, stroke_width: int = 0) -> int:
    try:
        l, t, r, b = draw.textbbox((0, 0), line, font=font, stroke_width=stroke_width)
        return int(r - l)
    except Exception:
        try:
            w = draw.textlength(line, font=font)
            return int(w + 2 * stroke_width)
        except Exception:
            w, _ = draw.textsize(line, font=font)
            return int(w + 2 * stroke_width)


def _break_long_word(draw, word: str, font, max_width: int, stroke_width: int) -> list:
    chunks = []
    cur = ""
    for ch in word:
        test = cur + ch
        if cur and _line_width_px(draw, test, font, stroke_width) > max_width:
            chunks.append(cur)
            cur = ch
        else:
            cur = test
    if cur:
        chunks.append(cur)
    return chunks


def wrap_text_to_width(text: str, draw: ImageDraw.ImageDraw, font: ImageFont.ImageFont,
                       max_width: int, stroke_width: int = 0) -> str:
    if not text:
        return text

    paragraphs = (text or "").split("\n")
    out_lines = []

    for para in paragraphs:
        p = para.strip()
        if not p:
            out_lines.append("")
            continue

        words = p.split()
        line = ""
        for w in words:
            if not line:
                if _line_width_px(draw, w, font, stroke_width) <= max_width:
                    line = w
                else:
                    chunks = _break_long_word(draw, w, font, max_width, stroke_width)
                    out_lines.extend(chunks[:-1])
                    line = chunks[-1] if chunks else ""
                continue

            test = f"{line} {w}"
            if _line_width_px(draw, test, font, stroke_width) <= max_width:
                line = test
            else:
                out_lines.append(line)
                if _line_width_px(draw, w, font, stroke_width) <= max_width:
                    line = w
                else:
                    chunks = _break_long_word(draw, w, font, max_width, stroke_width)
                    out_lines.extend(chunks[:-1])
                    line = chunks[-1] if chunks else ""

        if line:
            out_lines.append(line)

    return "\n".join(out_lines)


# ----------------------------
# Тэкставы кліп (PIL -> moviepy), без абразання
# ----------------------------
def _measure_multiline_bbox(draw, text, font, stroke_width=0, spacing=4):
    try:
        return draw.multiline_textbbox(
            (0, 0),
            text,
            font=font,
            stroke_width=stroke_width,
            spacing=spacing,
            align="center",
        )
    except Exception:
        pass

    try:
        return draw.textbbox((0, 0), text, font=font, stroke_width=stroke_width)
    except Exception:
        pass

    w, h = draw.textsize(text, font=font)
    h = h + max(2, stroke_width + 2)
    return (0, 0, w, h)


def _clamp(v: float, lo: float, hi: float) -> float:
    return max(lo, min(hi, v))


def create_animated_text_clip(
    text,
    duration,
    font,
    fontsize,
    color,
    stroke_color,
    stroke_width,
    position_type,
    custom_x_shift,  # ЗРУХ X (адносна цэнтра)
    custom_y,
    animation,
    video_width,
    video_height,
    bg_color=None,
    bg_opacity=1.0,
    wrap_ratio: float = 0.90,
):
    try:
        txt_rgb = hex_to_rgb(color)
    except Exception:
        txt_rgb = (255, 255, 255)

    try:
        stroke_rgb = hex_to_rgb(stroke_color)
    except Exception:
        stroke_rgb = (0, 0, 0)

    if bg_color:
        try:
            bg_rgb = hex_to_rgb(bg_color)
        except Exception:
            bg_rgb = (0, 0, 0)
        bg_a = int(max(0.0, min(1.0, bg_opacity)) * 255)
    else:
        bg_rgb = (0, 0, 0)
        bg_a = 0

    try:
        pil_font = ImageFont.truetype(font, fontsize)
    except Exception:
        pil_font = ImageFont.load_default()

    dummy_img = Image.new("RGBA", (10, 10), (0, 0, 0, 0))
    dummy_draw = ImageDraw.Draw(dummy_img)

    spacing = max(0, int(fontsize * 0.15))

    # --- AUTO WRAP ---
    max_text_width = max(200, int(video_width * float(wrap_ratio)))
    wrapped_text = wrap_text_to_width(text, dummy_draw, pil_font, max_text_width, stroke_width=stroke_width)

    # --- BBOX ---
    l, t, r, b = _measure_multiline_bbox(dummy_draw, wrapped_text, pil_font, stroke_width=stroke_width, spacing=spacing)
    text_w = r - l
    text_h = b - t

    pad_x = max(10, int(fontsize * 0.25))
    pad_y = max(6, int(fontsize * 0.20))
    safe = max(2, int(stroke_width) + 3)

    img_w = int(math.ceil(text_w + 2 * (pad_x + safe)))
    img_h = int(math.ceil(text_h + 2 * (pad_y + safe)))

    img = Image.new("RGBA", (img_w, img_h), bg_rgb + (bg_a,))
    draw = ImageDraw.Draw(img)

    # галоўнае: улічваем bbox (можа быць адмоўны)
    text_x = (pad_x + safe) - l
    text_y = (pad_y + safe) - t

    draw.multiline_text(
        (text_x, text_y),
        wrapped_text,
        font=pil_font,
        fill=txt_rgb + (255,),
        stroke_width=stroke_width,
        stroke_fill=stroke_rgb + (255,),
        spacing=spacing,
        align="center",
    )

    arr = np.array(img)
    rgb = arr[..., :3]
    alpha = arr[..., 3].astype(np.float32) / 255.0

    clip = mpe.ImageClip(rgb, ismask=False).set_duration(duration)
    mask = mpe.ImageClip(alpha, ismask=True).set_duration(duration)
    clip = clip.set_mask(mask)

    # --- Пазіцыя (аптымізавана) ---
    # верх/ніз ссоўваем да цэнтра на 15% вышыні кадра
    center_pull = 0.15 * float(video_height)
    base_x_center = (video_width - clip.w) / 2

    if position_type == "bottom":
        x = base_x_center
        y = (video_height - clip.h - 20) - center_pull
    elif position_type == "top":
        x = base_x_center
        y = 20 + center_pull
    elif position_type == "center":
        x = base_x_center
        y = (video_height - clip.h) / 2
    else:  # custom: Х заўсёды ад цэнтра (як ва ўсіх), custom_x_shift — дадатковы зрух
        x = base_x_center + float(custom_x_shift)
        y = float(custom_y)

    # clamp, каб не вылятала за кадр
    x = _clamp(x, 0, max(0, video_width - clip.w))
    y = _clamp(y, 0, max(0, video_height - clip.h))

    anim = (animation or "").lower()

    if anim == "fade":
        fd = min(0.5, duration / 2)
        clip = clip.fadein(fd).fadeout(fd)
        return clip.set_position((x, y))
    elif anim == "slide":
        fd = min(0.5, duration / 2)

        def slide_pos(t_):
            progress = min(max(t_ / fd, 0), 1)
            return -clip.w + (x + clip.w) * progress, y

        return clip.set_position(slide_pos)
    elif anim == "zoom":
        clip = clip.resize(lambda t_: 0.5 + 0.5 * min(max(t_ / duration, 0), 1))
        return clip.set_position((x, y))
    else:
        return clip.set_position((x, y))


# ----------------------------
# Накладанне субтытраў
# ----------------------------
def apply_subtitles(
    video_path,
    subtitles_text,
    font,
    fontsize,
    color,
    stroke_color,
    stroke_width,
    position_type,
    custom_x_shift,
    custom_y,
    animation,
    export_quality,
    bg_color=None,
    bg_opacity=1.0,
    wrap_ratio: float = 0.90,
):
    subs = parse_srt_from_text(subtitles_text)
    video = mpe.VideoFileClip(video_path)
    w, h = video.w, video.h

    clips = [video]
    for s in subs:
        dur = s["end"] - s["start"]
        if dur <= 0:
            continue
        txt_clip = create_animated_text_clip(
            s["text"],
            dur,
            font,
            fontsize,
            color,
            stroke_color,
            stroke_width,
            position_type,
            custom_x_shift,
            custom_y,
            animation,
            w,
            h,
            bg_color=bg_color,
            bg_opacity=bg_opacity,
            wrap_ratio=wrap_ratio,
        ).set_start(s["start"])
        clips.append(txt_clip)

    final = mpe.CompositeVideoClip(clips)

    if export_quality == "мінімальнае":
        final = final.resize(height=480)
    elif export_quality == "сярэдняе":
        final = final.resize(height=720)
    elif export_quality == "максімальнае" and h < 1080:
        final = final.resize(height=1080)

    out = f"output_video_{uuid.uuid4().hex}.mp4"
    try:
        final.write_videofile(out, fps=video.fps, codec="libx264", audio_codec="aac")
    finally:
        video.close()
        final.close()
    return out


# ----------------------------
# Перадпрагляд (1 секунда)
# ----------------------------
def extract_first_frame(video_path):
    try:
        clip = mpe.VideoFileClip(video_path)
        frame = clip.get_frame(0)
        clip.close()
        return frame
    except Exception:
        return None


def create_single_frame_video(
    frame,
    text,
    font,
    fontsize,
    color,
    stroke_color,
    stroke_width,
    position_type,
    custom_x_shift,
    custom_y,
    animation,
    bg_color=None,
    bg_opacity=1.0,
    wrap_ratio: float = 0.90,
):
    if frame is None:
        return None

    h, w, _ = frame.shape
    base = mpe.ImageClip(frame).set_duration(1.0)

    txt_clip = create_animated_text_clip(
        text,
        1.0,
        font,
        fontsize,
        color,
        stroke_color,
        stroke_width,
        position_type,
        custom_x_shift,
        custom_y,
        animation,
        w,
        h,
        bg_color=bg_color,
        bg_opacity=bg_opacity,
        wrap_ratio=wrap_ratio,
    )

    final_clip = mpe.CompositeVideoClip([base, txt_clip])
    path = f"preview_video_{uuid.uuid4().hex}.mp4"
    try:
        final_clip.write_videofile(
            path,
            fps=24,
            codec="libx264",
            audio=False,
            verbose=False,
            logger=None,
        )
    finally:
        final_clip.close()
    return path