murtazadahmardeh commited on
Commit
9f091f5
1 Parent(s): 4cdf723
Files changed (1) hide show
  1. app.py +70 -0
app.py ADDED
@@ -0,0 +1,70 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import torch
2
+ import onnx
3
+ import onnxruntime as rt
4
+ from torchvision import transforms as T
5
+ from PIL import Image
6
+ from tokenizer_base import Tokenizer
7
+ import pathlib
8
+ import os
9
+ import gradio as gr
10
+ from huggingface_hub import Repository
11
+
12
+ repo = Repository(
13
+ local_dir="secret_models",
14
+ repo_type="model",
15
+ clone_from="docparser/captcha",
16
+ token=True
17
+ )
18
+ repo.git_pull()
19
+
20
+ cwd = pathlib.Path(__file__).parent.resolve()
21
+ model_file = os.path.join(cwd,"secret_models","captcha.onnx")
22
+ img_size = (32,128)
23
+ charset = r"0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ!\"#$%&'()*+,-./:;<=>?@[\\]^_`{|}~"
24
+ tokenizer_base = Tokenizer(charset)
25
+
26
+ def get_transform(img_size):
27
+ transforms = []
28
+ transforms.extend([
29
+ T.Resize(img_size, T.InterpolationMode.BICUBIC),
30
+ T.ToTensor(),
31
+ T.Normalize(0.5, 0.5)
32
+ ])
33
+ return T.Compose(transforms)
34
+
35
+ def to_numpy(tensor):
36
+ return tensor.detach().cpu().numpy() if tensor.requires_grad else tensor.cpu().numpy()
37
+
38
+ def initialize_model(model_file):
39
+ transform = get_transform(img_size)
40
+ # Onnx model loading
41
+ onnx_model = onnx.load(model_file)
42
+ onnx.checker.check_model(onnx_model)
43
+ ort_session = rt.InferenceSession(model_file)
44
+ return transform,ort_session
45
+
46
+ def get_text(img_org):
47
+ # img_org = Image.open(image_path)
48
+ # Preprocess. Model expects a batch of images with shape: (B, C, H, W)
49
+ x = transform(img_org.convert('RGB')).unsqueeze(0)
50
+
51
+ # compute ONNX Runtime output prediction
52
+ ort_inputs = {ort_session.get_inputs()[0].name: to_numpy(x)}
53
+ logits = ort_session.run(None, ort_inputs)[0]
54
+ probs = torch.tensor(logits).softmax(-1)
55
+ preds, probs = tokenizer_base.decode(probs)
56
+ preds = preds[0]
57
+ print(preds)
58
+ return preds
59
+
60
+ transform,ort_session = initialize_model(model_file=model_file)
61
+
62
+ gr.Interface(
63
+ get_text,
64
+ inputs=gr.Image(type="pil"),
65
+ outputs=gr.outputs.Textbox(),
66
+ title="Text Captcha Reader",
67
+ examples=["8000.png","11JW29.png","2a8486.jpg","2nbcx.png",
68
+ "000679.png","000HU.png","00Uga.png.jpg","00bAQwhAZU.jpg",
69
+ "00h57kYf.jpg","0EoHdtVb.png","0JS21.png","0p98z.png","10010.png"]
70
+ ).launch()