fix(files): bound filenames by bytes, not characters
/api/hook has been returning 500 in prod on any clip whose video title is non-Latin: OSError 36, "File name too long". sanitize_filename() capped the title at 100 CHARACTERS, but filesystems cap a name at 255 BYTES, and one Bengali or Arabic character costs three — so a title was already ~300 bytes before the pipeline decorated it. Every derived name stacks on that stem: "_clip_10.mp4", "subtitled_<ts>_", "temp_hook_<hex8>_", "autosubs_<ts>_.ass". Shipping captions by default added one more layer, which is what pushed the borderline cases over and surfaced it. - sanitize_filename now trims to MAX_TITLE_BYTES (120) via truncate_bytes(), which never splits a multi-byte character. 120 leaves room for every decoration stacked and still lands well under 255. - The hook overlay stopped embedding the full source name: its uuid already guarantees uniqueness, so the name rides along only as a debugging hint and is trimmed to 80 bytes. Deliberately NOT trimmed: the auto-caption output, which must stay exactly "subtitled_<ts>_<clip filename>" because the subtitle modal's walk-back and _canonical_clip_file both reconstruct the clean original from it. Length is bounded upstream instead; a legacy clip that predates the budget raises OSError 36, which the existing guard turns into "ship it uncaptioned".
This commit is contained in:
parent
28a1f6aef2
commit
bedecdc850
3 changed files with 112 additions and 3 deletions
20
hooks.py
20
hooks.py
|
|
@ -8,6 +8,18 @@ from PIL import Image, ImageDraw, ImageFont, ImageFilter
|
||||||
|
|
||||||
from ffmpeg_utils import video_encode_args, QUALITY, METADATA_SCRUB
|
from ffmpeg_utils import video_encode_args, QUALITY, METADATA_SCRUB
|
||||||
|
|
||||||
|
|
||||||
|
def _truncate_bytes(text, max_bytes):
|
||||||
|
"""Trim to a byte budget without splitting a multi-byte character.
|
||||||
|
|
||||||
|
Deliberately duplicated from main.truncate_bytes: this module stays free of
|
||||||
|
main's heavy imports (cv2, mediapipe, torch) so it can be used standalone.
|
||||||
|
"""
|
||||||
|
encoded = text.encode("utf-8")
|
||||||
|
if len(encoded) <= max_bytes:
|
||||||
|
return text
|
||||||
|
return encoded[:max_bytes].decode("utf-8", "ignore")
|
||||||
|
|
||||||
FONT_URL = "https://github.com/googlefonts/noto-fonts/raw/main/hinted/ttf/NotoSerif/NotoSerif-Bold.ttf"
|
FONT_URL = "https://github.com/googlefonts/noto-fonts/raw/main/hinted/ttf/NotoSerif/NotoSerif-Bold.ttf"
|
||||||
FONT_DIR = "fonts"
|
FONT_DIR = "fonts"
|
||||||
FONT_PATH = os.path.join(FONT_DIR, "NotoSerif-Bold.ttf")
|
FONT_PATH = os.path.join(FONT_DIR, "NotoSerif-Bold.ttf")
|
||||||
|
|
@ -338,7 +350,13 @@ def add_hook_to_video(video_path, text, output_path, position="top", font_scale=
|
||||||
target_box_width = int(video_width * 0.9)
|
target_box_width = int(video_width * 0.9)
|
||||||
|
|
||||||
# Unique per invocation so parallel jobs can't overwrite each other's overlay.
|
# Unique per invocation so parallel jobs can't overwrite each other's overlay.
|
||||||
hook_filename = f"temp_hook_{uuid.uuid4().hex[:8]}_{os.path.basename(video_path)}.png"
|
# The uuid alone guarantees that; the source name rides along only as a
|
||||||
|
# debugging hint, so it is trimmed by BYTES (filesystems cap at 255 bytes,
|
||||||
|
# and one Bengali or Arabic character costs three). Embedding it untrimmed
|
||||||
|
# raised OSError 36 and killed the endpoint in prod on 26-jul-2026.
|
||||||
|
stem = os.path.splitext(os.path.basename(video_path))[0]
|
||||||
|
hook_filename = (f"temp_hook_{uuid.uuid4().hex[:8]}_"
|
||||||
|
f"{_truncate_bytes(stem, 80)}.png")
|
||||||
|
|
||||||
try:
|
try:
|
||||||
img_path, box_w, box_h = create_hook_image(text, target_box_width, hook_filename, font_scale=font_scale, style=style)
|
img_path, box_w, box_h = create_hook_image(text, target_box_width, hook_filename, font_scale=font_scale, style=style)
|
||||||
|
|
|
||||||
31
main.py
31
main.py
|
|
@ -514,11 +514,31 @@ def get_video_resolution(video_path):
|
||||||
return width, height
|
return width, height
|
||||||
|
|
||||||
|
|
||||||
|
# Byte budget for the sanitized video title used as the stem of every derived
|
||||||
|
# file. Filesystems cap a name in BYTES (255 on ext4), not characters, and the
|
||||||
|
# pipeline decorates this stem: "_clip_10.mp4" (12), "subtitled_<ts>_" (21),
|
||||||
|
# "temp_hook_<hex8>_" (19), "autosubs_<ts>_" + ".ass" (24). Budgeting 120 bytes
|
||||||
|
# leaves room for all of them stacked and still lands well under the limit.
|
||||||
|
#
|
||||||
|
# The old cap was 100 CHARACTERS, which is 300 bytes of Bengali or Arabic — over
|
||||||
|
# the limit before any decoration. It surfaced as OSError 36 killing the hook
|
||||||
|
# endpoint in prod on 26-jul-2026.
|
||||||
|
MAX_TITLE_BYTES = 120
|
||||||
|
|
||||||
|
|
||||||
|
def truncate_bytes(text, max_bytes):
|
||||||
|
"""Trim ``text`` to a byte budget without splitting a multi-byte character."""
|
||||||
|
encoded = text.encode("utf-8")
|
||||||
|
if len(encoded) <= max_bytes:
|
||||||
|
return text
|
||||||
|
return encoded[:max_bytes].decode("utf-8", "ignore")
|
||||||
|
|
||||||
|
|
||||||
def sanitize_filename(filename):
|
def sanitize_filename(filename):
|
||||||
"""Remove invalid characters from filename."""
|
"""Remove invalid characters from filename and bound it for the filesystem."""
|
||||||
filename = re.sub(r'[<>:"/\\|?*#]', '', filename)
|
filename = re.sub(r'[<>:"/\\|?*#]', '', filename)
|
||||||
filename = filename.replace(' ', '_')
|
filename = filename.replace(' ', '_')
|
||||||
return filename[:100]
|
return truncate_bytes(filename, MAX_TITLE_BYTES)
|
||||||
|
|
||||||
|
|
||||||
def download_youtube_video(url, output_dir="."):
|
def download_youtube_video(url, output_dir="."):
|
||||||
|
|
@ -752,6 +772,13 @@ def auto_caption_clip(clip_path, transcript, clip_start, clip_end):
|
||||||
output_dir = os.path.dirname(clip_path)
|
output_dir = os.path.dirname(clip_path)
|
||||||
stem = os.path.basename(clip_path)
|
stem = os.path.basename(clip_path)
|
||||||
generation_id = int(time.time())
|
generation_id = int(time.time())
|
||||||
|
# The output name MUST stay exactly "subtitled_<ts>_<clip filename>":
|
||||||
|
# the modal's walk-back and _canonical_clip_file both reconstruct the
|
||||||
|
# clean original from it, so trimming the stem here would orphan the
|
||||||
|
# pair. Length is bounded upstream instead, by MAX_TITLE_BYTES at
|
||||||
|
# download time. A legacy clip whose name predates that budget can still
|
||||||
|
# overflow — that raises OSError 36, which the except below turns into
|
||||||
|
# "ship the clip uncaptioned" rather than a broken filename.
|
||||||
ass_path = os.path.join(output_dir, f"autosubs_{generation_id}_{stem}.ass")
|
ass_path = os.path.join(output_dir, f"autosubs_{generation_id}_{stem}.ass")
|
||||||
out_path = os.path.join(output_dir, f"subtitled_{generation_id}_{stem}")
|
out_path = os.path.join(output_dir, f"subtitled_{generation_id}_{stem}")
|
||||||
|
|
||||||
|
|
|
||||||
64
tests/test_filename_limits.py
Normal file
64
tests/test_filename_limits.py
Normal file
|
|
@ -0,0 +1,64 @@
|
||||||
|
"""Filenames must fit the filesystem, which counts BYTES, not characters.
|
||||||
|
|
||||||
|
Regression cover for OSError 36 ("File name too long") killing /api/hook in
|
||||||
|
prod on 26-jul-2026: a Bengali video title passed the 100-CHARACTER cap while
|
||||||
|
already being ~300 bytes, and the derived temp name pushed it further.
|
||||||
|
"""
|
||||||
|
import pytest
|
||||||
|
|
||||||
|
main = pytest.importorskip("main") # cv2 etc., absent in minimal CI
|
||||||
|
hooks = pytest.importorskip("hooks")
|
||||||
|
|
||||||
|
# ext4/APFS cap a single name at 255 bytes.
|
||||||
|
FS_LIMIT = 255
|
||||||
|
BENGALI = "মজার_ধাঁধা_শুনুন_আর_হাসুন_সকাল_হলেই_কার_মাথা_হারিয়ে_যায়কমেডি_ভিডিও"
|
||||||
|
|
||||||
|
|
||||||
|
class TestTruncateBytes:
|
||||||
|
def test_short_text_untouched(self):
|
||||||
|
assert main.truncate_bytes("hello", 100) == "hello"
|
||||||
|
|
||||||
|
def test_trims_to_the_byte_budget(self):
|
||||||
|
out = main.truncate_bytes(BENGALI * 5, 120)
|
||||||
|
assert len(out.encode("utf-8")) <= 120
|
||||||
|
|
||||||
|
def test_never_splits_a_multibyte_character(self):
|
||||||
|
# Budget deliberately lands mid-character.
|
||||||
|
for budget in range(1, 40):
|
||||||
|
out = main.truncate_bytes(BENGALI, budget)
|
||||||
|
out.encode("utf-8").decode("utf-8") # must not raise
|
||||||
|
assert len(out.encode("utf-8")) <= budget
|
||||||
|
|
||||||
|
def test_ascii_is_unaffected_by_the_byte_rule(self):
|
||||||
|
text = "a" * 200
|
||||||
|
assert main.truncate_bytes(text, 120) == "a" * 120
|
||||||
|
|
||||||
|
|
||||||
|
class TestSanitizeFilename:
|
||||||
|
def test_non_latin_title_fits_the_budget(self):
|
||||||
|
out = main.sanitize_filename(BENGALI * 4)
|
||||||
|
assert len(out.encode("utf-8")) <= main.MAX_TITLE_BYTES
|
||||||
|
|
||||||
|
def test_leaves_room_for_every_decoration_the_pipeline_adds(self):
|
||||||
|
# Worst case actually produced: a hook overlay built on top of an
|
||||||
|
# auto-captioned clip of a long-titled video.
|
||||||
|
stem = main.sanitize_filename(BENGALI * 4)
|
||||||
|
clip = f"{stem}_clip_10.mp4"
|
||||||
|
captioned = f"subtitled_1785060039_{clip}"
|
||||||
|
hook_png = f"temp_hook_abcd1234_{captioned}.png"
|
||||||
|
assert len(hook_png.encode("utf-8")) < FS_LIMIT, len(hook_png.encode("utf-8"))
|
||||||
|
|
||||||
|
def test_still_strips_unsafe_characters(self):
|
||||||
|
assert main.sanitize_filename('a<b>c:d"e/f\\g|h?i*j#k') == "abcdefghijk"
|
||||||
|
assert main.sanitize_filename("with spaces") == "with_spaces"
|
||||||
|
|
||||||
|
def test_the_old_character_cap_would_have_overflowed(self):
|
||||||
|
# Documents why the rule changed: 100 chars of Bengali is ~300 bytes.
|
||||||
|
assert len((BENGALI * 4)[:100].encode("utf-8")) > FS_LIMIT
|
||||||
|
|
||||||
|
|
||||||
|
class TestHookTempName:
|
||||||
|
def test_hook_helper_trims_by_bytes(self):
|
||||||
|
out = hooks._truncate_bytes(BENGALI * 5, 80)
|
||||||
|
assert len(out.encode("utf-8")) <= 80
|
||||||
|
out.encode("utf-8").decode("utf-8")
|
||||||
Loading…
Reference in a new issue