bowerbird-bookmarks 0.6.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.
bowerbird/__init__.py ADDED
@@ -0,0 +1,3 @@
1
+ """Bower — Brave bookmark audit, validation and discovery."""
2
+
3
+ __version__ = "0.1.0"
bowerbird/canonical.py ADDED
@@ -0,0 +1,73 @@
1
+ """URL canonicalisation — produces a dedupe key, not a replacement URL.
2
+
3
+ The canonical form unifies scheme to https, strips www./m., drops fragments,
4
+ tracking parameters and trailing slashes, sorts the query, and folds YouTube's
5
+ many URL shapes onto youtube.com/watch?v=ID.
6
+ """
7
+
8
+ from __future__ import annotations
9
+
10
+ import ipaddress
11
+ from urllib.parse import parse_qsl, urlencode, urlsplit, urlunsplit
12
+
13
+ TRACKING_PARAMS = {
14
+ "fbclid", "gclid", "gclsrc", "dclid", "msclkid", "yclid", "twclid",
15
+ "igshid", "mc_cid", "mc_eid", "mkt_tok", "spm", "si", "_hsenc", "_hsmi",
16
+ "vero_id", "cmpid", "ncid", "sr_share", "ref_src", "ref_url", "share_id",
17
+ }
18
+
19
+ YOUTUBE_HOSTS = {"youtube.com", "m.youtube.com", "www.youtube.com", "music.youtube.com"}
20
+ # Params that don't change which video you land on.
21
+ YOUTUBE_DROP = {"feature", "ab_channel", "pp", "index", "app", "sns", "annotation_id", "src_vid"}
22
+
23
+
24
+ def is_checkable(url: str) -> bool:
25
+ """http(s) URLs pointing at a public host."""
26
+ try:
27
+ parts = urlsplit(url)
28
+ except ValueError:
29
+ return False
30
+ if parts.scheme not in ("http", "https"):
31
+ return False
32
+ host = (parts.hostname or "").lower()
33
+ if not host or host == "localhost" or host.endswith(".local"):
34
+ return False
35
+ try:
36
+ if ipaddress.ip_address(host).is_private or ipaddress.ip_address(host).is_loopback:
37
+ return False
38
+ except ValueError:
39
+ pass # not an IP literal — a normal hostname
40
+ return True
41
+
42
+
43
+ def canonicalize(url: str) -> str:
44
+ try:
45
+ parts = urlsplit(url.strip())
46
+ except ValueError:
47
+ return url.strip()
48
+ if parts.scheme not in ("http", "https"):
49
+ return url.strip()
50
+
51
+ host = (parts.hostname or "").lower()
52
+ path = parts.path or "/"
53
+ query = [(k, v) for k, v in parse_qsl(parts.query, keep_blank_values=True)
54
+ if not k.startswith("utm_") and k not in TRACKING_PARAMS]
55
+
56
+ if host == "youtu.be":
57
+ video_id = path.strip("/").split("/")[0]
58
+ host, path = "youtube.com", "/watch"
59
+ query = [("v", video_id)] + [(k, v) for k, v in query if k != "v"]
60
+ if host in YOUTUBE_HOSTS:
61
+ host = "youtube.com"
62
+ query = [(k, v) for k, v in query if k not in YOUTUBE_DROP]
63
+
64
+ if host.startswith("www."):
65
+ host = host[4:]
66
+
67
+ port = parts.port
68
+ netloc = host if port in (None, 80, 443) else f"{host}:{port}"
69
+
70
+ if path != "/" and path.endswith("/"):
71
+ path = path.rstrip("/")
72
+
73
+ return urlunsplit(("https", netloc, path, urlencode(sorted(query)), ""))
@@ -0,0 +1,255 @@
1
+ """Two-pass LLM categorisation (cabinet's design, with its roadmap lesson applied).
2
+
3
+ Pass A (`derive_taxonomy`): one Claude Opus call looks at the existing folder
4
+ structure plus a sample of the corpus and produces a clean, fixed taxonomy —
5
+ deriving the taxonomy *before* assigning anything prevents the synonym-sprawl
6
+ failure mode ("Finance" vs "Finances") that grows batch by batch.
7
+
8
+ Pass B (`assign`): batches of bookmarks are matched against that fixed taxonomy
9
+ with structured outputs. Assignments record their source and model so a better
10
+ model can later redo only machine-made labels. Manual assignments are never
11
+ overwritten.
12
+ """
13
+
14
+ from __future__ import annotations
15
+
16
+ import json
17
+ import random
18
+ import sqlite3
19
+ from collections import Counter
20
+ from datetime import datetime, timezone
21
+ from urllib.parse import urlsplit
22
+
23
+ import anthropic
24
+
25
+ TAXONOMY_MODEL = "claude-opus-5"
26
+ ASSIGN_MODEL = "claude-haiku-4-5"
27
+ BATCH_SIZE = 25
28
+
29
+ TAXONOMY_SCHEMA = {
30
+ "type": "object",
31
+ "properties": {
32
+ "categories": {
33
+ "type": "array",
34
+ "items": {
35
+ "type": "object",
36
+ "properties": {
37
+ "name": {"type": "string"},
38
+ "children": {"type": "array", "items": {"type": "string"}},
39
+ },
40
+ "required": ["name", "children"],
41
+ "additionalProperties": False,
42
+ },
43
+ }
44
+ },
45
+ "required": ["categories"],
46
+ "additionalProperties": False,
47
+ }
48
+
49
+ ASSIGN_SCHEMA = {
50
+ "type": "object",
51
+ "properties": {
52
+ "items": {
53
+ "type": "array",
54
+ "items": {
55
+ "type": "object",
56
+ "properties": {
57
+ "index": {"type": "integer"},
58
+ "categories": {
59
+ "type": "array",
60
+ "items": {
61
+ "type": "object",
62
+ "properties": {
63
+ "path": {"type": "string"},
64
+ "confidence": {"type": "number"},
65
+ },
66
+ "required": ["path", "confidence"],
67
+ "additionalProperties": False,
68
+ },
69
+ },
70
+ },
71
+ "required": ["index", "categories"],
72
+ "additionalProperties": False,
73
+ },
74
+ }
75
+ },
76
+ "required": ["items"],
77
+ "additionalProperties": False,
78
+ }
79
+
80
+
81
+ def _folder_counts(conn: sqlite3.Connection) -> Counter:
82
+ counts: Counter = Counter()
83
+ for row in conn.execute("SELECT folder_path FROM bookmarks WHERE removed=0"):
84
+ for part in row["folder_path"].split("/"):
85
+ if part and part not in ("Bookmarks bar", "Other bookmarks", "Imported From Firefox",
86
+ "unfiled", "menu", "toolbar", "Imported"):
87
+ counts[part] += 1
88
+ return counts
89
+
90
+
91
+ def _sample_items(conn: sqlite3.Connection, n: int = 300) -> list[str]:
92
+ rows = conn.execute(
93
+ """SELECT b.title, b.url, b.folder_path FROM bookmarks b
94
+ WHERE b.removed=0 GROUP BY b.canonical_url ORDER BY RANDOM() LIMIT ?""", (n,)
95
+ ).fetchall()
96
+ return [f"{r['title'][:80]} | {(urlsplit(r['url']).hostname or '')} | {r['folder_path'][:60]}"
97
+ for r in rows]
98
+
99
+
100
+ def derive_taxonomy(conn: sqlite3.Connection, model: str = TAXONOMY_MODEL) -> dict:
101
+ client = anthropic.Anthropic()
102
+ folders = "\n".join(f"{name}: {count}" for name, count in _folder_counts(conn).most_common(80))
103
+ sample = "\n".join(_sample_items(conn))
104
+
105
+ response = client.messages.create(
106
+ model=model,
107
+ max_tokens=8000,
108
+ output_config={"effort": "medium",
109
+ "format": {"type": "json_schema", "schema": TAXONOMY_SCHEMA}},
110
+ messages=[{
111
+ "role": "user",
112
+ "content": (
113
+ "Design a category taxonomy for a personal bookmark collection of ~8,500 links "
114
+ "belonging to an academic who teaches computing, does research, 3D prints, and has "
115
+ "many hobbies. Requirements:\n"
116
+ "- 12-20 top-level categories, each with 0-8 children (two levels max).\n"
117
+ "- Merge synonyms and near-duplicates into one canonical name.\n"
118
+ "- Names are short (1-3 words). No 'Miscellaneous'/'Other' categories.\n"
119
+ "- The taxonomy must cover the whole collection; prefer broad, durable categories "
120
+ "over one-off niches.\n\n"
121
+ f"Existing folder names with bookmark counts:\n{folders}\n\n"
122
+ f"Random sample of bookmarks (title | domain | folder):\n{sample}"
123
+ ),
124
+ }],
125
+ )
126
+ if response.stop_reason == "refusal":
127
+ raise RuntimeError("taxonomy request was refused")
128
+ data = json.loads(next(b.text for b in response.content if b.type == "text"))
129
+
130
+ paths = []
131
+ for cat in data["categories"]:
132
+ paths.append(cat["name"])
133
+ paths.extend(f"{cat['name']} / {child}" for child in cat["children"])
134
+ for path in paths:
135
+ conn.execute("INSERT OR IGNORE INTO categories(path, source) VALUES(?, 'llm')", (path,))
136
+ conn.commit()
137
+ return {"top_level": len(data["categories"]), "total_paths": len(paths)}
138
+
139
+
140
+ def _system_prompt(conn: sqlite3.Connection) -> list[dict]:
141
+ taxonomy = "\n".join(r["path"] for r in conn.execute("SELECT path FROM categories ORDER BY path"))
142
+ return [{
143
+ "type": "text",
144
+ "text": (
145
+ "You categorise bookmarks from a personal collection into a fixed taxonomy.\n\n"
146
+ "Rules:\n"
147
+ "- Assign 1 to 3 categories per bookmark, most relevant first, each with a "
148
+ "confidence between 0 and 1.\n"
149
+ "- Use ONLY paths from the taxonomy below, exactly as written. Never invent new ones.\n"
150
+ "- Prefer the most specific applicable path (a child over its parent).\n"
151
+ "- The bookmark's original folder is a hint about the owner's intent, not ground truth.\n"
152
+ "- If genuinely nothing fits, return an empty categories array for that item.\n\n"
153
+ f"Taxonomy:\n{taxonomy}"
154
+ ),
155
+ "cache_control": {"type": "ephemeral"},
156
+ }]
157
+
158
+
159
+ def assign(conn: sqlite3.Connection, model: str = ASSIGN_MODEL,
160
+ limit: int | None = None, progress_every: int = 10) -> dict:
161
+ client = anthropic.Anthropic()
162
+ valid_paths = {r["path"] for r in conn.execute("SELECT path FROM categories")}
163
+ if not valid_paths:
164
+ raise RuntimeError("no taxonomy — run `bower categorize --taxonomy` first")
165
+ system = _system_prompt(conn)
166
+
167
+ rows = conn.execute(
168
+ """SELECT u.id, u.check_url, u.page_title, u.page_description,
169
+ (SELECT title FROM bookmarks b WHERE b.canonical_url=u.canonical_url
170
+ AND b.removed=0 LIMIT 1) AS title,
171
+ (SELECT folder_path FROM bookmarks b WHERE b.canonical_url=u.canonical_url
172
+ AND b.removed=0 LIMIT 1) AS folder_path
173
+ FROM urls u
174
+ WHERE u.status NOT IN ('skipped')
175
+ AND NOT EXISTS (SELECT 1 FROM url_categories c WHERE c.url_id=u.id)
176
+ ORDER BY u.id"""
177
+ + (f" LIMIT {int(limit)}" if limit else "")
178
+ ).fetchall()
179
+ if not rows:
180
+ return {"assigned": 0}
181
+
182
+ now = datetime.now(timezone.utc).isoformat()
183
+ cat_ids = {r["path"]: r["id"] for r in conn.execute("SELECT id, path FROM categories")}
184
+ assigned = skipped = batches = 0
185
+
186
+ for start in range(0, len(rows), BATCH_SIZE):
187
+ batch = rows[start:start + BATCH_SIZE]
188
+ lines = []
189
+ for i, r in enumerate(batch):
190
+ desc = (r["page_description"] or "")[:200]
191
+ lines.append(
192
+ f"[{i}] title: {(r['title'] or r['page_title'] or '')[:110]}\n"
193
+ f" url: {r['check_url'][:120]}\n"
194
+ f" folder: {(r['folder_path'] or '')[:80]}"
195
+ + (f"\n description: {desc}" if desc else "")
196
+ )
197
+ try:
198
+ response = client.messages.create(
199
+ model=model,
200
+ max_tokens=8000,
201
+ system=system,
202
+ output_config={"format": {"type": "json_schema", "schema": ASSIGN_SCHEMA}},
203
+ messages=[{"role": "user", "content": "Categorise these bookmarks:\n\n" + "\n".join(lines)}],
204
+ )
205
+ except anthropic.APIStatusError as exc:
206
+ print(f" batch at {start} failed: {exc.status_code} {exc.message}", flush=True)
207
+ skipped += len(batch)
208
+ continue
209
+ if response.stop_reason == "refusal":
210
+ skipped += len(batch)
211
+ continue
212
+
213
+ data = json.loads(next(b.text for b in response.content if b.type == "text"))
214
+ for item in data.get("items", []):
215
+ idx = item.get("index")
216
+ if not isinstance(idx, int) or not 0 <= idx < len(batch):
217
+ continue
218
+ url_id = batch[idx]["id"]
219
+ for cat in item.get("categories", [])[:3]:
220
+ cat_id = cat_ids.get(cat.get("path"))
221
+ if cat_id is None:
222
+ continue # hallucinated path — drop, never create
223
+ conn.execute(
224
+ """INSERT OR IGNORE INTO url_categories
225
+ (url_id, category_id, confidence, source, model, assigned_at)
226
+ VALUES(?,?,?,'llm',?,?)""",
227
+ (url_id, cat_id, float(cat.get("confidence", 0)), model, now))
228
+ assigned += 1
229
+ conn.commit()
230
+ batches += 1
231
+ if batches % progress_every == 0:
232
+ print(f" {min(start + BATCH_SIZE, len(rows))}/{len(rows)} processed", flush=True)
233
+
234
+ return {"assigned": assigned, "skipped": skipped, "batches": batches}
235
+
236
+
237
+ def rebuild_index(conn: sqlite3.Connection) -> dict:
238
+ """Rebuild the FTS5 search index from bookmarks + enrichment + categories."""
239
+ conn.execute("DELETE FROM search")
240
+ rows = conn.execute(
241
+ """SELECT u.id, u.check_url, u.page_title, u.page_description, u.page_text,
242
+ (SELECT GROUP_CONCAT(b.title, ' ') FROM bookmarks b
243
+ WHERE b.canonical_url=u.canonical_url AND b.removed=0) AS titles,
244
+ (SELECT GROUP_CONCAT(c.path, ' ; ') FROM url_categories uc
245
+ JOIN categories c ON c.id=uc.category_id WHERE uc.url_id=u.id) AS topics
246
+ FROM urls u"""
247
+ ).fetchall()
248
+ for r in rows:
249
+ conn.execute(
250
+ "INSERT INTO search(url_id, title, url, page, topics) VALUES(?,?,?,?,?)",
251
+ (r["id"], r["titles"] or "", r["check_url"],
252
+ " ".join(filter(None, [r["page_title"], r["page_description"], r["page_text"]])),
253
+ r["topics"] or ""))
254
+ conn.commit()
255
+ return {"indexed": len(rows)}
bowerbird/checker.py ADDED
@@ -0,0 +1,215 @@
1
+ """Link validation.
2
+
3
+ Policy (learned from cite-sight, extended for bookmarks):
4
+ - GET, never HEAD — many servers 403 HEAD.
5
+ - Only 404/410 mean dead. 401/403/429/451/5xx mean blocked — refused, not gone.
6
+ - Reaching a login page means the bookmark is alive behind an account (login_wall).
7
+ - A deep link that 200s after redirecting to the site root is suspect (soft-404).
8
+ - YouTube videos are checked via the oEmbed API — the watch page itself
9
+ returns 200 even for deleted videos.
10
+ - Per-host pacing + bounded global concurrency; one retry on 429/5xx/timeout.
11
+ """
12
+
13
+ from __future__ import annotations
14
+
15
+ import asyncio
16
+ import re
17
+ import sqlite3
18
+ import time
19
+ from datetime import datetime, timezone
20
+ from urllib.parse import parse_qs, quote, urlsplit
21
+
22
+ import httpx
23
+
24
+ USER_AGENT = (
25
+ "Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/537.36 "
26
+ "(KHTML, like Gecko) Chrome/126.0.0.0 Safari/537.36"
27
+ )
28
+ HEADERS = {
29
+ "User-Agent": USER_AGENT,
30
+ "Accept": "text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8",
31
+ "Accept-Language": "en-AU,en;q=0.8",
32
+ }
33
+
34
+ BODY_CAP = 65536
35
+ DEFAULT_HOST_INTERVAL = 1.0
36
+ HOST_INTERVALS = {"www.youtube.com": 0.3, "youtube.com": 0.3}
37
+
38
+ AUTH_HOST_RE = re.compile(
39
+ r"^(accounts\.google\.com|login\.microsoftonline\.com|login\.live\.com|"
40
+ r"id\.atlassian\.com|(auth|login|signin|sso|idp|identity)\.)|(\.okta\.com|\.auth0\.com)$"
41
+ )
42
+ LOGIN_PATH_RE = re.compile(
43
+ r"/(log-?in|sign-?in|sign_in|users/sign_in|account/login|auth|sso|session/new|"
44
+ r"wp-login\.php|oauth2?|authorize)([/?#]|$)", re.I
45
+ )
46
+ LOGIN_TITLE_RE = re.compile(r"\b(log ?in|sign ?in|authenticate|authentication required)\b", re.I)
47
+ SOFT404_RE = re.compile(
48
+ r"(page (you('re| are)? looking for )?(was |could )?not( be)? found|"
49
+ r"404 not found|page doesn.t exist|no longer (available|exists)|"
50
+ r"content (is )?unavailable|video unavailable|this page isn.t available)", re.I
51
+ )
52
+ TITLE_RE = re.compile(r"<title[^>]*>(.*?)</title>", re.I | re.S)
53
+
54
+
55
+ class HostPacer:
56
+ """Serialises requests per host with a minimum interval between them."""
57
+
58
+ def __init__(self) -> None:
59
+ self._locks: dict[str, asyncio.Lock] = {}
60
+ self._next_ok: dict[str, float] = {}
61
+
62
+ async def wait(self, host: str) -> None:
63
+ lock = self._locks.setdefault(host, asyncio.Lock())
64
+ async with lock:
65
+ delay = self._next_ok.get(host, 0.0) - time.monotonic()
66
+ if delay > 0:
67
+ await asyncio.sleep(delay)
68
+ interval = HOST_INTERVALS.get(host, DEFAULT_HOST_INTERVAL)
69
+ self._next_ok[host] = time.monotonic() + interval
70
+
71
+
72
+ def youtube_video_id(url: str) -> str | None:
73
+ parts = urlsplit(url)
74
+ host = (parts.hostname or "").lower().removeprefix("www.").removeprefix("m.")
75
+ if host == "youtu.be":
76
+ return parts.path.strip("/").split("/")[0] or None
77
+ if host in ("youtube.com", "music.youtube.com"):
78
+ if parts.path == "/watch":
79
+ return (parse_qs(parts.query).get("v") or [None])[0]
80
+ m = re.match(r"^/(embed|shorts|live|v)/([\w-]{6,})", parts.path)
81
+ if m:
82
+ return m.group(2)
83
+ return None
84
+
85
+
86
+ def classify_response(requested: str, resp: httpx.Response, body: str) -> tuple[str, str]:
87
+ """Returns (status, reason) for a completed non-YouTube response."""
88
+ code = resp.status_code
89
+ final = str(resp.url)
90
+ if code in (404, 410):
91
+ return "dead", f"http {code}"
92
+ if code in (401, 403, 407, 429, 451) or code >= 500:
93
+ return "blocked", f"http {code}"
94
+ if code >= 400:
95
+ return "blocked", f"http {code}"
96
+
97
+ fparts = urlsplit(final)
98
+ fhost = (fparts.hostname or "").lower()
99
+ title_m = TITLE_RE.search(body)
100
+ title = re.sub(r"\s+", " ", title_m.group(1)).strip() if title_m else ""
101
+
102
+ if AUTH_HOST_RE.search(fhost) or LOGIN_PATH_RE.search(fparts.path):
103
+ return "login_wall", f"landed on {fhost}{fparts.path}"
104
+ if 'type="password"' in body and (final.rstrip("/") != requested.rstrip("/") or LOGIN_TITLE_RE.search(title)):
105
+ return "login_wall", "password form on arrival"
106
+
107
+ if SOFT404_RE.search(title) or SOFT404_RE.search(body[:20000]):
108
+ return "dead", f"soft-404 ({title[:60] or 'body text'})"
109
+
110
+ rparts = urlsplit(requested)
111
+ if len(rparts.path) > 1 and fparts.path in ("", "/") and fhost and not rparts.query:
112
+ return "suspect", f"deep link redirected to root of {fhost}"
113
+
114
+ return "live", title[:100]
115
+
116
+
117
+ async def check_one(client: httpx.AsyncClient, pacer: HostPacer, url: str) -> dict:
118
+ vid = youtube_video_id(url)
119
+ probe = (
120
+ f"https://www.youtube.com/oembed?format=json&url={quote('https://www.youtube.com/watch?v=' + vid)}"
121
+ if vid else url
122
+ )
123
+ host = urlsplit(probe).hostname or ""
124
+ started = time.monotonic()
125
+
126
+ for attempt in (1, 2):
127
+ await pacer.wait(host)
128
+ try:
129
+ async with client.stream("GET", probe, headers=HEADERS) as resp:
130
+ if vid:
131
+ await resp.aread()
132
+ status, reason = {
133
+ 200: ("live", "oembed ok"),
134
+ 401: ("live", "oembed 401: exists, embedding disabled"),
135
+ 403: ("blocked", "oembed 403: private video"),
136
+ }.get(resp.status_code, ("dead", f"oembed {resp.status_code}: video gone"))
137
+ else:
138
+ body = b""
139
+ ctype = resp.headers.get("content-type", "")
140
+ if resp.status_code < 400 and ("html" in ctype or not ctype):
141
+ async for chunk in resp.aiter_bytes():
142
+ body += chunk
143
+ if len(body) >= BODY_CAP:
144
+ break
145
+ status, reason = classify_response(
146
+ url, resp, body.decode("utf-8", errors="replace")
147
+ )
148
+ http_status, final = resp.status_code, str(resp.url)
149
+ except httpx.TimeoutException:
150
+ status, reason, http_status, final = "timeout", "timed out", None, None
151
+ except httpx.HTTPError as exc:
152
+ status, reason, http_status, final = "error", f"{type(exc).__name__}: {exc}"[:200], None, None
153
+
154
+ if attempt == 1 and (status == "timeout" or (http_status in (429,) or (http_status or 0) >= 500)):
155
+ await asyncio.sleep(5)
156
+ continue
157
+ break
158
+
159
+ return {
160
+ "status": status, "reason": reason, "http_status": http_status,
161
+ "final_url": final if final != url else None,
162
+ "elapsed_ms": int((time.monotonic() - started) * 1000),
163
+ }
164
+
165
+
166
+ async def run_check(
167
+ conn: sqlite3.Connection,
168
+ limit: int | None = None,
169
+ concurrency: int = 30,
170
+ timeout: float = 15.0,
171
+ recheck: bool = False,
172
+ progress_every: int = 100,
173
+ ) -> dict:
174
+ where = "status <> 'skipped'" if recheck else "status = 'unchecked'"
175
+ rows = conn.execute(
176
+ f"SELECT id, check_url FROM urls WHERE {where} ORDER BY id"
177
+ + (f" LIMIT {int(limit)}" if limit else "")
178
+ ).fetchall()
179
+ if not rows:
180
+ return {"checked": 0}
181
+
182
+ pacer = HostPacer()
183
+ sem = asyncio.Semaphore(concurrency)
184
+ done = 0
185
+ counts: dict[str, int] = {}
186
+
187
+ async with httpx.AsyncClient(
188
+ follow_redirects=True, timeout=timeout, http2=False,
189
+ limits=httpx.Limits(max_connections=concurrency, max_keepalive_connections=10),
190
+ ) as client:
191
+
192
+ async def worker(row: sqlite3.Row) -> tuple[int, dict]:
193
+ async with sem:
194
+ return row["id"], await check_one(client, pacer, row["check_url"])
195
+
196
+ for coro in asyncio.as_completed([worker(r) for r in rows]):
197
+ url_id, result = await coro
198
+ conn.execute(
199
+ """UPDATE urls SET status=?, http_status=?, final_url=?, reason=?,
200
+ elapsed_ms=?, checked_at=?,
201
+ consecutive_failures = CASE WHEN ? IN ('dead','timeout','error')
202
+ THEN consecutive_failures + 1 ELSE 0 END
203
+ WHERE id=?""",
204
+ (result["status"], result["http_status"], result["final_url"],
205
+ result["reason"], result["elapsed_ms"],
206
+ datetime.now(timezone.utc).isoformat(), result["status"], url_id),
207
+ )
208
+ counts[result["status"]] = counts.get(result["status"], 0) + 1
209
+ done += 1
210
+ if done % progress_every == 0:
211
+ conn.commit()
212
+ print(f" {done}/{len(rows)} checked {counts}", flush=True)
213
+ conn.commit()
214
+
215
+ return {"checked": done, **counts}
bowerbird/cli.py ADDED
@@ -0,0 +1,126 @@
1
+ """Bower CLI: sources, ingest, check, report, stats, serve."""
2
+
3
+ from __future__ import annotations
4
+
5
+ import argparse
6
+ import asyncio
7
+ import json
8
+ from pathlib import Path
9
+
10
+ from . import db
11
+ from .checker import run_check
12
+ from .ingest import ingest_chromium_history, ingest_source
13
+ from .report import build_report
14
+ from .sources import detect, register
15
+
16
+
17
+ def main() -> None:
18
+ parser = argparse.ArgumentParser(prog="bower", description="Bookmark audit and dashboard")
19
+ parser.add_argument("--db", type=Path, default=None, help="database path")
20
+ sub = parser.add_subparsers(dest="cmd", required=True)
21
+
22
+ sub.add_parser("sources", help="detect and register browser bookmark stores")
23
+
24
+ p_ingest = sub.add_parser("ingest", help="import bookmarks from registered sources (read-only)")
25
+ p_ingest.add_argument("--source-id", type=int, default=None, help="only this source")
26
+ p_ingest.add_argument("--no-history", action="store_true", help="skip browser-history joins")
27
+
28
+ p_check = sub.add_parser("check", help="validate links")
29
+ p_check.add_argument("--limit", type=int, default=None)
30
+ p_check.add_argument("--concurrency", type=int, default=30)
31
+ p_check.add_argument("--recheck", action="store_true", help="re-validate already-checked URLs")
32
+
33
+ p_report = sub.add_parser("report", help="write reports/report.md and print it")
34
+ p_report.add_argument("--out", type=Path, default=db.data_home() / "reports/report.md")
35
+
36
+ sub.add_parser("stats", help="one-line status counts")
37
+
38
+ p_enrich = sub.add_parser("enrich", help="fetch page titles/descriptions for alive URLs")
39
+ p_enrich.add_argument("--limit", type=int, default=None)
40
+ p_enrich.add_argument("--concurrency", type=int, default=30)
41
+
42
+ p_cat = sub.add_parser("categorize", help="LLM categorisation (two-pass)")
43
+ p_cat.add_argument("--taxonomy", action="store_true", help="pass A: derive the taxonomy")
44
+ p_cat.add_argument("--assign", action="store_true", help="pass B: assign categories")
45
+ p_cat.add_argument("--limit", type=int, default=None)
46
+ p_cat.add_argument("--model", default=None, help="override the assignment model")
47
+
48
+ sub.add_parser("index", help="rebuild the full-text search index")
49
+
50
+ p_wb = sub.add_parser("wayback", help="look up Internet Archive snapshots for dead links")
51
+ p_wb.add_argument("--limit", type=int, default=None)
52
+
53
+ p_obs = sub.add_parser("obsidian", help="export topics + bookmark stubs as an Obsidian folder")
54
+ p_obs.add_argument("--out", type=Path, default=db.data_home() / "exports/obsidian")
55
+
56
+ p_write = sub.add_parser("writeback", help="write the cleaned tree back to a browser (dry-run by default)")
57
+ p_write.add_argument("--source-id", type=int, required=True)
58
+ p_write.add_argument("--apply", action="store_true",
59
+ help="actually write the file (backup is taken first; browser must be closed)")
60
+
61
+ p_serve = sub.add_parser("serve", help="run the dashboard at http://127.0.0.1:8420")
62
+ p_serve.add_argument("--port", type=int, default=8420)
63
+
64
+ args = parser.parse_args()
65
+ conn = db.connect(args.db)
66
+
67
+ if args.cmd == "sources":
68
+ found = detect()
69
+ register(conn, found)
70
+ for row in conn.execute("SELECT * FROM sources ORDER BY id"):
71
+ print(f" [{row['id']}] {row['browser']:<9} {row['profile']:<20} ({row['kind']}) {row['path']}")
72
+ elif args.cmd == "ingest":
73
+ register(conn, detect())
74
+ rows = conn.execute(
75
+ "SELECT * FROM sources" + (f" WHERE id={int(args.source_id)}" if args.source_id else "")
76
+ ).fetchall()
77
+ for source in rows:
78
+ stats = ingest_source(conn, source)
79
+ if source["kind"] == "chromium" and not args.no_history and "error" not in stats:
80
+ stats |= ingest_chromium_history(conn, source)
81
+ print(json.dumps(stats))
82
+ elif args.cmd == "check":
83
+ stats = asyncio.run(run_check(conn, limit=args.limit,
84
+ concurrency=args.concurrency, recheck=args.recheck))
85
+ print(json.dumps(stats, indent=2))
86
+ elif args.cmd == "report":
87
+ args.out.parent.mkdir(parents=True, exist_ok=True)
88
+ print(build_report(conn, args.out))
89
+ print(f"written to {args.out}")
90
+ elif args.cmd == "stats":
91
+ for row in conn.execute("SELECT status, COUNT(*) c FROM urls GROUP BY status ORDER BY c DESC"):
92
+ print(f"{row['status']:>10} {row['c']:,}")
93
+ elif args.cmd == "enrich":
94
+ from .enrich import run_enrich
95
+ print(json.dumps(asyncio.run(run_enrich(conn, limit=args.limit,
96
+ concurrency=args.concurrency))))
97
+ elif args.cmd == "categorize":
98
+ from .categorize import ASSIGN_MODEL, assign, derive_taxonomy
99
+ if args.taxonomy:
100
+ print(json.dumps(derive_taxonomy(conn)))
101
+ if args.assign or not args.taxonomy:
102
+ print(json.dumps(assign(conn, model=args.model or ASSIGN_MODEL, limit=args.limit)))
103
+ elif args.cmd == "index":
104
+ from .categorize import rebuild_index
105
+ print(json.dumps(rebuild_index(conn)))
106
+ elif args.cmd == "obsidian":
107
+ from .obsidian import export
108
+ print(json.dumps(export(conn, args.out)))
109
+ elif args.cmd == "wayback":
110
+ from .wayback import run_wayback
111
+ print(json.dumps(asyncio.run(run_wayback(conn, limit=args.limit))))
112
+ elif args.cmd == "writeback":
113
+ from .writeback import writeback
114
+ result = writeback(conn, args.source_id, apply=args.apply)
115
+ print(json.dumps(result, indent=2))
116
+ if not args.apply:
117
+ print("dry run — nothing written; re-run with --apply to write (browser must be closed)")
118
+ elif args.cmd == "serve":
119
+ import uvicorn
120
+ from .server import create_app
121
+ conn.close()
122
+ uvicorn.run(create_app(args.db), host="127.0.0.1", port=args.port)
123
+
124
+
125
+ if __name__ == "__main__":
126
+ main()