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
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import sys
|
| 2 |
+
import os
|
| 3 |
+
import io
|
| 4 |
+
import gradio as gr
|
| 5 |
+
import cv2
|
| 6 |
+
import json
|
| 7 |
+
import requests
|
| 8 |
+
import numpy as np
|
| 9 |
+
from gradio.components import Image
|
| 10 |
+
from PIL import Image, ExifTags
|
| 11 |
+
|
| 12 |
+
from id_ocr.engine.header import *
|
| 13 |
+
from id_live.engine.header import *
|
| 14 |
+
import id_ocr.engine.header as id_ocr_header
|
| 15 |
+
import id_live.engine.header as id_live_header
|
| 16 |
+
|
| 17 |
+
css = """
|
| 18 |
+
.example-image img{
|
| 19 |
+
display: flex; /* Use flexbox to align items */
|
| 20 |
+
justify-content: center; /* Center the image horizontally */
|
| 21 |
+
align-items: center; /* Center the image vertically */
|
| 22 |
+
height: 300px; /* Set the height of the container */
|
| 23 |
+
object-fit: contain; /* Preserve aspect ratio while fitting the image within the container */
|
| 24 |
+
}
|
| 25 |
+
.example-image img{
|
| 26 |
+
display: flex; /* Use flexbox to align items */
|
| 27 |
+
text-align: center;
|
| 28 |
+
justify-content: center; /* Center the image horizontally */
|
| 29 |
+
align-items: center; /* Center the image vertically */
|
| 30 |
+
height: 350px; /* Set the height of the container */
|
| 31 |
+
object-fit: contain; /* Preserve aspect ratio while fitting the image within the container */
|
| 32 |
+
}
|
| 33 |
+
|
| 34 |
+
.markdown-success-container {
|
| 35 |
+
background-color: #F6FFED;
|
| 36 |
+
padding: 20px;
|
| 37 |
+
margin: 20px;
|
| 38 |
+
border-radius: 1px;
|
| 39 |
+
border: 2px solid green;
|
| 40 |
+
text-align: center;
|
| 41 |
+
}
|
| 42 |
+
|
| 43 |
+
.markdown-fail-container {
|
| 44 |
+
background-color: #FFF1F0;
|
| 45 |
+
padding: 20px;
|
| 46 |
+
margin: 20px;
|
| 47 |
+
border-radius: 1px;
|
| 48 |
+
border: 2px solid red;
|
| 49 |
+
text-align: center;
|
| 50 |
+
}
|
| 51 |
+
|
| 52 |
+
.block-background {
|
| 53 |
+
# background-color: #202020; /* Set your desired background color */
|
| 54 |
+
border-radius: 5px;
|
| 55 |
+
}
|
| 56 |
+
"""
|
| 57 |
+
|
| 58 |
+
file_path = os.path.abspath(__file__)
|
| 59 |
+
root_path = os.path.dirname(file_path)
|
| 60 |
+
|
| 61 |
+
g_id_ocr_activation_result = -1
|
| 62 |
+
g_id_live_activation_result = -1
|
| 63 |
+
|
| 64 |
+
screenReplayThreshold = 0.5
|
| 65 |
+
portraitReplaceThreshold = 0.5
|
| 66 |
+
printedCopyThreshold = 0.5
|
| 67 |
+
|
| 68 |
+
def activate_id_ocr_sdk():
|
| 69 |
+
id_ocr_key = os.environ.get("LICENSE_KEY")
|
| 70 |
+
id_ocr_dict_path = os.path.join(root_path, "id_ocr/engine/bin")
|
| 71 |
+
|
| 72 |
+
ret = -1
|
| 73 |
+
if id_ocr_key is None:
|
| 74 |
+
print_warning("ID OCR online license key not found!")
|
| 75 |
+
return ret
|
| 76 |
+
else:
|
| 77 |
+
activate_ret = id_ocr_header.set_activation(id_ocr_key.encode('utf-8')).decode('utf-8')
|
| 78 |
+
ret = json.loads(activate_ret).get("errorCode", None)
|
| 79 |
+
|
| 80 |
+
if ret == 0:
|
| 81 |
+
init_ret = id_ocr_header.init_sdk(id_ocr_dict_path.encode('utf-8')).decode('utf-8')
|
| 82 |
+
ret = json.loads(init_ret).get("errorCode", None)
|
| 83 |
+
if ret == 0:
|
| 84 |
+
print_log("Successfully init ID OCR SDK!")
|
| 85 |
+
else:
|
| 86 |
+
print_log("Failed to init ID OCR SDK!")
|
| 87 |
+
else:
|
| 88 |
+
print_error(f"Falied to activate ID OCR SDK, Error code {ret}")
|
| 89 |
+
|
| 90 |
+
return ret
|
| 91 |
+
|
| 92 |
+
def activate_id_live_sdk():
|
| 93 |
+
id_live_key = os.environ.get("ID_LIVE_LICENSE_KEY")
|
| 94 |
+
id_live_dict_path = os.path.join(root_path, "id_live/engine/model")
|
| 95 |
+
|
| 96 |
+
ret = -1
|
| 97 |
+
if id_live_key is None:
|
| 98 |
+
print_warning("ID LIVE license key not found!")
|
| 99 |
+
return ret
|
| 100 |
+
else:
|
| 101 |
+
ret = id_live_header.set_activation(id_live_key.encode('utf-8'))
|
| 102 |
+
|
| 103 |
+
if ret == 0:
|
| 104 |
+
ret = id_live_header.init_sdk(id_live_dict_path.encode('utf-8'))
|
| 105 |
+
|
| 106 |
+
if ret == 0:
|
| 107 |
+
print_log("Successfully init ID LIVE SDK!")
|
| 108 |
+
else:
|
| 109 |
+
print_log("Failed to init ID LIVE SDK!")
|
| 110 |
+
else:
|
| 111 |
+
print_error(f"Falied to activate ID LIVE SDK, Error code {ret}")
|
| 112 |
+
|
| 113 |
+
return ret
|
| 114 |
+
|
| 115 |
+
def find_key_in_dict(d, target_key):
|
| 116 |
+
for key, value in d.items():
|
| 117 |
+
if key == target_key:
|
| 118 |
+
return value
|
| 119 |
+
elif isinstance(value, dict): # If the value is a dictionary, search recursively
|
| 120 |
+
result = find_key_in_dict(value, target_key)
|
| 121 |
+
if result is not None:
|
| 122 |
+
return result
|
| 123 |
+
return None
|
| 124 |
+
|
| 125 |
+
def json_to_html_table(data, image_keys):
|
| 126 |
+
html = "<table border='1' style='border-collapse: collapse; width: 100%;'>"
|
| 127 |
+
for key, value in data.items():
|
| 128 |
+
if isinstance(value, dict):
|
| 129 |
+
html += f"<tr><td colspan='2'><strong>{key}</strong></td></tr>"
|
| 130 |
+
for sub_key, sub_value in value.items():
|
| 131 |
+
if sub_key in image_keys:
|
| 132 |
+
html += f"<tr><td>{sub_key}</td><td><img src='data:image/png;base64,{sub_value}' width = '200' height= '100' /></td></tr>"
|
| 133 |
+
else:
|
| 134 |
+
html += f"<tr><td>{sub_key}</td><td>{sub_value}</td></tr>"
|
| 135 |
+
else:
|
| 136 |
+
if key in image_keys:
|
| 137 |
+
html += f"<tr><td>{key}</td><td><img src='data:image/png;base64,{value}' width = '200' height= '100' /></td></tr>"
|
| 138 |
+
else:
|
| 139 |
+
html += f"<tr><td>{key}</td><td>{value}</td></tr>"
|
| 140 |
+
|
| 141 |
+
html += "</table>"
|
| 142 |
+
return html
|
| 143 |
+
|
| 144 |
+
def apply_exif_rotation(image):
|
| 145 |
+
try:
|
| 146 |
+
exif = image._getexif()
|
| 147 |
+
if exif is not None:
|
| 148 |
+
for orientation in ExifTags.TAGS.keys():
|
| 149 |
+
if ExifTags.TAGS[orientation] == 'Orientation':
|
| 150 |
+
break
|
| 151 |
+
|
| 152 |
+
# Get the orientation value
|
| 153 |
+
orientation = exif.get(orientation, None)
|
| 154 |
+
|
| 155 |
+
# Apply the appropriate rotation based on the orientation
|
| 156 |
+
if orientation == 3:
|
| 157 |
+
image = image.rotate(180, expand=True)
|
| 158 |
+
elif orientation == 6:
|
| 159 |
+
image = image.rotate(270, expand=True)
|
| 160 |
+
elif orientation == 8:
|
| 161 |
+
image = image.rotate(90, expand=True)
|
| 162 |
+
|
| 163 |
+
except AttributeError:
|
| 164 |
+
print("No EXIF data found")
|
| 165 |
+
|
| 166 |
+
return image
|
| 167 |
+
|
| 168 |
+
def check_liveness(frame):
|
| 169 |
+
# if frame is None:
|
| 170 |
+
# liveness_result = f"""<div class="markdown-fail-container"><p style="text-align: center; font-size: 20px; color: red;">Liveness Check Failed</p></div>"""
|
| 171 |
+
# return [liveness_result, {"status": "error", "result": "select image file!"}]
|
| 172 |
+
|
| 173 |
+
# img_bytes = io.BytesIO()
|
| 174 |
+
# Image.open(frame).save(img_bytes, format="JPEG")
|
| 175 |
+
# img_bytes.seek(0)
|
| 176 |
+
|
| 177 |
+
# url = "https://recognito-iddocumentlivenessdetection.p.rapidapi.com/process_image"
|
| 178 |
+
|
| 179 |
+
# try:
|
| 180 |
+
# files = {'image': img_bytes}
|
| 181 |
+
# headers = {"X-RapidAPI-Key": os.environ.get("API_KEY")}
|
| 182 |
+
|
| 183 |
+
# result = requests.post(url=url, files=files, headers=headers)
|
| 184 |
+
# except:
|
| 185 |
+
# liveness_result = f"""<div class="markdown-fail-container"><p style="text-align: center; font-size: 20px; color: red;">Liveness Check Failed</p></div>"""
|
| 186 |
+
# return [liveness_result, {"status": "error", "result": "failed to open file!"}]
|
| 187 |
+
|
| 188 |
+
# if result.ok:
|
| 189 |
+
# json_result = result.json()
|
| 190 |
+
# if json_result.get("resultCode") == "Error":
|
| 191 |
+
# liveness_result = f"""<div class="markdown-fail-container"><p style="text-align: center; font-size: 20px; color: red;">Liveness Check Failed</p></div>"""
|
| 192 |
+
# return [liveness_result, {"status": "error", "result": "server error!"}]
|
| 193 |
+
|
| 194 |
+
# process_results = json_result.get("result")
|
| 195 |
+
# status = process_results.get("status")
|
| 196 |
+
# if status == "Ok":
|
| 197 |
+
# screenReply = process_results.get("screenReply")
|
| 198 |
+
# portraitReplace = process_results.get("portraitReplace")
|
| 199 |
+
# printedCopy = process_results.get("printedCopy")
|
| 200 |
+
# liveness_result = f"""<div class="markdown-success-container"><p style="text-align: center; font-size: 20px; color: green;">Liveness Check: GENUINE</p></div>"""
|
| 201 |
+
|
| 202 |
+
# # Check for "Spoof" condition
|
| 203 |
+
# if screenReply < screenReplayThreshold or portraitReplace < portraitReplaceThreshold or printedCopy < printedCopyThreshold:
|
| 204 |
+
# liveness_result = f"""<div class="markdown-fail-container"><p style="text-align: center; font-size: 20px; color: red;">Liveness Check: SPOOF</p></div>"""
|
| 205 |
+
|
| 206 |
+
# json_output = {"Screen Replay Check": "Failed" if screenReply < screenReplayThreshold else "Success",
|
| 207 |
+
# "Portrait Replace Check": "Failed" if portraitReplace < portraitReplaceThreshold else "Success",
|
| 208 |
+
# "Printed Cutout Check": "Failed" if printedCopy < printedCopyThreshold else "Success"}
|
| 209 |
+
# # Update json_result with the modified process_results
|
| 210 |
+
# return [liveness_result, json_output]
|
| 211 |
+
|
| 212 |
+
# liveness_result = f"""<div class="markdown-fail-container"><p style="text-align: center; font-size: 20px; color: red;">Liveness Check Failed</p></div>"""
|
| 213 |
+
# return [liveness_result, {"status": "error", "result": "document not found!"}]
|
| 214 |
+
# else:
|
| 215 |
+
# liveness_result = f"""<div class="markdown-fail-container"><p style="text-align: center; font-size: 20px; color: red;">Liveness Check Failed</p></div>"""
|
| 216 |
+
# return [liveness_result, {"status": "error", "result": f"{result.text}"}]
|
| 217 |
+
global g_id_live_activation_result
|
| 218 |
+
if g_id_live_activation_result != 0:
|
| 219 |
+
gr.Warning("ID LIVE SDK Activation Failed!")
|
| 220 |
+
return {"status": "error", "result": "activation error!"}
|
| 221 |
+
try:
|
| 222 |
+
image = Image.open(frame)
|
| 223 |
+
image = apply_exif_rotation(image.convert('RGB'))
|
| 224 |
+
except:
|
| 225 |
+
raise gr.Error("Please select image file!")
|
| 226 |
+
|
| 227 |
+
image_np = np.asarray(image)
|
| 228 |
+
result = id_live_header.processImage(image_np, image_np.shape[1], image_np.shape[0])
|
| 229 |
+
result_dict = json.loads(result.decode('utf-8'))
|
| 230 |
+
status = result_dict["status"]
|
| 231 |
+
if status == "Ok":
|
| 232 |
+
screenReply = float(result_dict["screenReply"])
|
| 233 |
+
portraitReplace = float(result_dict["portraitReplace"])
|
| 234 |
+
printedCopy = float(result_dict["printedCopy"])
|
| 235 |
+
detResult = "genuine"
|
| 236 |
+
|
| 237 |
+
# Check for "Spoof" condition
|
| 238 |
+
if screenReply < screenReplayThreshold or portraitReplace < portraitReplaceThreshold or printedCopy < printedCopyThreshold:
|
| 239 |
+
detResult = "spoof"
|
| 240 |
+
|
| 241 |
+
# Update json_result with the modified process_results
|
| 242 |
+
return {"status": "ok", "data": {"result": detResult, "screenreplay_integrity_score": screenReply, "portraitreplace_integrity_score": portraitReplace, "printedcutout_integrity_score": printedCopy}}
|
| 243 |
+
|
| 244 |
+
return {"status": "error", "result": "document not found!"}
|
| 245 |
+
|
| 246 |
+
|
| 247 |
+
def idcard_recognition(frame1, frame2):
|
| 248 |
+
# url = "https://recognito-iddocumentrecognition.p.rapidapi.com/api/read_idcard"
|
| 249 |
+
|
| 250 |
+
# files = None
|
| 251 |
+
# if frame1 is not None and frame2 is not None:
|
| 252 |
+
# files = {'image': open(frame1, 'rb'), 'image2': open(frame2, 'rb')}
|
| 253 |
+
# elif frame1 is not None and frame2 is None:
|
| 254 |
+
# files = {'image': open(frame1, 'rb')}
|
| 255 |
+
# elif frame1 is None and frame2 is not None:
|
| 256 |
+
# files = {'image': open(frame2, 'rb')}
|
| 257 |
+
# else:
|
| 258 |
+
# return ['', None, None]
|
| 259 |
+
|
| 260 |
+
# headers = {"X-RapidAPI-Key": os.environ.get("API_KEY")}
|
| 261 |
+
|
| 262 |
+
# r = requests.post(url=url, files=files, headers=headers)
|
| 263 |
+
|
| 264 |
+
# images = None
|
| 265 |
+
# rawValues = {}
|
| 266 |
+
# image_table_value = ""
|
| 267 |
+
# result_table_dict = {
|
| 268 |
+
# 'portrait':'',
|
| 269 |
+
# 'documentName':'',
|
| 270 |
+
# 'score':'',
|
| 271 |
+
# 'countryName':'',
|
| 272 |
+
# 'name':'',
|
| 273 |
+
# 'sex':'',
|
| 274 |
+
# 'address':'',
|
| 275 |
+
# 'dateOfBirth':'',
|
| 276 |
+
# 'dateOfIssue':'',
|
| 277 |
+
# 'dateOfExpiry':'',
|
| 278 |
+
# 'documentNumber':'',
|
| 279 |
+
# }
|
| 280 |
+
|
| 281 |
+
# if 'data' in r.json():
|
| 282 |
+
# for key, value in r.json()['data'].items():
|
| 283 |
+
# if key == 'image':
|
| 284 |
+
# for image_key, image_value in value.items():
|
| 285 |
+
# row_value = ("<tr>"
|
| 286 |
+
# "<td>{key}</td>"
|
| 287 |
+
# "<td><img src=""data:image/png;base64,{base64_image} width = '200' height= '100' /></td>"
|
| 288 |
+
# "</tr>".format(key=image_key, base64_image=image_value))
|
| 289 |
+
# image_table_value = image_table_value + row_value
|
| 290 |
+
|
| 291 |
+
# images = ("<table>"
|
| 292 |
+
# "<tr>"
|
| 293 |
+
# "<th>Field</th>"
|
| 294 |
+
# "<th>Image</th>"
|
| 295 |
+
# "</tr>"
|
| 296 |
+
# "{image_table_value}"
|
| 297 |
+
# "</table>".format(image_table_value=image_table_value))
|
| 298 |
+
|
| 299 |
+
# for key, value in r.json().items():
|
| 300 |
+
# if key == 'data':
|
| 301 |
+
# if 'image' in value:
|
| 302 |
+
# del value['image']
|
| 303 |
+
# rawValues[key] = value
|
| 304 |
+
# else:
|
| 305 |
+
# rawValues[key] = value
|
| 306 |
+
|
| 307 |
+
|
| 308 |
+
# for result_key in result_table_dict.keys():
|
| 309 |
+
# result_table_dict[result_key] = find_key_in_dict(r.json(), result_key)
|
| 310 |
+
|
| 311 |
+
# result = json_to_html_table(result_table_dict, {'portrait'})
|
| 312 |
+
# json_result = json.dumps(rawValues, indent=6)
|
| 313 |
+
# return [result, json_result, images]
|
| 314 |
+
|
| 315 |
+
global g_id_ocr_activation_result
|
| 316 |
+
if g_id_ocr_activation_result != 0:
|
| 317 |
+
gr.Warning("ID OCR SDK Activation Failed!")
|
| 318 |
+
return ['', None]
|
| 319 |
+
|
| 320 |
+
image1, image2 = '', ''
|
| 321 |
+
if frame1 is not None and frame2 is not None:
|
| 322 |
+
image1, image2 = frame1, frame2
|
| 323 |
+
elif frame1 is not None and frame2 is None:
|
| 324 |
+
image1 = frame1
|
| 325 |
+
elif frame1 is None and frame2 is not None:
|
| 326 |
+
image1 = frame2
|
| 327 |
+
elif frame1 is None and frame2 is None:
|
| 328 |
+
raise gr.Error("Please select images files!")
|
| 329 |
+
|
| 330 |
+
ocrResult = id_ocr_header.ocr_id_card(image1.encode('utf-8'), image2.encode('utf-8'))
|
| 331 |
+
ocrResDict = json.loads(ocrResult)
|
| 332 |
+
images = None
|
| 333 |
+
rawValues = {}
|
| 334 |
+
image_table_value = ""
|
| 335 |
+
result_table_dict = {
|
| 336 |
+
'portrait':'',
|
| 337 |
+
'documentName':'',
|
| 338 |
+
'score':'',
|
| 339 |
+
'countryName':'',
|
| 340 |
+
'name':'',
|
| 341 |
+
'sex':'',
|
| 342 |
+
'address':'',
|
| 343 |
+
'dateOfBirth':'',
|
| 344 |
+
'dateOfIssue':'',
|
| 345 |
+
'dateOfExpiry':'',
|
| 346 |
+
'documentNumber':'',
|
| 347 |
+
}
|
| 348 |
+
|
| 349 |
+
for key, value in ocrResDict.items():
|
| 350 |
+
if key == 'image':
|
| 351 |
+
for image_key, image_value in value.items():
|
| 352 |
+
row_value = ("<tr>"
|
| 353 |
+
"<td>{key}</td>"
|
| 354 |
+
"<td><img src=""data:image/png;base64,{base64_image} width = '200' height= '100' /></td>"
|
| 355 |
+
"</tr>".format(key=image_key, base64_image=image_value))
|
| 356 |
+
image_table_value = image_table_value + row_value
|
| 357 |
+
|
| 358 |
+
images = ("<table>"
|
| 359 |
+
"<tr>"
|
| 360 |
+
"<th>Field</th>"
|
| 361 |
+
"<th>Image</th>"
|
| 362 |
+
"</tr>"
|
| 363 |
+
"{image_table_value}"
|
| 364 |
+
"</table>".format(image_table_value=image_table_value))
|
| 365 |
+
|
| 366 |
+
value = ocrResDict.copy()
|
| 367 |
+
if 'image' in value:
|
| 368 |
+
del value['image']
|
| 369 |
+
rawValues = value
|
| 370 |
+
else:
|
| 371 |
+
rawValues = value
|
| 372 |
+
|
| 373 |
+
|
| 374 |
+
for result_key in result_table_dict.keys():
|
| 375 |
+
result_table_dict[result_key] = find_key_in_dict(ocrResDict, result_key)
|
| 376 |
+
|
| 377 |
+
result = json_to_html_table(result_table_dict, {'portrait'})
|
| 378 |
+
json_result = json.dumps(rawValues, indent=6)
|
| 379 |
+
return [result, json_result, images]
|
| 380 |
+
|
| 381 |
+
def launch_demo():
|
| 382 |
+
with gr.Blocks(css=css) as demo:
|
| 383 |
+
gr.Markdown(
|
| 384 |
+
f"""
|
| 385 |
+
<a href="https://recognito.vision" style="display: flex; align-items: center;">
|
| 386 |
+
<img src="https://recognito.vision/wp-content/uploads/2024/03/Recognito-modified.png" style="width: 8%; margin-right: 15px;"/>
|
| 387 |
+
<div>
|
| 388 |
+
<p style="font-size: 32px; font-weight: bold; margin: 0;">Recognito</p>
|
| 389 |
+
<p style="font-size: 18px; margin: 0;">www.recognito.vision</p>
|
| 390 |
+
</div>
|
| 391 |
+
</a>
|
| 392 |
+
<p style="font-size: 20px; font-weight: bold;">π Product Documentation</p>
|
| 393 |
+
<div style="display: flex; align-items: center;">
|
| 394 |
+
  <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>
|
| 395 |
+
</div>
|
| 396 |
+
<p style="font-size: 20px; font-weight: bold;">π Visit Recognito</p>
|
| 397 |
+
<div style="display: flex; align-items: center;">
|
| 398 |
+
  <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>
|
| 399 |
+
<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>
|
| 400 |
+
<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>
|
| 401 |
+
<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>
|
| 402 |
+
<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>
|
| 403 |
+
<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>
|
| 404 |
+
</div>
|
| 405 |
+
<p style="font-size: 20px; font-weight: bold;">π€ Contact us for our on-premise ID Document Verification SDKs deployment</p>
|
| 406 |
+
<div style="display: flex; align-items: center;">
|
| 407 |
+
  <a target="_blank" href="mailto:[email protected]"><img src="https://img.shields.io/badge/[email protected]?logo=gmail " alt="www.recognito.vision"></a>
|
| 408 |
+
<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>
|
| 409 |
+
<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>
|
| 410 |
+
<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>
|
| 411 |
+
</div>
|
| 412 |
+
<br/>
|
| 413 |
+
"""
|
| 414 |
+
)
|
| 415 |
+
|
| 416 |
+
with gr.Tabs():
|
| 417 |
+
with gr.Tab("ID Document Recognition"):
|
| 418 |
+
with gr.Row():
|
| 419 |
+
with gr.Column(scale=6):
|
| 420 |
+
with gr.Row():
|
| 421 |
+
with gr.Column(scale=3):
|
| 422 |
+
id_image_input1 = gr.Image(type='filepath', label='Front', elem_classes="example-image")
|
| 423 |
+
with gr.Column(scale=3):
|
| 424 |
+
id_image_input2 = gr.Image(type='filepath', label='Back', elem_classes="example-image")
|
| 425 |
+
|
| 426 |
+
with gr.Row():
|
| 427 |
+
id_examples = gr.Examples(
|
| 428 |
+
examples=[['examples/1_f.png', 'examples/1_b.png'],
|
| 429 |
+
['examples/2_f.png', 'examples/2_b.png'],
|
| 430 |
+
['examples/3_f.png', 'examples/3_b.png'],
|
| 431 |
+
['examples/4.png', None]],
|
| 432 |
+
inputs=[id_image_input1, id_image_input2],
|
| 433 |
+
outputs=None,
|
| 434 |
+
fn=idcard_recognition
|
| 435 |
+
)
|
| 436 |
+
|
| 437 |
+
with gr.Blocks():
|
| 438 |
+
with gr.Column(scale=4, min_width=400, elem_classes="block-background"):
|
| 439 |
+
id_recognition_button = gr.Button("ID Card Recognition", variant="primary", size="lg")
|
| 440 |
+
|
| 441 |
+
with gr.Tab("Key Fields"):
|
| 442 |
+
id_result_output = gr.HTML()
|
| 443 |
+
with gr.Tab("Raw JSON"):
|
| 444 |
+
json_result_output = gr.JSON()
|
| 445 |
+
with gr.Tab("Images"):
|
| 446 |
+
image_result_output = gr.HTML()
|
| 447 |
+
|
| 448 |
+
id_recognition_button.click(idcard_recognition, inputs=[id_image_input1, id_image_input2], outputs=[id_result_output, json_result_output, image_result_output])
|
| 449 |
+
|
| 450 |
+
with gr.Tab("ID Document Liveness Detection"):
|
| 451 |
+
with gr.Row():
|
| 452 |
+
with gr.Column(scale=1):
|
| 453 |
+
id_image_input = gr.Image(label="Image", type='filepath', elem_classes="example-image")
|
| 454 |
+
gr.Examples(examples=['examples/1_f.png', 'examples/2_f.png', 'examples/3_f.png', 'examples/4.png'], inputs=id_image_input)
|
| 455 |
+
|
| 456 |
+
with gr.Blocks():
|
| 457 |
+
with gr.Column(scale=1, elem_classes="block-background"):
|
| 458 |
+
check_liveness_button = gr.Button("Check Document Liveness", variant="primary", size="lg")
|
| 459 |
+
|
| 460 |
+
liveness_result = gr.Markdown("")
|
| 461 |
+
json_output = gr.JSON()
|
| 462 |
+
|
| 463 |
+
check_liveness_button.click(check_liveness, inputs=id_image_input, outputs=[liveness_result, json_output])
|
| 464 |
+
|
| 465 |
+
gr.HTML('<a href="https://visitorbadge.io/status?path=https%3A%2F%2Fhuggingface.co%2Fspaces%2Frecognito%2FID-Document-Verification"><img src="https://api.visitorbadge.io/api/combined?path=https%3A%2F%2Fhuggingface.co%2Fspaces%2Frecognito%2FID-Document-Verification&labelColor=%2337d67a&countColor=%23263759&style=flat" /></a>')
|
| 466 |
+
|
| 467 |
+
demo.launch(server_name="0.0.0.0", server_port=7860, show_api=False)
|
| 468 |
+
|
| 469 |
+
if __name__ == '__main__':
|
| 470 |
+
g_id_ocr_activation_result = activate_id_ocr_sdk()
|
| 471 |
+
g_id_live_activation_result = activate_id_live_sdk()
|
| 472 |
+
launch_demo()
|
| 473 |
+
|