Clone your own voice on your own computer: speak any text in 60+ languages and dub videos into another language in your voice. Fully local. Early version.
Rust chatterboxdesktopdubbingmobilemultilingualofflineomnivoicerustrvcspeech-synthesisspeech-to-textstttext-to-speechttsvoice-cloningvoxcpm2whisper
from __future__ import annotations
import difflib
import math
import os
import re
import subprocess
import sys
import unicodedata
from collections.abc import Callable
from dataclasses import dataclass
from pathlib import Path, PurePath
from . import langs
Line = tuple[float, float, str]
Words = list[tuple[float, float, str]]
MIN_S = 0.8
LINE_UNITS = 42.0
WIDE_UNITS = 2.6 # a line holds 16 Chinese or Japanese characters, the usual limit for them
MAX_LINES = 2
GAP_S = 1.5 # a pause this long ends a subtitle even inside a sentence
HOLD_S = 0.3 # Whisper ends a word a little early: a cue stays this much longer, unless the next one starts
CLEAR_S = 3.0 # rolling captions stay on screen through a shorter pause, as on YouTube
BOX_S = 0.2 # a box widens for a new word, easing in and out; the word shows, whole, once the box holds it
ROLL_S = 0.35
LEAD_S = 0.3 # a word starts showing this much before it is said, so it is clear as it is heard
FADE_OUT_S = 0.6
FRAME_S = 0.02 # a picture made of stills gets frames this far apart (50 fps) while a caption moves
_SENTENCE = re.compile(r"(?<=[.!?…])\s+|(?<=[。!?])")
_CLAUSE = re.compile(r"(?<=[,;:])\s+|(?<=[,、;:])|\s+(?=[—–]\s)")
_BREAK_AFTER = ".!?…,;:。!?,、;:"
_FONTS = {"win32": "Arial", "darwin": "Helvetica Neue"}
_LINUX_FONT = "Noto Sans"
_CJK_FONTS = {
"zh": ("Microsoft YaHei", "PingFang SC", "Noto Sans CJK SC"),
"yue": ("Microsoft JhengHei", "PingFang TC", "Noto Sans CJK TC"),
"ja": ("Yu Gothic", "Hiragino Sans", "Noto Sans CJK JP"),
"ko": ("Malgun Gothic", "Apple SD Gothic Neo", "Noto Sans CJK KR"),
}
@dataclass(frozen=True)
class Cue:
start: float
end: float
lines: tuple[str, ...]
# When each word starts, for captions that roll up word by word as they are spoken.
words: tuple[tuple[float, str], ...] = ()
@dataclass(frozen=True)
class Plan:
"""What the video's subtitles say (``lines``: where each spoken clip lands in the final track) and where the
ASS file goes."""
lines: list[Line] | None
language: str | None
position: str
path: Path
def _wide(ch: str) -> bool:
return unicodedata.east_asian_width(ch) in "WF"
def width(text: str) -> float:
return sum(WIDE_UNITS if _wide(ch) else 1.0 for ch in text)
def _join(a: str, b: str) -> str:
if not a:
return b
return a + b if _wide(a[-1]) and _wide(b[0]) else f"{a} {b}"
WIDE_RUN = (
4 # rolling captions add text without spaces (Chinese, Japanese) about a word, this many characters, at a time
)
def _tokens(text: str, run: int, gaps: bool = False) -> list[tuple[int, str]]:
"""(offset, token): words, with text in a script without spaces cut into runs of at most ``run`` characters;
``gaps``: a space between two such words stays, as an ideographic space in front of the second."""
out: list[tuple[int, str]] = []
for m in re.finditer(r"\S+", text):
word, k = m.group(), 0
before = text[: m.start()].rstrip()[-1:]
gap = "\u3000" if gaps and before and _wide(before) and _wide(word[0]) else ""
while k < len(word):
j = k + 1
if _wide(word[k]):
while j < len(word) and _wide(word[j]) and j - k < run:
j += 1
else:
while j < len(word) and not _wide(word[j]):
j += 1
out.append((m.start() + k, gap + word[k:j]))
k, gap = j, ""
return out
def _even(text: str, limit: float) -> list[str]:
"""Words (or characters, in a script without spaces) shared out over as few even pieces as fit ``limit``."""
tokens = [t for _, t in _tokens(text, 1)]
n = math.ceil(width(text) / limit)
target = width(text) / n
out, cur = [], ""
for tok in tokens:
nxt = _join(cur, tok)
if cur and len(out) < n - 1 and width(nxt) > target and width(nxt) - target > target - width(cur):
# A piece does not end on a short word ("to", "of", "і"): it goes on with the next piece.
words = cur.split(" ")
carry = []
while " " in text and len(words) > 1 and _short(words[-1]) and width(" ".join([*carry, tok])) < limit:
carry.insert(0, words.pop())
out.append(" ".join(words))
cur = " ".join([*carry, tok])
else:
cur = nxt
return [*out, cur] if cur else out
def _short(word: str) -> bool:
return len(word) <= 3 and word.isalpha() and word.islower()
def _groups(text: str, limit: float) -> list[str]:
"""A cue per sentence; a longer sentence is split at its clauses (whole clauses may share a cue), and a clause too
long for a cue into even pieces of words."""
out: list[str] = []
for sentence in filter(None, (s.strip() for s in _SENTENCE.split(text))):
if width(sentence) <= limit:
out.append(sentence)
continue
whole = False
for clause in filter(None, (c.strip() for c in _CLAUSE.split(sentence))):
if width(clause) > limit:
out.extend(_even(clause, limit))
whole = False
elif whole and width(_join(out[-1], clause)) <= limit:
out[-1] = _join(out[-1], clause)
else:
out.append(clause)
whole = True
return out
def _two_lines(text: str) -> tuple[str, ...]:
if width(text) <= LINE_UNITS:
return (text,)
best: tuple[float, str, str] | None = None
for i in range(1, len(text)):
if text[i] == " ":
left, right = text[:i], text[i + 1 :]
elif (_wide(text[i - 1]) or _wide(text[i])) and text[i] not in _BREAK_AFTER and text[i - 1] != " ":
left, right = text[:i], text[i:]
else:
continue
if not left or not right:
continue
score = abs(width(left) - width(right)) - (LINE_UNITS / 3 if left[-1] in _BREAK_AFTER else 0.0)
if max(width(left), width(right)) > LINE_UNITS:
score += 4 * LINE_UNITS
if best is None or score < best[0]:
best = (score, left, right)
return (text,) if best is None else (best[1], best[2])
def _shares(weights: list[float], total: float, floor: float) -> list[float]:
"""``total`` split by ``weights``, each at least ``floor`` when the total allows it."""
n = len(weights)
if total < floor * n:
floor = 0.0
fixed: set[int] = set()
while True:
free = total - floor * len(fixed)
wsum = sum(w for i, w in enumerate(weights) if i not in fixed) or 1.0
out = [floor if i in fixed else free * w / wsum for i, w in enumerate(weights)]
low = {i for i, d in enumerate(out) if i not in fixed and d < floor}
if not low:
return out
fixed |= low
def _token(word: str) -> str:
return re.sub(r"\W", "", word.lower())
def _word_spans(piece: str, at: int, start: float, end: float, words: Words) -> list[tuple[int, int, float, float]]:
"""The line's words at the times Whisper heard them; a word edited since takes the time of its neighbours."""
tokens = [(m.start(), m.end(), _token(m.group())) for m in re.finditer(r"\S+", piece)]
heard = [_token(w) for _, _, w in words]
match = difflib.SequenceMatcher(None, [t for _, _, t in tokens], heard, autojunk=False)
spans = [
(at + tokens[b.a + k][0], at + tokens[b.a + k][1], float(words[b.b + k][0]), float(words[b.b + k][1]))
for b in match.get_matching_blocks()
for k in range(b.size)
]
return spans or [(at, at + len(piece), start, end)]
def _runs(lines: list[Line], words: list[Words] | None) -> list[tuple[str, list[tuple[int, int, float, float]]]]:
"""Lines joined into continuous text until a pause of ``GAP_S``: a sentence that a transcript or a dub cut into
clips is one again. Each run keeps where its characters are: (first, past the last, start, end), per word when
the line's ``words`` have times, else per line."""
runs: list[tuple[str, list[tuple[int, int, float, float]]]] = []
text, spans, last_end, bare = "", [], -math.inf, False
for (start, end, spoken), heard in sorted(zip(lines, words or [[]] * len(lines)), key=lambda x: x[0][0]):
piece = re.sub(r"\s+", " ", spoken).strip()
if not piece or end <= start:
continue
# A line of Chinese or Japanese with no punctuation at all (sung lyrics, a transcript without it) is a
# phrase of its own: run on, it would be cut anywhere.
alone = any(_wide(ch) for ch in piece) and not any(ch in _BREAK_AFTER for ch in piece)
if text and (start - last_end >= GAP_S or alone or bare):
runs.append((text, spans))
text, spans = "", []
bare = alone
joined = _join(text, piece)
at = len(joined) - len(piece)
spans.extend(_word_spans(piece, at, start, end, heard) if heard else [(at, len(joined), start, end)])
text, last_end = joined, max(last_end, end)
if text:
runs.append((text, spans))
return runs
def _time_at(spans: list[tuple[int, int, float, float]], k: int) -> float:
before = spans[0][2]
for a, b, start, end in spans:
if k < a:
return before
if k < b:
return start + (end - start) * (k - a) / max(b - a, 1)
before = end
return before
def cues(lines: list[Line], words: list[Words] | None = None) -> list[Cue]:
"""Subtitles that each show a whole thought: sentences (short ones share a cue), a long sentence split at its
commas, then into even words; at most two lines. A cue's time is where its words are in the lines. Cues never
overlap and stay at least ``MIN_S`` on screen where the gap after allows."""
raw: list[tuple[float, float, str, tuple[tuple[float, str], ...]]] = []
for text, spans in _runs(lines, words):
pos = 0
for g in _groups(text, LINE_UNITS * MAX_LINES):
i = text.find(g, pos)
i = pos if i < 0 else i
pos = i + len(g)
said = tuple((_time_at(spans, i + k), tok) for k, tok in _tokens(g, WIDE_RUN, gaps=True))
raw.append((_time_at(spans, i), _time_at(spans, pos), g, said))
out: list[Cue] = []
for i, (a, b, text, said) in enumerate(raw):
nxt = raw[i + 1][0] if i + 1 < len(raw) else math.inf
start = max(a, out[-1].end if out else 0.0)
end = min(max(b + HOLD_S, start + MIN_S), nxt)
if end - start >= 0.05:
out.append(Cue(start, end, _two_lines(text), tuple((max(t, start), w) for t, w in said)))
return out
def rollup(items: list[Cue]) -> list[Cue]:
"""What a burned caption shows, as YouTube rolls captions up: words appear as they are spoken, a full line moves
up and the one above it leaves, so at most two lines show. A pause under ``CLEAR_S`` keeps the text; a longer one
clears it."""
shown: list[Cue] = []
done: list[str] = []
cur = ""
last_end = -math.inf
last_t = 0.0
for c in items:
said = c.words or tuple((c.start, w) for w in " ".join(c.lines).split())
if c.start - last_end > CLEAR_S:
done, cur = [], ""
for spoken, word in said:
nxt = _join(cur, word)
wraps = bool(cur) and width(nxt) > LINE_UNITS
# A change waits for the one before to finish moving, so nothing is cut short and jumps.
t = max(spoken - LEAD_S, last_t)
last_t = t + (ROLL_S if wraps else BOX_S)
if wraps:
done.append(cur)
cur = word.lstrip("\u3000")
else:
cur = nxt.lstrip("\u3000")
shown.append(Cue(t, c.end, (*done[-1:], cur)))
last_end = c.end
out: list[Cue] = []
for i, s in enumerate(shown):
nxt = shown[i + 1].start if i + 1 < len(shown) else math.inf
end = nxt if nxt - s.end <= CLEAR_S else s.end
if end - s.start >= 0.01:
out.append(Cue(s.start, end, s.lines))
return out
def _clears(shown: list[Cue], i: int) -> bool:
return i + 1 == len(shown) or shown[i + 1].start - shown[i].end > 1e-3
def change_times(items: list[Cue]) -> list[float]:
"""Every moment a burned caption changes, a frame of a picture made of stills: each change, and while a caption
moves, the steps of one 50 fps grid (overlapping animations share frames)."""
shown = rollup(items)
times: set[float] = set()
def grid(a: float, b: float) -> None:
times.update(round(k * FRAME_S, 3) for k in range(math.ceil(a / FRAME_S), math.floor(b / FRAME_S) + 1))
for i, c in enumerate(shown):
rolls = i > 0 and len(c.lines) == 2 and c.lines[0] == shown[i - 1].lines[-1]
times.add(round(c.start, 3))
grid(
c.start,
c.start + (ROLL_S if rolls else BOX_S),
)
times.add(round(c.end, 3))
if _clears(shown, i):
grid(c.end - FADE_OUT_S, c.end)
out: list[float] = []
for t in sorted(times):
if not out or t - out[-1] >= FRAME_S / 2:
out.append(t)
return out
STEPS = 8 # an eased motion in short straight steps, as ASS has no ease-in-out curve
_Body = Callable[[float], tuple[int, str]]
def _smooth(p: float) -> float:
return p * p * (3 - 2 * p)
def _hex(v: float) -> str:
return f"&H{max(0, min(255, round(v))):02X}&"
def _ease(tag: str, v0: float, v1: float, begin: float, dur: float, t: float, fmt: Callable[[float], str]) -> str:
"""``tag`` easing in and out from v0 to v1 over clock times begin..begin + dur, in an event that starts at t."""
if v0 == v1 or t >= begin + dur:
return f"\\{tag}{fmt(v1)}"
def at(u: float) -> float:
return v0 + (v1 - v0) * _smooth(min(max((u - begin) / dur, 0.0), 1.0))
out = f"\\{tag}{fmt(at(t))}"
for k in range(STEPS):
a, b = begin + dur * k / STEPS, begin + dur * (k + 1) / STEPS
if b > t:
out += f"\\t({max(a - t, 0.0) * 1000:.0f},{(b - t) * 1000:.0f},\\{tag}{fmt(at(b))})"
return out
def _events(
shown: list[Cue], measure: _Measure, left: float, anchor: float, top: bool
) -> list[tuple[int, float, float, str]]:
"""ASS events (layer, start, end, text) of rolling captions, each line placed by hand on a rounded half-transparent
box. A new word's box widens, then the word shows whole; when a line starts, the lines scroll up a row inside the
caption's two rows, the new one coming in from below and the top one leaving above; a caption fades out when it
clears. Text is never half-transparent and never outside its box."""
size = measure.size
pad_x, pad_y = round(size * 0.32), round(size * 0.1)
box_h = size + 2 * pad_y
pitch = box_h
radius = box_h * 0.32
fade_out = round(FADE_OUT_S * 1000)
window = (anchor, anchor + 2 * pitch) if top else (anchor - 2 * pitch, anchor)
clip = f"\\clip(0,{window[0]:.0f},100000,{window[1]:.0f})"
out: list[tuple[int, float, float, str]] = []
def row_y(row: int, rows: int) -> float:
"""Top of the box of a line: rows count from the anchored edge."""
return anchor + row * pitch if top else anchor - box_h - (rows - 1 - row) * pitch
def emit(start: float, end: float, x: float, y0: float, y1: float, body: _Body, tail: str = "") -> None:
"""One line's events: a slide from y0 to y1 in STEPS eased steps, then still; ``body(t)`` gives the tags and
text as seen at clock time t."""
if y0 == y1:
layer, text = body(start)
out.append((layer, start, end, f"{{\\an7\\pos({x:.0f},{y1:.0f}){clip}{tail}{text}"))
return
for k in range(STEPS):
a, b = ROLL_S * k / STEPS, ROLL_S * (k + 1) / STEPS
ya, yb = (y0 + (y1 - y0) * _smooth(t / ROLL_S) for t in (a, b))
layer, text = body(start + a)
move = f"\\move({x:.0f},{ya:.1f},{x:.0f},{yb:.1f},0,{(b - a) * 1000:.0f})"
out.append((layer, start + a, min(start + b, end), f"{{\\an7{move}{clip}{text}"))
if end > start + ROLL_S:
layer, text = body(start + ROLL_S)
out.append((layer, start + ROLL_S, end, f"{{\\an7\\pos({x:.0f},{y1:.0f}){clip}{tail}{text}"))
def box(st: dict) -> _Body:
"""A line's box: it widens from w0 to w1 and appears (alpha a0 to half) from s0."""
def body(t: float) -> tuple[int, str]:
tags = "\\bord0\\shad0\\1c&H000000&" + _ease("1a", st["a0"], 0x80, st["s0"], BOX_S, t, _hex)
if st["w0"] != st["w1"] and t < st["s0"] + BOX_S:
scale = _ease("fscx", st["w0"] / st["w1"] * 100, 100, st["s0"], BOX_S, t, lambda v: f"{v:.2f}")
tags += f"\\org({left - pad_x:.0f},0){scale}"
return 0, f"{tags}\\p1}}{_rounded(st['w1'], box_h, radius)}{{\\p0}}"
return body
def text(st: dict) -> _Body:
"""A line's pieces (a word, or a few characters of a script without spaces), each showing whole, at once,
from its own time."""
def body(t: float) -> tuple[int, str]:
out = []
for piece, show in zip(st["parts"], st["shows"], strict=True):
gap = piece[0] if piece[:1].isspace() else "" # escape() drops it
if t >= show:
out.append(gap + escape(piece))
else:
d = (show - t) * 1000
hidden = f"{{\\alpha&HFF&\\t({d:.0f},{d + 1:.0f},\\alpha&H00&)}}"
out.append(f"{gap}{hidden}{escape(piece)}{{\\alpha&H00&}}")
return 1, "}" + "".join(out)
return body
def still(line: str) -> dict:
w = measure(line) + 2 * pad_x
return {"text": line, "s0": -math.inf, "w0": w, "w1": w, "a0": 0x80, "parts": [line], "shows": [-math.inf]}
state: dict | None = None # the last line's animation
for i, c in enumerate(shown):
before = shown[i - 1] if i and not _clears(shown, i - 1) else None
if before is None:
state = None
rolled = before is not None and len(c.lines) == 2 and c.lines[0] == before.lines[-1]
moving = rolled and (not top or len(before.lines) == 2)
clear = f"\\fad(0,{fade_out})" if _clears(shown, i) else ""
rows = len(c.lines)
s = c.start
previous = state
for j, line in enumerate(c.lines):
y1 = row_y(j, rows)
last = j == rows - 1
if rolled and j == 0:
y0 = row_y(len(before.lines) - 1, len(before.lines))
elif moving and last:
y0 = y1 + pitch
else:
y0 = y1
w = measure(line) + 2 * pad_x
grown = previous is not None and line.startswith(previous["text"]) and line != previous["text"]
if last and previous is not None and not rolled and grown:
st = {
"text": line,
"s0": s,
"w0": previous["w1"],
"w1": w,
"a0": 0x80,
"parts": [*previous["parts"], line[len(previous["text"]) :]],
"shows": [*previous["shows"], s + BOX_S],
}
elif last and moving:
st = {"text": line, "s0": s, "w0": w, "w1": w, "a0": 0x80, "parts": [line], "shows": [-math.inf]}
elif last:
st = {"text": line, "s0": s, "w0": w, "w1": w, "a0": 255, "parts": [line], "shows": [s + BOX_S]}
elif previous is not None and line == previous["text"]:
st = previous
else:
st = still(line)
if last:
state = st
emit(c.start, c.end, left - pad_x, y0, y1, box(st), clear)
emit(c.start, c.end, left, y0 + pad_y, y1 + pad_y, text(st), clear)
if moving and len(before.lines) == 2:
gone = still(before.lines[0])
y0 = row_y(0, 2)
end = c.start + ROLL_S
emit(c.start, end, left - pad_x, y0, y0 - pitch, box(gone))
emit(c.start, end, left, y0 + pad_y, y0 + pad_y - pitch, text(gone))
return out
def font_name(language: str | None, platform: str = sys.platform) -> str:
"""The app's Noto Sans has no CJK, and the engine cannot reach it: system fonts by script and platform, and
libass takes any glyph a font lacks from another system font."""
cjk = _CJK_FONTS.get(langs.norm(language))
if cjk is not None:
return cjk[0] if platform == "win32" else cjk[1] if platform == "darwin" else cjk[2]
return _FONTS.get(platform, _LINUX_FONT)
_FONT_FILES = {
"win32": {
"Arial": "arial.ttf",
"Microsoft YaHei": "msyh.ttc",
"Microsoft JhengHei": "msjh.ttc",
"Yu Gothic": "YuGothR.ttc",
"Malgun Gothic": "malgun.ttf",
},
"darwin": {
"Helvetica Neue": "/System/Library/Fonts/HelveticaNeue.ttc",
"PingFang SC": "/System/Library/Fonts/PingFang.ttc",
"PingFang TC": "/System/Library/Fonts/PingFang.ttc",
"Hiragino Sans": "/System/Library/Fonts/ヒラギノ角ゴシック W3.ttc",
"Apple SD Gothic Neo": "/System/Library/Fonts/AppleSDGothicNeo.ttc",
},
}
def _font_file(name: str) -> str | None:
if sys.platform == "win32":
f = _FONT_FILES["win32"].get(name)
return str(Path(os.environ.get("WINDIR", r"C:\Windows")) / "Fonts" / f) if f else None
if sys.platform == "darwin":
return _FONT_FILES["darwin"].get(name)
try:
out = subprocess.run(
["fc-match", "-f", "%{file}", name], check=False, capture_output=True, text=True, timeout=5
).stdout
except (OSError, subprocess.SubprocessError):
return None
return out.strip() or None
class _Measure:
"""Widths of text in pixels as libass draws it at an ASS font size (the cell height, not the em); an estimate
when the font or Pillow is missing."""
def __init__(self, name: str, size: int) -> None:
self.size = size
self.font = None
try:
from PIL import ImageFont
path = _font_file(name)
if path and Path(path).is_file():
probe = ImageFont.truetype(path, 100)
ascent, descent = probe.getmetrics()
self.font = ImageFont.truetype(path, max(round(size * 100 / (ascent + descent)), 1))
except Exception:
self.font = None
def __call__(self, text: str) -> float:
if self.font is not None:
return float(self.font.getlength(text))
return width(text) * self.size * 0.4
def _rounded(w: float, h: float, r: float) -> str:
k = r * 0.4477 # 1 - 0.5523: a quarter circle as one cubic Bezier
path = [
("m", r, 0),
("l", w - r, 0),
("b", w - k, 0, w, k, w, r),
("l", w, h - r),
("b", w, h - k, w - k, h, w - r, h),
("l", r, h),
("b", k, h, 0, h - k, 0, h - r),
("l", 0, r),
("b", 0, k, k, 0, r, 0),
]
return " ".join(f"{cmd} " + " ".join(f"{v:.1f}" for v in pts) for cmd, *pts in path)
def _time(t: float) -> str:
cs = max(round(t * 100), 0)
return f"{cs // 360000}:{cs // 6000 % 60:02d}:{cs // 100 % 60:02d}.{cs % 100:02d}"
def escape(text: str) -> str:
text = text.replace("\\", "\\\u200b").replace("{", "\\{").replace("}", "\\}")
return re.sub(r"\s+", " ", text).strip()
def ass(items: list[Cue], width_px: int, height_px: int, position: str = "bottom", language: str | None = None) -> str:
size = max(round(min(height_px, width_px * 0.65) * 0.055), 12) # 0.65: a full line still fits a portrait video
margin_v = round(height_px * 0.05)
font = font_name(language)
measure = _Measure(font, size)
shown = rollup(items)
widest = max((measure(ln) for c in shown for ln in c.lines), default=0.0)
# Lines grow from one left edge, as on YouTube (a centred line would shift with every word); the widest line of
# the video is centred.
left = max(round(width_px * 0.04), round((width_px - widest) / 2))
style = [
("Name", "Default"),
("Fontname", font),
("Fontsize", size),
("PrimaryColour", "&H00FFFFFF"),
("SecondaryColour", "&H000000FF"),
("OutlineColour", "&H80000000"),
("BackColour", "&H00000000"),
("Bold", 0),
("Italic", 0),
("Underline", 0),
("StrikeOut", 0),
("ScaleX", 100),
("ScaleY", 100),
("Spacing", 0),
("Angle", 0),
("BorderStyle", 1),
("Outline", f"{round(size * 0.025, 1):g}"),
("Shadow", 0),
("Alignment", 7),
("MarginL", left),
("MarginR", round(width_px * 0.04)),
("MarginV", margin_v),
("Encoding", 1),
]
head = [
"[Script Info]",
"ScriptType: v4.00+",
f"PlayResX: {width_px}",
f"PlayResY: {height_px}",
"WrapStyle: 2",
"ScaledBorderAndShadow: yes",
"YCbCr Matrix: None",
"",
"[V4+ Styles]",
"Format: " + ", ".join(k for k, _ in style),
"Style: " + ",".join(str(v) for _, v in style),
"",
"[Events]",
"Format: Layer, Start, End, Style, Name, MarginL, MarginR, MarginV, Effect, Text",
]
top = position == "top"
anchor = margin_v if top else height_px - margin_v
events = [
f"Dialogue: {layer},{_time(a)},{_time(b)},Default,,0,0,0,,{text}"
for layer, a, b, text in _events(shown, measure, left, anchor, top)
]
return "\n".join([*head, *events]) + "\n"
def _ms(t: float) -> tuple[int, int, int, int]:
ms = max(round(t * 1000), 0)
return ms // 3600000, ms // 60000 % 60, ms // 1000 % 60, ms % 1000
def _srt_time(t: float) -> str:
h, m, s, ms = _ms(t)
return f"{h:02d}:{m:02d}:{s:02d},{ms:03d}"
def _vtt_time(t: float) -> str:
h, m, s, ms = _ms(t)
return f"{h:02d}:{m:02d}:{s:02d}.{ms:03d}"
def _sbv_time(t: float) -> str:
h, m, s, ms = _ms(t)
return f"{h}:{m:02d}:{s:02d}.{ms:03d}"
def _plain(line: str) -> str:
return re.sub(r"\s+", " ", line).strip()
def srt(items: list[Cue]) -> str:
"""For MP4 and WebM tracks: ffmpeg keeps an escaped ASS brace escaped in them, while an SRT brace stays a brace."""
blocks = []
for k, c in enumerate(items, 1):
text = "\n".join(_plain(ln.replace("\\", "\\\u200b")) for ln in c.lines)
blocks.append(f"{k}\n{_srt_time(c.start)} --> {_srt_time(c.end)}\n{text}\n")
return "\n".join(blocks)
def vtt(items: list[Cue]) -> str:
blocks = ["WEBVTT\n"]
for c in items:
lines = (_plain(ln).replace("&", "&").replace("<", "<").replace(">", ">") for ln in c.lines)
blocks.append(f"{_vtt_time(c.start)} --> {_vtt_time(c.end)}\n" + "\n".join(lines) + "\n")
return "\n".join(blocks)
def sbv(items: list[Cue]) -> str:
return "\n".join(
f"{_sbv_time(c.start)},{_sbv_time(c.end)}\n" + "\n".join(_plain(ln) for ln in c.lines) + "\n" for c in items
)
WRITERS: dict[str, Callable[[list[Cue]], str]] = {"srt": srt, "vtt": vtt, "sbv": sbv}
def write(plan: Plan, items: list[Cue], width_px: int, height_px: int) -> tuple[Path, Path]:
"""(the ASS file, the SRT next to it)."""
plan.path.parent.mkdir(parents=True, exist_ok=True)
plan.path.write_text(ass(items, width_px, height_px, plan.position, plan.language), encoding="utf-8")
other = plan.path.with_suffix(".srt")
other.write_text(srt(items), encoding="utf-8")
return plan.path, other
def filter_path(path: str | PurePath, windows: bool = os.name == "nt") -> str:
"""``path`` as a value of a filter option inside a filtergraph: escaped once for the option parser and once for
the graph parser. Windows paths get forward slashes, so only the drive colon needs escaping."""
s = str(path).replace("\\", "/") if windows else str(path)
for ch in "\\':":
s = s.replace(ch, "\\" + ch)
for ch in "\\'[],;":
s = s.replace(ch, "\\" + ch)
return s