File size: 10,044 Bytes
ba91b08
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
"""FX engine — cinematic short-form frames (speed ramps, kinetic captions,
whip/zoom transitions, parallax, flash + shake + glitch, grain, progress bar).

Pure PIL/numpy so it runs on a free CPU Space. Frames are produced at 720x1280
and upscaled to 1080x1920 by ffmpeg (much cheaper than drawing at full res).

The module is standalone: app.py passes in its font loader so there is no
circular import and the existing renderer endpoints stay untouched.
"""

import io
import math
import random

import numpy as np
import requests
from PIL import Image, ImageDraw, ImageEnhance, ImageFilter

RW, RH = 720, 1280           # internal render size
UP = (1080, 1920)            # final size (ffmpeg scales)


# ---------------------------------------------------------------------------
# Image helpers
# ---------------------------------------------------------------------------
def cover(img: Image.Image, w=RW, h=RH) -> Image.Image:
    scale = max(w / img.width, h / img.height)
    nw, nh = max(w, int(img.width * scale)), max(h, int(img.height * scale))
    img = img.resize((nw, nh), Image.LANCZOS)
    left, top = (nw - w) // 2, (nh - h) // 2
    return img.crop((left, top, left + w, top + h))


def fetch_image(url: str, timeout=25):
    try:
        r = requests.get(url, timeout=timeout, headers={"User-Agent": "Mozilla/5.0"})
        r.raise_for_status()
        return Image.open(io.BytesIO(r.content)).convert("RGB")
    except Exception as e:
        print("fx: image failed", url, e, flush=True)
        return None


def gradient(top, bottom, w=RW, h=RH) -> Image.Image:
    ramp = np.linspace(0, 1, h, dtype=np.float32)[:, None]
    arr = (np.array(top, dtype=np.float32)[None, None, :] * (1 - ramp[:, :, None])
           + np.array(bottom, dtype=np.float32)[None, None, :] * ramp[:, :, None])
    return Image.fromarray(np.repeat(arr.astype(np.uint8), w, axis=1))


def hex_rgb(value, default=(18, 225, 182)):
    try:
        v = value.lstrip("#")
        return tuple(int(v[i:i + 2], 16) for i in (0, 2, 4))
    except Exception:
        return default


def ease_out(t):      # decelerate — the "landing" of a speed ramp
    return 1 - (1 - t) ** 3


def ease_ramp(t):     # slow -> fast -> slow (velocity edit feel)
    return t * t * (3 - 2 * t)


# ---------------------------------------------------------------------------
# Per-shot backdrop with ken-burns + parallax
# ---------------------------------------------------------------------------
def shot_frame(base: Image.Image, t: float, idx: int, zoom_style: str) -> Image.Image:
    """t in [0,1] within the shot."""
    p = ease_ramp(t)
    if zoom_style == "in":
        z = 1.06 + 0.16 * p
    elif zoom_style == "out":
        z = 1.22 - 0.16 * p
    else:  # parallax pan
        z = 1.16
    nw, nh = int(RW * z), int(RH * z)
    img = base.resize((nw, nh), Image.BILINEAR)
    max_dx, max_dy = nw - RW, nh - RH
    if zoom_style == "pan":
        dx = int(max_dx * (p if idx % 2 == 0 else 1 - p))
        dy = int(max_dy * 0.5)
    else:
        dx = int(max_dx * 0.5)
        dy = int(max_dy * (0.35 + 0.3 * p if idx % 2 == 0 else 0.65 - 0.3 * p))
    return img.crop((dx, dy, dx + RW, dy + RH))


def apply_shake(img: Image.Image, amount: float, rnd: random.Random) -> Image.Image:
    if amount <= 0:
        return img
    dx = int(rnd.uniform(-1, 1) * 18 * amount)
    dy = int(rnd.uniform(-1, 1) * 18 * amount)
    return img.transform(img.size, Image.AFFINE, (1, 0, dx, 0, 1, dy), resample=Image.BILINEAR)


def apply_glitch(img: Image.Image, amount: float) -> Image.Image:
    if amount <= 0:
        return img
    arr = np.array(img)
    off = max(1, int(16 * amount))
    arr[:, :, 0] = np.roll(arr[:, :, 0], off, axis=1)
    arr[:, :, 2] = np.roll(arr[:, :, 2], -off, axis=1)
    # scanline tears
    h = arr.shape[0]
    for band in range(3):
        y = int((band * 0.31 + amount) % 1 * (h - 40))
        arr[y:y + 12] = np.roll(arr[y:y + 12], int(off * 3), axis=1)
    return Image.fromarray(arr)


def apply_flash(img: Image.Image, amount: float, color=(255, 255, 255)) -> Image.Image:
    if amount <= 0:
        return img
    overlay = Image.new("RGB", img.size, color)
    return Image.blend(img, overlay, min(0.85, amount))


def whip_blur(img: Image.Image, amount: float) -> Image.Image:
    if amount <= 0:
        return img
    return img.filter(ImageFilter.GaussianBlur(radius=1 + 9 * amount))


VIGNETTE = None


def vignette(img: Image.Image) -> Image.Image:
    global VIGNETTE
    if VIGNETTE is None:
        y, x = np.mgrid[0:RH, 0:RW]
        cx, cy = RW / 2, RH / 2
        d = np.sqrt(((x - cx) / cx) ** 2 + ((y - cy) / cy) ** 2)
        VIGNETTE = np.clip(1.06 - 0.42 * d, 0.32, 1.0).astype(np.float32)[:, :, None]
    return Image.fromarray((np.array(img, dtype=np.float32) * VIGNETTE).astype(np.uint8))


def grain(img: Image.Image, strength=6.0) -> Image.Image:
    noise = np.random.normal(0, strength, (RH // 4, RW // 4, 1)).astype(np.float32)
    noise = np.kron(noise, np.ones((4, 4, 1), dtype=np.float32))[:RH, :RW]
    arr = np.clip(np.array(img, dtype=np.float32) + noise, 0, 255)
    return Image.fromarray(arr.astype(np.uint8))


# ---------------------------------------------------------------------------
# Kinetic typography
# ---------------------------------------------------------------------------
def wrap(draw, words, font, max_w):
    lines, cur = [], []
    for w in words:
        test = " ".join(cur + [w])
        if draw.textlength(test, font=font) <= max_w or not cur:
            cur.append(w)
        else:
            lines.append(cur)
            cur = [w]
    if cur:
        lines.append(cur)
    return lines


def draw_kinetic(img, text, t, font, accent, position=0.72, uppercase=True, pop=True):
    """Word-by-word reveal; the newest word pops in the accent colour."""
    if not text:
        return img
    words = (text.upper() if uppercase else text).split()
    if not words:
        return img
    draw = ImageDraw.Draw(img)
    shown = max(1, min(len(words), int(math.ceil(len(words) * min(1.0, t / 0.72)))))
    lines = wrap(draw, words[:shown], font, RW - 110)
    lh = int(font.size * 1.16)
    total_h = lh * len(lines)
    y = int(RH * position) - total_h // 2

    idx = 0
    for line in lines:
        line_w = draw.textlength(" ".join(line), font=font)
        x = (RW - line_w) / 2
        for w in line:
            idx += 1
            is_new = idx == shown
            colour = accent if is_new else (255, 255, 255)
            wid = draw.textlength(w + " ", font=font)
            if is_new and pop:
                layer = Image.new("RGBA", (int(wid) + 60, lh + 60), (0, 0, 0, 0))
                ld = ImageDraw.Draw(layer)
                ld.text((30, 20), w, font=font, fill=colour + (255,),
                        stroke_width=max(2, font.size // 12), stroke_fill=(0, 0, 0, 235))
                k = 1.0 + 0.22 * (1 - ease_out(min(1.0, (t % 1) * 6)))
                layer = layer.resize((int(layer.width * k), int(layer.height * k)), Image.BILINEAR)
                img.paste(layer, (int(x - (layer.width - wid) / 2), int(y - 20 - (layer.height - lh) / 2)), layer)
            else:
                draw.text((x, y), w, font=font, fill=colour,
                          stroke_width=max(2, font.size // 12), stroke_fill=(0, 0, 0))
            x += wid
        y += lh
    return img


def draw_progress(img, t, accent):
    d = ImageDraw.Draw(img)
    d.rectangle([0, 0, int(RW * t), 7], fill=accent)


# ---------------------------------------------------------------------------
# Main frame builder
# ---------------------------------------------------------------------------
def build_frames(shots, durations, fps, style, font_for):
    """shots: [{image_url, text}], durations: seconds per shot.

    style: accent, uppercase, caption_position, font_size, fx flags.
    font_for(size) -> PIL font.
    """
    accent = hex_rgb(style.get("accent", "#12E1B6"))
    uppercase = bool(style.get("uppercase", True))
    position = float(style.get("caption_position", 0.72))
    font = font_for(int(style.get("font_size") or 62))
    use_shake = style.get("shake", True)
    use_glitch = style.get("glitch", True)
    use_flash = style.get("flash", True)
    use_grain = style.get("grain", True)
    rnd = random.Random(1234)

    bases = []
    for i, shot in enumerate(shots):
        img = fetch_image(shot.get("image_url")) if shot.get("image_url") else None
        if img is None:
            img = gradient((22, 26, 38), (5, 6, 11))
        img = cover(img)
        img = ImageEnhance.Contrast(img).enhance(1.12)
        img = ImageEnhance.Color(img).enhance(1.15)
        bases.append(img)

    total = sum(durations)
    frames = []
    elapsed = 0.0
    for i, (base, dur) in enumerate(zip(bases, durations)):
        n = max(2, int(round(dur * fps)))
        zoom_style = ["in", "pan", "out"][i % 3]
        for f in range(n):
            t = f / max(1, n - 1)
            frame = shot_frame(base, t, i, zoom_style)
            cut_in = 1 - min(1.0, f / max(1.0, fps * 0.22))    # 1 -> 0 at shot start
            cut_out = 1 - min(1.0, (n - 1 - f) / max(1.0, fps * 0.18))
            if cut_in > 0:
                frame = whip_blur(frame, cut_in * 0.9)
                if use_shake:
                    frame = apply_shake(frame, cut_in * 0.8, rnd)
                if use_glitch and i % 2 == 1:
                    frame = apply_glitch(frame, cut_in * 0.7)
                if use_flash:
                    frame = apply_flash(frame, cut_in * 0.35, accent if i % 3 == 0 else (255, 255, 255))
            if cut_out > 0:
                frame = whip_blur(frame, cut_out * 0.6)
            frame = vignette(frame)
            frame = draw_kinetic(frame, shots[i].get("text", ""), t, font, accent, position, uppercase)
            draw_progress(frame, (elapsed + t * dur) / max(0.1, total), accent)
            if use_grain:
                frame = grain(frame, 5.0)
            frames.append(frame)
        elapsed += dur
    return frames