-
Notifications
You must be signed in to change notification settings - Fork 4
Expand file tree
/
Copy pathapp.py
More file actions
198 lines (179 loc) · 7.05 KB
/
app.py
File metadata and controls
198 lines (179 loc) · 7.05 KB
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
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
from flask import Flask
from flask_cors import CORS, cross_origin
from flask import request
from flask import jsonify
import os
os.environ["CUDA_DEVICE_ORDER"] = "PCI_BUS_ID"
os.environ["CUDA_VISIBLE_DEVICES"] = ""
import numpy as np
import matplotlib.pyplot as plt
from pathlib import Path
from collections import Counter
import tensorflow as tf
from tensorflow import keras
from tensorflow.keras import layers
from keras.models import model_from_json
import base64
import time
# Khởi tạo Flask Server Backend
app = Flask(__name__)
# Apply Flask CORS
CORS(app)
app.config['CORS_HEADERS'] = 'Content-Type'
class mbbank():
img_width = 320
img_height = 80
max_length = 6
characters_mbbank = ['2', '3', '4', '5', '6', '7', '8', '9', 'A', 'B', 'C', 'D', 'E', 'G', 'H', 'K', 'M', 'N', 'P', 'Q', 'U', 'V', 'Y', 'Z', 'a', 'b', 'c', 'd', 'e', 'g', 'h', 'k', 'm', 'n', 'p', 'q', 't', 'u', 'v', 'y', 'z']
# Mapping characters to integers
char_to_num = layers.StringLookup(
vocabulary=list(characters_mbbank), mask_token=None
)
class bidv():
img_width = 145
img_height = 50
max_length = 6
characters_mbbank = ['2', '3', '4', '5', '6', '7', '8', '9', 'V', 'a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'j', 'k', 'm', 'n', 'p', 'q', 'r', 's', 't', 'u', 'v', 'x', 'y', 'z']
# Mapping characters to integers
char_to_num = layers.StringLookup(
vocabulary=list(characters_mbbank), mask_token=None
)
# Mapping integers back to original characters
num_to_char = layers.StringLookup(
vocabulary=char_to_num.get_vocabulary(), mask_token=None, invert=True
)
class eximbank():
img_width = 145
img_height = 50
max_length = 6
characters_mbbank = ['2', '3', '4', '5', '6', '7', '8', '9', 'V', 'a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'j', 'k', 'm', 'n', 'p', 'q', 'r', 's', 't', 'u', 'v', 'x', 'y', 'z']
# Mapping characters to integers
char_to_num = layers.StringLookup(
vocabulary=list(characters_mbbank), mask_token=None
)
# Mapping integers back to original characters
num_to_char = layers.StringLookup(
vocabulary=char_to_num.get_vocabulary(), mask_token=None, invert=True
)
class vietcombank():
img_width = 155
img_height = 50
max_length = 6
characters_mbbank = ['1', '2', '3', '4', '5', '6', '7', '8', '9']
# Mapping characters to integers
char_to_num = layers.StringLookup(
vocabulary=list(characters_mbbank), mask_token=None
)
# Mapping integers back to original characters
num_to_char = layers.StringLookup(
vocabulary=char_to_num.get_vocabulary(), mask_token=None, invert=True
)
def LoadModel(file):
# JSON format
xfile = os.path.splitext(file)
if (xfile[1] == ".json"):
with open(file, "r") as json:
json_model = json.read()
model = keras.models.model_from_json(json_model)
model.load_weights(xfile[0] + ".wgt")
# ONNX format
elif (xfile[1] == ".onnx"):
raise Exception("LoadModel; ONNX format not supported yet")
model = None
# TF/Keras format
else:
model = keras.models.load_model(file, custom_objects={'leaky_relu': tf.nn.leaky_relu})
return model
model_mbbank = LoadModel("mbbank/mbbank.json")
model_bidv = LoadModel("bidv/bidv.json")
model_eximbank = LoadModel("eximbank/eximbank.json")
model_vietcombank = LoadModel("vietcombank/vietcombank.json")
# A utility function to decode the output of the network
def decode_batch_predictions(pred,bank="mbbank"):
if bank == "mbbank":
bank_class = mbbank
if bank == "bidv":
bank_class = bidv
if bank == "vietcombank":
bank_class = vietcombank
input_len = np.ones(pred.shape[0]) * pred.shape[1]
# Use greedy search. For complex tasks, you can use beam search
results = keras.backend.ctc_decode(pred, input_length=input_len, greedy=True)[0][0][
:, :bank_class.max_length
]
# Iterate over the results and get back the text
output_text = []
for res in results:
res = tf.strings.reduce_join(bank_class.num_to_char(res)).numpy().decode("utf-8")
output_text.append(res)
return output_text
def encode_base64x(base64,bank="mbbank"):
if bank == "mbbank":
bank_class = mbbank
if bank == "bidv":
bank_class = bidv
if bank == "eximbank":
bank_class = eximbank
if bank == "vietcombank":
bank_class = vietcombank
img = tf.io.decode_base64(base64)
img = tf.io.decode_png(img, channels=1)
img = tf.image.convert_image_dtype(img, tf.float32)
img = tf.image.resize(img, [bank_class.img_height, bank_class.img_width])
img = tf.transpose(img, perm=[1, 0, 2])
return {"image": img}
@app.route("/api/captcha/mbbank", methods=["POST"])
@cross_origin(origin='*')
def mbbank_captcha_solver():
content = request.json
start_time = time.time()
imgstring = content['base64']
image_encode = encode_base64x(imgstring.replace("+", "-").replace("/", "_"),"mbbank")["image"]
listImage = np.array([image_encode])
preds = model_mbbank.predict(listImage)
pred_texts = decode_batch_predictions(preds,"mbbank")
captcha = pred_texts[0].replace('[UNK]', '').replace('-', '')
response = jsonify(status = "success",captcha = captcha)
return response
@app.route("/api/captcha/bidv", methods=["POST"])
@cross_origin(origin='*')
def bidv_captcha_solver():
content = request.json
start_time = time.time()
imgstring = content['base64']
image_encode = encode_base64x(imgstring.replace("+", "-").replace("/", "_"),"bidv")["image"]
listImage = np.array([image_encode])
preds = model_bidv.predict(listImage)
pred_texts = decode_batch_predictions(preds,"bidv")
captcha = pred_texts[0].replace('[UNK]', '').replace('-', '')
response = jsonify(status = "success",captcha = captcha)
return response
@app.route("/api/captcha/eximbank", methods=["POST"])
@cross_origin(origin='*')
def eximbank_captcha_solver():
content = request.json
start_time = time.time()
imgstring = content['base64']
image_encode = encode_base64x(imgstring.replace("+", "-").replace("/", "_"),"eximbank")["image"]
listImage = np.array([image_encode])
preds = model_eximbank.predict(listImage)
pred_texts = decode_batch_predictions(preds,"eximbank")
captcha = pred_texts[0].replace('[UNK]', '').replace('-', '')
response = jsonify(status = "success",captcha = captcha)
return response
@app.route("/api/captcha/vietcombank", methods=["POST"])
@cross_origin(origin='*')
def vietcombank_captcha_solver():
content = request.json
start_time = time.time()
imgstring = content['base64']
image_encode = encode_base64x(imgstring.replace("+", "-").replace("/", "_"),"vietcombank")["image"]
listImage = np.array([image_encode])
preds = model_vietcombank.predict(listImage)
pred_texts = decode_batch_predictions(preds,"vietcombank")
captcha = pred_texts[0].replace('[UNK]', '').replace('-', '')
response = jsonify(status = "success",captcha = captcha)
return response
# Chạy server
if __name__ == '__main__':
app.run(host='0.0.0.0', port='8277')