Phu92kt commited on
Commit
52ea25e
·
verified ·
1 Parent(s): 5117e83

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +88 -26
app.py CHANGED
@@ -1,28 +1,90 @@
1
- import gradio as gr
2
- import numpy as np
3
- import onnxruntime
 
 
4
  from PIL import Image
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
5
 
6
- session = onnxruntime.InferenceSession("captcha.onnx", providers=["CPUExecutionProvider"])
7
- alphabet = "ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789"
8
-
9
- def decode_output(logits):
10
- num_classes = 36
11
- seq_len = len(logits) // num_classes
12
- result = ""
13
- for i in range(seq_len):
14
- chunk = logits[i * num_classes : (i + 1) * num_classes]
15
- idx = int(np.argmax(chunk))
16
- result += alphabet[idx]
17
- return result
18
-
19
- def predict(image):
20
- image = image.resize((160, 60)).convert("RGB")
21
- arr = np.array(image).transpose(2, 0, 1) / 255.0
22
- arr = arr[np.newaxis, :]
23
- inputs = {session.get_inputs()[0].name: arr.astype(np.float32)}
24
- output = session.run(None, inputs)[0].flatten()
25
- return decode_output(output)
26
-
27
- iface = gr.Interface(fn=predict, inputs=gr.Image(type="pil"), outputs="text")
28
- iface.launch(enable_queue=True) # <-- Đảm bảo dòng này tồn tại
 
1
+ import torch
2
+ import onnx
3
+ import onnxruntime as rt
4
+ from torchvision import transforms as T
5
+ from pathlib import Path
6
  from PIL import Image
7
+ from huggingface_hub import hf_hub_download
8
+
9
+ import os
10
+ import gradio as gr
11
+
12
+ from utils.tokenizer_base import Tokenizer
13
+
14
+
15
+ # Download the model from Hugging Face Hub
16
+ cwd = Path(__file__).parent.resolve()
17
+ model_file = os.path.join(cwd, hf_hub_download("toandev/OCR-for-Captcha", "model.onnx"))
18
+
19
+ # Define the image size and vocabulary
20
+ img_size = (32, 128)
21
+ vocab = r"0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ!\"#$%&'()*+,-./:;<=>?@[\\]^_`{|}~"
22
+
23
+ # Initialize the tokenizer
24
+ tokenizer = Tokenizer(vocab)
25
+
26
+
27
+ def to_numpy(tensor):
28
+ """Convert tensor to numpy."""
29
+ return (
30
+ tensor.detach().cpu().numpy() if tensor.requires_grad else tensor.cpu().numpy()
31
+ )
32
+
33
+
34
+ def get_transform(img_size):
35
+ """Preprocess the input image."""
36
+ transforms = []
37
+ transforms.extend(
38
+ [
39
+ T.Resize(img_size, T.InterpolationMode.BICUBIC),
40
+ T.ToTensor(),
41
+ T.Normalize(0.5, 0.5),
42
+ ]
43
+ )
44
+ return T.Compose(transforms)
45
+
46
+
47
+ def load_model(model_file):
48
+ """Load the model and return the transform function."""
49
+ transform = get_transform(img_size)
50
+
51
+ onnx_model = onnx.load(model_file)
52
+ onnx.checker.check_model(onnx_model)
53
+
54
+ s = rt.InferenceSession(model_file)
55
+ return transform, s
56
+
57
+
58
+ # Load the model
59
+ transform, s = load_model(model_file=model_file)
60
+
61
+
62
+ def process(img: Image.Image):
63
+ """Predict the text from the input image."""
64
+ x = transform(img.convert("RGB")).unsqueeze(0)
65
+
66
+ ort_inputs = {s.get_inputs()[0].name: to_numpy(x)}
67
+ logits = s.run(None, ort_inputs)[0]
68
+ probs = torch.tensor(logits).softmax(-1)
69
+ preds, probs = tokenizer.decode(probs)
70
+
71
+ return preds[0]
72
+
73
+
74
+ iface = gr.Interface(
75
+ process,
76
+ gr.Image(type="pil", label="Input Image"),
77
+ gr.Textbox(label="Predicted Text"),
78
+ title="OCR for CAPTCHA",
79
+ description="Solve captchas from images including letters and numbers, success rate is about 80-90%.",
80
+ examples=[
81
+ "examples/1.png",
82
+ "examples/2.jpg",
83
+ "examples/3.jpg",
84
+ "examples/4.png",
85
+ "examples/5.png",
86
+ ],
87
+ )
88
 
89
+ if __name__ == "__main__":
90
+ iface.launch()