"""Reap score: transparent, additive signals with reason codes. Pure: no I/O.""" from __future__ import annotations import math import re from datetime import datetime from plexreaper.config import ProtectConfig, Weights from plexreaper.models import Breakdown, Evidence, Signal, Title def compile_protection(cfg: ProtectConfig) -> tuple[set[str], list[re.Pattern], set[int]]: patterns: list[re.Pattern] = [] for p in cfg.title_patterns: try: patterns.append(re.compile(p)) except re.error: continue return {g.lower() for g in cfg.genres}, patterns, set(cfg.libraries) def protection(title: Title, rules: tuple[set[str], list[re.Pattern], set[int]]) -> str | None: genres, patterns, libraries = rules if title.library_id in libraries: return f"library {title.library_name!r}" for g in title.genres: if g.lower() in genres: return f"genre {g!r}" for p in patterns: if p.search(title.title): return f"title matches {p.pattern!r}" return None def watched_collections(titles: list[Title], evidence: dict[str, Evidence]) -> set[str]: """Collections containing at least one title somebody watched (Tautulli full or Plex prior).""" out: set[str] = set() for t in titles: e = evidence.get(t.guid) if (e and e.watched) or t.plex_view_count > 0: out.update(t.collections) return out def score( title: Title, evidence: Evidence, w: Weights, *, now: datetime, watched_collections: set[str] = frozenset(), ) -> Breakdown: b = Breakdown() add = lambda code, pts, note: b.signals.append(Signal(code=code, points=pts, note=note)) # noqa: E731 # ---- positive: reasons to remove -------------------------------------- if not evidence.watched and title.plex_view_count == 0: add("NEVER", w.never, "no genuine watch on any server") if evidence.touch_sessions: add("GHOST", w.ghost, f"only {evidence.touch_sessions} sub-threshold session(s)") if evidence.abandoned_sessions: n = min(evidence.abandoned_sessions, w.abandon_cap) add("ABANDON", w.abandon * n, f"{evidence.abandoned_sessions} session(s) by {evidence.abandoned_users} user(s) bailed") days = (now - title.added_at).days if days > w.age_floor_days: span = max(1, w.age_ceiling_days - w.age_floor_days) pts = min(w.age_max, w.age_max * (days - w.age_floor_days) / span) add("AGE", round(pts, 1), f"in library {days / 365:.1f} years") gb = title.size_gb if gb > 1: add("SIZE", round(min(w.size_max, w.size_max * math.log10(gb) / 2), 1), f"{gb:.1f} GB") gph = title.gb_per_hour if gph is not None and gph > w.bloat_gb_per_hour: add("BLOAT", w.bloat, f"{gph:.0f} GB per hour of runtime") b.flags.append("downgrade") r = title.best_rating if r is not None and r > 0: if r <= w.verylow_threshold: add("LOWRATE", w.verylow, f"rated {r:.1f}") elif r <= w.lowrate_threshold: add("LOWRATE", w.lowrate, f"rated {r:.1f}") if ( title.kind == "show" and title.season_count > 1 and evidence.furthest_season == 1 and evidence.watched ): add("STALLED", w.stalled, f"nobody got past season 1 of {title.season_count}") b.flags.append("trim") # ---- negative: reasons to keep ---------------------------------------- if evidence.watched: pts = max(w.watched_cap, w.watched + w.watched_per_user * (evidence.full_users - 1)) add("WATCHED", pts, f"{evidence.full_sessions} full watch(es) by {evidence.full_users} user(s) on {', '.join(evidence.servers)}") if evidence.last_full and (now - evidence.last_full).days <= w.recent_days: add("RECENT", w.recent, f"last watched {(now - evidence.last_full).days} days ago") elif title.plex_view_count > 0: add("PRIOR", w.prior, f"{title.plex_view_count} Plex history view(s), no session detail") if any(c in watched_collections for c in title.collections): add("SIBLING", w.sibling, "a title in the same collection was watched") return b