"""SQLite-хранилище: items + FTS5 + sources + runs. Дедуп по канону URL и по simhash (band-индекс).""" import json, sqlite3, time from pathlib import Path from typing import Iterable, Optional from . import config from .extract import canon_url, hamming SCHEMA = """ PRAGMA journal_mode=WAL; PRAGMA synchronous=NORMAL; CREATE TABLE IF NOT EXISTS items( id INTEGER PRIMARY KEY AUTOINCREMENT, uid TEXT UNIQUE, source TEXT, kind TEXT, title TEXT, url TEXT, price TEXT, volume TEXT, ts TEXT, snippet TEXT, h INTEGER, score REAL DEFAULT 0, flags TEXT, seen_at TEXT ); CREATE INDEX IF NOT EXISTS idx_items_kind ON items(kind); CREATE INDEX IF NOT EXISTS idx_items_source ON items(source); CREATE INDEX IF NOT EXISTS idx_items_seen ON items(seen_at); CREATE INDEX IF NOT EXISTS idx_items_h ON items(h); CREATE TABLE IF NOT EXISTS sources( name TEXT PRIMARY KEY, url TEXT, adapter TEXT, ok INTEGER DEFAULT 0, fails INTEGER DEFAULT 0, last_ok TEXT, last_status INTEGER, added TEXT, note TEXT ); CREATE TABLE IF NOT EXISTS runs( id INTEGER PRIMARY KEY AUTOINCREMENT, started TEXT, ended TEXT, sources INTEGER, fetched INTEGER, new INTEGER, dup INTEGER, blocked INTEGER ); CREATE VIRTUAL TABLE IF NOT EXISTS items_fts USING fts5( title, snippet, content='items', content_rowid='id', tokenize='unicode61' ); CREATE TRIGGER IF NOT EXISTS items_ai AFTER INSERT ON items BEGIN INSERT INTO items_fts(rowid, title, snippet) VALUES (new.id, new.title, new.snippet); END; CREATE TRIGGER IF NOT EXISTS items_ad AFTER DELETE ON items BEGIN INSERT INTO items_fts(items_fts, rowid, title, snippet) VALUES('delete', old.id, old.title, old.snippet); END; CREATE TRIGGER IF NOT EXISTS items_au AFTER UPDATE ON items BEGIN INSERT INTO items_fts(items_fts, rowid, title, snippet) VALUES('delete', old.id, old.title, old.snippet); INSERT INTO items_fts(rowid, title, snippet) VALUES (new.id, new.title, new.snippet); END; """ class NearDup: """Дедуп по simhash с бэндами: 4 полосы по 16 бит, сравнение только внутри бэндов.""" BANDS = ((0, 16), (16, 32), (32, 48), (48, 64)) def __init__(self, hashes: Iterable[int] = ()): self.bands = [dict() for _ in self.BANDS] for h in hashes: self.add(h) def _keys(self, h: int): for i, (lo, hi) in enumerate(self.BANDS): yield i, (h >> lo) & 0xFFFF def add(self, h: int): for i, k in self._keys(h): self.bands[i].setdefault(k, []).append(h) def dup_of(self, h: int, threshold: int = 3) -> Optional[int]: for i, k in self._keys(h): for other in self.bands[i].get(k, ()): if hamming(h, other) <= threshold: return other return None def connect(path: Path | None = None) -> sqlite3.Connection: config.ensure_dirs() con = sqlite3.connect(str(path or config.DB), timeout=30) con.row_factory = sqlite3.Row con.executescript(SCHEMA) return con def add_source(con, name, url, adapter="auto", note="") -> bool: cur = con.execute("SELECT 1 FROM sources WHERE name=?", (name,)) if cur.fetchone(): return False con.execute("INSERT INTO sources(name,url,adapter,added,note) VALUES(?,?,?,?,?)", (name, url, adapter, time.strftime("%Y-%m-%d %H:%M:%S"), note)) return True def all_sources(con, only_ok=False, limit=None): q = "SELECT * FROM sources" if only_ok: q += " WHERE ok=1" q += " ORDER BY fails ASC, name ASC" if limit: q += f" LIMIT {int(limit)}" return con.execute(q).fetchall() def load_hashes(con) -> list[int]: return [r[0] & 0xFFFFFFFFFFFFFFFF for r in con.execute("SELECT h FROM items")] def insert_items(con, findings, dedup: NearDup | None = None) -> tuple[int, int]: """Возвращает (новых, дублей). Дубль по канону URL или по simhash.""" new = dup = 0 now = time.strftime("%Y-%m-%d %H:%M:%S") for f in findings: uid = canon_url(f.url) cur = con.execute("SELECT 1 FROM items WHERE uid=?", (uid,)) if cur.fetchone(): dup += 1 continue if dedup and dedup.dup_of(f.h) is not None: dup += 1 continue try: hval = f.h - (1 << 64) if f.h >= (1 << 63) else f.h # sqlite INTEGER = signed 64 con.execute( "INSERT INTO items(uid,source,kind,title,url,price,volume,ts,snippet,h,score,flags,seen_at)" " VALUES(?,?,?,?,?,?,?,?,?,?,?,?,?)", (uid, f.source, f.kind, f.title, f.url, f.price, f.volume, f.ts, f.snippet, hval, f.score, ",".join(f.flags), now)) new += 1 if dedup: dedup.add(f.h) except sqlite3.IntegrityError: dup += 1 return new, dup def set_source_result(con, name, status: int, items: int = 0): now = time.strftime("%Y-%m-%d %H:%M:%S") if status == 200: con.execute("UPDATE sources SET ok=ok+1, last_ok=?, last_status=?, note=? WHERE name=?", (now, status, f"{items} items", name)) else: con.execute("UPDATE sources SET fails=fails+1, last_status=? WHERE name=?", (status, name)) def log_run(con, started, sources, fetched, new, dup, blocked): con.execute("INSERT INTO runs(started,ended,sources,fetched,new,dup,blocked) VALUES(?,?,?,?,?,?,?)", (started, time.strftime("%Y-%m-%d %H:%M:%S"), sources, fetched, new, dup, blocked)) def stats(con) -> dict: g = lambda q, *a: con.execute(q, a).fetchone()[0] kinds = {r["kind"]: r["n"] for r in con.execute( "SELECT kind, COUNT(*) n FROM items GROUP BY kind ORDER BY n DESC")} return { "items": g("SELECT COUNT(*) FROM items"), "sources": g("SELECT COUNT(*) FROM sources"), "sources_ok": g("SELECT COUNT(*) FROM sources WHERE ok>0"), "sources_dead": g("SELECT COUNT(*) FROM sources WHERE ok=0 AND fails>0"), "runs": g("SELECT COUNT(*) FROM runs"), "priced": g("SELECT COUNT(*) FROM items WHERE price<>''"), "kinds": kinds, "last_run": dict(con.execute("SELECT * FROM runs ORDER BY id DESC LIMIT 1").fetchone() or {}), } def search(con, q: str, limit: int = 20): return con.execute( "SELECT i.* FROM items_fts f JOIN items i ON i.id=f.rowid WHERE items_fts MATCH ? ORDER BY rank LIMIT ?", (q, limit)).fetchall() def top(con, limit: int = 20, kind: str | None = None, days: int | None = None): q = "SELECT * FROM items" where, args = [], [] if kind: where.append("kind=?"); args.append(kind) if days: where.append("seen_at >= datetime('now', ?)"); args.append(f"-{int(days)} days") if where: q += " WHERE " + " AND ".join(where) q += " ORDER BY score DESC, id DESC LIMIT ?" args.append(limit) return con.execute(q, args).fetchall()