Spaces:
Sleeping
Sleeping
File size: 15,063 Bytes
73af5b7 10455c2 3e7f477 10455c2 3e7f477 b07b662 4575782 3e7f477 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 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 |
import gradio as gr
import numpy as np
from time import sleep
from deepface import DeepFace
from PIL import Image
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 photo.size == (1200, 900):
key = Image.open("key.png")
if np.mean((np.array(photo).astype(np.float64) - np.array(key).astype(np.float64))**2) < 10:
base_message = "Ключ распознан"
current_base_text = ""
for latter in base_message:
current_base_text += latter
base_text = f'''<div style="font-size:7em;text-align:center">{current_base_text}</div>'''
sleep(0.15)
yield gr.update(value=base_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)
base_text = f'''<div style="font-size:7em;text-align:center">Ключ распознан</div>'''
base_message2 = "Поздравляю, Александр, вы на последней задаче. Надеюсь, что вы найдёте точку старта, оттуда и начнётся ваш путь:"
current_base_text2 = ""
for latter in base_message2:
current_base_text2 += latter
text = f'''{base_text}
<div style="font-size:3em;">{current_base_text2}</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)
messages = [
"Путь свой начнёшь ты из дверей места святого —",
"Иди 10 метров вперёд и 30 налево.",
"Встань так, чтобы слева от тебя дух божественный обитал",
"А по правую руку дьявол праздный, что разум затуманивает.",
"Иди вперёд, да по сторонам не смотри, пока не дойдёшь до развилки двухтропинной:",
"Налево пойдёшь — золотую рыбку найдёшь, направо пойдёшь — подарок обретёшь.",
"С выбранного пути не сворачивай, пока перепутье не увидишь,",
"За перепутьем — дом солнечный, но тебе туда пока рано.",
"Налево поверни да по дороге прямо ступай,",
"Слева от тебя — купцы заморские, справа — тоже купцы, а за ними — место,",
"Где лучится не только душа твоя, но и тело.",
"С тропы в глубь джунглей не сворачивай, иди пока перекрестие не увидишь:",
"Прямо пойдёшь — культурно обогатишься, ",
"Налево свернёшь — к месту большого ума выйдешь,",
"Направо путь свой проложишь — друзьям угодишь.",
"Продолжай свой путь мимо места жизни обретения, да мимо полена каменного,",
"Вперёд иди, пока слева твоему взору не предстанет купец технологий заморских,",
"А спереди — Альянс местный.",
"Сверни влево, да прямо иди мимо заведений итальянских,",
"Как увидишь куриного барона, проходи до конца его владений.",
"Ищи крышку алую, туда тебе путь и лежит.",
]
current_mesages = []
base_text = f'''<div style="font-size:7em;text-align:center">Ключ распознан</div>
<div style="font-size:3em;">Поздравляю, Александр, вы на последней задаче. Надеюсь, что вы найдёте точку старта, оттуда и начнётся ваш путь:</div>
'''
for line in messages:
current_mesages.append("")
for ch in line:
current_mesages[-1] = current_mesages[-1] + ch
current_text = "<br>".join(current_mesages)
text = f'''{base_text}<br>
<div style="font-size:2em;">{current_text}</div>'''
sleep(0.03)
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)
APPEARANCE_TIME = "18:00 9 августа 2024 года" # не баг, а фича!
new_text = "Выйди заранее, и помни, что у места ты должен быть в {APPEARANCE_TIME}, не опаздывай!"
current_text2 = ""
for latter in new_text:
current_text2 += latter
current_text = "<br>".join(current_mesages)
text = f'''{base_text}<br>
<div style="font-size:2em;">{current_text}</div><br>
<div style="font-size:3em;">{current_text2}</div><br>'''
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
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) |