Avatar frames that follow the outline of the avatar (ring and parts hung on it), packs of frames that arrive from a catalog on the site by themselves, the frame shown to other members through the members service, save an avatar by user name, the diary of the mod, the seek bar on every video, the beta version line and its what is new, plus tests, the catalog builder, the sprites and the scripts that draw them. Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
333 lines
16 KiB
Python
333 lines
16 KiB
Python
#!/usr/bin/env python3
|
||
# -*- coding: utf-8 -*-
|
||
"""
|
||
LihonT 2 «Serena beta»: a video that moves on the beats of a song. Every scene starts on a strong beat, every beat makes the picture
|
||
jump and a new thing pop in. The beats come from scripts/analyze_beats.py (work/music/<song>.beats.json). Only our own material is
|
||
shown: the avatar frames drawn by scripts/frame_render.py, their sprites, the sticker labels of the earlier videos.
|
||
1080x1920, 30 fps, the sticker style of make_luna_promo2.py.
|
||
|
||
The song is chosen by name (work/music/<name>.mp3 and <name>.beats.json); PLANS says how the scenes are laid on its strong beats.
|
||
|
||
usage (from the repository root):
|
||
py -X utf8 -B scripts/make_serena_beat_video.py [--song baka|long] # work/serena-promo/serena_beat_<song>.mp4
|
||
py -X utf8 -B scripts/make_serena_beat_video.py --song long --still 3.0 # one frame as a picture
|
||
"""
|
||
|
||
from __future__ import annotations
|
||
|
||
import argparse
|
||
import json
|
||
import math
|
||
import shutil
|
||
import subprocess
|
||
import sys
|
||
from multiprocessing import Pool
|
||
from pathlib import Path
|
||
|
||
from PIL import Image, ImageDraw
|
||
|
||
sys.path.insert(0, str(Path(__file__).resolve().parent))
|
||
import make_luna_promo2 as V # noqa: E402
|
||
|
||
ROOT = V.ROOT
|
||
W, H, FPS = V.W, V.H, V.FPS
|
||
INK, CREAM, CORAL, YELLOW, MINT, VIOLET, SKY, PINK, WHITE = (V.INK, V.CREAM, V.CORAL, V.YELLOW, V.MINT, V.VIOLET, V.SKY, V.PINK, V.WHITE)
|
||
clamp, ease_out_cubic, ease_out_back = V.clamp, V.ease_out_cubic, V.ease_out_back
|
||
CACHE = ROOT / "work" / "serena-promo" / "beat-cache"
|
||
CAT_ORDER = ["none", "basic.cat", "basic.helmet", "basic.flower", "basic.crown", "basic.flame", "basic.cat", "basic.crown",
|
||
"basic.flower", "basic.helmet", "basic.flame", "basic.cat"]
|
||
NAMES = {"basic.cat": "Ушки", "basic.helmet": "Скафандр", "basic.flower": "Цветок", "basic.crown": "Корона", "basic.flame": "Пламя"}
|
||
SHAPES = ["circle", "flower", "squircle", "hexagon", "heart", "triangle", "flower", "heart"]
|
||
SHAPE_NAMES = {"circle": "Круг", "flower": "Цветочек", "squircle": "Квадрат", "hexagon": "Шестиугольник", "heart": "Сердечко",
|
||
"triangle": "Треугольник"}
|
||
# scene, the strong beat it starts on (None = the very start), the strong beat it ends on (None = the end), background colour
|
||
PLANS = {
|
||
"baka": [("intro", None, 0, CREAM), ("frames", 0, 2, (255, 226, 200)), ("grid", 2, 3, (215, 200, 255)),
|
||
("packs", 3, 5, (190, 240, 220)), ("list", 5, 7, (255, 236, 150)), ("more", 7, 9, (255, 205, 225)),
|
||
("outro", 9, None, (255, 196, 176))],
|
||
"long": [("intro", None, 0, CREAM), ("frames", 0, 3, (255, 226, 200)), ("grid", 3, 4, (215, 200, 255)),
|
||
("packs", 4, 6, (190, 240, 220)), ("list", 6, 9, (255, 236, 150)), ("more", 9, 12, (255, 205, 225)),
|
||
("shapes", 12, 14, (215, 200, 255)), ("outro", 14, None, (255, 196, 176))],
|
||
}
|
||
|
||
# filled by configure()
|
||
SONG = None
|
||
B: list = []
|
||
STRONG: list = []
|
||
DURATION = 0.0
|
||
FRAMES = 0
|
||
SCENES: list = []
|
||
_IMAGES: dict = {}
|
||
|
||
|
||
def configure(name: str) -> None:
|
||
global SONG, B, STRONG, DURATION, FRAMES, SCENES
|
||
SONG = ROOT / "work" / "music" / (name + ".mp3")
|
||
data = json.loads(SONG.with_suffix(".beats.json").read_text(encoding="utf-8"))
|
||
B, STRONG = data["beats"], data["strong_beats"]
|
||
DURATION = round(data["duration"], 2)
|
||
FRAMES = int(round(DURATION * FPS))
|
||
SCENES = []
|
||
for scene, a, b, color in PLANS[name]:
|
||
SCENES.append((scene, 0.0 if a is None else STRONG[a], DURATION if b is None else STRONG[b], color))
|
||
|
||
|
||
def beat_index(t: float) -> int:
|
||
"""The number of the last beat that has happened by time t (-1 before the first one)."""
|
||
n = -1
|
||
for i, b in enumerate(B):
|
||
if t >= b:
|
||
n = i
|
||
return n
|
||
|
||
|
||
def since_beat(t: float) -> float:
|
||
n = beat_index(t)
|
||
return t - B[n] if n >= 0 else 9.0
|
||
|
||
|
||
def jump(t: float) -> float:
|
||
"""1 right on a beat, falling to 0 in about a fifth of a second."""
|
||
return max(0.0, 1.0 - since_beat(t) / 0.2) ** 2
|
||
|
||
|
||
def pop_at(t: float, t0: float, speed: float = 0.32) -> float:
|
||
return ease_out_back((t - t0) / speed) if t >= t0 else 0.0
|
||
|
||
|
||
def prepare_images() -> None:
|
||
"""Draws every frame on a round avatar (and one frame on every shape) once, it takes a while, and keeps the pictures."""
|
||
CACHE.mkdir(parents=True, exist_ok=True)
|
||
import frame_render as FR
|
||
import make_frame_on_shape as S
|
||
pack = json.loads((ROOT / "frames" / "basic" / "pack.json").read_text(encoding="utf-8"))
|
||
for frame in pack["frames"]:
|
||
path = CACHE / ("basic.%s.png" % frame["id"])
|
||
if not path.exists():
|
||
FR.render(frame, "circle", 1000, 520).save(path)
|
||
if frame["id"] == "cat":
|
||
for shape in set(SHAPES):
|
||
path = CACHE / ("cat-on-%s.png" % shape)
|
||
if not path.exists():
|
||
FR.render(frame, shape, 1000, 520).save(path)
|
||
plain = CACHE / "none.png"
|
||
if not plain.exists():
|
||
img = Image.new("RGBA", (1000, 1000), (0, 0, 0, 0))
|
||
img.paste(S.avatar(520), (240, 320), S.shape_mask("circle", 520))
|
||
ImageDraw.Draw(img).ellipse([240, 320, 760, 840], outline=INK + (255,), width=8)
|
||
img.save(plain)
|
||
|
||
|
||
def image(name: str) -> Image.Image:
|
||
if name not in _IMAGES:
|
||
if name.startswith("sprite:"):
|
||
_IMAGES[name] = Image.open(ROOT / "frames" / "basic" / name[7:]).convert("RGBA")
|
||
elif name == "grid":
|
||
_IMAGES[name] = Image.open(ROOT / "work" / "frames" / "frames_grid.png").convert("RGBA")
|
||
else:
|
||
_IMAGES[name] = Image.open(CACHE / (name + ".png")).convert("RGBA")
|
||
return _IMAGES[name]
|
||
|
||
|
||
def small_burst(layer, cx, cy, t, t0, seed):
|
||
V.burst(layer, cx, cy, t, t0, seed=seed, count=22, power=620)
|
||
|
||
|
||
# ---------------------------------------------------------------- scenes (t is the time of the whole video, t0 the start of the scene)
|
||
|
||
def scene_intro(layer, t, t0):
|
||
k = pop_at(t, B[0], 0.5)
|
||
V.place(layer, V.ASSETS["logo"], W / 2, 860, 0.5 * k * (1 + 0.05 * jump(t)), math.sin(t * 2.4) * 6 + (1 - k) * 300)
|
||
V.burst(layer, W / 2, 860, t, B[0], seed=11, count=50, power=900)
|
||
if len(B) > 1 and t >= B[1]:
|
||
V.title(layer, max(0.0, t - B[1]), "LihonT 2", "Serena beta", y=1300)
|
||
|
||
|
||
def scene_frames(layer, t, t0):
|
||
first = beat_index(t0 + 0.01)
|
||
index = max(0, min(beat_index(t) - first, len(CAT_ORDER) - 1))
|
||
name = CAT_ORDER[index]
|
||
born = B[first + index]
|
||
k = 0.8 + 0.2 * ease_out_back((t - born) / 0.28) if t >= born else 1.0
|
||
V.place(layer, image(name), W / 2, 880, 1.0 * k * (1 + 0.025 * jump(t)), math.sin(t * 3) * 2.5)
|
||
small_burst(layer, W / 2, 1420, t, born, seed=20 + index)
|
||
V.label(layer, W / 2, 230, "Рамки для аватарок", pop_at(t, t0, 0.3), size=64, fill=YELLOW)
|
||
V.label(layer, W / 2, 1520, NAMES.get(name, "Без рамки"), pop_at(t, born, 0.22), size=76, fill=WHITE)
|
||
V.label(layer, W / 2, 1680, "и её видят все с модом", pop_at(t, B[first + 4], 0.3), size=44, fill=MINT)
|
||
|
||
|
||
def scene_grid(layer, t, t0):
|
||
grid = image("grid")
|
||
card = grid.resize((960, int(grid.height * 960 / grid.width)), Image.Resampling.LANCZOS)
|
||
k = pop_at(t, t0, 0.35) * (1 + 0.03 * jump(t))
|
||
V.sticker(layer, (W / 2 - card.width / 2 - 20, 540, W / 2 + card.width / 2 + 20, 560 + card.height + 20), V.WHITE, radius=36, shadow=12)
|
||
layer.alpha_composite(card, (int(W / 2 - card.width / 2), 560))
|
||
V.label(layer, W / 2, 260, "на любой форме", pop_at(t, t0, 0.3), size=76, fill=WHITE)
|
||
V.label(layer, W / 2, 420, "круг · цветок · сердце · шестиугольник", pop_at(t, t0 + 0.4, 0.3), size=40, fill=YELLOW)
|
||
V.label(layer, W / 2, 1600, "ободок повторяет контур", pop_at(t, t0 + 0.8, 0.3) * k, size=52, fill=MINT)
|
||
|
||
|
||
def scene_packs(layer, t, t0):
|
||
sprites = ["cat-ear.png", "crown.png", "helmet-antenna.png", "flame-tall.png", "cat-tuft.png", "helmet-collar.png", "flame-mid.png",
|
||
"cat-cowlick.png"]
|
||
first = beat_index(t0 + 0.01)
|
||
V.label(layer, W / 2, 250, "Новые паки", pop_at(t, t0, 0.3), size=84, fill=WHITE)
|
||
V.label(layer, W / 2, 400, "приходят сами", pop_at(t, t0 + 0.4, 0.3), size=64, fill=YELLOW)
|
||
for n, name in enumerate(sprites):
|
||
born = B[first + n]
|
||
k = pop_at(t, born, 0.3)
|
||
if k <= 0:
|
||
continue
|
||
col, row = n % 4, n // 4
|
||
cx, cy = 190 + col * 233, 760 + row * 330
|
||
V.sticker(layer, (cx - 105, cy - 125, cx + 105, cy + 125), WHITE if (col + row) % 2 == 0 else CREAM, radius=34, shadow=8)
|
||
sp = image("sprite:" + name)
|
||
V.place(layer, sp, cx, cy, min(190 / sp.width, 220 / sp.height) * k, (n % 3 - 1) * 4)
|
||
small_burst(layer, cx, cy, t, born, seed=40 + n)
|
||
V.label(layer, W / 2, 1500, "без обновления мода", pop_at(t, B[first + 8] if first + 8 < len(B) else t0 + 3.0, 0.3), size=56, fill=MINT)
|
||
V.label(layer, W / 2, 1650, "NEW", pop_at(t, B[first + 10] if first + 10 < len(B) else t0 + 3.4, 0.3), size=70, fill=CORAL)
|
||
|
||
|
||
def scene_list(layer, t, t0):
|
||
items = [("Дневник мода", MINT), ("Полоса перемотки", SKY), ("Аватарка по нику", YELLOW), ("Призрак", PINK),
|
||
("Темы и Windows 95", VIOLET), ("Плагины со значками", MINT), ("Режим DEBUG", CORAL), ("Рамки в паках", YELLOW),
|
||
("Свои стили", SKY), ("Открытый код", PINK), ("Без рекламы", MINT), ("Плагины без кода", VIOLET)]
|
||
first = beat_index(t0 + 0.01)
|
||
V.label(layer, W / 2, 230, "и ещё", pop_at(t, t0, 0.3), size=84, fill=WHITE)
|
||
last = [s for s in SCENES if s[0] == "list"][0][2]
|
||
shown = [n for n in range(len(items)) if first + n < len(B) and B[first + n] < last - 0.05]
|
||
step = min(160, 1250 // max(1, len(shown)))
|
||
for n in shown:
|
||
text, color = items[n]
|
||
born = B[first + n]
|
||
k = pop_at(t, born, 0.3)
|
||
if k <= 0:
|
||
continue
|
||
x = W / 2 + (-1) ** n * 40
|
||
y = 400 + n * step
|
||
V.label(layer, x, y, text, k, size=58, fill=color)
|
||
small_burst(layer, x, y, t, born, seed=60 + n)
|
||
|
||
|
||
def scene_more(layer, t, t0):
|
||
first = beat_index(t0 + 0.01)
|
||
k = pop_at(t, B[first], 0.32)
|
||
V.place(layer, V.ghost(380), W / 2 - 250, 620 + math.sin(t * 5) * 14, k * (1 + 0.04 * jump(t)), math.sin(t * 3) * 6)
|
||
V.label(layer, W / 2 - 250, 840, "Призрак", pop_at(t, B[first] + 0.1, 0.3), size=56, fill=WHITE)
|
||
k = pop_at(t, B[first + 2], 0.32)
|
||
V.place(layer, V.ASSETS["flame_lit"][int(t * 8) % 4], W / 2 + 250, 640, 0.7 * k * (1 + 0.04 * jump(t)), math.sin(t * 4) * 5)
|
||
V.label(layer, W / 2 + 250, 840, "Огоньки", pop_at(t, B[first + 2] + 0.1, 0.3), size=56, fill=YELLOW)
|
||
k = pop_at(t, B[first + 4], 0.32)
|
||
if k > 0:
|
||
d = ImageDraw.Draw(layer, "RGBA")
|
||
cx, cy, w, h = W / 2, 1180, 700 * k, 330 * k
|
||
d.rectangle([cx - w / 2 + 12, cy - h / 2 + 12, cx + w / 2 + 12, cy + h / 2 + 12], fill=INK + (255,))
|
||
d.rectangle([cx - w / 2, cy - h / 2, cx + w / 2, cy + h / 2], fill=(192, 192, 192, 255), outline=INK + (255,), width=5)
|
||
d.rectangle([cx - w / 2 + 8, cy - h / 2 + 8, cx + w / 2 - 8, cy - h / 2 + 8 + 56 * k], fill=(0, 0, 128, 255))
|
||
d.text((cx - w / 2 + 24, cy - h / 2 + 8 + 28 * k), "LihonT", font=V.P.font(max(8, int(34 * k)), True), fill=WHITE + (255,), anchor="lm")
|
||
d.rectangle([cx + w / 2 - 70 * k, cy - h / 2 + 14 * k, cx + w / 2 - 14 * k, cy - h / 2 + 52 * k], fill=(192, 192, 192, 255),
|
||
outline=INK + (255,), width=3)
|
||
d.text((cx, cy + 40 * k), "Windows 95", font=V.P.font(max(8, int(60 * k)), True), fill=INK + (255,), anchor="mm")
|
||
V.label(layer, W / 2, 1560, "Сброс как «Очистить кэш»", pop_at(t, B[first + 6], 0.32), size=50, fill=MINT)
|
||
V.label(layer, W / 2, 1700, "режим DEBUG", pop_at(t, B[first + 8] if first + 8 < len(B) else B[first + 7], 0.3), size=60, fill=CORAL)
|
||
|
||
|
||
def scene_shapes(layer, t, t0):
|
||
"""One frame (the ears) moving over the shapes of the avatar, one shape on every beat."""
|
||
first = beat_index(t0 + 0.01)
|
||
index = max(0, min(beat_index(t) - first, len(SHAPES) - 1))
|
||
shape = SHAPES[index]
|
||
born = B[first + index]
|
||
k = 0.8 + 0.2 * ease_out_back((t - born) / 0.28) if t >= born else 1.0
|
||
V.place(layer, image("cat-on-" + shape), W / 2, 900, 1.0 * k * (1 + 0.025 * jump(t)), math.sin(t * 3) * 2.5)
|
||
small_burst(layer, W / 2, 1420, t, born, seed=90 + index)
|
||
V.label(layer, W / 2, 230, "рамка сама ложится", pop_at(t, t0, 0.3), size=64, fill=YELLOW)
|
||
V.label(layer, W / 2, 1520, SHAPE_NAMES[shape], pop_at(t, born, 0.22), size=76, fill=WHITE)
|
||
|
||
|
||
def scene_outro(layer, t, t0):
|
||
k = pop_at(t, t0, 0.5)
|
||
V.place(layer, V.ASSETS["logo"], W / 2, 640, 0.46 * k * (1 + 0.05 * jump(t)), math.sin(t * 2.4) * 6 + (1 - k) * 280)
|
||
V.burst(layer, W / 2, 640, t, t0, seed=77, count=60, power=1000)
|
||
V.burst(layer, W / 2, 640, t, STRONG[-1], seed=78, count=60, power=1000)
|
||
V.title(layer, max(0.0, t - t0), "Serena beta", "Открытый код · лицензия VCBFU v2", y=1020)
|
||
V.label(layer, W / 2, 1300, "git.lihont.space", pop_at(t, t0 + 0.4, 0.3), size=60, fill=YELLOW)
|
||
V.label(layer, W / 2, 1450, "Telegram · @lihont", pop_at(t, t0 + 0.8, 0.3), size=60, fill=WHITE)
|
||
|
||
|
||
SCENE_DRAW = {"intro": scene_intro, "frames": scene_frames, "grid": scene_grid, "packs": scene_packs, "list": scene_list,
|
||
"more": scene_more, "shapes": scene_shapes, "outro": scene_outro}
|
||
|
||
|
||
def frame_at(t: float) -> Image.Image:
|
||
V.init_assets()
|
||
index = 0
|
||
for n, scene in enumerate(SCENES):
|
||
if t >= scene[1]:
|
||
index = n
|
||
name, start, end, color = SCENES[index]
|
||
img = Image.new("RGBA", (W, H), color + (255,))
|
||
if index > 0 and t - start < 0.3: # a circle of the new colour opens on the strong beat
|
||
img = Image.new("RGBA", (W, H), SCENES[index - 1][3] + (255,))
|
||
r = 1800 * ease_out_cubic((t - start) / 0.3)
|
||
mask = Image.new("L", (W, H), 0)
|
||
ImageDraw.Draw(mask).ellipse([W / 2 - r, H / 2 - r, W / 2 + r, H / 2 + r], fill=255)
|
||
img.paste(Image.new("RGBA", (W, H), color + (255,)), (0, 0), mask)
|
||
ox, oy = int(t * 30) % 80, int(t * 18) % 80
|
||
img.alpha_composite(V.ASSETS["dots"], (-ox, -oy))
|
||
layer = Image.new("RGBA", (W, H), (0, 0, 0, 0))
|
||
SCENE_DRAW[name](layer, t, start)
|
||
zoom = 1.0 + 0.03 * jump(t) # the whole picture jumps a little on every beat
|
||
if zoom > 1.001:
|
||
big = layer.resize((int(W * zoom), int(H * zoom)), Image.Resampling.BILINEAR)
|
||
layer = big.crop(((big.width - W) // 2, (big.height - H) // 2, (big.width - W) // 2 + W, (big.height - H) // 2 + H))
|
||
img.alpha_composite(layer)
|
||
for s in STRONG: # a white flash on the strong beats
|
||
d = t - s
|
||
if 0 <= d < 0.16:
|
||
img.alpha_composite(Image.new("RGBA", (W, H), (255, 255, 255, int(110 * (1 - d / 0.16)))))
|
||
return img
|
||
|
||
|
||
def render_frame(index: int) -> bytes:
|
||
return frame_at(index / FPS).convert("RGB").tobytes()
|
||
|
||
|
||
def _init(song: str) -> None:
|
||
configure(song)
|
||
V.init_assets()
|
||
|
||
|
||
def main() -> None:
|
||
parser = argparse.ArgumentParser()
|
||
parser.add_argument("--song", default="baka", choices=sorted(PLANS))
|
||
parser.add_argument("--still", type=float)
|
||
parser.add_argument("--jobs", type=int, default=6)
|
||
args = parser.parse_args()
|
||
configure(args.song)
|
||
out = ROOT / "work" / "serena-promo" / ("serena_beat_%s.mp4" % args.song)
|
||
out.parent.mkdir(parents=True, exist_ok=True)
|
||
prepare_images()
|
||
if args.still is not None:
|
||
path = out.parent / ("still_beat_%s_%.2f.png" % (args.song, args.still))
|
||
frame_at(args.still).convert("RGB").save(path)
|
||
print(path)
|
||
return
|
||
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(SONG), "-c:v", "libx264", "-preset", "medium",
|
||
"-crf", "18", "-pix_fmt", "yuv420p", "-af", "afade=t=out:st=%.2f:d=0.5" % (DURATION - 0.5), "-c:a", "aac", "-b:a", "192k",
|
||
"-t", "%.2f" % DURATION, str(out)]
|
||
proc = subprocess.Popen(command, stdin=subprocess.PIPE)
|
||
with Pool(args.jobs, initializer=_init, initargs=(args.song,)) 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()
|