marcarr 0.1.0__tar.gz
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-0.1.0/LICENSE +21 -0
- marcarr-0.1.0/PKG-INFO +97 -0
- marcarr-0.1.0/README.md +56 -0
- marcarr-0.1.0/marcarr/__init__.py +3 -0
- marcarr-0.1.0/marcarr/__main__.py +3 -0
- marcarr-0.1.0/marcarr/ai.py +198 -0
- marcarr-0.1.0/marcarr/auth.py +86 -0
- marcarr-0.1.0/marcarr/brief.py +71 -0
- marcarr-0.1.0/marcarr/cli.py +125 -0
- marcarr-0.1.0/marcarr/clients/__init__.py +0 -0
- marcarr-0.1.0/marcarr/clients/base.py +91 -0
- marcarr-0.1.0/marcarr/clients/plex.py +119 -0
- marcarr-0.1.0/marcarr/config.py +314 -0
- marcarr-0.1.0/marcarr/core.py +144 -0
- marcarr-0.1.0/marcarr/cuts.py +395 -0
- marcarr-0.1.0/marcarr/db.py +104 -0
- marcarr-0.1.0/marcarr/errors.py +32 -0
- marcarr-0.1.0/marcarr/events.py +167 -0
- marcarr-0.1.0/marcarr/graph.py +81 -0
- marcarr-0.1.0/marcarr/identity.py +145 -0
- marcarr-0.1.0/marcarr/jobs.py +302 -0
- marcarr-0.1.0/marcarr/library.py +257 -0
- marcarr-0.1.0/marcarr/mcp_server.py +295 -0
- marcarr-0.1.0/marcarr/models.py +113 -0
- marcarr-0.1.0/marcarr/pipeline.py +517 -0
- marcarr-0.1.0/marcarr/research.py +195 -0
- marcarr-0.1.0/marcarr/routes/__init__.py +0 -0
- marcarr-0.1.0/marcarr/routes/common.py +181 -0
- marcarr-0.1.0/marcarr/routes/cuts.py +175 -0
- marcarr-0.1.0/marcarr/routes/review.py +751 -0
- marcarr-0.1.0/marcarr/routes/system.py +441 -0
- marcarr-0.1.0/marcarr/routes/titles.py +505 -0
- marcarr-0.1.0/marcarr/schema.py +341 -0
- marcarr-0.1.0/marcarr/server.py +72 -0
- marcarr-0.1.0/marcarr/stages/__init__.py +0 -0
- marcarr-0.1.0/marcarr/stages/cast.py +147 -0
- marcarr-0.1.0/marcarr/stages/faces.py +197 -0
- marcarr-0.1.0/marcarr/stages/index.py +182 -0
- marcarr-0.1.0/marcarr/stages/label.py +450 -0
- marcarr-0.1.0/marcarr/stages/signals.py +282 -0
- marcarr-0.1.0/marcarr/stages/subs.py +279 -0
- marcarr-0.1.0/marcarr/stages/tagger.py +282 -0
- marcarr-0.1.0/marcarr/stages/tags_v1.json +2942 -0
- marcarr-0.1.0/marcarr/stages/vocab.py +124 -0
- marcarr-0.1.0/marcarr/states.py +157 -0
- marcarr-0.1.0/marcarr/store.py +1014 -0
- marcarr-0.1.0/marcarr/tagging.py +198 -0
- marcarr-0.1.0/marcarr/ui/assets/DMMono-400-4GdczIuU.woff2 +0 -0
- marcarr-0.1.0/marcarr/ui/assets/DMMono-500-DRMDZjhP.woff2 +0 -0
- marcarr-0.1.0/marcarr/ui/assets/DMSans-Xz1IZZA0.woff2 +0 -0
- marcarr-0.1.0/marcarr/ui/assets/Outfit-Bc-8i84L.woff2 +0 -0
- marcarr-0.1.0/marcarr/ui/assets/index-C2Nh-iqu.css +1 -0
- marcarr-0.1.0/marcarr/ui/assets/index-C5WqdLyT.js +563 -0
- marcarr-0.1.0/marcarr/ui/favicon.svg +1 -0
- marcarr-0.1.0/marcarr/ui/index.html +15 -0
- marcarr-0.1.0/marcarr/views.py +362 -0
- marcarr-0.1.0/marcarr.egg-info/PKG-INFO +97 -0
- marcarr-0.1.0/marcarr.egg-info/SOURCES.txt +71 -0
- marcarr-0.1.0/marcarr.egg-info/dependency_links.txt +1 -0
- marcarr-0.1.0/marcarr.egg-info/entry_points.txt +2 -0
- marcarr-0.1.0/marcarr.egg-info/requires.txt +21 -0
- marcarr-0.1.0/marcarr.egg-info/top_level.txt +1 -0
- marcarr-0.1.0/pyproject.toml +75 -0
- marcarr-0.1.0/setup.cfg +4 -0
- marcarr-0.1.0/tests/test_api.py +353 -0
- marcarr-0.1.0/tests/test_app_tags.py +44 -0
- marcarr-0.1.0/tests/test_brief.py +58 -0
- marcarr-0.1.0/tests/test_custom_cast.py +95 -0
- marcarr-0.1.0/tests/test_cuts.py +292 -0
- marcarr-0.1.0/tests/test_graph.py +92 -0
- marcarr-0.1.0/tests/test_pipeline.py +336 -0
- marcarr-0.1.0/tests/test_presence.py +83 -0
- marcarr-0.1.0/tests/test_stages.py +382 -0
marcarr-0.1.0/LICENSE
ADDED
|
@@ -0,0 +1,21 @@
|
|
|
1
|
+
MIT License
|
|
2
|
+
|
|
3
|
+
Copyright (c) 2026 jhd3197
|
|
4
|
+
|
|
5
|
+
Permission is hereby granted, free of charge, to any person obtaining a copy
|
|
6
|
+
of this software and associated documentation files (the "Software"), to deal
|
|
7
|
+
in the Software without restriction, including without limitation the rights
|
|
8
|
+
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
|
|
9
|
+
copies of the Software, and to permit persons to whom the Software is
|
|
10
|
+
furnished to do so, subject to the following conditions:
|
|
11
|
+
|
|
12
|
+
The above copyright notice and this permission notice shall be included in all
|
|
13
|
+
copies or substantial portions of the Software.
|
|
14
|
+
|
|
15
|
+
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
|
16
|
+
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
|
17
|
+
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
|
18
|
+
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
|
19
|
+
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
|
20
|
+
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
|
|
21
|
+
SOFTWARE.
|
marcarr-0.1.0/PKG-INFO
ADDED
|
@@ -0,0 +1,97 @@
|
|
|
1
|
+
Metadata-Version: 2.4
|
|
2
|
+
Name: marcarr
|
|
3
|
+
Version: 0.1.0
|
|
4
|
+
Summary: Know what's in every scene: shots, subtitles, scenes, faces and tags for your Plex library
|
|
5
|
+
License: MIT
|
|
6
|
+
Project-URL: Homepage, https://github.com/jhd3197/Marcarr
|
|
7
|
+
Project-URL: Repository, https://github.com/jhd3197/Marcarr
|
|
8
|
+
Project-URL: Issues, https://github.com/jhd3197/Marcarr/issues
|
|
9
|
+
Keywords: plex,scenes,video,tags,subtitles,faces,self-hosted
|
|
10
|
+
Classifier: Development Status :: 3 - Alpha
|
|
11
|
+
Classifier: Environment :: Web Environment
|
|
12
|
+
Classifier: Framework :: FastAPI
|
|
13
|
+
Classifier: License :: OSI Approved :: MIT License
|
|
14
|
+
Classifier: Operating System :: OS Independent
|
|
15
|
+
Classifier: Programming Language :: Python :: 3
|
|
16
|
+
Classifier: Programming Language :: Python :: 3.11
|
|
17
|
+
Classifier: Programming Language :: Python :: 3.12
|
|
18
|
+
Classifier: Topic :: Multimedia :: Video
|
|
19
|
+
Requires-Python: >=3.11
|
|
20
|
+
Description-Content-Type: text/markdown
|
|
21
|
+
License-File: LICENSE
|
|
22
|
+
Requires-Dist: fastapi>=0.110
|
|
23
|
+
Requires-Dist: uvicorn[standard]>=0.27
|
|
24
|
+
Requires-Dist: pydantic>=2
|
|
25
|
+
Requires-Dist: PyYAML>=6.0
|
|
26
|
+
Requires-Dist: requests>=2.31
|
|
27
|
+
Requires-Dist: numpy>=1.26
|
|
28
|
+
Requires-Dist: pillow>=10.1
|
|
29
|
+
Requires-Dist: prompture[media,openai]>=1.19.2
|
|
30
|
+
Provides-Extra: faces
|
|
31
|
+
Requires-Dist: opencv-python-headless>=4.8; extra == "faces"
|
|
32
|
+
Provides-Extra: mcp
|
|
33
|
+
Requires-Dist: prompture[mcp]>=1.19.2; extra == "mcp"
|
|
34
|
+
Requires-Dist: httpx>=0.27; extra == "mcp"
|
|
35
|
+
Provides-Extra: dev
|
|
36
|
+
Requires-Dist: pytest>=8; extra == "dev"
|
|
37
|
+
Requires-Dist: httpx>=0.27; extra == "dev"
|
|
38
|
+
Requires-Dist: responses>=0.25; extra == "dev"
|
|
39
|
+
Requires-Dist: ruff>=0.6; extra == "dev"
|
|
40
|
+
Dynamic: license-file
|
|
41
|
+
|
|
42
|
+
# Marcarr
|
|
43
|
+
|
|
44
|
+
*marcar*: to mark.
|
|
45
|
+
|
|
46
|
+
Marcarr is a self-hosted service that runs next to Plex. It looks at each film
|
|
47
|
+
or episode once and records what is in it: camera cuts, subtitle lines, scenes,
|
|
48
|
+
measured signals, faces, cast and tags ("christmas", "rain", "a cave"). Other
|
|
49
|
+
apps ask Marcarr instead of analysing the file again.
|
|
50
|
+
|
|
51
|
+
Its first two clients are [FansCut](https://github.com/jhd3197/FansCut), which
|
|
52
|
+
builds cuts from tagged scenes, and [Doblarr](https://github.com/jhd3197/Doblarr),
|
|
53
|
+
which dubs and needs to know where a line is said and who is on screen.
|
|
54
|
+
|
|
55
|
+
## On its own
|
|
56
|
+
|
|
57
|
+
You don't need FansCut or Doblarr to use Marcarr. Point it at your Plex server
|
|
58
|
+
and it gives you:
|
|
59
|
+
|
|
60
|
+
- **Scene search across your library**: every rain scene, every Christmas
|
|
61
|
+
dinner, every scene with a given actor, with the film and the time it starts.
|
|
62
|
+
- **Plex labels and collections**: films with a tag get a label (`marcarr:christmas`),
|
|
63
|
+
so a Kometa or smart-collection rule can build a "Christmas scenes" row.
|
|
64
|
+
- **A review page**: accept, fix or reject what the AI proposed, scene by scene.
|
|
65
|
+
- **Tools for AI clients**: an MCP server, so an assistant can ask "where does
|
|
66
|
+
this happen?" or tag a scene itself.
|
|
67
|
+
- **An API and one JSON file per video**: for any other tool that wants to know
|
|
68
|
+
what is in a file without decoding it.
|
|
69
|
+
|
|
70
|
+
## Running it
|
|
71
|
+
|
|
72
|
+
```
|
|
73
|
+
python -m venv .venv && .venv/Scripts/pip install -e ".[faces,mcp,dev]" # or bin/pip
|
|
74
|
+
cd ui && npm install && npm run build && cd ..
|
|
75
|
+
marcarr serve # http://127.0.0.1:7470, first run opens the setup
|
|
76
|
+
```
|
|
77
|
+
|
|
78
|
+
Or `docker compose up -d --build`. Settings are in `config.yaml`
|
|
79
|
+
(see `config.example.yaml`); the Settings page edits it.
|
|
80
|
+
|
|
81
|
+
Other commands: `marcarr scan` (read Plex once), `marcarr analyse <file>`
|
|
82
|
+
(one file, no Plex), `marcarr mcp` (MCP server on stdio), `marcarr status`.
|
|
83
|
+
|
|
84
|
+
For UI work without Plex: `python scripts/seed_demo.py --config demo/config.yaml video.mp4`,
|
|
85
|
+
then `marcarr --config demo/config.yaml serve`, and `npm run dev` in `ui/`
|
|
86
|
+
(proxies `/api` to port 7470).
|
|
87
|
+
|
|
88
|
+
## Layout
|
|
89
|
+
|
|
90
|
+
- `marcarr/stages/`: the analysis code taken from FansCut (subtitles, scenes,
|
|
91
|
+
signals, cast, faces, the tagger and its prompts, the 130-tag list).
|
|
92
|
+
- `marcarr/pipeline.py`: the seven steps per video, states, staleness, cost.
|
|
93
|
+
- `marcarr/routes/`: the v1 API. `ui/src/api/types.ts` is the contract.
|
|
94
|
+
- `ui/`: React + Vite, built from the design in `docs/design/`.
|
|
95
|
+
|
|
96
|
+
Connecting FansCut and Doblarr: [docs/CLIENTS.md](docs/CLIENTS.md).
|
|
97
|
+
The plan: [docs/PLAN.md](docs/PLAN.md).
|
marcarr-0.1.0/README.md
ADDED
|
@@ -0,0 +1,56 @@
|
|
|
1
|
+
# Marcarr
|
|
2
|
+
|
|
3
|
+
*marcar*: to mark.
|
|
4
|
+
|
|
5
|
+
Marcarr is a self-hosted service that runs next to Plex. It looks at each film
|
|
6
|
+
or episode once and records what is in it: camera cuts, subtitle lines, scenes,
|
|
7
|
+
measured signals, faces, cast and tags ("christmas", "rain", "a cave"). Other
|
|
8
|
+
apps ask Marcarr instead of analysing the file again.
|
|
9
|
+
|
|
10
|
+
Its first two clients are [FansCut](https://github.com/jhd3197/FansCut), which
|
|
11
|
+
builds cuts from tagged scenes, and [Doblarr](https://github.com/jhd3197/Doblarr),
|
|
12
|
+
which dubs and needs to know where a line is said and who is on screen.
|
|
13
|
+
|
|
14
|
+
## On its own
|
|
15
|
+
|
|
16
|
+
You don't need FansCut or Doblarr to use Marcarr. Point it at your Plex server
|
|
17
|
+
and it gives you:
|
|
18
|
+
|
|
19
|
+
- **Scene search across your library**: every rain scene, every Christmas
|
|
20
|
+
dinner, every scene with a given actor, with the film and the time it starts.
|
|
21
|
+
- **Plex labels and collections**: films with a tag get a label (`marcarr:christmas`),
|
|
22
|
+
so a Kometa or smart-collection rule can build a "Christmas scenes" row.
|
|
23
|
+
- **A review page**: accept, fix or reject what the AI proposed, scene by scene.
|
|
24
|
+
- **Tools for AI clients**: an MCP server, so an assistant can ask "where does
|
|
25
|
+
this happen?" or tag a scene itself.
|
|
26
|
+
- **An API and one JSON file per video**: for any other tool that wants to know
|
|
27
|
+
what is in a file without decoding it.
|
|
28
|
+
|
|
29
|
+
## Running it
|
|
30
|
+
|
|
31
|
+
```
|
|
32
|
+
python -m venv .venv && .venv/Scripts/pip install -e ".[faces,mcp,dev]" # or bin/pip
|
|
33
|
+
cd ui && npm install && npm run build && cd ..
|
|
34
|
+
marcarr serve # http://127.0.0.1:7470, first run opens the setup
|
|
35
|
+
```
|
|
36
|
+
|
|
37
|
+
Or `docker compose up -d --build`. Settings are in `config.yaml`
|
|
38
|
+
(see `config.example.yaml`); the Settings page edits it.
|
|
39
|
+
|
|
40
|
+
Other commands: `marcarr scan` (read Plex once), `marcarr analyse <file>`
|
|
41
|
+
(one file, no Plex), `marcarr mcp` (MCP server on stdio), `marcarr status`.
|
|
42
|
+
|
|
43
|
+
For UI work without Plex: `python scripts/seed_demo.py --config demo/config.yaml video.mp4`,
|
|
44
|
+
then `marcarr --config demo/config.yaml serve`, and `npm run dev` in `ui/`
|
|
45
|
+
(proxies `/api` to port 7470).
|
|
46
|
+
|
|
47
|
+
## Layout
|
|
48
|
+
|
|
49
|
+
- `marcarr/stages/`: the analysis code taken from FansCut (subtitles, scenes,
|
|
50
|
+
signals, cast, faces, the tagger and its prompts, the 130-tag list).
|
|
51
|
+
- `marcarr/pipeline.py`: the seven steps per video, states, staleness, cost.
|
|
52
|
+
- `marcarr/routes/`: the v1 API. `ui/src/api/types.ts` is the contract.
|
|
53
|
+
- `ui/`: React + Vite, built from the design in `docs/design/`.
|
|
54
|
+
|
|
55
|
+
Connecting FansCut and Doblarr: [docs/CLIENTS.md](docs/CLIENTS.md).
|
|
56
|
+
The plan: [docs/PLAN.md](docs/PLAN.md).
|
|
@@ -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)
|
|
@@ -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)
|
|
@@ -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)
|
|
@@ -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
|