"""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