Branchwell

AI Resource Pro / full-access-films / tools / make.py

1#!/usr/bin/env python3
2"""Build a full-access film from films/<name>.py: python3 tools/make.py <name>
3
4Fits every beat's footage to Eric's narration, writes the HyperFrames project to film-<name>/, and mixes voice with Slow Render.
5"""
6import glob, hashlib, html, importlib.util, json, os, re, shutil, subprocess, sys
7
8ROOT = os.path.abspath(os.path.join(os.path.dirname(__file__), ".."))
9os.chdir(ROOT)
10NAME = sys.argv[1]
11spec = importlib.util.spec_from_file_location("film", f"films/{NAME}.py")
12FILM = importlib.util.module_from_spec(spec); spec.loader.exec_module(FILM)
13OUT = f"film-{NAME}"
14VOICE = f"assets/vo/{NAME}"
15FOOTAGE = "/Users/Shared/airp-recordings/footage"
16MUSIC = "/Volumes/Expand/Video/Motion Projects/airp-runpod-comfyui/assets/suno/Slow Render.wav"
17TITLE_SECONDS = 3.6
18END_SECONDS = 8.3
19GAP = 0.55
20SIDE = (970, 955, 800, 62)
21WIDE = (1620, 800, 150, 46)
22
23
24def norm(word):
25 return re.sub(r"[^a-z0-9]", "", word.lower())
26
27
28def words(beat_id):
29 return json.load(open(f"{VOICE}/{beat_id}.words.json"))
30
31
32def phrase_time(beat_id, phrase):
33 w = [x for x in words(beat_id) if norm(x["word"])]
34 keys = [norm(x["word"]) for x in w]
35 want = [norm(x) for x in phrase.split()]
36 for i in range(len(keys) - len(want) + 1):
37 if keys[i:i + len(want)] == want:
38 return w[i]["start"]
39 sys.exit(f"no '{phrase}' in {beat_id}: {' '.join(keys)}")
40
41
42def shot_seconds(shot):
43 return (shot[2] - shot[1]) / (shot[3] if len(shot) > 3 else 1)
44
45
46def box_for(beat):
47 x = FILM.CROPS[beat["shots"][0][0]]
48 ratio = x[2] / x[3]
49 w0, h0, l0, t0 = SIDE if beat["layout"] == "side" else WIDE
50 w, h = (w0, round(w0 / ratio)) if w0 / ratio <= h0 else (round(h0 * ratio), h0)
51 return w, h, l0 + (w0 - w) // 2, t0 + (h0 - h) // 2
52
53
54def cut_clip(beat, duration):
55 w, h, _, _ = box_for(beat)
56 zoom = max([z[1] for z in beat.get("zooms", [])] + [1])
57 pixels_w = round(w * 2 * zoom / 2) * 2
58 pixels_h = round(h * 2 * zoom / 2) * 2
59 shots = list(beat["shots"])
60 total = sum(shot_seconds(s) for s in shots)
61 key = hashlib.sha1(json.dumps([shots, duration, pixels_w, pixels_h, FILM.CROPS, FILM.SOURCES, "sharp"]).encode()).hexdigest()[:12]
62 path = f"{OUT}/assets/clips/{beat['id']}-{key}.mp4"
63 if os.path.exists(path):
64 return path
65 args, filters, labels, inputs = ["ffmpeg", "-y", "-v", "error"], [], [], {}
66 used = 0.0
67 for i, shot in enumerate(shots):
68 src, a, b = shot[:3]
69 speed = shot[3] if len(shot) > 3 else 1
70 room = duration - used
71 length = (b - a) / speed
72 if length > room:
73 b = a + room * speed; length = room
74 hold = room - length if i == len(shots) - 1 else 0
75 if length <= 0.02:
76 continue
77 if src not in inputs:
78 inputs[src] = len(inputs)
79 args += ["-i", glob.glob(f"{FOOTAGE}/*{FILM.SOURCES[src]}*.mov")[0]]
80 x, y, cw, ch = FILM.CROPS[src]
81 pad = f",tpad=stop_mode=clone:stop_duration={hold:.3f}" if hold > 0.02 else ""
82 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}]")
83 labels.append(f"[v{i}]")
84 used += length
85 filters.append("".join(labels) + f"concat=n={len(labels)}:v=1:a=0[o]")
86 subprocess.run(args + ["-filter_complex", ";".join(filters), "-map", "[o]", "-c:v", "libx264", "-crf", "12", "-preset", "medium", "-g", "15", path], check=True)
87 return path
88
89
90def schedule():
91 clock = TITLE_SECONDS
92 timeline = []
93 for beat in FILM.BEATS:
94 length = words(beat["id"])[-1]["end"]
95 pre = beat.get("pre", 0)
96 scene_start = clock
97 voice_start = clock + pre
98 needed = sum(shot_seconds(s) for s in beat["shots"]) if beat.get("fit") else 0
99 duration = max(pre + length + GAP, needed)
100 timeline.append({**beat, "start": scene_start, "voice": voice_start, "length": length, "duration": duration})
101 clock += duration
102 return timeline, clock
103
104
105def note_html(beat, i, note):
106 kind, text = note[1], note[2]
107 shown = ' style="opacity:1"' if i < beat.get("shown", 0) else ""
108 return f'<div id="{beat["id"]}-n{i}" class="nt nt-{kind}"{shown}>{text}</div>'
109
110
111def scene_page(beat, clip):
112 bid = beat["id"]
113 duration = beat["duration"]
114 pre = beat.get("pre", 0)
115 at = lambda phrase: pre + (phrase if isinstance(phrase, (int, float)) else phrase_time(bid, phrase))
116 body, script = [], []
117 style = ""
118 if beat.get("chap"):
119 body.append(f'<div id="{bid}-tag" class="tag chap">{beat["chap"]}</div>')
120 if clip:
121 w, h, left, top = box_for(beat)
122 src = clip.split("/", 1)[1]
123 body.append(f'<div id="{bid}-win" class="win" style="left:{left}px;top:{top}px;width:{w}px;height:{h}px"><div id="{bid}-mv" class="mv" style="width:{w}px;height:{h}px"><video id="{bid}-v" class="clip" src="{src}" data-start="0" data-duration="{duration:.3f}" muted playsinline style="width:{w}px;height:{h}px"></video></div></div>')
124 if beat.get("open"):
125 script.append(f'open("#{bid}-win", 0.02);')
126 for z in beat.get("zooms", []):
127 t, s, fx, fy = z
128 x = max(w - s * w, min(0, w / 2 - s * fx * w))
129 y = max(h - s * h, min(0, h / 2 - s * fy * h))
130 script.append(f'camera("#{bid}-mv", {at(t) - 0.3:.3f}, {s}, {x:.1f}, {y:.1f}, 0.9);')
131 wrap = "nts-side" if beat["layout"] == "side" else ("nts-wide" if beat["layout"] == "wide" else "nts-card")
132 notes = beat.get("notes", [])
133 body.append(f'<div id="{bid}-col" class="{wrap}">' + "".join(note_html(beat, i, n) for i, n in enumerate(notes)) + "</div>")
134 pre_shown = beat.get("shown", 0)
135 for i, n in enumerate(notes):
136 target = f"#{bid}-n{i}"
137 if i < pre_shown:
138 continue
139 script.append(f'land("{target}", {at(n[0]):.3f});')
140 if notes and not beat.get("stay"):
141 script.append(f'leave("#{bid}-col", {duration - 0.25:.3f});')
142 page = f"""<template>
143 <style>
144 #root {{ position: absolute; inset: 0; }}
145 </style>
146 <div id="root" data-composition-id="{bid}" data-width="1920" data-height="1080">
147 {''.join(body)}
148 </div>
149 <script>
150 (() => {{
151 const tl = gsap.timeline({{ paused: true }});
152 const {{ land, rise, leave, card, cardOut, mark, open, camera }} = Film(tl);
153 {' '.join(script)}
154 tl.to({{}}, {{ duration: {duration:.3f} }}, 0);
155 window.__timelines["{bid}"] = tl;
156 }})();
157 </script>
158</template>
159"""
160 open(f"{OUT}/compositions/{bid}.html", "w").write(page)
161
162
163def extra_scene(sid, inner, duration, script):
164 open(f"{OUT}/compositions/{sid}.html", "w").write(f"""<template>
165 <style>#root {{ position: absolute; inset: 0; }}</style>
166 <div id="root" data-composition-id="{sid}" data-width="1920" data-height="1080">{inner}</div>
167 <script>
168 (() => {{
169 const tl = gsap.timeline({{ paused: true }});
170 const {{ land, rise, leave }} = Film(tl);
171 {script}
172 tl.to({{}}, {{ duration: {duration:.3f} }}, 0);
173 window.__timelines["{sid}"] = tl;
174 }})();
175 </script>
176</template>
177""")
178
179
180def write_cues(total):
181 cues = ['{ t: 0, shape: "dust", s: 10, turn: 0, tilt: 0, flat: 1, sway: 0, dim: 0.3 }']
182 end = total - END_SECONDS
183 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 }}')
184 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 }}')
185 open(f"{OUT}/assets/cues.js", "w").write(f"""window.FILM_SECONDS = {total:.3f};
186window.FIELD_CUES = [
187 {",".join(cues)}
188];
189""")
190
191
192def write_index(timeline, total):
193 hosts = [f'<div id="field" data-composition-id="field" data-composition-src="compositions/field.html" data-start="0" data-duration="{total:.3f}" data-track-index="0" data-track-kind="graphics" data-width="1920" data-height="1080"></div>']
194 rows = [("intro", 0, TITLE_SECONDS)] + [(b["id"], b["start"], b["duration"]) for b in timeline] + [("outro", total - END_SECONDS, END_SECONDS)]
195 for sid, start, duration in rows:
196 hosts.append(f'<div id="{sid}" data-composition-id="{sid}" data-composition-src="compositions/{sid}.html" data-start="{start:.3f}" data-duration="{duration:.3f}" data-track-index="1" data-track-kind="graphics" data-width="1920" data-height="1080"></div>')
197 hosts.append(f'<audio id="mix" class="clip" src="assets/mix.m4a" data-start="0" data-duration="{total:.3f}" data-track-index="2" data-volume="1"></audio>')
198 open(f"{OUT}/index.html", "w").write(f"""<!doctype html>
199<html lang="en">
200 <head>
201 <meta charset="UTF-8" />
202 <meta name="viewport" content="width=1920, height=1080" />
203 <script src="https://cdn.jsdelivr.net/npm/gsap@3.14.2/dist/gsap.min.js"></script>
204 <script src="https://cdn.jsdelivr.net/npm/three@0.160.1/build/three.min.js"></script>
205 <script src="assets/cues.js"></script>
206 <script src="assets/film.js"></script>
207 <link rel="stylesheet" href="assets/film.css" />
208 </head>
209 <body>
210 <div id="root" data-composition-id="main" data-start="0" data-duration="{total:.3f}" data-width="1920" data-height="1080" data-fps="30">
211 {chr(10).join(hosts)}
212 </div>
213 <script>
214 window.__timelines = window.__timelines || {{}};
215 window.__timelines["main"] = gsap.timeline({{ paused: true }});
216 </script>
217 </body>
218</html>
219""")
220
221
222def mix(timeline, total):
223 args, filters, labels = ["ffmpeg", "-y", "-v", "error"], [], []
224 for i, beat in enumerate(timeline):
225 args += ["-i", f"{VOICE}/{beat['id']}.mp3"]
226 ms = round(beat["voice"] * 1000)
227 filters.append(f"[{i}:a]aresample=48000,aformat=channel_layouts=stereo,adelay={ms}|{ms}[v{i}]")
228 labels.append(f"[v{i}]")
229 n = len(labels)
230 first = timeline[0]["voice"]
231 last = timeline[-1]["voice"] + timeline[-1]["length"]
232 crossfade, period, start = 22.96, 128.51, 48.25
233 count = int(total // period) + 2
234 for i in range(count):
235 args += ["-i", MUSIC]
236 filters.append(f"[{n + i}:a]aresample=48000,aformat=channel_layouts=stereo,atrim={start}:{start + period + crossfade},asetpts=PTS-STARTPTS[m{i}]")
237 prev = "m0"
238 for i in range(1, count):
239 filters.append(f"[{prev}][m{i}]acrossfade=d={crossfade}:c1=qsin:c2=qsin[x{i}]")
240 prev = f"x{i}"
241 under, clear = 10 ** (-26.5 / 20), 10 ** (-12 / 20)
242 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)))))"
243 gain = gain.replace(",", "\\,")
244 filters.append(f"[{prev}]atrim=0:{total:.3f},volume='{gain}':eval=frame[m]")
245 filters.append("".join(labels) + f"[m]amix=inputs={n + 1}:normalize=0:dropout_transition=0,apad,atrim=0:{total:.3f}[bed]")
246 os.makedirs("assets/mix", exist_ok=True)
247 bed = f"assets/mix/{NAME}-bed.wav"
248 subprocess.run(args + ["-filter_complex", ";".join(filters), "-map", "[bed]", "-c:a", "pcm_s24le", bed], check=True)
249 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
250 m = json.loads(r[r.rindex("{"):r.rindex("}") + 1])
251 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)
252
253
254def main():
255 os.makedirs(f"{OUT}/compositions", exist_ok=True)
256 os.makedirs(f"{OUT}/assets/clips", exist_ok=True)
257 for name in ("film.css", "film.js"):
258 shutil.copy(f"video/assets/{name}", f"{OUT}/assets/{name}")
259 if not os.path.exists(f"{OUT}/assets/fonts"):
260 shutil.copytree("video/assets/fonts", f"{OUT}/assets/fonts")
261 shutil.copy("tools/thumbnail/wordmark-dark.svg", f"{OUT}/assets/wordmark-dark.svg")
262 for name in ("hyperframes.json", "package.json"):
263 shutil.copy(f"video/{name}", f"{OUT}/{name}")
264 shutil.copy("video/compositions/field.html", f"{OUT}/compositions/field.html")
265 open(f"{OUT}/assets/film.css", "a").write(open("films/extra.css").read())
266 timeline, clock = schedule()
267 total = clock + END_SECONDS
268 for name in os.listdir(f"{OUT}/compositions"):
269 if name != "field.html":
270 os.remove(f"{OUT}/compositions/{name}")
271 previous = None
272 for index, beat in enumerate(timeline):
273 clip = None
274 if index + 1 < len(timeline) and timeline[index + 1].get("shown"):
275 beat["stay"] = True
276 if beat.get("shots"):
277 clip = cut_clip(beat, beat["duration"])
278 beat["open"] = previous != beat["layout"]
279 previous = beat["layout"]
280 scene_page(beat, clip)
281 extra_scene("intro", f'<div id="t1" class="big" style="position:absolute;left:150px;top:380px;width:1620px">{FILM.TITLE}</div><div id="t2" class="tag" style="position:absolute;left:150px;top:{FILM.SUB_TOP}px">{FILM.SUB}</div>', TITLE_SECONDS, f'rise("#t1", 0.3); land("#t2", 0.8); leave("#t1, #t2", {TITLE_SECONDS - 0.3});')
282 extra_scene("outro", f'<script src="https://cdn.jsdelivr.net/npm/three@0.160.1/build/three.min.js"></script><canvas id="logo3d" width="1920" height="1080" style="position:absolute;left:0;top:0;width:1920px;height:1080px;opacity:0"></canvas><img id="e0" src="assets/wordmark-dark.svg" alt="AI Resource Pro" style="position:absolute;left:640px;top:610px;width:640px;opacity:0" /><div id="e1" class="mid" style="position:absolute;left:0;right:0;top:730px;text-align:center">airesourcepro.com</div><div id="e2" class="say" style="position:absolute;left:210px;right:210px;top:815px;text-align:center">{FILM.CREDIT}</div>', 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});')
283 write_cues(total)
284 write_index(timeline, total)
285 mix(timeline, total)
286 json.dump([{k: b[k] for k in ("id", "start", "voice", "duration")} for b in timeline], open(f"{OUT}/timeline.json", "w"), indent=0)
287 print(f"{total:.1f} s ({total / 60:.2f} min), {len(timeline)} beats")
288
289
290main()