NINA / compress.py
Malina
Claude Fable 5.1
v0.90: scoped single-use tokens, hardened link fetch, 45-minute cap, whole-video digest, one classification call, no OCR
1d697a7
Raw History Blame
3.52 kB
# ─────────────────────────────────────────────
# NINA β€” server-side upload guard + compression
# ─────────────────────────────────────────────
# The website already rejects > MAX_UPLOAD_MB and best-effort compresses before
# upload, but the client check is bypassable (direct API calls) and browser
# compression is skipped for long clips. So we re-check the size here and, for
# anything still large, transcode it down with ffmpeg before the heavy pipeline
# touches it. NINA only needs the audio plus a handful of sampled frames, so an
# aggressive 720p / low-bitrate re-encode costs nothing in quality and speeds up
# decode + CLIP frame extraction on big files.
#
# Everything here is best-effort: on any failure (no ffmpeg, odd container,
# timeout) we return the original path and let the pipeline carry on.
import os
import shutil
import subprocess
import tempfile
from cache import register_tmp
from config import (
COMPRESS_AUDIO_BITRATE, COMPRESS_TARGET_HEIGHT, COMPRESS_TRIGGER_MB,
COMPRESS_VIDEO_BITRATE, MAX_UPLOAD_MB,
)
def file_mb(path: str) -> float:
"""Size of a file in MB, or 0.0 if it doesn't exist."""
try:
return os.path.getsize(path) / (1024 * 1024)
except OSError:
return 0.0
def too_large(path: str) -> bool:
"""True if the upload exceeds the hard cap and must be rejected."""
return file_mb(path) > MAX_UPLOAD_MB
def ensure_compressed(path: str) -> str:
"""Return a path to a download-sized version of `path`.
If the file is under the trigger size (or ffmpeg is unavailable, or the
re-encode fails or doesn't actually shrink it), the original path is returned
unchanged. Otherwise a new temp MP4 (≀720p, H.264 + AAC) is written and its
path returned.
"""
try:
size = file_mb(path)
if size <= COMPRESS_TRIGGER_MB:
return path
if not shutil.which("ffmpeg"):
print("[NINA] ffmpeg not found β€” skipping server-side compression.")
return path
fd, out = tempfile.mkstemp(prefix="nina_compressed_", suffix=".mp4")
os.close(fd)
register_tmp(out) # deleted by cache.evict_stale once the reuse window passes
# scale=-2:min(720,ih) β†’ cap height at 720, keep aspect ratio, even dims.
# The comma inside min() must be escaped so the filtergraph parser doesn't
# read it as a filter separator.
vf = f"scale=-2:'min({COMPRESS_TARGET_HEIGHT}\\,ih)'"
cmd = [
"ffmpeg", "-y", "-i", path,
"-vf", vf,
"-c:v", "libx264", "-preset", "veryfast", "-b:v", COMPRESS_VIDEO_BITRATE,
"-c:a", "aac", "-b:a", COMPRESS_AUDIO_BITRATE,
"-movflags", "+faststart",
"-loglevel", "error",
out,
]
subprocess.run(cmd, check=True, timeout=600)
new_size = file_mb(out)
if 0 < new_size < size:
print(f"[NINA] Server-side compression: {size:.1f} MB β†’ {new_size:.1f} MB.")
return out
# Didn't help (already small / re-encode grew it) β€” discard and keep original.
try:
os.remove(out)
except OSError:
pass
return path
except Exception as exc:
print(f"[NINA] Server-side compression skipped: {exc}")
return path