import fcntl import os import time import zipfile from pathlib import Path from typing import Dict, Iterable import numpy as np STATUS_FIELDS = [ "sign_language", "title", "duration_sec", "start_sec", "end_sec", "subtitle_languages", "subtitle_dir_path", "subtitle_en_source", "raw_video_path", "raw_metadata_path", "metadata_status", "subtitle_status", "download_status", "process_status", "upload_status", "local_cleanup_status", "archive_name", "last_error", "updated_at", ] def _lock_path(stats_path: Path) -> Path: return stats_path.with_suffix(stats_path.suffix + ".lock") def _load_stats_unlocked(stats_path: Path) -> Dict[str, Dict[str, str]]: if not stats_path.exists() or stats_path.stat().st_size == 0: return {} stats: Dict[str, Dict[str, str]] = {} with np.load(stats_path, allow_pickle=True) as data: video_ids = [str(item) for item in data.get("video_ids", np.asarray([], dtype=object)).tolist()] for index, video_id in enumerate(video_ids): record = {} for field in STATUS_FIELDS: values = data.get(field) record[field] = str(values[index]) if values is not None and index < len(values) else "" stats[video_id] = record return stats def load_stats(stats_path: Path, retries: int = 8, retry_delay: float = 0.2) -> Dict[str, Dict[str, str]]: if not stats_path.exists(): return {} lock_path = _lock_path(stats_path) lock_path.parent.mkdir(parents=True, exist_ok=True) last_error: Exception | None = None for _ in range(retries): with lock_path.open("a+", encoding="utf-8") as handle: fcntl.flock(handle.fileno(), fcntl.LOCK_SH) try: return _load_stats_unlocked(stats_path) except (EOFError, ValueError, OSError, zipfile.BadZipFile) as exc: last_error = exc finally: fcntl.flock(handle.fileno(), fcntl.LOCK_UN) time.sleep(retry_delay) if last_error is not None: raise last_error return {} def save_stats(stats_path: Path, stats: Dict[str, Dict[str, str]]) -> None: stats_path.parent.mkdir(parents=True, exist_ok=True) video_ids = sorted(stats) payload = {"video_ids": np.asarray(video_ids, dtype=object)} for field in STATUS_FIELDS: payload[field] = np.asarray([stats[video_id].get(field, "") for video_id in video_ids], dtype=object) tmp_path = stats_path.parent / f".{stats_path.stem}.{os.getpid()}.tmp.npz" np.savez(tmp_path, **payload) os.replace(tmp_path, stats_path) def ensure_record(stats: Dict[str, Dict[str, str]], video_id: str) -> Dict[str, str]: if video_id not in stats: stats[video_id] = {field: "" for field in STATUS_FIELDS} return stats[video_id] def update_video_stats(stats_path: Path, video_id: str, **updates: str) -> Dict[str, str]: lock_path = _lock_path(stats_path) lock_path.parent.mkdir(parents=True, exist_ok=True) with lock_path.open("a+", encoding="utf-8") as handle: fcntl.flock(handle.fileno(), fcntl.LOCK_EX) stats = _load_stats_unlocked(stats_path) record = ensure_record(stats, video_id) for key, value in updates.items(): if key in STATUS_FIELDS: record[key] = "" if value is None else str(value) save_stats(stats_path, stats) fcntl.flock(handle.fileno(), fcntl.LOCK_UN) return dict(record) def update_many_video_stats(stats_path: Path, video_ids: Iterable[str], **updates: str) -> None: lock_path = _lock_path(stats_path) lock_path.parent.mkdir(parents=True, exist_ok=True) with lock_path.open("a+", encoding="utf-8") as handle: fcntl.flock(handle.fileno(), fcntl.LOCK_EX) stats = _load_stats_unlocked(stats_path) for video_id in video_ids: record = ensure_record(stats, video_id) for key, value in updates.items(): if key in STATUS_FIELDS: record[key] = "" if value is None else str(value) save_stats(stats_path, stats) fcntl.flock(handle.fileno(), fcntl.LOCK_UN) def update_many_video_stats_with_retry(stats_path: Path, video_ids: Iterable[str], retries: int = 8, retry_delay: float = 0.2, **updates: str) -> None: last_error: Exception | None = None for _ in range(retries): try: update_many_video_stats(stats_path, video_ids, **updates) return except (EOFError, ValueError, OSError, zipfile.BadZipFile) as exc: last_error = exc time.sleep(retry_delay) if last_error is not None: raise last_error