hassan526 commited on
Commit
127a04c
Β·
verified Β·
1 Parent(s): e58d467

Upload 8 files

Browse files
app.py ADDED
@@ -0,0 +1,249 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import sys
2
+ sys.path.append('../')
3
+
4
+ import os
5
+ import gradio as gr
6
+ import json
7
+ import cv2
8
+ import requests
9
+ import numpy as np
10
+ from PIL import Image
11
+
12
+ from engine.header import *
13
+
14
+ file_path = os.path.abspath(__file__)
15
+ dir_path = os.path.dirname(file_path)
16
+ root_path = os.path.dirname(dir_path)
17
+
18
+ device_id = get_deviceid().decode('utf-8')
19
+ print_info('\t <Hardware ID> \t\t {}'.format(device_id))
20
+
21
+ css = """
22
+ .example-image img{
23
+ display: flex; /* Use flexbox to align items */
24
+ justify-content: center; /* Center the image horizontally */
25
+ align-items: center; /* Center the image vertically */
26
+ height: 300px; /* Set the height of the container */
27
+ object-fit: contain; /* Preserve aspect ratio while fitting the image within the container */
28
+ }
29
+ .example-image img{
30
+ display: flex; /* Use flexbox to align items */
31
+ justify-content: center; /* Center the image horizontally */
32
+ align-items: center; /* Center the image vertically */
33
+ height: 300px; /* Set the height of the container */
34
+ object-fit: contain; /* Preserve aspect ratio while fitting the image within the container */
35
+
36
+ .block-background {
37
+ # background-color: #202020; /* Set your desired background color */
38
+ border-radius: 5px;
39
+ }
40
+ }
41
+ """
42
+
43
+ def find_key_in_dict(d, target_key):
44
+ for key, value in d.items():
45
+ if key == target_key:
46
+ return value
47
+ elif isinstance(value, dict): # If the value is a dictionary, search recursively
48
+ result = find_key_in_dict(value, target_key)
49
+ if result is not None:
50
+ return result
51
+ return None
52
+
53
+ def json_to_html_table(data, image_keys):
54
+ html = "<table border='1' style='border-collapse: collapse; width: 100%;'>"
55
+ for key, value in data.items():
56
+ if isinstance(value, dict):
57
+ html += f"<tr><td colspan='2'><strong>{key}</strong></td></tr>"
58
+ for sub_key, sub_value in value.items():
59
+ if sub_key in image_keys:
60
+ html += f"<tr><td>{sub_key}</td><td><img src='data:image/png;base64,{sub_value}' width = '200' height= '100' /></td></tr>"
61
+ else:
62
+ html += f"<tr><td>{sub_key}</td><td>{sub_value}</td></tr>"
63
+ else:
64
+ if key in image_keys:
65
+ html += f"<tr><td>{key}</td><td><img src='data:image/png;base64,{value}' width = '200' height= '100' /></td></tr>"
66
+ else:
67
+ html += f"<tr><td>{key}</td><td>{value}</td></tr>"
68
+
69
+ html += "</table>"
70
+ return html
71
+
72
+ def activate_sdk():
73
+ online_key = os.environ.get("LICENSE_KEY")
74
+ offline_key_path = os.path.join(root_path, "license.txt")
75
+
76
+ dict_path = os.path.join(root_path, "engine/bin")
77
+
78
+ ret = -1
79
+ if online_key is None:
80
+ print_warning("Online license key not found!")
81
+ else:
82
+ print_info(f"LICENSE_KEY: {online_key}")
83
+ activate_ret = set_activation(online_key.encode('utf-8')).decode('utf-8')
84
+ ret = json.loads(activate_ret).get("errorCode", None)
85
+
86
+ if ret == 0:
87
+ print_log("Successfully online activation SDK!")
88
+ else:
89
+ print_error(f"Failed to online activation SDK, Error code {ret}\n Trying offline activation SDK...");
90
+ if os.path.exists(offline_key_path) is False:
91
+ print_warning("Offline license key file not found!")
92
+ print_error(f"Falied to offline activation SDK, Error code {ret}")
93
+ return ret
94
+ else:
95
+ file=open(offline_key_path,"r")
96
+ offline_key = file.read()
97
+ file.close()
98
+ activate_ret = set_activation(offline_key.encode('utf-8')).decode('utf-8')
99
+ ret = json.loads(activate_ret).get("errorCode", None)
100
+ if ret == 0:
101
+ print_log("Successfully offline activation SDK!")
102
+ else:
103
+ print_error(f"Falied to offline activation SDK, Error code {ret}")
104
+ return ret
105
+
106
+ init_ret = init_sdk(dict_path.encode('utf-8')).decode('utf-8')
107
+ ret = json.loads(activate_ret).get("errorCode", None)
108
+ print_log(f"Init SDK: {ret}")
109
+ return ret
110
+
111
+ def idcard_recognition(frame1, frame2):
112
+ global g_activation_result
113
+ if g_activation_result != 0:
114
+ gr.Warning("SDK Activation Failed!")
115
+ return ['', None]
116
+
117
+ image1, image2 = '', ''
118
+ if frame1 is not None and frame2 is not None:
119
+ image1, image2 = frame1, frame2
120
+ elif frame1 is not None and frame2 is None:
121
+ image1 = frame1
122
+ elif frame1 is None and frame2 is not None:
123
+ image1 = frame2
124
+ elif frame1 is None and frame2 is None:
125
+ raise gr.Error("Please select images files!")
126
+
127
+ ocrResult = ocr_id_card(image1.encode('utf-8'), image2.encode('utf-8'))
128
+ ocrResDict = json.loads(ocrResult)
129
+ images = None
130
+ rawValues = {}
131
+ image_table_value = ""
132
+ result_table_dict = {
133
+ 'portrait':'',
134
+ 'documentName':'',
135
+ 'score':'',
136
+ 'countryName':'',
137
+ 'name':'',
138
+ 'sex':'',
139
+ 'address':'',
140
+ 'dateOfBirth':'',
141
+ 'dateOfIssue':'',
142
+ 'dateOfExpiry':'',
143
+ 'documentNumber':'',
144
+ }
145
+
146
+ for key, value in ocrResDict.items():
147
+ if key == 'image':
148
+ for image_key, image_value in value.items():
149
+ row_value = ("<tr>"
150
+ "<td>{key}</td>"
151
+ "<td><img src=""data:image/png;base64,{base64_image} width = '200' height= '100' /></td>"
152
+ "</tr>".format(key=image_key, base64_image=image_value))
153
+ image_table_value = image_table_value + row_value
154
+
155
+ images = ("<table>"
156
+ "<tr>"
157
+ "<th>Field</th>"
158
+ "<th>Image</th>"
159
+ "</tr>"
160
+ "{image_table_value}"
161
+ "</table>".format(image_table_value=image_table_value))
162
+
163
+ value = ocrResDict.copy()
164
+ if 'image' in value:
165
+ del value['image']
166
+ rawValues = value
167
+ else:
168
+ rawValues = value
169
+
170
+
171
+ for result_key in result_table_dict.keys():
172
+ result_table_dict[result_key] = find_key_in_dict(ocrResDict, result_key)
173
+
174
+ result = json_to_html_table(result_table_dict, {'portrait'})
175
+ json_result = json.dumps(rawValues, indent=6)
176
+ return [result, json_result, images]
177
+
178
+ def launch_demo(activate_result):
179
+ with gr.Blocks(css=css) as demo:
180
+ gr.Markdown(
181
+ f"""
182
+ <a href="https://recognito.vision" style="display: flex; align-items: center;">
183
+ <img src="https://recognito.vision/wp-content/uploads/2024/03/Recognito-modified.png" style="width: 8%; margin-right: 15px;"/>
184
+ <div>
185
+ <p style="font-size: 32px; font-weight: bold; margin: 0;">Recognito</p>
186
+ <p style="font-size: 18px; margin: 0;">www.recognito.vision</p>
187
+ </div>
188
+ </a>
189
+ <p style="font-size: 20px; font-weight: bold;">πŸ“˜ Product Documentation</p>
190
+ <div style="display: flex; align-items: center;">
191
+ &emsp;&emsp;<a href="https://docs.recognito.vision" style="display: flex; align-items: center;"><img src="https://recognito.vision/wp-content/uploads/2024/05/book.png" style="width: 48px; margin-right: 5px;"/></a>
192
+ </div>
193
+ <p style="font-size: 20px; font-weight: bold;">🏠 Visit Recognito</p>
194
+ <div style="display: flex; align-items: center;">
195
+ &emsp;&emsp;<a href="https://recognito.vision" style="display: flex; align-items: center;"><img src="https://recognito.vision/wp-content/uploads/2024/03/recognito_64_cl.png" style="width: 32px; margin-right: 5px;"/></a>
196
+ &nbsp;&nbsp;&nbsp;&nbsp;<a href="https://www.linkedin.com/company/recognito-vision" style="display: flex; align-items: center;"><img src="https://recognito.vision/wp-content/uploads/2024/03/linkedin_64_cl.png" style="width: 32px; margin-right: 5px;"/></a>
197
+ &nbsp;&nbsp;&nbsp;&nbsp;<a href="https://huggingface.co/recognito" style="display: flex; align-items: center;"><img src="https://recognito.vision/wp-content/uploads/2024/03/hf_64_cl.png" style="width: 32px; margin-right: 5px;"/></a>
198
+ &nbsp;&nbsp;&nbsp;&nbsp;<a href="https://github.com/recognito-vision" style="display: flex; align-items: center;"><img src="https://recognito.vision/wp-content/uploads/2024/03/github_64_cl.png" style="width: 32px; margin-right: 5px;"/></a>
199
+ &nbsp;&nbsp;&nbsp;&nbsp;<a href="https://hub.docker.com/u/recognito" style="display: flex; align-items: center;"><img src="https://recognito.vision/wp-content/uploads/2024/03/docker_64_cl.png" style="width: 32px; margin-right: 5px;"/></a>
200
+ &nbsp;&nbsp;&nbsp;&nbsp;<a href="https://www.youtube.com/@recognito-vision" style="display: flex; align-items: center;"><img src="https://recognito.vision/wp-content/uploads/2024/04/youtube_64_cl.png" style="width: 32px; margin-right: 5px;"/></a>
201
+ </div>
202
+ <p style="font-size: 20px; font-weight: bold;">🀝 Contact us for our on-premise Face Recognition, Liveness Detection SDKs deployment</p>
203
+ <div style="display: flex; align-items: center;">
204
+ &emsp;&emsp;<a target="_blank" href="mailto:[email protected]"><img src="https://img.shields.io/badge/[email protected]?logo=gmail " alt="www.recognito.vision"></a>
205
+ &nbsp;&nbsp;&nbsp;&nbsp;<a target="_blank" href="https://wa.me/+14158003112"><img src="https://img.shields.io/badge/whatsapp-+14158003112-blue.svg?logo=whatsapp " alt="www.recognito.vision"></a>
206
+ &nbsp;&nbsp;&nbsp;&nbsp;<a target="_blank" href="https://t.me/recognito_vision"><img src="https://img.shields.io/badge/telegram-@recognito__vision-blue.svg?logo=telegram " alt="www.recognito.vision"></a>
207
+ &nbsp;&nbsp;&nbsp;&nbsp;<a target="_blank" href="https://join.slack.com/t/recognito-workspace/shared_invite/zt-2d4kscqgn-"><img src="https://img.shields.io/badge/slack-recognito__workspace-blue.svg?logo=slack " alt="www.recognito.vision"></a>
208
+ </div>
209
+ <br/>
210
+ """
211
+ )
212
+
213
+ with gr.Row():
214
+ with gr.Column(scale=6):
215
+ with gr.Row():
216
+ with gr.Column(scale=3):
217
+ id_image_input1 = gr.Image(type='filepath', label='Front', elem_classes="example-image")
218
+ with gr.Column(scale=3):
219
+ id_image_input2 = gr.Image(type='filepath', label='Back', elem_classes="example-image")
220
+
221
+ with gr.Row():
222
+ id_examples = gr.Examples(
223
+ examples=[[os.path.join(root_path,'examples/1_f.png'), os.path.join(root_path, 'examples/1_b.png')],
224
+ [os.path.join(root_path,'examples/2_f.png'), os.path.join(root_path, 'examples/2_b.png')],
225
+ [os.path.join(root_path,'examples/3_f.png'), os.path.join(root_path, 'examples/3_b.png')],
226
+ [os.path.join(root_path,'examples/4.png'), None]],
227
+ inputs=[id_image_input1, id_image_input2],
228
+ outputs=None,
229
+ fn=idcard_recognition
230
+ )
231
+
232
+ with gr.Blocks():
233
+ with gr.Column(scale=4, min_width=400, elem_classes="block-background"):
234
+ id_recognition_button = gr.Button("ID Card Recognition", variant="primary", size="lg")
235
+ with gr.Tab("Key Fields"):
236
+ id_result_output = gr.HTML()
237
+ with gr.Tab("Raw JSON"):
238
+ json_result_output = gr.JSON()
239
+ with gr.Tab("Images"):
240
+ image_result_output = gr.HTML()
241
+
242
+
243
+ id_recognition_button.click(idcard_recognition, inputs=[id_image_input1, id_image_input2], outputs=[id_result_output, json_result_output, image_result_output])
244
+
245
+ demo.launch(server_name="0.0.0.0", server_port=7860, show_api=False)
246
+
247
+ if __name__ == '__main__':
248
+ g_activation_result = activate_sdk()
249
+ launch_demo(g_activation_result)
examples/1_b.png ADDED
examples/1_f.png ADDED
examples/2_b.png ADDED
examples/2_f.png ADDED
examples/3_b.png ADDED
examples/3_f.png ADDED
examples/4.png ADDED