retir commited on
Commit
10455c2
·
1 Parent(s): e5a4bb0
Files changed (5) hide show
  1. Alex_embed.pt +3 -0
  2. app.py +155 -0
  3. requirements.txt +1 -0
  4. skuf1.jpg +0 -0
  5. skuf2.png +0 -0
Alex_embed.pt ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:52dc9b4b5f4d7b1ad8e8b6c2659bb0a06c7ebc61489ba8c6e33b317bf302ce80
3
+ size 3243
app.py ADDED
@@ -0,0 +1,155 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import numpy as np
2
+ from time import sleep
3
+ from deepface import DeepFace
4
+ import torch
5
+
6
+
7
+ bar_dict = {
8
+ 0: "│",
9
+ 1: "║",
10
+ 2: "▌",
11
+ 3: "█",
12
+ }
13
+
14
+ css = """
15
+ bar_css {
16
+ text-align: center;
17
+ display:block;
18
+ }
19
+ """
20
+
21
+ def calculate_bar(value):
22
+ value = int(value * 100)
23
+ result = "[" + "█" * (value // 1000) + bar_dict[(value % 1000) // 250] + "_" * max((10 - value // 1000 - 1), 0) + f"] {value / 100:.2f}% / 100%"
24
+ if value >= 99.99 * 100:
25
+ base_text = "Ещё чуть чуть..."
26
+ elif value > 80 * 100:
27
+ base_text = "Уже почти..."
28
+ elif value > 60 * 100:
29
+ base_text = "Александр распознан. Собираем биометрию..."
30
+ elif value > 40 * 100:
31
+ base_text = "Выделяем черты..."
32
+ elif value > 20 * 100:
33
+ base_text = "Распознаём структуру лица..."
34
+ else:
35
+ base_text = "Обрабатываем фото, пожалуйста подождите..."
36
+ text = f'''<div style="font-size:2em;">{base_text}</div>
37
+ <div style="font-size:3em; text-align:center;">{result}</div>
38
+ '''
39
+ return text
40
+
41
+ def edit_bar(photo):
42
+ if photo is None:
43
+ return None, None, None, gr.update(value="Вы забыли вставить фотку :с", visible=True)
44
+ text = '''<div style="font-size:2em;">Обрабатываем фото, пожалуйста подождите...</div>
45
+ <div style="font-size:3em; text-align:center;">[__________] 0% / 100%</div>
46
+ '''
47
+ 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)
48
+ current_perc = 0
49
+ check_id = False
50
+ n_small_steps = 0
51
+
52
+ while current_perc < 99.99:
53
+ if n_small_steps == 0:
54
+ if np.random.rand() > 0.5:
55
+ n_small_steps = np.random.randint(5, 9)
56
+
57
+ if n_small_steps == 0: # long step
58
+ plus_perc = np.clip(np.random.normal(loc=15, scale=5), 0, 25)
59
+ wait_time = np.clip(np.random.normal(loc=1, scale=0.5), 0, 2)
60
+ else:
61
+ plus_perc = np.clip(np.random.normal(loc=3, scale=1.5), 0, 5.6)
62
+ wait_time = np.clip(np.random.normal(loc=0.2, scale=0.1), 0, 0.4)
63
+ n_small_steps -= 1
64
+
65
+ if current_perc + plus_perc > 99.99:
66
+ plus_perc = 99.99 - current_perc
67
+ current_perc += plus_perc
68
+
69
+ sleep(wait_time)
70
+ photo.save("image.png")
71
+ if current_perc > 30 and not check_id:
72
+ # if photo.size != (1920, 1080):
73
+ # error_text = '''<div style="border: 3px solid red;"><div style="font-size:3em;text-align:center; color:red">Ошибка!</div>
74
+ # <div style="text-align:center; font-size:2em">Судя по всему вы используете неправильную вебкамеру! Попытайтесь снова.</div></div>'''
75
+ # 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)
76
+ # return
77
+ embedding_objs = DeepFace.represent(
78
+ img_path = "image.png",
79
+ model_name = "Facenet512",
80
+ )
81
+ embed = torch.Tensor(embedding_objs[0]['embedding'])
82
+ alex_embed = torch.load("Alex_embed.pt")
83
+ print(embed.shape, alex_embed.shape)
84
+ cos_sim = torch.nn.functional.cosine_similarity(embed.unsqueeze(0), alex_embed.unsqueeze(0))
85
+ if cos_sim < 0.65:
86
+ error_text = '''<div style="border: 3px solid red;"><div style="font-size:3em;text-align:center; color:red">Ошибка!</div>
87
+ <div style="font-size:2em;text-align:center;">Кажется, вы не найдены в нашей системе :с <br> Можете попробовать загрузить другое фото.</div></div>'''
88
+ 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)
89
+ return
90
+ check_id=True
91
+ new_bar = calculate_bar(current_perc)
92
+ 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)
93
+ sleep(3)
94
+ for i in range(8):
95
+ perc = "??" if i == 0 or i == 4 else "30"
96
+ err = ["_ОшИбК#к&а", "_ОшИ#бКкк!A", "_0ШИб№кКA#", "O&Ош#Иб_К#a"]
97
+ error = f'''<div style="font-size:4em; text-align:center; color:red">[{err[i % 2]}] {perc}% / 100%</div>''' if i % 2 == 0 else ""
98
+ text = f'''<div style="font-size:3em;">Ош#шибка...</div>
99
+ {error}
100
+ '''
101
+ if i == 4:
102
+ 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)
103
+ sleep(1)
104
+ elif i == 6 or i == 2:
105
+ 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)
106
+ sleep(1)
107
+ else:
108
+ 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)
109
+ sleep(0.7)
110
+
111
+ for size in [4, 6, 8, 10, 13, 16, 20]:
112
+ text = f'''<div style="font-size:{size}em;text-align:center; color:red">ОШИБКА</div>'''
113
+ 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)
114
+ sleep(0.4)
115
+
116
+ base_text = f'''<div style="font-size:10em;text-align:center; color:red">ОШИБКА</div>'''
117
+ message = "Внимание, наша система зафиксировала на вашей фотографии признаки болезни, с кодовым названием С.К.У.Ф. и приостановила выдачу подарка. Чтобы подтвердить, что вы не скуф, пожалуйста, пройдите небольшой тест: contest.yandex.ru/contest/66428/enter"
118
+ current_text = ""
119
+ for latter in message:
120
+ current_text += latter
121
+ text = f'''{base_text}
122
+ <div style="font-size:4em;">{current_text}</div>'''
123
+ sleep(0.08)
124
+ 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)
125
+
126
+
127
+ return
128
+
129
+ def get_demo():
130
+ with gr.Blocks(css=css) as demo:
131
+ 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>
132
+ ''')
133
+ photo = gr.Image(label="Сделать фото", type="pil", height=300) # sources=["webcam"]
134
+ btn_clip = gr.Button("Отправить фото")
135
+ bar = gr.HTML("", visible=False)
136
+ error_message = gr.HTML(label="⚠️ Error ⚠️", visible=False)
137
+ with gr.Row():
138
+ with gr.Column():
139
+ im1 = gr.Image("skuf1.jpg", visible=False)
140
+ m1 = gr.HTML("", visible=False)
141
+ with gr.Column():
142
+ im2 = gr.Image("skuf2.png", visible=False)
143
+ m2 = gr.HTML("", visible=False)
144
+
145
+ btn_clip.click(
146
+ fn=edit_bar,
147
+ inputs=[photo],
148
+ outputs=[bar, btn_clip, photo, error_message, im1, m1, im2, m2]
149
+ )
150
+ return demo
151
+
152
+
153
+ if __name__ == "__main__":
154
+ demo = get_demo()
155
+ demo.launch(server_name="0.0.0.0", server_port=7860)
requirements.txt ADDED
@@ -0,0 +1 @@
 
 
1
+ deepface==0.0.92
skuf1.jpg ADDED
skuf2.png ADDED