videos: center YouTube auto-captions at download time

YouTube auto-generated captions (via yt-dlp) stamp every cue timing line
with `align:start position:0%`, pinning the on-screen text to the
bottom-left of the player. This strips that exact cue setting from the
downloaded .vtt files so browsers render the captions centered.

- add strip_youtube_caption_positioning() to wrolpi/captions.py — a
  targeted text replacement (not a webvtt round-trip) so the `<c>`
  word-timing tags in the cue text are preserved; matches only the exact
  auto-caption signature, so deliberately positioned cues (e.g. with a
  `line` setting) are left untouched; idempotent.
- call it from VideoDownloader after normalize_video_file_names, gated on
  a youtube.com / youtu.be source URL. It runs before the FileGroup is
  created, so the first index reads the corrected file — no re-index
  plumbing needed.

Complements the client-side fix in #543 (which centers captions in the
player for existing/any-source files); this makes new YouTube downloads
correct at the source.

Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
This commit is contained in:
Roland 2026-07-16 17:54:00 -06:00 • committed by lrnselfreliance
parent 15787104fd
commit 029f30c4c8
3 changed files with 96 additions and 1 deletions

View file

@ -21,6 +21,7 @@ from sqlalchemy.orm import Session
from yt_dlp import YoutubeDL, DownloadError
from yt_dlp.extractor import YoutubeTabIE # noqa
from wrolpi.captions import strip_youtube_caption_positioning
from wrolpi.cmd import YT_DLP_BIN
from wrolpi.common import logger, get_media_directory, escape_file_name, resolve_generators, background_task, \
trim_file_name, cached_multiprocessing_result, get_absolute_media_path, aiohttp_post, normalize_domain
@ -1037,6 +1038,16 @@ class VideoDownloader(Downloader, ABC):
video_paths = self._delete_part_files(video_path, video_paths)
video_paths = self.normalize_video_file_names(video_path, video_paths)
if url and ('youtube.com' in url or 'youtu.be' in url):
# YouTube auto-captions pin the text to the bottom-left; center them at the source. Runs
# before the FileGroup is created, so the first index reads the corrected file.
for path in video_paths:
if path.name.endswith('.vtt'):
try:
strip_youtube_caption_positioning(path)
except Exception:
logger.warning(f'Failed to center YouTube captions in {path}', exc_info=True)
return ExecutedVideo(
url=url,
video_path=video_path,

View file

@ -1,5 +1,6 @@
#! /usr/bin/env python3
import pathlib
import re
import subprocess
import tempfile
from pathlib import Path
@ -11,7 +12,35 @@ import webvtt
from wrolpi.cmd import FFMPEG_BIN
from wrolpi.common import logger
__all__ = ['read_captions', 'read_captions_with_timestamps', 'extract_captions']
__all__ = ['read_captions', 'read_captions_with_timestamps', 'extract_captions',
'strip_youtube_caption_positioning']
# YouTube auto-generated captions (downloaded via yt-dlp) stamp every cue's timing line with
# `align:start position:0%`, which pins the on-screen text to the bottom-left of the player and makes it hard
# to read. This matches only that exact signature on a cue timing line so we never touch a deliberately
# positioned cue. The `<c>` word-timing tags in the cue text are left untouched.
YOUTUBE_CUE_SETTINGS = re.compile(
r'^(\d{2}:\d{2}:\d{2}\.\d{3} --> \d{2}:\d{2}:\d{2}\.\d{3}) align:start position:0%[ \t]*$',
re.MULTILINE,
)
def strip_youtube_caption_positioning(caption_path: Union[str, Path]) -> bool:
"""Remove YouTube's `align:start position:0%` cue settings from a .vtt file so the browser renders the
captions centered. Rewrites the file in place only if something changed.
This is intended for captions downloaded from youtube.com; the caller is responsible for that gate.
:return: True if the file was modified.
"""
caption_path = pathlib.Path(caption_path)
text = caption_path.read_text()
new_text = YOUTUBE_CUE_SETTINGS.sub(r'\1', text)
if new_text != text:
caption_path.write_text(new_text)
logger.info(f'Centered YouTube captions in {caption_path}')
return True
return False
def _parse_vtt_timestamp(timestamp: str) -> float:

View file

@ -67,3 +67,58 @@ def test_read_captions_with_timestamps(fixture_name, request):
caption_file = request.getfixturevalue(fixture_name)
chunks = captions.read_captions_with_timestamps(caption_file)
assert chunks == EXPECTED_CAPTION_CHUNKS
def test_strip_youtube_caption_positioning(vtt_file1):
"""YouTube's `align:start position:0%` cue settings are removed so captions render centered."""
original = vtt_file1.read_text()
assert 'align:start position:0%' in original
changed = captions.strip_youtube_caption_positioning(vtt_file1)
assert changed is True
new_text = vtt_file1.read_text()
# The mis-positioning cue settings are gone...
assert 'align:start position:0%' not in new_text
# ...but the timestamps and the `<c>` word-timing tags in the cue text survive untouched.
assert '00:00:00.000 --> 00:00:05.269' in new_text
assert '<00:00:01.310><c> welcome</c>' in new_text
# The captions are still readable/parseable and unchanged in content.
assert list(captions.read_captions_with_timestamps(vtt_file1)) == EXPECTED_CAPTION_CHUNKS
# Idempotent: a second pass changes nothing.
assert captions.strip_youtube_caption_positioning(vtt_file1) is False
assert vtt_file1.read_text() == new_text
def test_strip_youtube_caption_positioning_leaves_clean_files(vtt_file2):
"""A VTT with no cue settings (already centered) is not rewritten."""
original = vtt_file2.read_text()
assert 'align:start position:0%' not in original
assert captions.strip_youtube_caption_positioning(vtt_file2) is False
assert vtt_file2.read_text() == original
def test_strip_youtube_caption_positioning_preserves_deliberate_placement(test_directory):
"""A cue deliberately positioned (with a `line` setting) is not the auto-caption signature; leave it."""
vtt = test_directory / 'deliberate.en.vtt'
content = (
'WEBVTT\n'
'\n'
'00:00:00.000 --> 00:00:02.000 align:start position:0% line:0\n'
'top-left on purpose\n'
'\n'
'00:00:02.000 --> 00:00:04.000 align:start position:0%\n'
'auto-caption line\n'
)
vtt.write_text(content)
changed = captions.strip_youtube_caption_positioning(vtt)
assert changed is True
new_text = vtt.read_text()
# The deliberate `line:0` cue is untouched...
assert '00:00:00.000 --> 00:00:02.000 align:start position:0% line:0' in new_text
# ...while the plain auto-caption cue is centered.
assert '00:00:02.000 --> 00:00:04.000\nauto-caption line' in new_text