File size: 6,212 Bytes
01c9143
 
 
 
 
 
c95dcd6
01c9143
 
 
a15da10
01c9143
 
 
c95dcd6
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
01c9143
3b17d42
 
 
 
 
 
 
 
 
 
 
 
 
 
 
01c9143
 
 
 
964e8c0
01c9143
 
964e8c0
a294f5a
 
 
 
 
 
209424a
a294f5a
 
 
 
 
 
 
 
 
c95dcd6
a294f5a
 
 
 
c95dcd6
a294f5a
 
01c9143
3b17d42
 
 
c95dcd6
 
3b17d42
 
 
 
 
 
 
c95dcd6
01c9143
 
 
3b17d42
91bd18b
01c9143
3b17d42
 
 
 
 
 
6587425
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
f973997
6b092bc
 
7487de4
f774f1b
18fe3c3
6b092bc
 
01c9143
 
 
780f8bc
9a2eb41
27da5d4
01c9143
 
 
d08693f
c95dcd6
01c9143
c95dcd6
01c9143
6587425
 
 
01c9143
964e8c0
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
import os
import gradio as gr
import requests
import base64
from io import BytesIO
from PIL import Image
import hashlib

def image_to_base64(image):
    buffered = BytesIO()
    image.save(buffered, format="JPEG", quality=90)
    return base64.b64encode(buffered.getvalue()).decode('utf-8')

def base64_to_image(base64_str):
    return base64.b64decode(base64_str + '=' * (-len(base64_str) % 4))

def check_db(img_array, suffix, token_server_url):
    hashes = []
    out_array = []
    for item in img_array:
        try:
            image_data = base64_to_image(item["image"])
            
            hash_object = hashlib.sha256(image_data)
            image_hash = hash_object.hexdigest()
            
            hashes.append(image_hash)
            out_array.append((Image.open(BytesIO(image_data)), item["url"] + suffix))
    
        except base64.binascii.Error as e:
            raise ValueError(f"Invalid base64 string: {str(e)}")
        except Exception as e:
            raise ValueError(f"Error processing image: {str(e)}")

    try:
        r = requests.post(url=token_server_url + '/lookup-hashes', json={"hashes": hashes})
        out_array = [value for i, value in enumerate(out_array) if i not in r.json().get('res')]
    except:
        raise gr.Error("Token Server Error!")

    return out_array

def search_face(file, token):
    free_url = os.environ.get("SERVER_URL_FREE")
    premium_url = os.environ.get("SERVER_URL_PREMIUM")
    token_server_url = os.environ.get("TOKEN_URL")

    url = free_url
    if token:
        try:
            r = requests.post(url=token_server_url + '/verify-token', json={"token": token})
            if r.json().get('status') == 'success':
                url = premium_url
            else:
                raise gr.Error("Invalid token! For free search, use empty string for token")
        except:
            raise gr.Error("Invalid token!")

    try:
        image = Image.open(file)
        image_base64 = image_to_base64(image)
        r = requests.post(url=url, headers={"X-RapidAPI-Key": os.environ.get("API_KEY")}, json={"image": image_base64})
    except:
        raise gr.Error("Please select image file!")

    status_code = r.status_code
    if status_code == 301:
        gr.Info("Too many faces in the photo.")
    elif status_code == 302:
        gr.Info("Face is not clear enough.")
    elif status_code == 303:
        gr.Info("No matches found. Try Deep Search with Premium Token.")
    elif status_code == 304:
        gr.Info("No face in the photo.")
    elif status_code == 305:
        gr.Info("Search blocked for privacy issue.")
    elif status_code == 401:
        gr.Info("Invalid image format.")
    elif status_code == 402:
        gr.Info("Wrong request.")
    elif status_code == 403:
        gr.Info("Please try again later.")
    elif status_code == 404:
        gr.Info("Timeout, try again.")

    if status_code > 300:
        return []   

    try:        
        res = r.json().get('img_array')
        suffix = "*********"
        if url == premium_url:
            suffix = ""
        
        out_array = check_db(res, suffix, token_server_url)

        if url == premium_url:
            try:
                r = requests.post(url=token_server_url + '/activate-token', json={"token": token})
            except:
                raise gr.Error("Invalid token!")

        return out_array
    except:
        raise gr.Error("Try again.")

def search_face_free(file):
    return search_face(file, '')

custom_css = """
caption.caption {
    user-select: text;
    cursor: text;
}
"""

js = """
function aff() {
const links = document.querySelectorAll('a');

const currentUrl = new URL(window.location.href);
const currentParams = currentUrl.searchParams.toString();

links.forEach(link => {
    const href = link.getAttribute('href');
    if (href && (href.startsWith('https://faceonlive.pocketsflow.com') || href.startsWith('https://faceonlive.com'))) {
        const targetUrl = new URL(href);
        // Append current page parameters to the link
        currentParams.split('&').forEach(param => {
            if (param) {
                const [key, value] = param.split('=');
                targetUrl.searchParams.set(key, value);
            }
        });
        link.setAttribute('href', targetUrl.toString());
        console.log(`Updated Link: ${targetUrl.toString()}`);
    }
});

  return ''
}
"""

with gr.Blocks(css=custom_css) as demo:
    gr.Markdown(
        """
    # Free Face Search Online
    #### [Discover more about our Face Search on our website.](https://faceonlive.com/face-search-online)
    <br>
    """
    )
    with gr.Row():
        with gr.Column(scale=1):
            image = gr.Image(type='filepath', height=480)
            token = gr.Textbox(placeholder="(Optional) Get Premium Token Below.", label="Premium Token")
            gr.HTML("<a href='https://faceonlive.pocketsflow.com/checkout?productId=676c15b1971244a587ca07cb' target='_blank'>Get Premium Token: Perform Deep Search & Full URLs</a>")            
            gr.HTML("<a href='https://faceonlive.pocketsflow.com/checkout?productId=676d7e7597f8b3b699f84820' target='_blank'>Protect Your Privacy – Start Your Takedown Now</a>")
            search_face_button = gr.Button("Search Face")
        with gr.Column(scale=2):
            output = gr.Gallery(label="Found Images", columns=[4], object_fit="contain", height="auto")
    
    gr.Examples(['examples/1.jpg', 'examples/2.jpg'], inputs=image, cache_examples=True, cache_mode='lazy', fn=search_face_free, outputs=[output])

    search_face_button.click(search_face, inputs=[image, token], outputs=[output], api_name=False)

    gr.HTML('<a href="https://visitorbadge.io/status?path=https%3A%2F%2Fhuggingface.co%2Fspaces%2FFaceOnLive%2FFace-Search-Online"><img src="https://api.visitorbadge.io/api/combined?path=https%3A%2F%2Fhuggingface.co%2Fspaces%2FFaceOnLive%2FFace-Search-Online&labelColor=%23ff8a65&countColor=%2337d67a&style=flat&labelStyle=upper" /></a>')
    html = gr.HTML()
    demo.load(None, inputs=None, outputs=html, js=js)

demo.queue(api_open=False, default_concurrency_limit=4).launch(server_name="0.0.0.0", server_port=7860, show_api=False)