#!/usr/bin/env python3 """Build a full-access film from films/.py: python3 tools/make.py Fits every beat's footage to Eric's narration, writes the HyperFrames project to film-/, and mixes voice with Slow Render. """ import glob, hashlib, html, importlib.util, json, os, re, shutil, subprocess, sys ROOT = os.path.abspath(os.path.join(os.path.dirname(__file__), "..")) os.chdir(ROOT) NAME = sys.argv[1] spec = importlib.util.spec_from_file_location("film", f"films/{NAME}.py") FILM = importlib.util.module_from_spec(spec); spec.loader.exec_module(FILM) OUT = f"film-{NAME}" VOICE = f"assets/vo/{NAME}" FOOTAGE = "/Users/Shared/airp-recordings/footage" MUSIC = "/Volumes/Expand/Video/Motion Projects/airp-runpod-comfyui/assets/suno/Slow Render.wav" TITLE_SECONDS = 3.6 END_SECONDS = 8.3 GAP = 0.55 SIDE = (970, 955, 800, 62) WIDE = (1620, 800, 150, 46) def norm(word): return re.sub(r"[^a-z0-9]", "", word.lower()) def words(beat_id): return json.load(open(f"{VOICE}/{beat_id}.words.json")) def phrase_time(beat_id, phrase): w = [x for x in words(beat_id) if norm(x["word"])] keys = [norm(x["word"]) for x in w] want = [norm(x) for x in phrase.split()] for i in range(len(keys) - len(want) + 1): if keys[i:i + len(want)] == want: return w[i]["start"] sys.exit(f"no '{phrase}' in {beat_id}: {' '.join(keys)}") def shot_seconds(shot): return (shot[2] - shot[1]) / (shot[3] if len(shot) > 3 else 1) def box_for(beat): x = FILM.CROPS[beat["shots"][0][0]] ratio = x[2] / x[3] w0, h0, l0, t0 = SIDE if beat["layout"] == "side" else WIDE w, h = (w0, round(w0 / ratio)) if w0 / ratio <= h0 else (round(h0 * ratio), h0) return w, h, l0 + (w0 - w) // 2, t0 + (h0 - h) // 2 def cut_clip(beat, duration): w, h, _, _ = box_for(beat) zoom = max([z[1] for z in beat.get("zooms", [])] + [1]) pixels_w = round(w * 2 * zoom / 2) * 2 pixels_h = round(h * 2 * zoom / 2) * 2 shots = list(beat["shots"]) total = sum(shot_seconds(s) for s in shots) key = hashlib.sha1(json.dumps([shots, duration, pixels_w, pixels_h, FILM.CROPS, FILM.SOURCES, "sharp"]).encode()).hexdigest()[:12] path = f"{OUT}/assets/clips/{beat['id']}-{key}.mp4" if os.path.exists(path): return path args, filters, labels, inputs = ["ffmpeg", "-y", "-v", "error"], [], [], {} used = 0.0 for i, shot in enumerate(shots): src, a, b = shot[:3] speed = shot[3] if len(shot) > 3 else 1 room = duration - used length = (b - a) / speed if length > room: b = a + room * speed; length = room hold = room - length if i == len(shots) - 1 else 0 if length <= 0.02: continue if src not in inputs: inputs[src] = len(inputs) args += ["-i", glob.glob(f"{FOOTAGE}/*{FILM.SOURCES[src]}*.mov")[0]] x, y, cw, ch = FILM.CROPS[src] pad = f",tpad=stop_mode=clone:stop_duration={hold:.3f}" if hold > 0.02 else "" filters.append(f"[{inputs[src]}:v]trim={a:.3f}:{b:.3f},setpts=(PTS-STARTPTS)/{speed},fps=30,crop={cw}:{ch}:{x}:{y},scale={pixels_w}:{pixels_h}:force_original_aspect_ratio=decrease:flags=lanczos,unsharp=5:5:0.7:5:5:0,pad={pixels_w}:{pixels_h}:(ow-iw)/2:(oh-ih)/2:0x121922,setsar=1,format=yuv420p{pad}[v{i}]") labels.append(f"[v{i}]") used += length filters.append("".join(labels) + f"concat=n={len(labels)}:v=1:a=0[o]") subprocess.run(args + ["-filter_complex", ";".join(filters), "-map", "[o]", "-c:v", "libx264", "-crf", "12", "-preset", "medium", "-g", "15", path], check=True) return path def schedule(): clock = TITLE_SECONDS timeline = [] for beat in FILM.BEATS: length = words(beat["id"])[-1]["end"] pre = beat.get("pre", 0) scene_start = clock voice_start = clock + pre needed = sum(shot_seconds(s) for s in beat["shots"]) if beat.get("fit") else 0 duration = max(pre + length + GAP, needed) timeline.append({**beat, "start": scene_start, "voice": voice_start, "length": length, "duration": duration}) clock += duration return timeline, clock def note_html(beat, i, note): kind, text = note[1], note[2] shown = ' style="opacity:1"' if i < beat.get("shown", 0) else "" return f'
{text}
' def scene_page(beat, clip): bid = beat["id"] duration = beat["duration"] pre = beat.get("pre", 0) at = lambda phrase: pre + (phrase if isinstance(phrase, (int, float)) else phrase_time(bid, phrase)) body, script = [], [] style = "" if beat.get("chap"): body.append(f'
{beat["chap"]}
') if clip: w, h, left, top = box_for(beat) src = clip.split("/", 1)[1] body.append(f'
') if beat.get("open"): script.append(f'open("#{bid}-win", 0.02);') for z in beat.get("zooms", []): t, s, fx, fy = z x = max(w - s * w, min(0, w / 2 - s * fx * w)) y = max(h - s * h, min(0, h / 2 - s * fy * h)) script.append(f'camera("#{bid}-mv", {at(t) - 0.3:.3f}, {s}, {x:.1f}, {y:.1f}, 0.9);') wrap = "nts-side" if beat["layout"] == "side" else ("nts-wide" if beat["layout"] == "wide" else "nts-card") notes = beat.get("notes", []) body.append(f'
' + "".join(note_html(beat, i, n) for i, n in enumerate(notes)) + "
") pre_shown = beat.get("shown", 0) for i, n in enumerate(notes): target = f"#{bid}-n{i}" if i < pre_shown: continue script.append(f'land("{target}", {at(n[0]):.3f});') if notes and not beat.get("stay"): script.append(f'leave("#{bid}-col", {duration - 0.25:.3f});') page = f""" """ open(f"{OUT}/compositions/{bid}.html", "w").write(page) def extra_scene(sid, inner, duration, script): open(f"{OUT}/compositions/{sid}.html", "w").write(f""" """) def write_cues(total): cues = ['{ t: 0, shape: "dust", s: 10, turn: 0, tilt: 0, flat: 1, sway: 0, dim: 0.3 }'] end = total - END_SECONDS cues.append(f'{{ t: {end - 2.4:.3f}, shape: "mark", s: 4, x: 0, y: 0, sway: 0, turn: 0, twist: 0.12, flat: 1, wave: [0, -1], dur: 2.3 }}') cues.append(f'{{ t: {end + 0.6:.3f}, shape: "mark", s: 7.2, x: 0, y: 0, sway: 0, turn: 0, twist: 0.1, flat: 1, burst: 1.4, dim: 0, fade: [0.95, 0.98], snap: 1, wave: 0, dur: 1.9 }}') open(f"{OUT}/assets/cues.js", "w").write(f"""window.FILM_SECONDS = {total:.3f}; window.FIELD_CUES = [ {",".join(cues)} ]; """) def write_index(timeline, total): hosts = [f'
'] rows = [("intro", 0, TITLE_SECONDS)] + [(b["id"], b["start"], b["duration"]) for b in timeline] + [("outro", total - END_SECONDS, END_SECONDS)] for sid, start, duration in rows: hosts.append(f'
') hosts.append(f'') open(f"{OUT}/index.html", "w").write(f"""
{chr(10).join(hosts)}
""") def mix(timeline, total): args, filters, labels = ["ffmpeg", "-y", "-v", "error"], [], [] for i, beat in enumerate(timeline): args += ["-i", f"{VOICE}/{beat['id']}.mp3"] ms = round(beat["voice"] * 1000) filters.append(f"[{i}:a]aresample=48000,aformat=channel_layouts=stereo,adelay={ms}|{ms}[v{i}]") labels.append(f"[v{i}]") n = len(labels) first = timeline[0]["voice"] last = timeline[-1]["voice"] + timeline[-1]["length"] crossfade, period, start = 22.96, 128.51, 48.25 count = int(total // period) + 2 for i in range(count): args += ["-i", MUSIC] filters.append(f"[{n + i}:a]aresample=48000,aformat=channel_layouts=stereo,atrim={start}:{start + period + crossfade},asetpts=PTS-STARTPTS[m{i}]") prev = "m0" for i in range(1, count): filters.append(f"[{prev}][m{i}]acrossfade=d={crossfade}:c1=qsin:c2=qsin[x{i}]") prev = f"x{i}" under, clear = 10 ** (-26.5 / 20), 10 ** (-12 / 20) gain = f"if(lt(t,{first - 0.6}),{clear}*clip(t/0.8,0,1),if(lt(t,{first}),{clear}+({under}-{clear})*(t-{first - 0.6})/0.6,if(lt(t,{last + 0.2}),{under},if(lt(t,{total - 3}),{under}+({clear}-{under})*clip((t-{last + 0.2})/1.2,0,1),{clear}*clip(({total}-t-0.1)/2.9,0,1)))))" gain = gain.replace(",", "\\,") filters.append(f"[{prev}]atrim=0:{total:.3f},volume='{gain}':eval=frame[m]") filters.append("".join(labels) + f"[m]amix=inputs={n + 1}:normalize=0:dropout_transition=0,apad,atrim=0:{total:.3f}[bed]") os.makedirs("assets/mix", exist_ok=True) bed = f"assets/mix/{NAME}-bed.wav" subprocess.run(args + ["-filter_complex", ";".join(filters), "-map", "[bed]", "-c:a", "pcm_s24le", bed], check=True) r = subprocess.run(["ffmpeg", "-hide_banner", "-i", bed, "-af", "loudnorm=I=-14:TP=-1.5:LRA=11:print_format=json", "-f", "null", "-"], capture_output=True, text=True).stderr m = json.loads(r[r.rindex("{"):r.rindex("}") + 1]) subprocess.run(["ffmpeg", "-y", "-v", "error", "-i", bed, "-af", f"loudnorm=I=-14:TP=-1.5:LRA=11:linear=true:measured_I={m['input_i']}:measured_TP={m['input_tp']}:measured_LRA={m['input_lra']}:measured_thresh={m['input_thresh']}:offset={m['target_offset']},aresample=48000", "-c:a", "aac", "-b:a", "256k", f"{OUT}/assets/mix.m4a"], check=True) def main(): os.makedirs(f"{OUT}/compositions", exist_ok=True) os.makedirs(f"{OUT}/assets/clips", exist_ok=True) for name in ("film.css", "film.js"): shutil.copy(f"video/assets/{name}", f"{OUT}/assets/{name}") if not os.path.exists(f"{OUT}/assets/fonts"): shutil.copytree("video/assets/fonts", f"{OUT}/assets/fonts") shutil.copy("tools/thumbnail/wordmark-dark.svg", f"{OUT}/assets/wordmark-dark.svg") for name in ("hyperframes.json", "package.json"): shutil.copy(f"video/{name}", f"{OUT}/{name}") shutil.copy("video/compositions/field.html", f"{OUT}/compositions/field.html") open(f"{OUT}/assets/film.css", "a").write(open("films/extra.css").read()) timeline, clock = schedule() total = clock + END_SECONDS for name in os.listdir(f"{OUT}/compositions"): if name != "field.html": os.remove(f"{OUT}/compositions/{name}") previous = None for index, beat in enumerate(timeline): clip = None if index + 1 < len(timeline) and timeline[index + 1].get("shown"): beat["stay"] = True if beat.get("shots"): clip = cut_clip(beat, beat["duration"]) beat["open"] = previous != beat["layout"] previous = beat["layout"] scene_page(beat, clip) extra_scene("intro", f'
{FILM.TITLE}
{FILM.SUB}
', TITLE_SECONDS, f'rise("#t1", 0.3); land("#t2", 0.8); leave("#t1, #t2", {TITLE_SECONDS - 0.3});') extra_scene("outro", f'AI Resource Pro
airesourcepro.com
{FILM.CREDIT}
', END_SECONDS, f'const DURATION = {END_SECONDS}; ' + open("films/outro-logo.js").read() + f' tl.to("#e0", {{ opacity: 1, duration: 0.7, ease: "power2.out" }}, 4.35); land("#e1", 4.85); land("#e2", 5.25); leave("#logo3d, #e0, #e1, #e2", {END_SECONDS - 0.7});') write_cues(total) write_index(timeline, total) mix(timeline, total) json.dump([{k: b[k] for k in ("id", "start", "voice", "duration")} for b in timeline], open(f"{OUT}/timeline.json", "w"), indent=0) print(f"{total:.1f} s ({total / 60:.2f} min), {len(timeline)} beats") main()