import gradio as gr
import os
import requests

from PIL import Image

def face_compare(frame1, frame2):
    url = "https://face.miniai.live/api/face_match"
    files = {'image1': open(frame1, 'rb'), 'image2': open(frame2, 'rb')}
    r = requests.post(url=url, files=files)
    response = r.json()

    detections = response.get("detections", [])
    matches = response.get("match", [])
    detection_rows = ""
    match_rows = ""

    # Process detections
    for detection in detections:
        face_image = detection.get("face", "")
        face_img_tag = f"<img src='data:image/png;base64,{face_image}' width='100' />" if face_image else "N/A"
        first_face_index = detection.get("firstFaceIndex", "N/A")
        second_face_index = detection.get("secondFaceIndex", "N/A")

        detection_rows += f"""
        <tr>
            <td>{first_face_index}</td>
            <td>{second_face_index}</td>
            <td>{face_img_tag}</td>
        </tr>
        """

    # Process matches
    for match in matches:
        first_face_index = match.get("firstFaceIndex", "N/A")
        second_face_index = match.get("secondFaceIndex", "N/A")
        similarity = match.get("similarity", "N/A")

        match_rows += f"""
        <tr>
            <td>{first_face_index}</td>
            <td>{second_face_index}</td>
            <td>{similarity:.6f}</td>
        </tr>
        """

    # Create HTML tables
    detections_table = f"""
    <h3>Face Detection</h3>
    <table border="1" style="border-collapse: collapse; width: 100%;">
        <tr>
            <th>First Face Index</th>
            <th>Second Face Index</th>
            <th>Face Image</th>
        </tr>
        {detection_rows}
    </table>
    """

    matches_table = f"""
    <h3>Matching Results</h3>
    <table border="1" style="border-collapse: collapse; width: 100%;">
        <tr>
            <th>First Face Index</th>
            <th>Second Face Index</th>
            <th>Similarity</th>
        </tr>
        {match_rows}
    </table>
    """

    return detections_table + matches_table

def check_liveness(frame):
    url = "https://facelive.miniai.live/api/check_liveness"
    files = {'image': open(frame, 'rb')}
    r = requests.post(url=url, files=files)

    html = None
    table_value = ""

    for key, value in r.json().items():
        row_value = ("<tr>"
                        "<td>{key}</td>"
                        "<td>{value}</td>"
                    "</tr>".format(key=key, value=value))
        table_value = table_value + row_value

    html = ("<table>"
                "<tr>"
                    "<th style=""width:30%"">Field</th>"
                    "<th style=""width:50%"">Value</th>"
                "</tr>"
                "{table_value}"
                "</table>".format(table_value=table_value))
    
    return html

# APP Interface
with gr.Blocks() as MiniAIdemo:
    gr.Markdown(
        """
        <a href="https://miniai.live" style="display: flex; align-items: center;">
            <img src="https://miniai.live/wp-content/uploads/2024/02/logo_name-1-768x426-1.png" style="width: 18%; margin-right: 15px;"/>
            <div>
                <p style="font-size: 40px; font-weight: bold; margin-right: 20px;">FaceRecognition-LivenessDetection SDK Demo</p>
                <p style="font-size: 20px; margin-right: 0;">Experience our NIST FRVT Top Ranked FaceRecognition, iBeta 2 Certified Face Liveness Detection Engine</p>
            </div>
        </a>
        <br/>
        <div style="display: flex; justify-content: center; align-items: center;"> 
           <table style="text-align: center;">
              <tr>
                 <td style="text-align: center; vertical-align: middle;"><a href="https://github.com/MiniAiLive"><img src="https://miniai.live/wp-content/uploads/2024/10/new_git-1-300x67.png" style="height: 50px; margin-right: 5px;" title="GITHUB"/></a></td> 
                 <td style="text-align: center; vertical-align: middle;"><a href="https://huggingface.co/MiniAiLive"><img src="https://miniai.live/wp-content/uploads/2024/10/new_hugging-1-300x67.png" style="height: 50px; margin-right: 5px;" title="HuggingFace"/></a></td> 
                 <td style="text-align: center; vertical-align: middle;"><a href="https://demo.miniai.live"><img src="https://miniai.live/wp-content/uploads/2024/10/new_gradio-300x67.png" style="height: 50px; margin-right: 5px;" title="Gradio"/></a></td> 
              </tr> 
              <tr>
                 <td style="text-align: center; vertical-align: middle;"><a href="https://docs.miniai.live/"><img src="https://miniai.live/wp-content/uploads/2024/10/a-300x70.png" style="height: 50px; margin-right: 5px;" title="Documentation"/></a></td> 
                 <td style="text-align: center; vertical-align: middle;"><a href="https://www.youtube.com/@miniailive"><img src="https://miniai.live/wp-content/uploads/2024/10/Untitled-1-300x70.png" style="height: 50px; margin-right: 5px;" title="Youtube"/></a></td> 
                 <td style="text-align: center; vertical-align: middle;"><a href="https://play.google.com/store/apps/dev?id=5831076207730531667"><img src="https://miniai.live/wp-content/uploads/2024/10/googleplay-300x62.png" style="height: 50px; margin-right: 5px;" title="Google Play"/></a></td>
              </tr>
           </table>
        </div>
        <br/>
        """
    )
    with gr.Tabs():
        with gr.Tab("Face Recognition"):
            with gr.Row():
                with gr.Column():
                    im_match_in1 = gr.Image(type='filepath', height=300)
                    gr.Examples(
                        [
                            "images/compare/demo-pic22.jpg",
                            "images/compare/demo-pic60.jpg",
                            "images/compare/demo-pic35.jpg",
                            "images/compare/demo-pic33.jpg",
                            "images/compare/demo-pic34.jpg",
                        ],
                        inputs=im_match_in1
                    )
                with gr.Column():
                    im_match_in2 = gr.Image(type='filepath', height=300)
                    gr.Examples(
                        [
                            "images/compare/demo-pic41.jpg",
                            "images/compare/demo-pic32.jpg",
                            "images/compare/demo-pic39.jpg",
                            "images/compare/demo-pic61.jpg",
                            "images/compare/demo-pic40.jpg",
                        ],
                        inputs=im_match_in2
                    )
                with gr.Column():
                    txt_compare_out = gr.HTML()
            btn_f_match = gr.Button("Check Comparing!", variant='primary')
            btn_f_match.click(face_compare, inputs=[im_match_in1, im_match_in2], outputs=txt_compare_out)
        with gr.Tab("Face Liveness Detection"):
            with gr.Row():
                with gr.Column():
                    im_liveness_in = gr.Image(type='filepath', height=300)
                    gr.Examples(
                        [
                            "images/liveness/f_real_andr.jpg",
                            "images/liveness/f_fake_andr_mask3d.jpg",
                            "images/liveness/f_fake_andr_monitor.jpg",
                            "images/liveness/f_fake_andr_outline.jpg",
                            "images/liveness/f_fake_andr_outline3d.jpg",
                            "images/liveness/1.jpg",
                            "images/liveness/3.png",
                            "images/liveness/4.jpg",
                        ],
                        inputs=im_liveness_in
                    )
                    btn_f_liveness = gr.Button("Check Liveness!", variant='primary')
                with gr.Column():
                    livness_result_output = gr.HTML()
            btn_f_liveness.click(check_liveness, inputs=im_liveness_in, outputs=livness_result_output)
    gr.HTML('<a href="https://visitorbadge.io/status?path=https%3A%2F%2Fhuggingface.co%2Fspaces%2FMiniAiLive%2FFaceRecognition-LivenessDetection-Demo"><img src="https://api.visitorbadge.io/api/combined?path=https%3A%2F%2Fhuggingface.co%2Fspaces%2FMiniAiLive%2FFaceRecognition-LivenessDetection-Demo&label=VISITORS&labelColor=%2337d67a&countColor=%23ff8a65&style=plastic&labelStyle=none" /></a>')
if __name__ == "__main__":
    MiniAIdemo.launch()