Spaces:
Sleeping
Sleeping
| 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) |