Asib27 commited on
Commit
c2bf863
1 Parent(s): 65d81f0

add model code

Browse files
Files changed (1) hide show
  1. app.py +74 -0
app.py CHANGED
@@ -1,4 +1,78 @@
1
  import gradio as gr
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
2
 
3
  def greet(name):
4
  return "Hello " + name + "!!"
 
1
  import gradio as gr
2
+ import numpy as np
3
+ import cv2
4
+ import tensorflow as tf
5
+ import keras
6
+ from keras import layers, models
7
+
8
+ model = model = tf.keras.models.load_model('model/ocr_model.h5')
9
+
10
+ def preprocessImage(img, shape):
11
+ img = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)
12
+ img = cv2.resize(img, (shape))
13
+ img = (img/255).astype(np.float32)
14
+ img = img.T
15
+ img = np.expand_dims(img, axis=-1)
16
+ return img
17
+
18
+ label2char ={0: ' ',
19
+ 1: "'",
20
+ 2: '-',
21
+ 3: 'A',
22
+ 4: 'B',
23
+ 5: 'C',
24
+ 6: 'D',
25
+ 7: 'E',
26
+ 8: 'F',
27
+ 9: 'G',
28
+ 10: 'H',
29
+ 11: 'I',
30
+ 12: 'J',
31
+ 13: 'K',
32
+ 14: 'L',
33
+ 15: 'M',
34
+ 16: 'N',
35
+ 17: 'O',
36
+ 18: 'P',
37
+ 19: 'Q',
38
+ 20: 'R',
39
+ 21: 'S',
40
+ 22: 'T',
41
+ 23: 'U',
42
+ 24: 'V',
43
+ 25: 'W',
44
+ 26: 'X',
45
+ 27: 'Y',
46
+ 28: 'Z',
47
+ 29: '`'}
48
+
49
+ def getStringFromEncode(lst :list):
50
+ return ''.join([label2char[i] if i in label2char else '' for i in lst])
51
+
52
+ def decode_batch_predictions(pred):
53
+ pred = pred[:, :-2] # first two layers of ctc garbage
54
+ input_len = np.ones(pred.shape[0])*pred.shape[1]
55
+
56
+ results = keras.backend.ctc_decode(pred,
57
+ input_length=input_len,
58
+ greedy=True)[0][0]
59
+
60
+ output_text = []
61
+ for res in results.numpy():
62
+ outstr = getStringFromEncode(res)
63
+ output_text.append(outstr)
64
+
65
+ # return final text results
66
+ return output_text
67
+
68
+ def predict(img):
69
+ img = preprocessImage(img, (256,64))
70
+ img = np.expand_dims(img, axis=0) # 1 image in batch
71
+
72
+ preds = model.predict(img)
73
+ pred_texts = decode_batch_predictions(preds)
74
+ return pred_texts[0]
75
+
76
 
77
  def greet(name):
78
  return "Hello " + name + "!!"