Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
5 changes: 5 additions & 0 deletions aai_cli/AGENTS.md
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,11 @@ Scoped guidance for the package source. Repo-wide invariants (gate, commit
hooks, conventions) live in the root `AGENTS.md`; test-suite guidance lives in
`tests/AGENTS.md`.

Caption subtitle filenames cross two ffmpeg parsers: escape the subtitle option
value first, then the filtergraph value. Passing `-vf` as one argv item avoids a
shell layer but does not avoid either ffmpeg layer. Real rendering regressions
live in `tests/test_caption_ffmpeg.py`; keep font-size styling intact.

## Architecture

A Typer CLI. `aai_cli/main.py` builds the `app` and registers every command
Expand Down
23 changes: 10 additions & 13 deletions aai_cli/commands/caption/_exec.py
Original file line number Diff line number Diff line change
Expand Up @@ -16,10 +16,9 @@
from __future__ import annotations

import dataclasses
import os
import tempfile
from dataclasses import dataclass
from pathlib import Path
from pathlib import Path, PurePath

import assemblyai as aai
from rich.markup import escape
Expand Down Expand Up @@ -54,20 +53,18 @@ def default_out_path(media: Path) -> Path:
return media.parent / f"{media.stem}.captioned{media.suffix}"


# ffmpeg's filtergraph syntax gives these characters meaning (option/filter/chain
# separators, stream labels, quoting), so a path embedded in `-vf subtitles=…`
# must escape them or a TMPDIR containing one would corrupt the filter spec.
_FILTER_ESCAPES = str.maketrans({ch: f"\\{ch}" for ch in "\\':,;[]"})
# The filename is parsed twice: first by the filtergraph, then by the subtitles
# option parser. Escape from the inside out so the graph preserves option escapes.
_OPTION_ESCAPES = str.maketrans({ch: f"\\{ch}" for ch in "\\':"})
_FILTER_ESCAPES = str.maketrans({ch: f"\\{ch}" for ch in "\\',;[]"})


def subtitles_filter(srt: Path, font_size: int | None) -> str:
def subtitles_filter(srt: PurePath, font_size: int | None) -> str:
"""The ``-vf`` filtergraph burning ``srt`` into the video."""
# ffmpeg's filtergraph parser takes forward slashes on every platform; a Windows
# backslash path would otherwise need each separator escaped (and the drive colon
# mishandled). Normalize to "/" first, then escape the remaining metacharacters
# (notably the drive ":") — e.g. C:\a\b.srt -> C\:/a/b.srt. No-op on POSIX.
posix = str(srt).replace(os.sep, "/")
spec = f"subtitles={posix.translate(_FILTER_ESCAPES)}"
# as_posix normalizes Windows separators without rewriting literal POSIX
# backslashes. There is no shell-escaping layer: -vf is passed as one argv item.
filename = srt.as_posix().translate(_OPTION_ESCAPES).translate(_FILTER_ESCAPES)
spec = f"subtitles={filename}"
if font_size is not None:
spec += f":force_style=FontSize={font_size}"
return spec
Expand Down
13 changes: 7 additions & 6 deletions tests/test_caption_exec.py
Original file line number Diff line number Diff line change
Expand Up @@ -63,9 +63,10 @@ def record_ffmpeg(monkeypatch, *, returncode: int = 0, stderr: str = ""):
def run(args: list[str]) -> subprocess.CompletedProcess[str]:
recorded["args"] = args
escaped = args[8].removeprefix("subtitles=").split(":force_style")[0]
# subtitles_filter escapes filtergraph metacharacters (and the Windows drive
# colon) with a leading backslash; reverse that to recover the real on-disk path.
srt_path = re.sub(r"\\(.)", r"\1", escaped)
# This boundary fake only recovers the file for pipeline assertions. Real
# parser acceptance and rendered pixels are checked in test_caption_ffmpeg.
option_value = re.sub(r"\\(.)", r"\1", escaped)
srt_path = re.sub(r"\\(.)", r"\1", option_value)
recorded["srt"] = Path(srt_path).read_text(encoding="utf-8")
return subprocess.CompletedProcess(
args=args, returncode=returncode, stdout="", stderr=stderr
Expand Down Expand Up @@ -136,10 +137,10 @@ def test_subtitles_filter_appends_font_size():


def test_subtitles_filter_escapes_filtergraph_metacharacters():
# ffmpeg's filtergraph syntax gives these characters meaning; an unescaped
# one in a TMPDIR-derived path would corrupt the filter spec.
# Colon must survive the graph parser; apostrophe is special at both levels.
# Comma, semicolon and brackets need only graph-level escaping.
spec = caption_exec.subtitles_filter(Path("/tmp/a'b:c,d;e[f]g.srt"), None)
assert spec == "subtitles=/tmp/a\\'b\\:c\\,d\\;e\\[f\\]g.srt"
assert spec == r"subtitles=/tmp/a\\\'b\\:c\,d\;e\[f\]g.srt"


# --- validation order (cheap local checks before any credential or network) ----
Expand Down
93 changes: 93 additions & 0 deletions tests/test_caption_ffmpeg.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,93 @@
"""Real ffmpeg parser/rendering regressions; only the SDK boundary is faked."""

from __future__ import annotations

import os
import subprocess
import tempfile
from pathlib import Path, PureWindowsPath
from types import SimpleNamespace

import pytest
from typer.testing import CliRunner

from aai_cli.commands.caption import _exec as caption_exec
from aai_cli.core import client, config
from aai_cli.main import app

SRT = "1\n00:00:00,000 --> 00:00:02,000\nHello captions\n"
DIRECTORIES = ["plain", "o'brien", "comma,dir", "semi;dir", "bracket[dir]", "space dir"]
if os.name == "posix":
DIRECTORIES += ["tmp:dir", r"back\slash"]


def _ffmpeg(*args: str) -> str:
result = subprocess.run(
["ffmpeg", "-hide_banner", "-loglevel", "error", "-y", *args],
capture_output=True,
text=True,
timeout=30,
check=False,
)
assert result.returncode == 0, result.stderr
return result.stdout


def _hashes(*args: str) -> list[str]:
return [
line
for line in _ffmpeg(*args, "-f", "framehash", "-").splitlines()
if not line.startswith("#")
]


@pytest.mark.parametrize("dirname", DIRECTORIES)
@pytest.mark.parametrize("font_size", [None, 28])
def test_caption_cli_renders_subtitles(tmp_path, monkeypatch, dirname, font_size):
temp_root = tmp_path / dirname
temp_root.mkdir()
monkeypatch.setattr(tempfile, "tempdir", str(temp_root))
monkeypatch.setattr(config, "resolve_api_key", lambda **_: "test-key")
calls = []

def export(chars_per_caption=None):
calls.append(("srt", chars_per_caption))
return SRT

def transcribe(api_key, audio, *, config):
calls.append(("transcribe", Path(audio).name))
return SimpleNamespace(id="test-caption", export_subtitles_srt=export)

monkeypatch.setattr(client, "transcribe", transcribe)
media = tmp_path / "talk.mp4"
_ffmpeg("-f", "lavfi", "-i", "color=c=black:s=320x240:r=1:d=2", "-c:v", "mpeg4", str(media))
args = ["caption", str(media), "--chars-per-caption", "32", "--json"]
if font_size is not None:
args += ["--font-size", str(font_size)]
result = CliRunner().invoke(app, args)
assert result.exit_code == 0, result.output
assert calls == [("transcribe", "talk.mp4"), ("srt", 32)]
baseline = _hashes("-i", str(media))
captioned = _hashes("-i", str(tmp_path / "talk.captioned.mp4"))
assert len(baseline) == len(captioned) == 2
assert captioned != baseline


def test_windows_path_filter_contract(tmp_path, monkeypatch):
# On POSIX a literal C: directory tests the parser, NOT native Windows I/O.
monkeypatch.chdir(tmp_path)
windows = PureWindowsPath(r"C:\captions\captions.srt")
srt = Path(windows.as_posix()) if os.name == "posix" else tmp_path / "captions.srt"
srt.parent.mkdir(parents=True, exist_ok=True)
srt.write_text(SRT, encoding="utf-8")
filter_path = windows if os.name == "posix" else PureWindowsPath(srt)
spec = caption_exec.subtitles_filter(filter_path, None)
if os.name == "posix":
# Avoid libavformat treating C: as a URL protocol on this POSIX host.
# Keep the generated drive colon and separators intact for both parsers.
spec = spec.replace("subtitles=", "subtitles=./", 1)
source = ("-f", "lavfi", "-i", "color=c=black:s=320x240:r=1:d=2")
baseline = _hashes(*source)
captioned = _hashes(*source, "-vf", spec)
assert len(baseline) == len(captioned) == 2
assert captioned != baseline