tokenreel 0.2.0__py3-none-any.whl
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.
- tokenreel/__init__.py +1 -0
- tokenreel/align.py +48 -0
- tokenreel/cli.py +45 -0
- tokenreel/mcp_server.py +158 -0
- tokenreel/render.py +210 -0
- tokenreel/safe_ffmpeg.py +42 -0
- tokenreel/segment.py +89 -0
- tokenreel/telemetry.py +39 -0
- tokenreel/timing.py +107 -0
- tokenreel/tts.py +49 -0
- tokenreel-0.2.0.dist-info/METADATA +180 -0
- tokenreel-0.2.0.dist-info/RECORD +15 -0
- tokenreel-0.2.0.dist-info/WHEEL +4 -0
- tokenreel-0.2.0.dist-info/entry_points.txt +3 -0
- tokenreel-0.2.0.dist-info/licenses/LICENSE +202 -0
tokenreel/__init__.py
ADDED
|
@@ -0,0 +1 @@
|
|
|
1
|
+
__version__ = "0.2.0"
|
tokenreel/align.py
ADDED
|
@@ -0,0 +1,48 @@
|
|
|
1
|
+
"""Exact word timings from audio via faster-whisper (extra: align). MIT, CPU friendly.
|
|
2
|
+
|
|
3
|
+
This replaces the calibrated estimate in tts.py when available. The aligner runs locally;
|
|
4
|
+
the small English model (about 75 MB) is downloaded once from the Hugging Face hub on first
|
|
5
|
+
use, then cached. Set TOKENREEL_WHISPER_MODEL to change the model size.
|
|
6
|
+
|
|
7
|
+
The script words are the source of truth for caption text. If the recognizer returns the
|
|
8
|
+
same number of words, script words get the recognizer's times. Otherwise the recognizer's
|
|
9
|
+
words are used as-is.
|
|
10
|
+
"""
|
|
11
|
+
from __future__ import annotations
|
|
12
|
+
|
|
13
|
+
import os
|
|
14
|
+
from pathlib import Path
|
|
15
|
+
|
|
16
|
+
from .timing import Word
|
|
17
|
+
|
|
18
|
+
_model = None
|
|
19
|
+
|
|
20
|
+
|
|
21
|
+
def _whisper():
|
|
22
|
+
global _model
|
|
23
|
+
if _model is None:
|
|
24
|
+
from faster_whisper import WhisperModel # lazy: optional dependency
|
|
25
|
+
|
|
26
|
+
_model = WhisperModel(os.environ.get("TOKENREEL_WHISPER_MODEL", "tiny.en"), device="cpu", compute_type="int8")
|
|
27
|
+
return _model
|
|
28
|
+
|
|
29
|
+
|
|
30
|
+
def align(wav: Path, script_words: list[str], offset: float = 0.0) -> list[Word]:
|
|
31
|
+
import numpy as np
|
|
32
|
+
import soundfile as sf
|
|
33
|
+
|
|
34
|
+
# decode our own wav and resample to 16 kHz mono, so faster-whisper never touches PyAV
|
|
35
|
+
# (PyAV 19 broke its decode path)
|
|
36
|
+
audio, rate = sf.read(str(wav), dtype="float32")
|
|
37
|
+
if audio.ndim > 1:
|
|
38
|
+
audio = audio.mean(axis=1)
|
|
39
|
+
if rate != 16000:
|
|
40
|
+
n = int(len(audio) * 16000 / rate)
|
|
41
|
+
audio = np.interp(np.linspace(0, len(audio) - 1, n), np.arange(len(audio)), audio).astype("float32")
|
|
42
|
+
segments, _ = _whisper().transcribe(audio, word_timestamps=True, language="en", beam_size=1)
|
|
43
|
+
heard = [w for seg in segments for w in (seg.words or [])]
|
|
44
|
+
if not heard:
|
|
45
|
+
return []
|
|
46
|
+
if len(heard) == len(script_words):
|
|
47
|
+
return [Word(t, round(offset + h.start, 3), round(offset + h.end, 3)) for t, h in zip(script_words, heard)]
|
|
48
|
+
return [Word(h.word.strip(), round(offset + h.start, 3), round(offset + h.end, 3)) for h in heard]
|
tokenreel/cli.py
ADDED
|
@@ -0,0 +1,45 @@
|
|
|
1
|
+
import argparse
|
|
2
|
+
import json
|
|
3
|
+
import sys
|
|
4
|
+
|
|
5
|
+
from . import __version__
|
|
6
|
+
from .segment import plan
|
|
7
|
+
|
|
8
|
+
|
|
9
|
+
def main(argv=None) -> int:
|
|
10
|
+
ap = argparse.ArgumentParser(prog="tokenreel")
|
|
11
|
+
ap.add_argument("--version", action="version", version=__version__)
|
|
12
|
+
sub = ap.add_subparsers(dest="cmd", required=True)
|
|
13
|
+
p = sub.add_parser("plan", help="print the scene plan for a text file (JSON)")
|
|
14
|
+
p.add_argument("file")
|
|
15
|
+
c = sub.add_parser("srt", help="print estimated captions (SRT) for a text file")
|
|
16
|
+
c.add_argument("file")
|
|
17
|
+
r = sub.add_parser("render", help="render a silent preview mp4 (needs Pillow and ffmpeg)")
|
|
18
|
+
r.add_argument("file")
|
|
19
|
+
r.add_argument("--out", default="build")
|
|
20
|
+
r.add_argument("--audio", action="store_true", help="narrate offline with Kokoro")
|
|
21
|
+
r.add_argument("--align", action="store_true", help="exact word times via faster-whisper (needs --audio)")
|
|
22
|
+
r.add_argument("--burn", action="store_true", help="burn captions into the video, highlighting each word as it is spoken")
|
|
23
|
+
r.add_argument("--plain-captions", action="store_true", help="with --burn, use static captions without word highlighting")
|
|
24
|
+
a = ap.parse_args(argv)
|
|
25
|
+
if a.cmd == "plan":
|
|
26
|
+
with open(a.file, encoding="utf-8") as f:
|
|
27
|
+
scenes = plan(f.read())
|
|
28
|
+
json.dump([s.__dict__ for s in scenes], sys.stdout, indent=2)
|
|
29
|
+
print()
|
|
30
|
+
elif a.cmd == "srt":
|
|
31
|
+
from .timing import estimate_timings, to_srt
|
|
32
|
+
|
|
33
|
+
with open(a.file, encoding="utf-8") as f:
|
|
34
|
+
print(to_srt(estimate_timings(f.read())))
|
|
35
|
+
elif a.cmd == "render":
|
|
36
|
+
from .render import render
|
|
37
|
+
|
|
38
|
+
with open(a.file, encoding="utf-8") as f:
|
|
39
|
+
mp4, srt = render(plan(f.read()), a.out, audio=a.audio, align=a.align, burn=a.burn, highlight=not a.plain_captions)
|
|
40
|
+
print(mp4, srt, sep="\n")
|
|
41
|
+
return 0
|
|
42
|
+
|
|
43
|
+
|
|
44
|
+
if __name__ == "__main__":
|
|
45
|
+
raise SystemExit(main())
|
tokenreel/mcp_server.py
ADDED
|
@@ -0,0 +1,158 @@
|
|
|
1
|
+
"""TokenReel as an MCP server (extra: mcp). Runs over stdio by default.
|
|
2
|
+
|
|
3
|
+
Tools let an AI agent plan scenes from text, get estimated captions, and render a
|
|
4
|
+
narrated, captioned 1080x1920 video, all locally.
|
|
5
|
+
|
|
6
|
+
Security: the client never supplies file paths. Output goes to TOKENREEL_OUT (default
|
|
7
|
+
~/tokenreel-output), one fresh subfolder per render, and the file name is restricted to a
|
|
8
|
+
short allow-listed charset. Input size and scene count are capped. Everything runs offline.
|
|
9
|
+
"""
|
|
10
|
+
from __future__ import annotations
|
|
11
|
+
|
|
12
|
+
import functools
|
|
13
|
+
import os
|
|
14
|
+
import re
|
|
15
|
+
import shutil
|
|
16
|
+
import uuid
|
|
17
|
+
from dataclasses import asdict
|
|
18
|
+
from pathlib import Path
|
|
19
|
+
|
|
20
|
+
try: # mcp 2.x
|
|
21
|
+
from mcp.server.mcpserver import MCPServer as _Server
|
|
22
|
+
from mcp.server.mcpserver.exceptions import ToolError
|
|
23
|
+
except ImportError: # mcp 1.x
|
|
24
|
+
from mcp.server.fastmcp import FastMCP as _Server
|
|
25
|
+
from mcp.server.fastmcp.exceptions import ToolError
|
|
26
|
+
|
|
27
|
+
from . import __version__
|
|
28
|
+
from .segment import plan
|
|
29
|
+
from .timing import estimate_timings, to_srt
|
|
30
|
+
|
|
31
|
+
MAX_CHARS = 20_000
|
|
32
|
+
MAX_SCENES = 40
|
|
33
|
+
_NAME = re.compile(r"[A-Za-z0-9_-]{1,40}")
|
|
34
|
+
|
|
35
|
+
mcp = _Server(
|
|
36
|
+
"tokenreel",
|
|
37
|
+
version=__version__,
|
|
38
|
+
instructions=(
|
|
39
|
+
"Turn text or Markdown into short animated, narrated, captioned videos (1080x1920). "
|
|
40
|
+
"Fenced code blocks become code scenes, 'first, then, finally' sentences become flow "
|
|
41
|
+
"diagrams, equations become math cards. Use plan_scenes to preview, render_video to produce an mp4."
|
|
42
|
+
),
|
|
43
|
+
)
|
|
44
|
+
|
|
45
|
+
|
|
46
|
+
def _friendly(fn):
|
|
47
|
+
"""Show anticipated failures to the agent. Only ToolError messages reach the client;
|
|
48
|
+
any other exception becomes the opaque 'Error executing tool'."""
|
|
49
|
+
|
|
50
|
+
@functools.wraps(fn)
|
|
51
|
+
def wrapper(*args, **kwargs):
|
|
52
|
+
try:
|
|
53
|
+
return fn(*args, **kwargs)
|
|
54
|
+
except (ValueError, RuntimeError) as exc:
|
|
55
|
+
raise ToolError(str(exc)) from exc
|
|
56
|
+
|
|
57
|
+
return wrapper
|
|
58
|
+
|
|
59
|
+
|
|
60
|
+
def _check(text: str) -> str:
|
|
61
|
+
if not text.strip():
|
|
62
|
+
raise ValueError("text is empty")
|
|
63
|
+
if len(text) > MAX_CHARS:
|
|
64
|
+
raise ValueError(f"text too long ({len(text)} chars, max {MAX_CHARS})")
|
|
65
|
+
return text
|
|
66
|
+
|
|
67
|
+
|
|
68
|
+
def _out_root() -> Path:
|
|
69
|
+
root = Path(os.environ.get("TOKENREEL_OUT", Path.home() / "tokenreel-output")).resolve()
|
|
70
|
+
root.mkdir(parents=True, exist_ok=True)
|
|
71
|
+
return root
|
|
72
|
+
|
|
73
|
+
|
|
74
|
+
def _require_extras(narrate: bool, exact_timings: bool) -> None:
|
|
75
|
+
"""Fail early with an actionable message instead of a raw ImportError mid-render."""
|
|
76
|
+
from importlib.util import find_spec
|
|
77
|
+
|
|
78
|
+
def need(mod: str, extra: str) -> None:
|
|
79
|
+
if find_spec(mod) is None:
|
|
80
|
+
raise RuntimeError(f"this option needs the '{extra}' extra (pip install 'tokenreel[{extra}]'); module {mod} is missing")
|
|
81
|
+
|
|
82
|
+
need("PIL", "render")
|
|
83
|
+
if narrate:
|
|
84
|
+
need("kokoro_onnx", "tts")
|
|
85
|
+
need("soundfile", "tts")
|
|
86
|
+
from . import tts
|
|
87
|
+
|
|
88
|
+
if not tts.available():
|
|
89
|
+
raise RuntimeError(f"Kokoro model files not found in {tts.MODEL_DIR}; see the README")
|
|
90
|
+
if exact_timings:
|
|
91
|
+
need("faster_whisper", "align")
|
|
92
|
+
|
|
93
|
+
|
|
94
|
+
@mcp.tool()
|
|
95
|
+
@_friendly
|
|
96
|
+
def plan_scenes(text: str) -> list[dict]:
|
|
97
|
+
"""Split text or Markdown into scenes. Each scene has a kind (text, flow, math, code),
|
|
98
|
+
its text, keywords and, for flow scenes, numbered steps. No files are written."""
|
|
99
|
+
scenes = plan(_check(text))[:MAX_SCENES]
|
|
100
|
+
return [asdict(s) for s in scenes]
|
|
101
|
+
|
|
102
|
+
|
|
103
|
+
@mcp.tool()
|
|
104
|
+
@_friendly
|
|
105
|
+
def make_captions(text: str) -> str:
|
|
106
|
+
"""Return estimated SRT captions for the text. For exact timings render with narration."""
|
|
107
|
+
return to_srt(estimate_timings(_check(text)))
|
|
108
|
+
|
|
109
|
+
|
|
110
|
+
@mcp.tool()
|
|
111
|
+
@_friendly
|
|
112
|
+
def render_video(
|
|
113
|
+
text: str,
|
|
114
|
+
name: str = "video",
|
|
115
|
+
narrate: bool = False,
|
|
116
|
+
exact_timings: bool = False,
|
|
117
|
+
burn_captions: bool = False,
|
|
118
|
+
highlight_words: bool = True,
|
|
119
|
+
) -> dict:
|
|
120
|
+
"""Render text to an mp4 plus captions.srt inside the server's output folder.
|
|
121
|
+
|
|
122
|
+
narrate: offline Kokoro voiceover (needs the model files, see the README).
|
|
123
|
+
exact_timings: align word times with a local recognizer (needs narrate).
|
|
124
|
+
burn_captions: draw captions into the video.
|
|
125
|
+
highlight_words: with burn_captions, fill each word with an accent colour as it is spoken.
|
|
126
|
+
Returns the output paths. Requires ffmpeg and the render extra."""
|
|
127
|
+
if not _NAME.fullmatch(name):
|
|
128
|
+
raise ValueError("name must be 1-40 characters of letters, digits, '-' or '_'")
|
|
129
|
+
if exact_timings and not narrate:
|
|
130
|
+
raise ValueError("exact_timings requires narrate=true")
|
|
131
|
+
if shutil.which("ffmpeg") is None:
|
|
132
|
+
raise RuntimeError("ffmpeg was not found on PATH")
|
|
133
|
+
scenes = plan(_check(text))
|
|
134
|
+
if len(scenes) > MAX_SCENES:
|
|
135
|
+
raise ValueError(f"too many scenes ({len(scenes)}, max {MAX_SCENES})")
|
|
136
|
+
_require_extras(narrate, exact_timings)
|
|
137
|
+
from .render import render
|
|
138
|
+
|
|
139
|
+
workdir = _out_root() / f"{name}-{uuid.uuid4().hex[:8]}"
|
|
140
|
+
mp4, srt = render(scenes, workdir, f"{name}.mp4", audio=narrate, align=exact_timings, burn=burn_captions, highlight=highlight_words)
|
|
141
|
+
root = _out_root()
|
|
142
|
+
return {
|
|
143
|
+
"video": str(mp4),
|
|
144
|
+
"captions": str(srt),
|
|
145
|
+
# relative to TOKENREEL_OUT, which is what a host sees when the server runs in a container
|
|
146
|
+
"video_relative": mp4.relative_to(root).as_posix(),
|
|
147
|
+
"captions_relative": srt.relative_to(root).as_posix(),
|
|
148
|
+
"scenes": len(scenes),
|
|
149
|
+
"narrated": narrate,
|
|
150
|
+
}
|
|
151
|
+
|
|
152
|
+
|
|
153
|
+
def main() -> None:
|
|
154
|
+
mcp.run(os.environ.get("TOKENREEL_TRANSPORT", "stdio"))
|
|
155
|
+
|
|
156
|
+
|
|
157
|
+
if __name__ == "__main__":
|
|
158
|
+
main()
|
tokenreel/render.py
ADDED
|
@@ -0,0 +1,210 @@
|
|
|
1
|
+
"""Frame rendering with Pillow (extra: render) and assembly through safe_ffmpeg.
|
|
2
|
+
|
|
3
|
+
Portrait 1080x1920 for Shorts and Reels. Each scene becomes one PNG; the concat list
|
|
4
|
+
and ffmpeg call stay inside a confined working directory.
|
|
5
|
+
"""
|
|
6
|
+
from __future__ import annotations
|
|
7
|
+
|
|
8
|
+
import textwrap
|
|
9
|
+
from pathlib import Path
|
|
10
|
+
|
|
11
|
+
from .safe_ffmpeg import run
|
|
12
|
+
from .segment import Scene
|
|
13
|
+
from .timing import estimate_timings
|
|
14
|
+
|
|
15
|
+
W, H = 1080, 1920
|
|
16
|
+
# kind -> (gradient top, gradient bottom, accent, badge label)
|
|
17
|
+
THEME = {
|
|
18
|
+
"text": ((16, 18, 40), (44, 28, 84), (167, 139, 250), "EXPLAINER"),
|
|
19
|
+
"code": ((8, 14, 24), (16, 40, 44), (52, 211, 153), "CODE"),
|
|
20
|
+
"math": ((28, 14, 44), (74, 32, 64), (251, 191, 36), "MATH"),
|
|
21
|
+
"flow": ((8, 22, 44), (14, 58, 92), (56, 189, 248), "FLOW"),
|
|
22
|
+
}
|
|
23
|
+
_SANS = ["segoeuib.ttf", "DejaVuSans-Bold.ttf", "arialbd.ttf"]
|
|
24
|
+
_BODY = ["segoeui.ttf", "DejaVuSans.ttf", "arial.ttf"]
|
|
25
|
+
_MONO = ["consola.ttf", "DejaVuSansMono.ttf", "cour.ttf"]
|
|
26
|
+
_KW = {"def", "class", "return", "import", "from", "if", "else", "elif", "for", "while", "in",
|
|
27
|
+
"const", "let", "var", "function", "async", "await", "try", "except", "with", "as", "None",
|
|
28
|
+
"True", "False", "print", "self"}
|
|
29
|
+
|
|
30
|
+
|
|
31
|
+
def _font(names, size):
|
|
32
|
+
from PIL import ImageFont
|
|
33
|
+
|
|
34
|
+
for n in names:
|
|
35
|
+
try:
|
|
36
|
+
return ImageFont.truetype(n, size)
|
|
37
|
+
except OSError:
|
|
38
|
+
continue
|
|
39
|
+
return ImageFont.load_default(size)
|
|
40
|
+
|
|
41
|
+
|
|
42
|
+
def _gradient(top, bottom):
|
|
43
|
+
from PIL import Image
|
|
44
|
+
|
|
45
|
+
col = Image.linear_gradient("L").resize((W, H))
|
|
46
|
+
return Image.composite(Image.new("RGB", (W, H), bottom), Image.new("RGB", (W, H), top), col)
|
|
47
|
+
|
|
48
|
+
|
|
49
|
+
def _code_line(d, xy, line, font, accent):
|
|
50
|
+
"""Tiny highlighter: keywords accent, strings amber, comments grey, rest white."""
|
|
51
|
+
import re
|
|
52
|
+
|
|
53
|
+
x, y = xy
|
|
54
|
+
for tok in re.findall(r"#.*|\"[^\"]*\"|'[^']*'|\w+|\W", line):
|
|
55
|
+
if tok.startswith("#"):
|
|
56
|
+
fill = (130, 140, 160)
|
|
57
|
+
elif tok[0] in "\"'":
|
|
58
|
+
fill = (251, 191, 36)
|
|
59
|
+
elif tok in _KW:
|
|
60
|
+
fill = accent
|
|
61
|
+
else:
|
|
62
|
+
fill = (232, 236, 244)
|
|
63
|
+
d.text((x, y), tok, fill=fill, font=font)
|
|
64
|
+
x += d.textlength(tok, font=font)
|
|
65
|
+
|
|
66
|
+
|
|
67
|
+
def draw_scene(scene: Scene, path: Path, index: int = 0, total: int = 1) -> None:
|
|
68
|
+
from PIL import ImageDraw
|
|
69
|
+
|
|
70
|
+
top, bottom, accent, label = THEME.get(scene.kind, THEME["text"])
|
|
71
|
+
img = _gradient(top, bottom)
|
|
72
|
+
d = ImageDraw.Draw(img, "RGBA")
|
|
73
|
+
|
|
74
|
+
# badge
|
|
75
|
+
f_badge = _font(_SANS, 40)
|
|
76
|
+
bw = int(d.textlength(label, font=f_badge)) + 72
|
|
77
|
+
d.rounded_rectangle((70, 110, 70 + bw, 190), 40, fill=(*accent, 255))
|
|
78
|
+
d.text((106, 124), label, fill=(12, 12, 24), font=f_badge)
|
|
79
|
+
d.text((W - 70, 124), f"{index + 1}/{total}", fill=(255, 255, 255, 150), font=f_badge, anchor="ra")
|
|
80
|
+
|
|
81
|
+
# card
|
|
82
|
+
card = (60, 260, W - 60, H - 380)
|
|
83
|
+
d.rounded_rectangle((card[0] + 8, card[1] + 14, card[2] + 8, card[3] + 14), 48, fill=(0, 0, 0, 90))
|
|
84
|
+
d.rounded_rectangle(card, 48, fill=(255, 255, 255, 22), outline=(*accent, 150), width=3)
|
|
85
|
+
d.rounded_rectangle((card[0], card[1] + 40, card[0] + 14, card[3] - 40), 7, fill=(*accent, 255))
|
|
86
|
+
|
|
87
|
+
if scene.kind == "code":
|
|
88
|
+
f = _font(_MONO, 52)
|
|
89
|
+
for dot, c in enumerate(((255, 95, 86), (255, 189, 46), (39, 201, 63))):
|
|
90
|
+
d.ellipse((110 + dot * 56, 305, 140 + dot * 56, 335), fill=c)
|
|
91
|
+
lines_ = scene.text.splitlines()[:14]
|
|
92
|
+
y = max(390, (card[1] + card[3]) // 2 - len(lines_) * 78 // 2)
|
|
93
|
+
for n, line in enumerate(lines_, 1):
|
|
94
|
+
d.text((110, y), f"{n:>2}", fill=(110, 120, 140), font=f)
|
|
95
|
+
_code_line(d, (190, y), line[:30], f, accent)
|
|
96
|
+
y += 78
|
|
97
|
+
elif scene.kind == "flow" and len(scene.steps) >= 2:
|
|
98
|
+
f = _font(_BODY, 52)
|
|
99
|
+
f_num = _font(_SANS, 46)
|
|
100
|
+
n_steps = len(scene.steps)
|
|
101
|
+
box_h, gap = 150, 70
|
|
102
|
+
total_h = n_steps * box_h + (n_steps - 1) * gap
|
|
103
|
+
y = (card[1] + card[3]) // 2 - total_h // 2
|
|
104
|
+
for k, step in enumerate(scene.steps):
|
|
105
|
+
x0, x1 = 130, W - 130
|
|
106
|
+
d.rounded_rectangle((x0, y, x1, y + box_h), 36, fill=(255, 255, 255, 34), outline=(*accent, 230), width=3)
|
|
107
|
+
d.ellipse((x0 + 28, y + 35, x0 + 108, y + 115), fill=(*accent, 255))
|
|
108
|
+
d.text((x0 + 68, y + 76), str(k + 1), fill=(12, 12, 24), font=f_num, anchor="mm")
|
|
109
|
+
label_s = textwrap.shorten(step, 34, placeholder="...")
|
|
110
|
+
d.text((x0 + 140, y + 76), label_s, fill=(246, 247, 252), font=f, anchor="lm")
|
|
111
|
+
if k < n_steps - 1:
|
|
112
|
+
cx, ay = W // 2, y + box_h + 8
|
|
113
|
+
d.polygon([(cx - 22, ay), (cx + 22, ay), (cx, ay + gap - 16)], fill=(*accent, 255))
|
|
114
|
+
y += box_h + gap
|
|
115
|
+
else:
|
|
116
|
+
n = len(scene.text)
|
|
117
|
+
size = 84 if n < 60 else 72 if n < 110 else 60
|
|
118
|
+
f = _font(_BODY, size)
|
|
119
|
+
width = {84: 18, 72: 22, 60: 28}[size]
|
|
120
|
+
body = "\n".join(textwrap.wrap(scene.text, width))
|
|
121
|
+
box = d.multiline_textbbox((0, 0), body, font=f, spacing=size // 2)
|
|
122
|
+
y0 = (card[1] + card[3]) // 2 - (box[3] - box[1]) // 2
|
|
123
|
+
d.multiline_text((120, y0), body, fill=(246, 247, 252), font=f, spacing=size // 2)
|
|
124
|
+
|
|
125
|
+
# keyword chips
|
|
126
|
+
f_chip = _font(_SANS, 38)
|
|
127
|
+
x = 70
|
|
128
|
+
for k in scene.keywords[:4]:
|
|
129
|
+
label_k = f"#{k}"
|
|
130
|
+
cw = int(d.textlength(label_k, font=f_chip)) + 48
|
|
131
|
+
if x + cw > W - 70:
|
|
132
|
+
break
|
|
133
|
+
d.rounded_rectangle((x, H - 300, x + cw, H - 230), 35, fill=(255, 255, 255, 30), outline=(*accent, 200), width=2)
|
|
134
|
+
d.text((x + 24, H - 290), label_k, fill=(*accent, 255), font=f_chip)
|
|
135
|
+
x += cw + 18
|
|
136
|
+
|
|
137
|
+
# progress bar
|
|
138
|
+
d.rounded_rectangle((70, H - 130, W - 70, H - 112), 9, fill=(255, 255, 255, 40))
|
|
139
|
+
d.rounded_rectangle((70, H - 130, 70 + int((W - 140) * (index + 1) / total), H - 112), 9, fill=(*accent, 255))
|
|
140
|
+
img.save(path)
|
|
141
|
+
|
|
142
|
+
|
|
143
|
+
def scene_durations(scenes: list[Scene]) -> list[float]:
|
|
144
|
+
return [max(1.5, estimate_timings(s.text)[-1].end) for s in scenes]
|
|
145
|
+
|
|
146
|
+
|
|
147
|
+
def render(scenes: list[Scene], workdir: str | Path, out_name: str = "out.mp4", audio: bool = False,
|
|
148
|
+
align: bool = False, burn: bool = False, highlight: bool = True):
|
|
149
|
+
"""Render scenes to mp4 and captions. With audio=True, narrate offline via Kokoro and
|
|
150
|
+
time scenes and captions to the real clip lengths. align=True refines word times with a local
|
|
151
|
+
recognizer (faster-whisper); burn=True renders captions into the video, with each word
|
|
152
|
+
highlighted as it is spoken unless highlight=False. Returns (mp4, srt)."""
|
|
153
|
+
from .timing import spoken_form, to_ass, to_srt
|
|
154
|
+
|
|
155
|
+
work = Path(workdir).resolve()
|
|
156
|
+
work.mkdir(parents=True, exist_ok=True)
|
|
157
|
+
words, durs, wavs, t0 = [], [], [], 0.0
|
|
158
|
+
for i, sc in enumerate(scenes):
|
|
159
|
+
# code scenes are shown on screen, not read aloud verbatim
|
|
160
|
+
spoken = spoken_form("Here is some " + (sc.lang or "code") + "." if sc.kind == "code" else sc.text)
|
|
161
|
+
if audio:
|
|
162
|
+
from . import tts
|
|
163
|
+
|
|
164
|
+
wav = work / f"scene{i:03}.wav"
|
|
165
|
+
clip = tts.synth(spoken, wav)
|
|
166
|
+
wavs.append(wav.name)
|
|
167
|
+
dur = max(1.5, clip + 0.35)
|
|
168
|
+
ws = None
|
|
169
|
+
if align:
|
|
170
|
+
from . import align as aligner
|
|
171
|
+
|
|
172
|
+
ws = aligner.align(wav, spoken.split(), offset=t0)
|
|
173
|
+
words += ws or tts.calibrated_words(spoken, clip, offset=t0)
|
|
174
|
+
else:
|
|
175
|
+
ws = estimate_timings(spoken, offset=t0)
|
|
176
|
+
dur = max(1.5, ws[-1].end - t0)
|
|
177
|
+
words += ws
|
|
178
|
+
durs.append(dur)
|
|
179
|
+
t0 += dur
|
|
180
|
+
lines = []
|
|
181
|
+
for i, (sc, dur) in enumerate(zip(scenes, durs)):
|
|
182
|
+
name = f"scene{i:03}.png"
|
|
183
|
+
draw_scene(sc, work / name, i, len(scenes))
|
|
184
|
+
lines += [f"file '{name}'", f"duration {dur:.3f}"]
|
|
185
|
+
lines.append(f"file 'scene{len(scenes) - 1:03}.png'")
|
|
186
|
+
(work / "list.txt").write_text("\n".join(lines) + "\n", encoding="utf-8")
|
|
187
|
+
cmd = ["ffmpeg", "-hide_banner", "-nostdin", "-y", "-protocol_whitelist", "file",
|
|
188
|
+
"-f", "concat", "-safe", "0", "-i", str(work / "list.txt")]
|
|
189
|
+
if audio:
|
|
190
|
+
alines = []
|
|
191
|
+
for wav, dur in zip(wavs, durs):
|
|
192
|
+
alines += [f"file '{wav}'", f"duration {dur:.3f}"]
|
|
193
|
+
(work / "alist.txt").write_text("\n".join(alines) + "\n", encoding="utf-8")
|
|
194
|
+
cmd += ["-protocol_whitelist", "file", "-f", "concat", "-safe", "0", "-i", str(work / "alist.txt"),
|
|
195
|
+
"-c:a", "aac", "-shortest"]
|
|
196
|
+
srt = work / "captions.srt"
|
|
197
|
+
srt.write_text(to_srt(words), encoding="utf-8")
|
|
198
|
+
vf = "format=yuv420p"
|
|
199
|
+
if burn and highlight:
|
|
200
|
+
# per-word karaoke fill; relative name + cwd=work keeps ffmpeg inside the workdir
|
|
201
|
+
(work / "captions.ass").write_text(to_ass(words), encoding="utf-8")
|
|
202
|
+
# fps first: scene images arrive as one frame per scene, and subtitles are only drawn on
|
|
203
|
+
# frames the filter actually receives, so without this they would freeze for a whole scene
|
|
204
|
+
vf = "fps=30,ass=captions.ass,format=yuv420p"
|
|
205
|
+
elif burn:
|
|
206
|
+
style = "FontName=Segoe UI,Bold=1,Fontsize=9,Outline=1,Shadow=0,MarginV=60,Alignment=2"
|
|
207
|
+
vf = f"fps=30,subtitles=captions.srt:original_size=1080x1920:force_style='{style}',format=yuv420p"
|
|
208
|
+
cmd += ["-vf", vf, "-r", "30", out_name]
|
|
209
|
+
run(cmd, cwd=work)
|
|
210
|
+
return work / out_name, srt
|
tokenreel/safe_ffmpeg.py
ADDED
|
@@ -0,0 +1,42 @@
|
|
|
1
|
+
"""Hardened ffmpeg invocation.
|
|
2
|
+
|
|
3
|
+
Mitigates the playlist-demuxer SSRF and local-file-read class of bugs
|
|
4
|
+
(for example CVE-2023-6605 in the DASH demuxer) by never passing untrusted
|
|
5
|
+
URLs to ffmpeg, restricting protocols to `file`, and confining paths to a
|
|
6
|
+
working directory. Run inside a container or gVisor for defense in depth.
|
|
7
|
+
"""
|
|
8
|
+
from __future__ import annotations
|
|
9
|
+
|
|
10
|
+
import subprocess
|
|
11
|
+
from pathlib import Path
|
|
12
|
+
|
|
13
|
+
ALLOWED_SUFFIX = {".png", ".jpg", ".jpeg", ".wav", ".mp3", ".mp4", ".srt", ".vtt"}
|
|
14
|
+
|
|
15
|
+
|
|
16
|
+
class UnsafePath(ValueError):
|
|
17
|
+
pass
|
|
18
|
+
|
|
19
|
+
|
|
20
|
+
def confine(path: str | Path, root: str | Path) -> Path:
|
|
21
|
+
"""Resolve path and require it to live under root (blocks traversal and symlink escape)."""
|
|
22
|
+
root_p = Path(root).resolve()
|
|
23
|
+
p = (root_p / path).resolve() if not Path(path).is_absolute() else Path(path).resolve()
|
|
24
|
+
if root_p != p and root_p not in p.parents:
|
|
25
|
+
raise UnsafePath(f"path escapes workdir: {path}")
|
|
26
|
+
if p.suffix.lower() not in ALLOWED_SUFFIX:
|
|
27
|
+
raise UnsafePath(f"file type not allowed: {p.suffix}")
|
|
28
|
+
return p
|
|
29
|
+
|
|
30
|
+
|
|
31
|
+
def build_cmd(inputs: list[str | Path], output: str | Path, root: str | Path, extra: list[str] | None = None) -> list[str]:
|
|
32
|
+
cmd = ["ffmpeg", "-hide_banner", "-nostdin", "-y"]
|
|
33
|
+
for i in inputs:
|
|
34
|
+
cmd += ["-protocol_whitelist", "file", "-i", str(confine(i, root))]
|
|
35
|
+
cmd += list(extra or [])
|
|
36
|
+
cmd.append(str(confine(output, root)))
|
|
37
|
+
return cmd
|
|
38
|
+
|
|
39
|
+
|
|
40
|
+
def run(cmd: list[str], timeout: int = 300, cwd: str | Path | None = None) -> subprocess.CompletedProcess:
|
|
41
|
+
# list args, no shell, hard timeout
|
|
42
|
+
return subprocess.run(cmd, check=True, capture_output=True, timeout=timeout, shell=False, cwd=cwd)
|
tokenreel/segment.py
ADDED
|
@@ -0,0 +1,89 @@
|
|
|
1
|
+
"""Scene planning: split text into scenes and tag each with a visual kind.
|
|
2
|
+
|
|
3
|
+
Pure stdlib so the core installs with zero dependencies. spaCy is an optional
|
|
4
|
+
upgrade for better sentence and entity handling (extra: nlp).
|
|
5
|
+
"""
|
|
6
|
+
from __future__ import annotations
|
|
7
|
+
|
|
8
|
+
import re
|
|
9
|
+
from collections import Counter
|
|
10
|
+
from dataclasses import dataclass, field
|
|
11
|
+
|
|
12
|
+
_FENCE = re.compile(r"```(\w*)\n(.*?)```", re.DOTALL)
|
|
13
|
+
_SENT = re.compile(r"(?<=[.!?])\s+(?=[A-Z0-9])")
|
|
14
|
+
_WORD = re.compile(r"[A-Za-z][A-Za-z0-9_\-]{2,}")
|
|
15
|
+
_STOP = frozenset(
|
|
16
|
+
["the", "and", "for", "with", "that", "this", "from", "are", "was", "were", "has", "have", "had", "not", "but", "you", "your", "can", "will", "into", "over", "then", "than", "its", "it's", "their", "there", "which", "when", "what", "how", "why"]
|
|
17
|
+
)
|
|
18
|
+
_MATH = re.compile(r"[=^∑∫√]|\\frac|\b\d+\s*[*/+\-]\s*\d+")
|
|
19
|
+
_FLOW = re.compile(r"\b(then|next|after that|finally|first|second|step \d+)\b", re.IGNORECASE)
|
|
20
|
+
|
|
21
|
+
|
|
22
|
+
@dataclass
|
|
23
|
+
class Scene:
|
|
24
|
+
kind: str # "code" | "math" | "flow" | "text"
|
|
25
|
+
text: str
|
|
26
|
+
keywords: list[str] = field(default_factory=list)
|
|
27
|
+
lang: str = ""
|
|
28
|
+
steps: list[str] = field(default_factory=list)
|
|
29
|
+
|
|
30
|
+
|
|
31
|
+
def keywords(text: str, k: int = 4) -> list[str]:
|
|
32
|
+
counts = Counter(w.lower() for w in _WORD.findall(text) if w.lower() not in _STOP)
|
|
33
|
+
return [w for w, _ in counts.most_common(k)]
|
|
34
|
+
|
|
35
|
+
|
|
36
|
+
def _kind(sentence: str) -> str:
|
|
37
|
+
if _MATH.search(sentence):
|
|
38
|
+
return "math"
|
|
39
|
+
if _FLOW.search(sentence):
|
|
40
|
+
return "flow"
|
|
41
|
+
return "text"
|
|
42
|
+
|
|
43
|
+
|
|
44
|
+
def plan(text: str, max_chars: int = 220) -> list[Scene]:
|
|
45
|
+
"""Split text into scenes. Fenced code blocks become code scenes."""
|
|
46
|
+
scenes: list[Scene] = []
|
|
47
|
+
pos = 0
|
|
48
|
+
for m in _FENCE.finditer(text):
|
|
49
|
+
scenes += _prose(text[pos : m.start()], max_chars)
|
|
50
|
+
scenes.append(Scene("code", m.group(2).rstrip(), keywords(m.group(2)), m.group(1)))
|
|
51
|
+
pos = m.end()
|
|
52
|
+
scenes += _prose(text[pos:], max_chars)
|
|
53
|
+
return scenes
|
|
54
|
+
|
|
55
|
+
|
|
56
|
+
def _make(kind: str, text: str) -> Scene:
|
|
57
|
+
return Scene(kind, text, keywords(text), steps=steps(text) if kind == "flow" else [])
|
|
58
|
+
|
|
59
|
+
|
|
60
|
+
def _prose(chunk: str, max_chars: int) -> list[Scene]:
|
|
61
|
+
"""Group consecutive sentences of the same kind, capped at max_chars."""
|
|
62
|
+
out: list[Scene] = []
|
|
63
|
+
buf, kind = "", ""
|
|
64
|
+
for s in (x.strip() for x in _SENT.split(" ".join(chunk.split()))):
|
|
65
|
+
if not s:
|
|
66
|
+
continue
|
|
67
|
+
k = _kind(s)
|
|
68
|
+
if buf and (k != kind or len(buf) + len(s) + 1 > max_chars):
|
|
69
|
+
out.append(_make(kind, buf))
|
|
70
|
+
buf = ""
|
|
71
|
+
buf = f"{buf} {s}".strip()
|
|
72
|
+
kind = k
|
|
73
|
+
if buf:
|
|
74
|
+
out.append(_make(kind, buf))
|
|
75
|
+
return out
|
|
76
|
+
|
|
77
|
+
|
|
78
|
+
_LEAD = re.compile(r"^(first(ly)?|second(ly)?|third(ly)?|then|next|after that|finally|lastly|step \d+)[,:]?\s+", re.IGNORECASE)
|
|
79
|
+
|
|
80
|
+
|
|
81
|
+
def steps(text: str, max_steps: int = 5) -> list[str]:
|
|
82
|
+
"""Split a flow scene into short step labels, dropping leading connectors."""
|
|
83
|
+
out = []
|
|
84
|
+
for sent in _SENT.split(text):
|
|
85
|
+
sent = _LEAD.sub("", sent.strip()).rstrip(".!?")
|
|
86
|
+
if sent:
|
|
87
|
+
out.append(sent[0].upper() + sent[1:])
|
|
88
|
+
return out[:max_steps]
|
|
89
|
+
|
tokenreel/telemetry.py
ADDED
|
@@ -0,0 +1,39 @@
|
|
|
1
|
+
"""Opt-in, anonymous usage ping. OFF by default.
|
|
2
|
+
|
|
3
|
+
Enabled only when TOKENREEL_TELEMETRY=1 AND TOKENREEL_TELEMETRY_URL is set.
|
|
4
|
+
Sends no text, paths, hostnames, IPs we control, or identifiers. See TELEMETRY.md.
|
|
5
|
+
"""
|
|
6
|
+
from __future__ import annotations
|
|
7
|
+
|
|
8
|
+
import json
|
|
9
|
+
import os
|
|
10
|
+
import platform
|
|
11
|
+
import urllib.request
|
|
12
|
+
|
|
13
|
+
from . import __version__
|
|
14
|
+
|
|
15
|
+
|
|
16
|
+
def payload() -> dict:
|
|
17
|
+
return {
|
|
18
|
+
"v": __version__,
|
|
19
|
+
"os": platform.system(),
|
|
20
|
+
"py": platform.python_version().rsplit(".", 1)[0],
|
|
21
|
+
}
|
|
22
|
+
|
|
23
|
+
|
|
24
|
+
def enabled() -> bool:
|
|
25
|
+
return os.environ.get("TOKENREEL_TELEMETRY") == "1" and bool(os.environ.get("TOKENREEL_TELEMETRY_URL"))
|
|
26
|
+
|
|
27
|
+
|
|
28
|
+
def ping() -> bool:
|
|
29
|
+
if not enabled() or os.environ.get("DO_NOT_TRACK") == "1":
|
|
30
|
+
return False
|
|
31
|
+
url = os.environ["TOKENREEL_TELEMETRY_URL"]
|
|
32
|
+
if not url.startswith("https://"):
|
|
33
|
+
return False
|
|
34
|
+
req = urllib.request.Request(url, json.dumps(payload()).encode(), {"Content-Type": "application/json"})
|
|
35
|
+
try:
|
|
36
|
+
urllib.request.urlopen(req, timeout=3).close()
|
|
37
|
+
return True
|
|
38
|
+
except Exception: # noqa: BLE001 - telemetry must never break the tool
|
|
39
|
+
return False
|
tokenreel/timing.py
ADDED
|
@@ -0,0 +1,107 @@
|
|
|
1
|
+
"""Word timings and captions.
|
|
2
|
+
|
|
3
|
+
A TTS or aligner backend supplies real word timings as a list of (word, start, end).
|
|
4
|
+
Without one, estimate_timings() spreads time over words by character weight so the
|
|
5
|
+
pipeline still works offline with no audio (silent preview renders).
|
|
6
|
+
"""
|
|
7
|
+
from __future__ import annotations
|
|
8
|
+
|
|
9
|
+
import re
|
|
10
|
+
from dataclasses import dataclass
|
|
11
|
+
|
|
12
|
+
CHARS_PER_SEC = 15.0 # roughly 180 wpm
|
|
13
|
+
|
|
14
|
+
|
|
15
|
+
@dataclass
|
|
16
|
+
class Word:
|
|
17
|
+
text: str
|
|
18
|
+
start: float
|
|
19
|
+
end: float
|
|
20
|
+
|
|
21
|
+
|
|
22
|
+
def spoken_form(text: str) -> str:
|
|
23
|
+
"""Make text alignable: aligners give no timing to bare digits and symbols."""
|
|
24
|
+
reps = {"=": " equals ", "+": " plus ", "/": " over ", "^": " to the power of ", "%": " percent "}
|
|
25
|
+
for k, v in reps.items():
|
|
26
|
+
text = text.replace(k, v)
|
|
27
|
+
ones = ["zero", "one", "two", "three", "four", "five", "six", "seven", "eight", "nine"]
|
|
28
|
+
text = re.sub(r"\d", lambda m: f" {ones[int(m.group())]} ", text)
|
|
29
|
+
return " ".join(text.split())
|
|
30
|
+
|
|
31
|
+
|
|
32
|
+
def estimate_timings(text: str, offset: float = 0.0, cps: float = CHARS_PER_SEC) -> list[Word]:
|
|
33
|
+
words = spoken_form(text).split()
|
|
34
|
+
t = offset
|
|
35
|
+
out: list[Word] = []
|
|
36
|
+
for w in words:
|
|
37
|
+
d = max(0.18, (len(w) + 1) / cps)
|
|
38
|
+
out.append(Word(w, round(t, 3), round(t + d, 3)))
|
|
39
|
+
t += d
|
|
40
|
+
return out
|
|
41
|
+
|
|
42
|
+
|
|
43
|
+
def _ts(x: float) -> str:
|
|
44
|
+
ms = round(x * 1000)
|
|
45
|
+
h, ms = divmod(ms, 3_600_000)
|
|
46
|
+
m, ms = divmod(ms, 60_000)
|
|
47
|
+
s, ms = divmod(ms, 1000)
|
|
48
|
+
return f"{h:02}:{m:02}:{s:02},{ms:03}"
|
|
49
|
+
|
|
50
|
+
|
|
51
|
+
def _ass_ts(x: float) -> str:
|
|
52
|
+
cs = round(x * 100)
|
|
53
|
+
h, cs = divmod(cs, 360_000)
|
|
54
|
+
m, cs = divmod(cs, 6_000)
|
|
55
|
+
s, cs = divmod(cs, 100)
|
|
56
|
+
return f"{h}:{m:02}:{s:02}.{cs:02}"
|
|
57
|
+
|
|
58
|
+
|
|
59
|
+
_ASS_HEAD = """[Script Info]
|
|
60
|
+
ScriptType: v4.00+
|
|
61
|
+
PlayResX: 1080
|
|
62
|
+
PlayResY: 1920
|
|
63
|
+
WrapStyle: 2
|
|
64
|
+
ScaledBorderAndShadow: yes
|
|
65
|
+
|
|
66
|
+
[V4+ Styles]
|
|
67
|
+
Format: Name, Fontname, Fontsize, PrimaryColour, SecondaryColour, OutlineColour, BackColour, Bold, Italic, Underline, StrikeOut, ScaleX, ScaleY, Spacing, Angle, BorderStyle, Outline, Shadow, Alignment, MarginL, MarginR, MarginV, Encoding
|
|
68
|
+
Style: Karaoke,{font},{size},{done},{todo},&H00000000,&H64000000,1,0,0,0,100,100,0,0,1,5,0,2,80,80,{margin},1
|
|
69
|
+
|
|
70
|
+
[Events]
|
|
71
|
+
Format: Layer, Start, End, Style, Name, MarginL, MarginR, MarginV, Effect, Text
|
|
72
|
+
"""
|
|
73
|
+
|
|
74
|
+
|
|
75
|
+
def to_ass(
|
|
76
|
+
words: list[Word],
|
|
77
|
+
per_cue: int = 4,
|
|
78
|
+
font: str = "Segoe UI",
|
|
79
|
+
size: int = 64,
|
|
80
|
+
margin_v: int = 400,
|
|
81
|
+
done: str = "&H0024BFFB",
|
|
82
|
+
todo: str = "&H00FFFFFF",
|
|
83
|
+
) -> str:
|
|
84
|
+
"""Karaoke captions: each word fills with the `done` colour (ASS is BGR, default amber)
|
|
85
|
+
exactly while it is spoken. Positions are real pixels on a 1080x1920 canvas."""
|
|
86
|
+
out = [_ASS_HEAD.format(font=font, size=size, margin=margin_v, done=done, todo=todo)]
|
|
87
|
+
for i in range(0, len(words), per_cue):
|
|
88
|
+
chunk = words[i : i + per_cue]
|
|
89
|
+
start = chunk[0].start
|
|
90
|
+
parts = []
|
|
91
|
+
for k, w in enumerate(chunk):
|
|
92
|
+
nxt = chunk[k + 1].start if k + 1 < len(chunk) else w.end
|
|
93
|
+
# centiseconds from cumulative rounding so a cue never drifts from its end time
|
|
94
|
+
cs = round((nxt - start) * 100) - round((w.start - start) * 100)
|
|
95
|
+
clean = w.text.replace("\\", "").replace("{", "").replace("}", "")
|
|
96
|
+
parts.append("{\\kf" + str(max(1, cs)) + "}" + clean)
|
|
97
|
+
text = " ".join(parts)
|
|
98
|
+
out.append(f"Dialogue: 0,{_ass_ts(start)},{_ass_ts(chunk[-1].end)},Karaoke,,0,0,0,,{text}\n")
|
|
99
|
+
return "".join(out)
|
|
100
|
+
|
|
101
|
+
|
|
102
|
+
def to_srt(words: list[Word], per_cue: int = 4) -> str:
|
|
103
|
+
cues = []
|
|
104
|
+
for n, i in enumerate(range(0, len(words), per_cue), 1):
|
|
105
|
+
chunk = words[i : i + per_cue]
|
|
106
|
+
cues.append(f"{n}\n{_ts(chunk[0].start)} --> {_ts(chunk[-1].end)}\n{' '.join(w.text for w in chunk)}\n")
|
|
107
|
+
return "\n".join(cues)
|
tokenreel/tts.py
ADDED
|
@@ -0,0 +1,49 @@
|
|
|
1
|
+
"""Local, offline TTS through kokoro-onnx (extra: tts). No text leaves the machine.
|
|
2
|
+
|
|
3
|
+
kokoro-onnx on PyPI (0.4.7 at time of writing) returns audio only, no word timings, so
|
|
4
|
+
timings are calibrated: the estimated word weights are scaled to the true clip length.
|
|
5
|
+
That keeps captions in step with the audio per scene. For exact word times, run a forced
|
|
6
|
+
aligner (WhisperX, extra: align) on the wav and pass its words to to_srt().
|
|
7
|
+
|
|
8
|
+
Model files (about 350 MB) are downloaded by the user, never fetched silently:
|
|
9
|
+
kokoro-v1.0.onnx and voices-v1.0.bin from the kokoro-onnx model-files-v1.0 release.
|
|
10
|
+
"""
|
|
11
|
+
from __future__ import annotations
|
|
12
|
+
|
|
13
|
+
import os
|
|
14
|
+
from pathlib import Path
|
|
15
|
+
|
|
16
|
+
from .timing import Word, estimate_timings
|
|
17
|
+
|
|
18
|
+
MODEL_DIR = Path(os.environ.get("TOKENREEL_MODELS", Path.home() / ".tokenreel" / "models"))
|
|
19
|
+
_engine = None
|
|
20
|
+
|
|
21
|
+
|
|
22
|
+
def available() -> bool:
|
|
23
|
+
return (MODEL_DIR / "kokoro-v1.0.onnx").exists() and (MODEL_DIR / "voices-v1.0.bin").exists()
|
|
24
|
+
|
|
25
|
+
|
|
26
|
+
def _kokoro():
|
|
27
|
+
global _engine
|
|
28
|
+
if _engine is None:
|
|
29
|
+
from kokoro_onnx import Kokoro # lazy: optional dependency
|
|
30
|
+
|
|
31
|
+
_engine = Kokoro(str(MODEL_DIR / "kokoro-v1.0.onnx"), str(MODEL_DIR / "voices-v1.0.bin"))
|
|
32
|
+
return _engine
|
|
33
|
+
|
|
34
|
+
|
|
35
|
+
def synth(spoken_text: str, out_wav: Path, voice: str = "af_heart", speed: float = 1.0) -> float:
|
|
36
|
+
"""Write a wav, return its duration in seconds."""
|
|
37
|
+
import soundfile as sf
|
|
38
|
+
|
|
39
|
+
samples, rate = _kokoro().create(spoken_text, voice=voice, speed=speed, lang="en-us")
|
|
40
|
+
sf.write(str(out_wav), samples, rate)
|
|
41
|
+
return len(samples) / rate
|
|
42
|
+
|
|
43
|
+
|
|
44
|
+
def calibrated_words(spoken_text: str, duration: float, offset: float = 0.0) -> list[Word]:
|
|
45
|
+
words = estimate_timings(spoken_text)
|
|
46
|
+
if not words:
|
|
47
|
+
return []
|
|
48
|
+
scale = duration / words[-1].end
|
|
49
|
+
return [Word(w.text, round(offset + w.start * scale, 3), round(offset + w.end * scale, 3)) for w in words]
|
|
@@ -0,0 +1,180 @@
|
|
|
1
|
+
Metadata-Version: 2.5
|
|
2
|
+
Name: tokenreel
|
|
3
|
+
Version: 0.2.0
|
|
4
|
+
Summary: Turn plain text and technical content into animated, captioned short videos. Offline-first, secure by default.
|
|
5
|
+
Author: Sunil Gentyala
|
|
6
|
+
License: Apache-2.0
|
|
7
|
+
License-File: LICENSE
|
|
8
|
+
Requires-Python: >=3.10
|
|
9
|
+
Provides-Extra: align
|
|
10
|
+
Requires-Dist: faster-whisper>=1.0; extra == 'align'
|
|
11
|
+
Requires-Dist: numpy; extra == 'align'
|
|
12
|
+
Requires-Dist: soundfile; extra == 'align'
|
|
13
|
+
Provides-Extra: dev
|
|
14
|
+
Requires-Dist: mcp>=1.2; extra == 'dev'
|
|
15
|
+
Requires-Dist: pillow>=10; extra == 'dev'
|
|
16
|
+
Requires-Dist: pytest>=8; extra == 'dev'
|
|
17
|
+
Requires-Dist: ruff>=0.6; extra == 'dev'
|
|
18
|
+
Provides-Extra: mcp
|
|
19
|
+
Requires-Dist: mcp>=1.2; extra == 'mcp'
|
|
20
|
+
Requires-Dist: pillow>=10; extra == 'mcp'
|
|
21
|
+
Provides-Extra: nlp
|
|
22
|
+
Requires-Dist: spacy>=3.7; extra == 'nlp'
|
|
23
|
+
Provides-Extra: render
|
|
24
|
+
Requires-Dist: pillow>=10; extra == 'render'
|
|
25
|
+
Provides-Extra: tts
|
|
26
|
+
Requires-Dist: kokoro-onnx>=0.4.7; extra == 'tts'
|
|
27
|
+
Requires-Dist: soundfile; extra == 'tts'
|
|
28
|
+
Description-Content-Type: text/markdown
|
|
29
|
+
|
|
30
|
+
<div align="center">
|
|
31
|
+
|
|
32
|
+
# TokenReel
|
|
33
|
+
|
|
34
|
+
**Turn plain text and technical content into animated, narrated, captioned short videos.**
|
|
35
|
+
Offline-first. No watermark. No cloud TTS. Secure by default.
|
|
36
|
+
|
|
37
|
+
[](https://github.com/sunilgentyala/tokenreel/actions/workflows/ci.yml)
|
|
38
|
+

|
|
39
|
+

|
|
40
|
+
|
|
41
|
+
<img src="assets/demo.gif" alt="TokenReel demo: text, flow, math and code scenes with burned-in captions" width="270">
|
|
42
|
+
|
|
43
|
+
</div>
|
|
44
|
+
|
|
45
|
+
## What it does
|
|
46
|
+
|
|
47
|
+
Give it Markdown or plain text. TokenReel plans the scenes with NLP, then draws, narrates and
|
|
48
|
+
captions them for Shorts and Reels (1080x1920).
|
|
49
|
+
|
|
50
|
+
| Your text | Scene it becomes |
|
|
51
|
+
|---|---|
|
|
52
|
+
| Prose | **Explainer** card with keyword chips |
|
|
53
|
+
| "First ... Then ... Finally ..." | **Flow** diagram with numbered steps and arrows |
|
|
54
|
+
| Equations and numbers (`x = n / m`, `O(1)`) | **Math** card, spoken as words ("n over m") |
|
|
55
|
+
| Fenced code blocks | **Code** panel with line numbers and syntax colors |
|
|
56
|
+
|
|
57
|
+
## Why another video generator
|
|
58
|
+
|
|
59
|
+
The popular free tools compose stock footage from a topic. They do not animate code, flows or
|
|
60
|
+
math, and caption tooling often defaults to cloud TTS that sends your script elsewhere.
|
|
61
|
+
TokenReel keeps everything on your machine and is built for technical explainers.
|
|
62
|
+
|
|
63
|
+
## Quick start
|
|
64
|
+
|
|
65
|
+
```bash
|
|
66
|
+
pip install -e ".[dev]"
|
|
67
|
+
tokenreel plan examples/demo.md # scene plan as JSON, no extras needed
|
|
68
|
+
tokenreel srt examples/demo.md # estimated captions
|
|
69
|
+
```
|
|
70
|
+
|
|
71
|
+
Silent preview video (needs [ffmpeg](https://ffmpeg.org) on PATH and the `render` extra):
|
|
72
|
+
|
|
73
|
+
```bash
|
|
74
|
+
pip install -e ".[render]"
|
|
75
|
+
tokenreel render examples/demo.md
|
|
76
|
+
```
|
|
77
|
+
|
|
78
|
+
Narrated video with captions burned in, each word highlighted as it is spoken
|
|
79
|
+
(`--plain-captions` for static captions):
|
|
80
|
+
|
|
81
|
+
```bash
|
|
82
|
+
pip install -e ".[render,tts,align]"
|
|
83
|
+
# download kokoro-v1.0.onnx and voices-v1.0.bin (about 350 MB) from the
|
|
84
|
+
# kokoro-onnx "model-files-v1.0" release into ~/.tokenreel/models
|
|
85
|
+
tokenreel render examples/demo.md --audio --align --burn
|
|
86
|
+
```
|
|
87
|
+
|
|
88
|
+
Output goes to `build/` as `out.mp4` and `captions.srt`.
|
|
89
|
+
|
|
90
|
+
## Use it from an AI agent (MCP)
|
|
91
|
+
|
|
92
|
+
TokenReel ships an [MCP](https://modelcontextprotocol.io) server, `tokenreel-mcp`, so an agent
|
|
93
|
+
can plan and render videos for you. It runs locally over stdio.
|
|
94
|
+
|
|
95
|
+
```bash
|
|
96
|
+
pip install -e ".[mcp,render]"
|
|
97
|
+
claude mcp add tokenreel -- tokenreel-mcp # Claude Code
|
|
98
|
+
```
|
|
99
|
+
|
|
100
|
+
Or in any MCP client config:
|
|
101
|
+
|
|
102
|
+
```json
|
|
103
|
+
{ "mcpServers": { "tokenreel": { "command": "tokenreel-mcp" } } }
|
|
104
|
+
```
|
|
105
|
+
|
|
106
|
+
| Tool | What it does |
|
|
107
|
+
|---|---|
|
|
108
|
+
| `plan_scenes` | Split text into scenes (text, flow, math, code) with keywords and flow steps |
|
|
109
|
+
| `make_captions` | Estimated SRT captions |
|
|
110
|
+
| `render_video` | Render an mp4 plus captions, optionally narrated, aligned and burned in |
|
|
111
|
+
|
|
112
|
+
Safety: the client never passes file paths. Output goes to `TOKENREEL_OUT` (default
|
|
113
|
+
`~/tokenreel-output`), one new folder per render, with a restricted file name. Input size and
|
|
114
|
+
scene count are capped.
|
|
115
|
+
|
|
116
|
+
### Sandboxed, fully offline (container)
|
|
117
|
+
|
|
118
|
+
Two images are published to GHCR:
|
|
119
|
+
|
|
120
|
+
| Image | Can do |
|
|
121
|
+
|---|---|
|
|
122
|
+
| `ghcr.io/sunilgentyala/tokenreel:latest` | plan, captions, silent renders |
|
|
123
|
+
| `ghcr.io/sunilgentyala/tokenreel:narrate` | everything, including narration, exact timings and burned captions (1.6 GB) |
|
|
124
|
+
|
|
125
|
+
The narration image has the small English recognizer baked in. The voice model
|
|
126
|
+
(`kokoro-v1.0.onnx`, `voices-v1.0.bin`, about 350 MB, see the quick start) is mounted, not baked:
|
|
127
|
+
|
|
128
|
+
```bash
|
|
129
|
+
claude mcp add tokenreel-sandbox -- docker run -i --rm --network none \
|
|
130
|
+
-v ~/.tokenreel/models:/home/reel/.tokenreel/models:ro \
|
|
131
|
+
-v ~/tokenreel-output:/home/reel/out \
|
|
132
|
+
ghcr.io/sunilgentyala/tokenreel:narrate
|
|
133
|
+
```
|
|
134
|
+
|
|
135
|
+
`--network none` works: nothing needs the network at run time. Paths returned by
|
|
136
|
+
`render_video` are inside the container, so use `video_relative` and `captions_relative`
|
|
137
|
+
(relative to the mounted output folder).
|
|
138
|
+
|
|
139
|
+
## How it works
|
|
140
|
+
|
|
141
|
+
```
|
|
142
|
+
text / Markdown
|
|
143
|
+
-> sentence + scene segmentation (code, math, flow, text) and keywords
|
|
144
|
+
-> spoken-form normalization (digits and symbols become words)
|
|
145
|
+
-> local TTS (kokoro-onnx)
|
|
146
|
+
-> word timings (faster-whisper, local; or a calibrated estimate)
|
|
147
|
+
-> frames (Pillow) -> hardened ffmpeg -> mp4 + srt
|
|
148
|
+
```
|
|
149
|
+
|
|
150
|
+
Word-level timing matters because aligners give no time to bare digits or symbols, so
|
|
151
|
+
narration text is normalized to spoken words before alignment. When the recognizer hears a
|
|
152
|
+
different number of words than the script, its words are used for the captions as-is.
|
|
153
|
+
|
|
154
|
+
## Security and privacy
|
|
155
|
+
|
|
156
|
+
- Untrusted input is treated as hostile: paths are confined to a working directory, file
|
|
157
|
+
types are allow-listed, ffmpeg runs with list arguments, `-protocol_whitelist file` and a
|
|
158
|
+
timeout, and untrusted URLs never reach ffmpeg (see CVE-2023-6605 for why).
|
|
159
|
+
- Run rendering in a container, ideally with gVisor, with no network and resource limits.
|
|
160
|
+
- Releases ship a CycloneDX SBOM, build provenance attestations and Sigstore signatures.
|
|
161
|
+
- Telemetry is off by default and opt-in only. See [TELEMETRY.md](TELEMETRY.md).
|
|
162
|
+
- Report vulnerabilities privately. See [SECURITY.md](SECURITY.md).
|
|
163
|
+
|
|
164
|
+
## Design notes
|
|
165
|
+
|
|
166
|
+
- Rendering is our own frame generator plus ffmpeg, not Remotion. Remotion's license requires
|
|
167
|
+
a paid company license for larger organizations, which would burden operators of a
|
|
168
|
+
self-hosted tool.
|
|
169
|
+
- The core installs with zero dependencies. NLP, TTS, alignment and rendering are optional
|
|
170
|
+
extras.
|
|
171
|
+
|
|
172
|
+
## Status and roadmap
|
|
173
|
+
|
|
174
|
+
Early alpha. Done: scene planning, flow diagrams, offline narration, exact word
|
|
175
|
+
timings, burned-in captions with per-word highlighting. Next: math typesetting, architecture
|
|
176
|
+
diagrams, more voices and languages, a 16:9 layout.
|
|
177
|
+
|
|
178
|
+
## License
|
|
179
|
+
|
|
180
|
+
Apache-2.0. See [LICENSE](LICENSE).
|
|
@@ -0,0 +1,15 @@
|
|
|
1
|
+
tokenreel/__init__.py,sha256=Zn1KFblwuFHiDRdRAiRnDBRkbPttWh44jKa5zG2ov0E,22
|
|
2
|
+
tokenreel/align.py,sha256=eKhqnM3ChiXldPDanp2a0_6bON_EBjO4jKzLLH2RStg,1938
|
|
3
|
+
tokenreel/cli.py,sha256=DDPuSt4Qg3VA54dEEVvPROgUfjW5eQYbMIjjMZiAW80,1899
|
|
4
|
+
tokenreel/mcp_server.py,sha256=ZJA5yMSCCfMqXsxONEOPyGdyHu4f8-nat-4kihgSofI,5476
|
|
5
|
+
tokenreel/render.py,sha256=MvnIaRLmZtb9htqHQyZK3ima4U_xHOlLgp90YhJrGWc,9220
|
|
6
|
+
tokenreel/safe_ffmpeg.py,sha256=P2W3RnxYC9sDW7fKMcWCCun4SeEoZ3PivRL_s6jqBkA,1660
|
|
7
|
+
tokenreel/segment.py,sha256=m-HxiCrvseacGcu_hGUnVN2CE_aLULXHOobJ8CLDHFE,3098
|
|
8
|
+
tokenreel/telemetry.py,sha256=tLVBHq2AupGIvRfclwZnyDCjnOdjGR93jyIFGNvq9WU,1134
|
|
9
|
+
tokenreel/timing.py,sha256=Y_rGmu5BtJt4wzcvX-CbzUzD3XkPsP4zvbQbIkd37gE,3717
|
|
10
|
+
tokenreel/tts.py,sha256=bZbTcHO762l2LddqwrJ6PRJmapcXcseioBu_tMzqSw8,1854
|
|
11
|
+
tokenreel-0.2.0.dist-info/METADATA,sha256=ui_3GW5oxwBnxxeF69YGUR37SpcU5VqKz3c-n1Pn7mY,6804
|
|
12
|
+
tokenreel-0.2.0.dist-info/WHEEL,sha256=2iZrJkDIkeDh0k9SikKMqFuRP-ua6mb4Ir1AsER4BEw,87
|
|
13
|
+
tokenreel-0.2.0.dist-info/entry_points.txt,sha256=yAF6cI0yAbwT1LMDDX-Uz5U6VKy3cvNuNWnLJJWJnPs,91
|
|
14
|
+
tokenreel-0.2.0.dist-info/licenses/LICENSE,sha256=z8d0m5b2O9McPEK1xHG_dWgUBT6EfBDz6wA0F7xSPTA,11358
|
|
15
|
+
tokenreel-0.2.0.dist-info/RECORD,,
|
|
@@ -0,0 +1,202 @@
|
|
|
1
|
+
|
|
2
|
+
Apache License
|
|
3
|
+
Version 2.0, January 2004
|
|
4
|
+
http://www.apache.org/licenses/
|
|
5
|
+
|
|
6
|
+
TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
|
|
7
|
+
|
|
8
|
+
1. Definitions.
|
|
9
|
+
|
|
10
|
+
"License" shall mean the terms and conditions for use, reproduction,
|
|
11
|
+
and distribution as defined by Sections 1 through 9 of this document.
|
|
12
|
+
|
|
13
|
+
"Licensor" shall mean the copyright owner or entity authorized by
|
|
14
|
+
the copyright owner that is granting the License.
|
|
15
|
+
|
|
16
|
+
"Legal Entity" shall mean the union of the acting entity and all
|
|
17
|
+
other entities that control, are controlled by, or are under common
|
|
18
|
+
control with that entity. For the purposes of this definition,
|
|
19
|
+
"control" means (i) the power, direct or indirect, to cause the
|
|
20
|
+
direction or management of such entity, whether by contract or
|
|
21
|
+
otherwise, or (ii) ownership of fifty percent (50%) or more of the
|
|
22
|
+
outstanding shares, or (iii) beneficial ownership of such entity.
|
|
23
|
+
|
|
24
|
+
"You" (or "Your") shall mean an individual or Legal Entity
|
|
25
|
+
exercising permissions granted by this License.
|
|
26
|
+
|
|
27
|
+
"Source" form shall mean the preferred form for making modifications,
|
|
28
|
+
including but not limited to software source code, documentation
|
|
29
|
+
source, and configuration files.
|
|
30
|
+
|
|
31
|
+
"Object" form shall mean any form resulting from mechanical
|
|
32
|
+
transformation or translation of a Source form, including but
|
|
33
|
+
not limited to compiled object code, generated documentation,
|
|
34
|
+
and conversions to other media types.
|
|
35
|
+
|
|
36
|
+
"Work" shall mean the work of authorship, whether in Source or
|
|
37
|
+
Object form, made available under the License, as indicated by a
|
|
38
|
+
copyright notice that is included in or attached to the work
|
|
39
|
+
(an example is provided in the Appendix below).
|
|
40
|
+
|
|
41
|
+
"Derivative Works" shall mean any work, whether in Source or Object
|
|
42
|
+
form, that is based on (or derived from) the Work and for which the
|
|
43
|
+
editorial revisions, annotations, elaborations, or other modifications
|
|
44
|
+
represent, as a whole, an original work of authorship. For the purposes
|
|
45
|
+
of this License, Derivative Works shall not include works that remain
|
|
46
|
+
separable from, or merely link (or bind by name) to the interfaces of,
|
|
47
|
+
the Work and Derivative Works thereof.
|
|
48
|
+
|
|
49
|
+
"Contribution" shall mean any work of authorship, including
|
|
50
|
+
the original version of the Work and any modifications or additions
|
|
51
|
+
to that Work or Derivative Works thereof, that is intentionally
|
|
52
|
+
submitted to Licensor for inclusion in the Work by the copyright owner
|
|
53
|
+
or by an individual or Legal Entity authorized to submit on behalf of
|
|
54
|
+
the copyright owner. For the purposes of this definition, "submitted"
|
|
55
|
+
means any form of electronic, verbal, or written communication sent
|
|
56
|
+
to the Licensor or its representatives, including but not limited to
|
|
57
|
+
communication on electronic mailing lists, source code control systems,
|
|
58
|
+
and issue tracking systems that are managed by, or on behalf of, the
|
|
59
|
+
Licensor for the purpose of discussing and improving the Work, but
|
|
60
|
+
excluding communication that is conspicuously marked or otherwise
|
|
61
|
+
designated in writing by the copyright owner as "Not a Contribution."
|
|
62
|
+
|
|
63
|
+
"Contributor" shall mean Licensor and any individual or Legal Entity
|
|
64
|
+
on behalf of whom a Contribution has been received by Licensor and
|
|
65
|
+
subsequently incorporated within the Work.
|
|
66
|
+
|
|
67
|
+
2. Grant of Copyright License. Subject to the terms and conditions of
|
|
68
|
+
this License, each Contributor hereby grants to You a perpetual,
|
|
69
|
+
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
|
|
70
|
+
copyright license to reproduce, prepare Derivative Works of,
|
|
71
|
+
publicly display, publicly perform, sublicense, and distribute the
|
|
72
|
+
Work and such Derivative Works in Source or Object form.
|
|
73
|
+
|
|
74
|
+
3. Grant of Patent License. Subject to the terms and conditions of
|
|
75
|
+
this License, each Contributor hereby grants to You a perpetual,
|
|
76
|
+
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
|
|
77
|
+
(except as stated in this section) patent license to make, have made,
|
|
78
|
+
use, offer to sell, sell, import, and otherwise transfer the Work,
|
|
79
|
+
where such license applies only to those patent claims licensable
|
|
80
|
+
by such Contributor that are necessarily infringed by their
|
|
81
|
+
Contribution(s) alone or by combination of their Contribution(s)
|
|
82
|
+
with the Work to which such Contribution(s) was submitted. If You
|
|
83
|
+
institute patent litigation against any entity (including a
|
|
84
|
+
cross-claim or counterclaim in a lawsuit) alleging that the Work
|
|
85
|
+
or a Contribution incorporated within the Work constitutes direct
|
|
86
|
+
or contributory patent infringement, then any patent licenses
|
|
87
|
+
granted to You under this License for that Work shall terminate
|
|
88
|
+
as of the date such litigation is filed.
|
|
89
|
+
|
|
90
|
+
4. Redistribution. You may reproduce and distribute copies of the
|
|
91
|
+
Work or Derivative Works thereof in any medium, with or without
|
|
92
|
+
modifications, and in Source or Object form, provided that You
|
|
93
|
+
meet the following conditions:
|
|
94
|
+
|
|
95
|
+
(a) You must give any other recipients of the Work or
|
|
96
|
+
Derivative Works a copy of this License; and
|
|
97
|
+
|
|
98
|
+
(b) You must cause any modified files to carry prominent notices
|
|
99
|
+
stating that You changed the files; and
|
|
100
|
+
|
|
101
|
+
(c) You must retain, in the Source form of any Derivative Works
|
|
102
|
+
that You distribute, all copyright, patent, trademark, and
|
|
103
|
+
attribution notices from the Source form of the Work,
|
|
104
|
+
excluding those notices that do not pertain to any part of
|
|
105
|
+
the Derivative Works; and
|
|
106
|
+
|
|
107
|
+
(d) If the Work includes a "NOTICE" text file as part of its
|
|
108
|
+
distribution, then any Derivative Works that You distribute must
|
|
109
|
+
include a readable copy of the attribution notices contained
|
|
110
|
+
within such NOTICE file, excluding those notices that do not
|
|
111
|
+
pertain to any part of the Derivative Works, in at least one
|
|
112
|
+
of the following places: within a NOTICE text file distributed
|
|
113
|
+
as part of the Derivative Works; within the Source form or
|
|
114
|
+
documentation, if provided along with the Derivative Works; or,
|
|
115
|
+
within a display generated by the Derivative Works, if and
|
|
116
|
+
wherever such third-party notices normally appear. The contents
|
|
117
|
+
of the NOTICE file are for informational purposes only and
|
|
118
|
+
do not modify the License. You may add Your own attribution
|
|
119
|
+
notices within Derivative Works that You distribute, alongside
|
|
120
|
+
or as an addendum to the NOTICE text from the Work, provided
|
|
121
|
+
that such additional attribution notices cannot be construed
|
|
122
|
+
as modifying the License.
|
|
123
|
+
|
|
124
|
+
You may add Your own copyright statement to Your modifications and
|
|
125
|
+
may provide additional or different license terms and conditions
|
|
126
|
+
for use, reproduction, or distribution of Your modifications, or
|
|
127
|
+
for any such Derivative Works as a whole, provided Your use,
|
|
128
|
+
reproduction, and distribution of the Work otherwise complies with
|
|
129
|
+
the conditions stated in this License.
|
|
130
|
+
|
|
131
|
+
5. Submission of Contributions. Unless You explicitly state otherwise,
|
|
132
|
+
any Contribution intentionally submitted for inclusion in the Work
|
|
133
|
+
by You to the Licensor shall be under the terms and conditions of
|
|
134
|
+
this License, without any additional terms or conditions.
|
|
135
|
+
Notwithstanding the above, nothing herein shall supersede or modify
|
|
136
|
+
the terms of any separate license agreement you may have executed
|
|
137
|
+
with Licensor regarding such Contributions.
|
|
138
|
+
|
|
139
|
+
6. Trademarks. This License does not grant permission to use the trade
|
|
140
|
+
names, trademarks, service marks, or product names of the Licensor,
|
|
141
|
+
except as required for reasonable and customary use in describing the
|
|
142
|
+
origin of the Work and reproducing the content of the NOTICE file.
|
|
143
|
+
|
|
144
|
+
7. Disclaimer of Warranty. Unless required by applicable law or
|
|
145
|
+
agreed to in writing, Licensor provides the Work (and each
|
|
146
|
+
Contributor provides its Contributions) on an "AS IS" BASIS,
|
|
147
|
+
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
|
|
148
|
+
implied, including, without limitation, any warranties or conditions
|
|
149
|
+
of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
|
|
150
|
+
PARTICULAR PURPOSE. You are solely responsible for determining the
|
|
151
|
+
appropriateness of using or redistributing the Work and assume any
|
|
152
|
+
risks associated with Your exercise of permissions under this License.
|
|
153
|
+
|
|
154
|
+
8. Limitation of Liability. In no event and under no legal theory,
|
|
155
|
+
whether in tort (including negligence), contract, or otherwise,
|
|
156
|
+
unless required by applicable law (such as deliberate and grossly
|
|
157
|
+
negligent acts) or agreed to in writing, shall any Contributor be
|
|
158
|
+
liable to You for damages, including any direct, indirect, special,
|
|
159
|
+
incidental, or consequential damages of any character arising as a
|
|
160
|
+
result of this License or out of the use or inability to use the
|
|
161
|
+
Work (including but not limited to damages for loss of goodwill,
|
|
162
|
+
work stoppage, computer failure or malfunction, or any and all
|
|
163
|
+
other commercial damages or losses), even if such Contributor
|
|
164
|
+
has been advised of the possibility of such damages.
|
|
165
|
+
|
|
166
|
+
9. Accepting Warranty or Additional Liability. While redistributing
|
|
167
|
+
the Work or Derivative Works thereof, You may choose to offer,
|
|
168
|
+
and charge a fee for, acceptance of support, warranty, indemnity,
|
|
169
|
+
or other liability obligations and/or rights consistent with this
|
|
170
|
+
License. However, in accepting such obligations, You may act only
|
|
171
|
+
on Your own behalf and on Your sole responsibility, not on behalf
|
|
172
|
+
of any other Contributor, and only if You agree to indemnify,
|
|
173
|
+
defend, and hold each Contributor harmless for any liability
|
|
174
|
+
incurred by, or claims asserted against, such Contributor by reason
|
|
175
|
+
of your accepting any such warranty or additional liability.
|
|
176
|
+
|
|
177
|
+
END OF TERMS AND CONDITIONS
|
|
178
|
+
|
|
179
|
+
APPENDIX: How to apply the Apache License to your work.
|
|
180
|
+
|
|
181
|
+
To apply the Apache License to your work, attach the following
|
|
182
|
+
boilerplate notice, with the fields enclosed by brackets "[]"
|
|
183
|
+
replaced with your own identifying information. (Don't include
|
|
184
|
+
the brackets!) The text should be enclosed in the appropriate
|
|
185
|
+
comment syntax for the file format. We also recommend that a
|
|
186
|
+
file or class name and description of purpose be included on the
|
|
187
|
+
same "printed page" as the copyright notice for easier
|
|
188
|
+
identification within third-party archives.
|
|
189
|
+
|
|
190
|
+
Copyright [yyyy] [name of copyright owner]
|
|
191
|
+
|
|
192
|
+
Licensed under the Apache License, Version 2.0 (the "License");
|
|
193
|
+
you may not use this file except in compliance with the License.
|
|
194
|
+
You may obtain a copy of the License at
|
|
195
|
+
|
|
196
|
+
http://www.apache.org/licenses/LICENSE-2.0
|
|
197
|
+
|
|
198
|
+
Unless required by applicable law or agreed to in writing, software
|
|
199
|
+
distributed under the License is distributed on an "AS IS" BASIS,
|
|
200
|
+
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
|
201
|
+
See the License for the specific language governing permissions and
|
|
202
|
+
limitations under the License.
|