Commit ·
f2d21db
1
Parent(s): 8d8ccdb
feat: add utility file
Browse files
README.md
CHANGED
|
@@ -9,6 +9,6 @@ app_file: app.py
|
|
| 9 |
pinned: false
|
| 10 |
license: apache-2.0
|
| 11 |
short_description: Character captcha recognition using a CNN Transformer.
|
| 12 |
-
|
| 13 |
-
|
| 14 |
-
|
|
|
|
| 9 |
pinned: false
|
| 10 |
license: apache-2.0
|
| 11 |
short_description: Character captcha recognition using a CNN Transformer.
|
| 12 |
+
models:
|
| 13 |
+
- krishnatherokar/captcha-recognition
|
| 14 |
+
---
|
utils.py
ADDED
|
@@ -0,0 +1,38 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import numpy as np
|
| 2 |
+
import keras
|
| 3 |
+
from keras.ops import ctc_decode
|
| 4 |
+
|
| 5 |
+
HEIGHT = 50
|
| 6 |
+
WIDTH = 200
|
| 7 |
+
|
| 8 |
+
characters = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789"
|
| 9 |
+
num_classes = len(characters)
|
| 10 |
+
char_to_num = {char: i for i, char in enumerate(characters)}
|
| 11 |
+
num_to_char = {i: char for i, char in enumerate(characters)}
|
| 12 |
+
|
| 13 |
+
def process_images(img):
|
| 14 |
+
img = img.convert("L")
|
| 15 |
+
img = img.resize((WIDTH, HEIGHT))
|
| 16 |
+
img = np.array(img) / 255.0
|
| 17 |
+
return img
|
| 18 |
+
|
| 19 |
+
base_model = keras.saving.load_model("hf://krishnatherokar/captcha-recognition")
|
| 20 |
+
|
| 21 |
+
def predict_and_decode(img):
|
| 22 |
+
# preprocess
|
| 23 |
+
processed_image = process_images(img)
|
| 24 |
+
test_input = np.expand_dims([processed_image], axis=-1)
|
| 25 |
+
|
| 26 |
+
# predict
|
| 27 |
+
preds = base_model.predict(test_input)
|
| 28 |
+
|
| 29 |
+
input_len = np.ones(preds.shape[0]) * preds.shape[1]
|
| 30 |
+
decode = ctc_decode(
|
| 31 |
+
preds,
|
| 32 |
+
sequence_lengths=input_len,
|
| 33 |
+
strategy='greedy'
|
| 34 |
+
)[0][0]
|
| 35 |
+
|
| 36 |
+
for result in decode:
|
| 37 |
+
text = "".join([num_to_char[int(x)] for x in result if x >= 0 and x < num_classes])
|
| 38 |
+
return text
|