diff --git a/hooks.py b/hooks.py index 26ae652..196fa7e 100644 --- a/hooks.py +++ b/hooks.py @@ -8,6 +8,18 @@ from PIL import Image, ImageDraw, ImageFont, ImageFilter 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_DIR = "fonts" 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) # 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: img_path, box_w, box_h = create_hook_image(text, target_box_width, hook_filename, font_scale=font_scale, style=style) diff --git a/main.py b/main.py index f744e44..3d0ddb9 100644 --- a/main.py +++ b/main.py @@ -514,11 +514,31 @@ def get_video_resolution(video_path): 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__" (21), +# "temp_hook__" (19), "autosubs__" + ".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): - """Remove invalid characters from filename.""" + """Remove invalid characters from filename and bound it for the filesystem.""" filename = re.sub(r'[<>:"/\\|?*#]', '', filename) filename = filename.replace(' ', '_') - return filename[:100] + return truncate_bytes(filename, MAX_TITLE_BYTES) 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) stem = os.path.basename(clip_path) generation_id = int(time.time()) + # The output name MUST stay exactly "subtitled__": + # 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") out_path = os.path.join(output_dir, f"subtitled_{generation_id}_{stem}") diff --git a/tests/test_filename_limits.py b/tests/test_filename_limits.py new file mode 100644 index 0000000..bde4326 --- /dev/null +++ b/tests/test_filename_limits.py @@ -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('ac: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")