initial commit
This commit is contained in:
@@ -0,0 +1 @@
|
||||
"""Shared utilities (config, device, logging, image/video helpers)."""
|
||||
@@ -0,0 +1,51 @@
|
||||
"""Centralised YAML configuration loading and project paths."""
|
||||
from __future__ import annotations
|
||||
|
||||
from functools import lru_cache
|
||||
from pathlib import Path
|
||||
from typing import Any
|
||||
|
||||
import yaml
|
||||
|
||||
PROJECT_ROOT = Path(__file__).resolve().parent.parent
|
||||
CONFIG_DIR = PROJECT_ROOT / "config"
|
||||
_CONFIG_FILES = ("config.yaml", "model_config.yaml")
|
||||
|
||||
|
||||
def _deep_update(base: dict, new: dict) -> dict:
|
||||
for key, value in new.items():
|
||||
if isinstance(value, dict) and isinstance(base.get(key), dict):
|
||||
_deep_update(base[key], value)
|
||||
else:
|
||||
base[key] = value
|
||||
return base
|
||||
|
||||
|
||||
@lru_cache(maxsize=1)
|
||||
def load_config() -> dict[str, Any]:
|
||||
"""Load and merge all YAML config files. The result is cached; do not mutate it."""
|
||||
cfg: dict[str, Any] = {}
|
||||
for name in _CONFIG_FILES:
|
||||
path = CONFIG_DIR / name
|
||||
if not path.exists():
|
||||
raise FileNotFoundError(f"Missing configuration file: {path}")
|
||||
with path.open("r", encoding="utf-8") as fh:
|
||||
_deep_update(cfg, yaml.safe_load(fh) or {})
|
||||
return cfg
|
||||
|
||||
|
||||
def resolve_path(path: str | Path) -> Path:
|
||||
"""Resolve a config path relative to the project root (absolute paths pass through)."""
|
||||
p = Path(path)
|
||||
return p if p.is_absolute() else PROJECT_ROOT / p
|
||||
|
||||
|
||||
def ensure_project_dirs() -> None:
|
||||
"""Create every directory the application writes to."""
|
||||
cfg = load_config()
|
||||
for rel in cfg["paths"].values():
|
||||
resolve_path(rel).mkdir(parents=True, exist_ok=True)
|
||||
for model_cfg in cfg["models"].values():
|
||||
for key in ("cache_dir", "weights_dir"):
|
||||
if key in model_cfg:
|
||||
resolve_path(model_cfg[key]).mkdir(parents=True, exist_ok=True)
|
||||
@@ -0,0 +1,50 @@
|
||||
"""Device selection and CUDA helpers."""
|
||||
from __future__ import annotations
|
||||
|
||||
from utils.logger import get_logger
|
||||
|
||||
logger = get_logger("device")
|
||||
|
||||
|
||||
def resolve_device(requested: str | None = "auto") -> str:
|
||||
"""Map a user choice (auto/cuda/gpu/cpu) to 'cuda' or 'cpu', falling back to CPU."""
|
||||
import torch
|
||||
|
||||
requested = (requested or "auto").strip().lower()
|
||||
if requested in ("auto", "cuda", "gpu") or requested.startswith("cuda"):
|
||||
if torch.cuda.is_available():
|
||||
return "cuda"
|
||||
if requested != "auto":
|
||||
logger.warning("CUDA requested but not available - falling back to CPU.")
|
||||
return "cpu"
|
||||
if requested != "cpu":
|
||||
logger.warning("Unknown device '%s' - using CPU.", requested)
|
||||
return "cpu"
|
||||
|
||||
|
||||
def cuda_sync(device: str) -> None:
|
||||
"""Synchronise CUDA so wall-clock timings include queued GPU work."""
|
||||
import torch
|
||||
|
||||
if device.startswith("cuda") and torch.cuda.is_available():
|
||||
torch.cuda.synchronize()
|
||||
|
||||
|
||||
def is_cuda_oom(exc: BaseException) -> bool:
|
||||
"""True if an exception looks like a CUDA out-of-memory error."""
|
||||
return "out of memory" in str(exc).lower()
|
||||
|
||||
|
||||
def device_info() -> dict:
|
||||
"""Return basic information about the available compute device."""
|
||||
import torch
|
||||
|
||||
info = {"cuda_available": torch.cuda.is_available(), "torch": torch.__version__}
|
||||
if torch.cuda.is_available():
|
||||
props = torch.cuda.get_device_properties(0)
|
||||
info.update(
|
||||
gpu_name=props.name,
|
||||
gpu_total_mb=round(props.total_memory / 1024**2, 1),
|
||||
cuda_version=torch.version.cuda,
|
||||
)
|
||||
return info
|
||||
@@ -0,0 +1,53 @@
|
||||
"""Image loading and resizing helpers."""
|
||||
from __future__ import annotations
|
||||
|
||||
from pathlib import Path
|
||||
|
||||
import cv2
|
||||
import numpy as np
|
||||
|
||||
|
||||
class ImageLoadError(ValueError):
|
||||
"""Raised when an image cannot be read or decoded."""
|
||||
|
||||
|
||||
def validate_extension(filename: str, allowed: list[str] | tuple[str, ...]) -> None:
|
||||
ext = Path(filename).suffix.lower()
|
||||
if ext not in allowed:
|
||||
raise ImageLoadError(f"Unsupported file type '{ext}'. Allowed: {', '.join(allowed)}")
|
||||
|
||||
|
||||
def load_image_rgb(source) -> np.ndarray:
|
||||
"""Load an image from a path, bytes, or file-like object as an RGB uint8 array."""
|
||||
try:
|
||||
if isinstance(source, (str, Path)):
|
||||
data = np.fromfile(str(source), dtype=np.uint8) # unicode-safe on Windows
|
||||
elif isinstance(source, (bytes, bytearray)):
|
||||
data = np.frombuffer(source, dtype=np.uint8)
|
||||
elif hasattr(source, "getvalue"):
|
||||
data = np.frombuffer(source.getvalue(), dtype=np.uint8)
|
||||
elif hasattr(source, "read"):
|
||||
data = np.frombuffer(source.read(), dtype=np.uint8)
|
||||
else:
|
||||
raise ImageLoadError(f"Unsupported image source type: {type(source).__name__}")
|
||||
except OSError as exc:
|
||||
raise ImageLoadError(f"Could not read image file: {exc}") from exc
|
||||
if data.size == 0:
|
||||
raise ImageLoadError("The image file is empty.")
|
||||
bgr = cv2.imdecode(data, cv2.IMREAD_COLOR)
|
||||
if bgr is None:
|
||||
raise ImageLoadError("Could not decode the image - the file is corrupt or not a supported image.")
|
||||
return cv2.cvtColor(bgr, cv2.COLOR_BGR2RGB)
|
||||
|
||||
|
||||
def resize_long_side(image: np.ndarray, max_side: int | None) -> tuple[np.ndarray, float]:
|
||||
"""Downscale so the long side is at most max_side. Returns (image, scale). 0/None disables."""
|
||||
if not max_side or max_side <= 0:
|
||||
return image, 1.0
|
||||
h, w = image.shape[:2]
|
||||
longest = max(h, w)
|
||||
if longest <= max_side:
|
||||
return image, 1.0
|
||||
scale = max_side / float(longest)
|
||||
new_size = (max(1, int(round(w * scale))), max(1, int(round(h * scale))))
|
||||
return cv2.resize(image, new_size, interpolation=cv2.INTER_AREA), scale
|
||||
@@ -0,0 +1,32 @@
|
||||
"""Logging setup: console + logs/app.log."""
|
||||
from __future__ import annotations
|
||||
|
||||
import logging
|
||||
import sys
|
||||
|
||||
_CONFIGURED = False
|
||||
|
||||
|
||||
def get_logger(name: str = "ovd") -> logging.Logger:
|
||||
"""Return a child of the shared 'ovd' logger, configuring handlers once."""
|
||||
global _CONFIGURED
|
||||
if not _CONFIGURED:
|
||||
root = logging.getLogger("ovd")
|
||||
root.setLevel(logging.INFO)
|
||||
root.propagate = False
|
||||
fmt = logging.Formatter("%(asctime)s | %(levelname)s | %(name)s | %(message)s")
|
||||
console = logging.StreamHandler(sys.stdout)
|
||||
console.setFormatter(fmt)
|
||||
root.addHandler(console)
|
||||
try:
|
||||
from utils.config_loader import PROJECT_ROOT
|
||||
|
||||
log_dir = PROJECT_ROOT / "logs"
|
||||
log_dir.mkdir(exist_ok=True)
|
||||
file_handler = logging.FileHandler(log_dir / "app.log", encoding="utf-8")
|
||||
file_handler.setFormatter(fmt)
|
||||
root.addHandler(file_handler)
|
||||
except OSError:
|
||||
pass # read-only filesystem: console logging only
|
||||
_CONFIGURED = True
|
||||
return logging.getLogger(name if name.startswith("ovd") else f"ovd.{name}")
|
||||
@@ -0,0 +1,66 @@
|
||||
"""Video I/O helpers built on OpenCV."""
|
||||
from __future__ import annotations
|
||||
|
||||
import math
|
||||
import shutil
|
||||
import subprocess
|
||||
from pathlib import Path
|
||||
|
||||
import cv2
|
||||
|
||||
from utils.logger import get_logger
|
||||
|
||||
logger = get_logger("video_utils")
|
||||
|
||||
|
||||
class VideoError(RuntimeError):
|
||||
"""Raised for unreadable videos or writer/codec failures."""
|
||||
|
||||
|
||||
def get_video_info(path: str | Path) -> dict:
|
||||
"""Return fps, frame count, size and duration of a video file."""
|
||||
cap = cv2.VideoCapture(str(path))
|
||||
try:
|
||||
if not cap.isOpened():
|
||||
raise VideoError(f"Cannot open video '{Path(path).name}'. The format or codec may be unsupported.")
|
||||
fps = float(cap.get(cv2.CAP_PROP_FPS) or 0.0)
|
||||
frames = int(cap.get(cv2.CAP_PROP_FRAME_COUNT) or 0)
|
||||
width = int(cap.get(cv2.CAP_PROP_FRAME_WIDTH) or 0)
|
||||
height = int(cap.get(cv2.CAP_PROP_FRAME_HEIGHT) or 0)
|
||||
finally:
|
||||
cap.release()
|
||||
if not math.isfinite(fps) or fps <= 0:
|
||||
fps = 25.0
|
||||
logger.warning("Video reports no FPS; assuming 25.")
|
||||
duration = frames / fps if frames > 0 else 0.0
|
||||
return {"fps": fps, "total_frames": frames, "width": width, "height": height, "duration_s": duration}
|
||||
|
||||
|
||||
def create_video_writer(path: str | Path, fps: float, size: tuple[int, int], codecs: list[str]):
|
||||
"""Open a VideoWriter trying each codec in order. Returns (writer, codec_used)."""
|
||||
Path(path).parent.mkdir(parents=True, exist_ok=True)
|
||||
for codec in codecs:
|
||||
writer = cv2.VideoWriter(str(path), cv2.VideoWriter_fourcc(*codec), fps, size)
|
||||
if writer.isOpened():
|
||||
return writer, codec
|
||||
writer.release()
|
||||
logger.warning("Video codec '%s' unavailable; trying next.", codec)
|
||||
raise VideoError(f"Could not create a video writer with any of the codecs {codecs}.")
|
||||
|
||||
|
||||
def reencode_h264(src: str | Path, dst: str | Path) -> bool:
|
||||
"""Re-encode to browser-playable H.264 with ffmpeg, if installed. Returns success."""
|
||||
ffmpeg = shutil.which("ffmpeg")
|
||||
if not ffmpeg:
|
||||
return False
|
||||
cmd = [ffmpeg, "-y", "-loglevel", "error", "-i", str(src), "-c:v", "libx264",
|
||||
"-pix_fmt", "yuv420p", "-movflags", "+faststart", str(dst)]
|
||||
try:
|
||||
proc = subprocess.run(cmd, capture_output=True, text=True, timeout=1800)
|
||||
except (OSError, subprocess.TimeoutExpired) as exc:
|
||||
logger.warning("ffmpeg re-encode failed: %s", exc)
|
||||
return False
|
||||
if proc.returncode != 0:
|
||||
logger.warning("ffmpeg re-encode failed: %s", proc.stderr.strip()[:300])
|
||||
return False
|
||||
return Path(dst).exists() and Path(dst).stat().st_size > 0
|
||||
Reference in New Issue
Block a user