marcarr 0.1.0__py3-none-any.whl
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- marcarr/__init__.py +3 -0
- marcarr/__main__.py +3 -0
- marcarr/ai.py +198 -0
- marcarr/auth.py +86 -0
- marcarr/brief.py +71 -0
- marcarr/cli.py +125 -0
- marcarr/clients/__init__.py +0 -0
- marcarr/clients/base.py +91 -0
- marcarr/clients/plex.py +119 -0
- marcarr/config.py +314 -0
- marcarr/core.py +144 -0
- marcarr/cuts.py +395 -0
- marcarr/db.py +104 -0
- marcarr/errors.py +32 -0
- marcarr/events.py +167 -0
- marcarr/graph.py +81 -0
- marcarr/identity.py +145 -0
- marcarr/jobs.py +302 -0
- marcarr/library.py +257 -0
- marcarr/mcp_server.py +295 -0
- marcarr/models.py +113 -0
- marcarr/pipeline.py +517 -0
- marcarr/research.py +195 -0
- marcarr/routes/__init__.py +0 -0
- marcarr/routes/common.py +181 -0
- marcarr/routes/cuts.py +175 -0
- marcarr/routes/review.py +751 -0
- marcarr/routes/system.py +441 -0
- marcarr/routes/titles.py +505 -0
- marcarr/schema.py +341 -0
- marcarr/server.py +72 -0
- marcarr/stages/__init__.py +0 -0
- marcarr/stages/cast.py +147 -0
- marcarr/stages/faces.py +197 -0
- marcarr/stages/index.py +182 -0
- marcarr/stages/label.py +450 -0
- marcarr/stages/signals.py +282 -0
- marcarr/stages/subs.py +279 -0
- marcarr/stages/tagger.py +282 -0
- marcarr/stages/tags_v1.json +2942 -0
- marcarr/stages/vocab.py +124 -0
- marcarr/states.py +157 -0
- marcarr/store.py +1014 -0
- marcarr/tagging.py +198 -0
- marcarr/ui/assets/DMMono-400-4GdczIuU.woff2 +0 -0
- marcarr/ui/assets/DMMono-500-DRMDZjhP.woff2 +0 -0
- marcarr/ui/assets/DMSans-Xz1IZZA0.woff2 +0 -0
- marcarr/ui/assets/Outfit-Bc-8i84L.woff2 +0 -0
- marcarr/ui/assets/index-C2Nh-iqu.css +1 -0
- marcarr/ui/assets/index-C5WqdLyT.js +563 -0
- marcarr/ui/favicon.svg +1 -0
- marcarr/ui/index.html +15 -0
- marcarr/views.py +362 -0
- marcarr-0.1.0.dist-info/METADATA +97 -0
- marcarr-0.1.0.dist-info/RECORD +59 -0
- marcarr-0.1.0.dist-info/WHEEL +5 -0
- marcarr-0.1.0.dist-info/entry_points.txt +2 -0
- marcarr-0.1.0.dist-info/licenses/LICENSE +21 -0
- marcarr-0.1.0.dist-info/top_level.txt +1 -0
marcarr/__init__.py
ADDED
marcarr/__main__.py
ADDED
marcarr/ai.py
ADDED
|
@@ -0,0 +1,198 @@
|
|
|
1
|
+
"""Language-model calls, through Prompture.
|
|
2
|
+
|
|
3
|
+
The model is a Prompture model string ("claude/claude-sonnet-5-5",
|
|
4
|
+
"ollama/qwen3-vl:8b", "google/gemini-2.5-flash"). With ``ai.base_url`` set and
|
|
5
|
+
a bare model name, the endpoint is treated as OpenAI-compatible (Ollama's /v1,
|
|
6
|
+
LM Studio, a gateway).
|
|
7
|
+
|
|
8
|
+
Every call adds its cost to the current :class:`Meter`, so a step knows what
|
|
9
|
+
it spent (the Activity page shows it per video and per month).
|
|
10
|
+
"""
|
|
11
|
+
|
|
12
|
+
from __future__ import annotations
|
|
13
|
+
|
|
14
|
+
import contextlib
|
|
15
|
+
import re
|
|
16
|
+
import threading
|
|
17
|
+
from collections.abc import Iterator
|
|
18
|
+
from typing import Any
|
|
19
|
+
|
|
20
|
+
from pydantic import BaseModel, ValidationError
|
|
21
|
+
|
|
22
|
+
from .config import AICfg
|
|
23
|
+
from .errors import MarcarrError
|
|
24
|
+
|
|
25
|
+
|
|
26
|
+
class AIError(MarcarrError):
|
|
27
|
+
pass
|
|
28
|
+
|
|
29
|
+
|
|
30
|
+
class Meter:
|
|
31
|
+
"""Dollars and tokens spent by the calls made inside ``metered()``."""
|
|
32
|
+
|
|
33
|
+
def __init__(self) -> None:
|
|
34
|
+
self.cost = 0.0
|
|
35
|
+
self.tokens = 0
|
|
36
|
+
self.calls = 0
|
|
37
|
+
|
|
38
|
+
def add(self, usage: dict[str, Any] | None) -> None:
|
|
39
|
+
usage = usage or {}
|
|
40
|
+
self.calls += 1
|
|
41
|
+
try:
|
|
42
|
+
self.cost += float(usage.get("cost") or 0.0)
|
|
43
|
+
except (TypeError, ValueError):
|
|
44
|
+
pass
|
|
45
|
+
try:
|
|
46
|
+
self.tokens += int(usage.get("total_tokens") or 0)
|
|
47
|
+
except (TypeError, ValueError):
|
|
48
|
+
pass
|
|
49
|
+
|
|
50
|
+
|
|
51
|
+
_local = threading.local()
|
|
52
|
+
|
|
53
|
+
|
|
54
|
+
@contextlib.contextmanager
|
|
55
|
+
def metered() -> Iterator[Meter]:
|
|
56
|
+
"""Count the cost of every AI call made on this thread inside the block."""
|
|
57
|
+
meter = Meter()
|
|
58
|
+
prev = getattr(_local, "meter", None)
|
|
59
|
+
_local.meter = meter
|
|
60
|
+
try:
|
|
61
|
+
yield meter
|
|
62
|
+
finally:
|
|
63
|
+
_local.meter = prev
|
|
64
|
+
if prev is not None:
|
|
65
|
+
prev.cost += meter.cost
|
|
66
|
+
prev.tokens += meter.tokens
|
|
67
|
+
prev.calls += meter.calls
|
|
68
|
+
|
|
69
|
+
|
|
70
|
+
def _record(usage: dict[str, Any] | None) -> None:
|
|
71
|
+
meter = getattr(_local, "meter", None)
|
|
72
|
+
if meter is not None:
|
|
73
|
+
meter.add(usage)
|
|
74
|
+
hook = getattr(_local, "on_call", None)
|
|
75
|
+
if hook is not None and usage:
|
|
76
|
+
hook(usage)
|
|
77
|
+
|
|
78
|
+
|
|
79
|
+
def on_call(fn: Any) -> None:
|
|
80
|
+
"""Called with the usage of each model call made on this thread (the live log)."""
|
|
81
|
+
_local.on_call = fn
|
|
82
|
+
|
|
83
|
+
|
|
84
|
+
def model_spec(cfg: AICfg, *, vision: bool = False) -> tuple[str, dict[str, Any]]:
|
|
85
|
+
"""The Prompture model string and driver overrides for this config."""
|
|
86
|
+
model = (cfg.vision_model if vision and cfg.vision_model else cfg.model).strip()
|
|
87
|
+
if not model:
|
|
88
|
+
raise AIError("no AI model is set (Settings > AI)")
|
|
89
|
+
overrides: dict[str, Any] = {}
|
|
90
|
+
provider = model.split("/", 1)[0] if "/" in model else ""
|
|
91
|
+
if cfg.base_url and not provider:
|
|
92
|
+
model = f"openai/{model}"
|
|
93
|
+
overrides["base_url"] = cfg.base_url.rstrip("/")
|
|
94
|
+
overrides["api_key"] = cfg.api_key or "not-needed"
|
|
95
|
+
elif not provider:
|
|
96
|
+
raise AIError(f"the model {model!r} needs a provider prefix such as ollama/, claude/ or "
|
|
97
|
+
"google/ (or set a base URL for an OpenAI-compatible endpoint)")
|
|
98
|
+
else:
|
|
99
|
+
key = (cfg.keys or {}).get(provider) or cfg.api_key
|
|
100
|
+
if key:
|
|
101
|
+
overrides["api_key"] = key
|
|
102
|
+
if cfg.base_url and provider == "ollama":
|
|
103
|
+
overrides["endpoint"] = cfg.base_url
|
|
104
|
+
return model, overrides
|
|
105
|
+
|
|
106
|
+
|
|
107
|
+
def capabilities(model: str) -> Any | None:
|
|
108
|
+
"""Prompture's catalog entry for "provider/model" (vision, reasoning, limits)."""
|
|
109
|
+
provider, _, model_id = model.partition("/")
|
|
110
|
+
try:
|
|
111
|
+
from prompture.infra.model_rates import get_model_capabilities
|
|
112
|
+
|
|
113
|
+
return get_model_capabilities(provider, model_id)
|
|
114
|
+
except Exception: # noqa: BLE001 - an unknown model just has no catalog entry
|
|
115
|
+
return None
|
|
116
|
+
|
|
117
|
+
|
|
118
|
+
REASONING_ROOM = 16_000 # a reasoning model thinks before it answers: both count
|
|
119
|
+
|
|
120
|
+
|
|
121
|
+
def call_options(cfg: AICfg, model: str, max_tokens: int) -> dict[str, Any]:
|
|
122
|
+
"""Options for one call. A reasoning model gets the configured effort and room
|
|
123
|
+
for its thinking, or it can spend the whole budget before writing the answer."""
|
|
124
|
+
opts: dict[str, Any] = {"timeout": cfg.timeout, "max_tokens": max_tokens, "temperature": 0.2}
|
|
125
|
+
caps = capabilities(model)
|
|
126
|
+
if caps is not None and caps.is_reasoning:
|
|
127
|
+
opts["effort"] = cfg.effort
|
|
128
|
+
room = max(max_tokens * 4, REASONING_ROOM)
|
|
129
|
+
if caps.max_output_tokens:
|
|
130
|
+
room = min(room, int(caps.max_output_tokens))
|
|
131
|
+
opts["max_tokens"] = room
|
|
132
|
+
return opts
|
|
133
|
+
|
|
134
|
+
|
|
135
|
+
def driver_for(cfg: AICfg, *, vision: bool = False) -> Any:
|
|
136
|
+
model, overrides = model_spec(cfg, vision=vision)
|
|
137
|
+
import prompture
|
|
138
|
+
|
|
139
|
+
try:
|
|
140
|
+
return prompture.get_driver_for_model(model, **overrides)
|
|
141
|
+
except Exception as exc: # noqa: BLE001 - any init failure means "unavailable"
|
|
142
|
+
raise AIError(f"could not start {model}: {exc}") from exc
|
|
143
|
+
|
|
144
|
+
|
|
145
|
+
def ask_json(cfg: AICfg, schema: type[BaseModel], system: str, prompt: str, *,
|
|
146
|
+
images: list[Any] | None = None, retries: int = 1, max_tokens: int = 4096) -> Any:
|
|
147
|
+
"""A validated instance of *schema*; *images* (bytes or paths) go to a vision model.
|
|
148
|
+
|
|
149
|
+
An invalid reply is retried once with the validation error as feedback,
|
|
150
|
+
then reported as AIError (never repaired into a guess).
|
|
151
|
+
"""
|
|
152
|
+
import prompture
|
|
153
|
+
from prompture.exceptions import ExtractionError
|
|
154
|
+
|
|
155
|
+
vision = bool(images)
|
|
156
|
+
driver = driver_for(cfg, vision=vision)
|
|
157
|
+
model, _ = model_spec(cfg, vision=vision)
|
|
158
|
+
feedback = ""
|
|
159
|
+
last: Exception | None = None
|
|
160
|
+
options = call_options(cfg, model, max_tokens)
|
|
161
|
+
for _attempt in range(retries + 1):
|
|
162
|
+
try:
|
|
163
|
+
result = prompture.ask_for_json(
|
|
164
|
+
driver=driver, content_prompt=prompt + feedback,
|
|
165
|
+
json_schema=schema.model_json_schema(), system_prompt=system,
|
|
166
|
+
model_name=model.split("/", 1)[-1], options=options,
|
|
167
|
+
ai_cleanup=False, cache=False, images=images or None)
|
|
168
|
+
_record(result.get("usage"))
|
|
169
|
+
return schema.model_validate(result["json_object"])
|
|
170
|
+
except (ExtractionError, ValidationError, KeyError, TypeError) as exc:
|
|
171
|
+
last = exc
|
|
172
|
+
_record(getattr(exc, "usage", None)) # a cut-off reply was still paid for
|
|
173
|
+
if "max_tokens" in str(exc):
|
|
174
|
+
# cut off, not wrong: the same question with more room
|
|
175
|
+
options = {**options, "max_tokens": int(options["max_tokens"]) * 2}
|
|
176
|
+
feedback = ""
|
|
177
|
+
continue
|
|
178
|
+
feedback = (f"\nThe previous answer was invalid: {str(exc)[:300]}. "
|
|
179
|
+
"Return JSON matching the schema exactly.")
|
|
180
|
+
except AIError:
|
|
181
|
+
raise
|
|
182
|
+
except Exception as exc: # noqa: BLE001 - transport failures
|
|
183
|
+
raise AIError(f"{model} failed: {exc}") from exc
|
|
184
|
+
raise AIError(f"{model} returned invalid JSON after {retries + 1} tries: {last}")
|
|
185
|
+
|
|
186
|
+
|
|
187
|
+
APPROX_RE = re.compile(r"^(?:(\d+):)?([0-5]?\d):([0-5]\d)$")
|
|
188
|
+
|
|
189
|
+
|
|
190
|
+
def parse_approx(s: Any) -> float:
|
|
191
|
+
""" "1:02:03" / "05:10" / 310 -> seconds."""
|
|
192
|
+
if isinstance(s, (int, float)):
|
|
193
|
+
return float(s)
|
|
194
|
+
m = APPROX_RE.match(str(s).strip())
|
|
195
|
+
if not m:
|
|
196
|
+
raise AIError(f"bad time {s!r} (use mm:ss or h:mm:ss)")
|
|
197
|
+
h, mi, se = m.groups()
|
|
198
|
+
return int(h or 0) * 3600 + int(mi) * 60 + int(se)
|
marcarr/auth.py
ADDED
|
@@ -0,0 +1,86 @@
|
|
|
1
|
+
"""API keys for connected apps, each with scopes:
|
|
2
|
+
|
|
3
|
+
* ``read``: everything GET
|
|
4
|
+
* ``propose``: add tags as proposals (FansCut, Doblarr, MCP clients)
|
|
5
|
+
* ``review``: keep, drop and edit tags, confirm faces (the review pages)
|
|
6
|
+
* ``run``: queue analysis
|
|
7
|
+
|
|
8
|
+
A request with a key is held to its scopes. A request without one is the web
|
|
9
|
+
UI or a trusted caller: allowed, unless ``server.require_key`` is on and the
|
|
10
|
+
call does not come from this machine. Settings and key management are never
|
|
11
|
+
open to a key: they are for the person at the web UI.
|
|
12
|
+
"""
|
|
13
|
+
|
|
14
|
+
from __future__ import annotations
|
|
15
|
+
|
|
16
|
+
import datetime as _dt
|
|
17
|
+
import hashlib
|
|
18
|
+
import json
|
|
19
|
+
import secrets
|
|
20
|
+
import uuid
|
|
21
|
+
from typing import Any
|
|
22
|
+
|
|
23
|
+
from .db import Database, dumps
|
|
24
|
+
from .errors import MarcarrError, NotFoundError
|
|
25
|
+
|
|
26
|
+
SCOPES = ("read", "propose", "review", "run")
|
|
27
|
+
|
|
28
|
+
|
|
29
|
+
def _hash(key: str) -> str:
|
|
30
|
+
return hashlib.sha256(key.encode()).hexdigest()
|
|
31
|
+
|
|
32
|
+
|
|
33
|
+
def _now() -> str:
|
|
34
|
+
return _dt.datetime.now().isoformat(timespec="seconds")
|
|
35
|
+
|
|
36
|
+
|
|
37
|
+
class Keys:
|
|
38
|
+
def __init__(self, db: Database):
|
|
39
|
+
self.db = db
|
|
40
|
+
|
|
41
|
+
@staticmethod
|
|
42
|
+
def _row(r: Any) -> dict[str, Any]:
|
|
43
|
+
return {"id": r["id"], "name": r["name"], "prefix": r["prefix"],
|
|
44
|
+
"scopes": json.loads(r["scopes"]), "created_at": r["created_at"],
|
|
45
|
+
"last_used": r["last_used"]}
|
|
46
|
+
|
|
47
|
+
def list(self) -> list[dict[str, Any]]:
|
|
48
|
+
return [self._row(r) for r in self.db.query("SELECT * FROM api_keys ORDER BY created_at")]
|
|
49
|
+
|
|
50
|
+
def add(self, name: str, scopes: list[str]) -> dict[str, Any]:
|
|
51
|
+
name = (name or "").strip()[:60]
|
|
52
|
+
if not name:
|
|
53
|
+
raise MarcarrError("give the app a name")
|
|
54
|
+
bad = [s for s in scopes if s not in SCOPES]
|
|
55
|
+
if bad:
|
|
56
|
+
raise MarcarrError(f"unknown scope: {', '.join(bad)}")
|
|
57
|
+
key = "mk_" + secrets.token_urlsafe(24)
|
|
58
|
+
kid = uuid.uuid4().hex[:10]
|
|
59
|
+
self.db.execute("INSERT INTO api_keys (id, name, key_hash, prefix, scopes, created_at)"
|
|
60
|
+
" VALUES (?,?,?,?,?,?)",
|
|
61
|
+
(kid, name, _hash(key), key[:7], dumps(scopes or ["read"]), _now()))
|
|
62
|
+
return {**self.get(kid), "key": key}
|
|
63
|
+
|
|
64
|
+
def get(self, kid: str) -> dict[str, Any]:
|
|
65
|
+
r = self.db.one("SELECT * FROM api_keys WHERE id = ?", (kid,))
|
|
66
|
+
if r is None:
|
|
67
|
+
raise NotFoundError(f"key {kid} not found")
|
|
68
|
+
return self._row(r)
|
|
69
|
+
|
|
70
|
+
def renew(self, kid: str) -> dict[str, Any]:
|
|
71
|
+
self.get(kid)
|
|
72
|
+
key = "mk_" + secrets.token_urlsafe(24)
|
|
73
|
+
self.db.execute("UPDATE api_keys SET key_hash = ?, prefix = ? WHERE id = ?",
|
|
74
|
+
(_hash(key), key[:7], kid))
|
|
75
|
+
return {**self.get(kid), "key": key}
|
|
76
|
+
|
|
77
|
+
def delete(self, kid: str) -> None:
|
|
78
|
+
self.get(kid)
|
|
79
|
+
self.db.execute("DELETE FROM api_keys WHERE id = ?", (kid,))
|
|
80
|
+
|
|
81
|
+
def check(self, key: str) -> dict[str, Any] | None:
|
|
82
|
+
r = self.db.one("SELECT * FROM api_keys WHERE key_hash = ?", (_hash(key),))
|
|
83
|
+
if r is None:
|
|
84
|
+
return None
|
|
85
|
+
self.db.execute("UPDATE api_keys SET last_used = ? WHERE id = ?", (_now(), r["id"]))
|
|
86
|
+
return self._row(r)
|
marcarr/brief.py
ADDED
|
@@ -0,0 +1,71 @@
|
|
|
1
|
+
"""A scene as plain text: what the title page's Copy brief puts on the clipboard and
|
|
2
|
+
what the MCP get_scene tool returns, so a person and an AI read the same thing.
|
|
3
|
+
|
|
4
|
+
It names the edition, the time range, who is seen, heard or only named, the tags
|
|
5
|
+
with their evidence (and the moment each was seen or heard), the dialogue, and a
|
|
6
|
+
link back to the same moment.
|
|
7
|
+
"""
|
|
8
|
+
|
|
9
|
+
from __future__ import annotations
|
|
10
|
+
|
|
11
|
+
from typing import Any
|
|
12
|
+
|
|
13
|
+
MAX_LINES = 60
|
|
14
|
+
|
|
15
|
+
|
|
16
|
+
def clock(t: float) -> str:
|
|
17
|
+
t = max(0, int(t))
|
|
18
|
+
h, m, s = t // 3600, t % 3600 // 60, t % 60
|
|
19
|
+
return f"{h}:{m:02d}:{s:02d}" if h else f"{m}:{s:02d}"
|
|
20
|
+
|
|
21
|
+
|
|
22
|
+
def evidence_text(x: Any) -> str:
|
|
23
|
+
"""One piece of evidence: "snow" or {"text": "snow", "at": 12} -> "snow (0:12)"."""
|
|
24
|
+
if isinstance(x, dict):
|
|
25
|
+
at = x.get("at")
|
|
26
|
+
return f"{x.get('text', '')} ({clock(at)})" if at is not None else str(x.get("text", ""))
|
|
27
|
+
return str(x)
|
|
28
|
+
|
|
29
|
+
|
|
30
|
+
def scene_brief(d: dict[str, Any], *, link: str = "", ids: bool = False) -> str:
|
|
31
|
+
"""The brief of one scene from its detail (Views.scene_detail). `ids` adds the
|
|
32
|
+
person and tag ids an app or AI needs to act on them."""
|
|
33
|
+
names = {c["id"]: c.get("character") or c.get("actor") or c["id"] for c in d.get("cast") or []}
|
|
34
|
+
|
|
35
|
+
def who(pids: list[str]) -> str:
|
|
36
|
+
return ", ".join(f"{names.get(p, p)} ({p})" if ids else names.get(p, p) for p in pids)
|
|
37
|
+
|
|
38
|
+
t = d["title"]
|
|
39
|
+
head = t["name"] + (f" ({t['year']})" if t.get("year") else "")
|
|
40
|
+
if d.get("edition"):
|
|
41
|
+
head += f", {d['edition']}"
|
|
42
|
+
out = [f"{head}: scene {d['n']}, {clock(d['start'])} to {clock(d['end'])}"]
|
|
43
|
+
if ids:
|
|
44
|
+
out.append(f"video: {d['video']}")
|
|
45
|
+
if d.get("summary"):
|
|
46
|
+
out.append(f"What happens: {d['summary']}")
|
|
47
|
+
if d.get("place_name"):
|
|
48
|
+
out.append(f"Place: {d['place_name']}")
|
|
49
|
+
seen = d.get("seen", d.get("people")) or []
|
|
50
|
+
out.append(f"Seen: {who(seen) or 'nobody recognised'}")
|
|
51
|
+
if d.get("speakers"):
|
|
52
|
+
out.append(f"Heard speaking, not seen: {who(d['speakers'])}")
|
|
53
|
+
if d.get("mentioned"):
|
|
54
|
+
out.append(f"Only named: {who(d['mentioned'])}")
|
|
55
|
+
tags = [x for x in d.get("all_tags") or [] if x["status"] != "rejected" or ids]
|
|
56
|
+
if tags:
|
|
57
|
+
out.append("Tags:")
|
|
58
|
+
for x in sorted(tags, key=lambda x: (x["status"] != "accepted", x["name"])):
|
|
59
|
+
state = {"accepted": "kept", "proposed": "to review", "rejected": "dropped"}[x["status"]]
|
|
60
|
+
line = f" {x['name']} ({state}" + (f", {x['id']}, {x['source']}" if ids else "") + ")"
|
|
61
|
+
ev = [f"{k}: " + "; ".join(evidence_text(e) for e in v) for k, v in (x.get("evidence") or {}).items() if v]
|
|
62
|
+
out.append(line + (": " + " | ".join(ev) if ev else ""))
|
|
63
|
+
lines = d.get("lines") or []
|
|
64
|
+
if lines:
|
|
65
|
+
out.append("Dialogue:")
|
|
66
|
+
out += [f" {clock(ln['start'])} {ln['text']}" for ln in lines[:MAX_LINES]]
|
|
67
|
+
if len(lines) > MAX_LINES:
|
|
68
|
+
out.append(f" ... {len(lines) - MAX_LINES} more lines")
|
|
69
|
+
if link:
|
|
70
|
+
out.append(f"Link: {link}")
|
|
71
|
+
return "\n".join(out)
|
marcarr/cli.py
ADDED
|
@@ -0,0 +1,125 @@
|
|
|
1
|
+
"""marcarr serve | scan | analyse | mcp | status."""
|
|
2
|
+
|
|
3
|
+
from __future__ import annotations
|
|
4
|
+
|
|
5
|
+
import argparse
|
|
6
|
+
import json
|
|
7
|
+
import logging
|
|
8
|
+
import logging.handlers
|
|
9
|
+
import sys
|
|
10
|
+
from pathlib import Path
|
|
11
|
+
|
|
12
|
+
from . import __version__
|
|
13
|
+
from . import config as cfgmod
|
|
14
|
+
|
|
15
|
+
|
|
16
|
+
def _logging(data_dir: Path, verbose: bool) -> None:
|
|
17
|
+
data_dir.mkdir(parents=True, exist_ok=True)
|
|
18
|
+
fmt = logging.Formatter("%(asctime)s %(levelname)s %(name)s: %(message)s")
|
|
19
|
+
root = logging.getLogger()
|
|
20
|
+
root.setLevel(logging.DEBUG if verbose else logging.INFO)
|
|
21
|
+
console = logging.StreamHandler()
|
|
22
|
+
console.setFormatter(fmt)
|
|
23
|
+
root.addHandler(console)
|
|
24
|
+
fh = logging.handlers.RotatingFileHandler(data_dir / "marcarr.log", maxBytes=5_000_000,
|
|
25
|
+
backupCount=3, encoding="utf-8")
|
|
26
|
+
fh.setFormatter(fmt)
|
|
27
|
+
root.addHandler(fh)
|
|
28
|
+
|
|
29
|
+
|
|
30
|
+
def main(argv: list[str] | None = None) -> int:
|
|
31
|
+
p = argparse.ArgumentParser(prog="marcarr", description="Know what's in every scene.")
|
|
32
|
+
p.add_argument("--config", help="path to config.yaml (default: ./config.yaml or $MARCARR_CONFIG)")
|
|
33
|
+
p.add_argument("-v", "--verbose", action="store_true")
|
|
34
|
+
p.add_argument("--version", action="version", version=f"marcarr {__version__}")
|
|
35
|
+
sub = p.add_subparsers(dest="cmd")
|
|
36
|
+
s = sub.add_parser("serve", help="run the web UI and the API")
|
|
37
|
+
s.add_argument("--host")
|
|
38
|
+
s.add_argument("--port", type=int)
|
|
39
|
+
sub.add_parser("scan", help="read the Plex libraries once and exit")
|
|
40
|
+
a = sub.add_parser("analyse", help="analyse one file (no Plex needed) and print the result")
|
|
41
|
+
a.add_argument("path")
|
|
42
|
+
a.add_argument("--name", help="what to call it (default: the file name)")
|
|
43
|
+
a.add_argument("--steps", help="comma-separated steps (default: all)")
|
|
44
|
+
m = sub.add_parser("mcp", help="MCP server over stdio, for AI clients")
|
|
45
|
+
m.add_argument("--url", help="Marcarr's address (default: http://127.0.0.1:<port>)")
|
|
46
|
+
sub.add_parser("status", help="print the queue and the month")
|
|
47
|
+
args = p.parse_args(argv)
|
|
48
|
+
cmd = args.cmd or "serve"
|
|
49
|
+
cfg_path = Path(args.config) if args.config else cfgmod.default_path()
|
|
50
|
+
|
|
51
|
+
if cmd == "mcp":
|
|
52
|
+
from .mcp_server import serve as mcp_serve
|
|
53
|
+
|
|
54
|
+
cfg = cfgmod.load(cfg_path)
|
|
55
|
+
mcp_serve(args.url or f"http://127.0.0.1:{cfg.server.port}")
|
|
56
|
+
return 0
|
|
57
|
+
|
|
58
|
+
cfg = cfgmod.load(cfg_path)
|
|
59
|
+
_logging(cfg.data_dir, args.verbose)
|
|
60
|
+
|
|
61
|
+
if cmd == "serve":
|
|
62
|
+
import uvicorn
|
|
63
|
+
|
|
64
|
+
from .core import Core
|
|
65
|
+
from .server import create_app
|
|
66
|
+
|
|
67
|
+
if not cfg_path.is_file():
|
|
68
|
+
cfgmod.save(cfg, cfg_path)
|
|
69
|
+
host = args.host or cfg.server.host
|
|
70
|
+
port = args.port or cfg.server.port
|
|
71
|
+
import socket
|
|
72
|
+
|
|
73
|
+
with socket.socket() as probe: # a second copy must not touch the queue
|
|
74
|
+
try:
|
|
75
|
+
probe.bind((host, port))
|
|
76
|
+
except OSError:
|
|
77
|
+
print(f"Port {port} is in use: is Marcarr already running?", file=sys.stderr)
|
|
78
|
+
return 1
|
|
79
|
+
core = Core(cfg, cfg_path, start_worker=False)
|
|
80
|
+
app = create_app(core, start_worker=True)
|
|
81
|
+
logging.getLogger("marcarr").info("Marcarr %s on http://%s:%s", __version__, host, port)
|
|
82
|
+
uvicorn.run(app, host=host, port=port, log_level="warning")
|
|
83
|
+
return 0
|
|
84
|
+
|
|
85
|
+
from .core import Core
|
|
86
|
+
|
|
87
|
+
core = Core(cfg, cfg_path, start_worker=False)
|
|
88
|
+
try:
|
|
89
|
+
if cmd == "scan":
|
|
90
|
+
job = core.library.submit_scan()
|
|
91
|
+
core.worker.run_pending("light")
|
|
92
|
+
print(json.dumps(core.jobs.get(job["id"])["result"], indent=2))
|
|
93
|
+
elif cmd == "analyse":
|
|
94
|
+
vid = _register(core, Path(args.path), args.name)
|
|
95
|
+
steps = [x.strip() for x in args.steps.split(",")] if args.steps else None
|
|
96
|
+
core.pipeline.submit(vid, steps)
|
|
97
|
+
core.worker.run_pending("heavy")
|
|
98
|
+
from .views import Views
|
|
99
|
+
|
|
100
|
+
v = Views(core).video_view(core.store.video(vid))
|
|
101
|
+
print(json.dumps({"video": vid, "steps": v["step_info"], "scenes": v["scenes"],
|
|
102
|
+
"shots": v["shots"], "lines": v["lines"]}, indent=2))
|
|
103
|
+
elif cmd == "status":
|
|
104
|
+
print(json.dumps({"queue": core.jobs.depth(), "month_cost": core.store.month_cost(),
|
|
105
|
+
"review": core.store.review_count()}, indent=2))
|
|
106
|
+
finally:
|
|
107
|
+
core.close()
|
|
108
|
+
return 0
|
|
109
|
+
|
|
110
|
+
|
|
111
|
+
def _register(core: object, path: Path, name: str | None) -> str:
|
|
112
|
+
"""A file outside Plex gets a local title so it can be analysed on its own."""
|
|
113
|
+
from .store import slug
|
|
114
|
+
|
|
115
|
+
if not path.is_file():
|
|
116
|
+
raise SystemExit(f"no such file: {path}")
|
|
117
|
+
c = core # type: ignore[assignment]
|
|
118
|
+
tid = "local:" + slug(name or path.stem)
|
|
119
|
+
c.store.upsert_title({"id": tid, "type": "movie", "name": name or path.stem, # type: ignore[attr-defined]
|
|
120
|
+
"sort_name": (name or path.stem).lower(), "file": str(path)})
|
|
121
|
+
return c.library.add_file(tid, str(path)) # type: ignore[attr-defined]
|
|
122
|
+
|
|
123
|
+
|
|
124
|
+
if __name__ == "__main__":
|
|
125
|
+
sys.exit(main())
|
|
File without changes
|
marcarr/clients/base.py
ADDED
|
@@ -0,0 +1,91 @@
|
|
|
1
|
+
"""Shared HTTP base for the Plex client: session, timeout, retry on transient errors."""
|
|
2
|
+
|
|
3
|
+
from __future__ import annotations
|
|
4
|
+
|
|
5
|
+
import time
|
|
6
|
+
from typing import Any
|
|
7
|
+
|
|
8
|
+
import requests
|
|
9
|
+
|
|
10
|
+
from ..errors import ClientError
|
|
11
|
+
|
|
12
|
+
MAX_IMAGE = 20_000_000 # bytes; a bigger "poster" is not one
|
|
13
|
+
|
|
14
|
+
|
|
15
|
+
def read_capped(resp: requests.Response, limit: int) -> bytes | None:
|
|
16
|
+
"""The body of a streamed response, or None once it passes `limit` bytes."""
|
|
17
|
+
declared = resp.headers.get("Content-Length", "")
|
|
18
|
+
if declared.isdigit() and int(declared) > limit:
|
|
19
|
+
return None
|
|
20
|
+
buf = bytearray()
|
|
21
|
+
for chunk in resp.iter_content(1 << 16):
|
|
22
|
+
buf += chunk
|
|
23
|
+
if len(buf) > limit:
|
|
24
|
+
return None
|
|
25
|
+
return bytes(buf)
|
|
26
|
+
|
|
27
|
+
|
|
28
|
+
class BaseClient:
|
|
29
|
+
service = "service"
|
|
30
|
+
max_retries = 2
|
|
31
|
+
backoff = 0.5
|
|
32
|
+
max_wait = 30.0
|
|
33
|
+
|
|
34
|
+
def __init__(self, base_url: str, timeout: float = 30, headers: dict[str, str] | None = None):
|
|
35
|
+
self.base_url = base_url.rstrip("/")
|
|
36
|
+
self.timeout = timeout
|
|
37
|
+
self.session = requests.Session()
|
|
38
|
+
if headers:
|
|
39
|
+
self.session.headers.update(headers)
|
|
40
|
+
|
|
41
|
+
def get_image(self, path: str, params: dict[str, Any] | None = None) -> bytes | None:
|
|
42
|
+
"""An image's bytes, or None when the server has none (no retries: art is optional).
|
|
43
|
+
|
|
44
|
+
Raises ClientError when the server could not be asked (down, timeout, 5xx,
|
|
45
|
+
429): that is not "no art", and callers must not remember it as such."""
|
|
46
|
+
try:
|
|
47
|
+
resp = self.session.get(f"{self.base_url}{path}", params=params, timeout=self.timeout,
|
|
48
|
+
headers={"Accept": "image/*"}, stream=True)
|
|
49
|
+
except requests.RequestException as exc:
|
|
50
|
+
raise ClientError(f"{self.service} unreachable: {exc.__class__.__name__}") from exc
|
|
51
|
+
with resp:
|
|
52
|
+
if resp.status_code == 429 or resp.status_code >= 500:
|
|
53
|
+
raise ClientError(f"{self.service} returned HTTP {resp.status_code}",
|
|
54
|
+
resp.status_code)
|
|
55
|
+
ctype = resp.headers.get("Content-Type", "")
|
|
56
|
+
if resp.status_code != 200 or not ctype.startswith("image/"):
|
|
57
|
+
return None
|
|
58
|
+
return read_capped(resp, MAX_IMAGE) or None
|
|
59
|
+
|
|
60
|
+
def _once(self, path: str, params: dict[str, Any] | None) -> Any:
|
|
61
|
+
url = f"{self.base_url}{path}"
|
|
62
|
+
try:
|
|
63
|
+
resp = self.session.get(url, params=params, timeout=self.timeout)
|
|
64
|
+
except requests.RequestException as exc:
|
|
65
|
+
raise ClientError(f"{self.service} unreachable: {exc.__class__.__name__}") from exc
|
|
66
|
+
if resp.status_code in (401, 403):
|
|
67
|
+
raise ClientError(f"{self.service} rejected the credentials", resp.status_code)
|
|
68
|
+
if resp.status_code >= 400:
|
|
69
|
+
raise ClientError(
|
|
70
|
+
f"{self.service} returned HTTP {resp.status_code}",
|
|
71
|
+
resp.status_code,
|
|
72
|
+
resp.headers.get("Retry-After"),
|
|
73
|
+
)
|
|
74
|
+
try:
|
|
75
|
+
return resp.json()
|
|
76
|
+
except ValueError as exc:
|
|
77
|
+
raise ClientError(f"{self.service} sent a non-JSON reply", resp.status_code) from exc
|
|
78
|
+
|
|
79
|
+
def _get(self, path: str, params: dict[str, Any] | None = None) -> Any:
|
|
80
|
+
for attempt in range(self.max_retries + 1):
|
|
81
|
+
try:
|
|
82
|
+
return self._once(path, params)
|
|
83
|
+
except ClientError as exc:
|
|
84
|
+
transient = exc.status is None or exc.status == 429 or exc.status >= 500
|
|
85
|
+
if not transient or attempt == self.max_retries:
|
|
86
|
+
raise
|
|
87
|
+
delay = self.backoff * 2**attempt
|
|
88
|
+
if exc.retry_after and exc.retry_after.isdigit():
|
|
89
|
+
delay = max(delay, float(exc.retry_after))
|
|
90
|
+
time.sleep(min(delay, self.max_wait))
|
|
91
|
+
raise AssertionError("unreachable") # pragma: no cover
|