Metadata-Version: 2.4
Name: reelith
Version: 0.0.1
Classifier: Programming Language :: Rust
Classifier: Programming Language :: Python :: 3
Classifier: Topic :: Multimedia :: Video
Requires-Dist: mcp>=1.9
Requires-Dist: numpy>=1.26
Requires-Dist: pyarrow>=15
Requires-Dist: httpx>=0.27
Requires-Dist: beautifulsoup4>=4.12
Requires-Dist: lxml>=5
License-File: LICENSE
Summary: Local MCP film recommender for your Letterboxd history
Keywords: mcp,letterboxd,recommendations,model-context-protocol
Author: Mahdi Alikhah
License: MIT
Requires-Python: >=3.11
Description-Content-Type: text/markdown; charset=UTF-8; variant=GFM
Project-URL: Homepage, https://github.com/MahdiAlikhah/reelith
Project-URL: Issues, https://github.com/MahdiAlikhah/reelith/issues
Project-URL: Repository, https://github.com/MahdiAlikhah/reelith

# reelith

[![CI](https://github.com/MahdiAlikhah/reelith/actions/workflows/ci.yml/badge.svg)](https://github.com/MahdiAlikhah/reelith/actions/workflows/ci.yml)
[![PyPI](https://img.shields.io/pypi/v/reelith)](https://pypi.org/project/reelith/)
[![License: MIT](https://img.shields.io/badge/license-MIT-blue.svg)](LICENSE)
[![Python 3.11+](https://img.shields.io/badge/python-3.11%2B-blue.svg)](pyproject.toml)

A local, offline-capable film recommender for your Letterboxd history.

Your client LLM acts as a **semantic router**: it turns "something cynical and
slick" into anchor films like *Fight Club* and *Nightcrawler*, and a local vector
engine does the actual search. Nothing about your taste leaves your machine, and
the recommendations come from arithmetic over your own ratings rather than from a
model's memory.

## How it works

```
your mood
   │
   ▼
client LLM (BYO: Claude Desktop, ...)      ← semantic router, no recommendations of its own
   │  MCP over stdio, three tools
   ▼
Python MCP server  ──────────────┐
   │                             │
   ▼                             ▼
Rust/PyO3 vector engine      SQLite local state
(cosine + Hilbert + Lehmer)  (history, policy, cache)
```

- **Anchors → vector.** Your positive anchors become a centroid; the policy blends
  it with a learned vector `s_t` (state `S₀` is a flat, unweighted centroid of your
  rated history — the MDP starting state).
- **Search.** Cosine scores over the whole catalog, then a top-*m* region ordered
  by Hilbert rank and sampled by weighted Lehmer unranking. Sampling without
  replacement, no duplicates, tunable temperature. As temperature approaches zero,
  the output converges exactly to greedy.
- **Feedback.** `accept` / `reject_dislike` move `s_t`; `reject_seen_it` only masks.

## Requirements

- Python 3.11+
- [uv](https://docs.astral.sh/uv/)

That is all a user needs. The Rust extension ships as a prebuilt `abi3` wheel
(one wheel covers every Python 3.11+), and the recommendation index builds
itself on first run, so there is no compiler and no setup step.

## Install (users)

The server entry is always the same — `uvx reelith`, stdio transport. No compiler,
no config file, nothing to build.

```bash
uvx reelith doctor        # check this machine, then prints your client entry
```

Then add it to any MCP client:

```json
{ "mcpServers": { "reelith": { "command": "uvx", "args": ["reelith"] } } }
```

Claude Code:

```bash
claude mcp add reelith -- uvx reelith
```

`reelith doctor` is worth running first: the first recommendation downloads the
index, and in most MCP clients that progress goes to a stderr stream the host
never shows. Running it in a terminal once means the download happens where you
can see it.

## The download (what it is and why)

reelith needs a **vector index** to rank films: one vector per film, learned from
10.2 million Letterboxd ratings. That is the model. It is not a cache of the
site, and it is not your data — it is what makes recommendations arithmetic
instead of an LLM guessing.

It comes as three files totalling ~40 MB, fetched once into `~/.reelith/artifact/`:

| File | Size | What it is |
|---|---|---|
| `embeddings.bin` | 34 MB | 138,016 films × 64 floats. The actual vectors. |
| `films.sidecar.parquet` | 6.1 MB | Per-film metadata: slug, title, and `year` for the subset that has one. |
| `meta.json` | 300 B | Dimensions and build provenance, used for integrity checks. |

**Why not ship them inside the package?** A wheel is downloaded per virtualenv,
per platform. The index is fetched once per machine and shared by every client
that uses reelith.

**Why not fetch live from Letterboxd?** Rediscovering 138k films on every query
would be slow, rate-limited, and `robots.txt` forbids the browse pages. Live
Letterboxd is used only to bridge a film the index has never seen.

**After the first run there is no network requirement.** Queries are answered
from the mmap'd vectors on disk.

If the bundle is unreachable, reelith falls back to rebuilding from the public
[Letterboxd 10M ratings dataset](https://huggingface.co/datasets/titouann/letterboxd-10m-movies-ratings-2025):
`/prep/fetch-letterboxd` (~107 MB) then `letterboxd`, ~30 s of CPU. Same index,
more bytes. A self-hoster is never stuck.

Override the location with `REELITH_HOME`, point at a bundle or mirror with
`REELITH_BUNDLE_URL`, use a prebuilt index with `REELITH_ARTIFACT_DIR`, or set
`REELITH_NO_BOOTSTRAP=1` to get the old loud failure instead (useful in CI and
offline runs).

## Install (per client)

The entry is identical everywhere — `uvx reelith`, stdio transport — because
`uvx` resolves the package without you choosing a Python or a venv. Copy the row
for your client.

**Claude Code**
```bash
claude mcp add reelith -- uvx reelith
```

**Claude Desktop** — `claude_desktop_config.json` (Windows:
`%APPDATA%\Claude\`, macOS: `~/Library/Application Support/Claude/`, Linux:
`~/.config/Claude/`):
```json
{ "mcpServers": { "reelith": { "command": "uvx", "args": ["reelith"] } } }
```
Restart Claude Desktop afterwards.

**Cursor** — `~/.cursor/mcp.json`:
```json
{ "mcpServers": { "reelith": { "command": "uvx", "args": ["reelith"] } } }
```

**VS Code** — `.vscode/mcp.json`:
```json
{ "servers": { "reelith": { "type": "stdio", "command": "uvx", "args": ["reelith"] } } }
```

**Codex CLI**
```bash
codex mcp add reelith -- uvx reelith
```

**Gemini CLI** — `~/.gemini/settings.json`:
```json
{ "mcpServers": { "reelith": { "command": "uvx", "args": ["reelith"] } } }
```

**DeepSeek Harness** — `~/.dsh/profiles/<profile>/cordis.patch.yml`:
```yaml
- id: reelith
  command: 'uvx'
  args: ['reelith']
```

**Anything else** that speaks MCP over stdio: the command is `uvx`, the args are
`["reelith"]`. That is the whole interface.

Do not have `uv`? Install it first:
`powershell -c "irm https://astral.sh/uv/install.ps1 | iex"` (Windows) or
`curl -LsSf https://astral.sh/uv/install.sh | sh` (macOS/Linux).

### Without uvx

```bash
pip install reelith     # compiles Rust; needs a toolchain
reelith doctor
```
Then use `"command": "reelith"` with no args. Prefer `uvx`: it needs no compiler
and no venv.

## Develop

```bash
uv sync                       # builds the Rust extension from source
uv run pytest                 # 238 tests, no network needed
```

The `prep` dependency group (dataset build only) is not installed by default: it is
large and the server never imports it. Add it with `uv sync --group prep` when you
build an artifact.

Try it against the committed synthetic fixture before building a real artifact:

```bash
uv run python examples/quickstart.py
```

That drives all three tools over a real MCP client session — ingest a sample
export, query, record feedback — and prints what comes back. No client to
configure, no network, no API key. To use a real artifact instead:

```bash
uv run python examples/quickstart.py --artifact data/artifacts/dev --state data/demo.db
```

To run the actual server (what a client launches), use `uv run reelith` with the
environment variables from [docs/client-config.md](docs/client-config.md).

## Build a real artifact

The committed fixture is 200 synthetic films — enough to exercise every code path,
not enough to recommend anything. For real use, build from a ratings dataset:

```bash
uv run --group prep python -m reelith.prep build \
    --dataset <huggingface-dataset> \
    --outdir data/artifacts/dev
```

This produces three files, which travel together:

| File | Contents |
|---|---|
| `embeddings.bin` | `LREC` magic, version, N, dim, then N×dim float32 unit vectors |
| `films.sidecar.parquet` | slug, title, year, runtime, director, genres, `hilbert_rank` (several are empty: see below) |
| `meta.json` | build parameters, dim, row count, checksums |

Expected scale: ~159k films × 64 dims ≈ 41 MB. See
[docs/FULL-BUILD.md](docs/FULL-BUILD.md) for the full-size build and
[docs/OFFLINE-BUILD.md](docs/OFFLINE-BUILD.md) for a no-network build.

## Connect a client

See **[docs/client-config.md](docs/client-config.md)**. Short version: register
`reelith` as a stdio MCP server, point `REELITH_ARTIFACT_DIR` at your artifact, and
paste **[docs/SYSTEM-PROMPT.md](docs/SYSTEM-PROMPT.md)** into the client's custom
instructions.

## The three tools

| Tool | Purpose |
|---|---|
| `ingest_letterboxd_data(username \| local_zip_path)` | Load history from a public profile or export zip. Exactly one argument. |
| `query_embedding_space(positive_anchor_movies, ...)` | Recommend films near the anchors. Supports `k`, negatives, director/year/runtime filters, `include_watched`. |
| `record_rl_feedback(movie_id, feedback_type)` | `accept` / `reject_dislike` / `reject_seen_it`. |

Anchors are film titles, not moods — the client LLM supplies the semantics. Titles
outside the local index come back in `missing_anchors` with a reason
(`no_api_key`, `no_tmdb_result`, `no_proxy`, `network`) so the client can say so
honestly instead of guessing.

## Prompts and resources

Two more MCP surfaces, both read-only, for jobs that are not tool calls:

| Surface | Name | What it does |
|---|---|---|
| prompt | `recommend` | Takes a `mood`, expands it into the "find anchors, then query" instruction. |
| prompt | `onboard` | The setup flow: ask for a username or export zip, then ingest. |
| resource | `reelith://index` | Films, dimensions, ratings and history size — the index's provenance. |
| resource | `reelith://history` | Your films with the rating that counts, newest first. |
| resource | `reelith://films/{slug}` | One film record. |

Resources are what a person can *attach* to a conversation; tools are what the
model calls. Inspect engine state without burning a turn on a tool call.

Caveat on `reelith://films/{slug}`: the artifact carries `year` for only 22,289 of
138,016 films, and no genres, director or runtime at all. Those fields are `null`,
not zero — the ratings dump does not include them.

## Layout

```
src/reelith/
  server.py      MCP server, three tools
  context.py     startup wiring: artifact, engine, state, policy, resolver
  prompts.py     the system prompt (canonical copy)
  artifact.py    artifact loading
  state.py       SQLite: history, policy, trajectories, TMDB cache
  rl.py          policy: S0, query blending, feedback updates, temperature
  oov.py         out-of-vocabulary resolution + TMDB proxy imputation
  ingest/        zip parsing, scraping, pagination
  prep/          artifact build: ALS, dimensionality reduction, Hilbert keys
crates/reelith-engine/   Rust: mmap vectors, Fenwick sampling, Hilbert ordering
spec/                   per-module specs
tasks/                  plan, task list, checkpoints
```

## Testing

```bash
uv run pytest                    # everything
uv run pytest tests/server -q    # MCP tools through a real client session
cargo test --offline             # Rust: sampling, Fenwick, Hilbert
```

The test suite needs no network. Scraper tests use synthetic HTML fixtures that
reproduce Letterboxd's documented markup conventions — they pin our parsers'
behavior, but they were not recorded from the live site, so a future DOM change
would not be caught by them. The parsers fail loudly rather than silently dropping
rows.

## Known limits

- **Coverage is the artifact's vocabulary.** Films outside it are resolved through
  TMDB proxies or reported missing; they are never invented.
- **Scraping is best-effort.** Letterboxd has no public API and may change its
  markup. The zip export path is the stable fallback.
- **Embeddings are trained geometry, not semantics.** A random-projection fallback
  replaces UMAP when `umap-learn` is unavailable; recommendations remain coherent
  but less sharp.
- **Single user, single process.** stdio transport, one state database, no auth.

## License

Not yet chosen.

