Files
LihonT/scripts/make_release_video.py
cheb0chik 2907c99c44 LihonT 3 Luna alpha 1: the lock, the journal of entries and the front-camera picture
Lock for the whole app, every chat or chosen chats, opened by the phone's own fingerprint, face or lock-screen code. A journal of entries
(time, result, wrong fingers, chats opened) with optional front-camera pictures kept in a private folder, and a clear-all button.
Also: the mascot and the promo scripts for this release.

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
2026-11-11 15:11:30 +03:00

369 lines
14 KiB
Python
Raw Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
"A new version": the mascot (scripts/make_mascot.py) meows and the news appear next to it as subtitles, one line at a time. The same
scene for every release: give it the lines (a word between *stars* is highlighted) and it makes the video, with a meow on every line.
py -X utf8 -B scripts/make_release_video.py # the lines below, 16:9
py -X utf8 -B scripts/make_release_video.py --vertical # 9:16
py -X utf8 -B scripts/make_release_video.py --title "alpha 2" --lines "Мяу!" "Вышла *alpha 2*"
py -X utf8 -B scripts/make_release_video.py --still 3.5 # one frame
Everything is ours: the cat is drawn here, the meows are synthesized here (numpy), the music under them is work/music/store.mp3.
"""
from __future__ import annotations
import argparse
import math
import shutil
import subprocess
import sys
from functools import lru_cache
from multiprocessing import Pool
from pathlib import Path
import numpy as np
from PIL import Image, ImageDraw, ImageFont
from scipy.signal import butter, sosfilt
sys.path.insert(0, str(Path(__file__).resolve().parent))
import make_mascot as MC # noqa: E402
import make_store_music as M # noqa: E402
import make_store_video as V # noqa: E402
from make_store_video import INK, GREY, VIOLET, burst, card, clamp, font, in_out, lerp, out_back, out_cubic, put, put_c, rr, seg # noqa: E402
ROOT = Path(__file__).resolve().parents[1]
OUT = ROOT / "work" / "release-video"
SPRITES = OUT / "sprites"
FPS = 30
SPRITE = 720
MOUTHS = (0.0, 0.55, 1.0)
MEOW = 0.62 # how long one meow lasts
FIRST = 1.0 # the first line starts here
TITLE = "alpha 1"
LINES = [
"Мяу! Вышла новая версия",
"LihonT 3 · Luna *alpha 1*",
"Теперь есть *блокировка* TikTok отпечатком",
"Можно закрыть *все чаты* или только выбранные",
"Журнал входов: кто пытался и его *фото*",
"Скачать на *lihont.space*",
]
W = H = 0
VERT = False
def setup(vertical: bool) -> None:
global W, H, VERT
V.set_format(vertical)
W, H, VERT = V.W, V.H, bool(vertical)
# ---------------------------------------------------------------- the cat
def prepare() -> None:
"""Draws every picture of the cat once: 24 frames of the loop with the mouth shut, half open and open."""
SPRITES.mkdir(parents=True, exist_ok=True)
for frame in range(24):
for level, mouth in enumerate(MOUTHS):
path = SPRITES / ("m_%02d_%d.png" % (frame, level))
if not path.exists():
MC.mascot(frame=frame, mouth=mouth, size=SPRITE).save(path)
@lru_cache(maxsize=80)
def sprite(frame: int, level: int) -> Image.Image:
return Image.open(SPRITES / ("m_%02d_%d.png" % (frame, level))).convert("RGBA")
@lru_cache(maxsize=4)
def shadow(width: int) -> Image.Image:
layer = Image.new("RGBA", (width + 80, width // 4 + 80), (0, 0, 0, 0))
ImageDraw.Draw(layer).ellipse([40, 40, width + 40, width // 4 + 40], fill=(30, 20, 50, 55))
from PIL import ImageFilter
return layer.filter(ImageFilter.GaussianBlur(16))
# ---------------------------------------------------------------- the lines
def parse(line: str) -> list[tuple[str, bool]]:
"""Words with a flag: the ones between stars are highlighted."""
words, on = [], False
for chunk in line.split("*"):
for word in chunk.split():
words.append((word, on))
on = not on
return words
def wrap(words, size: int, width: int):
f = font(size, "bold")
space = f.getlength(" ")
rows, row, run = [], [], 0.0
for word, mark in words:
w = f.getlength(word)
if row and run + space + w > width:
rows.append(row)
row, run = [], 0.0
run += (space if row else 0) + w
row.append((word, mark, w))
if row:
rows.append(row)
return rows, f
GAP = 0.74 # from the start of one meow to the start of the next
def meows_in(line: str) -> int:
"""How many times the cat meows on a line: two, and three on a long one."""
return 3 if len(line.replace("*", "")) > 28 else 2
def hold(line: str) -> float:
n = meows_in(line)
return max(2.4, 0.9 + 0.07 * len(line.replace("*", "")), GAP * (n - 1) + MEOW + 1.0)
def starts(lines) -> list[float]:
"""When each line starts: long ones, and ones with more meows, are kept on the screen a little longer."""
out, t = [], FIRST
for line in lines:
out.append(t)
t += hold(line)
out.append(t)
return out
def meow_times(lines) -> list[tuple[float, int, int]]:
"""Every meow: (when, which one of the line, how many on the line)."""
s = starts(lines)
out = []
for i, line in enumerate(lines):
n = meows_in(line)
for k in range(n):
out.append((s[i] + k * GAP, k, n))
return out
def total(lines) -> float:
return starts(lines)[-1] + 1.6
# ---------------------------------------------------------------- the picture
def cat_geometry():
if VERT:
return W // 2, 600, 760
return 470, 590, 700
def draw_cat(img, t, lines):
s = starts(lines)
cx, cy, size = cat_geometry()
# which meow is going on, and how open the mouth is
open_ = 0.0
for t0, _, _ in meow_times(lines):
if t0 <= t < t0 + MEOW:
open_ = math.sin(math.pi * (t - t0) / MEOW) ** 0.7
level = 0 if open_ < 0.2 else 1 if open_ < 0.65 else 2
pop = out_back(seg(t, 0.15, 0.85), 1.6)
scale = size / SPRITE * pop * (1 + 0.035 * open_)
bob = -10 * open_
put_c(img, shadow(380), cx, cy + size * 0.43, scale * 1.0, clamp(pop) * 0.9)
put_c(img, sprite(int(t * 12) % 24, level), cx, cy + bob, scale, clamp(pop * 1.5))
def draw_title(img, t, lines):
"""The name of the version over the cat: glossy letters that pop in once the first meow is over."""
a = FIRST + GAP + MEOW + 0.2
if t < a:
return
fade = 1.0
cx = W // 2
y = 215 if VERT else 190
V.candy_text(img, cx, y, TITLE.upper(), 120 if VERT else 96, t, a, 0.07, alpha=fade)
put_text = V.text
put_text(img, (cx, y - (105 if VERT else 90)), "новая версия LihonT", 40 if VERT else 34, "semi", GREY, "mm", alpha=out_cubic(seg(t, a, a + 0.4)))
def draw_subtitle(img, t, lines):
s = starts(lines)
index = max([i for i in range(len(lines)) if t >= s[i]], default=-1)
if index < 0:
return
line, t0 = lines[index], s[index]
words = parse(line)
box_w = 940 if VERT else 900
size = 76 if VERT else 74
rows, f = wrap(words, size, box_w - 100)
while len(rows) > 4 and size > 44:
size -= 6
rows, f = wrap(words, size, box_w - 100)
lh = int(size * 1.28)
box_h = len(rows) * lh + 80
come = out_back(seg(t, t0, t0 + 0.35), 1.3)
last = index == len(lines) - 1
leave = 0.0 if last else seg(t, s[index + 1] - 0.18, s[index + 1])
alpha = clamp(come * 1.4) * (1 - leave)
if VERT:
bx, by = W // 2, 1290 + box_h // 2 - 120
else:
bx, by = 1330, H // 2 + 40
layer = card(box_w, box_h, 44, (255, 255, 255), blur=40, dy=18, alpha=52).copy() # the card is cached: it must not be drawn on
pad = 80
# the little tail of the speech card points at the cat
d = ImageDraw.Draw(layer)
if VERT:
d.polygon([(layer.width // 2 - 34 - 160, pad + 4), (layer.width // 2 + 34 - 160, pad + 4), (layer.width // 2 - 160, pad - 40)], fill=(255, 255, 255, 255))
else:
d.polygon([(pad + 4, layer.height // 2 - 34), (pad + 4, layer.height // 2 + 34), (pad - 44, layer.height // 2)], fill=(255, 255, 255, 255))
# the words appear one after another
total_words = sum(len(r) for r in rows)
reveal = min(0.8, 0.13 * total_words)
k = 0
y = pad + 40 + lh // 2 - 4
for row in rows:
row_w = sum(w for _, _, w in row) + f.getlength(" ") * (len(row) - 1)
x = (layer.width - row_w) / 2
for word, mark, w in row:
at = t0 + 0.12 + reveal * k / max(1, total_words)
age = t - at
if age > 0:
lift = (1 - out_cubic(clamp(age / 0.18))) * 14
ink = VIOLET if mark else INK
ImageDraw.Draw(layer).text((x + w / 2, y + lift), word, font=f, fill=ink + (int(255 * clamp(age / 0.12)),), anchor="mm")
x += w + f.getlength(" ")
k += 1
y += lh
put_c(img, layer, bx, by, lerp(0.92, 1.0, come), alpha)
if last and t > t0 + 0.9:
burst(img, bx, by - 30, t, t0 + 0.9, seed=4, n=46, power=640, life=1.3)
def frame_at(t: float, lines) -> Image.Image:
img = Image.new("RGBA", (W, H), (255, 255, 255, 255))
draw_cat(img, t, lines)
draw_title(img, t, lines)
draw_subtitle(img, t, lines)
fade_in = clamp(t / 0.25)
if fade_in < 1:
img.alpha_composite(Image.new("RGBA", (W, H), (255, 255, 255, int(255 * (1 - fade_in)))))
return img
# ---------------------------------------------------------------- the sound
def lowpass_band(x, lo, hi):
return sosfilt(butter(2, [lo, hi], "band", fs=M.SR, output="sos"), x)
def meow(base=560.0, d=MEOW, seed=0):
"""A cat's "мя-а-у": the pitch climbs and falls, the vowel moves from "и" through "а" to "у", with a little breath and vibrato."""
rng = np.random.default_rng(seed)
t = M.tt(d)
x = np.clip(t / d, 0, 1)
f = base * (0.78 + 0.62 * np.sin(np.pi * np.clip(x * 1.15, 0, 1)) ** 0.9 - 0.2 * x) * (1 + 0.012 * np.sin(2 * math.pi * 6.5 * t))
phase = 2 * math.pi * np.cumsum(f) / M.SR
source = sum(np.sin(k * phase) / k ** 1.05 for k in range(1, 16))
low = lowpass_band(source, 300, 700) # "у"
mid = lowpass_band(source, 700, 1500) # "а"
high = lowpass_band(source, 1700, 3200) # "и"
w_i = np.clip(1.4 - 3.2 * x, 0, 1) ** 1.2
w_a = np.sin(np.pi * np.clip(x * 1.1, 0, 1)) ** 1.4
w_u = np.clip(3.0 * (x - 0.55), 0, 1)
voice = low * (0.4 + w_u * 1.1) + mid * (0.25 + w_a * 1.0) + high * (0.15 + w_i * 0.9)
breath = lowpass_band(rng.standard_normal(len(t)), 2500, 7000) * 0.02 * np.sin(np.pi * x)
envelope = np.minimum(1, t / 0.025) * np.clip((d - t) / 0.16, 0, 1) ** 1.3 * (0.85 + 0.15 * np.sin(np.pi * x))
return (voice + breath) * envelope * 0.55
def soundtrack(lines, duration: float, path: Path) -> None:
mix = M.Mix(duration + 0.5)
s = starts(lines)
for i, (t0, k, n) in enumerate(meow_times(lines)):
# each meow of a line a little different: the first is the brightest, the last the lowest and longest
base = [560.0, 610.0, 520.0, 590.0, 640.0][i % 5] * (1.0 - 0.07 * k)
length = MEOW * (1.12 if k == n - 1 and n > 1 else 1.0)
mix.add(meow(base, length, seed=i), t0, 0.9, pan=-0.2 + 0.1 * (k % 2), send=0.1)
if k == 0:
mix.add(M.pop(900, 300, 0.1), t0 + 0.18, 0.18, pan=0.2)
title_at = FIRST + GAP + MEOW + 0.2
mix.add(M.bell(M.midi(88), 1.4), title_at, 0.28, send=0.4)
mix.add(M.sparkle(1.2, 8, 86, 1), title_at + 0.1, 0.4, send=0.4)
end = s[-2]
mix.add(M.sparkle(1.6, 12, 84, 2), end + 0.9, 0.55, send=0.4)
mix.add(M.bell(M.midi(93), 1.8), end + 0.9, 0.3, send=0.5)
data = np.stack([mix.left, mix.right], axis=1)[: int((duration + 0.5) * M.SR)]
data = np.tanh(data * 1.1)
data /= max(1e-9, np.abs(data).max()) / 0.85
M.write(path, data.astype(np.float32))
# ---------------------------------------------------------------- the video
_LINES: list = []
def _init(vertical: bool, lines) -> None:
global _LINES
setup(vertical)
_LINES = lines
def render_frame(index: int) -> bytes:
return frame_at(index / FPS, _LINES).convert("RGB").tobytes()
def main() -> None:
global TITLE
parser = argparse.ArgumentParser()
parser.add_argument("--title", default=TITLE, help="the name of the version, shown in big letters")
parser.add_argument("--lines", nargs="+", default=LINES)
parser.add_argument("--vertical", action="store_true")
parser.add_argument("--still", type=float, nargs="*")
parser.add_argument("--no-music", action="store_true")
parser.add_argument("--jobs", type=int, default=6)
args = parser.parse_args()
TITLE = args.title
setup(args.vertical)
OUT.mkdir(parents=True, exist_ok=True)
prepare()
lines = list(args.lines)
duration = total(lines)
tag = "_9x16" if args.vertical else ""
if args.still:
for t in args.still:
path = OUT / ("still%s_%05.2f.png" % (tag, t))
frame_at(t, lines).convert("RGB").save(path)
print(path)
return
wav = OUT / "meows.wav"
soundtrack(lines, duration, wav)
out = OUT / ("release%s.mp4" % tag)
music = ROOT / "work" / "music" / "store.mp3"
command = [shutil.which("ffmpeg") or "ffmpeg", "-y", "-loglevel", "error", "-f", "rawvideo", "-pix_fmt", "rgb24", "-s", "%dx%d" % (W, H),
"-r", str(FPS), "-i", "-", "-i", str(wav)]
if args.no_music or not music.is_file():
command += ["-af", "afade=t=out:st=%.2f:d=0.6" % (duration - 0.6)]
else:
command += ["-i", str(music), "-filter_complex",
"[2:a]volume=0.2,afade=t=in:st=0:d=0.8,afade=t=out:st=%.2f:d=1.0[b];[1:a][b]amix=inputs=2:duration=first:normalize=0,"
"afade=t=out:st=%.2f:d=0.6[a]" % (duration - 1.0, duration - 0.6), "-map", "0:v", "-map", "[a]"]
command += ["-c:v", "libx264", "-preset", "medium", "-crf", "17", "-pix_fmt", "yuv420p", "-c:a", "aac", "-b:a", "192k", "-t", "%.2f" % duration, str(out)]
proc = subprocess.Popen(command, stdin=subprocess.PIPE)
frames = int(round(duration * FPS))
with Pool(args.jobs, initializer=_init, initargs=(args.vertical, lines)) as pool:
for n, data in enumerate(pool.imap(render_frame, range(frames), chunksize=4)):
proc.stdin.write(data)
if n % 60 == 0:
print("frame %d/%d" % (n, frames), flush=True)
proc.stdin.close()
proc.wait()
print("done:", out)
if __name__ == "__main__":
main()