Branchwell

Become a Pro / full-access-films · becomeapro.ai / tools / build_film.py

1#!/usr/bin/env python3
2"""Build the film from video/scenes/film.scenes and video/scenes/cues.tpl.js.
3
4 python3 tools/build_film.py
5
6Every time in a scene is a phrase in the voiceover, so changing a take retimes the film:
7 @{b09:16 bits} start of that phrase, in scene time
8 @{b09:16 bits+0.2} with an offset; #2 picks the second match (@{b06:network volume#2})
9 @{b09:start} @{b09:end} @{end} @{end-0.25}
10Writes compositions/, index.html, assets/cues.js and assets/timeline.json.
11"""
12import json, os, re, sys
13
14ROOT = os.path.join(os.path.dirname(os.path.abspath(__file__)), "..")
15VIDEO = os.path.join(ROOT, "video")
16VO = os.path.join(ROOT, "assets", "vo", "film")
17LEAD_IN = 1.2
18HOLD_AFTER = {"b01": 0.4, "b02": 0.4, "b03": 0.4, "b04": 1.51, "b05": 7.791}
19
20
21def norm(word):
22 return re.sub(r"[^a-z0-9]", "", word.lower())
23
24
25def load_beats():
26 beats, clock = {}, LEAD_IN
27 for beat, hold in HOLD_AFTER.items():
28 words = json.load(open(os.path.join(VO, beat + ".words.json")))
29 for word in words:
30 word["key"] = norm(word["word"])
31 words = [w for w in words if w["key"]]
32 length = words[-1]["end"]
33 beats[beat] = {"start": clock, "length": length, "words": words}
34 clock += length + hold
35 return beats, clock
36
37
38def phrase_time(beats, beat, phrase):
39 phrase, _, nth = phrase.partition("#")
40 data = beats[beat]
41 if phrase == "start":
42 return data["start"]
43 if phrase == "end":
44 return data["start"] + data["length"]
45 wanted = [norm(w) for w in phrase.split()]
46 keys = [w["key"] for w in data["words"]]
47 hits = [i for i in range(len(keys) - len(wanted) + 1) if keys[i : i + len(wanted)] == wanted]
48 if len(hits) < int(nth or 1):
49 sys.exit(f"no match for '{phrase}' in {beat}")
50 return data["start"] + data["words"][hits[int(nth or 1) - 1]]["start"]
51
52
53def resolve(beats, expr, scene=None):
54 match = re.fullmatch(r"\s*(?:(b\d\d):)?(.*?)\s*([+-]\s*\d+(?:\.\d+)?)?\s*", expr)
55 beat, name, offset = match.groups()
56 offset = float(offset.replace(" ", "")) if offset else 0.0
57 if beat:
58 value = phrase_time(beats, beat, name)
59 if scene:
60 value -= scene["start"]
61 elif name == "end":
62 value = scene["duration"]
63 else:
64 value = float(name or 0)
65 return value + offset
66
67
68def fill(beats, text, scene=None):
69 return re.sub(r"@\{([^}]+)\}", lambda m: f"{resolve(beats, m.group(1), scene):.3f}", text)
70
71
72def parse_scenes(beats, total):
73 source = open(os.path.join(VIDEO, "scenes", "film.scenes")).read()
74 blocks = re.split(r"^=== ", source, flags=re.M)[1:]
75 scenes = []
76 for block in blocks:
77 head, _, rest = block.partition("\n")
78 name, _, start = head.partition("|")
79 markup, _, script = rest.partition("\n---\n")
80 scenes.append({"id": name.strip(), "start": resolve(beats, start.strip().strip("@{}")), "markup": markup, "script": script})
81 for scene, following in zip(scenes, scenes[1:] + [None]):
82 scene["duration"] = (following["start"] if following else total) - scene["start"]
83 if scene["duration"] <= 0:
84 sys.exit(f"scene {scene['id']} has no length")
85 return scenes
86
87
88def write_scene(beats, scene):
89 markup = fill(beats, scene["markup"], scene)
90 script = fill(beats, scene["script"], scene)
91 style = "\n".join(re.findall(r"<style>(.*?)</style>", markup, flags=re.S))
92 markup = re.sub(r"<style>.*?</style>\s*", "", markup, flags=re.S).strip()
93 page = f"""<template>
94 <style>
95 #root {{ position: absolute; inset: 0; }}
96{style}
97 </style>
98 <div id="root" data-composition-id="{scene['id']}" data-width="1920" data-height="1080">
99{markup}
100 </div>
101 <script>
102 (() => {{
103 const tl = gsap.timeline({{ paused: true }});
104 const {{ land, rise, leave, card, cardOut, mark, open, camera }} = Film(tl);
105{script.strip()}
106 window.__timelines["{scene['id']}"] = tl;
107 }})();
108 </script>
109</template>
110"""
111 open(os.path.join(VIDEO, "compositions", scene["id"] + ".html"), "w").write(page)
112
113
114def write_index(scenes, total):
115 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>']
116 for scene in scenes:
117 hosts.append(f' <div id="{scene["id"]}" data-composition-id="{scene["id"]}" data-composition-src="compositions/{scene["id"]}.html" data-start="{scene["start"]:.3f}" data-duration="{scene["duration"]:.3f}" data-track-index="1" data-track-kind="graphics" data-width="1920" data-height="1080"></div>')
118 if os.path.exists(os.path.join(VIDEO, "assets", "mix.m4a")):
119 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>')
120 page = """<!doctype html>
121<html lang="en">
122 <head>
123 <meta charset="UTF-8" />
124 <meta name="viewport" content="width=1920, height=1080" />
125 <script src="https://cdn.jsdelivr.net/npm/gsap@3.14.2/dist/gsap.min.js"></script>
126 <script src="assets/cues.js"></script>
127 <script src="assets/film.js"></script>
128 <link rel="stylesheet" href="assets/film.css" />
129 </head>
130 <body>
131 <div id="root" data-composition-id="main" data-start="0" data-duration="%.3f" data-width="1920" data-height="1080" data-fps="30">
132%s
133 </div>
134 <script>
135 window.__timelines = window.__timelines || {};
136 window.__timelines["main"] = gsap.timeline({ paused: true });
137 </script>
138 </body>
139</html>
140""" % (total, "\n".join(hosts))
141 open(os.path.join(VIDEO, "index.html"), "w").write(page)
142
143
144def main():
145 beats, total = load_beats()
146 scenes = parse_scenes(beats, total)
147 for name in os.listdir(os.path.join(VIDEO, "compositions")):
148 if name != "field.html":
149 os.remove(os.path.join(VIDEO, "compositions", name))
150 for scene in scenes:
151 write_scene(beats, scene)
152 cues = fill(beats, open(os.path.join(VIDEO, "scenes", "cues.tpl.js")).read())
153 open(os.path.join(VIDEO, "assets", "cues.js"), "w").write(f"window.FILM_SECONDS = {total:.3f};\n" + cues)
154 write_index(scenes, total)
155 timeline = {"total": total, "beats": {k: {"start": v["start"], "length": v["length"]} for k, v in beats.items()}, "scenes": [{"id": s["id"], "start": s["start"], "duration": s["duration"]} for s in scenes]}
156 json.dump(timeline, open(os.path.join(VIDEO, "assets", "timeline.json"), "w"), indent=1)
157 print(f"{total:.1f} s ({total/60:.2f} min), {len(scenes)} scenes")
158 for s in scenes:
159 print(f" {s['id']:12} {s['start']:7.2f} {s['duration']:6.2f}")
160
161
162main()