ballagb19 commited on
Commit
59da50d
·
verified ·
1 Parent(s): e969fbd

Upload captcha_solver/utils/detector.py with huggingface_hub

Browse files
Files changed (1) hide show
  1. captcha_solver/utils/detector.py +72 -0
captcha_solver/utils/detector.py ADDED
@@ -0,0 +1,72 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Heuristic captcha type detector.
2
+
3
+ This is intentionally simple: it looks at image dimensions, presence of
4
+ many equal-sized tiles, color distribution, etc. For audio it returns
5
+ "audio" if audio was provided. For images it picks the most likely
6
+ captcha type. The user-provided `type` field always wins.
7
+ """
8
+
9
+ from __future__ import annotations
10
+
11
+ from typing import Optional
12
+
13
+ import numpy as np
14
+ from PIL import Image
15
+
16
+ from captcha_solver.utils.image import decode_base64_image, image_to_pil
17
+
18
+
19
+ def detect_type(image_b64: Optional[str], audio_b64: Optional[str]) -> str:
20
+ """Best-guess captcha type from inputs. Returns one of:
21
+ 'math', 'text_ocr', 'image_grid', 'audio'.
22
+
23
+ 'math' is the default for any non-grid text-like image. When in doubt
24
+ we still pick a solver rather than return None.
25
+ """
26
+ if audio_b64:
27
+ return "audio"
28
+ if not image_b64:
29
+ return "math"
30
+
31
+ try:
32
+ data = decode_base64_image(image_b64)
33
+ img = image_to_pil(data)
34
+ except Exception:
35
+ return "math"
36
+
37
+ w, h = img.size
38
+ aspect = w / max(h, 1)
39
+ arr = np.asarray(img.convert("L"))
40
+ h_std = float(arr.std())
41
+ edges = _edge_density(arr)
42
+
43
+ if 0.7 <= aspect <= 1.4 and h_std < 60 and edges < 0.08 and w < 400 and h < 200:
44
+ return "math"
45
+ if 0.4 <= aspect <= 0.7 and edges > 0.12 and _has_tile_grid(arr):
46
+ return "image_grid"
47
+ if h_std > 40 and (w >= 200 or h >= 60):
48
+ return "text_ocr"
49
+ return "math"
50
+
51
+
52
+ def _edge_density(arr: np.ndarray) -> float:
53
+ """Fraction of pixels that are 'edges' (Sobel-lite)."""
54
+ gx = np.abs(np.diff(arr.astype(np.int16), axis=1))
55
+ gy = np.abs(np.diff(arr.astype(np.int16), axis=0))
56
+ e = (gx[:-1, :] > 30).sum() + (gy[:, :-1] > 30).sum()
57
+ return e / max(arr.size, 1)
58
+
59
+
60
+ def _has_tile_grid(arr: np.ndarray) -> bool:
61
+ """Check for a 3x3 grid pattern (9 tiles) by looking for vertical/horizontal dark seams."""
62
+ h, w = arr.shape
63
+ if h < 90 or w < 90:
64
+ return False
65
+ rows = [h // 3, 2 * h // 3]
66
+ cols = [w // 3, 2 * w // 3]
67
+ seam_strengths = []
68
+ for r in rows:
69
+ seam_strengths.append(arr[r - 2 : r + 3, :].mean())
70
+ for c in cols:
71
+ seam_strengths.append(arr[:, c - 2 : c + 3].mean())
72
+ return min(seam_strengths) < 100