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
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""Math captcha solver.
|
| 2 |
+
|
| 3 |
+
Strategy order (fast -> slow, accurate -> less):
|
| 4 |
+
1. Pure-Python regex on OCR output (sub-millisecond)
|
| 5 |
+
2. Tiny LLM (Qwen2.5 1.5B) for cleanup if OCR returns garbled math
|
| 6 |
+
3. Ollama text model if enabled
|
| 7 |
+
|
| 8 |
+
For the OCR step we use Florence-2 (or fall back to Tesseract if
|
| 9 |
+
available). The math string is then evaluated safely.
|
| 10 |
+
"""
|
| 11 |
+
|
| 12 |
+
from __future__ import annotations
|
| 13 |
+
|
| 14 |
+
import ast
|
| 15 |
+
import operator
|
| 16 |
+
import re
|
| 17 |
+
from typing import Optional
|
| 18 |
+
|
| 19 |
+
from captcha_solver.solvers.base import BaseSolver, SolveAttempt
|
| 20 |
+
from captcha_solver.utils.image import decode_base64_image, image_to_pil
|
| 21 |
+
|
| 22 |
+
|
| 23 |
+
_SAFE_OPS = {
|
| 24 |
+
ast.Add: operator.add,
|
| 25 |
+
ast.Sub: operator.sub,
|
| 26 |
+
ast.Mult: operator.mul,
|
| 27 |
+
ast.Div: operator.truediv,
|
| 28 |
+
ast.Mod: operator.mod,
|
| 29 |
+
ast.Pow: operator.pow,
|
| 30 |
+
ast.USub: operator.neg,
|
| 31 |
+
ast.UAdd: operator.pos,
|
| 32 |
+
}
|
| 33 |
+
|
| 34 |
+
|
| 35 |
+
def _safe_eval(expr: str) -> Optional[float]:
|
| 36 |
+
"""Evaluate a math expression with only + - * / % ** and parens."""
|
| 37 |
+
if not expr or not re.match(r"^[\d\s+\-*/%().]+$", expr):
|
| 38 |
+
return None
|
| 39 |
+
try:
|
| 40 |
+
tree = ast.parse(expr, mode="eval")
|
| 41 |
+
return _eval_node(tree.body)
|
| 42 |
+
except Exception:
|
| 43 |
+
return None
|
| 44 |
+
|
| 45 |
+
|
| 46 |
+
def _eval_node(node):
|
| 47 |
+
if isinstance(node, ast.Constant) and isinstance(node.value, (int, float)):
|
| 48 |
+
return node.value
|
| 49 |
+
if isinstance(node, ast.BinOp):
|
| 50 |
+
op = _SAFE_OPS.get(type(node.op))
|
| 51 |
+
if op is None:
|
| 52 |
+
raise ValueError("op not allowed")
|
| 53 |
+
return op(_eval_node(node.left), _eval_node(node.right))
|
| 54 |
+
if isinstance(node, ast.UnaryOp):
|
| 55 |
+
op = _SAFE_OPS.get(type(node.op))
|
| 56 |
+
if op is None:
|
| 57 |
+
raise ValueError("op not allowed")
|
| 58 |
+
return op(_eval_node(node.operand))
|
| 59 |
+
raise ValueError("unsupported")
|
| 60 |
+
|
| 61 |
+
|
| 62 |
+
_WORD_TO_NUM = {
|
| 63 |
+
"zero": 0, "one": 1, "two": 2, "three": 3, "four": 4,
|
| 64 |
+
"five": 5, "six": 6, "seven": 7, "eight": 8, "nine": 9,
|
| 65 |
+
"ten": 10, "eleven": 11, "twelve": 12, "thirteen": 13,
|
| 66 |
+
"fourteen": 14, "fifteen": 15, "sixteen": 16, "seventeen": 17,
|
| 67 |
+
"eighteen": 18, "nineteen": 19, "twenty": 20, "thirty": 30,
|
| 68 |
+
"forty": 40, "fifty": 50, "hundred": 100,
|
| 69 |
+
}
|
| 70 |
+
|
| 71 |
+
|
| 72 |
+
def _words_to_expr(text: str) -> str:
|
| 73 |
+
"""Convert 'three plus five' -> '3+5'."""
|
| 74 |
+
s = text.lower()
|
| 75 |
+
s = s.replace("plus", "+").replace("add", "+").replace("+", " + ")
|
| 76 |
+
s = s.replace("minus", "-").replace("subtract", "-")
|
| 77 |
+
s = s.replace("times", "*").replace("multiplied by", "*").replace("x", "*")
|
| 78 |
+
s = s.replace("divided by", "/").replace("over", "/")
|
| 79 |
+
s = s.replace("equals", "=").replace("is", "")
|
| 80 |
+
tokens: list[str] = []
|
| 81 |
+
for w in re.findall(r"[a-z]+|\d+|[+\-*/()]", s):
|
| 82 |
+
if w in _WORD_TO_NUM:
|
| 83 |
+
tokens.append(str(_WORD_TO_NUM[w]))
|
| 84 |
+
else:
|
| 85 |
+
tokens.append(w)
|
| 86 |
+
return " ".join(tokens)
|
| 87 |
+
|
| 88 |
+
|
| 89 |
+
def _normalize_ocr_math(s: str) -> str:
|
| 90 |
+
s = s.strip()
|
| 91 |
+
s = s.replace("×", "*").replace("x", "*").replace("X", "*")
|
| 92 |
+
s = s.replace("÷", "/").replace("−", "-")
|
| 93 |
+
# Strip trailing "=..." (handles "=?", "= 7", "=42", "= ?")
|
| 94 |
+
s = re.sub(r"=.*$", "", s)
|
| 95 |
+
# Strip OCR garbage that looks like a single trailing digit (often "?" read as 6/2/7)
|
| 96 |
+
# Only strip if it's a single digit at the very end AND not part of an expression
|
| 97 |
+
s_no_space = s.replace(" ", "")
|
| 98 |
+
# If the result still ends with a lone digit that doesn't follow an operator, leave it
|
| 99 |
+
# (e.g. "3+5=2" -> "3+5", but "12+8=?" -> "12+8" since ? is stripped first)
|
| 100 |
+
s = s.replace("?", "")
|
| 101 |
+
s = s.replace(" ", "")
|
| 102 |
+
return s
|
| 103 |
+
|
| 104 |
+
|
| 105 |
+
def _extract_math_expression(s: str) -> Optional[str]:
|
| 106 |
+
s = _normalize_ocr_math(s)
|
| 107 |
+
# Try to find a chain of at least one operator between numbers
|
| 108 |
+
m = re.search(r"(-?\d+(?:\.\d+)?\s*[+\-*/%]\s*-?\d+(?:\.\d+)?(?:\s*[+\-*/%]\s*-?\d+(?:\.\d+)?)*)", s)
|
| 109 |
+
if m:
|
| 110 |
+
return m.group(1)
|
| 111 |
+
return None
|
| 112 |
+
|
| 113 |
+
|
| 114 |
+
class MathSolver(BaseSolver):
|
| 115 |
+
name = "math"
|
| 116 |
+
captcha_type = "math"
|
| 117 |
+
|
| 118 |
+
def attempts(self):
|
| 119 |
+
return [
|
| 120 |
+
self._solve_regex,
|
| 121 |
+
self._solve_tesseract_fallback,
|
| 122 |
+
self._solve_ollama_if_enabled,
|
| 123 |
+
]
|
| 124 |
+
|
| 125 |
+
def _solve_regex(self) -> SolveAttempt:
|
| 126 |
+
"""Pure regex path: try to extract and eval the math string from the raw input.
|
| 127 |
+
|
| 128 |
+
Note: when the input is an image, we need OCR first. We delegate to
|
| 129 |
+
a small helper that uses Florence-2 and a cleanup LLM if needed.
|
| 130 |
+
"""
|
| 131 |
+
raw = self._raw_text
|
| 132 |
+
if not raw:
|
| 133 |
+
return SolveAttempt(answer="", confidence=0.0, solver_name="math.regex", error="no text input")
|
| 134 |
+
|
| 135 |
+
for src in (raw, _words_to_expr(raw)):
|
| 136 |
+
expr = _extract_math_expression(src)
|
| 137 |
+
if not expr:
|
| 138 |
+
continue
|
| 139 |
+
val = _safe_eval(expr)
|
| 140 |
+
if val is None:
|
| 141 |
+
continue
|
| 142 |
+
conf = 0.92 if src is raw else 0.8
|
| 143 |
+
return SolveAttempt(answer=_format_int(val), confidence=conf, solver_name="math.regex")
|
| 144 |
+
return SolveAttempt(answer="", confidence=0.0, solver_name="math.regex", error="no math found")
|
| 145 |
+
|
| 146 |
+
def _solve_tesseract_fallback(self) -> SolveAttempt:
|
| 147 |
+
"""Use Tesseract OCR when Florence-2 isn't available.
|
| 148 |
+
|
| 149 |
+
Useful when HF models can't be downloaded (expired token, offline).
|
| 150 |
+
"""
|
| 151 |
+
if not self._pil_image:
|
| 152 |
+
return SolveAttempt(answer="", confidence=0.0, solver_name="math.tesseract", error="no image")
|
| 153 |
+
try:
|
| 154 |
+
from captcha_solver.utils.tesseract_ocr import ocr_captcha_math
|
| 155 |
+
text = ocr_captcha_math(self._pil_image)
|
| 156 |
+
except Exception as exc:
|
| 157 |
+
return SolveAttempt(answer="", confidence=0.0, solver_name="math.tesseract", error=str(exc))
|
| 158 |
+
if not text:
|
| 159 |
+
return SolveAttempt(answer="", confidence=0.0, solver_name="math.tesseract", error="empty OCR")
|
| 160 |
+
expr = _extract_math_expression(text)
|
| 161 |
+
if not expr:
|
| 162 |
+
return SolveAttempt(answer="", confidence=0.0, solver_name="math.tesseract", error=f"no math in: {text!r}")
|
| 163 |
+
val = _safe_eval(expr)
|
| 164 |
+
if val is None:
|
| 165 |
+
return SolveAttempt(answer="", confidence=0.0, solver_name="math.tesseract", error=f"eval failed: {expr}")
|
| 166 |
+
return SolveAttempt(answer=_format_int(val), confidence=0.6, solver_name="math.tesseract")
|
| 167 |
+
|
| 168 |
+
def _solve_ollama_if_enabled(self) -> SolveAttempt:
|
| 169 |
+
if not self.ctx.ollama.enabled:
|
| 170 |
+
return SolveAttempt(answer="", confidence=0.0, solver_name="math.ollama", error="ollama disabled")
|
| 171 |
+
if not self._raw_text:
|
| 172 |
+
return SolveAttempt(answer="", confidence=0.0, solver_name="math.ollama", error="no text")
|
| 173 |
+
out = self.ctx.ollama.generate_text(
|
| 174 |
+
f"Extract and solve the math expression. Return ONLY the final integer answer.\nExpression: {self._raw_text}",
|
| 175 |
+
system="You solve simple arithmetic. Reply with one integer, nothing else.",
|
| 176 |
+
max_tokens=8,
|
| 177 |
+
)
|
| 178 |
+
m = re.search(r"-?\d+", out)
|
| 179 |
+
if not m:
|
| 180 |
+
return SolveAttempt(answer="", confidence=0.0, solver_name="math.ollama", error="no number in output")
|
| 181 |
+
return SolveAttempt(answer=m.group(0), confidence=0.88, solver_name="math.ollama")
|
| 182 |
+
|
| 183 |
+
def prepare(self, image_b64: Optional[str], audio_b64: Optional[str], hint: Optional[str]) -> None:
|
| 184 |
+
"""OCR the image to text (or accept a pre-OCR'd hint).
|
| 185 |
+
|
| 186 |
+
Stores the result in self._raw_text and keeps the PIL image in
|
| 187 |
+
self._pil_image for the tesseract fallback.
|
| 188 |
+
"""
|
| 189 |
+
self._pil_image = None
|
| 190 |
+
if hint:
|
| 191 |
+
self._raw_text = hint
|
| 192 |
+
return
|
| 193 |
+
if not image_b64:
|
| 194 |
+
self._raw_text = ""
|
| 195 |
+
return
|
| 196 |
+
try:
|
| 197 |
+
data = decode_base64_image(image_b64)
|
| 198 |
+
img = image_to_pil(data)
|
| 199 |
+
self._pil_image = img
|
| 200 |
+
except Exception as exc:
|
| 201 |
+
self._raw_text = ""
|
| 202 |
+
self._last_error = f"decode: {exc}"
|
| 203 |
+
return
|
| 204 |
+
try:
|
| 205 |
+
raw = self.ctx.florence.ocr(img, task="<OCR>")
|
| 206 |
+
self._raw_text = _clean_ocr_text(raw)
|
| 207 |
+
except Exception as exc:
|
| 208 |
+
self._raw_text = ""
|
| 209 |
+
self._last_error = f"florence: {exc}"
|
| 210 |
+
|
| 211 |
+
def __init__(self, ctx) -> None:
|
| 212 |
+
super().__init__(ctx)
|
| 213 |
+
self._raw_text: str = ""
|
| 214 |
+
self._pil_image = None
|
| 215 |
+
self._last_error: str = ""
|
| 216 |
+
|
| 217 |
+
|
| 218 |
+
def _clean_ocr_text(s: str) -> str:
|
| 219 |
+
s = s.strip()
|
| 220 |
+
s = s.replace("\n", " ").replace("\r", " ")
|
| 221 |
+
s = re.sub(r"\s+", " ", s)
|
| 222 |
+
return s
|
| 223 |
+
|
| 224 |
+
|
| 225 |
+
def _format_int(v: float) -> str:
|
| 226 |
+
if abs(v - round(v)) < 1e-9:
|
| 227 |
+
return str(int(round(v)))
|
| 228 |
+
return ("%g" % v)
|