Update captcha_solver_hf.py

#1
Files changed (1) hide show
  1. captcha_solver_hf.py +15 -9
captcha_solver_hf.py CHANGED
@@ -32,6 +32,7 @@ def solve_captcha(image):
32
  for contour in contours:
33
  (x, y, w, h) = cv2.boundingRect(contour)
34
  if w / h > 1.25:
 
35
  half_width = int(w / 2)
36
  letter_image_regions.append((x, y, half_width, h))
37
  letter_image_regions.append((x + half_width, y, half_width, h))
@@ -41,22 +42,27 @@ def solve_captcha(image):
41
  if len(letter_image_regions) != 4:
42
  return "Error: Could not identify 4 letters in the CAPTCHA"
43
 
 
44
  letter_image_regions = sorted(letter_image_regions, key=lambda x: x[0])
45
 
46
- predictions = []
47
-
48
  for letter_bounding_box in letter_image_regions:
49
  x, y, w, h = letter_bounding_box
50
  letter_image = image[y - 2:y + h + 2, x - 2:x + w + 2]
51
  letter_image = resize_to_fit(letter_image, 20, 20)
52
  letter_image = np.expand_dims(letter_image, axis=2)
53
- letter_image = np.expand_dims(letter_image, axis=0)
54
-
55
- prediction = model.predict(letter_image)
56
- letter = lb.inverse_transform(prediction)[0]
57
- predictions.append(letter)
 
 
 
 
 
 
58
 
59
- captcha_text = "".join(predictions)
60
  return captcha_text
61
-
62
  # We don't need a test function here anymore, as testing will be done through the Gradio interface
 
32
  for contour in contours:
33
  (x, y, w, h) = cv2.boundingRect(contour)
34
  if w / h > 1.25:
35
+ # This contour is too wide, split it in half
36
  half_width = int(w / 2)
37
  letter_image_regions.append((x, y, half_width, h))
38
  letter_image_regions.append((x + half_width, y, half_width, h))
 
42
  if len(letter_image_regions) != 4:
43
  return "Error: Could not identify 4 letters in the CAPTCHA"
44
 
45
+ # Sort the detected letter images based on x coordinate
46
  letter_image_regions = sorted(letter_image_regions, key=lambda x: x[0])
47
 
48
+ # ---------- SPEED IMPROVEMENT STARTS HERE ----------
49
+ letter_images = []
50
  for letter_bounding_box in letter_image_regions:
51
  x, y, w, h = letter_bounding_box
52
  letter_image = image[y - 2:y + h + 2, x - 2:x + w + 2]
53
  letter_image = resize_to_fit(letter_image, 20, 20)
54
  letter_image = np.expand_dims(letter_image, axis=2)
55
+ letter_images.append(letter_image)
56
+
57
+ # Stack all 4 letters into one batch → only ONE model call
58
+ batch = np.array(letter_images) # shape: (4, 20, 20, 1)
59
+
60
+ # Much faster than calling predict 4 times
61
+ predictions = model.predict(batch, verbose=0)
62
+
63
+ # Convert predictions to letters
64
+ captcha_text = "".join(lb.inverse_transform(predictions))
65
+ # ---------- SPEED IMPROVEMENT ENDS HERE ----------
66
 
 
67
  return captcha_text
 
68
  # We don't need a test function here anymore, as testing will be done through the Gradio interface