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|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""SQLite learning database for tracking solver accuracy and optimization history."""
|
| 2 |
+
from __future__ import annotations
|
| 3 |
+
|
| 4 |
+
import json
|
| 5 |
+
import sqlite3
|
| 6 |
+
import time
|
| 7 |
+
from pathlib import Path
|
| 8 |
+
from typing import Any
|
| 9 |
+
|
| 10 |
+
DATA_DIR = Path(__file__).resolve().parent.parent.parent / "data"
|
| 11 |
+
DATA_DIR.mkdir(parents=True, exist_ok=True)
|
| 12 |
+
DB_PATH = DATA_DIR / "learning.db"
|
| 13 |
+
|
| 14 |
+
SCHEMA = """
|
| 15 |
+
CREATE TABLE IF NOT EXISTS attempts (
|
| 16 |
+
id INTEGER PRIMARY KEY AUTOINCREMENT,
|
| 17 |
+
captcha_type TEXT NOT NULL,
|
| 18 |
+
solver_used TEXT NOT NULL,
|
| 19 |
+
hint TEXT,
|
| 20 |
+
image_hash TEXT,
|
| 21 |
+
answer TEXT,
|
| 22 |
+
expected TEXT,
|
| 23 |
+
correct INTEGER,
|
| 24 |
+
confidence REAL,
|
| 25 |
+
latency_ms INTEGER,
|
| 26 |
+
preprocess_steps TEXT,
|
| 27 |
+
run_source TEXT DEFAULT 'api',
|
| 28 |
+
timestamp TEXT DEFAULT (datetime('now'))
|
| 29 |
+
);
|
| 30 |
+
|
| 31 |
+
CREATE TABLE IF NOT EXISTS solver_stats (
|
| 32 |
+
solver_name TEXT NOT NULL,
|
| 33 |
+
captcha_type TEXT NOT NULL,
|
| 34 |
+
total INTEGER DEFAULT 0,
|
| 35 |
+
correct INTEGER DEFAULT 0,
|
| 36 |
+
avg_latency_ms REAL DEFAULT 0,
|
| 37 |
+
last_run TEXT DEFAULT (datetime('now')),
|
| 38 |
+
PRIMARY KEY (solver_name, captcha_type)
|
| 39 |
+
);
|
| 40 |
+
|
| 41 |
+
CREATE TABLE IF NOT EXISTS optimization_log (
|
| 42 |
+
id INTEGER PRIMARY KEY AUTOINCREMENT,
|
| 43 |
+
cycle INTEGER,
|
| 44 |
+
action TEXT,
|
| 45 |
+
before_val TEXT,
|
| 46 |
+
after_val TEXT,
|
| 47 |
+
before_acc REAL,
|
| 48 |
+
after_acc REAL,
|
| 49 |
+
notes TEXT,
|
| 50 |
+
timestamp TEXT DEFAULT (datetime('now'))
|
| 51 |
+
);
|
| 52 |
+
|
| 53 |
+
CREATE TABLE IF NOT EXISTS cycles (
|
| 54 |
+
id INTEGER PRIMARY KEY AUTOINCREMENT,
|
| 55 |
+
status TEXT DEFAULT 'running',
|
| 56 |
+
total_solves INTEGER DEFAULT 0,
|
| 57 |
+
correct_solves INTEGER DEFAULT 0,
|
| 58 |
+
avg_latency_ms REAL DEFAULT 0,
|
| 59 |
+
started_at TEXT DEFAULT (datetime('now')),
|
| 60 |
+
finished_at TEXT
|
| 61 |
+
);
|
| 62 |
+
"""
|
| 63 |
+
|
| 64 |
+
|
| 65 |
+
class LearningDB:
|
| 66 |
+
def __init__(self, db_path: str | Path = DB_PATH) -> None:
|
| 67 |
+
self.db_path = Path(db_path)
|
| 68 |
+
self.db_path.parent.mkdir(parents=True, exist_ok=True)
|
| 69 |
+
self._conn: sqlite3.Connection | None = None
|
| 70 |
+
|
| 71 |
+
@property
|
| 72 |
+
def conn(self) -> sqlite3.Connection:
|
| 73 |
+
if self._conn is None:
|
| 74 |
+
self._conn = sqlite3.connect(str(self.db_path), check_same_thread=False)
|
| 75 |
+
self._conn.row_factory = sqlite3.Row
|
| 76 |
+
self._conn.executescript(SCHEMA)
|
| 77 |
+
self._conn.commit()
|
| 78 |
+
return self._conn
|
| 79 |
+
|
| 80 |
+
def close(self) -> None:
|
| 81 |
+
if self._conn:
|
| 82 |
+
self._conn.close()
|
| 83 |
+
self._conn = None
|
| 84 |
+
|
| 85 |
+
# --- Attempts ---
|
| 86 |
+
def record_attempt(
|
| 87 |
+
self,
|
| 88 |
+
captcha_type: str,
|
| 89 |
+
solver_used: str,
|
| 90 |
+
answer: str | None,
|
| 91 |
+
expected: str | None = None,
|
| 92 |
+
correct: bool | None = None,
|
| 93 |
+
confidence: float | None = None,
|
| 94 |
+
latency_ms: int | None = None,
|
| 95 |
+
hint: str | None = None,
|
| 96 |
+
image_hash: str | None = None,
|
| 97 |
+
preprocess_steps: str | None = None,
|
| 98 |
+
run_source: str = "api",
|
| 99 |
+
) -> int:
|
| 100 |
+
if correct is None and expected is not None and answer is not None:
|
| 101 |
+
correct = answer.strip().lower() == expected.strip().lower()
|
| 102 |
+
cur = self.conn.execute(
|
| 103 |
+
"""INSERT INTO attempts
|
| 104 |
+
(captcha_type, solver_used, hint, image_hash, answer, expected, correct, confidence, latency_ms, preprocess_steps, run_source)
|
| 105 |
+
VALUES (?,?,?,?,?,?,?,?,?,?,?)""",
|
| 106 |
+
(captcha_type, solver_used, hint, image_hash, answer, expected,
|
| 107 |
+
int(correct) if correct is not None else None,
|
| 108 |
+
confidence, latency_ms, preprocess_steps, run_source),
|
| 109 |
+
)
|
| 110 |
+
self.conn.commit()
|
| 111 |
+
self._update_stats(solver_used, captcha_type, correct, latency_ms)
|
| 112 |
+
return cur.lastrowid
|
| 113 |
+
|
| 114 |
+
def _update_stats(self, solver: str, ctype: str, correct: bool | None, latency_ms: int | None) -> None:
|
| 115 |
+
row = self.conn.execute(
|
| 116 |
+
"SELECT total, correct, avg_latency_ms FROM solver_stats WHERE solver_name=? AND captcha_type=?",
|
| 117 |
+
(solver, ctype)
|
| 118 |
+
).fetchone()
|
| 119 |
+
if row:
|
| 120 |
+
t = row["total"] + 1
|
| 121 |
+
c = row["correct"] + (1 if correct else 0) if correct is not None else row["correct"]
|
| 122 |
+
avg = row["avg_latency_ms"]
|
| 123 |
+
if latency_ms:
|
| 124 |
+
avg = ((avg * row["total"]) + latency_ms) / t
|
| 125 |
+
self.conn.execute(
|
| 126 |
+
"UPDATE solver_stats SET total=?, correct=?, avg_latency_ms=?, last_run=datetime('now') WHERE solver_name=? AND captcha_type=?",
|
| 127 |
+
(t, c, avg, solver, ctype)
|
| 128 |
+
)
|
| 129 |
+
else:
|
| 130 |
+
self.conn.execute(
|
| 131 |
+
"INSERT INTO solver_stats (solver_name, captcha_type, total, correct, avg_latency_ms) VALUES (?,?,1,?,?)",
|
| 132 |
+
(solver, ctype, (1 if correct else 0) if correct is not None else 0, latency_ms or 0)
|
| 133 |
+
)
|
| 134 |
+
self.conn.commit()
|
| 135 |
+
|
| 136 |
+
# --- Stats ---
|
| 137 |
+
def get_best_solver(self, captcha_type: str, min_samples: int = 5) -> dict | None:
|
| 138 |
+
rows = self.conn.execute(
|
| 139 |
+
"""SELECT solver_name, total, correct,
|
| 140 |
+
CAST(correct AS REAL) / MAX(total, 1) AS accuracy,
|
| 141 |
+
avg_latency_ms
|
| 142 |
+
FROM solver_stats
|
| 143 |
+
WHERE captcha_type=? AND total>=?
|
| 144 |
+
ORDER BY accuracy DESC, total DESC
|
| 145 |
+
LIMIT 1""",
|
| 146 |
+
(captcha_type, min_samples),
|
| 147 |
+
).fetchall()
|
| 148 |
+
if rows:
|
| 149 |
+
d = dict(rows[0])
|
| 150 |
+
d["accuracy"] = round(d["accuracy"], 3) if d.get("accuracy") is not None else 0.0
|
| 151 |
+
return d
|
| 152 |
+
return None
|
| 153 |
+
|
| 154 |
+
def get_solver_ranking(self, captcha_type: str | None = None) -> list[dict]:
|
| 155 |
+
if captcha_type:
|
| 156 |
+
rows = self.conn.execute(
|
| 157 |
+
"SELECT * FROM solver_stats WHERE captcha_type=? ORDER BY CAST(correct AS REAL)/MAX(total,1) DESC",
|
| 158 |
+
(captcha_type,)
|
| 159 |
+
).fetchall()
|
| 160 |
+
else:
|
| 161 |
+
rows = self.conn.execute(
|
| 162 |
+
"SELECT * FROM solver_stats ORDER BY CAST(correct AS REAL)/MAX(total,1) DESC"
|
| 163 |
+
).fetchall()
|
| 164 |
+
return [dict(r) for r in rows]
|
| 165 |
+
|
| 166 |
+
def get_recent_failures(self, limit: int = 20) -> list[dict]:
|
| 167 |
+
rows = self.conn.execute(
|
| 168 |
+
"""SELECT * FROM attempts WHERE correct=0 AND answer IS NOT NULL
|
| 169 |
+
ORDER BY timestamp DESC LIMIT ?""",
|
| 170 |
+
(limit,)
|
| 171 |
+
).fetchall()
|
| 172 |
+
return [dict(r) for r in rows]
|
| 173 |
+
|
| 174 |
+
# --- Cycles ---
|
| 175 |
+
def start_cycle(self) -> int:
|
| 176 |
+
cur = self.conn.execute("INSERT INTO cycles (status) VALUES ('running')")
|
| 177 |
+
self.conn.commit()
|
| 178 |
+
return cur.lastrowid
|
| 179 |
+
|
| 180 |
+
def finish_cycle(self, cycle_id: int, total: int, correct: int, avg_latency: float) -> None:
|
| 181 |
+
self.conn.execute(
|
| 182 |
+
"UPDATE cycles SET status='completed', total_solves=?, correct_solves=?, avg_latency_ms=?, finished_at=datetime('now') WHERE id=?",
|
| 183 |
+
(total, correct, avg_latency, cycle_id)
|
| 184 |
+
)
|
| 185 |
+
self.conn.commit()
|
| 186 |
+
|
| 187 |
+
def log_optimization(
|
| 188 |
+
self, cycle: int, action: str,
|
| 189 |
+
before_val: str, after_val: str,
|
| 190 |
+
before_acc: float, after_acc: float,
|
| 191 |
+
notes: str = ""
|
| 192 |
+
) -> int:
|
| 193 |
+
cur = self.conn.execute(
|
| 194 |
+
"INSERT INTO optimization_log (cycle, action, before_val, after_val, before_acc, after_acc, notes) VALUES (?,?,?,?,?,?,?)",
|
| 195 |
+
(cycle, action, before_val, after_val, before_acc, after_acc, notes)
|
| 196 |
+
)
|
| 197 |
+
self.conn.commit()
|
| 198 |
+
return cur.lastrowid
|
| 199 |
+
|
| 200 |
+
# --- Export ---
|
| 201 |
+
def summary(self) -> dict:
|
| 202 |
+
totals = self.conn.execute(
|
| 203 |
+
"SELECT COUNT(*) as total, SUM(CASE WHEN correct=1 THEN 1 ELSE 0 END) as correct, AVG(latency_ms) as avg_ms FROM attempts"
|
| 204 |
+
).fetchone()
|
| 205 |
+
acc = round((totals["correct"] / max(totals["total"], 1)) * 100, 1) if totals["total"] else 0
|
| 206 |
+
return {
|
| 207 |
+
"total_attempts": totals["total"],
|
| 208 |
+
"correct": totals["correct"],
|
| 209 |
+
"accuracy_pct": acc,
|
| 210 |
+
"avg_latency_ms": round(totals["avg_ms"] or 0),
|
| 211 |
+
"solver_count": self.conn.execute("SELECT COUNT(*) FROM solver_stats").fetchone()[0],
|
| 212 |
+
"optimization_cycles": self.conn.execute("SELECT COUNT(*) FROM optimization_log").fetchone()[0],
|
| 213 |
+
}
|
| 214 |
+
|
| 215 |
+
def get_recent_attempts(self, limit: int = 50) -> list[dict]:
|
| 216 |
+
rows = self.conn.execute("SELECT * FROM attempts ORDER BY timestamp DESC LIMIT ?", (limit,)).fetchall()
|
| 217 |
+
return [dict(r) for r in rows]
|