Files
jellyfin-scene-search/scene_search/jellyfin.py
T

352 lines
11 KiB
Python

from __future__ import annotations
import hashlib
import io
import json
import math
from dataclasses import dataclass
from pathlib import Path
from typing import Any
import requests
from PIL import Image
ITEM_DETAIL_FIELDS = "Path,MediaSources,Tags,Trickplay,Etag"
@dataclass(frozen=True)
class TrickplaySelection:
media_source_id: str | None
width: int
height: int
interval_ms: int
thumbnail_count: int
tile_columns: int
tile_rows: int
@property
def thumbnails_per_sheet(self) -> int:
return self.tile_columns * self.tile_rows
class JellyfinClient:
def __init__(self, url: str, api_key: str, timeout_seconds: int = 60) -> None:
if not url:
raise RuntimeError("JELLYFIN_URL is not configured")
if not api_key:
raise RuntimeError("JELLYFIN_API_KEY is not configured")
self.url = url.rstrip("/")
self.timeout_seconds = timeout_seconds
self.session = requests.Session()
self.session.headers.update({
"X-Emby-Token": api_key,
"Authorization": f'MediaBrowser Token="{api_key}"',
"Accept": "application/json",
})
def _get(self, path: str, *, params: dict[str, Any] | None = None) -> requests.Response:
response = self.session.get(
f"{self.url}{path}",
params=params,
timeout=self.timeout_seconds,
)
if not response.ok:
raise RuntimeError(
f"Jellyfin {response.status_code} GET {path}: {response.text[:500]}"
)
return response
def system_info(self) -> dict[str, Any]:
return self._get("/System/Info").json()
def media_folders(self) -> list[dict[str, Any]]:
data = self._get("/Library/MediaFolders").json()
return list(data.get("Items") or [])
def find_library(self, name: str) -> dict[str, Any]:
libraries = self.media_folders()
matches = [
item
for item in libraries
if str(item.get("Name") or "").casefold() == name.casefold()
]
if not matches:
available = ", ".join(
sorted(str(item.get("Name") or item.get("Id")) for item in libraries)
)
raise RuntimeError(
f"Jellyfin library {name!r} not found. Available: {available or 'none'}"
)
return matches[0]
def items(
self,
library_id: str,
*,
limit: int | None = None,
) -> list[dict[str, Any]]:
results: list[dict[str, Any]] = []
start = 0
page_size = 200
while limit is None or len(results) < limit:
request_limit = page_size
if limit is not None:
request_limit = min(request_limit, limit - len(results))
if request_limit <= 0:
break
data = self._get(
"/Items",
params={
"ParentId": library_id,
"Recursive": "true",
"IncludeItemTypes": "Movie,Episode,Video",
"Fields": ITEM_DETAIL_FIELDS,
"EnableTotalRecordCount": "true",
"StartIndex": start,
"Limit": request_limit,
},
).json()
page = list(data.get("Items") or [])
if not page:
break
results.extend(page)
start += len(page)
total = int(data.get("TotalRecordCount") or len(results))
if start >= total or len(page) < request_limit:
break
return results[:limit] if limit is not None else results
def item_count(self, library_id: str) -> int:
data = self._get(
"/Items",
params={
"ParentId": library_id,
"Recursive": "true",
"IncludeItemTypes": "Movie,Episode,Video",
"EnableTotalRecordCount": "true",
"StartIndex": 0,
"Limit": 1,
},
).json()
return int(data.get("TotalRecordCount") or 0)
def item(self, item_id: str) -> dict[str, Any]:
data = self._get(
"/Items",
params={
"Ids": item_id,
"Recursive": "true",
"Fields": ITEM_DETAIL_FIELDS,
"EnableTotalRecordCount": "false",
"Limit": 1,
},
).json()
items = list(data.get("Items") or [])
if not items:
raise RuntimeError(f"Jellyfin item not found: {item_id}")
return items[0]
@staticmethod
def select_trickplay(
item: dict[str, Any],
preferred_width: int = 320,
preferred_media_source_id: str | None = None,
) -> TrickplaySelection | None:
manifest = item.get("Trickplay") or {}
candidates: list[TrickplaySelection] = []
if not isinstance(manifest, dict):
return None
for media_source_id, widths in manifest.items():
if not isinstance(widths, dict):
continue
for width_key, raw_info in widths.items():
if not isinstance(raw_info, dict):
continue
try:
width = int(raw_info.get("Width") or width_key)
height = int(raw_info.get("Height") or 0)
interval_ms = int(raw_info.get("Interval") or 0)
thumbnail_count = int(raw_info.get("ThumbnailCount") or 0)
tile_columns = int(raw_info.get("TileWidth") or 0)
tile_rows = int(raw_info.get("TileHeight") or 0)
except (TypeError, ValueError):
continue
if min(
width,
height,
interval_ms,
thumbnail_count,
tile_columns,
tile_rows,
) <= 0:
continue
candidates.append(
TrickplaySelection(
media_source_id=str(media_source_id) if media_source_id else None,
width=width,
height=height,
interval_ms=interval_ms,
thumbnail_count=thumbnail_count,
tile_columns=tile_columns,
tile_rows=tile_rows,
)
)
if not candidates:
return None
if preferred_media_source_id:
source_matches = [
candidate
for candidate in candidates
if candidate.media_source_id == preferred_media_source_id
]
if source_matches:
candidates = source_matches
return min(
candidates,
key=lambda candidate: (
abs(candidate.width - preferred_width),
-candidate.width,
),
)
def trickplay_sheet_bytes(
self,
item_id: str,
selection: TrickplaySelection,
sheet_index: int,
) -> bytes:
params: dict[str, Any] = {}
if selection.media_source_id:
params["MediaSourceId"] = selection.media_source_id
response = self._get(
f"/Videos/{item_id}/Trickplay/{selection.width}/{sheet_index}.jpg",
params=params,
)
return response.content
def download_trickplay_frames(
self,
item_id: str,
selection: TrickplaySelection,
out_dir: Path,
) -> list[Path]:
out_dir.mkdir(parents=True, exist_ok=True)
for old in out_dir.glob("frame_*.jpg"):
old.unlink()
capacity = selection.thumbnails_per_sheet
sheet_count = math.ceil(selection.thumbnail_count / capacity)
paths: list[Path] = []
for sheet_index in range(sheet_count):
with Image.open(
io.BytesIO(
self.trickplay_sheet_bytes(
item_id,
selection,
sheet_index,
)
)
) as sheet:
sheet = sheet.convert("RGB")
for local_index in range(capacity):
global_index = sheet_index * capacity + local_index
if global_index >= selection.thumbnail_count:
break
column = local_index % selection.tile_columns
row = local_index // selection.tile_columns
left = column * selection.width
top = row * selection.height
frame = sheet.crop((
left,
top,
left + selection.width,
top + selection.height,
))
path = out_dir / f"frame_{global_index + 1:06d}.jpg"
frame.save(path, "JPEG", quality=90)
paths.append(path)
return paths
def jellyfin_media_id(item_id: str) -> str:
return hashlib.sha256(f"jellyfin:{item_id}".encode()).hexdigest()[:32]
def item_tags(item: dict[str, Any]) -> list[str]:
tags = item.get("Tags") or []
if not isinstance(tags, list):
return []
return [str(tag).strip() for tag in tags if str(tag).strip()]
def primary_media_source(item: dict[str, Any]) -> dict[str, Any]:
sources = item.get("MediaSources") or []
if not isinstance(sources, list):
return {}
for source in sources:
if isinstance(source, dict):
return source
return {}
def tags_to_json(tags: list[str]) -> str:
return json.dumps(tags, ensure_ascii=False, separators=(",", ":"))
def tags_from_json(value: str | None) -> list[str]:
if not value:
return []
try:
parsed = json.loads(value)
except (TypeError, json.JSONDecodeError):
return []
if not isinstance(parsed, list):
return []
return [str(tag).strip() for tag in parsed if str(tag).strip()]
def route_override_from_tags(
tags: list[str],
*,
force_specialist_tag: str,
force_general_tag: str,
specialist_tags: tuple[str, ...],
) -> tuple[str, str] | None:
normalized = {tag.casefold() for tag in tags}
if force_specialist_tag and force_specialist_tag.casefold() in normalized:
return ("specialist", "jellyfin-force-tag")
if force_general_tag and force_general_tag.casefold() in normalized:
return ("general", "jellyfin-force-tag")
if normalized.intersection(tag.casefold() for tag in specialist_tags):
return ("specialist", "jellyfin-specialist-tag")
return None
def caption_context_from_tags(
tags: list[str],
*,
control_tags: tuple[str, ...] = (),
) -> str | None:
controls = {tag.casefold() for tag in control_tags if tag}
visible_tags = [tag for tag in tags if tag.casefold() not in controls]
if not visible_tags:
return None
return "Jellyfin tags: " + ", ".join(visible_tags)