golyew commited on
Commit
7528682
·
verified ·
1 Parent(s): 4e2534d

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +16 -43
app.py CHANGED
@@ -6,31 +6,19 @@ from tokenizer_base import Tokenizer
6
  import gradio as gr
7
 
8
  # Параметры модели
9
- model_file = "captcha.onnx"
10
- img_size = (32, 128)
11
- charset = r"0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ!\"#$%&'()*+,-./:;<=>?@[\\]^_`{|}~"
12
- tokenizer_base = Tokenizer(charset)
13
 
14
  # Надёжный препроцессинг
15
  def preprocess_image(img, img_size):
16
- # Приводим к RGB (убираем альфу/градации серого)
17
  img = img.convert("RGB")
18
-
19
- # Resize bicubic
20
  img = img.resize(img_size, Image.BICUBIC)
21
-
22
- # В numpy (HWC → float32)
23
  img = np.array(img).astype(np.float32) / 255.0
24
-
25
- # HWC → CHW
26
- img = np.transpose(img, (2, 0, 1))
27
-
28
- # Нормализация (x-mean)/std
29
  img = (img - 0.5) / 0.5
30
-
31
- # Добавляем batch размерность
32
- img = np.expand_dims(img, axis=0)
33
-
34
  return img
35
 
36
  # softmax на numpy
@@ -38,42 +26,27 @@ def softmax(x, axis=-1):
38
  e_x = np.exp(x - np.max(x, axis=axis, keepdims=True))
39
  return e_x / e_x.sum(axis=axis, keepdims=True)
40
 
41
- # Инициализация модели ONNX
42
  def initialize_model(model_file):
43
  onnx_model = onnx.load(model_file)
44
  onnx.checker.check_model(onnx_model)
45
  ort_session = rt.InferenceSession(model_file)
46
  return ort_session
47
 
48
- # Функция для распознавания текста
49
  def get_text(img_org):
50
- x = preprocess_image(img_org, img_size)
51
-
52
- # Предсказание с помощью ONNX
53
  ort_inputs = {ort_session.get_inputs()[0].name: x}
54
  logits = ort_session.run(None, ort_inputs)[0]
55
-
56
  probs = softmax(logits, axis=-1)
57
- preds, probs = tokenizer_base.decode(probs)
58
  return preds[0]
59
 
60
- # Инициализация модели
61
- ort_session = initialize_model(model_file=model_file)
62
 
63
  # Gradio интерфейс
64
- def gradio_interface():
65
- return gr.Interface(
66
- fn=get_text,
67
- inputs=gr.Image(type="pil"),
68
- outputs=gr.Textbox(),
69
- title="Text Captcha Reader",
70
- description="Распознавание текста на изображениях капчи.",
71
- examples=[
72
- "8000.png", "11JW29.png", "2a8486.jpg", "2nbcx.png",
73
- "000679.png", "000HU.png", "00Uga.png.jpg", "00bAQwhAZU.jpg",
74
- "00h57kYf.jpg", "0EoHdtVb.png", "0JS21.png", "0p98z.png", "10010.png"
75
- ]
76
- )
77
-
78
- # Запуск интерфейса
79
- gradio_interface().launch()
 
6
  import gradio as gr
7
 
8
  # Параметры модели
9
+ MODEL_FILE = "captcha.onnx"
10
+ IMG_SIZE = (32, 128)
11
+ CHARSET = r"0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ!\"#$%&'()*+,-./:;<=>?@[\\]^_`{|}~"
12
+ tokenizer_base = Tokenizer(CHARSET)
13
 
14
  # Надёжный препроцессинг
15
  def preprocess_image(img, img_size):
 
16
  img = img.convert("RGB")
 
 
17
  img = img.resize(img_size, Image.BICUBIC)
 
 
18
  img = np.array(img).astype(np.float32) / 255.0
19
+ img = np.transpose(img, (2, 0, 1)) # HWC → CHW
 
 
 
 
20
  img = (img - 0.5) / 0.5
21
+ img = np.expand_dims(img, axis=0) # batch dim
 
 
 
22
  return img
23
 
24
  # softmax на numpy
 
26
  e_x = np.exp(x - np.max(x, axis=axis, keepdims=True))
27
  return e_x / e_x.sum(axis=axis, keepdims=True)
28
 
29
+ # Инициализация модели
30
  def initialize_model(model_file):
31
  onnx_model = onnx.load(model_file)
32
  onnx.checker.check_model(onnx_model)
33
  ort_session = rt.InferenceSession(model_file)
34
  return ort_session
35
 
36
+ # Распознавание текста
37
  def get_text(img_org):
38
+ x = preprocess_image(img_org, IMG_SIZE)
 
 
39
  ort_inputs = {ort_session.get_inputs()[0].name: x}
40
  logits = ort_session.run(None, ort_inputs)[0]
 
41
  probs = softmax(logits, axis=-1)
42
+ preds, _ = tokenizer_base.decode(probs)
43
  return preds[0]
44
 
45
+ # Загружаем модель один раз
46
+ ort_session = initialize_model(MODEL_FILE)
47
 
48
  # Gradio интерфейс
49
+ demo = gr.Interface(
50
+ fn=get_text,
51
+ inputs=gr.Image(type="pil"),
52
+ outputs=gr.T