diff --git a/app.py b/app.py index f9588ae..65f6f16 100644 --- a/app.py +++ b/app.py @@ -64,6 +64,22 @@ MIN_SOURCE_SECONDS = int(os.environ.get("MIN_SOURCE_SECONDS", "45")) QUALITY_PROBE_SCRIPT = os.path.join(os.path.dirname(os.path.abspath(__file__)), "quality_probe.py") DISABLE_YOUTUBE_URL = os.environ.get("DISABLE_YOUTUBE_URL", "false").lower() in ("1", "true", "yes") +# Every log line in this module is emoji-prefixed, and a Windows console is +# cp1252 by default. _recover_jobs_from_disk() prints one during startup, so +# without this the server dies before it ever listens: +# +# UnicodeEncodeError: 'charmap' codec can't encode characters in position 0-1 +# ERROR: Application startup failed. Exiting. +# +# subtitles._configure_stdio solved this for the transcription path; the server +# needs it too, and needs it before the first print. +for _stream in (sys.stdout, sys.stderr): + if hasattr(_stream, "reconfigure"): + try: + _stream.reconfigure(encoding="utf-8", errors="replace") + except Exception: + pass + # ---- Cloud billing (paid / managed-keys) integration -------------------------- # All paid-mode code lives in the optional `cloud/` package and is imported ONLY # when BILLING_ENABLED is set. With the flag off, the app behaves exactly as the @@ -1674,9 +1690,18 @@ async def process_endpoint( os.makedirs(job_output_dir, exist_ok=True) # Prepare Command - cmd = ["python", "-u", "main.py"] # -u for unbuffered + # sys.executable, not "python": bare "python" resolves against PATH, which + # outside Docker is whatever interpreter happens to be first — not the venv + # running this server. Every job then dies on `import cv2`. The quality + # probe above already gets this right. + cmd = [sys.executable, "-u", "main.py"] # -u for unbuffered env = os.environ.copy() env["GEMINI_API_KEY"] = api_key # Override with key from request + # The stdio fix above only covers this process. main.py prints an emoji on + # its first line and configures nothing, so on a cp1252 console the child + # still dies before it renders anything -- the server starts and every job + # fails instead. setdefault, so an explicit PYTHONIOENCODING still wins. + env.setdefault("PYTHONIOENCODING", "utf-8") # Optional layouts are per job. The renderer reads these at import time in # the subprocess, so they must be set before Popen — same path WATERMARK diff --git a/ffmpeg_utils.py b/ffmpeg_utils.py index 26621b0..b398513 100644 --- a/ffmpeg_utils.py +++ b/ffmpeg_utils.py @@ -154,3 +154,23 @@ def video_encode_args(tier=QUALITY): f"(FFMPEG_ENCODER={mode})") return list((_NVENC_ARGS if use_nvenc else _X264_ARGS)[tier]) + + +def escape_filter_value(value): + r"""Escape a path/value for use inside a quoted FFmpeg filter argument. + + Windows absolute paths are why this exists: ``:`` separates filter options, + so an interpolated ``C:/x/y.txt`` makes the parser look for an option named + ``/x/y.txt`` and the whole filtergraph fails to build. + + NOTE: an apostrophe in the path cannot be made safe here. ffmpeg's + filtergraph parser is not a shell -- the shell idiom ``'\''`` was tried on + 29-jul-2026 and is worse than doing nothing: it drops the apostrophe AND + swallows the following option, so ``ass='...Earth'\''s.ass':fontsdir='...'`` + resolved to a filename of "...Earths.ass:fontsdir=..." and failed to open. + + The only reliable answer is to keep apostrophes OUT of any path that is + interpolated into a filter. Callers generate their own filenames, so they + control this: use a neutral name, never one derived from a video title. + """ + return value.replace('\\', '/').replace(':', '\\:').replace("'", "\\'") diff --git a/main.py b/main.py index 32d6fa1..6e5db1e 100644 --- a/main.py +++ b/main.py @@ -1093,7 +1093,9 @@ def process_video_to_vertical(input_video, final_output_video, aspect_ratio=ASPE silent_video_path = stem + ".v1video.mp4" audio_track_path = stem + ".v1audio.aac" for stale in (silent_video_path, audio_track_path, final_output_video): - if os.path.exists(stale): + # isfile, not exists: a caller that hands us a directory should not + # take an EACCES here, and must never have it deleted either. + if os.path.isfile(stale): os.remove(stale) print(f"🎬 Processing clip: {input_video}") @@ -1591,7 +1593,13 @@ if __name__ == '__main__': # 2. Decision: Analyze clips or process whole? if args.skip_analysis: print("⏩ Skipping analysis, processing entire video...") - output_file = args.output if args.output else os.path.join(output_dir, f"{video_title}_vertical.mp4") + # --output is documented as "directory or file". When it names a + # directory we still need a filename: passing the directory through + # ends up in os.remove() on it further down and dies with EACCES. + output_file = args.output + if (not output_file or os.path.isdir(output_file) + or output_file.endswith(("/", os.sep))): + output_file = os.path.join(output_dir, f"{video_title}_vertical.mp4") render_clip(input_video, output_file, output_format) else: # Get duration (needed by both the transcript and the vision path). diff --git a/reframe_v2.py b/reframe_v2.py index c12be39..0f180bd 100644 --- a/reframe_v2.py +++ b/reframe_v2.py @@ -26,7 +26,8 @@ import camera_inset import punch_in import screencast_layout import split_layout -from ffmpeg_utils import video_encode_args, QUALITY_FAST, METADATA_SCRUB +from ffmpeg_utils import (video_encode_args, escape_filter_value, QUALITY_FAST, + METADATA_SCRUB) ANALYSIS_MAX_WIDTH = 640 @@ -522,7 +523,7 @@ def render(input_video, final_output_video, aspect_ratio, content_ranges=None, with open(cmd_path, "w") as f: f.write("\n".join(lines) + "\n") graph = ( - f"[0:v]sendcmd=f='{cmd_path}'," + f"[0:v]sendcmd=f='{escape_filter_value(cmd_path)}'," f"crop@c={init}," f"scale={out_w}:{out_h},setsar=1[v]" ) diff --git a/subtitles.py b/subtitles.py index baab575..4e8c0e0 100644 --- a/subtitles.py +++ b/subtitles.py @@ -3,7 +3,8 @@ import re import subprocess import sys -from ffmpeg_utils import video_encode_args, QUALITY, METADATA_SCRUB +from ffmpeg_utils import (video_encode_args, escape_filter_value, QUALITY, + METADATA_SCRUB) _STDIO_CONFIGURED = False @@ -100,8 +101,12 @@ def _escape_ffmpeg_filter_value(value): interpolated into a filter. Callers generate their own subtitle filenames, so they control this: use a neutral name (``subs__.ass``), never one derived from a video title. + + The implementation now lives in ffmpeg_utils so the reframe engine can use + it too: it was building `sendcmd=f=''` unescaped, which is the + same bug this function was written for. """ - return value.replace('\\', '/').replace(':', '\\:').replace("'", "\\'") + return escape_filter_value(value) def _normalize_subtitle_word(value):