Download app.py from aralawrence11/tiny-talking-face-cpu-lovable: direct link, hf CLI and curl.
- Browser
- Download file 71.6 kB
-
https://huggingface.co/spaces/aralawrence11/tiny-talking-face-cpu-lovable/resolve/main/app.py
- Command line
-
hf download hf://spaces/aralawrence11/tiny-talking-face-cpu-lovable/app.py
-
curl -L -o app.py https://huggingface.co/spaces/aralawrence11/tiny-talking-face-cpu-lovable/resolve/main/app.py
71.6 kB
import os, subprocess, uuid, random, tempfile, shutil
from fastapi import FastAPI, HTTPException, Request
from fastapi.responses import FileResponse, Response
from pydantic import BaseModel
import requests
import numpy as np
import soundfile as sf
app = FastAPI()
RENDERS_DIR = "/tmp/renders"
os.makedirs(RENDERS_DIR, exist_ok=True)
# ---------------------------------------------------------------------------
# Fonts
# ---------------------------------------------------------------------------
FONT_CANDIDATES = {
"montserrat": ["/usr/share/fonts/truetype/liberation/LiberationSans-Bold.ttf"],
"poppins": ["/usr/share/fonts/truetype/liberation/LiberationSans-Bold.ttf"],
"anton": ["/usr/share/fonts/truetype/freefont/FreeSansBold.ttf"],
"impact": ["/usr/share/fonts/truetype/freefont/FreeSansBold.ttf"],
"oswald": ["/usr/share/fonts/truetype/liberation/LiberationSansNarrow-Bold.ttf"],
"bebas": ["/usr/share/fonts/truetype/liberation/LiberationSansNarrow-Bold.ttf"],
"roboto": ["/usr/share/fonts/truetype/liberation/LiberationSans-Bold.ttf"],
"dejavu sans":["/usr/share/fonts/truetype/dejavu/DejaVuSans-Bold.ttf"],
"serif": ["/usr/share/fonts/truetype/dejavu/DejaVuSerif-Bold.ttf"],
}
FALLBACK_FONT = "/usr/share/fonts/truetype/dejavu/DejaVuSans-Bold.ttf"
def resolve_font(name):
key = (name or "").strip().lower()
for cand in FONT_CANDIDATES.get(key, []):
if os.path.exists(cand):
return cand
return FALLBACK_FONT
# --- Kokoro TTS (lazy-loaded singleton) ---
_kokoro = {"pipe": None}
def get_kokoro(lang_code="a"):
if _kokoro["pipe"] is None:
from kokoro import KPipeline
_kokoro["pipe"] = KPipeline(lang_code=lang_code)
return _kokoro["pipe"]
class TTSReq(BaseModel):
text: str
voice: str | None = "af_bella"
speed: float | None = 1.0
class RenderReq(BaseModel):
voice_url: str
script: str
hook: str | None = None
onscreen_cta: str | None = None
# Style
font: str | None = "Montserrat"
caption_style: str | None = "bold_center"
caption_color: str | None = "#FFFFFF"
title_color: str | None = "#FFFFFF"
cta_color: str | None = "#FFD54A"
accent_color: str | None = "#FFD54A"
background: str | None = "black"
subtitle_size: int | None = 64
title_size: int | None = 88
cta_size: int | None = 56
stroke_width: float | None = 5
shadow: bool | None = True
box_opacity: float | None = 0.55
uppercase: bool | None = False
animation: str | None = "subtle_zoom"
# Caption reveal: "phrase" (one go) | "word" (one word at a time) | "karaoke" (words build up)
caption_animation: str | None = "phrase"
# Placement (fractions of the 1920px-tall canvas)
title_position: float | None = 0.13
caption_position: float | None = 0.63
cta_position: float | None = 0.56
safe_top: float | None = 0.10
safe_bottom: float | None = 0.24
max_seconds: int | None = 60
# Section branding outro
brand_link: str | None = None
brand_text: str | None = None
brand_duration: int | None = 0
seed: int | None = None
@app.get("/")
def root():
return {"ok": True, "service": "shorts-renderer", "version": 4,
"caption_animations": ["phrase", "word", "karaoke"]}
@app.get("/health")
def health():
return {"ok": True}
@app.post("/tts")
def tts(req: TTSReq):
voice = req.voice or "af_bella"
lang = voice[0] if voice else "a"
try:
pipe = get_kokoro(lang_code=lang)
chunks = []
for _gs, _ps, audio in pipe(req.text, voice=voice, speed=req.speed or 1.0):
arr = audio.detach().cpu().numpy() if hasattr(audio, "detach") else np.asarray(audio)
chunks.append(arr)
if not chunks:
raise HTTPException(500, "Kokoro produced no audio")
wav = np.concatenate(chunks).astype(np.float32)
job = str(uuid.uuid4())
wav_path = os.path.join(RENDERS_DIR, f"{job}.wav")
mp3_path = os.path.join(RENDERS_DIR, f"{job}.mp3")
sf.write(wav_path, wav, 24000)
subprocess.run(["ffmpeg","-y","-i",wav_path,"-b:a","128k",mp3_path],
check=True, capture_output=True, timeout=120)
with open(mp3_path,"rb") as f:
data = f.read()
try: os.remove(wav_path)
except OSError: pass
return Response(content=data, media_type="audio/mpeg")
except HTTPException:
raise
except Exception as e:
raise HTTPException(500, f"tts failed: {type(e).__name__}: {str(e)[:400]}")
def probe_duration(path):
try:
out = subprocess.check_output([
"ffprobe","-v","error","-show_entries","format=duration",
"-of","default=noprint_wrappers=1:nokey=1", path
], timeout=60).decode().strip()
return float(out or "0")
except Exception:
return 0.0
# ---- color helpers ----
def hex_to_ff(color, default="0xFFFFFF"):
if not color: return default
c = color.strip()
if c.startswith("#") and len(c) == 7:
return "0x" + c[1:].upper()
if c.lower() in ("black","white","red","yellow"):
return c.lower()
return default
def hex_to_ass(color, default="&H00FFFFFF"):
if not color: return default
c = color.strip().lstrip("#")
if len(c) != 6: return default
r, g, b = c[0:2], c[2:4], c[4:6]
return f"&H00{b}{g}{r}".upper()
def solid_bg(background):
b = (background or "black").strip().lower()
if b == "white": return "white"
if b.startswith("#") and len(b) == 7: return "0x" + b[1:].upper()
if b in ("black","gray","navy"): return b
return "black"
def build_caption_entries(script, duration, upper, mode):
"""Return timed caption entries covering the WHOLE narration so nothing is cut.
modes:
- "phrase" (default): 3-4 words shown together in one go.
- "word": one word at a time.
- "karaoke": words build up inside a line, then the line resets.
Word timings are proportional to word length for tighter audio sync.
"""
words = script.split()
if upper: words = [w.upper() for w in words]
if not words: words = [script.strip() or " "]
mode = (mode or "phrase").strip().lower()
weights = [max(2, len(w)) for w in words]
wsum = float(sum(weights)) or 1.0
starts, t = [], 0.0
for wt in weights:
starts.append(t); t += duration * wt / wsum
ends = starts[1:] + [duration]
entries = [] # (start, end, text)
if mode == "word":
for i, w in enumerate(words):
entries.append((starts[i], ends[i], w))
elif mode == "karaoke":
LINE = 5
i = 0
while i < len(words):
grp_start = i
grp_end = min(i + LINE, len(words))
for gi in range(grp_start, grp_end):
entries.append((starts[gi], ends[gi], " ".join(words[grp_start:gi + 1])))
i += LINE
else: # phrase / one-go
SIZE = 4
i = 0
while i < len(words):
grp_end = min(i + SIZE, len(words))
entries.append((starts[i], ends[grp_end - 1], " ".join(words[i:grp_end])))
i += SIZE
# Guarantee a minimum visible window and no gaps/overlaps.
fixed = []
for idx, (s, e, txt) in enumerate(entries):
e = max(e, s + 0.25)
fixed.append((round(s, 3), round(e, 3), txt))
return fixed
def esc(t): return t.replace("\\","\\\\").replace(":","\\:").replace("'","\u2019")
@app.post("/render")
def render(req: RenderReq):
job = str(uuid.uuid4())
voice_path = os.path.join(RENDERS_DIR, f"{job}.mp3")
main_path = os.path.join(RENDERS_DIR, f"{job}_main.mp4")
out_path = os.path.join(RENDERS_DIR, f"{job}.mp4")
srt_path = os.path.join(RENDERS_DIR, f"{job}.srt")
try:
r = requests.get(req.voice_url, timeout=60)
except Exception as e:
raise HTTPException(400, f"voice fetch error: {str(e)[:200]}")
if r.status_code != 200 or len(r.content) < 500:
raise HTTPException(400, f"voice fetch failed {r.status_code} ({len(r.content)} bytes)")
with open(voice_path,"wb") as f: f.write(r.content)
audio_dur = probe_duration(voice_path)
if audio_dur <= 0:
raise HTTPException(400, "voice_url did not return decodable audio")
# Cover the FULL narration (never truncate captions); only a generous hard cap.
hard_cap = float(req.max_seconds or 60)
hard_cap = max(hard_cap, 60.0)
duration = max(3.0, min(hard_cap, audio_dur))
upper = bool(req.uppercase)
entries = build_caption_entries(req.script, duration, upper, req.caption_animation)
font = resolve_font(req.font)
title_c = hex_to_ff(req.title_color, "0xFFFFFF")
cta_c = hex_to_ff(req.cta_color, "0xFFD54A")
cap_c = hex_to_ff(req.caption_color, "0xFFFFFF")
box_op = max(0.0, min(1.0, float(req.box_opacity if req.box_opacity is not None else 0.55)))
stroke = int(max(0, min(12, float(req.stroke_width or 4))))
title_size = int(req.title_size or 88)
sub_size = int(req.subtitle_size or 64)
cta_size = int(req.cta_size or 56)
y_cap = int(max(0.0, min(1.0, float(req.caption_position or 0.63))) * 1920)
y_title = int(max(0.0, min(1.0, float(req.title_position or 0.13))) * 1920)
y_cta = int(max(0.0, min(1.0, float(req.cta_position or 0.56))) * 1920)
hook = (req.hook or "").strip()
cta = (req.onscreen_cta or "").strip()
if upper:
hook, cta = hook.upper(), cta.upper()
drawtexts = []
if hook:
# Fixed headline for the whole clip while captions flow underneath.
drawtexts.append(
f"drawtext=fontfile={font}:text='{esc(hook)}':fontcolor={title_c}:fontsize={title_size}:"
f"borderw={stroke}:bordercolor=black:x=(w-text_w)/2:y={y_title}:"
f"box=1:boxcolor=black@{box_op}:boxborderw=24:line_spacing=10"
)
if cta:
drawtexts.append(
f"drawtext=fontfile={font}:text='{esc(cta)}':fontcolor={cta_c}:fontsize={cta_size}:"
f"borderw={stroke}:bordercolor=black:x=(w-text_w)/2:y={y_cta}:"
f"box=1:boxcolor=black@{box_op}:boxborderw=18"
)
# Flowing captions as time-gated drawtext (reliable: no libass/subtitles dependency).
for (s, e, txt) in entries:
drawtexts.append(
f"drawtext=fontfile={font}:text='{esc(txt)}':fontcolor={cap_c}:fontsize={sub_size}:"
f"borderw={max(1,stroke)}:bordercolor=black:x=(w-text_w)/2:y={y_cap}:"
f"box=1:boxcolor=black@{box_op}:boxborderw=18:enable='between(t,{s},{e})'"
)
vf = ",".join(drawtexts) if drawtexts else "null"
bg = solid_bg(req.background)
anim = (req.animation or "").lower()
zoom = "zoompan=z='min(zoom+0.0008,1.15)':d=1:s=1080x1920" if "zoom" in anim else "scale=1080:1920"
bg_filter = f"color=c={bg}:s=1080x1920:d={duration},{zoom}"
cmd = [
"ffmpeg","-y","-f","lavfi","-i", bg_filter,"-i", voice_path,
"-vf", vf,"-c:v","libx264","-preset","veryfast","-pix_fmt","yuv420p",
"-c:a","aac","-b:a","128k","-shortest","-t", f"{duration}","-r","30", main_path,
]
try:
subprocess.run(cmd, check=True, capture_output=True, timeout=300)
except subprocess.CalledProcessError as e:
raise HTTPException(500, f"ffmpeg failed: {e.stderr.decode()[-500:]}")
# ---- Optional section-branding outro (black screen + link) ----
brand_secs = int(req.brand_duration or 0)
if brand_secs > 0 and (req.brand_text or req.brand_link):
outro_path = os.path.join(RENDERS_DIR, f"{job}_outro.mp4")
line1 = esc((req.brand_text or "").strip().upper() if upper else (req.brand_text or "").strip())
line2 = esc((req.brand_link or "").strip())
dts = []
if line1:
dts.append(f"drawtext=fontfile={font}:text='{line1}':fontcolor=white:fontsize=64:"
f"borderw=3:bordercolor=black:x=(w-text_w)/2:y=(h/2)-90")
if line2:
dts.append(f"drawtext=fontfile={font}:text='{line2}':fontcolor={hex_to_ff(req.accent_color,'0xFFD54A')}:"
f"fontsize=52:borderw=3:bordercolor=black:x=(w-text_w)/2:y=(h/2)+20")
ovf = ",".join(["fade=t=in:st=0:d=0.4"] + dts) if dts else "fade=t=in:st=0:d=0.4"
ocmd = [
"ffmpeg","-y",
"-f","lavfi","-i", f"color=c=black:s=1080x1920:d={brand_secs}:r=30",
"-f","lavfi","-i", f"anullsrc=channel_layout=stereo:sample_rate=44100",
"-vf", ovf,"-c:v","libx264","-preset","veryfast","-pix_fmt","yuv420p",
"-c:a","aac","-b:a","128k","-t", f"{brand_secs}", outro_path,
]
try:
subprocess.run(ocmd, check=True, capture_output=True, timeout=120)
concat_txt = os.path.join(RENDERS_DIR, f"{job}_list.txt")
with open(concat_txt,"w") as f:
f.write(f"file '{main_path}'\nfile '{outro_path}'\n")
subprocess.run(
["ffmpeg","-y","-f","concat","-safe","0","-i",concat_txt,
"-c:v","libx264","-preset","veryfast","-pix_fmt","yuv420p",
"-c:a","aac","-b:a","128k", out_path],
check=True, capture_output=True, timeout=180,
)
except subprocess.CalledProcessError:
os.replace(main_path, out_path)
else:
os.replace(main_path, out_path)
return FileResponse(out_path, media_type="video/mp4", filename=f"{job}.mp4")
@app.get("/file/{name}")
def get_file(name: str):
p = os.path.join(RENDERS_DIR, name)
if not os.path.exists(p): raise HTTPException(404)
return FileResponse(p, media_type="video/mp4")
# ==========================================================================
# Template-video engine (merged from template-generator). Adds /templates and
# /render-template without touching the existing /render, /tts, /health routes.
# ==========================================================================
from pathlib import Path
from typing import Optional
import re
import time as _time
import json as _json
import io
from PIL import Image, ImageDraw, ImageFont
ROOT = Path(__file__).resolve().parent
FONT_DIR = ROOT / "fonts"
W, H = 1080, 1920
FPS = 20
KOKORO_VOICES = [
"af_heart", "af_bella", "af_nicole", "af_sarah", "af_sky", "af_alloy",
"af_aoede", "af_jessica", "af_kore", "af_nova", "af_river",
"am_adam", "am_michael", "am_echo", "am_eric", "am_fenrir",
"am_liam", "am_onyx", "am_puck", "am_santa",
"bf_emma", "bf_isabella", "bf_alice", "bf_lily",
"bm_george", "bm_lewis", "bm_daniel", "bm_fable",
]
DEFAULT_VOICE = "af_heart"
TEMPLATES = [
"atmospheric_text_hook",
"tweet_thread",
"notes_app",
"fullscreen_title_hook",
]
YELLOW = (255, 212, 0)
NAVY = (10, 14, 30)
NAVY2 = (18, 24, 48)
CREAM = (247, 240, 222)
# (single FastAPI instance defined above; do not re-create it here)
# ---------------------------------------------------------------------------
# Auth (optional bearer for private-Space friendliness; open if no key set)
# ---------------------------------------------------------------------------
SPACE_KEY = os.environ.get("SPACE_AUTH_KEY", "").strip()
def _check_auth(req: Request) -> bool:
if not SPACE_KEY:
return True
auth = req.headers.get("authorization", "")
return auth.replace("Bearer ", "").strip() == SPACE_KEY
# ---------------------------------------------------------------------------
# Fonts
# ---------------------------------------------------------------------------
def _font(name: str, size: int) -> ImageFont.FreeTypeFont:
path = FONT_DIR / name
try:
if path.exists():
return ImageFont.truetype(str(path), size)
except Exception:
pass
for fallback in ["/usr/share/fonts/truetype/dejavu/DejaVuSans-Bold.ttf"]:
if Path(fallback).exists():
return ImageFont.truetype(fallback, size)
return ImageFont.load_default()
def anton(size):
return _font("Anton.ttf", size)
def bebas(size):
return _font("BebasNeue.ttf", size)
def archivo(size):
return _font("ArchivoBlack.ttf", size)
def inter(size):
f = FONT_DIR / "Inter-Bold.ttf"
return _font("Inter-Bold.ttf" if f.exists() else "ArchivoBlack.ttf", size)
# ---------------------------------------------------------------------------
# Kokoro TTS
# ---------------------------------------------------------------------------
def synth(text: str, voice: str) -> tuple[np.ndarray, int]:
"""Synthesize one segment of text -> (float32 mono samples, sample_rate).
Reuses the shared Kokoro pipeline singleton (get_kokoro) from the base app."""
text = (text or "").strip()
if not text:
return np.zeros(int(24000 * 0.3), dtype=np.float32), 24000
v = voice if voice in KOKORO_VOICES else DEFAULT_VOICE
try:
pipe = get_kokoro(lang_code=v[0] if v else "a")
chunks = []
for _, _, audio in pipe(text, voice=v):
arr = audio.detach().cpu().numpy() if hasattr(audio, "detach") else np.asarray(audio)
chunks.append(arr.astype(np.float32))
if not chunks:
raise RuntimeError("empty kokoro output")
return np.concatenate(chunks), 24000
except Exception as e:
print("Kokoro TTS (template) failed, using silence fallback:", e, flush=True)
approx = max(0.6, len(text.split()) / 2.5)
return np.zeros(int(24000 * approx), dtype=np.float32), 24000
def synth_segments(lines: list[str], voice: str, gap_s: float = 0.18) -> tuple[np.ndarray, int, list[float]]:
"""Synthesize each line separately so segment durations are exact.
Returns (full_audio, sr, per_segment_duration_including_gap)."""
sr = 24000
audio_parts = []
durations = []
gap = np.zeros(int(sr * gap_s), dtype=np.float32)
for i, line in enumerate(lines):
a, sr = synth(line, voice)
dur = len(a) / sr
audio_parts.append(a)
if i < len(lines) - 1:
audio_parts.append(gap)
dur += gap_s
durations.append(dur)
full = np.concatenate(audio_parts) if audio_parts else np.zeros(1, dtype=np.float32)
return full, sr, durations
# ---------------------------------------------------------------------------
# Text helpers
# ---------------------------------------------------------------------------
def split_sentences(text: str, max_items: int) -> list[str]:
text = (text or "").strip()
if not text:
return []
parts = [p.strip() for p in re.split(r"(?<=[.!?])\s+|\n+", text) if p.strip()]
if not parts:
parts = [text]
return parts[:max_items]
def wrap_text(text: str, font: ImageFont.FreeTypeFont, max_width: int, draw: ImageDraw.ImageDraw) -> list[str]:
words = text.split()
lines, cur = [], ""
for w in words:
test = (cur + " " + w).strip()
if draw.textlength(test, font=font) <= max_width or not cur:
cur = test
else:
lines.append(cur)
cur = w
if cur:
lines.append(cur)
return lines
def draw_text_block(draw, xy_center, lines, font, fill, max_width, line_spacing=1.08,
stroke_width=0, stroke_fill=None, align="center"):
cx, cy = xy_center
sizes = [draw.textbbox((0, 0), ln, font=font, stroke_width=stroke_width) for ln in lines]
heights = [b[3] - b[1] for b in sizes]
total_h = sum(heights) * line_spacing
y = cy - total_h / 2
for ln, h in zip(lines, heights):
w = draw.textlength(ln, font=font)
x = cx - w / 2
draw.text((x, y), ln, font=font, fill=fill, stroke_width=stroke_width, stroke_fill=stroke_fill)
y += h * line_spacing
return y
def gradient_bg(top, bottom):
img = Image.new("RGB", (W, H), top)
px = img.load()
for y in range(H):
t = y / H
r = int(top[0] + (bottom[0] - top[0]) * t)
g = int(top[1] + (bottom[1] - top[1]) * t)
b = int(top[2] + (bottom[2] - top[2]) * t)
for x in range(0, W, 4):
px[x, y] = (r, g, b)
# cheap horizontal fill (speed): stretch every 4th column
arr = np.array(img)
for i in range(1, 4):
arr[:, i::4] = arr[:, 0::4][:, : arr[:, i::4].shape[1]]
return Image.fromarray(arr)
def load_background_image(url: Optional[str]) -> Optional[Image.Image]:
if not url:
return None
try:
r = requests.get(url, timeout=20)
r.raise_for_status()
img = Image.open(io.BytesIO(r.content)).convert("RGB")
# cover-fit into 1080x1920
scale = max(W / img.width, H / img.height)
nw, nh = int(img.width * scale), int(img.height * scale)
img = img.resize((nw, nh))
left = (nw - W) // 2
top = (nh - H) // 2
return img.crop((left, top, left + W, top + H))
except Exception as e:
print("bg image load failed:", e, flush=True)
return None
def dim(img: Image.Image, amount=0.45) -> Image.Image:
overlay = Image.new("RGB", img.size, (0, 0, 0))
return Image.blend(img, overlay, amount)
# ---------------------------------------------------------------------------
# Template 1: atmospheric_text_hook
# ---------------------------------------------------------------------------
def render_atmospheric(headline: str, hook_lines: list[str], bg_img, active: int) -> Image.Image:
base = dim(bg_img, 0.5) if bg_img is not None else gradient_bg((30, 30, 34), (5, 5, 8))
img = base.copy()
draw = ImageDraw.Draw(img)
# dark gradient overlay top/bottom for legibility
grad = Image.new("L", (1, H), 0)
for y in range(H):
v = 0
if y < H * 0.28:
v = int(160 * (1 - y / (H * 0.28)))
elif y > H * 0.78:
v = int(200 * ((y - H * 0.78) / (H * 0.22)))
grad.putpixel((0, y), v)
grad = grad.resize((W, H))
black = Image.new("RGB", (W, H), (0, 0, 0))
img = Image.composite(black, img, grad)
draw = ImageDraw.Draw(img)
f_head = archivo(78)
head_lines = wrap_text(headline.upper(), f_head, W - 140, draw)
draw_text_block(draw, (W / 2, 190), head_lines, f_head, "white", W - 140,
stroke_width=6, stroke_fill="black")
f_hook = anton(96)
y = 780
for i, line in enumerate(hook_lines):
if i > active:
continue
wrapped = wrap_text(line.upper(), f_hook, W - 100, draw)
color = YELLOW if i % 2 == 0 else "white"
yb = draw_text_block(draw, (W / 2, y + 70), wrapped, f_hook, color, W - 100,
stroke_width=8, stroke_fill="black")
y = yb + 30
if active >= len(hook_lines) - 1:
f_cta = archivo(58)
draw_text_block(draw, (W / 2, H - 190), ["SAVE THIS POST!"], f_cta, YELLOW, W - 120,
stroke_width=6, stroke_fill="black")
return img
# ---------------------------------------------------------------------------
# Template 2: tweet_thread
# ---------------------------------------------------------------------------
def draw_tweet_card(canvas: Image.Image, top_y: int, handle: str, text: str, timestamp: str, idx: int):
card_w = 900
x0 = (W - card_w) // 2
draw = ImageDraw.Draw(canvas)
f_user = inter(34)
f_handle = inter(26)
f_body = inter(36)
f_time = inter(22)
tmp = Image.new("RGB", (10, 10))
tdraw = ImageDraw.Draw(tmp)
body_lines = wrap_text(text, f_body, card_w - 90, tdraw)
card_h = 170 + len(body_lines) * 48 + 40
card = Image.new("RGBA", (card_w, card_h), (255, 255, 255, 255))
cd = ImageDraw.Draw(card)
cd.rounded_rectangle([0, 0, card_w - 1, card_h - 1], radius=28, outline=(210, 210, 215), width=2)
cd.text((28, 20), "‹", font=inter(30), fill=(60, 100, 220))
cd.text((28, 66), "Tweet", font=inter(30), fill=(20, 20, 24))
# avatar
cd.ellipse([28, 118, 88, 178], fill=(120, 150, 230))
cd.text((100, 118), "Username:", font=f_user, fill=(20, 20, 24))
cd.text((100, 156), "@ContentMaster", font=f_handle, fill=(120, 130, 145))
ty = 210
for ln in body_lines:
cd.text((28, ty), ln, font=f_body, fill=(15, 15, 20))
ty += 48
cd.text((28, ty + 14), timestamp, font=f_time, fill=(150, 155, 165))
canvas.paste(card, (x0, top_y), card)
return card_h
def render_tweet_thread(tweets: list[str], active: int) -> Image.Image:
img = gradient_bg(NAVY, (4, 6, 14))
y = 260
shown = tweets[: active + 1]
# cascade: show last 3 stacked, offset each by +40px x/y
start = max(0, len(shown) - 4)
for i, t in enumerate(shown[start:]):
idx = start + i
offset = i * 46
top = y + offset
h = draw_tweet_card(img, top, "@ContentMaster", t, f"3:15 PM · Jan 9, 2021 · {120 + idx*40}K Views", idx)
draw = ImageDraw.Draw(img)
draw_text_block(draw, (W / 2, 130), ["MY VIRAL THREAD"], archivo(56), "white", W - 140,
stroke_width=4, stroke_fill="black")
return img
# ---------------------------------------------------------------------------
# Template 3: notes_app
# ---------------------------------------------------------------------------
def render_notes_app(lines: list[str], active: int) -> Image.Image:
img = gradient_bg((14, 16, 22), (4, 4, 6))
draw = ImageDraw.Draw(img)
phone_w, phone_h = 760, 1560
px0, py0 = (W - phone_w) // 2, (H - phone_h) // 2
draw.rounded_rectangle([px0 - 18, py0 - 18, px0 + phone_w + 18, py0 + phone_h + 18],
radius=90, fill=(30, 30, 32))
draw.rounded_rectangle([px0, py0, px0 + phone_w, py0 + phone_h], radius=72, fill=CREAM)
# status bar
f_status = inter(24)
draw.text((px0 + 40, py0 + 30), "9:31", font=f_status, fill=(30, 30, 30))
draw.text((px0 + phone_w - 150, py0 + 30), "🔋 📶", font=f_status, fill=(30, 30, 30))
draw.text((px0 + 40, py0 + 90), "‹ Notes", font=inter(30), fill=(230, 160, 40))
f_body = archivo(46)
y = py0 + 190
for i, ln in enumerate(lines):
if i > active:
continue
wrapped = wrap_text(ln.upper(), f_body, phone_w - 100, draw)
for wln in wrapped:
draw.text((px0 + 50, y), wln, font=f_body, fill=(15, 15, 15))
y += 60
y += 26
return img
# ---------------------------------------------------------------------------
# Template 4: fullscreen_title_hook
# ---------------------------------------------------------------------------
def render_fullscreen_title(lines: list[str], active: int) -> Image.Image:
img = gradient_bg((16, 20, 46), (4, 5, 14))
draw = ImageDraw.Draw(img)
n = len(lines)
y = H * 0.30
for i, ln in enumerate(lines):
if i > active:
continue
size = 150 if i == 0 else 84
f = anton(size)
color = YELLOW if i == n - 1 else "white"
wrapped = wrap_text(ln.upper(), f, W - 100, draw)
yb = draw_text_block(draw, (W / 2, y + size * 0.6), wrapped, f, color, W - 100,
stroke_width=7 if i == 0 else 5, stroke_fill="black")
y = yb + 30
return img
# ---------------------------------------------------------------------------
# Render orchestration
# ---------------------------------------------------------------------------
def build_content(template: str, headline: Optional[str], script: str, lines_override: Optional[list[str]]):
if lines_override:
lines = [l.strip() for l in lines_override if l.strip()]
else:
if template == "tweet_thread":
lines = split_sentences(script, 5)
elif template == "notes_app":
lines = split_sentences(script, 5)
elif template == "fullscreen_title_hook":
lines = split_sentences(script, 4)
else:
lines = split_sentences(script, 4)
if not lines:
lines = [headline or "Watch this"]
return lines
def render_frames(template: str, headline: str, lines: list[str], bg_img) -> list[Image.Image]:
frames = []
n = len(lines)
for i in range(n):
if template == "atmospheric_text_hook":
frames.append(render_atmospheric(headline, lines, bg_img, i))
elif template == "tweet_thread":
frames.append(render_tweet_thread(lines, i))
elif template == "notes_app":
frames.append(render_notes_app(lines, i))
else:
frames.append(render_fullscreen_title(lines, i))
return frames
def assemble_video(frames: list[Image.Image], durations: list[float], audio: np.ndarray, sr: int) -> bytes:
with tempfile.TemporaryDirectory() as tmp:
tmp = Path(tmp)
list_path = tmp / "list.txt"
with open(list_path, "w") as f:
for i, (frame, dur) in enumerate(zip(frames, durations)):
p = tmp / f"f{i:03d}.png"
frame.convert("RGB").save(p, "PNG")
f.write(f"file '{p.name}'\nduration {max(dur, 0.35):.3f}\n")
# ffmpeg concat needs the last file repeated w/o duration
last = tmp / f"f{len(frames)-1:03d}.png"
f.write(f"file '{last.name}'\n")
audio_path = tmp / "audio.wav"
sf.write(str(audio_path), audio, sr)
video_noaudio = tmp / "video_noaudio.mp4"
cmd1 = [
"ffmpeg", "-y", "-f", "concat", "-safe", "0", "-i", str(list_path),
"-vf", f"fps={FPS},scale={W}:{H}", "-pix_fmt", "yuv420p", str(video_noaudio),
]
subprocess.run(cmd1, cwd=tmp, check=True, capture_output=True)
out_path = tmp / "out.mp4"
cmd2 = [
"ffmpeg", "-y", "-i", str(video_noaudio), "-i", str(audio_path),
"-c:v", "libx264", "-preset", "veryfast", "-crf", "23",
"-c:a", "aac", "-b:a", "160k", "-shortest", str(out_path),
]
subprocess.run(cmd2, check=True, capture_output=True)
return out_path.read_bytes()
def do_render(payload: dict) -> bytes:
template = payload.get("template", "atmospheric_text_hook")
if template not in TEMPLATES:
template = "atmospheric_text_hook"
voice = payload.get("voice", DEFAULT_VOICE)
script = (payload.get("script") or payload.get("voice_script") or "").strip()
headline = (payload.get("headline") or "").strip() or (script.split(".")[0][:60] if script else "Watch This")
lines_override = payload.get("lines")
bg_url = payload.get("background_image_url") or payload.get("background_image")
lines = build_content(template, headline, script, lines_override)
bg_img = load_background_image(bg_url) if template == "atmospheric_text_hook" else None
if template == "atmospheric_text_hook" and bg_img is None:
bg_img = gradient_bg((40, 32, 26), (10, 8, 8))
# narrate: headline (for atmospheric/fullscreen) + each line as its own segment
narrate_lines = lines if script else lines
audio, sr, seg_durs = synth_segments(narrate_lines, voice)
frames = render_frames(template, headline, lines, bg_img)
mp4_bytes = assemble_video(frames, seg_durs, audio, sr)
return mp4_bytes
# ---------------------------------------------------------------------------
# Template video routes (additive; does not affect /render, /tts, /health)
# ---------------------------------------------------------------------------
class TemplateRenderReq(BaseModel):
template: str | None = "atmospheric_text_hook"
script: str | None = None
voice_script: str | None = None
voice: str | None = DEFAULT_VOICE
headline: str | None = None
lines: list[str] | None = None
background_image: str | None = None
background_image_url: str | None = None
@app.get("/templates")
def list_templates():
return {
"templates": [
{"id": "atmospheric_text_hook", "label": "Atmospheric text hook",
"description": "Moody photo background with bold yellow/white hook lines and a Save-this-post CTA."},
{"id": "tweet_thread", "label": "Tweet thread",
"description": "Cascading fake-tweet cards revealing a thread, one tweet per beat."},
{"id": "notes_app", "label": "Notes app",
"description": "iPhone Notes screenshot look, lines appearing like a typed note."},
{"id": "fullscreen_title_hook", "label": "Fullscreen title hook",
"description": "Huge stacked title cards, escalating size, classic scroll-stopper."},
],
"voices": KOKORO_VOICES,
}
@app.post("/render-template")
def render_template(req: TemplateRenderReq):
payload = {
"template": req.template or "atmospheric_text_hook",
"script": req.script or req.voice_script or "",
"voice": req.voice or DEFAULT_VOICE,
"headline": req.headline,
"lines": req.lines,
"background_image_url": req.background_image_url or req.background_image,
}
try:
mp4 = do_render(payload)
return Response(content=mp4, media_type="video/mp4")
except Exception as e:
import traceback
traceback.print_exc()
raise HTTPException(500, f"template render failed: {type(e).__name__}: {str(e)[:400]}")
# ===========================================================================
# v5: animated templates, music bed, custom uploaded media
# ===========================================================================
import io as _io
import math as _math
from pathlib import Path as _Path
import anim_templates as anim
def _download(url: str, suffix: str) -> str:
r = requests.get(url, timeout=120)
r.raise_for_status()
p = os.path.join(tempfile.mkdtemp(), f"dl{suffix}")
with open(p, "wb") as f:
f.write(r.content)
return p
def _media_frames(url: str, total: float, fps: int) -> list:
"""Decode an uploaded image or video into `total*fps` cover-fitted frames."""
if not url:
return []
low = url.split("?")[0].lower()
is_video = any(low.endswith(x) for x in (".mp4", ".mov", ".webm", ".m4v", ".avi"))
n = max(int(total * fps), 1)
if not is_video:
try:
r = requests.get(url, timeout=60)
r.raise_for_status()
img = anim.cover(Image.open(_io.BytesIO(r.content)).convert("RGB"))
return [anim.ken_burns(img, k / n) for k in range(n)]
except Exception as e:
print("media image failed:", e, flush=True)
return []
try:
src = _download(url, ".mp4")
outdir = tempfile.mkdtemp()
subprocess.run(
["ffmpeg", "-y", "-stream_loop", "-1", "-t", f"{total:.2f}", "-i", src,
"-vf", f"fps={fps},scale={anim.SW}:{anim.SH}:force_original_aspect_ratio=increase,"
f"crop={anim.SW}:{anim.SH}",
"-an", os.path.join(outdir, "m%05d.png")],
check=True, capture_output=True,
)
files = sorted(_Path(outdir).glob("m*.png"))[:n]
frames = [Image.open(f).convert("RGB") for f in files]
while frames and len(frames) < n:
frames.append(frames[-1])
return frames
except Exception as e:
print("media video failed:", e, flush=True)
return []
def _assemble_animated(frames, fps, audio, sr, music_url=None, music_volume=0.18,
media_audio_url=None, media_audio_volume=0.0,
brand_link=None, brand_text=None, brand_duration=0.0) -> bytes:
with tempfile.TemporaryDirectory() as tmp:
tmp = _Path(tmp)
for i, fr in enumerate(frames):
fr.convert("RGB").save(tmp / f"f{i:05d}.png", "PNG", compress_level=1)
audio_path = tmp / "voice.wav"
sf.write(str(audio_path), audio, sr)
silent = tmp / "silent.mp4"
subprocess.run(
["ffmpeg", "-y", "-framerate", str(fps), "-i", str(tmp / "f%05d.png"),
"-vf", "scale=1080:1920:flags=lanczos", "-pix_fmt", "yuv420p",
"-c:v", "libx264", "-preset", "veryfast", "-crf", "22", str(silent)],
check=True, capture_output=True,
)
inputs = ["-i", str(silent), "-i", str(audio_path)]
parts, mix_labels = [], ["[1:a]"]
idx = 2
if music_url:
try:
mp = _download(music_url, ".mp3")
inputs += ["-i", mp]
parts.append(f"[{idx}:a]volume={max(0.0, min(music_volume, 1.0)):.3f},"
f"afade=t=in:st=0:d=1.2,aloop=loop=-1:size=2e9[mus]")
mix_labels.append("[mus]")
idx += 1
except Exception as e:
print("music failed:", e, flush=True)
if media_audio_url and media_audio_volume > 0:
try:
ap = _download(media_audio_url, ".mp4")
inputs += ["-i", ap]
parts.append(f"[{idx}:a]volume={min(media_audio_volume, 1.0):.3f}[mda]")
mix_labels.append("[mda]")
idx += 1
except Exception as e:
print("media audio failed:", e, flush=True)
out = tmp / "out.mp4"
cmd = ["ffmpeg", "-y"] + inputs
if len(mix_labels) > 1:
fc = ";".join(parts + [
"".join(mix_labels) + f"amix=inputs={len(mix_labels)}:duration=first:"
f"dropout_transition=0,alimiter=limit=0.95[aout]"
])
cmd += ["-filter_complex", fc, "-map", "0:v", "-map", "[aout]"]
else:
cmd += ["-map", "0:v", "-map", "1:a"]
cmd += ["-c:v", "copy", "-c:a", "aac", "-b:a", "192k", "-shortest", str(out)]
subprocess.run(cmd, check=True, capture_output=True)
if brand_duration and brand_duration > 0:
outro = tmp / "outro.mp4"
txt = (brand_text or brand_link or "").replace(":", "\\:").replace("'", "\u2019")
link = (brand_link or "").replace(":", "\\:").replace("'", "\u2019")
font = FALLBACK_FONT
vf = (f"drawtext=fontfile={font}:text='{txt}':fontcolor=white:fontsize=64:"
f"x=(w-text_w)/2:y=(h-text_h)/2-70,"
f"drawtext=fontfile={font}:text='{link}':fontcolor=0xFFD400:fontsize=48:"
f"x=(w-text_w)/2:y=(h-text_h)/2+60")
subprocess.run(
["ffmpeg", "-y", "-f", "lavfi", "-i", f"color=c=black:s=1080x1920:d={brand_duration}",
"-f", "lavfi", "-i", f"anullsrc=r=44100:cl=stereo:d={brand_duration}",
"-vf", vf, "-pix_fmt", "yuv420p", "-c:v", "libx264", "-preset", "veryfast",
"-c:a", "aac", "-shortest", str(outro)], check=True, capture_output=True)
joined = tmp / "joined.mp4"
lst = tmp / "cat.txt"
lst.write_text(f"file '{out}'\nfile '{outro}'\n")
subprocess.run(["ffmpeg", "-y", "-f", "concat", "-safe", "0", "-i", str(lst),
"-c:v", "libx264", "-preset", "veryfast", "-crf", "22",
"-c:a", "aac", str(joined)], check=True, capture_output=True)
return joined.read_bytes()
return out.read_bytes()
class AnimatedReq(BaseModel):
template: str = "depth_parallax"
script: str | None = None
voice_script: str | None = None
headline: str | None = None
lines: list[str] | None = None
voice: str | None = DEFAULT_VOICE
max_lines: int | None = 6
background_image_url: str | None = None
media_url: str | None = None # uploaded clip or image (custom templates)
media_audio: bool | None = False
media_audio_volume: float | None = 0.35
music_url: str | None = None
music_volume: float | None = 0.18
brand_link: str | None = None
brand_text: str | None = None
brand_duration: float | None = 0.0
fps: int | None = 24
@app.get("/animated-templates")
def animated_templates():
return {"templates": anim.META, "voices": KOKORO_VOICES}
@app.post("/render-animated")
def render_animated(req: AnimatedReq):
try:
script = (req.script or req.voice_script or "").strip()
lines = [l.strip() for l in (req.lines or []) if l.strip()]
if not lines:
lines = split_sentences(script, max(2, min(req.max_lines or 6, 8)))
if not lines:
lines = [req.headline or "Watch this"]
headline = (req.headline or "").strip() or lines[0][:60]
audio, sr, seg_durs = synth_segments(lines, req.voice or DEFAULT_VOICE)
total = max(sum(seg_durs), 3.0)
fps = max(12, min(req.fps or 24, 30))
bg = None
if req.background_image_url:
try:
r = requests.get(req.background_image_url, timeout=40)
r.raise_for_status()
bg = anim.cover(Image.open(_io.BytesIO(r.content)).convert("RGB"))
except Exception as e:
print("bg failed:", e, flush=True)
media_frames = _media_frames(req.media_url, total, fps) if req.media_url else []
template = req.template if req.template in anim.ANIMATED else (
"custom_media" if media_frames else "depth_parallax")
frames = anim.render_animation(template, headline, lines, seg_durs, total,
bg=bg, media_frames=media_frames, fps=fps)
mp4 = _assemble_animated(
frames, fps, audio, sr,
music_url=req.music_url,
music_volume=req.music_volume if req.music_volume is not None else 0.18,
media_audio_url=req.media_url if req.media_audio else None,
media_audio_volume=(req.media_audio_volume or 0.35) if req.media_audio else 0.0,
brand_link=req.brand_link, brand_text=req.brand_text,
brand_duration=req.brand_duration or 0.0,
)
return Response(content=mp4, media_type="video/mp4")
except Exception as e:
import traceback
traceback.print_exc()
raise HTTPException(500, f"animated render failed: {type(e).__name__}: {str(e)[:400]}")
# ===========================================================================
# Automation 2 — source-clip pipeline
# /clip/probe : resolve a source URL -> duration, title, timed subtitles
# /clip/render : cut one segment, reframe to 9:16, burn captions,
# optionally mute the source and lay a Kokoro voice over it.
# Downloads are cached per video id in /tmp so a 100-clip batch downloads once.
# ===========================================================================
import glob as _glob
import hashlib as _hashlib
CLIP_CACHE = "/tmp/clipcache"
os.makedirs(CLIP_CACHE, exist_ok=True)
COOKIE_FILE = "/tmp/yt_cookies.txt"
def _cookie_file():
raw = os.environ.get("YTDLP_COOKIES", "").strip()
if not raw:
return None
if not os.path.exists(COOKIE_FILE):
with open(COOKIE_FILE, "w", encoding="utf-8") as f:
f.write(raw.replace("\\n", "\n"))
return COOKIE_FILE
def _ydl_opts(extra: dict) -> dict:
base = {
"quiet": True,
"no_warnings": True,
"noplaylist": True,
"cachedir": "/tmp/ytdlcache",
"retries": 1,
"fragment_retries": 2,
"extractor_retries": 1,
"socket_timeout": 12,
"geo_bypass": True,
"http_headers": {
"User-Agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 "
"(KHTML, like Gecko) Chrome/124.0 Safari/537.36",
"Accept-Language": "en-US,en;q=0.9",
},
}
ck = _cookie_file()
if ck:
base["cookiefile"] = ck
proxy = os.environ.get("YTDLP_PROXY", "").strip()
if proxy:
base["proxy"] = proxy
base.update(extra)
return base
# --- multi-strategy YouTube access ------------------------------------------
# Datacenter IPs get throttled/blocked by the default web client, so we walk a
# ladder of player clients and remember the first one that works.
YT_STRATEGIES = [
("android_vr", {"youtube": {"player_client": ["android_vr"]}}),
("tv", {"youtube": {"player_client": ["tv"]}}),
("ios", {"youtube": {"player_client": ["ios"]}}),
("mweb", {"youtube": {"player_client": ["mweb"]}}),
("web_safari", {"youtube": {"player_client": ["web_safari"]}}),
("web_embedded", {"youtube": {"player_client": ["web_embedded"]}}),
("android", {"youtube": {"player_client": ["android"]}}),
("default", None),
]
STRATEGY_MEMO = "/tmp/yt_strategy.txt"
def _is_youtube(url: str) -> bool:
return bool(re.search(r"(youtube\.com|youtu\.be)", url or "", re.I))
def _normalize_url(url: str) -> str:
u = (url or "").strip()
if "dropbox.com" in u:
u = u.split("?")[0] + "?dl=1"
if "drive.google.com" in u:
m = re.search(r"/d/([A-Za-z0-9_-]+)", u) or re.search(r"[?&]id=([A-Za-z0-9_-]+)", u)
if m:
u = f"https://drive.google.com/uc?export=download&id={m.group(1)}"
return u
def _ordered_strategies():
order = list(YT_STRATEGIES)
try:
with open(STRATEGY_MEMO) as f:
win = f.read().strip()
order.sort(key=lambda s: 0 if s[0] == win else 1)
except Exception:
pass
return order
def _remember(name: str):
try:
with open(STRATEGY_MEMO, "w") as f:
f.write(name)
except Exception:
pass
def _ffprobe_json(target: str) -> dict:
try:
out = subprocess.check_output(
["ffprobe", "-v", "quiet", "-print_format", "json", "-show_format", "-show_streams", target],
timeout=120,
)
return _json.loads(out.decode("utf-8", "ignore"))
except Exception as e:
raise HTTPException(400, f"ffprobe could not open this source: {type(e).__name__}: {str(e)[:200]}")
def _direct_probe(url: str) -> dict:
"""Duration/title for a plain media URL (upload, signed URL, CDN mp4)."""
try:
meta = _ffprobe_json(url)
except Exception:
local = _direct_download(url, os.path.join(CLIP_CACHE, _src_key(url)))
meta = _ffprobe_json(local)
dur = 0.0
try:
dur = float((meta.get("format") or {}).get("duration") or 0)
except Exception:
dur = 0.0
if dur <= 0:
for s in meta.get("streams", []):
try:
dur = max(dur, float(s.get("duration") or 0))
except Exception:
pass
name = (meta.get("format") or {}).get("tags", {}).get("title")
if not name:
name = os.path.basename((url.split("?")[0] or "source")) or "Source video"
return {"id": None, "title": name[:120], "duration": dur}
def _direct_download(url: str, dest_noext: str) -> str:
"""Stream a plain media URL to disk (no yt-dlp)."""
dest = dest_noext + ".mp4"
with requests.get(url, stream=True, timeout=120, headers={"User-Agent": "Mozilla/5.0"}) as r:
r.raise_for_status()
with open(dest, "wb") as f:
for chunk in r.iter_content(1024 * 512):
if chunk:
f.write(chunk)
if os.path.getsize(dest) < 1024:
raise HTTPException(400, "source download produced an empty file")
return dest
def _run_with_timeout(fn, seconds: int):
import concurrent.futures as _cf
with _cf.ThreadPoolExecutor(max_workers=1) as ex:
return ex.submit(fn).result(timeout=seconds)
def _ydl_try(url: str, extra: dict, download: bool):
"""Run yt-dlp across every strategy; return (info, strategy) or raise."""
from yt_dlp import YoutubeDL
url = _normalize_url(url)
if not _is_youtube(url):
opts = _ydl_opts(dict(extra))
try:
def _go():
with YoutubeDL(opts) as ydl:
return ydl.extract_info(url, download=download)
return _run_with_timeout(_go, 600 if download else 90), "direct"
except Exception as e:
raise HTTPException(400, f"direct source failed: {type(e).__name__}: {str(e)[:200]}")
errors = []
deadline = _time.time() + (600 if download else 75)
per_try = 300 if download else 20
for name, args in _ordered_strategies():
left = deadline - _time.time()
if left <= 5:
errors.append("deadline reached before trying " + name)
break
opts = _ydl_opts(dict(extra))
if args:
opts["extractor_args"] = args
try:
def _go(o=opts):
with YoutubeDL(o) as ydl:
return ydl.extract_info(url, download=download)
info = _run_with_timeout(_go, min(per_try, max(8, int(left))))
if info:
_remember(name)
return info, name
except Exception as e:
errors.append(f"{name}: {type(e).__name__}: {str(e)[:160]}")
continue
joined = " | ".join(errors[-4:])
blocked = any(k in joined.lower() for k in
("sign in to confirm", "bot", "403", "forbidden", "unavailable", "timeout"))
hint = (" YouTube is blocking this server's IP. Upload the video file instead,"
" or add YouTube cookies (YTDLP_COOKIES) to this Space.") if blocked else ""
raise HTTPException(400, "all download methods failed -> " + joined + hint)
def _src_key(url: str) -> str:
return _hashlib.sha1(url.encode("utf-8")).hexdigest()[:16]
def _parse_vtt(text: str) -> list:
"""Very small WebVTT parser -> [{start,end,text}] with de-duplicated lines."""
cues, buf = [], None
def ts(v):
v = v.strip().replace(",", ".")
parts = v.split(":")
try:
if len(parts) == 3:
return int(parts[0]) * 3600 + int(parts[1]) * 60 + float(parts[2])
if len(parts) == 2:
return int(parts[0]) * 60 + float(parts[1])
except Exception:
return None
return None
for raw in text.splitlines():
line = raw.strip()
if "-->" in line:
a, _, b = line.partition("-->")
s, e = ts(a), ts(b.split(" ")[0] if " " in b.strip() else b)
if s is None or e is None:
buf = None
continue
buf = {"start": s, "end": e, "text": ""}
cues.append(buf)
elif line and buf is not None and not line.startswith(("WEBVTT", "Kind:", "Language:", "NOTE")):
clean = re.sub(r"<[^>]+>", "", line).strip()
if clean:
buf["text"] = (buf["text"] + " " + clean).strip()
out, seen = [], ""
for c in cues:
t = c["text"].strip()
if not t or t == seen:
continue
seen = t
out.append({"start": round(c["start"], 3), "end": round(c["end"], 3), "text": t[:220]})
return out
def _fetch_subtitles(info: dict) -> list:
tracks = {}
tracks.update(info.get("subtitles") or {})
for k, v in (info.get("automatic_captions") or {}).items():
tracks.setdefault(k, v)
pick = None
for lang in ("en", "en-US", "en-GB", "en-orig"):
if lang in tracks:
pick = tracks[lang]
break
if not pick and tracks:
pick = list(tracks.values())[0]
if not pick:
return []
url = None
for fmt in pick:
if fmt.get("ext") in ("vtt", "srt"):
url = fmt.get("url")
break
if not url:
url = pick[0].get("url")
if not url:
return []
try:
r = requests.get(url, timeout=45)
r.raise_for_status()
return _parse_vtt(r.text)
except Exception as e:
print("subtitle fetch failed:", e, flush=True)
return []
class ProbeReq(BaseModel):
url: str
@app.post("/clip/probe")
def clip_probe(req: ProbeReq, request: Request):
_check_auth(request)
try:
import yt_dlp # noqa: F401
except Exception as e:
raise HTTPException(500, f"yt-dlp unavailable: {e}")
url = _normalize_url(req.url)
if not _is_youtube(url):
d = _direct_probe(url)
if not d["duration"]:
raise HTTPException(400, "could not read the duration of this source")
return {"video_id": None, "title": d["title"], "duration": d["duration"],
"subtitles": [], "has_subtitles": False, "strategy": "ffprobe"}
info, strategy = _ydl_try(
url, {"skip_download": True, "writesubtitles": True, "writeautomaticsub": True}, False
)
subs = _fetch_subtitles(info)
return {
"video_id": info.get("id"),
"title": info.get("title") or "Source video",
"duration": float(info.get("duration") or 0),
"subtitles": subs,
"has_subtitles": bool(subs),
"strategy": strategy,
}
@app.post("/clip/diag")
def clip_diag(req: ProbeReq, request: Request):
"""Try every download method against a URL and report which ones work."""
_check_auth(request)
from yt_dlp import YoutubeDL
url = _normalize_url(req.url)
out = []
for name, args in YT_STRATEGIES:
opts = _ydl_opts({"skip_download": True})
if args:
opts["extractor_args"] = args
try:
with YoutubeDL(opts) as ydl:
info = ydl.extract_info(url, download=False)
out.append({"strategy": name, "ok": True, "title": info.get("title"),
"duration": info.get("duration")})
except Exception as e:
out.append({"strategy": name, "ok": False, "error": f"{type(e).__name__}: {str(e)[:200]}"})
working = [o["strategy"] for o in out if o["ok"]]
if working:
_remember(working[0])
return {"url": url, "working": working, "results": out}
def _ensure_source(url: str) -> str:
key = _src_key(url)
hits = sorted(_glob.glob(os.path.join(CLIP_CACHE, key + ".*")))
for h in hits:
if os.path.getsize(h) > 0:
return h
try:
from yt_dlp import YoutubeDL
except Exception as e:
raise HTTPException(500, f"yt-dlp unavailable: {e}")
if not _is_youtube(_normalize_url(url)):
return _direct_download(_normalize_url(url), os.path.join(CLIP_CACHE, key))
out = os.path.join(CLIP_CACHE, key + ".%(ext)s")
_ydl_try(url, {
"outtmpl": out,
"format": "bestvideo[height<=720][ext=mp4]+bestaudio[ext=m4a]/best[height<=720]/best",
"merge_output_format": "mp4",
"concurrent_fragment_downloads": 4,
}, True)
hits = sorted(_glob.glob(os.path.join(CLIP_CACHE, key + ".*")))
if not hits:
raise HTTPException(500, "download produced no file")
# keep the cache small — newest 3 sources only
files = sorted(_glob.glob(os.path.join(CLIP_CACHE, "*")), key=os.path.getmtime, reverse=True)
for old in files[6:]:
try: os.remove(old)
except OSError: pass
return hits[0]
def _ass_escape(t: str) -> str:
return t.replace("\\", "\\\\").replace("{", "(").replace("}", ")").replace("\n", " ")
def _ass_time(t: float) -> str:
t = max(0.0, t)
h = int(t // 3600); m = int((t % 3600) // 60); s = t % 60
return f"{h:d}:{m:02d}:{s:05.2f}"
ASS_FONTS = {"Anton": "Anton", "BebasNeue": "Bebas Neue", "ArchivoBlack": "Archivo Black",
"Inter": "Liberation Sans", "Montserrat": "Liberation Sans"}
def _build_ass(cues: list, preset: str, font: str, color: str, accent: str, path: str,
font_size: int = 0, position: float = -1.0, uppercase: bool = True):
fontname = ASS_FONTS.get(font, "Liberation Sans")
primary = hex_to_ass(color, "&H00FFFFFF")
outline_col = "&H00000000"
size = {"clean_caps": 78, "karaoke_pop": 84, "split_frame": 66,
"blur_fill": 74, "bottom_bar": 62}.get(preset, 74)
align, marginv = (2, 430) if preset != "split_frame" else (2, 240)
if preset == "bottom_bar":
marginv = 250
if font_size and font_size > 0:
size = max(28, min(140, int(font_size)))
if position is not None and position >= 0:
# position: 0 = bottom of frame, 1 = top of frame
marginv = int(max(60, min(1700, position * 1920)))
header = f"""[Script Info]
ScriptType: v4.00+
PlayResX: 1080
PlayResY: 1920
WrapStyle: 2
ScaledBorderAndShadow: yes
[V4+ Styles]
Format: Name, Fontname, Fontsize, PrimaryColour, SecondaryColour, OutlineColour, BackColour, Bold, Italic, Underline, StrikeOut, ScaleX, ScaleY, Spacing, Angle, BorderStyle, Outline, Shadow, Alignment, MarginL, MarginR, MarginV, Encoding
Style: Cap,{fontname},{size},{primary},{hex_to_ass(accent, '&H004AD5FF')},{outline_col},&H80000000,-1,0,0,0,100,100,0,0,1,6,2,{align},70,70,{marginv},1
[Events]
Format: Layer, Start, End, Style, Name, MarginL, MarginR, MarginV, Effect, Text
"""
lines = []
for c in cues:
text = _ass_escape(str(c.get("text", "")).strip())
if not text:
continue
if uppercase:
text = text.upper()
if preset == "karaoke_pop":
text = "{\\fad(60,60)\\fscx104\\fscy104}" + text
else:
text = "{\\fad(50,50)}" + text
lines.append(
f"Dialogue: 0,{_ass_time(float(c['start']))},{_ass_time(float(c['end']))},Cap,,0,0,0,,{text}"
)
with open(path, "w", encoding="utf-8") as f:
f.write(header + "\n".join(lines) + "\n")
def _frame_filter(preset: str, accent: str) -> str:
"""Reframe a 16:9 source into a 1080x1920 canvas per template preset."""
if preset == "blur_fill":
return ("[0:v]split=2[bg][fg];"
"[bg]scale=1080:1920:force_original_aspect_ratio=increase,crop=1080:1920,"
"gblur=sigma=32,eq=brightness=-0.08[bgb];"
"[fg]scale=1080:-2[fgs];"
"[bgb][fgs]overlay=(W-w)/2:(H-h)/2[v]")
if preset == "split_frame":
return ("[0:v]scale=1080:-2[fgs];"
"color=c=0x0B0B0F:s=1080x1920:d=1[bg];"
"[bg][fgs]overlay=0:220:shortest=1[v]")
if preset == "bottom_bar":
return ("[0:v]scale=1080:1920:force_original_aspect_ratio=increase,crop=1080:1920[vc];"
f"color=c={accent.replace('#','0x')}:s=1080x14:d=1[bar];"
"[vc][bar]overlay=0:1780:shortest=1[v]")
# clean_caps / karaoke_pop -> straight center crop
return "[0:v]scale=1080:1920:force_original_aspect_ratio=increase,crop=1080:1920[v]"
def _fx_chain(req) -> str:
"""Cool-edit chain applied to the reframed 1080x1920 video."""
k = max(0.2, min(2.0, float(getattr(req, "fx_intensity", 1.0) or 1.0)))
parts = []
if getattr(req, "fx_zoom", False):
z = 0.10 * k
parts.append(
"crop=w='iw/(1+%.3f*mod(t,6)/6)':h='ih/(1+%.3f*mod(t,6)/6)':"
"x='(iw-ow)/2':y='(ih-oh)/2',scale=1080:1920" % (z, z)
)
if getattr(req, "fx_shake", False):
a = 6 * k
parts.append(
"crop=w=iw-24:h=ih-24:x='12+%.2f*sin(2*PI*t*7)':y='12+%.2f*cos(2*PI*t*5)',"
"scale=1080:1920" % (a, a)
)
if getattr(req, "fx_grade", True):
parts.append("eq=contrast=%.3f:saturation=%.3f:gamma=0.98" % (1 + 0.10 * k, 1 + 0.18 * k))
if getattr(req, "fx_glitch", False):
sh = int(round(6 * k))
parts.append("rgbashift=rh=%d:bh=-%d:enable='lt(mod(t,2.6),0.09)'" % (sh, sh))
parts.append("hue=s=0:enable='lt(mod(t,5.2),0.05)'")
if getattr(req, "fx_flash", False):
parts.append("eq=brightness=%.2f:enable='lt(mod(t,4),0.07)'" % (0.30 * k))
if getattr(req, "fx_grain", False):
parts.append("noise=alls=%d:allf=t+u" % max(2, int(round(8 * k))))
if getattr(req, "fx_vignette", False):
parts.append("vignette=PI/5")
return ",".join(parts)
class ClipReq(BaseModel):
url: str
start: float = 0
duration: float = 15
preset: str = "clean_caps"
font: str = "Anton"
caption_color: str = "#FFFFFF"
accent: str = "#FFD54A"
captions: Optional[list] = None # [{start,end,text}] in SOURCE time
mute_source: bool = False
voice_text: Optional[str] = None # Kokoro narration laid over the clip
voice: str = "af_bella"
music_volume: float = 0.25
font_size: int = 0
caption_position: float = -1.0 # 0 = bottom, 1 = top
uppercase: bool = True
fx_zoom: bool = False
fx_shake: bool = False
fx_glitch: bool = False
fx_grain: bool = False
fx_flash: bool = False
fx_vignette: bool = False
fx_grade: bool = True
fx_intensity: float = 1.0
@app.post("/clip/render")
def clip_render(req: ClipReq, request: Request):
_check_auth(request)
src = _ensure_source(req.url)
job = str(uuid.uuid4())
work = tempfile.mkdtemp(prefix="clip_")
out = os.path.join(RENDERS_DIR, f"{job}.mp4")
try:
dur = max(3.0, min(90.0, float(req.duration or 15)))
start = max(0.0, float(req.start or 0))
# ---- captions, shifted into clip-relative time ----
vf = _frame_filter(req.preset, req.accent)
fx = _fx_chain(req)
vlab = "[v]"
if fx:
vf += f";[v]{fx}[vfx]"
vlab = "[vfx]"
cues = []
for c in (req.captions or []):
try:
s = float(c.get("start", 0)) - start
e = float(c.get("end", 0)) - start
except Exception:
continue
if e <= 0.05 or s >= dur:
continue
cues.append({"start": max(0.0, s), "end": min(dur, e), "text": c.get("text", "")})
if cues:
ass = os.path.join(work, "caps.ass")
_build_ass(cues, req.preset, req.font, req.caption_color, req.accent, ass,
req.font_size, req.caption_position, req.uppercase)
vf += f";{vlab}ass={ass}[vout]"
else:
vf += f";{vlab}null[vout]"
cmd = ["ffmpeg", "-y", "-ss", f"{start:.2f}", "-t", f"{dur:.2f}", "-i", src]
voice_path = None
if req.voice_text and req.voice_text.strip():
wav, sr = synth(req.voice_text.strip(), req.voice or "af_bella")
voice_path = os.path.join(work, "vo.wav")
sf.write(voice_path, wav, sr)
cmd += ["-i", voice_path]
filters = [vf]
if voice_path and req.mute_source:
amap = "[1:a]aresample=48000,apad[aout]"
filters.append(amap)
elif voice_path:
filters.append(
f"[0:a]volume={max(0.0, min(1.0, req.music_volume))},aresample=48000[bed];"
"[1:a]aresample=48000[vo];[bed][vo]amix=inputs=2:duration=first:dropout_transition=0[aout]"
)
elif req.mute_source:
filters.append("anullsrc=channel_layout=stereo:sample_rate=48000[aout]")
else:
filters.append("[0:a]aresample=48000[aout]")
cmd += ["-filter_complex", ";".join(filters), "-map", "[vout]", "-map", "[aout]"]
cmd += ["-t", f"{dur:.2f}", "-r", "30", "-c:v", "libx264", "-preset", "veryfast",
"-crf", "23", "-pix_fmt", "yuv420p", "-c:a", "aac", "-b:a", "128k",
"-movflags", "+faststart", out]
proc = subprocess.run(cmd, capture_output=True, timeout=900)
if proc.returncode != 0 or not os.path.exists(out):
raise HTTPException(500, f"ffmpeg failed: {proc.stderr.decode()[-500:]}")
with open(out, "rb") as f:
data = f.read()
return Response(content=data, media_type="video/mp4")
finally:
shutil.rmtree(work, ignore_errors=True)
try: os.remove(out)
except OSError: pass
class PeaksReq(BaseModel):
url: str
window: float = 15
count: int = 10
@app.post("/clip/peaks")
def clip_peaks(req: PeaksReq, request: Request):
"""Free 'best moment' detection: loudness energy peaks across the source."""
_check_auth(request)
src = _ensure_source(req.url)
win = max(5.0, min(60.0, float(req.window or 15)))
probe = subprocess.run(
["ffprobe", "-v", "error", "-show_entries", "format=duration",
"-of", "default=nw=1:nk=1", src], capture_output=True, timeout=120)
try:
duration = float(probe.stdout.decode().strip())
except Exception:
duration = 0.0
proc = subprocess.run(
["ffmpeg", "-i", src, "-af", "astats=metadata=1:reset=1,ametadata=print:key=lavfi.astats.Overall.RMS_level:file=-",
"-f", "null", "-"], capture_output=True, timeout=900)
text = proc.stdout.decode(errors="ignore") + proc.stderr.decode(errors="ignore")
samples = []
t = None
for line in text.splitlines():
line = line.strip()
if line.startswith("frame:"):
m = re.search(r"pts_time:([0-9.]+)", line)
t = float(m.group(1)) if m else None
elif "RMS_level=" in line and t is not None:
try:
samples.append((t, float(line.split("=")[-1])))
except Exception:
pass
scored = []
if samples:
step = max(1.0, win / 3)
pos = 0.0
end = duration or (samples[-1][0])
while pos + win <= end:
vals = [v for (ts, v) in samples if pos <= ts < pos + win and v > -90]
if vals:
scored.append({"start": round(pos, 2), "score": round(sum(vals) / len(vals), 2)})
pos += step
scored.sort(key=lambda x: x["score"], reverse=True)
picks = []
for c in scored:
if all(abs(c["start"] - p["start"]) >= win for p in picks):
picks.append(c)
if len(picks) >= int(req.count or 10):
break
picks.sort(key=lambda x: x["start"])
return {"duration": duration, "window": win, "peaks": picks}
class FetchReq(BaseModel):
url: str
mode: str = "video" # video | audio
height: int = 1080
DL_CACHE = os.path.join(CLIP_CACHE, "dl")
os.makedirs(DL_CACHE, exist_ok=True)
@app.post("/clip/info")
def clip_info(req: ProbeReq, request: Request):
"""Lightweight metadata for the downloader tool (title, thumb, qualities)."""
_check_auth(request)
info, strategy = _ydl_try(req.url, {"skip_download": True}, False)
heights = sorted({int(f.get("height") or 0) for f in (info.get("formats") or [])
if f.get("height")}, reverse=True)
return {
"title": info.get("title") or "Video",
"uploader": info.get("uploader") or info.get("channel") or "",
"duration": float(info.get("duration") or 0),
"thumbnail": info.get("thumbnail"),
"heights": [h for h in heights if h <= 2160][:8],
"strategy": strategy,
}
@app.post("/clip/fetch")
def clip_fetch(req: FetchReq, request: Request):
"""Full-file download (Crayo-style YouTube downloader): mp4 or mp3."""
_check_auth(request)
key = _src_key(f"{req.url}|{req.mode}|{req.height}")
out = os.path.join(DL_CACHE, key + ".%(ext)s")
if req.mode == "audio":
extra = {"outtmpl": out, "format": "bestaudio/best",
"postprocessors": [{"key": "FFmpegExtractAudio",
"preferredcodec": "mp3", "preferredquality": "192"}]}
else:
h = max(240, min(2160, int(req.height or 1080)))
extra = {"outtmpl": out, "merge_output_format": "mp4",
"concurrent_fragment_downloads": 4,
"format": (f"bestvideo[height<={h}][ext=mp4]+bestaudio[ext=m4a]/"
f"bestvideo[height<={h}]+bestaudio/best[height<={h}]/best")}
info, _strategy = _ydl_try(req.url, extra, True)
hits = [p for p in _glob.glob(os.path.join(DL_CACHE, key + ".*")) if not p.endswith(".part")]
hits.sort(key=os.path.getmtime, reverse=True)
if not hits:
raise HTTPException(500, "download produced no file")
path = hits[0]
for old in sorted(_glob.glob(os.path.join(DL_CACHE, "*")), key=os.path.getmtime, reverse=True)[4:]:
try: os.remove(old)
except OSError: pass
title = re.sub(r"[^A-Za-z0-9 ._-]", "", info.get("title") or "video")[:120]
media = "audio/mpeg" if req.mode == "audio" else "video/mp4"
return FileResponse(path, media_type=media, headers={"X-Title": title})
@app.get("/clip/health")
def clip_health():
try:
import yt_dlp
v = yt_dlp.version.__version__
except Exception as e:
v = f"missing: {e}"
return {"ok": True, "yt_dlp": v}
# ===========================================================================
# FX Studio — advanced "cool edits" generator (kinetic captions, speed ramps,
# whip transitions, flash/shake/glitch, grain, music bed + Kokoro narration).
# Additive: every existing renderer endpoint above is untouched, so this Space
# keeps serving as the backup renderer for the main automation.
# ===========================================================================
try:
import fx_engine as _fx
except Exception as _e: # pragma: no cover
_fx = None
print("fx_engine unavailable:", _e, flush=True)
class FxShot(BaseModel):
image_url: str | None = None
text: str | None = ""
say: str | None = None
seconds: float | None = None
class FxReq(BaseModel):
shots: list[FxShot]
voice: str | None = None
narrate: bool = True
music_url: str | None = None
music_volume: float | None = 0.22
fps: int | None = 24
accent: str | None = "#12E1B6"
font_size: int | None = 62
uppercase: bool | None = True
caption_position: float | None = 0.72
shake: bool | None = True
glitch: bool | None = True
flash: bool | None = True
grain: bool | None = True
@app.get("/fx/health")
def fx_health():
return {"ok": _fx is not None, "engine": "fx-v1"}
@app.post("/fx/render")
def fx_render(req: FxReq):
if _fx is None:
raise HTTPException(500, "fx engine not loaded")
try:
shots = [s for s in req.shots if s][:12]
if not shots:
raise HTTPException(400, "no shots")
fps = max(12, min(req.fps or 24, 30))
voice = req.voice or DEFAULT_VOICE
say_lines = [(s.say or s.text or "").strip() for s in shots]
if req.narrate and any(say_lines):
audio, sr, durations = synth_segments([l or "." for l in say_lines], voice)
durations = [max(1.1, min(d, 6.0)) for d in durations]
else:
durations = [float(s.seconds or 2.2) for s in shots]
sr = 24000
audio = np.zeros(int(sr * sum(durations)), dtype=np.float32)
style = {
"accent": req.accent or "#12E1B6",
"font_size": req.font_size or 62,
"uppercase": req.uppercase if req.uppercase is not None else True,
"caption_position": req.caption_position if req.caption_position is not None else 0.72,
"shake": req.shake, "glitch": req.glitch,
"flash": req.flash, "grain": req.grain,
}
frames = _fx.build_frames(
[{"image_url": s.image_url, "text": s.text or ""} for s in shots],
durations, fps, style, lambda size: anton(size),
)
mp4 = _assemble_animated(
frames, fps, audio, sr,
music_url=req.music_url,
music_volume=req.music_volume if req.music_volume is not None else 0.22,
)
return Response(content=mp4, media_type="video/mp4")
except HTTPException:
raise
except Exception as e:
import traceback
traceback.print_exc()
raise HTTPException(500, f"fx render failed: {type(e).__name__}: {str(e)[:400]}")
import os, subprocess, uuid, random, tempfile, shutil
from fastapi import FastAPI, HTTPException, Request
from fastapi.responses import FileResponse, Response
from pydantic import BaseModel
import requests
import numpy as np
import soundfile as sf
app = FastAPI()
RENDERS_DIR = "/tmp/renders"
os.makedirs(RENDERS_DIR, exist_ok=True)
# ---------------------------------------------------------------------------
# Fonts
# ---------------------------------------------------------------------------
FONT_CANDIDATES = {
"montserrat": ["/usr/share/fonts/truetype/liberation/LiberationSans-Bold.ttf"],
"poppins": ["/usr/share/fonts/truetype/liberation/LiberationSans-Bold.ttf"],
"anton": ["/usr/share/fonts/truetype/freefont/FreeSansBold.ttf"],
"impact": ["/usr/share/fonts/truetype/freefont/FreeSansBold.ttf"],
"oswald": ["/usr/share/fonts/truetype/liberation/LiberationSansNarrow-Bold.ttf"],
"bebas": ["/usr/share/fonts/truetype/liberation/LiberationSansNarrow-Bold.ttf"],
"roboto": ["/usr/share/fonts/truetype/liberation/LiberationSans-Bold.ttf"],
"dejavu sans":["/usr/share/fonts/truetype/dejavu/DejaVuSans-Bold.ttf"],
"serif": ["/usr/share/fonts/truetype/dejavu/DejaVuSerif-Bold.ttf"],
}
FALLBACK_FONT = "/usr/share/fonts/truetype/dejavu/DejaVuSans-Bold.ttf"
def resolve_font(name):
key = (name or "").strip().lower()
for cand in FONT_CANDIDATES.get(key, []):
if os.path.exists(cand):
return cand
return FALLBACK_FONT
# --- Kokoro TTS (lazy-loaded singleton) ---
_kokoro = {"pipe": None}
def get_kokoro(lang_code="a"):
if _kokoro["pipe"] is None:
from kokoro import KPipeline
_kokoro["pipe"] = KPipeline(lang_code=lang_code)
return _kokoro["pipe"]
class TTSReq(BaseModel):
text: str
voice: str | None = "af_bella"
speed: float | None = 1.0
class RenderReq(BaseModel):
voice_url: str
script: str
hook: str | None = None
onscreen_cta: str | None = None
# Style
font: str | None = "Montserrat"
caption_style: str | None = "bold_center"
caption_color: str | None = "#FFFFFF"
title_color: str | None = "#FFFFFF"
cta_color: str | None = "#FFD54A"
accent_color: str | None = "#FFD54A"
background: str | None = "black"
subtitle_size: int | None = 64
title_size: int | None = 88
cta_size: int | None = 56
stroke_width: float | None = 5
shadow: bool | None = True
box_opacity: float | None = 0.55
uppercase: bool | None = False
animation: str | None = "subtle_zoom"
# Caption reveal: "phrase" (one go) | "word" (one word at a time) | "karaoke" (words build up)
caption_animation: str | None = "phrase"
# Placement (fractions of the 1920px-tall canvas)
title_position: float | None = 0.13
caption_position: float | None = 0.63
cta_position: float | None = 0.56
safe_top: float | None = 0.10
safe_bottom: float | None = 0.24
max_seconds: int | None = 60
# Section branding outro
brand_link: str | None = None
brand_text: str | None = None
brand_duration: int | None = 0
seed: int | None = None
def root():
return {"ok": True, "service": "shorts-renderer", "version": 4,
"caption_animations": ["phrase", "word", "karaoke"]}
def health():
return {"ok": True}
def tts(req: TTSReq):
voice = req.voice or "af_bella"
lang = voice[0] if voice else "a"
try:
pipe = get_kokoro(lang_code=lang)