File size: 8,484 Bytes
e1ced61
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
"""SQLite fingerprint index for decontamination (``docs/02`` §5, ``docs/07`` §5).

Two indexes are produced by the ``fingerprint`` command:

- ``eval.sqlite`` — fingerprints of the frozen evaluation registry
- ``train_candidates.sqlite`` — fingerprints of every normalized train source

The schema is intentionally simple and deterministic: one ``fingerprints`` row
per base_id plus one ``images`` row per (base_id, image) so exact-image and
pHash near-duplicate joins are plain indexed SQL. The ``decontaminate`` command
reads both indexes and never mutates them.

OCR MinHash is stored as a nullable column populated later by the P5 OCR pass
(:func:`update_ocr_minhash`); at P3 it is empty for every row.
"""

from __future__ import annotations

import json
import sqlite3
from collections.abc import Iterable, Iterator, Mapping, Sequence
from dataclasses import dataclass
from pathlib import Path
from typing import Any

from .fingerprints import Fingerprints

_SCHEMA = """
CREATE TABLE IF NOT EXISTS fingerprints (
    base_id                   TEXT PRIMARY KEY,
    source                    TEXT NOT NULL,
    source_revision           TEXT NOT NULL,
    config                    TEXT NOT NULL,
    split                     TEXT NOT NULL,
    native_id                 TEXT NOT NULL,
    policy                    TEXT NOT NULL,
    question_sha256           TEXT NOT NULL,
    choices_sha256            TEXT NOT NULL,
    question_canonical_sha256 TEXT NOT NULL,
    question_minhash          TEXT NOT NULL,
    choice_minhash            TEXT NOT NULL,
    ocr_minhash               TEXT NOT NULL DEFAULT '[]',
    derived_from_eval         INTEGER NOT NULL DEFAULT 0,
    raw_json                  TEXT NOT NULL
);
CREATE TABLE IF NOT EXISTS images (
    base_id       TEXT NOT NULL,
    image_sha256  TEXT NOT NULL,
    phash         TEXT NOT NULL,
    PRIMARY KEY (base_id, image_sha256)
);
CREATE INDEX IF NOT EXISTS idx_images_sha   ON images(image_sha256);
CREATE INDEX IF NOT EXISTS idx_images_phash ON images(phash);
CREATE INDEX IF NOT EXISTS idx_fp_source    ON fingerprints(source);
"""


def _connect(db_path: str | Path) -> sqlite3.Connection:
    path = Path(db_path)
    path.parent.mkdir(parents=True, exist_ok=True)
    conn = sqlite3.connect(str(path))
    conn.execute("PRAGMA journal_mode=WAL")
    conn.executescript(_SCHEMA)
    return conn


def _signature_json(sig: Sequence[int]) -> str:
    return json.dumps(list(sig))


def write_fingerprints(db_path: str | Path, fingerprints: Iterable[Fingerprints]) -> int:
    """(Re)build the index from ``fingerprints``; return the row count.

    The index is a derived artifact, so this overwrites any prior contents.
    """
    conn = _connect(db_path)
    try:
        with conn:
            conn.execute("DELETE FROM fingerprints")
            conn.execute("DELETE FROM images")
            count = 0
            for fp in fingerprints:
                conn.execute(
                    """INSERT INTO fingerprints
                       (base_id, source, source_revision, config, split, native_id,
                        policy, question_sha256, choices_sha256, question_canonical_sha256,
                        question_minhash, choice_minhash, ocr_minhash, derived_from_eval,
                        raw_json)
                       VALUES (?,?,?,?,?,?,?,?,?,?,?,?,?,?,?)""",
                    (
                        fp.base_id,
                        fp.source,
                        fp.source_revision,
                        fp.config,
                        fp.split,
                        fp.native_id,
                        fp.policy,
                        fp.question_sha256,
                        fp.choices_sha256,
                        fp.question_canonical_sha256,
                        _signature_json(fp.question_minhash),
                        _signature_json(fp.choice_minhash),
                        _signature_json(fp.ocr_minhash),
                        int(fp.derived_from_eval),
                        json.dumps(fp.raw, sort_keys=True),
                    ),
                )
                for sha, phash in zip(fp.image_sha256, fp.image_phash, strict=True):
                    conn.execute(
                        "INSERT OR REPLACE INTO images (base_id, image_sha256, phash) "
                        "VALUES (?,?,?)",
                        (fp.base_id, sha, phash),
                    )
                # Text-only items still get one placeholder image row keyed by their
                # (single) sha so nothing is silently dropped; text items have none.
                count += 1
        return count
    finally:
        conn.close()


def update_ocr_minhash(db_path: str | Path, base_id: str, ocr_signature: Sequence[int]) -> bool:
    """Set the OCR MinHash for one base_id (P5 OCR enrichment). Returns whether updated."""
    conn = _connect(db_path)
    try:
        with conn:
            cur = conn.execute(
                "UPDATE fingerprints SET ocr_minhash = ? WHERE base_id = ?",
                (_signature_json(ocr_signature), base_id),
            )
        return cur.rowcount > 0
    finally:
        conn.close()


@dataclass(frozen=True)
class LoadedFingerprints:
    base_id: str
    source: str
    source_revision: str
    config: str
    split: str
    native_id: str
    policy: str
    question_sha256: str
    choices_sha256: str
    question_canonical_sha256: str
    image_sha256: tuple[str, ...]
    image_phash: tuple[str, ...]
    question_minhash: tuple[int, ...]
    choice_minhash: tuple[int, ...]
    ocr_minhash: tuple[int, ...]
    derived_from_eval: bool


def _load_images(conn: sqlite3.Connection, base_id: str) -> tuple[tuple[str, ...], tuple[str, ...]]:
    rows = conn.execute(
        "SELECT image_sha256, phash FROM images WHERE base_id = ?", (base_id,)
    ).fetchall()
    shas = tuple(r[0] for r in rows)
    phashes = tuple(r[1] for r in rows)
    return shas, phashes


def _parse_sig(value: str) -> tuple[int, ...]:
    if not value:
        return ()
    return tuple(int(x) for x in json.loads(value))


def load_all(db_path: str | Path) -> list[LoadedFingerprints]:
    """Load every fingerprint from the index, keyed by base_id (sorted)."""
    conn = sqlite3.connect(str(db_path))
    try:
        rows = conn.execute(
            """SELECT base_id, source, source_revision, config, split, native_id,
                      policy, question_sha256, choices_sha256, question_canonical_sha256,
                      question_minhash, choice_minhash, ocr_minhash, derived_from_eval
               FROM fingerprints ORDER BY base_id"""
        ).fetchall()
        result: list[LoadedFingerprints] = []
        for r in rows:
            shas, phashes = _load_images(conn, r[0])
            result.append(
                LoadedFingerprints(
                    base_id=r[0],
                    source=r[1],
                    source_revision=r[2],
                    config=r[3],
                    split=r[4],
                    native_id=r[5],
                    policy=r[6],
                    question_sha256=r[7],
                    choices_sha256=r[8],
                    question_canonical_sha256=r[9],
                    image_sha256=shas,
                    image_phash=phashes,
                    question_minhash=_parse_sig(r[10]),
                    choice_minhash=_parse_sig(r[11]),
                    ocr_minhash=_parse_sig(r[12]),
                    derived_from_eval=bool(r[13]),
                )
            )
        return result
    finally:
        conn.close()


def eval_image_shas(db_path: str | Path) -> set[str]:
    """All image SHA-256 present in an index (for exact-image reject)."""
    conn = sqlite3.connect(str(db_path))
    try:
        return {row[0] for row in conn.execute("SELECT DISTINCT image_sha256 FROM images")}
    finally:
        conn.close()


def row_count(db_path: str | Path) -> int:
    conn = sqlite3.connect(str(db_path))
    try:
        return int(conn.execute("SELECT COUNT(*) FROM fingerprints").fetchone()[0])
    finally:
        conn.close()


def iter_rows(db_path: str | Path) -> Iterator[Mapping[str, Any]]:
    """Yield raw source rows (the ``raw_json`` column) for audit/rebuild."""
    conn = sqlite3.connect(str(db_path))
    try:
        for raw in conn.execute("SELECT raw_json FROM fingerprints ORDER BY base_id"):
            yield json.loads(raw[0])
    finally:
        conn.close()