File size: 14,697 Bytes
17316c3
 
 
 
 
 
 
9c1d3fc
 
 
 
 
17316c3
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
9c1d3fc
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
17316c3
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
13573d3
17316c3
 
 
 
 
 
 
 
13573d3
17316c3
 
13573d3
 
 
17316c3
13573d3
 
 
 
17316c3
 
 
 
13573d3
17316c3
 
 
 
 
2c3dcf5
 
b8b7120
3229779
 
 
 
 
 
 
 
 
ca9b0c8
3229779
 
e1f071d
 
 
 
17316c3
 
 
 
 
 
 
05a69ae
 
 
 
 
 
9c1d3fc
 
17316c3
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
a53a581
17316c3
a53a581
 
17316c3
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
d23d11b
 
 
 
 
 
 
 
 
 
17316c3
 
 
 
 
 
 
 
 
 
 
 
 
 
13573d3
17316c3
 
 
 
 
 
 
 
 
 
 
 
 
 
d23d11b
17316c3
 
 
 
 
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
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
import sys
import os
import io
import gradio as gr
import json
import requests
from PIL import Image
from flask import request 
import sqlite3 
from datetime import datetime, timedelta 
# Initialize SQLite database 


css = """
.example-image img{
    display: flex; /* Use flexbox to align items */
    justify-content: center; /* Center the image horizontally */
    align-items: center; /* Center the image vertically */
    height: 300px; /* Set the height of the container */
    object-fit: contain;  /* Preserve aspect ratio while fitting the image within the container */
}
.example-image img{
    display: flex; /* Use flexbox to align items */
    text-align: center;
    justify-content: center; /* Center the image horizontally */
    align-items: center; /* Center the image vertically */
    height: 350px;  /* Set the height of the container */
    object-fit: contain;  /* Preserve aspect ratio while fitting the image within the container */
}
.markdown-success-container {
    background-color: #F6FFED;
    padding: 20px;
    margin: 20px;
    border-radius: 1px;
    border: 2px solid green;
    text-align: center;
}
.markdown-fail-container {
    background-color: #FFF1F0;
    padding: 20px;
    margin: 20px;
    border-radius: 1px;
    border: 2px solid red;
    text-align: center;
}
.block-background {
    # background-color: #202020; /* Set your desired background color */
    border-radius: 5px;
}
"""

# Initialize SQLite database
conn = sqlite3.connect("ip_requests.db")
cursor = conn.cursor()
cursor.execute("""
    CREATE TABLE IF NOT EXISTS requests (
        ip_address TEXT PRIMARY KEY,
        count INTEGER,
        last_request TIMESTAMP
    )
""")
conn.commit()

def track_requests(ip_address):
    now = datetime.now()
    cursor.execute("SELECT count, last_request FROM requests WHERE ip_address=?", (ip_address,))
    result = cursor.fetchone()

    if result:
        count, last_request = result
        last_request = datetime.strptime(last_request, "%Y-%m-%d %H:%M:%S")
        if now - last_request > timedelta(days=1):
            count = 0
    else:
        count = 0

    count += 1
    cursor.execute("""
        INSERT OR REPLACE INTO requests (ip_address, count, last_request)
        VALUES (?, ?, ?)
    """, (ip_address, count, now.strftime("%Y-%m-%d %H:%M:%S")))
    conn.commit()
    return count


screenReplayThreshold = 0.5
portraitReplaceThreshold = 0.5
printedCopyThreshold = 0.5

def find_key_in_dict(d, target_key):
  for key, value in d.items():
    if key == target_key:
      return value
    elif isinstance(value, dict):  # If the value is a dictionary, search recursively
      result = find_key_in_dict(value, target_key)
      if result is not None:
        return result
  return None

def json_to_html_table(data, image_keys):
  html = "<table border='1' style='border-collapse: collapse; width: 100%;'>"
  for key, value in data.items():
    if isinstance(value, dict):
      html += f"<tr><td colspan='2'><strong>{key}</strong></td></tr>"
      for sub_key, sub_value in value.items():
        if sub_key in image_keys:
          html += f"<tr><td>{sub_key}</td><td><img src='data:image/png;base64,{sub_value}' width = '200'  height= '100' /></td></tr>"
        else:
          html += f"<tr><td>{sub_key}</td><td>{sub_value}</td></tr>"
    else:
      if key in image_keys:
        html += f"<tr><td>{key}</td><td><img src='data:image/png;base64,{value}' width = '200'  height= '100' /></td></tr>"
      else:
        html += f"<tr><td>{key}</td><td>{value}</td></tr>"
      
  html += "</table>"
  return html

def check_liveness(frame):
    
  if frame is None:
    liveness_result = f"""<div class="markdown-fail-container"><p style="text-align: center; font-size: 20px; color: red;">Liveness Check Failed</p></div>"""
    return [liveness_result, {"status": "error", "result": "select image file!"}]
  
  img_bytes = io.BytesIO()
  Image.open(frame).save(img_bytes, format="JPEG")
  img_bytes.seek(0)    
  
  url = "https://api.cortex.cerebrium.ai/v4/p-4f1d877e/my-first-project/check-liveness/"
  
  try:
    files = [
          ('file', ('image.jpg', img_bytes, 'image/jpeg'))
      ]

    headers = {
        'Authorization': 'Bearer eyJhbGciOiJSUzI1NiIsInR5cCI6IkpXVCJ9.eyJwcm9qZWN0SWQiOiJwLTRmMWQ4NzdlIiwiaWF0IjoxNzM5MjM2NjA5LCJleHAiOjIwNTQ4MTI2MDl9.0LH0iOnqHZfKTH4GF5iTZ4qNj5vylCryo8rBnErljsq2qD2cpVTetCqhKtnbstTUEjuv6MAJw9jt58z-QNJfYLK9sJcnBhawTR3iM2Ap_bFyjlzg2LbgkwRPjUVJkkcuCRhBKyebXwvqQBvWyOtMq6UekauumbmYBRbA2-T4u343YD4tO2xIfsTsTXznALp1SechjRuys-3xo3ZQbUs05_p38fOFucKI-abc91Eq6sIOkLFjYEM68yuV0UBWl-OSpPu66e0SClroAVlKFDMPS9MY0Jr7X1pBYX4jew6vozj9D8Y-HS-KkdPFqJ7HrZOfQd0wGUgYJHyC58yReWXaRQ',
        # 'Content-Type': 'application/json'
      }
    result = requests.post(url=url, files=files, headers=headers)
  except:
    liveness_result = f"""<div class="markdown-fail-container"><p style="text-align: center; font-size: 20px; color: red;">Liveness Check Failed</p></div>"""
    return [liveness_result, {"status": "error", "result": "failed to open file!"}]
  print("the result is", result)
  if result.ok:
    json_result = result.json()
    if json_result.get("resultCode") == "Error":
      liveness_result = f"""<div class="markdown-fail-container"><p style="text-align: center; font-size: 20px; color: red;">Liveness Check Failed</p></div>"""
      return [liveness_result, {"status": "error", "result": "server error!"}]
    if 'data' in json_result:
        data = json_result['data']
        print("the result data is is",data)
        if data["IsLive"] :
            liveness_result = f"""<div class="markdown-success-container"><p style="text-align: center; font-size: 20px; color: green;">Liveness Check: Live </p></div>"""
            json_output = {"Is Live": "Success", 
                           "document Type": data["DocumentType"],
                           # "Printed Cutout Check": "Failed" if printedCopy < printedCopyThreshold else "Success"
                          }
            # Update json_result with the modified process_results
            return [liveness_result, json_output]
        else:
            liveness_result = f"""<div class="markdown-fail-container"><p style="text-align: center; font-size: 20px; color: red;">Liveness Check: Fake </p></div>"""
            json_output = {"Is Live": "Failed", 
                           "document Type": data["DocumentType"],
                           # "Printed Cutout Check": "Failed" if printedCopy < printedCopyThreshold else "Success"
                          }
            # Update json_result with the modified process_results
            return [liveness_result, json_output]
    liveness_result = f"""<div class="markdown-fail-container"><p style="text-align: center; font-size: 20px; color: red;">Liveness Check Failed</p></div>"""
    return [liveness_result, {"status": "error", "result": "document not found!"}]
  else:
    liveness_result = f"""<div class="markdown-fail-container"><p style="text-align: center; font-size: 20px; color: red;">Liveness Check Failed</p></div>"""
    return [liveness_result, {"status": "error", "result": f"{result.text}"}]
    
def idcard_recognition(frame1):
  ip_address = request.remote_addr
  request_count = track_requests(ip_address)
  print("you have exceeded the daily limit of 5 requests", request_count)
  if request_count > 3:
      print("you have exceeded the daily limit of 5 requests")
      return "You have exceeded the daily limit of 5 requests."
        
        
  url = "https://api.cortex.cerebrium.ai/v4/p-4f1d877e/my-first-project/process-image/"
  # url = "https://edreesi-ocr-api.hf.space/process-image/"
  
  files = None
  if frame1 is not None:
      # Open the image using Pillow
      img = Image.open(frame1).convert("RGB")  # Convert to RGB to remove alpha channels
      img_bytes = io.BytesIO()
      
      # Save the image in JPEG format with consistent quality
      img.save(img_bytes, format="JPEG", quality=95, optimize=True, exif=b"")  # Strip EXIF metadata
      img_bytes.seek(0)  # Reset the file pointer
      
      # Log the file size for debugging
      print("Gradio File Size:", len(img_bytes.getvalue()), "bytes")
      
      # Prepare the files payload
      files = [
          ('file', ('image.jpg', img_bytes, 'image/jpeg'))
      ]
  else:
      return ['', None, None]
  
#   headers = {"X-RapidAPI-Key": os.environ.get("API_KEY")}
  headers = {}
#   r = requests.post(url=url, files=files, headers=headers)

  # r = requests.request("POST", url, headers=headers, data={}, files=files)
  payload = json.dumps({"prompt": "your value here"})

  headers = {
    'Authorization': 'Bearer eyJhbGciOiJSUzI1NiIsInR5cCI6IkpXVCJ9.eyJwcm9qZWN0SWQiOiJwLTRmMWQ4NzdlIiwiaWF0IjoxNzM5MjM2NjA5LCJleHAiOjIwNTQ4MTI2MDl9.0LH0iOnqHZfKTH4GF5iTZ4qNj5vylCryo8rBnErljsq2qD2cpVTetCqhKtnbstTUEjuv6MAJw9jt58z-QNJfYLK9sJcnBhawTR3iM2Ap_bFyjlzg2LbgkwRPjUVJkkcuCRhBKyebXwvqQBvWyOtMq6UekauumbmYBRbA2-T4u343YD4tO2xIfsTsTXznALp1SechjRuys-3xo3ZQbUs05_p38fOFucKI-abc91Eq6sIOkLFjYEM68yuV0UBWl-OSpPu66e0SClroAVlKFDMPS9MY0Jr7X1pBYX4jew6vozj9D8Y-HS-KkdPFqJ7HrZOfQd0wGUgYJHyC58yReWXaRQ',
    # 'Content-Type': 'application/json'
  }

  r = requests.request("POST", url, headers=headers, data={}, files=files)
  # print(r.text)
  print("Status Code:", r.status_code)
  print("r Body:", r.text)
#   r = requests.post(url=url, files=files, headers=headers)
  print('the result is', r.json())
  images = None   
  rawValues = {}
  image_table_value = ""
  result_table_dict = {
    'portrait':'', 
    'type':'',
    'score':'',
    # 'countryName':'',
    'FullName':'', 
    'Gender':'', 
    'PlaceOfBirth':'', 
    'DateOfBirth':'', 
    'IssuanceCenter':'',
    'IdentityNumber':'',
    'DateOfIssue':'', 
    'DateOfExpiry':'',
    }
  
  if 'data' in r.json():
    data = r.json()['data']
    for key, value in data.items():
        if key == 'faceImage':
            # Assign faceImage to the portrait field
            result_table_dict['portrait'] = value
        elif key == 'barcodeImage':
            # Add barcodeImage to the result dictionary
            result_table_dict['barcodeImage'] = value
        else:
            # Add other fields to the result dictionary
            result_table_dict[key] = value

    # Generate HTML for images
    image_table_value = ""
    if 'barcodeImage' in data:
        image_table_value += (
            "<tr>"
            f"<td>barcodeImage</td>"
            f"<td><img src='data:image/png;base64,{data['barcodeImage']}' width='200' height='100' /></td>"
            "</tr>"
        )

    # Generate the final HTML table for images
    images = (
        "<table>"
        "<tr>"
        "<th>Field</th>"
        "<th>Image</th>"
        "</tr>"
        f"{image_table_value}"
        "</table>"
    )

    # Prepare raw values for JSON output
    for key, value in r.json().items():
        if key == 'data':
            if 'faceImage' in value:
                del value['faceImage']
            if 'barcodeImage' in value:
                del value['barcodeImage']
            rawValues[key] = value
        else:
            rawValues[key] = value

    # Generate the result HTML table
    result = json_to_html_table(result_table_dict, {'portrait', 'barcodeImage'})
    json_result = json.dumps(rawValues, indent=6)
    return [result, json_result, images]
  
def launch_demo():
  with gr.Blocks(css=css) as demo:
    gr.Markdown(
      f"""
      
      <p style="font-size: 20px; font-weight: bold;">πŸ“˜ Product Documentation</p>
      <div style="display: flex; align-items: center;">          
        &emsp;&emsp;<a href="" 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>
      </div>
      <p style="font-size: 20px; font-weight: bold;">🏠 Visit Recognito</p>
      
      <br/>
      """
    )

    with gr.Tabs():
      with gr.Tab("ID Document Recognition"):
        with gr.Row():
          with gr.Column(scale=6):
            with gr.Row():
              with gr.Column(scale=6):
                id_image_input1 = gr.Image(type='filepath', label='ID Card Image', elem_classes="example-image")
            #   with gr.Column(scale=3):
            #     id_image_input2 = gr.Image(type='filepath', label='Back', elem_classes="example-image")
            
            # with gr.Row():
              # id_examples = gr.Examples(
              #   examples=[['examples/1_f.png', 'examples/1_b.png'], 
              #             ['examples/2_f.png', 'examples/2_b.png'], 
              #             ['examples/3_f.png', 'examples/3_b.png'], 
              #             ['examples/4.png', None]],
              #   inputs=[id_image_input1, id_image_input1],
              #   outputs=None,
              #   fn=idcard_recognition
              # )
            
          with gr.Blocks():
            with gr.Column(scale=4, min_width=400, elem_classes="block-background"):     
              id_recognition_button = gr.Button("ID Card Recognition", variant="primary", size="lg")

              with gr.Tab("Key Fields"):
                id_result_output = gr.HTML()
              with gr.Tab("Raw JSON"):
                json_result_output = gr.JSON()
              with gr.Tab("Images"):
                image_result_output = gr.HTML()
              
              id_recognition_button.click(idcard_recognition, inputs=id_image_input1, outputs=[id_result_output, json_result_output, image_result_output])

      with gr.Tab("Id Card Liveness Detection"):
        with gr.Row():
          with gr.Column(scale=1):
            id_image_input = gr.Image(label="Image", type='filepath', elem_classes="example-image")
            gr.Examples(examples=['examples/1_f.png', 'examples/2_f.png', 'examples/3_f.png', 'examples/4.png'], inputs=id_image_input)

          with gr.Blocks():
            with gr.Column(scale=1, elem_classes="block-background"):     
              check_liveness_button = gr.Button("Check Document Liveness", variant="primary", size="lg")
              
              liveness_result = gr.Markdown("")
              json_output = gr.JSON()
              
              check_liveness_button.click(check_liveness, inputs=id_image_input, outputs=[liveness_result, json_output])
    
    gr.HTML('<a href="https://visitorbadge.io/status?path=https%3A%2F%2Fedreesi-card-recognition.hf.space%2F"><img src="https://api.visitorbadge.io/api/visitors?path=https%3A%2F%2Fedreesi-card-recognition.hf.space%2F&countColor=%23263759" /></a>')
    
  demo.launch(server_name="0.0.0.0", server_port=7860, show_api=False)

if __name__ == '__main__':
  launch_demo()