File size: 2,194 Bytes
f07b0a9
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
import tensorflow as tf
from tensorflow import keras
from tensorflow.keras import layers

from huggingface_hub import from_pretrained_keras

import numpy as np
import gradio as gr

max_length = 5
img_width = 200
img_height = 50

model = from_pretrained_keras("keras-io/ocr-for-captcha", compile=False)

prediction_model = keras.models.Model(
    model.get_layer(name="image").input, model.get_layer(name="dense2").output
)

with open("vocab.txt", "r") as f:
    vocab = f.read().splitlines()

# ánh xạ các số nguyên trở lại thành các ký tự gốc
num_to_char = layers.StringLookup(
    vocabulary=vocab, mask_token=None, invert=True
)

def decode_batch_predictions(pred):
    input_len = np.ones(pred.shape[0]) * pred.shape[1]
    # Sử dụng thuật toán Greedy Search
    results = keras.backend.ctc_decode(pred, input_length=input_len, greedy=True)[0][0][
        :, :max_length
    ]
    # lặp qua các kết quả và nhận lại text
    output_text = []
    for res in results:
        res = tf.strings.reduce_join(num_to_char(res)).numpy().decode("utf-8")
        output_text.append(res)
    return output_text

def classify_image(img_path):
    # đọc ảnh
    img = tf.io.read_file(img_path)
    # giải mã và chuyển đổi ảnh thành ảnh xám
    img = tf.io.decode_png(img, channels=1)
    # chuyển đổi ảnh sang định dạng float32 trong khoảng [0, 1]
    img = tf.image.convert_image_dtype(img, tf.float32)
    # thay đổi kích thước của ảnh thành kích thước mong muốn
    img = tf.image.resize(img, [img_height, img_width])
    # chuyển vị ảnh sao cho chiều thời gian tương ứng với chiều rộng của ảnh
    img = tf.transpose(img, perm=[1, 0, 2])
    img = tf.expand_dims(img, axis=0)
    preds = prediction_model.predict(img)
    pred_text = decode_batch_predictions(preds)
    return pred_text[0]
  
image = gr.inputs.Image(type='filepath')
text = gr.outputs.Textbox()

iface = gr.Interface(classify_image,image,text,
  title="Giải Captcha",
	description = "mô hình OCR sử dụng Keras để đọc Captcha 🤖🦹🏻",
        examples = ["dd764.png","3p4nn.png"]
)


iface.launch()