topit-mcp 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.
- topit_mcp/__init__.py +1 -0
- topit_mcp/auth.py +162 -0
- topit_mcp/client.py +156 -0
- topit_mcp/dupes.py +78 -0
- topit_mcp/export.py +85 -0
- topit_mcp/images.py +156 -0
- topit_mcp/server.py +139 -0
- topit_mcp-0.1.0.dist-info/METADATA +81 -0
- topit_mcp-0.1.0.dist-info/RECORD +11 -0
- topit_mcp-0.1.0.dist-info/WHEEL +4 -0
- topit_mcp-0.1.0.dist-info/entry_points.txt +2 -0
topit_mcp/__init__.py
ADDED
|
@@ -0,0 +1 @@
|
|
|
1
|
+
"""Topit local companion: an MCP stdio server that ranks, de-duplicates and exports the photos in a folder."""
|
topit_mcp/auth.py
ADDED
|
@@ -0,0 +1,162 @@
|
|
|
1
|
+
"""How the companion signs in to Topit.
|
|
2
|
+
|
|
3
|
+
1. TOPIT_API_KEY: a personal key (tpk_...) from mytopit.com/settings/api. Best for CI and for
|
|
4
|
+
Claude Desktop config files.
|
|
5
|
+
2. `topit-mcp login`: the browser sign-in. The companion registers itself with Topit's OAuth server
|
|
6
|
+
(the same one the remote connector uses), opens the consent page, receives the code on a one-time
|
|
7
|
+
loopback address (http://127.0.0.1:<port>/callback, RFC 8252) and exchanges it with PKCE. The tokens
|
|
8
|
+
are saved in ~/.config/topit/credentials.json (readable only by you) and refreshed when they expire.
|
|
9
|
+
`topit-mcp logout` deletes the file and revokes the connection.
|
|
10
|
+
"""
|
|
11
|
+
from __future__ import annotations
|
|
12
|
+
|
|
13
|
+
import base64
|
|
14
|
+
import contextlib
|
|
15
|
+
import hashlib
|
|
16
|
+
import http.server
|
|
17
|
+
import json
|
|
18
|
+
import os
|
|
19
|
+
import secrets
|
|
20
|
+
import tempfile
|
|
21
|
+
import threading
|
|
22
|
+
import time
|
|
23
|
+
import webbrowser
|
|
24
|
+
from pathlib import Path
|
|
25
|
+
from typing import Optional
|
|
26
|
+
from urllib.parse import parse_qs, urlencode, urlparse
|
|
27
|
+
|
|
28
|
+
import httpx
|
|
29
|
+
|
|
30
|
+
from topit_mcp.client import api_base
|
|
31
|
+
|
|
32
|
+
SCOPES = "photos:rank taste:read"
|
|
33
|
+
|
|
34
|
+
|
|
35
|
+
def creds_path() -> Path:
|
|
36
|
+
base = Path(os.getenv("XDG_CONFIG_HOME") or Path.home() / ".config")
|
|
37
|
+
return base / "topit" / "credentials.json"
|
|
38
|
+
|
|
39
|
+
|
|
40
|
+
def _save(data: dict) -> None:
|
|
41
|
+
p = creds_path()
|
|
42
|
+
p.parent.mkdir(parents=True, exist_ok=True)
|
|
43
|
+
# A temporary file of its own for each write (mkstemp: a unique name, created 0600 in the same call,
|
|
44
|
+
# so another user never has a moment to open the refresh token), then an atomic replace. A shared
|
|
45
|
+
# name let two sign-ins delete or collide with each other's file (Greptile on #2308).
|
|
46
|
+
fd, tmp = tempfile.mkstemp(dir=p.parent, prefix=".credentials-", suffix=".tmp")
|
|
47
|
+
try:
|
|
48
|
+
with os.fdopen(fd, "w") as f:
|
|
49
|
+
f.write(json.dumps(data))
|
|
50
|
+
os.replace(tmp, p)
|
|
51
|
+
except BaseException:
|
|
52
|
+
with contextlib.suppress(FileNotFoundError):
|
|
53
|
+
os.unlink(tmp)
|
|
54
|
+
raise
|
|
55
|
+
|
|
56
|
+
|
|
57
|
+
def _load() -> Optional[dict]:
|
|
58
|
+
p = creds_path()
|
|
59
|
+
if not p.is_file():
|
|
60
|
+
return None
|
|
61
|
+
try:
|
|
62
|
+
return json.loads(p.read_text())
|
|
63
|
+
except Exception: # noqa: BLE001
|
|
64
|
+
return None
|
|
65
|
+
|
|
66
|
+
|
|
67
|
+
class NotSignedIn(Exception):
|
|
68
|
+
pass
|
|
69
|
+
|
|
70
|
+
|
|
71
|
+
def token() -> str:
|
|
72
|
+
"""The credential to send: TOPIT_API_KEY, else a fresh OAuth access token."""
|
|
73
|
+
key = (os.getenv("TOPIT_API_KEY") or "").strip()
|
|
74
|
+
if key:
|
|
75
|
+
return key
|
|
76
|
+
# Upload threads call this at the same time. The refresh token rotates on every use, so only one
|
|
77
|
+
# thread may refresh; the others wait and then read the token it saved.
|
|
78
|
+
with _refresh_lock:
|
|
79
|
+
return _token_locked()
|
|
80
|
+
|
|
81
|
+
|
|
82
|
+
_refresh_lock = threading.Lock()
|
|
83
|
+
|
|
84
|
+
|
|
85
|
+
def _token_locked() -> str:
|
|
86
|
+
data = _load()
|
|
87
|
+
if not data:
|
|
88
|
+
raise NotSignedIn("Not signed in to Topit. Set TOPIT_API_KEY (a key from mytopit.com/settings/api) "
|
|
89
|
+
"or run `topit-mcp login` once.")
|
|
90
|
+
if data.get("expires_at", 0) - 60 > time.time():
|
|
91
|
+
return data["access_token"]
|
|
92
|
+
r = httpx.post(f"{data['api']}/oauth/token", timeout=30, data={
|
|
93
|
+
"grant_type": "refresh_token", "refresh_token": data["refresh_token"], "client_id": data["client_id"]})
|
|
94
|
+
if r.status_code != 200:
|
|
95
|
+
raise NotSignedIn("Your Topit sign-in has expired or was revoked. Run `topit-mcp login` again.")
|
|
96
|
+
tok = r.json()
|
|
97
|
+
data.update(access_token=tok["access_token"], refresh_token=tok.get("refresh_token", data["refresh_token"]),
|
|
98
|
+
expires_at=time.time() + int(tok.get("expires_in") or 3600))
|
|
99
|
+
_save(data)
|
|
100
|
+
return data["access_token"]
|
|
101
|
+
|
|
102
|
+
|
|
103
|
+
def login(api: Optional[str] = None, open_browser: bool = True, timeout_s: int = 300) -> str:
|
|
104
|
+
api = (api or api_base()).rstrip("/")
|
|
105
|
+
got: dict = {}
|
|
106
|
+
|
|
107
|
+
class Handler(http.server.BaseHTTPRequestHandler):
|
|
108
|
+
def do_GET(self): # noqa: N802
|
|
109
|
+
q = parse_qs(urlparse(self.path).query)
|
|
110
|
+
got.update({k: v[0] for k, v in q.items()})
|
|
111
|
+
ok = "code" in got
|
|
112
|
+
self.send_response(200)
|
|
113
|
+
self.send_header("Content-Type", "text/html; charset=utf-8")
|
|
114
|
+
self.end_headers()
|
|
115
|
+
self.wfile.write(("<p>Topit is connected. You can close this tab.</p>" if ok else
|
|
116
|
+
"<p>Topit was not connected. You can close this tab.</p>").encode())
|
|
117
|
+
|
|
118
|
+
def log_message(self, *a): # quiet
|
|
119
|
+
pass
|
|
120
|
+
|
|
121
|
+
srv = http.server.HTTPServer(("127.0.0.1", 0), Handler)
|
|
122
|
+
redirect = f"http://127.0.0.1:{srv.server_address[1]}/callback"
|
|
123
|
+
reg = httpx.post(f"{api}/oauth/register", timeout=30, json={
|
|
124
|
+
"client_name": "Topit local companion", "redirect_uris": [redirect], "token_endpoint_auth_method": "none",
|
|
125
|
+
"grant_types": ["authorization_code", "refresh_token"], "response_types": ["code"], "scope": SCOPES})
|
|
126
|
+
reg.raise_for_status()
|
|
127
|
+
client_id = reg.json()["client_id"]
|
|
128
|
+
verifier = secrets.token_urlsafe(48)
|
|
129
|
+
challenge = base64.urlsafe_b64encode(hashlib.sha256(verifier.encode()).digest()).decode().rstrip("=")
|
|
130
|
+
state = secrets.token_urlsafe(16)
|
|
131
|
+
url = f"{api}/oauth/authorize?" + urlencode({
|
|
132
|
+
"response_type": "code", "client_id": client_id, "redirect_uri": redirect, "code_challenge": challenge,
|
|
133
|
+
"code_challenge_method": "S256", "state": state, "scope": SCOPES, "resource": f"{api}/mcp"})
|
|
134
|
+
print(f"Open this link to sign in to Topit:\n{url}\n", flush=True)
|
|
135
|
+
if open_browser:
|
|
136
|
+
webbrowser.open(url)
|
|
137
|
+
t = threading.Thread(target=lambda: [srv.handle_request() for _ in range(3) if "code" not in got and "error" not in got])
|
|
138
|
+
t.start()
|
|
139
|
+
t.join(timeout_s)
|
|
140
|
+
srv.server_close()
|
|
141
|
+
if got.get("state") != state or "code" not in got:
|
|
142
|
+
raise NotSignedIn(f"Sign-in did not finish ({got.get('error') or 'no answer'}).")
|
|
143
|
+
r = httpx.post(f"{api}/oauth/token", timeout=30, data={
|
|
144
|
+
"grant_type": "authorization_code", "code": got["code"], "redirect_uri": redirect, "client_id": client_id,
|
|
145
|
+
"code_verifier": verifier, "resource": f"{api}/mcp"})
|
|
146
|
+
r.raise_for_status()
|
|
147
|
+
tok = r.json()
|
|
148
|
+
_save({"api": api, "client_id": client_id, "access_token": tok["access_token"],
|
|
149
|
+
"refresh_token": tok["refresh_token"], "expires_at": time.time() + int(tok.get("expires_in") or 3600)})
|
|
150
|
+
return "Signed in to Topit."
|
|
151
|
+
|
|
152
|
+
|
|
153
|
+
def logout() -> str:
|
|
154
|
+
data = _load()
|
|
155
|
+
if data:
|
|
156
|
+
try:
|
|
157
|
+
httpx.post(f"{data['api']}/oauth/revoke", timeout=15, data={
|
|
158
|
+
"token": data["refresh_token"], "client_id": data["client_id"], "client_secret": ""})
|
|
159
|
+
except Exception: # noqa: BLE001
|
|
160
|
+
pass
|
|
161
|
+
creds_path().unlink(missing_ok=True)
|
|
162
|
+
return "Signed out of Topit."
|
topit_mcp/client.py
ADDED
|
@@ -0,0 +1,156 @@
|
|
|
1
|
+
"""The Topit API client: one agent-rank session, parallel uploads, one rank, and nothing left behind.
|
|
2
|
+
|
|
3
|
+
The same routes and account as the remote connector (backend api/agent_rank.py). Photos are decoded
|
|
4
|
+
and downscaled in a process pool while earlier chunks upload, 4 uploads in flight, so the slow part is
|
|
5
|
+
the upload link, not the CPU. A 429 waits for Retry-After and tries again; a 402 (the month's
|
|
6
|
+
allowance) stops at once and its message is passed on as it is.
|
|
7
|
+
"""
|
|
8
|
+
from __future__ import annotations
|
|
9
|
+
|
|
10
|
+
import os
|
|
11
|
+
import threading
|
|
12
|
+
import time
|
|
13
|
+
from concurrent.futures import FIRST_COMPLETED, ThreadPoolExecutor, wait
|
|
14
|
+
from dataclasses import dataclass, field
|
|
15
|
+
from typing import Callable, Dict, List, Optional, Sequence
|
|
16
|
+
|
|
17
|
+
import httpx
|
|
18
|
+
|
|
19
|
+
from topit_mcp import images
|
|
20
|
+
|
|
21
|
+
DEFAULT_API = "https://api.mytopit.com"
|
|
22
|
+
CHUNK = 25 # photos per upload call (the server takes up to 50 and 20 MB)
|
|
23
|
+
IN_FLIGHT = 4 # concurrent upload calls
|
|
24
|
+
|
|
25
|
+
|
|
26
|
+
class TopitError(Exception):
|
|
27
|
+
"""A message meant for the user, as Topit wrote it."""
|
|
28
|
+
|
|
29
|
+
|
|
30
|
+
def api_base() -> str:
|
|
31
|
+
return (os.getenv("TOPIT_API_URL") or DEFAULT_API).rstrip("/")
|
|
32
|
+
|
|
33
|
+
|
|
34
|
+
@dataclass
|
|
35
|
+
class RankOutcome:
|
|
36
|
+
ranked: List[dict]
|
|
37
|
+
skipped: List[dict] = field(default_factory=list)
|
|
38
|
+
allowance: Optional[dict] = None
|
|
39
|
+
timings: Dict[str, float] = field(default_factory=dict)
|
|
40
|
+
photos: int = 0
|
|
41
|
+
groups: int = 0
|
|
42
|
+
|
|
43
|
+
|
|
44
|
+
class TopitClient:
|
|
45
|
+
def __init__(self, token_provider: Callable[[], str], base_url: Optional[str] = None,
|
|
46
|
+
transport: Optional[httpx.BaseTransport] = None):
|
|
47
|
+
self._token = token_provider
|
|
48
|
+
self.base = (base_url or api_base()).rstrip("/")
|
|
49
|
+
self._http = httpx.Client(base_url=self.base, timeout=httpx.Timeout(120.0, connect=15.0),
|
|
50
|
+
transport=transport, headers={"User-Agent": "topit-mcp/0.1"})
|
|
51
|
+
|
|
52
|
+
def close(self) -> None:
|
|
53
|
+
self._http.close()
|
|
54
|
+
|
|
55
|
+
def _call(self, method: str, path: str, **kw) -> dict:
|
|
56
|
+
for attempt in range(6):
|
|
57
|
+
r = self._http.request(method, path, headers={"Authorization": f"Bearer {self._token()}"}, **kw)
|
|
58
|
+
if r.status_code == 429 and attempt < 5:
|
|
59
|
+
time.sleep(min(30.0, float(r.headers.get("Retry-After") or 2)))
|
|
60
|
+
continue
|
|
61
|
+
if r.status_code >= 400:
|
|
62
|
+
try:
|
|
63
|
+
body = r.json()
|
|
64
|
+
if isinstance(body.get("detail"), dict):
|
|
65
|
+
body = body["detail"]
|
|
66
|
+
msg = body.get("message") or body.get("detail") or body.get("error") or r.text
|
|
67
|
+
except Exception: # noqa: BLE001
|
|
68
|
+
msg = r.text or f"HTTP {r.status_code}"
|
|
69
|
+
if r.status_code == 401:
|
|
70
|
+
msg = ("Topit did not accept your sign-in. Set TOPIT_API_KEY to a key from "
|
|
71
|
+
"mytopit.com/settings/api, or run `topit-mcp login`.")
|
|
72
|
+
raise TopitError(str(msg))
|
|
73
|
+
return r.json()
|
|
74
|
+
raise TopitError("Topit is busy. Try again in a minute.")
|
|
75
|
+
|
|
76
|
+
def usage(self, workspace: Optional[str] = None) -> dict:
|
|
77
|
+
return self._call("GET", "/v1/agent-rank/usage", params={"workspace": workspace} if workspace else None)
|
|
78
|
+
|
|
79
|
+
def rank_paths(self, paths: Sequence[str], *, context: str, top_k: int, vibe: Optional[str] = None,
|
|
80
|
+
workspace: Optional[str] = None, progress: Optional[Callable[[int, int, str], None]] = None
|
|
81
|
+
) -> RankOutcome:
|
|
82
|
+
"""Downscale, upload and rank `paths`. Ids sent to Topit are indexes, never file names."""
|
|
83
|
+
t0 = time.perf_counter()
|
|
84
|
+
sess = self._call("POST", "/v1/agent-rank/sessions", json={"workspace": workspace} if workspace else {})
|
|
85
|
+
sid = sess["session_id"]
|
|
86
|
+
allowance = sess.get("allowance") or {}
|
|
87
|
+
if allowance and allowance.get("remaining", len(paths)) < len(paths):
|
|
88
|
+
# Refuse before uploading anything: the server would stop at the allowance anyway.
|
|
89
|
+
self._call("DELETE", f"/v1/agent-rank/sessions/{sid}")
|
|
90
|
+
raise TopitError(
|
|
91
|
+
f"This folder has {len(paths)} photos but only {allowance['remaining']} of the "
|
|
92
|
+
f"{allowance['allowance']} photos a month on the {allowance.get('plan_label', 'current')} plan are left. "
|
|
93
|
+
f"The allowance resets on {allowance.get('reset_label')}. Upgrade for more at "
|
|
94
|
+
f"{allowance.get('upgrade_url')} , or rank fewer photos.")
|
|
95
|
+
skipped: List[dict] = []
|
|
96
|
+
uploaded = 0
|
|
97
|
+
lock = threading.Lock()
|
|
98
|
+
timings: Dict[str, float] = {}
|
|
99
|
+
try:
|
|
100
|
+
pending: List[images.Prepared] = []
|
|
101
|
+
futures = set()
|
|
102
|
+
with ThreadPoolExecutor(max_workers=IN_FLIGHT) as up_pool, \
|
|
103
|
+
images.pool() as cpu:
|
|
104
|
+
|
|
105
|
+
def _send(batch: List[images.Prepared]):
|
|
106
|
+
files = [("files", (str(p.index), p.data, "image/jpeg")) for p in batch]
|
|
107
|
+
res = self._call("POST", f"/v1/agent-rank/sessions/{sid}/photos", files=files)
|
|
108
|
+
nonlocal uploaded
|
|
109
|
+
with lock:
|
|
110
|
+
uploaded += res.get("accepted", 0)
|
|
111
|
+
for rej in res.get("rejected", []):
|
|
112
|
+
skipped.append({"path": paths[int(rej["id"])], "reason": rej["reason"]})
|
|
113
|
+
if progress:
|
|
114
|
+
progress(uploaded, len(paths), "uploading")
|
|
115
|
+
return res
|
|
116
|
+
|
|
117
|
+
for prep in cpu.map(images.prepare, list(enumerate(paths)), chunksize=4):
|
|
118
|
+
if prep.data is None:
|
|
119
|
+
skipped.append({"path": prep.path, "reason": prep.error or "could not read"})
|
|
120
|
+
continue
|
|
121
|
+
pending.append(prep)
|
|
122
|
+
if len(pending) >= CHUNK:
|
|
123
|
+
if len(futures) >= IN_FLIGHT:
|
|
124
|
+
done, futures = wait(futures, return_when=FIRST_COMPLETED)
|
|
125
|
+
for f in done:
|
|
126
|
+
f.result()
|
|
127
|
+
futures.add(up_pool.submit(_send, pending))
|
|
128
|
+
pending = []
|
|
129
|
+
if pending:
|
|
130
|
+
futures.add(up_pool.submit(_send, pending))
|
|
131
|
+
for f in futures:
|
|
132
|
+
f.result()
|
|
133
|
+
timings["prepare_and_upload_s"] = round(time.perf_counter() - t0, 2)
|
|
134
|
+
if uploaded == 0:
|
|
135
|
+
raise TopitError("None of these files could be read as photos.")
|
|
136
|
+
if progress:
|
|
137
|
+
progress(uploaded, len(paths), "ranking")
|
|
138
|
+
t1 = time.perf_counter()
|
|
139
|
+
out = self._call("POST", f"/v1/agent-rank/sessions/{sid}/rank",
|
|
140
|
+
json={"context": context, "top_k": top_k, "vibe": vibe})
|
|
141
|
+
timings["rank_s"] = round(time.perf_counter() - t1, 2)
|
|
142
|
+
timings["total_s"] = round(time.perf_counter() - t0, 2)
|
|
143
|
+
except BaseException:
|
|
144
|
+
try:
|
|
145
|
+
self._call("DELETE", f"/v1/agent-rank/sessions/{sid}")
|
|
146
|
+
except Exception: # noqa: BLE001 the session expires in 15 minutes anyway
|
|
147
|
+
pass
|
|
148
|
+
raise
|
|
149
|
+
ranked = []
|
|
150
|
+
for r in out.get("ranked", []):
|
|
151
|
+
item = dict(r)
|
|
152
|
+
item["path"] = paths[int(r["id"])]
|
|
153
|
+
item.pop("id", None)
|
|
154
|
+
ranked.append(item)
|
|
155
|
+
return RankOutcome(ranked=ranked, skipped=skipped, allowance=out.get("allowance"), timings=timings,
|
|
156
|
+
photos=out.get("photos", 0), groups=out.get("groups", 0))
|
topit_mcp/dupes.py
ADDED
|
@@ -0,0 +1,78 @@
|
|
|
1
|
+
"""Near-duplicate groups, fully offline: nothing is sent anywhere and no account is needed.
|
|
2
|
+
|
|
3
|
+
The same grouping the Topit backend uses (ml/culling.cluster_by_phash): a 64-bit perceptual hash
|
|
4
|
+
(imagehash.phash) per photo and single-linkage groups at Hamming distance <= 18, which catches bursts,
|
|
5
|
+
crops and exposure variants. The suggested keeper in each group is the sharpest well-exposed shot:
|
|
6
|
+
Laplacian variance (the backend's blur measure) at 512 px, scaled down for clipped highlights or
|
|
7
|
+
shadows. This is a local estimate, not Topit's ranking; rank_photos gives that.
|
|
8
|
+
"""
|
|
9
|
+
from __future__ import annotations
|
|
10
|
+
|
|
11
|
+
from pathlib import Path
|
|
12
|
+
from typing import Dict, List, Optional, Tuple
|
|
13
|
+
|
|
14
|
+
import numpy as np
|
|
15
|
+
|
|
16
|
+
from topit_mcp import images
|
|
17
|
+
|
|
18
|
+
MAX_DIST = 18
|
|
19
|
+
|
|
20
|
+
|
|
21
|
+
def _measure(arg: Tuple[int, str]) -> Optional[Dict]:
|
|
22
|
+
i, p = arg
|
|
23
|
+
try:
|
|
24
|
+
import imagehash
|
|
25
|
+
|
|
26
|
+
im = images.open_upright(Path(p), 512)
|
|
27
|
+
ph = int(str(imagehash.phash(im)), 16)
|
|
28
|
+
g = np.asarray(im.convert("L"), dtype=np.float32)
|
|
29
|
+
lap = (-4 * g[1:-1, 1:-1] + g[:-2, 1:-1] + g[2:, 1:-1] + g[1:-1, :-2] + g[1:-1, 2:])
|
|
30
|
+
sharp = float(lap.var())
|
|
31
|
+
clipped = float(((g < 8) | (g > 247)).mean())
|
|
32
|
+
mean = float(g.mean())
|
|
33
|
+
exposure_ok = 1.0 - min(1.0, clipped * 3) - (0.3 if mean < 40 or mean > 220 else 0.0)
|
|
34
|
+
return {"i": i, "path": p, "phash": ph, "sharpness": round(sharp, 1), "exposure": round(max(0.0, exposure_ok), 2)}
|
|
35
|
+
except Exception as exc: # noqa: BLE001
|
|
36
|
+
return {"i": i, "path": p, "error": f"could not read ({type(exc).__name__})"}
|
|
37
|
+
|
|
38
|
+
|
|
39
|
+
def cluster(items: List[Dict], max_dist: int = MAX_DIST) -> List[List[Dict]]:
|
|
40
|
+
"""Single-linkage on pHash Hamming distance, as the backend's cluster_by_phash."""
|
|
41
|
+
remaining = list(items)
|
|
42
|
+
groups: List[List[Dict]] = []
|
|
43
|
+
while remaining:
|
|
44
|
+
group = [remaining.pop(0)]
|
|
45
|
+
changed = True
|
|
46
|
+
while changed:
|
|
47
|
+
changed = False
|
|
48
|
+
keep = []
|
|
49
|
+
for cand in remaining:
|
|
50
|
+
if any(bin(m["phash"] ^ cand["phash"]).count("1") <= max_dist for m in group):
|
|
51
|
+
group.append(cand)
|
|
52
|
+
changed = True
|
|
53
|
+
else:
|
|
54
|
+
keep.append(cand)
|
|
55
|
+
remaining = keep
|
|
56
|
+
groups.append(group)
|
|
57
|
+
return groups
|
|
58
|
+
|
|
59
|
+
|
|
60
|
+
def group_duplicates(paths: List[str], max_dist: int = MAX_DIST) -> Dict:
|
|
61
|
+
with images.pool() as pool:
|
|
62
|
+
measured = list(pool.map(_measure, list(enumerate(paths)), chunksize=4))
|
|
63
|
+
ok = [m for m in measured if m and "error" not in m]
|
|
64
|
+
skipped = [{"path": m["path"], "reason": m["error"]} for m in measured if m and "error" in m]
|
|
65
|
+
groups = []
|
|
66
|
+
for g in cluster(ok, max_dist):
|
|
67
|
+
if len(g) < 2:
|
|
68
|
+
continue
|
|
69
|
+
best = max(g, key=lambda m: m["sharpness"] * (0.5 + 0.5 * m["exposure"]))
|
|
70
|
+
groups.append({
|
|
71
|
+
"keep": best["path"],
|
|
72
|
+
"others": [m["path"] for m in g if m is not best],
|
|
73
|
+
"size": len(g),
|
|
74
|
+
"why": "sharpest, well-exposed shot in this group (local estimate)",
|
|
75
|
+
})
|
|
76
|
+
groups.sort(key=lambda g: -g["size"])
|
|
77
|
+
return {"photos": len(paths), "duplicate_groups": len(groups), "unique_photos": len(ok) - sum(g["size"] - 1 for g in groups),
|
|
78
|
+
"groups": groups, "skipped": skipped, "offline": True}
|
topit_mcp/export.py
ADDED
|
@@ -0,0 +1,85 @@
|
|
|
1
|
+
"""Copy a ranked selection into a folder, numbered in rank order. Originals are never modified.
|
|
2
|
+
|
|
3
|
+
001_IMG_1234.jpg, 002_IMG_0042.jpg, ... plus selection.csv (rank, file, source path).
|
|
4
|
+
|
|
5
|
+
Without max_long_edge, JPEG, PNG and WebP files are copied byte for byte (metadata kept, as it is your
|
|
6
|
+
own copy). HEIC and RAW become JPEGs (quality 92) so the selection opens anywhere; with
|
|
7
|
+
max_long_edge every file is re-encoded as a JPEG at that size. The destination must not be inside a
|
|
8
|
+
folder a photo came from, and no existing file is ever overwritten.
|
|
9
|
+
"""
|
|
10
|
+
from __future__ import annotations
|
|
11
|
+
|
|
12
|
+
import csv
|
|
13
|
+
import shutil
|
|
14
|
+
from pathlib import Path
|
|
15
|
+
from typing import Dict, List, Optional, Sequence, Union
|
|
16
|
+
|
|
17
|
+
from topit_mcp import images
|
|
18
|
+
|
|
19
|
+
|
|
20
|
+
class ExportError(Exception):
|
|
21
|
+
pass
|
|
22
|
+
|
|
23
|
+
|
|
24
|
+
def _paths(ranked: Sequence[Union[str, Dict]]) -> List[Path]:
|
|
25
|
+
out = []
|
|
26
|
+
for r in ranked:
|
|
27
|
+
p = r.get("path") if isinstance(r, dict) else r
|
|
28
|
+
if not p:
|
|
29
|
+
raise ExportError("Every selected item needs a file path.")
|
|
30
|
+
out.append(Path(str(p)).expanduser().resolve())
|
|
31
|
+
return out
|
|
32
|
+
|
|
33
|
+
|
|
34
|
+
def _inside(child: Path, parent: Path) -> bool:
|
|
35
|
+
try:
|
|
36
|
+
child.relative_to(parent)
|
|
37
|
+
return True
|
|
38
|
+
except ValueError:
|
|
39
|
+
return False
|
|
40
|
+
|
|
41
|
+
|
|
42
|
+
def export_selection(ranked: Sequence[Union[str, Dict]], destination: str,
|
|
43
|
+
max_long_edge: Optional[int] = None) -> Dict:
|
|
44
|
+
srcs = _paths(ranked)
|
|
45
|
+
if not srcs:
|
|
46
|
+
raise ExportError("Nothing to export.")
|
|
47
|
+
for s in srcs:
|
|
48
|
+
if not s.is_file():
|
|
49
|
+
raise ExportError(f"File not found: {s}")
|
|
50
|
+
dest = Path(destination).expanduser().resolve()
|
|
51
|
+
for s in srcs:
|
|
52
|
+
if _inside(dest, s.parent):
|
|
53
|
+
raise ExportError(f"Choose a destination outside the photo folders (it is inside {s.parent}).")
|
|
54
|
+
if max_long_edge is not None and not (64 <= int(max_long_edge) <= 20000):
|
|
55
|
+
raise ExportError("max_long_edge must be between 64 and 20000 pixels.")
|
|
56
|
+
dest.mkdir(parents=True, exist_ok=True)
|
|
57
|
+
width = max(3, len(str(len(srcs))))
|
|
58
|
+
plan = []
|
|
59
|
+
for n, src in enumerate(srcs, start=1):
|
|
60
|
+
ext = src.suffix.lower()
|
|
61
|
+
reencode = max_long_edge is not None or ext in images.HEIF or ext in images.RAW
|
|
62
|
+
name = f"{n:0{width}d}_{src.stem}{'.jpg' if reencode else src.suffix}"
|
|
63
|
+
if (dest / name).exists(): # checked for every file before anything is written
|
|
64
|
+
raise ExportError(f"{dest / name} already exists; nothing is overwritten. Choose an empty folder.")
|
|
65
|
+
plan.append((n, src, name, reencode))
|
|
66
|
+
written = []
|
|
67
|
+
for n, src, name, reencode in plan:
|
|
68
|
+
target = dest / name
|
|
69
|
+
if reencode:
|
|
70
|
+
im = images.open_upright(src, int(max_long_edge) if max_long_edge else 100000)
|
|
71
|
+
with open(target, "xb") as fh:
|
|
72
|
+
im.save(fh, "JPEG", quality=92)
|
|
73
|
+
else:
|
|
74
|
+
with open(src, "rb") as fin, open(target, "xb") as fout:
|
|
75
|
+
shutil.copyfileobj(fin, fout)
|
|
76
|
+
written.append({"rank": n, "file": name, "source": str(src)})
|
|
77
|
+
csv_path = dest / "selection.csv"
|
|
78
|
+
if csv_path.exists():
|
|
79
|
+
csv_path = dest / f"selection-{len(list(dest.glob('selection*.csv'))) + 1}.csv"
|
|
80
|
+
with open(csv_path, "x", newline="") as fh:
|
|
81
|
+
w = csv.DictWriter(fh, fieldnames=["rank", "file", "source"])
|
|
82
|
+
w.writeheader()
|
|
83
|
+
w.writerows(written)
|
|
84
|
+
return {"destination": str(dest), "exported": len(written), "files": [w_["file"] for w_ in written],
|
|
85
|
+
"list": str(csv_path)}
|
topit_mcp/images.py
ADDED
|
@@ -0,0 +1,156 @@
|
|
|
1
|
+
"""Find photos on disk and make the small, metadata-free copies that are the only thing sent to Topit.
|
|
2
|
+
|
|
3
|
+
Formats: JPEG, PNG, WebP; HEIC and HEIF through pillow-heif; camera RAW through the JPEG preview the
|
|
4
|
+
camera embedded in the file (rawpy's extract_thumb), so no RAW is developed. A RAW without a preview
|
|
5
|
+
is skipped with a reason.
|
|
6
|
+
|
|
7
|
+
The copy: oriented upright, scaled so its long edge is 1200 px (what the Topit scorer measures at),
|
|
8
|
+
RGB, JPEG quality 85, and saved with no EXIF, GPS, XMP or ICC data: nothing about where or when the
|
|
9
|
+
photo was taken leaves the computer. The original file is only ever opened for reading.
|
|
10
|
+
"""
|
|
11
|
+
from __future__ import annotations
|
|
12
|
+
|
|
13
|
+
import io
|
|
14
|
+
import os
|
|
15
|
+
from dataclasses import dataclass
|
|
16
|
+
from pathlib import Path
|
|
17
|
+
from typing import Iterable, List, Optional, Tuple
|
|
18
|
+
|
|
19
|
+
from PIL import Image, ImageOps
|
|
20
|
+
|
|
21
|
+
UPLOAD_EDGE = 1200
|
|
22
|
+
JPEG_QUALITY = 85
|
|
23
|
+
|
|
24
|
+
PLAIN = {".jpg", ".jpeg", ".png", ".webp"}
|
|
25
|
+
HEIF = {".heic", ".heif", ".hif"}
|
|
26
|
+
RAW = {".cr2", ".cr3", ".nef", ".nrw", ".arw", ".srf", ".sr2", ".dng", ".raf", ".orf", ".rw2", ".rwl", ".pef",
|
|
27
|
+
".srw", ".3fr", ".iiq", ".erf", ".kdc", ".mos", ".x3f"}
|
|
28
|
+
SUPPORTED = PLAIN | HEIF | RAW
|
|
29
|
+
|
|
30
|
+
_heif_ready = False
|
|
31
|
+
|
|
32
|
+
|
|
33
|
+
class Unreadable(Exception):
|
|
34
|
+
pass
|
|
35
|
+
|
|
36
|
+
|
|
37
|
+
def _heif() -> None:
|
|
38
|
+
global _heif_ready
|
|
39
|
+
if not _heif_ready:
|
|
40
|
+
import pillow_heif
|
|
41
|
+
|
|
42
|
+
pillow_heif.register_heif_opener()
|
|
43
|
+
_heif_ready = True
|
|
44
|
+
|
|
45
|
+
|
|
46
|
+
def discover(folder: Optional[str] = None, files: Optional[Iterable[str]] = None,
|
|
47
|
+
recursive: bool = False) -> Tuple[List[Path], List[dict]]:
|
|
48
|
+
"""Supported photo files, sorted by name, and the files that were skipped (with why)."""
|
|
49
|
+
found: List[Path] = []
|
|
50
|
+
skipped: List[dict] = []
|
|
51
|
+
if folder:
|
|
52
|
+
root = Path(folder).expanduser()
|
|
53
|
+
if not root.is_dir():
|
|
54
|
+
raise FileNotFoundError(f"Not a folder: {root}")
|
|
55
|
+
it = root.rglob("*") if recursive else root.iterdir()
|
|
56
|
+
for p in it:
|
|
57
|
+
if not p.is_file() or p.name.startswith("."):
|
|
58
|
+
continue
|
|
59
|
+
if p.suffix.lower() in SUPPORTED:
|
|
60
|
+
found.append(p)
|
|
61
|
+
else:
|
|
62
|
+
skipped.append({"path": str(p), "reason": "not a photo format Topit reads"})
|
|
63
|
+
for f in files or []:
|
|
64
|
+
p = Path(f).expanduser()
|
|
65
|
+
if not p.is_file():
|
|
66
|
+
skipped.append({"path": str(p), "reason": "file not found"})
|
|
67
|
+
elif p.suffix.lower() not in SUPPORTED:
|
|
68
|
+
skipped.append({"path": str(p), "reason": "not a photo format Topit reads"})
|
|
69
|
+
else:
|
|
70
|
+
found.append(p)
|
|
71
|
+
uniq = sorted({p.resolve() for p in found}, key=lambda p: (str(p.parent).lower(), p.name.lower()))
|
|
72
|
+
return uniq, skipped
|
|
73
|
+
|
|
74
|
+
|
|
75
|
+
def _raw_preview(path: Path) -> Image.Image:
|
|
76
|
+
import rawpy
|
|
77
|
+
|
|
78
|
+
try:
|
|
79
|
+
with rawpy.imread(str(path)) as raw:
|
|
80
|
+
thumb = raw.extract_thumb()
|
|
81
|
+
flip = getattr(raw.sizes, "flip", 0)
|
|
82
|
+
except Exception as exc: # rawpy.LibRawNoThumbnailError and friends
|
|
83
|
+
raise Unreadable(f"no embedded preview in this RAW file ({type(exc).__name__})")
|
|
84
|
+
if thumb.format == rawpy.ThumbFormat.JPEG:
|
|
85
|
+
im = Image.open(io.BytesIO(thumb.data))
|
|
86
|
+
im.load()
|
|
87
|
+
if (im.getexif() or {}).get(0x0112):
|
|
88
|
+
return ImageOps.exif_transpose(im)
|
|
89
|
+
else:
|
|
90
|
+
im = Image.fromarray(thumb.data)
|
|
91
|
+
# LibRaw's flip: 3 = 180, 5 = 90 CCW, 6 = 90 CW.
|
|
92
|
+
return {3: lambda i: i.rotate(180, expand=True), 5: lambda i: i.rotate(90, expand=True),
|
|
93
|
+
6: lambda i: i.rotate(-90, expand=True)}.get(flip, lambda i: i)(im)
|
|
94
|
+
|
|
95
|
+
|
|
96
|
+
def open_upright(path: Path, edge: int = UPLOAD_EDGE) -> Image.Image:
|
|
97
|
+
"""The photo, upright and at most `edge` px on its long side, as RGB."""
|
|
98
|
+
ext = path.suffix.lower()
|
|
99
|
+
if ext in RAW:
|
|
100
|
+
im = _raw_preview(path)
|
|
101
|
+
else:
|
|
102
|
+
if ext in HEIF:
|
|
103
|
+
_heif()
|
|
104
|
+
try:
|
|
105
|
+
im = Image.open(path)
|
|
106
|
+
if im.format == "JPEG":
|
|
107
|
+
im.draft("RGB", (edge, edge)) # DCT scaling: decodes a 24 MP JPEG at 1/2-1/8 size, fast
|
|
108
|
+
im = ImageOps.exif_transpose(im)
|
|
109
|
+
except Exception as exc:
|
|
110
|
+
raise Unreadable(f"could not open ({type(exc).__name__})")
|
|
111
|
+
im = im.convert("RGB")
|
|
112
|
+
if max(im.size) > edge:
|
|
113
|
+
im.thumbnail((edge, edge), Image.LANCZOS)
|
|
114
|
+
return im
|
|
115
|
+
|
|
116
|
+
|
|
117
|
+
def upload_copy(path: Path, edge: int = UPLOAD_EDGE) -> bytes:
|
|
118
|
+
"""A 1200 px JPEG of the photo with no metadata at all."""
|
|
119
|
+
im = open_upright(path, edge)
|
|
120
|
+
clean = Image.new("RGB", im.size)
|
|
121
|
+
clean.paste(im) # pixels only: nothing of the source's info dict comes along
|
|
122
|
+
out = io.BytesIO()
|
|
123
|
+
clean.save(out, "JPEG", quality=JPEG_QUALITY, optimize=False) # a new image: no exif, no icc, no xmp
|
|
124
|
+
return out.getvalue()
|
|
125
|
+
|
|
126
|
+
|
|
127
|
+
@dataclass
|
|
128
|
+
class Prepared:
|
|
129
|
+
index: int
|
|
130
|
+
path: str
|
|
131
|
+
data: Optional[bytes]
|
|
132
|
+
error: Optional[str] = None
|
|
133
|
+
|
|
134
|
+
|
|
135
|
+
def prepare(arg: Tuple[int, str]) -> Prepared:
|
|
136
|
+
"""Worker entry point (runs in a process pool)."""
|
|
137
|
+
i, p = arg
|
|
138
|
+
try:
|
|
139
|
+
return Prepared(i, p, upload_copy(Path(p)))
|
|
140
|
+
except Unreadable as exc:
|
|
141
|
+
return Prepared(i, p, None, str(exc))
|
|
142
|
+
except Exception as exc: # noqa: BLE001
|
|
143
|
+
return Prepared(i, p, None, f"could not read ({type(exc).__name__})")
|
|
144
|
+
|
|
145
|
+
|
|
146
|
+
def workers() -> int:
|
|
147
|
+
return max(1, min(8, (os.cpu_count() or 2)))
|
|
148
|
+
|
|
149
|
+
|
|
150
|
+
def pool():
|
|
151
|
+
"""A process pool for decoding. "spawn", not the Linux default "fork": the MCP server has threads
|
|
152
|
+
running (stdio reader, anyio workers), and a forked child can inherit one of their locks held and hang."""
|
|
153
|
+
import multiprocessing
|
|
154
|
+
from concurrent.futures import ProcessPoolExecutor
|
|
155
|
+
|
|
156
|
+
return ProcessPoolExecutor(max_workers=workers(), mp_context=multiprocessing.get_context("spawn"))
|
topit_mcp/server.py
ADDED
|
@@ -0,0 +1,139 @@
|
|
|
1
|
+
"""Topit local companion: an MCP server over stdio for Claude Desktop, Claude Code and Amp.
|
|
2
|
+
|
|
3
|
+
The remote Topit connector runs in the cloud and cannot see your disk. This one runs on your computer,
|
|
4
|
+
reads a folder, and sends Topit only 1200 px copies without EXIF or GPS, to the same account and taste
|
|
5
|
+
as the connector. Tools:
|
|
6
|
+
|
|
7
|
+
rank_photos Topit's ranking of a folder or a list of files for a context (needs sign-in)
|
|
8
|
+
group_duplicates near-duplicate groups and a suggested keeper, fully offline
|
|
9
|
+
export_selection copy a ranked list into a folder as 001_..., 002_...; originals are never changed
|
|
10
|
+
|
|
11
|
+
Run `topit-mcp` (stdio server), `topit-mcp login`, `topit-mcp logout` or `topit-mcp status`.
|
|
12
|
+
"""
|
|
13
|
+
from __future__ import annotations
|
|
14
|
+
|
|
15
|
+
import sys
|
|
16
|
+
from typing import Any, Dict, List, Optional
|
|
17
|
+
|
|
18
|
+
from mcp.server.fastmcp import Context, FastMCP
|
|
19
|
+
from mcp.server.fastmcp.exceptions import ToolError
|
|
20
|
+
from mcp.types import ToolAnnotations
|
|
21
|
+
|
|
22
|
+
from topit_mcp import auth, dupes, export, images
|
|
23
|
+
from topit_mcp.client import TopitClient, TopitError
|
|
24
|
+
|
|
25
|
+
mcp = FastMCP(
|
|
26
|
+
"Topit (local)",
|
|
27
|
+
instructions=("Ranks, de-duplicates and exports photos in folders on this computer with the user's Topit taste. "
|
|
28
|
+
"Only 1200 px copies without location data are sent to Topit, and they are deleted after ranking."),
|
|
29
|
+
)
|
|
30
|
+
|
|
31
|
+
|
|
32
|
+
def _paths(folder: Optional[str], files: Optional[List[str]], recursive: bool):
|
|
33
|
+
if not folder and not files:
|
|
34
|
+
raise ToolError("Give a folder or a list of files.")
|
|
35
|
+
try:
|
|
36
|
+
found, skipped = images.discover(folder, files, recursive)
|
|
37
|
+
except FileNotFoundError as exc:
|
|
38
|
+
raise ToolError(str(exc))
|
|
39
|
+
if not found:
|
|
40
|
+
raise ToolError("No photos found there (JPEG, PNG, WebP, HEIC or camera RAW).")
|
|
41
|
+
return [str(p) for p in found], skipped
|
|
42
|
+
|
|
43
|
+
|
|
44
|
+
@mcp.tool(title="Rank photos in a folder with Topit",
|
|
45
|
+
annotations=ToolAnnotations(title="Rank photos in a folder with Topit", readOnlyHint=True, openWorldHint=True))
|
|
46
|
+
async def rank_photos(folder: Optional[str] = None, files: Optional[List[str]] = None, context: str = "general",
|
|
47
|
+
top_k: int = 25, vibe: Optional[str] = None, workspace: Optional[str] = None,
|
|
48
|
+
recursive: bool = False, ctx: Optional[Context] = None) -> Dict[str, Any]:
|
|
49
|
+
"""Rank the photos in `folder` (or the listed `files`) with the user's Topit taste and return the best `top_k`
|
|
50
|
+
in order, each with its file path, score and a short reason.
|
|
51
|
+
|
|
52
|
+
context: general, instagram, tiktok, linkedin, dating, hinge, tinder, bumble or friends.
|
|
53
|
+
vibe: optional short text such as "golden hour, candid". workspace: "personal" (default) or a studio workspace,
|
|
54
|
+
which ranks with neutral taste, not the studio owner's personal taste.
|
|
55
|
+
Reads JPEG, PNG, WebP, HEIC and camera RAW (embedded preview). Sends 1200 px copies without EXIF or GPS; Topit
|
|
56
|
+
deletes them after ranking. Counts against the monthly allowance of the user's Topit plan."""
|
|
57
|
+
paths, skipped = _paths(folder, files, recursive)
|
|
58
|
+
import anyio
|
|
59
|
+
|
|
60
|
+
loop_token = anyio.lowlevel.current_token()
|
|
61
|
+
|
|
62
|
+
def progress(done: int, total: int, stage: str) -> None:
|
|
63
|
+
if ctx is not None:
|
|
64
|
+
try:
|
|
65
|
+
anyio.from_thread.run(ctx.report_progress, done, total, stage, token=loop_token)
|
|
66
|
+
except Exception: # noqa: BLE001 progress is best effort
|
|
67
|
+
pass
|
|
68
|
+
|
|
69
|
+
def _go():
|
|
70
|
+
client = TopitClient(auth.token)
|
|
71
|
+
try:
|
|
72
|
+
return client.rank_paths(paths, context=context, top_k=top_k, vibe=vibe, workspace=workspace,
|
|
73
|
+
progress=progress)
|
|
74
|
+
finally:
|
|
75
|
+
client.close()
|
|
76
|
+
|
|
77
|
+
try:
|
|
78
|
+
out = await anyio.to_thread.run_sync(_go)
|
|
79
|
+
except (TopitError, auth.NotSignedIn) as exc:
|
|
80
|
+
raise ToolError(str(exc))
|
|
81
|
+
return {"ranked": out.ranked, "photos_ranked": out.photos, "moments": out.groups,
|
|
82
|
+
"skipped": skipped + out.skipped, "allowance": out.allowance, "timings": out.timings}
|
|
83
|
+
|
|
84
|
+
|
|
85
|
+
@mcp.tool(title="Group duplicate photos (offline)",
|
|
86
|
+
annotations=ToolAnnotations(title="Group duplicate photos (offline)", readOnlyHint=True, openWorldHint=False))
|
|
87
|
+
async def group_duplicates(folder: Optional[str] = None, files: Optional[List[str]] = None, recursive: bool = False,
|
|
88
|
+
max_distance: int = dupes.MAX_DIST) -> Dict[str, Any]:
|
|
89
|
+
"""Find near-duplicate photos (bursts, crops, exposure variants) in a folder and suggest the sharpest,
|
|
90
|
+
best-exposed one to keep in each group. Runs entirely on this computer: nothing is uploaded and no Topit
|
|
91
|
+
account is needed. A local estimate, not Topit's personal ranking."""
|
|
92
|
+
import anyio
|
|
93
|
+
|
|
94
|
+
paths, skipped = _paths(folder, files, recursive)
|
|
95
|
+
out = await anyio.to_thread.run_sync(dupes.group_duplicates, paths, max(0, min(32, int(max_distance))))
|
|
96
|
+
out["skipped"] = skipped + out["skipped"]
|
|
97
|
+
return out
|
|
98
|
+
|
|
99
|
+
|
|
100
|
+
@mcp.tool(title="Export a photo selection",
|
|
101
|
+
annotations=ToolAnnotations(title="Export a photo selection", readOnlyHint=False, destructiveHint=False,
|
|
102
|
+
idempotentHint=False, openWorldHint=False))
|
|
103
|
+
async def export_selection(ranked: List[Any], destination: str, max_long_edge: Optional[int] = None) -> Dict[str, Any]:
|
|
104
|
+
"""Copy photos into `destination` in the given order, named 001_<name>, 002_<name>, ..., plus selection.csv.
|
|
105
|
+
`ranked` is a list of file paths, or the `ranked` list rank_photos returned. Originals are never changed or
|
|
106
|
+
moved, nothing is overwritten, and the destination must be outside the photos' folders. HEIC and RAW are saved
|
|
107
|
+
as JPEG; with max_long_edge every photo is saved as a JPEG of that size."""
|
|
108
|
+
import anyio
|
|
109
|
+
|
|
110
|
+
try:
|
|
111
|
+
return await anyio.to_thread.run_sync(export.export_selection, ranked, destination, max_long_edge)
|
|
112
|
+
except export.ExportError as exc:
|
|
113
|
+
raise ToolError(str(exc))
|
|
114
|
+
|
|
115
|
+
|
|
116
|
+
def main() -> None:
|
|
117
|
+
cmd = sys.argv[1] if len(sys.argv) > 1 else "serve"
|
|
118
|
+
if cmd == "login":
|
|
119
|
+
print(auth.login())
|
|
120
|
+
elif cmd == "logout":
|
|
121
|
+
print(auth.logout())
|
|
122
|
+
elif cmd == "status":
|
|
123
|
+
try:
|
|
124
|
+
client = TopitClient(auth.token)
|
|
125
|
+
u = client.usage()
|
|
126
|
+
print(f"Signed in. {u['used']} of {u['allowance']} photos used this month ({u['plan_label']}); "
|
|
127
|
+
f"resets {u['reset_label']}.")
|
|
128
|
+
except (TopitError, auth.NotSignedIn) as exc:
|
|
129
|
+
print(str(exc))
|
|
130
|
+
sys.exit(1)
|
|
131
|
+
elif cmd in ("serve", "stdio"):
|
|
132
|
+
mcp.run("stdio")
|
|
133
|
+
else:
|
|
134
|
+
print("usage: topit-mcp [serve|login|logout|status]")
|
|
135
|
+
sys.exit(2)
|
|
136
|
+
|
|
137
|
+
|
|
138
|
+
if __name__ == "__main__":
|
|
139
|
+
main()
|
|
@@ -0,0 +1,81 @@
|
|
|
1
|
+
Metadata-Version: 2.5
|
|
2
|
+
Name: topit-mcp
|
|
3
|
+
Version: 0.1.0
|
|
4
|
+
Summary: Topit local companion: rank, de-duplicate and export the photos in a folder with your Topit taste, from Claude, Claude Code or Amp.
|
|
5
|
+
Project-URL: Homepage, https://mytopit.com/mcp
|
|
6
|
+
Project-URL: Documentation, https://mytopit.com/settings/api
|
|
7
|
+
Author-email: Topit AI LLC <hello@mytopit.com>
|
|
8
|
+
License: Proprietary
|
|
9
|
+
Keywords: claude,instagram,mcp,model-context-protocol,photo-culling,photos
|
|
10
|
+
Classifier: Operating System :: OS Independent
|
|
11
|
+
Classifier: Programming Language :: Python :: 3
|
|
12
|
+
Classifier: Topic :: Multimedia :: Graphics
|
|
13
|
+
Requires-Python: >=3.10
|
|
14
|
+
Requires-Dist: anyio<5,>=4.9
|
|
15
|
+
Requires-Dist: httpx<0.29.0,>=0.28.1
|
|
16
|
+
Requires-Dist: imagehash<5.0.0,>=4.3.1
|
|
17
|
+
Requires-Dist: mcp<1.31.0,>=1.30.0
|
|
18
|
+
Requires-Dist: numpy<3,>=1.26
|
|
19
|
+
Requires-Dist: pillow-heif<2.0.0,>=0.18.0
|
|
20
|
+
Requires-Dist: pillow<12.0.0,>=10.4.0
|
|
21
|
+
Requires-Dist: rawpy<0.27.0,>=0.21.0
|
|
22
|
+
Provides-Extra: test
|
|
23
|
+
Requires-Dist: pytest<10,>=8; extra == 'test'
|
|
24
|
+
Description-Content-Type: text/markdown
|
|
25
|
+
|
|
26
|
+
# topit-mcp: your best photos, picked by your own taste
|
|
27
|
+
|
|
28
|
+
<!-- mcp-name: com.mytopit/topit -->
|
|
29
|
+
|
|
30
|
+
Ask Claude, Claude Code, Cursor or Amp to "find my best 25 photos in this folder for Instagram" and get
|
|
31
|
+
[Topit](https://mytopit.com)'s ranking, trained on your own taste, not a generic guess.
|
|
32
|
+
|
|
33
|
+
`topit-mcp` is the local companion: a small MCP server that ranks, de-duplicates and exports the photos in a
|
|
34
|
+
folder on your computer (JPEG, PNG, WebP, HEIC and camera RAW).
|
|
35
|
+
|
|
36
|
+
## Quick start
|
|
37
|
+
|
|
38
|
+
1. Get a free key at **mytopit.com → Settings → API & MCP → Create key**, or run `uvx topit-mcp login` once.
|
|
39
|
+
2. Add it to your agent:
|
|
40
|
+
|
|
41
|
+
```sh
|
|
42
|
+
# Claude Code
|
|
43
|
+
claude mcp add --env TOPIT_API_KEY=tpk_... --transport stdio topit-local -- uvx topit-mcp
|
|
44
|
+
# Amp
|
|
45
|
+
amp mcp add topit-local --env TOPIT_API_KEY=tpk_... -- uvx topit-mcp
|
|
46
|
+
```
|
|
47
|
+
|
|
48
|
+
Claude Desktop (`claude_desktop_config.json`):
|
|
49
|
+
|
|
50
|
+
```json
|
|
51
|
+
{ "mcpServers": { "topit": { "command": "uvx", "args": ["topit-mcp"], "env": { "TOPIT_API_KEY": "tpk_..." } } } }
|
|
52
|
+
```
|
|
53
|
+
|
|
54
|
+
No install at all? Use the hosted connector `https://api.mytopit.com/mcp` (sign in with your Topit account).
|
|
55
|
+
It ranks photos already in Topit or sent in the chat, but cannot read your disk.
|
|
56
|
+
|
|
57
|
+
## Try it
|
|
58
|
+
|
|
59
|
+
- "Rank the photos in ~/Pictures/Lisbon for Instagram and give me the best 25."
|
|
60
|
+
- "Which of these are duplicates? Keep the best of each."
|
|
61
|
+
- "Copy the top 10 to ~/Desktop/lisbon-picks at 2048 px."
|
|
62
|
+
|
|
63
|
+
## Tools
|
|
64
|
+
|
|
65
|
+
| Tool | Does |
|
|
66
|
+
|---|---|
|
|
67
|
+
| `rank_photos(folder or files, context, top_k)` | Topit's ranking with a score and a reason per photo |
|
|
68
|
+
| `group_duplicates(folder or files)` | Near-duplicate groups and the sharpest keeper; runs offline |
|
|
69
|
+
| `export_selection(ranked, destination)` | Copies the picks in rank order as `001_…`, never touching the originals |
|
|
70
|
+
|
|
71
|
+
## What leaves your computer
|
|
72
|
+
|
|
73
|
+
Only a 1200 px JPEG copy of each photo, with no EXIF, GPS, camera or date data, and no file names. Topit keeps
|
|
74
|
+
only the measured numbers, for at most 15 minutes. No photo is stored. `group_duplicates` sends nothing.
|
|
75
|
+
|
|
76
|
+
## Limits
|
|
77
|
+
|
|
78
|
+
Each Topit plan includes ranked photos every month, starting with the free plan. See your allowance and usage at
|
|
79
|
+
mytopit.com/settings/api.
|
|
80
|
+
|
|
81
|
+
Requires Python 3.10+ and [uv](https://docs.astral.sh/uv/). Questions: hello@mytopit.com.
|
|
@@ -0,0 +1,11 @@
|
|
|
1
|
+
topit_mcp/__init__.py,sha256=L7zigbtSDvS4UzvNltCh5vvborBf8HuT4pyAwW8rj0g,111
|
|
2
|
+
topit_mcp/auth.py,sha256=6ZdLgpvyrsvytcvaoot9vJnbJl3xoMUAaXZAFoqYrks,6571
|
|
3
|
+
topit_mcp/client.py,sha256=CgJNma4SOpV6FVNKUD2PCSXVzeC-GflPK5FwMhhmWiY,7523
|
|
4
|
+
topit_mcp/dupes.py,sha256=vh-H8NCWT4IQj_5ENEoBVLMDM-xZ-wCm_dS0g8Z9TZM,3286
|
|
5
|
+
topit_mcp/export.py,sha256=PsE_h0BoLbEUy46TVZ09AD1kmZZSr-RPgzy0sf76qYc,3484
|
|
6
|
+
topit_mcp/images.py,sha256=yNRiCwMcOPYYOv_AmnZpZDz0uzVKPhGBrJ_ZZOk6sx8,5658
|
|
7
|
+
topit_mcp/server.py,sha256=WKD8TsnT5rtnJAi2QXe11m6WsAnjDKmoxxQ8X2N0Q00,6625
|
|
8
|
+
topit_mcp-0.1.0.dist-info/METADATA,sha256=K3m3Ma04b64cVPLPl8XYWhAsE0XeV3U9a9S2-zBfxKE,3238
|
|
9
|
+
topit_mcp-0.1.0.dist-info/WHEEL,sha256=2iZrJkDIkeDh0k9SikKMqFuRP-ua6mb4Ir1AsER4BEw,87
|
|
10
|
+
topit_mcp-0.1.0.dist-info/entry_points.txt,sha256=AheP8H6MgoBHpRCZKg24ExsqrhxEmaByDvlTUCgyqqw,52
|
|
11
|
+
topit_mcp-0.1.0.dist-info/RECORD,,
|