File size: 16,628 Bytes
11a414e
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
"""SQLite manifest: the single source of truth for provenance and pipeline state.

Tables
------
sources       one row per (normalized) URL; download state
hits          every (url, engine, query) that surfaced a URL -> class hints and provenance
harvest_runs  completed (engine, query) harvests so reruns skip them
images        one row per unique image (sha256 of original bytes) with all pipeline state
embeddings    optional CLIP embeddings (float16 blobs)

Image status flow
-----------------
downloaded -> validated -> normalized -> deduped -> kept | review | discarded
Every stage only touches rows in its own input status, so all stages are idempotent
and a rerun after an interruption never repeats finished work.
"""
from __future__ import annotations

import json
import sqlite3
import threading
from contextlib import contextmanager
from datetime import datetime, timezone
from pathlib import Path
from typing import Any, Iterable, Iterator
from urllib.parse import parse_qsl, urlencode, urlsplit, urlunsplit

import numpy as np

STATUSES = ("downloaded", "validated", "normalized", "deduped", "kept", "review", "discarded")

SCHEMA = """
PRAGMA journal_mode=WAL;
PRAGMA synchronous=NORMAL;

CREATE TABLE IF NOT EXISTS sources (
    url_norm      TEXT PRIMARY KEY,
    url           TEXT NOT NULL,
    status        TEXT NOT NULL DEFAULT 'pending',
    attempts      INTEGER NOT NULL DEFAULT 0,
    http_status   INTEGER,
    error         TEXT,
    image_id      TEXT,
    harvested_at  TEXT,
    downloaded_at TEXT
);
CREATE INDEX IF NOT EXISTS idx_sources_status ON sources(status);
CREATE INDEX IF NOT EXISTS idx_sources_image  ON sources(image_id);

CREATE TABLE IF NOT EXISTS hits (
    url_norm     TEXT NOT NULL,
    engine       TEXT NOT NULL,
    query        TEXT NOT NULL,
    class_hint   TEXT,
    lang         TEXT,
    harvested_at TEXT,
    PRIMARY KEY (url_norm, engine, query)
);

CREATE TABLE IF NOT EXISTS harvest_runs (
    engine      TEXT NOT NULL,
    query       TEXT NOT NULL,
    class_hint  TEXT,
    max_num     INTEGER,
    urls_found  INTEGER,
    urls_new    INTEGER,
    finished_at TEXT,
    PRIMARY KEY (engine, query)
);

CREATE TABLE IF NOT EXISTS images (
    image_id         TEXT PRIMARY KEY,
    sha256           TEXT NOT NULL,
    origin           TEXT NOT NULL DEFAULT 'web',
    source_ref       TEXT,
    orig_path        TEXT,
    orig_format      TEXT,
    filesize         INTEGER,
    width            INTEGER,
    height           INTEGER,
    aspect_ratio     REAL,
    norm_path        TEXT,
    norm_width       INTEGER,
    norm_height      INTEGER,
    pixel_sha256     TEXT,
    phash            TEXT,
    dhash            TEXT,
    phash_flip       TEXT,
    dhash_flip       TEXT,
    flags            TEXT NOT NULL DEFAULT '[]',
    status           TEXT NOT NULL,
    discard_reason   TEXT,
    dup_of           TEXT,
    cluster_id       TEXT,
    clip_score       REAL,
    relevance_bucket TEXT,
    board_type       TEXT,
    condition        TEXT,
    source_type      TEXT,
    review_status    TEXT,
    reviewer         TEXT,
    reviewed_at      TEXT,
    split            TEXT,
    session_id       TEXT,
    board_id         TEXT,
    created_at       TEXT,
    updated_at       TEXT
);
CREATE INDEX IF NOT EXISTS idx_images_status  ON images(status);
CREATE INDEX IF NOT EXISTS idx_images_cluster ON images(cluster_id);
CREATE INDEX IF NOT EXISTS idx_images_dup_of  ON images(dup_of);

CREATE TABLE IF NOT EXISTS embeddings (
    image_id TEXT PRIMARY KEY,
    dim      INTEGER NOT NULL,
    vec      BLOB NOT NULL
);
"""

IMAGE_COLUMNS = {
    "image_id", "sha256", "origin", "source_ref", "orig_path", "orig_format", "filesize", "width",
    "height", "aspect_ratio", "norm_path", "norm_width", "norm_height", "pixel_sha256", "phash",
    "dhash", "phash_flip", "dhash_flip", "flags", "status", "discard_reason", "dup_of", "cluster_id",
    "clip_score", "relevance_bucket", "board_type", "condition", "source_type", "review_status",
    "reviewer", "reviewed_at", "split", "session_id", "board_id", "created_at", "updated_at",
}

_TRACKING_PARAMS = {"fbclid", "gclid", "msclkid", "yclid"}
_DEFAULT_PORTS = {"http": 80, "https": 443}


def utcnow() -> str:
    return datetime.now(timezone.utc).isoformat(timespec="seconds")


def normalize_url(url: str) -> str:
    """Canonical form used as the dedup key for URLs (case, default ports, fragment, tracking)."""
    parts = urlsplit(url.strip())
    scheme = parts.scheme.lower()
    host = (parts.hostname or "").lower()
    try:
        port = parts.port
    except ValueError:
        port = None
    netloc = host
    if port and port != _DEFAULT_PORTS.get(scheme):
        netloc = f"{host}:{port}"
    query = sorted(
        (k, v) for k, v in parse_qsl(parts.query, keep_blank_values=True)
        if not k.lower().startswith("utm_") and k.lower() not in _TRACKING_PARAMS
    )
    return urlunsplit((scheme, netloc, parts.path or "/", urlencode(query), ""))


def _check_columns(fields: Iterable[str]) -> None:
    bad = set(fields) - IMAGE_COLUMNS
    if bad:
        raise KeyError(f"unknown image column(s): {sorted(bad)}")


class Manifest:
    """Thread-safe SQLite wrapper (one connection, serialized by an RLock)."""

    def __init__(self, db_path: str | Path):
        self.db_path = Path(db_path)
        self.db_path.parent.mkdir(parents=True, exist_ok=True)
        self._conn = sqlite3.connect(str(self.db_path), check_same_thread=False,
                                     isolation_level=None, timeout=60)
        self._conn.row_factory = sqlite3.Row
        self._lock = threading.RLock()
        self._tx_depth = 0
        with self._lock:
            self._conn.executescript(SCHEMA)

    # -- infrastructure -----------------------------------------------------------------
    def close(self) -> None:
        with self._lock:
            self._conn.close()

    def __enter__(self) -> "Manifest":
        return self

    def __exit__(self, *exc) -> None:
        self.close()

    @contextmanager
    def transaction(self) -> Iterator[None]:
        """Group many writes into one commit (re-entrant)."""
        with self._lock:
            outer = self._tx_depth == 0
            if outer:
                self._conn.execute("BEGIN")
            self._tx_depth += 1
            try:
                yield
            except BaseException:
                self._tx_depth -= 1
                if outer:
                    self._conn.execute("ROLLBACK")
                raise
            else:
                self._tx_depth -= 1
                if outer:
                    self._conn.execute("COMMIT")

    def execute(self, sql: str, params: Iterable[Any] = ()) -> sqlite3.Cursor:
        with self._lock:
            return self._conn.execute(sql, tuple(params))

    def query(self, sql: str, params: Iterable[Any] = ()) -> list[sqlite3.Row]:
        with self._lock:
            return self._conn.execute(sql, tuple(params)).fetchall()

    # -- sources / hits -------------------------------------------------------------------
    def add_hit(self, url: str, engine: str, query: str, class_hint: str | None = None,
                lang: str | None = None) -> bool:
        """Record a harvested URL. Returns True if the URL was new."""
        url_norm = normalize_url(url)
        now = utcnow()
        with self._lock:
            cur = self._conn.execute(
                "INSERT OR IGNORE INTO sources(url_norm, url, status, harvested_at) "
                "VALUES (?, ?, 'pending', ?)", (url_norm, url, now))
            is_new = cur.rowcount == 1
            self._conn.execute(
                "INSERT OR IGNORE INTO hits(url_norm, engine, query, class_hint, lang, harvested_at) "
                "VALUES (?, ?, ?, ?, ?, ?)", (url_norm, engine, query, class_hint, lang, now))
        return is_new

    def pending_sources(self, limit: int | None = None, include_transient: bool = False) -> list[dict]:
        statuses = ("pending", "failed_transient") if include_transient else ("pending",)
        sql = f"SELECT * FROM sources WHERE status IN ({','.join('?' * len(statuses))}) ORDER BY harvested_at, url_norm"
        params: list[Any] = list(statuses)
        if limit:
            sql += " LIMIT ?"
            params.append(limit)
        return [dict(r) for r in self.query(sql, params)]

    def mark_source(self, url_norm: str, status: str, http_status: int | None = None,
                    error: str | None = None, image_id: str | None = None, attempts: int = 0) -> None:
        self.execute(
            "UPDATE sources SET status=?, http_status=?, error=?, image_id=?, "
            "attempts=attempts+?, downloaded_at=? WHERE url_norm=?",
            (status, http_status, error, image_id, attempts, utcnow(), url_norm))

    # -- harvest runs ---------------------------------------------------------------------
    def run_done(self, engine: str, query: str) -> bool:
        return bool(self.query("SELECT 1 FROM harvest_runs WHERE engine=? AND query=?", (engine, query)))

    def record_run(self, engine: str, query: str, class_hint: str | None, max_num: int,
                   found: int, new: int) -> None:
        self.execute(
            "INSERT OR REPLACE INTO harvest_runs VALUES (?, ?, ?, ?, ?, ?, ?)",
            (engine, query, class_hint, max_num, found, new, utcnow()))

    # -- images ----------------------------------------------------------------------------
    def add_image(self, **fields: Any) -> bool:
        """Insert an image row if its image_id is new. Returns True if inserted."""
        _check_columns(fields)
        fields.setdefault("origin", "web")
        now = utcnow()
        fields.setdefault("created_at", now)
        fields.setdefault("updated_at", now)
        if isinstance(fields.get("flags"), (list, tuple, set)):
            fields["flags"] = json.dumps(sorted(fields["flags"]))
        cols = list(fields)
        cur = self.execute(
            f"INSERT OR IGNORE INTO images({','.join(cols)}) VALUES ({','.join('?' * len(cols))})",
            [fields[c] for c in cols])
        return cur.rowcount == 1

    @staticmethod
    def _row(row: sqlite3.Row | None) -> dict | None:
        if row is None:
            return None
        d = dict(row)
        d["flags"] = json.loads(d.get("flags") or "[]")
        return d

    def get_image(self, image_id: str) -> dict | None:
        rows = self.query("SELECT * FROM images WHERE image_id=?", (image_id,))
        return self._row(rows[0]) if rows else None

    def images(self, statuses: Iterable[str] | None = None, origin: str | None = None,
               where: str | None = None, params: Iterable[Any] = ()) -> list[dict]:
        clauses, args = [], []
        if statuses:
            statuses = tuple(statuses)
            clauses.append(f"status IN ({','.join('?' * len(statuses))})")
            args += list(statuses)
        if origin:
            clauses.append("origin=?")
            args.append(origin)
        if where:
            clauses.append(f"({where})")
            args += list(params)
        sql = "SELECT * FROM images" + (" WHERE " + " AND ".join(clauses) if clauses else "")
        sql += " ORDER BY image_id"
        return [self._row(r) for r in self.query(sql, args)]

    def update_image(self, image_id: str, **fields: Any) -> None:
        _check_columns(fields)
        if not fields:
            return
        if isinstance(fields.get("flags"), (list, tuple, set)):
            fields["flags"] = json.dumps(sorted(fields["flags"]))
        fields["updated_at"] = utcnow()
        sets = ", ".join(f"{c}=?" for c in fields)
        self.execute(f"UPDATE images SET {sets} WHERE image_id=?", [*fields.values(), image_id])

    def add_flags(self, image_id: str, *new_flags: str) -> None:
        img = self.get_image(image_id)
        if img is None:
            return
        merged = sorted(set(img["flags"]) | set(new_flags))
        self.update_image(image_id, flags=merged)

    def discard(self, image_id: str, reason: str, dup_of: str | None = None) -> None:
        self.update_image(image_id, status="discarded", discard_reason=reason, dup_of=dup_of)

    def count_by(self, column: str, where: str = "1=1", params: Iterable[Any] = ()) -> dict[str, int]:
        _check_columns([column])
        rows = self.query(
            f"SELECT {column} AS k, COUNT(*) AS n FROM images WHERE {where} GROUP BY {column}", params)
        return {(r["k"] if r["k"] is not None else "none"): r["n"] for r in rows}

    # -- provenance ----------------------------------------------------------------------
    def class_hints_by_image(self) -> dict[str, set[str]]:
        """image_id -> class hints, folding duplicates (dup_of) into their keeper."""
        rows = self.query(
            "SELECT s.image_id AS image_id, h.class_hint AS class_hint "
            "FROM sources s JOIN hits h ON h.url_norm = s.url_norm "
            "WHERE s.image_id IS NOT NULL AND h.class_hint IS NOT NULL")
        direct: dict[str, set[str]] = {}
        for r in rows:
            direct.setdefault(r["image_id"], set()).add(r["class_hint"])
        result = {k: set(v) for k, v in direct.items()}
        for r in self.query("SELECT image_id, dup_of FROM images WHERE dup_of IS NOT NULL"):
            if r["image_id"] in direct:
                result.setdefault(r["dup_of"], set()).update(direct[r["image_id"]])
        return result

    def provenance(self, image_id: str) -> dict[str, list[str]]:
        """Source URLs, queries, engines and class hints for an image incl. its duplicates."""
        rows = self.query(
            "SELECT s.url AS url, h.engine AS engine, h.query AS query, h.class_hint AS class_hint "
            "FROM sources s LEFT JOIN hits h ON h.url_norm = s.url_norm "
            "WHERE s.image_id IN (SELECT ? UNION SELECT image_id FROM images WHERE dup_of = ?)",
            (image_id, image_id))
        out: dict[str, set[str]] = {"source_urls": set(), "engines": set(), "queries": set(),
                                    "class_hints": set()}
        for r in rows:
            out["source_urls"].add(r["url"])
            if r["engine"]:
                out["engines"].add(r["engine"])
            if r["query"]:
                out["queries"].add(r["query"])
            if r["class_hint"]:
                out["class_hints"].add(r["class_hint"])
        return {k: sorted(v) for k, v in out.items()}

    def valid_counts_by_class(self, valid_statuses: Iterable[str] = ("deduped", "kept", "validated", "normalized")) -> dict[str, int]:
        """Return a mapping of class_hint -> count of valid (non-discarded) images."""
        statuses = tuple(valid_statuses)
        sql = f"""
            SELECT h.class_hint, COUNT(DISTINCT i.image_id)
            FROM images i
            JOIN sources s ON i.source_ref = s.url_norm OR i.image_id = s.image_id
            JOIN hits h ON s.url_norm = h.url_norm
            WHERE i.status IN ({','.join('?' * len(statuses))})
            GROUP BY h.class_hint
        """
        rows = self.query(sql, statuses)
        return {r[0]: r[1] for r in rows if r[0]}

    def export_jsonl(self, path: str | Path) -> int:
        path = Path(path)
        path.parent.mkdir(parents=True, exist_ok=True)
        n = 0
        with open(path, "w", encoding="utf-8") as fh:
            for img in self.images():
                img.update(self.provenance(img["image_id"]))
                fh.write(json.dumps(img, ensure_ascii=False) + "\n")
                n += 1
        return n

    # -- embeddings ----------------------------------------------------------------------
    def save_embeddings(self, vectors: dict[str, np.ndarray]) -> None:
        with self.transaction():
            for image_id, vec in vectors.items():
                arr = np.asarray(vec, dtype=np.float16)
                self.execute("INSERT OR REPLACE INTO embeddings VALUES (?, ?, ?)",
                             (image_id, int(arr.shape[0]), arr.tobytes()))

    def load_embeddings(self, image_ids: Iterable[str] | None = None) -> tuple[list[str], np.ndarray]:
        rows = self.query("SELECT image_id, dim, vec FROM embeddings ORDER BY image_id")
        if image_ids is not None:
            wanted = set(image_ids)
            rows = [r for r in rows if r["image_id"] in wanted]
        if not rows:
            return [], np.zeros((0, 0), dtype=np.float32)
        ids = [r["image_id"] for r in rows]
        mat = np.stack([np.frombuffer(r["vec"], dtype=np.float16).astype(np.float32) for r in rows])
        return ids, mat