| | import gradio as gr
|
| | import numpy as np
|
| | from time import sleep
|
| | from deepface import DeepFace
|
| | import torch
|
| |
|
| | bar_dict = {
|
| | 0: "│",
|
| | 1: "║",
|
| | 2: "▌",
|
| | 3: "█",
|
| | }
|
| |
|
| | css = """
|
| | bar_css {
|
| | text-align: center;
|
| | display:block;
|
| | }
|
| | """
|
| |
|
| | def calculate_bar(value):
|
| | value = int(value * 100)
|
| | result = "[" + "█" * (value // 1000) + bar_dict[(value % 1000) // 250] + "_" * max((10 - value // 1000 - 1), 0) + f"] {value / 100:.2f}% / 100%"
|
| | if value >= 99.99 * 100:
|
| | base_text = "Ещё чуть чуть..."
|
| | elif value > 80 * 100:
|
| | base_text = "Уже почти..."
|
| | elif value > 60 * 100:
|
| | base_text = "Александр распознан. Собираем биометрию..."
|
| | elif value > 40 * 100:
|
| | base_text = "Выделяем черты..."
|
| | elif value > 20 * 100:
|
| | base_text = "Распознаём структуру лица..."
|
| | else:
|
| | base_text = "Обрабатываем фото, пожалуйста подождите..."
|
| | text = f'''<div style="font-size:2em;">{base_text}</div>
|
| | <div style="font-size:3em; text-align:center;">{result}</div>
|
| | '''
|
| | return text
|
| |
|
| | def edit_bar(photo):
|
| | if photo is None:
|
| | return None, None, None, gr.update(value="Вы забыли вставить фотку :с", visible=True)
|
| | text = '''<div style="font-size:2em;">Обрабатываем фото, пожалуйста подождите...</div>
|
| | <div style="font-size:3em; text-align:center;">[__________] 0% / 100%</div>
|
| | '''
|
| | yield gr.update(value=text, visible=True), gr.update(visible=False), gr.update(visible=False), gr.update(visible=False), gr.update(visible=False), gr.update(visible=False), gr.update(visible=False), gr.update(visible=False)
|
| | current_perc = 0
|
| | check_id = False
|
| | n_small_steps = 0
|
| |
|
| | while current_perc < 99.99:
|
| | if n_small_steps == 0:
|
| | if np.random.rand() > 0.5:
|
| | n_small_steps = np.random.randint(5, 9)
|
| |
|
| | if n_small_steps == 0:
|
| | plus_perc = np.clip(np.random.normal(loc=15, scale=5), 0, 25)
|
| | wait_time = np.clip(np.random.normal(loc=1, scale=0.5), 0, 2)
|
| | else:
|
| | plus_perc = np.clip(np.random.normal(loc=3, scale=1.5), 0, 5.6)
|
| | wait_time = np.clip(np.random.normal(loc=0.2, scale=0.1), 0, 0.4)
|
| | n_small_steps -= 1
|
| |
|
| | if current_perc + plus_perc > 99.99:
|
| | plus_perc = 99.99 - current_perc
|
| | current_perc += plus_perc
|
| |
|
| | sleep(wait_time)
|
| | photo.save("image.png")
|
| | if current_perc > 30 and not check_id:
|
| |
|
| |
|
| |
|
| |
|
| |
|
| | try:
|
| | embedding_objs = DeepFace.represent(
|
| | img_path = "image.png",
|
| | model_name = "Facenet512",
|
| | )
|
| | except ValueError:
|
| | error_text = '''<div style="border: 3px solid red;"><div style="font-size:3em;text-align:center; color:red">Ошибка!</div>
|
| | <div style="text-align:center; font-size:2em">Не можем найти лицо на фото! Попытайтесь сделать снимок снова.</div></div>'''
|
| | yield gr.update(visible=False), gr.update(visible=True), gr.update(visible=True), gr.update(visible=True, value=error_text), gr.update(visible=False), gr.update(visible=False), gr.update(visible=False), gr.update(visible=False)
|
| | return
|
| | embed = torch.Tensor(embedding_objs[0]['embedding'])
|
| | alex_embed = torch.load("Alex_embed.pt")
|
| | print(embed.shape, alex_embed.shape)
|
| | cos_sim = torch.nn.functional.cosine_similarity(embed.unsqueeze(0), alex_embed.unsqueeze(0))
|
| | if cos_sim < 0.65:
|
| | error_text = '''<div style="border: 3px solid red;"><div style="font-size:3em;text-align:center; color:red">Ошибка!</div>
|
| | <div style="font-size:2em;text-align:center;">Кажется, вы не найдены в нашей системе :с <br> Можете попробовать загрузить другое фото.</div></div>'''
|
| | yield gr.update(visible=False), gr.update(visible=True), gr.update(visible=True), gr.update(visible=True, value=error_text), gr.update(visible=False), gr.update(visible=False), gr.update(visible=False), gr.update(visible=False)
|
| | return
|
| | check_id=True
|
| | new_bar = calculate_bar(current_perc)
|
| | yield gr.update(value=new_bar, visible=True), gr.update(visible=False), gr.update(visible=False), gr.update(visible=False), gr.update(visible=False), gr.update(visible=False), gr.update(visible=False), gr.update(visible=False)
|
| | sleep(3)
|
| | for i in range(8):
|
| | perc = "??" if i == 0 or i == 4 else "30"
|
| | err = ["_ОшИбК#к&а", "_ОшИ#бКкк!A", "_0ШИб№кКA#", "O&Ош#Иб_К#a"]
|
| | error = f'''<div style="font-size:4em; text-align:center; color:red">[{err[i % 2]}] {perc}% / 100%</div>''' if i % 2 == 0 else ""
|
| | text = f'''<div style="font-size:3em;">Ош#шибка...</div>
|
| | {error}
|
| | '''
|
| | if i == 4:
|
| | yield gr.update(value=text, visible=True), gr.update(visible=False), gr.update(visible=False), gr.update(visible=False), gr.update(visible=True), gr.update(visible=False), gr.update(visible=False), gr.update(visible=True)
|
| | sleep(1)
|
| | elif i == 6 or i == 2:
|
| | yield gr.update(value=text, visible=True), gr.update(visible=False), gr.update(visible=False), gr.update(visible=False), gr.update(visible=False), gr.update(visible=True), gr.update(visible=True), gr.update(visible=False)
|
| | sleep(1)
|
| | else:
|
| | yield gr.update(value=text, visible=True), gr.update(visible=False), gr.update(visible=False), gr.update(visible=False), gr.update(visible=False), gr.update(visible=False), gr.update(visible=False), gr.update(visible=False)
|
| | sleep(0.7)
|
| |
|
| | for size in [4, 6, 8, 10, 13, 16, 20]:
|
| | text = f'''<div style="font-size:{size}em;text-align:center; color:red">ОШИБКА</div>'''
|
| | yield gr.update(value=text, visible=True), gr.update(visible=False), gr.update(visible=False), gr.update(visible=False), gr.update(visible=False), gr.update(visible=False), gr.update(visible=False), gr.update(visible=False)
|
| | sleep(0.4)
|
| |
|
| | base_text = f'''<div style="font-size:10em;text-align:center; color:red">ОШИБКА</div>'''
|
| | message = "Внимание, наша система зафиксировала на вашей фотографии признаки болезни, с кодовым названием С.К.У.Ф. и приостановила выдачу подарка. Чтобы подтвердить, что вы не скуф, пожалуйста, пройдите небольшой тест: contest.yandex.ru/contest/66428/enter"
|
| | current_text = ""
|
| | for latter in message:
|
| | current_text += latter
|
| | text = f'''{base_text}
|
| | <div style="font-size:4em;">{current_text}</div>'''
|
| | sleep(0.08)
|
| | yield gr.update(value=text), gr.update(visible=False), gr.update(visible=False), gr.update(visible=False), gr.update(visible=False), gr.update(visible=False), gr.update(visible=False), gr.update(visible=False)
|
| |
|
| |
|
| | return
|
| |
|
| | def get_demo():
|
| | with gr.Blocks(css=css) as demo:
|
| | text = gr.HTML('''<h1 style="font-size:5em;text-align:center;">Yarik Delivery</h1><div style="font-size:2em;text-align:center">Если вы попали на этот сайт, значит у вас был день рождения и ваши друзья подготовили вам подарок, поздравляем! Чтобы забрать свой подарок пожалуйста, пришлите вашу фотографию, чтобы система смогла распознать вас. <br><br> Имейте ввиду, что наша система поддерживает только фотографии, сделанные с <strong> видеокамеры, подаренной вашими друзьями</strong>.</div>
|
| | ''')
|
| | photo = gr.Image(label="Сделать фото", type="pil", height=300)
|
| | btn_clip = gr.Button("Отправить фото")
|
| | bar = gr.HTML("", visible=False)
|
| | error_message = gr.HTML(label="⚠️ Error ⚠️", visible=False)
|
| | with gr.Row():
|
| | with gr.Column():
|
| | im1 = gr.Image("skuf1.jpg", visible=False)
|
| | m1 = gr.HTML("", visible=False)
|
| | with gr.Column():
|
| | im2 = gr.Image("skuf2.png", visible=False)
|
| | m2 = gr.HTML("", visible=False)
|
| |
|
| | btn_clip.click(
|
| | fn=edit_bar,
|
| | inputs=[photo],
|
| | outputs=[bar, btn_clip, photo, error_message, im1, m1, im2, m2]
|
| | )
|
| | return demo
|
| |
|
| |
|
| | if __name__ == "__main__":
|
| | demo = get_demo()
|
| | demo.launch(server_name="0.0.0.0", server_port=7860) |