Files
Kronic-Krusaders/thumbnail_worker.py
T
2026-11-25 20:20:27 -06:00

285 lines
7.5 KiB
Python

from __future__ import annotations
import hashlib
import json
import os
import subprocess
import time
from pathlib import Path
from dotenv import load_dotenv
BASE_DIR = Path(__file__).resolve().parent
load_dotenv(BASE_DIR / "config.env")
FFMPEG_BIN = os.getenv("FFMPEG_BIN", "/usr/bin/ffmpeg")
THUMBNAIL_DIR = Path(
os.getenv("THUMBNAIL_DIR", str(BASE_DIR / "thumbnails"))
).expanduser().resolve()
THUMBNAIL_DIR.mkdir(parents=True, exist_ok=True)
# A failed source is retried automatically when its size or mtime changes.
_FAILURE_SUFFIX = ".failed.json"
# These errors mean the input itself could not be opened/parsed. Retrying at a
# different timestamp cannot possibly help and just creates duplicate log spam.
_FATAL_INPUT_ERRORS = (
"ebml header parsing failed",
"invalid as first byte of an ebml number",
"invalid data found when processing input",
"error opening input",
"error opening input file",
"error opening input files",
"moov atom not found",
"invalid atom size",
)
def _key_text(key_path) -> str:
return str(key_path)
def _thumbnail_hash(key_path) -> str:
return hashlib.sha1(
_key_text(key_path).encode("utf-8", "surrogatepass")
).hexdigest()
def get_thumbnail_path(key_path) -> Path:
return THUMBNAIL_DIR / f"{_thumbnail_hash(key_path)}.jpg"
def _failure_path(key_path) -> Path:
return THUMBNAIL_DIR / f"{_thumbnail_hash(key_path)}{_FAILURE_SUFFIX}"
def _source_fingerprint(path: Path) -> dict:
try:
stat = path.stat()
return {
"path": str(path),
"size": int(stat.st_size),
"mtime_ns": int(stat.st_mtime_ns),
}
except OSError:
return {
"path": str(path),
"size": -1,
"mtime_ns": -1,
}
def _load_failure(key_path):
marker = _failure_path(key_path)
try:
return json.loads(marker.read_text(encoding="utf-8"))
except Exception:
return None
def _failure_still_valid(source_path: Path, key_path) -> bool:
failure = _load_failure(key_path)
if not failure:
return False
current = _source_fingerprint(source_path)
previous = failure.get("fingerprint") or {}
return (
current.get("path") == previous.get("path")
and current.get("size") == previous.get("size")
and current.get("mtime_ns") == previous.get("mtime_ns")
)
def _write_failure(source_path: Path, key_path, error_text: str):
marker = _failure_path(key_path)
payload = {
"fingerprint": _source_fingerprint(source_path),
"failed_at": int(time.time()),
"error": str(error_text or "")[-4000:],
}
temp = marker.with_suffix(marker.suffix + ".tmp")
try:
temp.write_text(
json.dumps(payload, ensure_ascii=False, indent=2),
encoding="utf-8",
)
os.replace(temp, marker)
except OSError:
try:
temp.unlink(missing_ok=True)
except OSError:
pass
def _clear_failure(key_path):
try:
_failure_path(key_path).unlink(missing_ok=True)
except OSError:
pass
def _looks_like_obviously_invalid_matroska(path: Path):
"""
MKV/WebM files begin with the EBML magic 1A 45 DF A3.
We only use this quick check for .mkv/.webm because it is deterministic
and avoids spawning FFmpeg for a file that starts with zeros or other
obviously invalid data.
It is intentionally conservative: all other media types continue to
FFmpeg normally.
"""
if path.suffix.lower() not in {".mkv", ".webm"}:
return False, ""
try:
with path.open("rb") as handle:
header = handle.read(4)
except OSError as error:
return True, f"could not read source file: {error}"
if len(header) < 4:
return True, "file is too small to contain an EBML header"
if header != b"\x1a\x45\xdf\xa3":
return True, (
"invalid MKV/WebM EBML header "
f"(first bytes: {header.hex(' ')})"
)
return False, ""
def _fatal_input_error(stderr_text: str) -> bool:
text = str(stderr_text or "").lower()
return any(pattern in text for pattern in _FATAL_INPUT_ERRORS)
def _capture(source_path: Path, output_path: Path, seek_seconds: int):
command = [
FFMPEG_BIN,
"-hide_banner",
"-loglevel",
"error",
"-ss",
str(int(seek_seconds)),
"-i",
str(source_path),
"-frames:v",
"1",
"-vf",
"scale=480:-2",
"-q:v",
"3",
"-y",
str(output_path),
]
result = subprocess.run(
command,
stdout=subprocess.DEVNULL,
stderr=subprocess.PIPE,
text=True,
errors="replace",
)
if result.returncode == 0 and output_path.is_file():
try:
if output_path.stat().st_size > 0:
return True, ""
except OSError:
pass
try:
output_path.unlink(missing_ok=True)
except OSError:
pass
return False, (result.stderr or "").strip()
def generate_thumbnail(
source_path,
*,
key_path=None,
):
"""
Generate and return the JPEG thumbnail path, or None.
Compatibility:
generate_thumbnail(path)
generate_thumbnail(path, key_path=original_library_path)
Failed media is remembered persistently until the source file changes.
"""
source = Path(source_path).expanduser()
key = key_path if key_path is not None else source_path
output = get_thumbnail_path(key)
if output.is_file():
return output
# If this exact source version already failed, do not run FFmpeg again.
if _failure_still_valid(source, key):
return None
if not source.is_file():
message = "source file does not exist"
_write_failure(source, key, message)
print(
f"[THUMBNAIL] Skipping {source}: {message}",
flush=True,
)
return None
# Cheap deterministic guard for the exact failure shown in the logs:
# 00 00 ... instead of the MKV EBML header.
invalid, reason = _looks_like_obviously_invalid_matroska(source)
if invalid:
_write_failure(source, key, reason)
print(
f"[THUMBNAIL] Skipping invalid media {source}: {reason}",
flush=True,
)
return None
# Normal first attempt.
ok, error = _capture(source, output, 5)
if ok:
_clear_failure(key)
return output
# If FFmpeg could not even parse/open the input, seeking to 60 seconds
# cannot fix it. Persist the failure immediately.
if _fatal_input_error(error):
_write_failure(source, key, error)
summary = error.splitlines()[-1] if error else "invalid media input"
print(
f"[THUMBNAIL] Invalid media {source}: {summary}",
flush=True,
)
return None
# Some valid files have black/empty/opening frames at 5 seconds, so retain
# the original 60-second fallback for ordinary decode/capture failures.
ok60, error60 = _capture(source, output, 60)
if ok60:
_clear_failure(key)
return output
final_error = error60 or error or "thumbnail capture failed"
_write_failure(source, key, final_error)
# One concise log entry instead of subprocess traceback + a second wall of
# FFmpeg diagnostics every scan.
summary = final_error.splitlines()[-1] if final_error else "unknown error"
print(
f"[THUMBNAIL] Failed {source}: {summary}",
flush=True,
)
return None