File size: 9,352 Bytes
73af5b7 10455c2 91298fc 88ea329 10455c2 91298fc 10455c2 |
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 |
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: # long step
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:
# if photo.size != (1920, 1080):
# 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
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) # sources=["webcam"]
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) |