@arbidocs/blocks 0.5.190 → 0.5.192
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/bin/arbidocs-mix-take.mjs +34 -0
- package/bin/arbidocs-record-take.mjs +77 -11
- package/bin/arbidocs-voice-take.mjs +32 -0
- package/dist/{ConnectedNativeDocxComparison-XE5NMZMY.cjs → ConnectedNativeDocxComparison-PPVXDQY3.cjs} +7 -7
- package/dist/{ConnectedNativeDocxComparison-XE5NMZMY.cjs.map → ConnectedNativeDocxComparison-PPVXDQY3.cjs.map} +1 -1
- package/dist/{ConnectedStreamedWordArtifact-EY3YWYDD.cjs → ConnectedStreamedWordArtifact-GAACBGTY.cjs} +7 -7
- package/dist/{ConnectedStreamedWordArtifact-EY3YWYDD.cjs.map → ConnectedStreamedWordArtifact-GAACBGTY.cjs.map} +1 -1
- package/dist/{DocumentReviewCard-RFE4THHR.cjs → DocumentReviewCard-Q3NKJLSM.cjs} +14 -14
- package/dist/{DocumentReviewCard-RFE4THHR.cjs.map → DocumentReviewCard-Q3NKJLSM.cjs.map} +1 -1
- package/dist/{FilesViewerDialog-VO247UEI.cjs → FilesViewerDialog-4JWDTDO7.cjs} +11 -11
- package/dist/{FilesViewerDialog-VO247UEI.cjs.map → FilesViewerDialog-4JWDTDO7.cjs.map} +1 -1
- package/dist/agents/index.cjs +172 -172
- package/dist/{chunk-PGKCL6YA.cjs → chunk-33236Q7Y.cjs} +8 -8
- package/dist/{chunk-PGKCL6YA.cjs.map → chunk-33236Q7Y.cjs.map} +1 -1
- package/dist/{chunk-E7BSG5IS.cjs → chunk-633ZCYVN.cjs} +37 -37
- package/dist/{chunk-E7BSG5IS.cjs.map → chunk-633ZCYVN.cjs.map} +1 -1
- package/dist/{chunk-U4MJIYGD.cjs → chunk-65NQW4RR.cjs} +4 -4
- package/dist/{chunk-U4MJIYGD.cjs.map → chunk-65NQW4RR.cjs.map} +1 -1
- package/dist/{chunk-JAKLLNLL.cjs → chunk-AWQEN6WW.cjs} +9 -7
- package/dist/chunk-AWQEN6WW.cjs.map +1 -0
- package/dist/{chunk-GENUGV6V.cjs → chunk-AZUPMHZI.cjs} +4 -4
- package/dist/{chunk-GENUGV6V.cjs.map → chunk-AZUPMHZI.cjs.map} +1 -1
- package/dist/{chunk-72O4YH5M.cjs → chunk-EAH7LFJN.cjs} +5 -5
- package/dist/{chunk-72O4YH5M.cjs.map → chunk-EAH7LFJN.cjs.map} +1 -1
- package/dist/{chunk-UNT2VY3B.cjs → chunk-EFV52SZ6.cjs} +4 -4
- package/dist/{chunk-UNT2VY3B.cjs.map → chunk-EFV52SZ6.cjs.map} +1 -1
- package/dist/{chunk-IXSOSISW.cjs → chunk-ELN3YOXF.cjs} +28 -28
- package/dist/{chunk-IXSOSISW.cjs.map → chunk-ELN3YOXF.cjs.map} +1 -1
- package/dist/{chunk-NAEBNQTO.cjs → chunk-GLNL5AL5.cjs} +29 -29
- package/dist/{chunk-NAEBNQTO.cjs.map → chunk-GLNL5AL5.cjs.map} +1 -1
- package/dist/{chunk-HTH3XIFF.cjs → chunk-GZPNBSRE.cjs} +8 -8
- package/dist/{chunk-HTH3XIFF.cjs.map → chunk-GZPNBSRE.cjs.map} +1 -1
- package/dist/chunk-HME72RFP.cjs +145 -0
- package/dist/chunk-HME72RFP.cjs.map +1 -0
- package/dist/{chunk-GW5LTX66.cjs → chunk-J46Y2L26.cjs} +4 -4
- package/dist/{chunk-GW5LTX66.cjs.map → chunk-J46Y2L26.cjs.map} +1 -1
- package/dist/{chunk-LHWFSXM5.cjs → chunk-KD37PODE.cjs} +3 -3
- package/dist/{chunk-LHWFSXM5.cjs.map → chunk-KD37PODE.cjs.map} +1 -1
- package/dist/{chunk-VCCAG4GQ.cjs → chunk-KZH6HMJL.cjs} +4 -4
- package/dist/{chunk-VCCAG4GQ.cjs.map → chunk-KZH6HMJL.cjs.map} +1 -1
- package/dist/{chunk-AQYCL2IJ.cjs → chunk-QDIIOZBP.cjs} +5 -5
- package/dist/{chunk-AQYCL2IJ.cjs.map → chunk-QDIIOZBP.cjs.map} +1 -1
- package/dist/{chunk-USYCBTKK.cjs → chunk-R6HGMPF4.cjs} +41 -7
- package/dist/chunk-R6HGMPF4.cjs.map +1 -0
- package/dist/{chunk-QSVYI72E.cjs → chunk-RNQ3MDTR.cjs} +4 -4
- package/dist/{chunk-QSVYI72E.cjs.map → chunk-RNQ3MDTR.cjs.map} +1 -1
- package/dist/{chunk-HZ35LMO3.cjs → chunk-VJHDCYKE.cjs} +4 -4
- package/dist/{chunk-HZ35LMO3.cjs.map → chunk-VJHDCYKE.cjs.map} +1 -1
- package/dist/{chunk-3GWYFQSI.cjs → chunk-Z6M2CI63.cjs} +84 -79
- package/dist/chunk-Z6M2CI63.cjs.map +1 -0
- package/dist/collaboration/index.cjs +3 -3
- package/dist/collaboration/sharing/ShareControl.d.ts +10 -1
- package/dist/collaboration/sharing/ShareControl.js +64 -4
- package/dist/collaboration/sharing/ShareControl.js.map +2 -2
- package/dist/components/GridRowNavigator.d.ts +8 -1
- package/dist/components/GridRowNavigator.js +4 -2
- package/dist/components/GridRowNavigator.js.map +2 -2
- package/dist/connect/docx.cjs +10 -10
- package/dist/connect/index.cjs +816 -767
- package/dist/connect/index.cjs.map +1 -1
- package/dist/connect/viewer.cjs +9 -9
- package/dist/connection/billing/ProjectDetail.d.ts +5 -1
- package/dist/connection/billing/ProjectDetail.js +82 -69
- package/dist/connection/billing/ProjectDetail.js.map +2 -2
- package/dist/connection/databases/ConnectedDatabasesPage.d.ts +7 -1
- package/dist/connection/databases/ConnectedDatabasesPage.js +18 -9
- package/dist/connection/databases/ConnectedDatabasesPage.js.map +2 -2
- package/dist/connection/databases/DatabaseWorkbench.d.ts +6 -1
- package/dist/connection/databases/DatabaseWorkbench.js +20 -15
- package/dist/connection/databases/DatabaseWorkbench.js.map +2 -2
- package/dist/connection/facts/factsSource.d.ts +2 -0
- package/dist/connection/facts/factsSource.js +10 -3
- package/dist/connection/facts/factsSource.js.map +2 -2
- package/dist/connection/files/page/ConnectedFilesPage.js +2 -1
- package/dist/connection/files/page/ConnectedFilesPage.js.map +2 -2
- package/dist/connection/projects/ConnectedProjectPage.d.ts +8 -1
- package/dist/connection/projects/ConnectedProjectPage.js +15 -1
- package/dist/connection/projects/ConnectedProjectPage.js.map +2 -2
- package/dist/connection/viewer/ConnectedDocumentViewer.d.ts +7 -0
- package/dist/connection/viewer/ConnectedDocumentViewer.js +28 -23
- package/dist/connection/viewer/ConnectedDocumentViewer.js.map +2 -2
- package/dist/databases/DatabaseFilterMenu.d.ts +6 -1
- package/dist/databases/DatabaseFilterMenu.js +13 -4
- package/dist/databases/DatabaseFilterMenu.js.map +2 -2
- package/dist/databases/DatabaseToolbar.d.ts +11 -1
- package/dist/databases/DatabaseToolbar.js +26 -1
- package/dist/databases/DatabaseToolbar.js.map +2 -2
- package/dist/databases/index.cjs +70 -69
- package/dist/embed/index.cjs +13 -13
- package/dist/files/index.cjs +221 -221
- package/dist/index.cjs +242 -242
- package/dist/pages/index.cjs +21 -21
- package/dist/record/band.d.ts +95 -0
- package/dist/record/index.cjs +414 -13
- package/dist/record/index.cjs.map +1 -1
- package/dist/record/index.d.ts +35 -2
- package/dist/record/index.js +402 -15
- package/dist/record/index.js.map +1 -1
- package/dist/record/narration.d.ts +71 -0
- package/dist/shell/index.cjs +1 -1
- package/dist/styles.css +1 -1
- package/dist/workflow-canvas/index.cjs +24 -24
- package/node_modules/@arbidocs/coedit/package.json +1 -1
- package/package.json +11 -6
- package/record/SKILL.md +178 -26
- package/record/mix-take.py +320 -0
- package/record/recap-slide.mjs +118 -0
- package/record/voice-take.py +129 -0
- package/dist/chunk-3GWYFQSI.cjs.map +0 -1
- package/dist/chunk-JAKLLNLL.cjs.map +0 -1
- package/dist/chunk-USYCBTKK.cjs.map +0 -1
- package/dist/chunk-WCT6FT2K.cjs +0 -87
- package/dist/chunk-WCT6FT2K.cjs.map +0 -1
|
@@ -0,0 +1,320 @@
|
|
|
1
|
+
"""Lay a narrated take's voice on its edit, and close the edit on the recap slide.
|
|
2
|
+
|
|
3
|
+
arbidocs-mix-take <story stem> --site <site> [--videos e2e/videos] [--script <story>.narration.json]
|
|
4
|
+
[--clips <dir>] [--recap recap] [--no-recap] [--speed 1.2] [--out <mp4>] [--publish <dir>]
|
|
5
|
+
|
|
6
|
+
Run from the site's root after the edit (`arbidocs-render-take`). For <videos>/<site>-<stem>.* it
|
|
7
|
+
reads the take (.webm, for its clock), the edit (.cut.mp4 and .cut.plan.json), the focus timeline
|
|
8
|
+
(.focus.json: the brand) and the narration log (.narration.json: each line's start on the take's
|
|
9
|
+
clock); the clips and their manifest (<videos>/narration/<stem>/); and the story's script
|
|
10
|
+
(e2e/record/<stem>.narration.json), whose `recap` is the closing slide.
|
|
11
|
+
|
|
12
|
+
A line starts on the edit where its start falls there, mapped as render-take.py maps everything:
|
|
13
|
+
the take's clock onto the video's (the timecode in its frames), then the edit's cuts. The edit's
|
|
14
|
+
closing card gives way to the recap slide (recap-slide.mjs), its points ticked off as the voice
|
|
15
|
+
names them: the last slide of a video is a conclusion (a recap of what was shown, a closing line,
|
|
16
|
+
a thank-you), never just another chapter card. Writes <site>-<stem>.narrated.mp4 and, beside it,
|
|
17
|
+
.narrated.json: where every line landed, and what to look at (`problems`).
|
|
18
|
+
|
|
19
|
+
`--publish <dir>` copies the video there as `<site>-<stem>.take<N>.narrated.mp4`, N one more than
|
|
20
|
+
the takes already there: a published take is never overwritten.
|
|
21
|
+
|
|
22
|
+
Needs ffmpeg, node (with @playwright/test) and the python render-take.py needs (numpy, opencv).
|
|
23
|
+
"""
|
|
24
|
+
import argparse
|
|
25
|
+
import importlib.util
|
|
26
|
+
import json
|
|
27
|
+
import re
|
|
28
|
+
import shutil
|
|
29
|
+
import subprocess
|
|
30
|
+
import sys
|
|
31
|
+
import tempfile
|
|
32
|
+
from pathlib import Path
|
|
33
|
+
|
|
34
|
+
HERE = Path(__file__).resolve().parent
|
|
35
|
+
RENDER = HERE / "render-take.py"
|
|
36
|
+
RECAP = HERE / "recap-slide.mjs"
|
|
37
|
+
FPS = 25
|
|
38
|
+
XFADE = 0.6 # s: the edit's last frame dissolves into the slide
|
|
39
|
+
LEAD = 0.7 # s from the slide's first frame to its first line
|
|
40
|
+
GAP = 0.6 # s between the slide's lines
|
|
41
|
+
STEP_FADE = 0.3 # s: a point's tick dissolving in
|
|
42
|
+
HOLD = 2.0 # s on the slide after its last line
|
|
43
|
+
FADE_OUT = 1.0 # s to black, at the very end
|
|
44
|
+
# The band's captions in the page (src/record/band.ts: a 64 px band, its label 360 px wide), a
|
|
45
|
+
# little inside their edges.
|
|
46
|
+
BAND_CAPTIONS = (367, 3.4, 1583, 60)
|
|
47
|
+
|
|
48
|
+
|
|
49
|
+
def run(cmd):
|
|
50
|
+
done = subprocess.run(cmd, capture_output=True, text=True)
|
|
51
|
+
if done.returncode:
|
|
52
|
+
sys.exit(f"{cmd[0]} failed:\n{done.stderr[-3000:]}")
|
|
53
|
+
return done.stdout
|
|
54
|
+
|
|
55
|
+
|
|
56
|
+
def load_render():
|
|
57
|
+
spec = importlib.util.spec_from_file_location("render_take", RENDER)
|
|
58
|
+
module = importlib.util.module_from_spec(spec)
|
|
59
|
+
spec.loader.exec_module(module)
|
|
60
|
+
return module
|
|
61
|
+
|
|
62
|
+
|
|
63
|
+
def next_take(existing, base, suffix):
|
|
64
|
+
"""The name a new take is published under: `<base>.take<N><suffix>`, N one more than the highest
|
|
65
|
+
take among `existing` names (1 when there is none). Earlier takes keep their names."""
|
|
66
|
+
pattern = re.compile(re.escape(base) + r"\.take(\d+)" + re.escape(suffix) + "$")
|
|
67
|
+
taken = [int(m.group(1)) for m in map(pattern.match, existing) if m]
|
|
68
|
+
return f"{base}.take{max(taken, default=0) + 1}{suffix}"
|
|
69
|
+
|
|
70
|
+
|
|
71
|
+
def publish(video, folder, base):
|
|
72
|
+
"""Copy `video` into `folder` under the next take's name, never onto an existing file."""
|
|
73
|
+
folder = Path(folder)
|
|
74
|
+
folder.mkdir(parents=True, exist_ok=True)
|
|
75
|
+
target = folder / next_take([p.name for p in folder.iterdir()], base, ".narrated.mp4")
|
|
76
|
+
with open(video, "rb") as src, open(target, "xb") as dst: # "x": fails if it exists
|
|
77
|
+
shutil.copyfileobj(src, dst)
|
|
78
|
+
return target
|
|
79
|
+
|
|
80
|
+
|
|
81
|
+
def caption_box(frame_width, page_width):
|
|
82
|
+
"""Where the band's captions are in the edit's frames (x0, y0, x1, y1)."""
|
|
83
|
+
s = frame_width / page_width
|
|
84
|
+
x0, y0, x1, y1 = BAND_CAPTIONS
|
|
85
|
+
return round(x0 * s), round(y0 * s), round(x1 * s), round(y1 * s)
|
|
86
|
+
|
|
87
|
+
|
|
88
|
+
def take_clock(rt, src, tl):
|
|
89
|
+
"""render-take.py's clock (take seconds -> video seconds): the timecode, else the sync marker, else
|
|
90
|
+
the cards' dark frames."""
|
|
91
|
+
import numpy as np
|
|
92
|
+
sw, sh, _ = rt.probe(src)
|
|
93
|
+
vp = tl.get("viewport") or {}
|
|
94
|
+
clock = rt.read_timecode(src, vp.get("width", sw), vp.get("height", sh), sw, sh) if tl.get("focus") is not None else None
|
|
95
|
+
offset = 0.0
|
|
96
|
+
if clock is None and tl.get("sync") is not None:
|
|
97
|
+
at = rt.find_sync(src, tl["sync"])
|
|
98
|
+
if at is not None:
|
|
99
|
+
offset = at - tl["sync"]
|
|
100
|
+
if clock is None and tl.get("cards") and tl.get("focus") is not None:
|
|
101
|
+
clock = rt.card_anchors(src, tl["cards"], offset)
|
|
102
|
+
|
|
103
|
+
def v(t):
|
|
104
|
+
if not clock:
|
|
105
|
+
return t + offset
|
|
106
|
+
tt, vt = clock
|
|
107
|
+
if t <= tt[0]:
|
|
108
|
+
return vt[0] + (t - tt[0])
|
|
109
|
+
if t >= tt[-1]:
|
|
110
|
+
return vt[-1] + (t - tt[-1])
|
|
111
|
+
return float(np.interp(t, tt, vt))
|
|
112
|
+
|
|
113
|
+
return v, (f"timecode, {len(clock[0])} anchors" if clock else f"offset {offset:+.2f} s")
|
|
114
|
+
|
|
115
|
+
|
|
116
|
+
def caption_onset(video, at, box, before=0.25, after=3.0):
|
|
117
|
+
"""When a line's caption shows in the band: the first frame from just before its voice that
|
|
118
|
+
differs, with text in the band a moment later (a caption clearing is not the next one showing).
|
|
119
|
+
None if nothing shows."""
|
|
120
|
+
import numpy as np
|
|
121
|
+
x0, y0, x1, y1 = box
|
|
122
|
+
w, h = x1 - x0, y1 - y0
|
|
123
|
+
raw = subprocess.run(["ffmpeg", "-v", "error", "-ss", f"{max(at - before, 0):.3f}", "-i", str(video), "-t", f"{before + after:.3f}",
|
|
124
|
+
"-vf", f"fps={FPS},crop={w}:{h}:{x0}:{y0},format=gray", "-f", "rawvideo", "-"],
|
|
125
|
+
capture_output=True, check=True).stdout
|
|
126
|
+
f = np.frombuffer(raw, np.uint8).reshape(-1, h, w).astype(np.int16)
|
|
127
|
+
if not len(f):
|
|
128
|
+
return None
|
|
129
|
+
text = (f > 150).sum(axis=(1, 2))
|
|
130
|
+
for i in range(1, len(f)):
|
|
131
|
+
if (np.abs(f[i] - f[0]) > 60).sum() > 120 and text[min(i + 5, len(f) - 1)] > 80:
|
|
132
|
+
return max(at - before, 0) + i / FPS
|
|
133
|
+
return None
|
|
134
|
+
|
|
135
|
+
|
|
136
|
+
def recap_lines(recap):
|
|
137
|
+
"""The script lines the recap slide is said with, in order: its opening, a line per point, its close."""
|
|
138
|
+
return [recap["open"], *[p["line"] for p in recap["points"]], recap["close"]]
|
|
139
|
+
|
|
140
|
+
|
|
141
|
+
def recap_slide(rt_dims, brand, recap, manifest, work):
|
|
142
|
+
"""The slide's steps as PNGs, and when each shows and each line is said (slide seconds)."""
|
|
143
|
+
w, h = rt_dims
|
|
144
|
+
spec = work / "recap.json"
|
|
145
|
+
spec.write_text(json.dumps({"width": w, "height": h, "brand": brand, "recap": recap}))
|
|
146
|
+
run(["node", str(RECAP), str(spec), str(work / "recap")])
|
|
147
|
+
lines, t = [], LEAD
|
|
148
|
+
for line in recap_lines(recap):
|
|
149
|
+
lines.append({"id": line, "at": round(t, 3), "duration": manifest[line]["duration"], "file": manifest[line]["file"]})
|
|
150
|
+
t += manifest[line]["duration"] + GAP
|
|
151
|
+
length = t - GAP + HOLD
|
|
152
|
+
said = {l["id"]: l["at"] for l in lines}
|
|
153
|
+
steps = [("step-0", 0.0)] + [(f"step-{i + 1}", said[p["line"]] + 0.1) for i, p in enumerate(recap["points"])]
|
|
154
|
+
steps.append(("step-final", said[recap["close"]]))
|
|
155
|
+
return steps, lines, length
|
|
156
|
+
|
|
157
|
+
|
|
158
|
+
def slide_video(steps, length, work):
|
|
159
|
+
"""The steps, each dissolving into the next as it shows, and a fade to black at the end."""
|
|
160
|
+
out = work / "slide.mp4"
|
|
161
|
+
cmd = ["ffmpeg", "-v", "error", "-y"]
|
|
162
|
+
for i, (name, at) in enumerate(steps):
|
|
163
|
+
until = steps[i + 1][1] + STEP_FADE if i + 1 < len(steps) else length
|
|
164
|
+
cmd += ["-loop", "1", "-framerate", str(FPS), "-t", f"{until - at:.3f}", "-i", str(work / "recap" / f"{name}.png")]
|
|
165
|
+
graph, last = [], "0:v"
|
|
166
|
+
for i in range(1, len(steps)):
|
|
167
|
+
graph.append(f"[{last}][{i}:v]xfade=transition=fade:duration={STEP_FADE}:offset={steps[i][1]:.3f}[x{i}]")
|
|
168
|
+
last = f"x{i}"
|
|
169
|
+
graph.append(f"[{last}]fade=t=out:st={length - FADE_OUT:.3f}:d={FADE_OUT},format=yuv420p[v]")
|
|
170
|
+
run(cmd + ["-filter_complex", ";".join(graph), "-map", "[v]", "-r", str(FPS), "-c:v", "libx264", "-preset", "medium",
|
|
171
|
+
"-crf", "18", "-pix_fmt", "yuv420p", str(out)])
|
|
172
|
+
return out
|
|
173
|
+
|
|
174
|
+
|
|
175
|
+
def main():
|
|
176
|
+
ap = argparse.ArgumentParser()
|
|
177
|
+
ap.add_argument("stem", help="the story, e.g. 32-demo-5min")
|
|
178
|
+
ap.add_argument("--site", required=True)
|
|
179
|
+
ap.add_argument("--videos", default="e2e/videos", help="where the take's files are")
|
|
180
|
+
ap.add_argument("--script", help="the story's narration script (default e2e/record/<stem>.narration.json)")
|
|
181
|
+
ap.add_argument("--clips", help="the spoken clips and their manifest (default <videos>/narration/<stem>)")
|
|
182
|
+
ap.add_argument("--recap", default="recap", help="the script's key holding the recap slide (a story with two endings has two)")
|
|
183
|
+
ap.add_argument("--no-recap", action="store_true", help="a clip that is part of a longer video: no closing slide")
|
|
184
|
+
ap.add_argument("--out")
|
|
185
|
+
ap.add_argument("--publish", help="copy the video to this folder as the next take, never over an earlier one")
|
|
186
|
+
ap.add_argument("--speed", type=float, default=1.0,
|
|
187
|
+
help="play the narrated video this much faster (1.2: a sixth shorter), the voice kept at its pitch")
|
|
188
|
+
args = ap.parse_args()
|
|
189
|
+
if not 0.5 <= args.speed <= 2.0:
|
|
190
|
+
ap.error("--speed must be between 0.5 and 2 (ffmpeg's atempo range)")
|
|
191
|
+
|
|
192
|
+
name = f"{args.site}-{args.stem}"
|
|
193
|
+
base = Path(args.videos) / name
|
|
194
|
+
|
|
195
|
+
def beside(suffix): # a story stem may hold dots: never Path.with_suffix
|
|
196
|
+
return base.parent / f"{base.name}{suffix}"
|
|
197
|
+
|
|
198
|
+
src, cut = beside(".webm"), beside(".cut.mp4")
|
|
199
|
+
plan = json.loads(beside(".cut.plan.json").read_text())
|
|
200
|
+
tl = json.loads(beside(".focus.json").read_text())
|
|
201
|
+
said = json.loads(beside(".narration.json").read_text())["lines"]
|
|
202
|
+
clips = Path(args.clips) if args.clips else Path(args.videos) / "narration" / args.stem
|
|
203
|
+
manifest = json.loads((clips / "manifest.json").read_text())["lines"]
|
|
204
|
+
script = json.loads(Path(args.script or f"e2e/record/{args.stem}.narration.json").read_text())
|
|
205
|
+
recap = None if args.no_recap else script.get(args.recap)
|
|
206
|
+
if recap is None and not args.no_recap:
|
|
207
|
+
sys.exit(f'the script has no "{args.recap}": a video ends on a recap slide (see record/SKILL.md), '
|
|
208
|
+
"or pass --no-recap for a clip that is part of a longer video")
|
|
209
|
+
if recap:
|
|
210
|
+
unspoken = [line for line in recap_lines(recap) if line not in manifest]
|
|
211
|
+
if unspoken:
|
|
212
|
+
sys.exit(f"the recap's lines are not spoken yet (arbidocs-voice-take): {', '.join(unspoken)}")
|
|
213
|
+
out = Path(args.out) if args.out else beside(".narrated.mp4")
|
|
214
|
+
out.parent.mkdir(parents=True, exist_ok=True)
|
|
215
|
+
|
|
216
|
+
rt = load_render()
|
|
217
|
+
v, how = take_clock(rt, str(src), tl)
|
|
218
|
+
cuts = [tuple(c) for c in plan["cuts"]]
|
|
219
|
+
m = rt.make_map(cuts)
|
|
220
|
+
print(f"clock: {how}; {len(cuts)} cuts; edit {plan['duration']:.1f} s")
|
|
221
|
+
|
|
222
|
+
# 1. Each line where it starts on the edit; a line the edit cuts into, or that runs into the next, is reported.
|
|
223
|
+
placed, problems = [], []
|
|
224
|
+
for line in said:
|
|
225
|
+
if not line.get("file"):
|
|
226
|
+
problems.append(f"{line['id']}: no clip (not spoken when the take ran), left silent")
|
|
227
|
+
continue
|
|
228
|
+
a, b = v(line["start"]), v(line["start"] + line["duration"])
|
|
229
|
+
into = [c for c in cuts if c[0] < b - 0.05 and c[1] > a + 0.05]
|
|
230
|
+
placed.append({**line, "at": round(m(a), 3), "cutInto": [c[2] for c in into]})
|
|
231
|
+
# A caption the page painted late (it was busy): the voice waits for it. Only ever later.
|
|
232
|
+
box = caption_box(rt.W, (tl.get("viewport") or {}).get("width", 1600))
|
|
233
|
+
for p in placed:
|
|
234
|
+
if p.get("caption") is False:
|
|
235
|
+
continue
|
|
236
|
+
shown = caption_onset(cut, p["at"], box)
|
|
237
|
+
if shown is not None and shown - p["at"] > 0.15:
|
|
238
|
+
problems.append(f"{p['id']}: its caption showed {shown - p['at']:.2f} s after the voice was due: the voice waits for it")
|
|
239
|
+
p["at"] = round(shown, 3)
|
|
240
|
+
placed.sort(key=lambda p: p["at"])
|
|
241
|
+
for prev, p in zip(placed, placed[1:]):
|
|
242
|
+
if p["at"] < prev["at"] + prev["duration"] - 0.05:
|
|
243
|
+
problems.append(f"{p['id']} starts {prev['at'] + prev['duration'] - p['at']:.2f} s before {prev['id']} ends: moved after it")
|
|
244
|
+
p["at"] = round(prev["at"] + prev["duration"] + 0.45, 3)
|
|
245
|
+
problems += [f"{p['id']}: the edit cuts into it ({', '.join(p['cutInto'])})" for p in placed if p["cutInto"]]
|
|
246
|
+
|
|
247
|
+
# 2. The edit up to its closing card, then the recap slide.
|
|
248
|
+
end_card = plan["cards"][-1] if plan["cards"] and plan["cards"][-1].get("kind") == "end" else None
|
|
249
|
+
t_end = end_card["start"] if end_card and recap else plan["duration"]
|
|
250
|
+
late = [p["id"] for p in placed if p["at"] + p["duration"] > t_end + 0.05]
|
|
251
|
+
if late:
|
|
252
|
+
problems.append(f"said past the end of the edit{' (its closing card gives way to the slide)' if recap else ''}: {', '.join(late)}")
|
|
253
|
+
w, h = rt.W, rt.H
|
|
254
|
+
with tempfile.TemporaryDirectory() as tmp:
|
|
255
|
+
work = Path(tmp)
|
|
256
|
+
video = work / "video.mp4"
|
|
257
|
+
steps, start, length = [], t_end, 0.0
|
|
258
|
+
if recap:
|
|
259
|
+
steps, slide_lines, length = recap_slide((w, h), tl.get("brand") or {}, recap, manifest, work)
|
|
260
|
+
slide = slide_video(steps, length, work)
|
|
261
|
+
start = t_end - XFADE
|
|
262
|
+
for line in slide_lines:
|
|
263
|
+
placed.append({"id": line["id"], "start": None, "duration": line["duration"], "file": str(clips / line["file"]),
|
|
264
|
+
"at": round(start + line["at"], 3), "cutInto": []})
|
|
265
|
+
run(["ffmpeg", "-v", "error", "-y", "-i", str(cut), "-i", str(slide), "-filter_complex",
|
|
266
|
+
f"[0:v]trim=end={t_end:.3f},setpts=PTS-STARTPTS,fps={FPS},format=yuv420p,settb=AVTB[m];"
|
|
267
|
+
f"[1:v]fps={FPS},format=yuv420p,settb=AVTB[s];"
|
|
268
|
+
f"[m][s]xfade=transition=fade:duration={XFADE}:offset={start:.3f},format=yuv420p[v]",
|
|
269
|
+
"-map", "[v]", "-c:v", "libx264", "-preset", "medium", "-crf", "18", "-pix_fmt", "yuv420p", str(video)])
|
|
270
|
+
else:
|
|
271
|
+
run(["ffmpeg", "-v", "error", "-y", "-i", str(cut), "-an", "-vf", f"fps={FPS},format=yuv420p",
|
|
272
|
+
"-c:v", "libx264", "-preset", "medium", "-crf", "18", "-pix_fmt", "yuv420p", str(video)])
|
|
273
|
+
total = start + length
|
|
274
|
+
|
|
275
|
+
# 3. The voice: every clip at its time over silence the video's length, levelled for speech.
|
|
276
|
+
audio = work / "voice.m4a"
|
|
277
|
+
cmd = ["ffmpeg", "-v", "error", "-y", "-f", "lavfi", "-t", f"{total:.3f}", "-i", "anullsrc=r=24000:cl=mono"]
|
|
278
|
+
graph = []
|
|
279
|
+
for i, p in enumerate(placed, start=1):
|
|
280
|
+
cmd += ["-i", p["file"]]
|
|
281
|
+
graph.append(f"[{i}:a]adelay=delays={max(0, round(p['at'] * 1000))}:all=1[a{i}]")
|
|
282
|
+
graph.append("[0:a]" + "".join(f"[a{i}]" for i in range(1, len(placed) + 1))
|
|
283
|
+
+ f"amix=inputs={len(placed) + 1}:duration=first:normalize=0,loudnorm=I=-16:TP=-1.5:LRA=11,aresample=48000[out]")
|
|
284
|
+
run(cmd + ["-filter_complex", ";".join(graph), "-map", "[out]", "-c:a", "aac", "-b:a", "160k", str(audio)])
|
|
285
|
+
|
|
286
|
+
if args.speed == 1:
|
|
287
|
+
run(["ffmpeg", "-v", "error", "-y", "-i", str(video), "-i", str(audio), "-map", "0:v", "-map", "1:a",
|
|
288
|
+
"-c", "copy", "-shortest", "-movflags", "+faststart", str(out)])
|
|
289
|
+
else:
|
|
290
|
+
# Faster as a whole: the picture's clock and the voice's tempo together (atempo keeps the pitch).
|
|
291
|
+
run(["ffmpeg", "-v", "error", "-y", "-i", str(video), "-i", str(audio), "-filter_complex",
|
|
292
|
+
f"[0:v]setpts=PTS/{args.speed},fps={FPS}[v];[1:a]atempo={args.speed}[a]", "-map", "[v]", "-map", "[a]",
|
|
293
|
+
"-c:v", "libx264", "-preset", "medium", "-crf", "18", "-pix_fmt", "yuv420p", "-c:a", "aac", "-b:a", "160k",
|
|
294
|
+
"-shortest", "-movflags", "+faststart", str(out)])
|
|
295
|
+
|
|
296
|
+
# Times on the delivered video's clock (a line's `start` stays on the take's).
|
|
297
|
+
k = args.speed
|
|
298
|
+
scripted = [line["id"] for line in script["lines"]]
|
|
299
|
+
unsaid = [i for i in scripted if i not in {p["id"] for p in placed}]
|
|
300
|
+
if unsaid:
|
|
301
|
+
problems.append(f"in the script but not said in this take: {', '.join(unsaid)}")
|
|
302
|
+
report = {"video": str(out), "speed": k, "duration": round(total / k, 2), "editEnd": round(t_end / k, 3),
|
|
303
|
+
"slide": {"start": round(start / k, 3), "length": round(length / k, 3),
|
|
304
|
+
"steps": [{"step": s, "at": round((start + at) / k, 3)} for s, at in steps]} if recap else None,
|
|
305
|
+
"lines": [{"id": p["id"], "start": p["start"], "at": round(p["at"] / k, 3), "duration": round(p["duration"] / k, 3)}
|
|
306
|
+
for p in sorted(placed, key=lambda p: p["at"])],
|
|
307
|
+
"problems": problems}
|
|
308
|
+
out.parent.joinpath(out.name[: -len(out.suffix)] + ".json").write_text(json.dumps(report, indent=1))
|
|
309
|
+
speech = sum(p["duration"] for p in placed)
|
|
310
|
+
print(f"{len(placed)} lines ({speech / k:.1f} s of voice) on {total / k:.1f} s of video at {k}x"
|
|
311
|
+
+ (f"; the slide from {start / k:.1f} s" if recap else ""))
|
|
312
|
+
for p in problems:
|
|
313
|
+
print(f"warning: {p}")
|
|
314
|
+
print(f"wrote {out}")
|
|
315
|
+
if args.publish:
|
|
316
|
+
print(f"published {publish(out, args.publish, name)} (earlier takes kept)")
|
|
317
|
+
|
|
318
|
+
|
|
319
|
+
if __name__ == "__main__":
|
|
320
|
+
main()
|
|
@@ -0,0 +1,118 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* The closing recap slide of a narrated video, as PNGs, one per step: the story's points ticked off one
|
|
3
|
+
* by one as the voice names them, then the close (the title underlined, a thank-you). Styled with the
|
|
4
|
+
* brand the take recorded (its fonts and colours), like the edit's cards. Run by mix-take.py.
|
|
5
|
+
*
|
|
6
|
+
* node recap-slide.mjs <spec.json> <out dir>
|
|
7
|
+
*
|
|
8
|
+
* spec: { width, height, brand, recap: { kicker, title, lede, points: [{ title, detail }], closing } }.
|
|
9
|
+
* Writes step-0.png (nothing ticked) … step-N.png (all N ticked) and step-final.png.
|
|
10
|
+
*/
|
|
11
|
+
import { mkdirSync, readFileSync, writeFileSync } from 'node:fs'
|
|
12
|
+
import path from 'node:path'
|
|
13
|
+
import { pathToFileURL } from 'node:url'
|
|
14
|
+
import { chromium } from '@playwright/test'
|
|
15
|
+
|
|
16
|
+
const esc = (s = '') =>
|
|
17
|
+
s.replace(/[&<>"]/g, (ch) => ({ '&': '&', '<': '<', '>': '>', '"': '"' })[ch])
|
|
18
|
+
|
|
19
|
+
function css(b, w, h) {
|
|
20
|
+
const fonts = (b.fontFiles ?? [])
|
|
21
|
+
.map(
|
|
22
|
+
(f) =>
|
|
23
|
+
`@font-face { font-family: "${f.family}"; font-weight: ${f.weight ?? '100 900'}; src: url(${f.url});${f.unicodeRange ? ` unicode-range: ${f.unicodeRange};` : ''} }`
|
|
24
|
+
)
|
|
25
|
+
.join('\n')
|
|
26
|
+
return `${fonts}
|
|
27
|
+
:root { --from: ${b.coverFrom ?? '#0b1622'}; --mid: ${b.coverMid ?? '#0e1b2c'}; --to: ${b.coverTo ?? '#1f6feb'};
|
|
28
|
+
--accent: ${b.accent ?? '#c9a24b'}; --ink: ${b.ink ?? '#0e1b2d'}; --text: ${b.coverTitle ?? '#f4f6f8'};
|
|
29
|
+
--display: ${b.displayFont ?? 'ui-serif, Georgia, serif'}; --sans: ${b.sansFont ?? 'Inter, ui-sans-serif, system-ui, sans-serif'}; }
|
|
30
|
+
* { box-sizing: border-box; margin: 0; padding: 0; }
|
|
31
|
+
html, body { width: ${w}px; height: ${h}px; overflow: hidden; background: var(--from); color: var(--text);
|
|
32
|
+
font-family: var(--sans); -webkit-font-smoothing: antialiased; }
|
|
33
|
+
.slide { position: relative; width: ${w}px; height: ${h}px; overflow: hidden;
|
|
34
|
+
background: radial-gradient(70% 85% at 96% 112%, color-mix(in srgb, var(--to) 64%, transparent) 0%, transparent 62%),
|
|
35
|
+
radial-gradient(46% 58% at -4% -8%, color-mix(in srgb, var(--accent) 12%, transparent) 0%, transparent 70%),
|
|
36
|
+
linear-gradient(135deg, var(--from) 0%, var(--mid) 58%, var(--from) 100%); }
|
|
37
|
+
.slide::before { content: ""; position: absolute; inset: 40px; border: 1px solid color-mix(in srgb, var(--accent) 32%, transparent); border-radius: 4px; }
|
|
38
|
+
.grid { position: absolute; inset: 0; display: grid; grid-template-columns: 0.9fr 1fr; column-gap: 110px; align-items: center;
|
|
39
|
+
padding: 120px 150px 170px; }
|
|
40
|
+
.kicker { text-transform: uppercase; letter-spacing: .28em; font-size: 22px; font-weight: 600; color: var(--accent); }
|
|
41
|
+
h1 { font-family: var(--display); font-weight: 560; font-size: 104px; line-height: 1.02; letter-spacing: -.02em; margin-top: 34px; }
|
|
42
|
+
h1 span { background: linear-gradient(var(--accent), var(--accent)) no-repeat 0 94% / 0% 7px; }
|
|
43
|
+
.final h1 span { background-size: 100% 7px; }
|
|
44
|
+
.lede { margin-top: 38px; font-size: 30px; line-height: 1.45; color: color-mix(in srgb, var(--text) 72%, transparent); max-width: 25ch; }
|
|
45
|
+
ol { list-style: none; }
|
|
46
|
+
li { display: grid; grid-template-columns: 58px 1fr; column-gap: 30px; padding: 30px 0;
|
|
47
|
+
border-top: 1px solid color-mix(in srgb, var(--accent) 24%, transparent); opacity: .3; }
|
|
48
|
+
li:last-child { border-bottom: 1px solid color-mix(in srgb, var(--accent) 24%, transparent); }
|
|
49
|
+
li.done { opacity: 1; }
|
|
50
|
+
.tick { width: 58px; height: 58px; border-radius: 50%; display: grid; place-items: center; margin-top: 4px;
|
|
51
|
+
border: 2px solid color-mix(in srgb, var(--accent) 75%, transparent); }
|
|
52
|
+
.tick svg { width: 30px; height: 30px; fill: none; stroke: var(--ink); stroke-width: 3.4; stroke-linecap: round; stroke-linejoin: round; visibility: hidden; }
|
|
53
|
+
li.done .tick { background: var(--accent); border-color: var(--accent); box-shadow: 0 0 0 7px color-mix(in srgb, var(--accent) 18%, transparent); }
|
|
54
|
+
li.done .tick svg { visibility: visible; }
|
|
55
|
+
.n { font-size: 17px; font-weight: 650; letter-spacing: .22em; color: var(--accent); }
|
|
56
|
+
li h2 { font-size: 37px; line-height: 1.18; font-weight: 600; letter-spacing: -.005em; margin-top: 8px; }
|
|
57
|
+
li p { font-size: 24px; line-height: 1.4; color: color-mix(in srgb, var(--text) 66%, transparent); margin-top: 8px; }
|
|
58
|
+
.foot { position: absolute; left: 150px; right: 150px; bottom: 92px; display: flex; align-items: center; justify-content: space-between; }
|
|
59
|
+
.mark { display: flex; align-items: center; gap: 16px; font-size: 22px; color: color-mix(in srgb, var(--text) 64%, transparent); }
|
|
60
|
+
.rule { width: 56px; height: 2px; background: var(--accent); }
|
|
61
|
+
.thanks { font-family: var(--display); font-size: 34px; font-weight: 500; color: var(--text); visibility: hidden; }
|
|
62
|
+
.thanks b { color: var(--accent); font-weight: 500; }
|
|
63
|
+
.final .thanks { visibility: visible; }
|
|
64
|
+
`
|
|
65
|
+
}
|
|
66
|
+
|
|
67
|
+
const TICK = '<svg viewBox="0 0 24 24"><path d="M5 12.5l4.5 4.5L19 7.5"/></svg>'
|
|
68
|
+
|
|
69
|
+
function markup(spec, done, final) {
|
|
70
|
+
const r = spec.recap
|
|
71
|
+
const [lead, last] = (() => {
|
|
72
|
+
const words = r.title.split(' ')
|
|
73
|
+
return [words.slice(0, -1).join(' '), words[words.length - 1]]
|
|
74
|
+
})()
|
|
75
|
+
const points = r.points
|
|
76
|
+
.map(
|
|
77
|
+
(p, i) => `<li class="${i < done ? 'done' : ''}"><div class="tick">${TICK}</div><div>
|
|
78
|
+
<div class="n">${String(i + 1).padStart(2, '0')}</div><h2>${esc(p.title)}</h2><p>${esc(p.detail)}</p></div></li>`
|
|
79
|
+
)
|
|
80
|
+
.join('')
|
|
81
|
+
return `<div class="slide${final ? ' final' : ''}"><div class="grid">
|
|
82
|
+
<div><div class="kicker">${esc(r.kicker)}</div><h1>${esc(lead)} <span>${esc(last)}</span></h1><p class="lede">${esc(r.lede)}</p></div>
|
|
83
|
+
<ol>${points}</ol></div>
|
|
84
|
+
<div class="foot"><div class="mark"><span class="rule"></span><span>${esc(spec.brand?.firmLabel ?? '')}</span></div>
|
|
85
|
+
<div class="thanks">${esc(r.closing)}</div></div></div>`
|
|
86
|
+
}
|
|
87
|
+
|
|
88
|
+
async function main() {
|
|
89
|
+
const [specFile, outDir] = process.argv.slice(2)
|
|
90
|
+
if (!specFile || !outDir) throw new Error('usage: recap-slide.mjs <spec.json> <out dir>')
|
|
91
|
+
const spec = JSON.parse(readFileSync(specFile, 'utf8'))
|
|
92
|
+
const { width: w, height: h } = spec
|
|
93
|
+
mkdirSync(outDir, { recursive: true })
|
|
94
|
+
const html = path.join(outDir, 'recap.html')
|
|
95
|
+
writeFileSync(
|
|
96
|
+
html,
|
|
97
|
+
`<!doctype html><html><head><meta charset="utf-8"><style>${css(spec.brand ?? {}, w, h)}</style></head><body><div id="o"></div></body></html>`
|
|
98
|
+
)
|
|
99
|
+
const browser = await chromium.launch()
|
|
100
|
+
try {
|
|
101
|
+
const page = await browser.newPage({ viewport: { width: w, height: h } })
|
|
102
|
+
await page.goto(pathToFileURL(html).href)
|
|
103
|
+
const n = spec.recap.points.length
|
|
104
|
+
const steps = [
|
|
105
|
+
...Array.from({ length: n + 1 }, (_, i) => [`step-${i}`, i, false]),
|
|
106
|
+
['step-final', n, true],
|
|
107
|
+
]
|
|
108
|
+
for (const [name, done, final] of steps) {
|
|
109
|
+
await page.locator('#o').evaluate((el, m) => (el.innerHTML = m), markup(spec, done, final))
|
|
110
|
+
await page.evaluate(() => document.fonts.ready)
|
|
111
|
+
await page.screenshot({ path: path.join(outDir, `${name}.png`) })
|
|
112
|
+
}
|
|
113
|
+
} finally {
|
|
114
|
+
await browser.close()
|
|
115
|
+
}
|
|
116
|
+
}
|
|
117
|
+
|
|
118
|
+
await main()
|
|
@@ -0,0 +1,129 @@
|
|
|
1
|
+
"""Speak a story's narration: one clip per line, and a manifest of their lengths for the story to pace by.
|
|
2
|
+
|
|
3
|
+
arbidocs-voice-take <story>.narration.json <out dir> --model <kokoro dir> [--ref <clip.wav>]
|
|
4
|
+
|
|
5
|
+
The narration is the story's script:
|
|
6
|
+
|
|
7
|
+
{"voice": "bf_lily", "lang": "en-gb", "speed": 1, "lines": [{"id", "text", "speech"?}], "recap": {...},
|
|
8
|
+
"spoken": [[pattern, said]], "phonemes": [[heard, meant]], "respell": [[pattern, said]]}
|
|
9
|
+
|
|
10
|
+
`text` is what the band shows; what is spoken is `speech` when given, else `text` with `spoken`
|
|
11
|
+
applied (regular expressions: a time, a web address, a name written one way and said another).
|
|
12
|
+
`phonemes` fixes what Kokoro's phonemiser gets wrong (its guess -> the word as it is said);
|
|
13
|
+
`respell` does the same for Chatterbox, which reads text, not phonemes.
|
|
14
|
+
|
|
15
|
+
The house voice is Kokoro's `bf_lily` in British English (82M, ONNX, offline, on the CPU):
|
|
16
|
+
`pip install kokoro-onnx soundfile` in a venv, and <kokoro dir> holding `model.onnx` and
|
|
17
|
+
`voices/<voice>.bin` (both from the Hugging Face repo onnx-community/Kokoro-82M-v1.0-ONNX).
|
|
18
|
+
`"engine": "chatterbox"` (with `exaggeration`, `cfg`) instead clones the voice of the clip given as
|
|
19
|
+
`--ref` (`pip install chatterbox-tts`; a GPU if there is one, else the CPU: slower, same voice,
|
|
20
|
+
about 4.6 GB of memory).
|
|
21
|
+
|
|
22
|
+
A line whose words, voice and speed have not changed is not spoken again. After changing
|
|
23
|
+
`phonemes` or `respell`, delete the clips of the lines they touch.
|
|
24
|
+
"""
|
|
25
|
+
import argparse
|
|
26
|
+
import hashlib
|
|
27
|
+
import json
|
|
28
|
+
import re
|
|
29
|
+
import sys
|
|
30
|
+
from pathlib import Path
|
|
31
|
+
|
|
32
|
+
PAD = 0.06 # s of silence kept either side of the voice
|
|
33
|
+
HOUSE_VOICE = "bf_lily"
|
|
34
|
+
HOUSE_LANG = "en-gb"
|
|
35
|
+
|
|
36
|
+
|
|
37
|
+
def spoken(text, rules):
|
|
38
|
+
"""`text` as it is said: each [pattern, said] rule applied in order."""
|
|
39
|
+
for pattern, said in rules:
|
|
40
|
+
text = re.sub(pattern, said, text)
|
|
41
|
+
return text
|
|
42
|
+
|
|
43
|
+
|
|
44
|
+
def clip_key(tag, said):
|
|
45
|
+
"""A clip is spoken again only when this changes: the voice's settings and the words said."""
|
|
46
|
+
return hashlib.sha1(f"{tag}|{said}".encode()).hexdigest()[:12]
|
|
47
|
+
|
|
48
|
+
|
|
49
|
+
def main():
|
|
50
|
+
ap = argparse.ArgumentParser()
|
|
51
|
+
ap.add_argument("script")
|
|
52
|
+
ap.add_argument("out")
|
|
53
|
+
ap.add_argument("--model", help="Kokoro: directory with model.onnx and voices/<voice>.bin")
|
|
54
|
+
ap.add_argument("--ref", help="Chatterbox: reference clip of the voice to clone")
|
|
55
|
+
args = ap.parse_args()
|
|
56
|
+
|
|
57
|
+
import numpy as np
|
|
58
|
+
import soundfile as sf
|
|
59
|
+
|
|
60
|
+
script = json.loads(Path(args.script).read_text())
|
|
61
|
+
voice = script.get("voice", HOUSE_VOICE)
|
|
62
|
+
lang = script.get("lang", HOUSE_LANG)
|
|
63
|
+
speed = float(script.get("speed", 1.0))
|
|
64
|
+
out = Path(args.out)
|
|
65
|
+
out.mkdir(parents=True, exist_ok=True)
|
|
66
|
+
manifest_path = out / "manifest.json"
|
|
67
|
+
old = json.loads(manifest_path.read_text())["lines"] if manifest_path.exists() else {}
|
|
68
|
+
|
|
69
|
+
engine = script.get("engine", "kokoro")
|
|
70
|
+
if engine == "chatterbox":
|
|
71
|
+
if not args.ref:
|
|
72
|
+
sys.exit("engine chatterbox needs --ref <clip of the voice to clone>")
|
|
73
|
+
import torch
|
|
74
|
+
from chatterbox.tts import ChatterboxTTS
|
|
75
|
+
tts = ChatterboxTTS.from_pretrained(device="cuda" if torch.cuda.is_available() else "cpu")
|
|
76
|
+
ex, cfg = float(script.get("exaggeration", 0.5)), float(script.get("cfg", 0.5))
|
|
77
|
+
rate = tts.sr
|
|
78
|
+
respell = script.get("respell", [])
|
|
79
|
+
|
|
80
|
+
def render(said):
|
|
81
|
+
torch.manual_seed(0)
|
|
82
|
+
return tts.generate(spoken(said, respell), audio_prompt_path=args.ref, exaggeration=ex, cfg_weight=cfg).squeeze(0).cpu().numpy()
|
|
83
|
+
tag = f"cb|{Path(args.ref).name}|{ex}|{cfg}"
|
|
84
|
+
else:
|
|
85
|
+
if not args.model:
|
|
86
|
+
sys.exit("the Kokoro voice needs --model <directory with model.onnx and voices/>")
|
|
87
|
+
from kokoro_onnx import Kokoro
|
|
88
|
+
model = Path(args.model)
|
|
89
|
+
pack = model / f"voice-{voice}.npz"
|
|
90
|
+
if not pack.exists():
|
|
91
|
+
np.savez(pack, **{voice: np.fromfile(model / "voices" / f"{voice}.bin", dtype=np.float32).reshape(-1, 1, 256)})
|
|
92
|
+
kokoro = Kokoro(str(model / "model.onnx"), str(pack))
|
|
93
|
+
rate = 24000
|
|
94
|
+
fixes = script.get("phonemes", [])
|
|
95
|
+
|
|
96
|
+
def render(said):
|
|
97
|
+
phonemes = kokoro.tokenizer.phonemize(said, lang=lang)
|
|
98
|
+
for heard, meant in fixes:
|
|
99
|
+
phonemes = phonemes.replace(heard, meant)
|
|
100
|
+
audio, _ = kokoro.create(phonemes, voice=voice, speed=speed, lang=lang, is_phonemes=True)
|
|
101
|
+
return audio
|
|
102
|
+
tag = f"{voice}|{speed}"
|
|
103
|
+
|
|
104
|
+
rules = script.get("spoken", [])
|
|
105
|
+
lines = {}
|
|
106
|
+
for line in script["lines"]:
|
|
107
|
+
said = line.get("speech") or spoken(line["text"], rules)
|
|
108
|
+
key = clip_key(tag, said)
|
|
109
|
+
wav = out / f"{line['id']}.wav"
|
|
110
|
+
if old.get(line["id"], {}).get("key") == key and wav.exists():
|
|
111
|
+
lines[line["id"]] = {**old[line["id"]], "text": line["text"]}
|
|
112
|
+
continue
|
|
113
|
+
audio = np.asarray(render(said), np.float32)
|
|
114
|
+
loud = np.flatnonzero(np.abs(audio) > 0.01) # trim the model's own lead-in and tail
|
|
115
|
+
if loud.size:
|
|
116
|
+
audio = audio[max(0, loud[0] - int(0.02 * rate)):loud[-1] + int(0.08 * rate)]
|
|
117
|
+
audio = np.concatenate([np.zeros(int(PAD * rate), np.float32), audio, np.zeros(int(PAD * rate), np.float32)])
|
|
118
|
+
sf.write(wav, audio, rate, subtype="PCM_16")
|
|
119
|
+
lines[line["id"]] = {"text": line["text"], "spoken": said, "file": wav.name, "duration": round(len(audio) / rate, 3), "key": key,
|
|
120
|
+
"peak": round(float(np.abs(audio).max()), 3)}
|
|
121
|
+
print(f"{line['id']:10s} {lines[line['id']]['duration']:5.2f} s {said}", flush=True)
|
|
122
|
+
|
|
123
|
+
total = sum(v["duration"] for v in lines.values())
|
|
124
|
+
manifest_path.write_text(json.dumps({"voice": voice, "lang": lang, "speed": speed, "total": round(total, 2), "lines": lines}, indent=1))
|
|
125
|
+
print(f"{len(lines)} lines, {total:.1f} s of narration -> {manifest_path}")
|
|
126
|
+
|
|
127
|
+
|
|
128
|
+
if __name__ == "__main__":
|
|
129
|
+
main()
|