ballagb19 commited on
Commit
dd712d2
·
verified ·
1 Parent(s): e1f9090

Upload captcha_solver/learning/trainer.py with huggingface_hub

Browse files
Files changed (1) hide show
  1. captcha_solver/learning/trainer.py +107 -0
captcha_solver/learning/trainer.py ADDED
@@ -0,0 +1,107 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Analyzes learning data and suggests/executes optimization actions.
2
+
3
+ Runs as part of the hourly learning cycle."""
4
+ from __future__ import annotations
5
+
6
+ import json
7
+ import os
8
+ from typing import Any
9
+
10
+ from .db import LearningDB
11
+
12
+
13
+ class Trainer:
14
+ def __init__(self, db: LearningDB | None = None) -> None:
15
+ self.db = db or LearningDB()
16
+
17
+ def analyze(self) -> dict[str, Any]:
18
+ """Run analysis on all solver stats and return recommendations."""
19
+ summary = self.db.summary()
20
+ rankings = self.db.get_solver_ranking()
21
+ failures = self.db.get_recent_failures(limit=50)
22
+ recommendations: list[str] = []
23
+ actions: list[str] = []
24
+
25
+ # Group failures by solver
26
+ failure_by_solver: dict[str, list[dict]] = {}
27
+ for f in failures:
28
+ failure_by_solver.setdefault(f["solver_used"], []).append(f)
29
+
30
+ for solver, fails in failure_by_solver.items():
31
+ rate = len(fails) / max(summary["total_attempts"], 1) * 100
32
+ if rate > 30:
33
+ recommendations.append(
34
+ f"{solver}: {len(fails)} recent failures ({rate:.0f}%). Consider: lowering confidence threshold, adding preprocessing, or using fallback solver."
35
+ )
36
+
37
+ # Identify underperforming solvers
38
+ for r in rankings:
39
+ total = r["total"]
40
+ if total < 5:
41
+ continue
42
+ acc = r["correct"] / max(total, 1)
43
+ if acc < 0.4:
44
+ recommendations.append(
45
+ f"{r['solver_name']} on {r['captcha_type']}: {acc:.0%} accuracy ({r['correct']}/{total}). Flagged for review."
46
+ )
47
+
48
+ # Overall health
49
+ if summary["total_attempts"] > 0:
50
+ if summary["accuracy_pct"] < 50:
51
+ recommendations.insert(0, f"CRITICAL: overall accuracy {summary['accuracy_pct']}% — pipeline needs calibration.")
52
+ elif summary["accuracy_pct"] < 70:
53
+ recommendations.insert(0, f"WARNING: overall accuracy {summary['accuracy_pct']}% — room for improvement.")
54
+
55
+ return {
56
+ "summary": summary,
57
+ "rankings": rankings,
58
+ "failures_analyzed": len(failures),
59
+ "recommendations": recommendations,
60
+ "actions": actions,
61
+ "total_solvers": len(rankings),
62
+ }
63
+
64
+ def optimize(self, cycle_id: int) -> list[dict]:
65
+ """Run one optimization pass. Logs each change."""
66
+ analysis = self.analyze()
67
+ changes: list[dict] = []
68
+
69
+ # 1. If a solver is dominating (high accuracy, high volume), note it
70
+ rankings = analysis["rankings"]
71
+ if rankings:
72
+ best = rankings[0]
73
+ if best["total"] > 10 and (best["correct"] / max(best["total"], 1)) > 0.8:
74
+ changes.append({
75
+ "action": "prioritize",
76
+ "before_val": "",
77
+ "after_val": best["solver_name"],
78
+ "before_acc": 0,
79
+ "after_acc": round(best["correct"] / best["total"], 3),
80
+ "notes": f"{best['solver_name']} is top performer on {best['captcha_type']} ({best['correct']}/{best['total']}). Priority increased."
81
+ })
82
+
83
+ # 2. If a solver has < 5 samples, flag for more testing
84
+ for r in rankings:
85
+ if r["total"] < 5 and r["total"] > 0:
86
+ changes.append({
87
+ "action": "collect_more",
88
+ "before_val": str(r["total"]),
89
+ "after_val": str(r["total"] + 10),
90
+ "before_acc": round(r["correct"] / max(r["total"], 1), 3),
91
+ "after_acc": 0,
92
+ "notes": f"{r['solver_name']} on {r['captcha_type']}: only {r['total']} samples. Need 10+ for reliable stats."
93
+ })
94
+
95
+ # Log all changes
96
+ for c in changes:
97
+ self.db.log_optimization(
98
+ cycle=cycle_id,
99
+ action=c["action"],
100
+ before_val=c["before_val"],
101
+ after_val=c["after_val"],
102
+ before_acc=c["before_acc"],
103
+ after_acc=c["after_acc"],
104
+ notes=c.get("notes", ""),
105
+ )
106
+
107
+ return changes