· 5 years ago · Nov 02, 2020, 02:02 PM
1from flask import Flask, request, jsonify
2from flask_restful import Resource, Api
3from werkzeug.exceptions import BadRequest
4from keras.preprocessing.image import image
5import numpy as np
6from PIL import Image
7import base64, io, os, binascii, cv2, pycountry, pickle, csv
8from sklearn.preprocessing import MultiLabelBinarizer
9from myconstants1 import path_logs # , path_resources
10from logConfig1 import setup_logger
11
12logger = setup_logger('recDoc1', path_logs + 'recDoc1.log')
13
14app = Flask(__name__)
15api = Api(app)
16
17
18# THIS IS WHAT I ADDED
19def handle_confidence_level(confLv, confLv1):
20 if confLv > 60:
21 logger.debug({
22 "Status": "valid",
23 "Confidence Level (of requested document type)": confLv1
24 })
25
26 return {
27 "Status": "valid",
28 "Confidence Level (of requested document type)": confLv1
29 }
30
31 elif confLv < 20:
32 logger.debug({
33 "Status": "invalid",
34 "Confidence Level (of requested document type)": confLv1
35 })
36 print("invalid")
37
38 return {
39 "Status": "invalid",
40 "Confidence Level (of requested document type)": confLv1
41 }
42
43 elif 60 >= confLv >= 20:
44 print("Review")
45 logger.debug({
46 "Status": "Review",
47 "Confidence Level (of requested document type)": confLv1
48 })
49 return {
50 "Status": "Review",
51 "Confidence Level (of requested document type)": confLv1
52 }
53
54 else:
55 logger.debug({"status": "Invalid"})
56 return {"status:" "Invalid"}
57#
58
59
60class HandleRequest2(Resource):
61 confidence_level = ""
62 global state_name # you can use global at the point where you actually use the value, no need to define it here
63
64 def post(self):
65 path = os.getcwd()
66 print(path)
67 self.data = request.get_json()
68
69 json = {
70 "Status": "FAILED",
71 "message": "ALL fields are mandatory"
72 }
73 try:
74 self.data = request.get_json()
75 except BadRequest:
76
77 return jsonify(json)
78
79 country = self.data["country_code"]
80
81 if country == "":
82 return json
83
84 try:
85 image_data = base64.b64decode(self.data["image"])
86 except binascii.Error:
87 jsonify1 = {"Status": "failed", "message": "invalid base64 string"}
88 print("invalid base64 string")
89
90 logger.debug(str(jsonify1))
91
92 return jsonify1
93
94 country = self.data["country_code"].lower()
95
96 country = country
97
98 DocumentType = (self.data["DocumentType"]).replace(" ", "_").lower()
99 state_code = self.data["state_code"].upper()
100
101 try:
102 country = pycountry.countries.get(alpha_3=self.data['country_code'].upper()).name.lower()
103 print("country1 : ", country)
104 logger.debug(f"country1 : {country}")
105 country = country.split()
106 country = ("_".join(country))
107 print("country: ", country)
108 logger.debug(f"country: {country}")
109 except AttributeError:
110
111 jsonify1 = {
112 "Status": "failed",
113 "message": "invalid country_code"
114 }
115 print("invalid country_code")
116 logger.debug(f"{jsonify1}")
117 return jsonify1
118
119 alpha_2 = pycountry.countries.get(alpha_3=self.data["country_code"].upper()).alpha_2
120 print("alpha_2", alpha_2)
121
122 if DocumentType not in ["passport", "driving_licence"]:
123 logger.debug({
124 "Status": "failed",
125 "message": "invalid DocumentType"
126 })
127 return {
128 "Status": "failed",
129 "message": "invalid DocumentType"
130 }
131 else:
132 print("documenttype: ", DocumentType)
133
134 with open(rf'{path}/{country}\labels.csv') as f:
135 labels = dict(filter(None, csv.reader(f)))
136 print("labels:", labels)
137
138 if DocumentType == "passport":
139 print(rf'{country}_passport')
140 if (f"{country}_passport") in labels:
141 # path = os.path.exists(rf"{path_resources}"+"//{country}//training//{country}_{DocumentType}")
142 print(rf"{country}_passport available")
143 prediction = (f"{country}_{DocumentType}")
144 logger.debug(f"inside passport")
145
146 else:
147 print("wrong here")
148
149 elif DocumentType == "driving_licence":
150 logger.debug(f"inside document type")
151 if rf"{country}_driving_licence" in labels:
152 prediction = (f"{country}_{DocumentType}")
153 print("prediction:", prediction)
154
155 elif state_code == "":
156 logger.debug({
157 "Status": "failed",
158 "message": "invalid DocumentType or state code or provide valid state code"
159 })
160
161 return {
162 "Status": "failed",
163 "message": "invalid DocumentType or state code or provide valid state code"
164 }
165
166 elif state_code != "":
167
168 state_name = pycountry.subdivisions.get(code=f"{alpha_2}-{state_code}")
169
170 print("state_name : ", state_name)
171 if state_name != None:
172 state_name = state_name.name.lower()
173 state_name = state_name.split()
174 state_name = ("_".join(state_name))
175 print("state_name : ", state_name)
176 logger.debug(f"state_name : {state_name}")
177 if rf"{country}_driving_licence" in labels:
178
179 # print("path1 : ", path1)
180 # logger.info(str(path1))
181
182 # if path1 == False:
183 # logger.debug(f"Data Not Found")
184 # return {"Status" : "Not Found", "message" : "Data Not Found"}
185 # else:
186 # print("here1")
187
188 prediction = (f"{country}_{DocumentType}_{state_name}")
189 print("prediction1 : ", prediction)
190 logger.debug(f"prediction1 : {prediction}")
191
192 else:
193 logger.debug({
194 "Status": "failed",
195 "message": "invalid state code"
196 })
197 return {
198 "Status": "failed",
199 "message": "invalid state code"
200 }
201
202 else:
203 print("else here")
204
205 else:
206 print("else")
207 return {
208 "Status": "failed",
209 "message": "invalid DocumentType or State code2"
210 }
211
212 try:
213 pickle_in = open(rf"{path}//{country}.p", "rb")
214 except FileNotFoundError:
215 return ({"Status": "failed",
216 "message": f"{country} model not available"})
217
218 image_data = base64.b64decode(self.data["image"])
219 try:
220
221 test_img = Image.open(io.BytesIO(image_data))
222 except Exception:
223 return ({"Status": "failed",
224 "message": "provide valid base64 string"})
225
226 print(type(image_data))
227
228 print("test_img1")
229
230 test_img = Image.open(io.BytesIO(image_data))
231 # print("test_img", test_img)
232 im = test_img.resize((200, 99), Image.ANTIALIAS)
233 print("done")
234 try:
235 im.save("im.jpg") or im.save("im.png")
236 except OSError:
237 return ({"status": "provide jpg image"})
238 try:
239
240 test_img = image.load_img("im.jpg", target_size=(200, 99))
241
242 except OSError:
243 logger.debug({"Status": "failed",
244 "message": "provide valid base64 string"})
245
246 return ({"Status": "failed",
247 "message": "provide valid base64 string"})
248
249 test_img = np.array(test_img) / 255
250 samples_to_predict = np.expand_dims(test_img, axis=0)
251
252 img = np.asarray(test_img)
253
254 def grayscale(img):
255 img = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)
256 return img
257
258 def equalize(img):
259 img = cv2.equalizeHist(img)
260 return img
261
262 def preprocessing(img):
263 img = grayscale(img)
264 img = equalize(img)
265 img = img / 255
266 return img
267
268
269model = pickle.load(pickle_in)
270print(rf'{country}_model loaded...')
271test_img = cv2.imread("im.jpg")
272# print(test_img)
273print("image loaded for testing...")
274img = np.asarray(test_img)
275print(img.shape)
276img = preprocessing(img)
277img = img.reshape(1, 99, 200, 1)
278print(img.shape)
279# print("img1",img)
280predictions = model.predict(img)
281print("predictions", predictions)
282
283prediction_prob = model.predict_proba(img)
284print("prediction_prob:", prediction_prob)
285logger.debug(f"prediction_prob : {prediction_prob}")
286result2 = np.argmax(predictions)
287print("result2:", result2)
288logger.debug(f"result2 : {result2}")
289mlb = MultiLabelBinarizer()
290mlb.fit([labels])
291idxs = np.argsort(predictions)[::-1][:2]
292
293for (i, j) in enumerate(idxs):
294 try:
295 label = "{}: {:.2f}%".format(list(mlb.classes_), predictions[j] * 100)
296 print("label", labels)
297 cv2.putText(test_img, label, (10, (i * 30) + 25), cv2.FONT_HERSHEY_SIMPLEX, 0.7, (0, 255, 0), 2)
298 except:
299 print([labels], [j])
300 # show the probabilities for each of the individual labels
301 for (label1, predictions) in zip(mlb.classes_, predictions):
302 label = labels[str(result2)]
303 print("label1:", label)
304 if label1 == prediction:
305 print("{}: {:.2f}%".format(label1, predictions1 * 100))
306 logger.debug("{}: {:.2f}%".format(label1, predictions1 * 100))
307 confidence_level = predictions * 100
308 confidence_level1 = "{:.2f}".format(confidence_level)
309 print("confidence_level: ", confidence_level1)
310 logger.debug(f"confidence_level: {confidence_level1}")
311
312 # THIS IS WHAT I CHANGED
313 result = handle_confidence_level(confidence_level, confidence_level1)
314 for key, value in result:
315 print(key)
316 print(value)
317 #
318
319
320api.add_resource(HandleRequest2, '/recDoc1')
321
322if __name__ == '__main__':
323 app.run(debug=False)
324
325
326