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|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
import streamlit as st
|
2 |
+
import cv2
|
3 |
+
import json
|
4 |
+
import os
|
5 |
+
import re
|
6 |
+
from datetime import datetime
|
7 |
+
from io import BytesIO
|
8 |
+
|
9 |
+
import requests
|
10 |
+
import shutil
|
11 |
+
import vk_api
|
12 |
+
from bs4 import BeautifulSoup
|
13 |
+
from deepface import DeepFace
|
14 |
+
from googletrans import Translator
|
15 |
+
from reportlab.lib import colors
|
16 |
+
from reportlab.lib.pagesizes import letter
|
17 |
+
from reportlab.lib.styles import getSampleStyleSheet
|
18 |
+
from reportlab.platypus import Image, SimpleDocTemplate, Table, TableStyle
|
19 |
+
from ultralytics import YOLO
|
20 |
+
|
21 |
+
with open('/Users/brasd99/Documents/Others/AFL-Face-Checker/config.json', 'r') as f:
|
22 |
+
config = json.load(f)
|
23 |
+
|
24 |
+
FACE_DET_TRESH = config['FACE_DET_TRESH']
|
25 |
+
FACE_DIST_TRESH = config['FACE_DIST_TRESH']
|
26 |
+
YOLO_WEIGHTS_URL = config['YOLO_WEIGHTS_URL']
|
27 |
+
AVATARS_URI = config['AVATARS_URI']
|
28 |
+
APP_NAME = config['APP_NAME']
|
29 |
+
APP_DESCRIPTION = config['APP_DESCRIPTION']
|
30 |
+
|
31 |
+
def load_detector():
|
32 |
+
yolo_weights_filename = os.path.basename(YOLO_WEIGHTS_URL)
|
33 |
+
|
34 |
+
if not os.path.exists(yolo_weights_filename):
|
35 |
+
response = requests.get(YOLO_WEIGHTS_URL)
|
36 |
+
with open(yolo_weights_filename, "wb") as file:
|
37 |
+
file.write(response.content)
|
38 |
+
|
39 |
+
return YOLO(yolo_weights_filename)
|
40 |
+
|
41 |
+
model = load_detector()
|
42 |
+
|
43 |
+
styles = getSampleStyleSheet()
|
44 |
+
style_table = TableStyle([
|
45 |
+
('BACKGROUND', (0, 0), (-1, 0), colors.grey),
|
46 |
+
('TEXTCOLOR', (0, 0), (-1, 0), colors.whitesmoke),
|
47 |
+
('ALIGN', (0, 0), (-1, -1), 'CENTER'),
|
48 |
+
('FONTNAME', (0, 0), (-1, 0), 'Helvetica-Bold'),
|
49 |
+
('FONTSIZE', (0, 0), (-1, 0), 14),
|
50 |
+
('BOTTOMPADDING', (0, 0), (-1, 0), 12),
|
51 |
+
('BACKGROUND', (0, 1), (-1, -1), colors.beige),
|
52 |
+
('GRID', (0, 0), (-1, -1), 1, colors.black),
|
53 |
+
])
|
54 |
+
|
55 |
+
def parse_album(data):
|
56 |
+
album_info = data['NGRX_STATE']['game']['info']['data']['photoSetUrl']
|
57 |
+
album_info = album_info.split("-")[-1].split("_")
|
58 |
+
owner_id = - int(album_info[0])
|
59 |
+
album_id = int(album_info[1])
|
60 |
+
return owner_id, album_id
|
61 |
+
|
62 |
+
def get_photos(owner_id, album_id, vk):
|
63 |
+
offset = 0
|
64 |
+
total_count = float('inf')
|
65 |
+
count_per_request = 50
|
66 |
+
|
67 |
+
output = []
|
68 |
+
|
69 |
+
while offset < total_count:
|
70 |
+
params = {
|
71 |
+
'owner_id': owner_id,
|
72 |
+
'album_id': album_id,
|
73 |
+
'count': count_per_request,
|
74 |
+
'offset': offset,
|
75 |
+
'extended': '1'
|
76 |
+
}
|
77 |
+
|
78 |
+
response = vk.photos.get(**params)
|
79 |
+
|
80 |
+
for item in response['items']:
|
81 |
+
max_item = max(item['sizes'], key=lambda item: item['height'])
|
82 |
+
output.append(max_item['url'])
|
83 |
+
|
84 |
+
total_count = response['count']
|
85 |
+
offset += count_per_request
|
86 |
+
|
87 |
+
return output
|
88 |
+
|
89 |
+
def download_images(photos, players):
|
90 |
+
current_datetime = datetime.now()
|
91 |
+
folder_name = current_datetime.strftime("%Y-%m-%d_%H-%M-%S")
|
92 |
+
os.mkdir(folder_name)
|
93 |
+
|
94 |
+
players_path = os.path.join(folder_name, 'players')
|
95 |
+
photos_path = os.path.join(folder_name, 'photos')
|
96 |
+
temp_path = os.path.join(folder_name, 'temp')
|
97 |
+
|
98 |
+
os.mkdir(players_path)
|
99 |
+
os.mkdir(photos_path)
|
100 |
+
os.mkdir(temp_path)
|
101 |
+
|
102 |
+
update_progress(0, 'Downloading photos...')
|
103 |
+
for i, photo_url in enumerate(photos):
|
104 |
+
filename = f'{i}.jpg'
|
105 |
+
response = requests.get(photo_url)
|
106 |
+
with open(os.path.join(photos_path, filename), "wb") as file:
|
107 |
+
file.write(response.content)
|
108 |
+
update_progress((i+1)/len(photos), 'Downloading photos...')
|
109 |
+
|
110 |
+
for team_state in players.keys():
|
111 |
+
update_progress(0, f"Downloading {team_state} players' avatars...")
|
112 |
+
for i, player in enumerate(players[team_state]):
|
113 |
+
filename = f"{player['id']}.jpg"
|
114 |
+
response = requests.get(player['avatar_url'])
|
115 |
+
with open(os.path.join(players_path, filename), "wb") as file:
|
116 |
+
file.write(response.content)
|
117 |
+
update_progress((i+1)/len(players[team_state]), f"Downloading {team_state} players' avatars...")
|
118 |
+
|
119 |
+
return {
|
120 |
+
'photos_path': photos_path,
|
121 |
+
'players_path': players_path,
|
122 |
+
'temp_path': temp_path,
|
123 |
+
'folder_name': folder_name
|
124 |
+
}
|
125 |
+
|
126 |
+
def find_photos(data, vk):
|
127 |
+
pattern = re.compile('<script id="axl-desktop-state" type="application/json">(.+?)</script>')
|
128 |
+
script_content = pattern.search(data).group(1).replace('&q;', '"')
|
129 |
+
|
130 |
+
data = json.loads(script_content)
|
131 |
+
|
132 |
+
owner_id, album_id = parse_album(data)
|
133 |
+
|
134 |
+
return get_photos(owner_id, album_id, vk)
|
135 |
+
|
136 |
+
def translate(text):
|
137 |
+
translator = Translator()
|
138 |
+
output = translator.translate(text, src='ru', dest='en')
|
139 |
+
return output.text
|
140 |
+
|
141 |
+
def get_players(data):
|
142 |
+
output = {}
|
143 |
+
team_states = ['home', 'away']
|
144 |
+
soup = BeautifulSoup(data, 'lxml')
|
145 |
+
|
146 |
+
for team_state in team_states:
|
147 |
+
update_progress(0, f'Getting information about {team_state} players...')
|
148 |
+
output[team_state] = []
|
149 |
+
player_roots = soup.find_all("div", {"class": f"{team_state} ng-star-inserted"})
|
150 |
+
for i, player_root in enumerate(player_roots):
|
151 |
+
player_info = player_root.find("a", {"class": "wrapper ng-star-inserted"})
|
152 |
+
id = re.findall(r'\d+', player_info['href'])[-1]
|
153 |
+
avatar_url = AVATARS_URI.replace("PLAYER_ID", id)
|
154 |
+
name = player_info.find("span", {"class": "name"}).get_text()
|
155 |
+
name = translate(name)
|
156 |
+
position = player_info.find("span", {"class": "position"}).get_text()
|
157 |
+
output[team_state].append({
|
158 |
+
'id': id,
|
159 |
+
'name': name,
|
160 |
+
'position': position,
|
161 |
+
'avatar_url': avatar_url
|
162 |
+
})
|
163 |
+
update_progress((i+1)/len(player_roots), f'Getting information about {team_state} players...')
|
164 |
+
|
165 |
+
return output
|
166 |
+
|
167 |
+
def load_players_avatars(players, images_path, face_det_tresh):
|
168 |
+
for team_state in players.keys():
|
169 |
+
update_progress(0, f'Reading avatars of {team_state} team...')
|
170 |
+
for i, player in enumerate(players[team_state]):
|
171 |
+
image_name = f"{player['id']}.jpg"
|
172 |
+
player['image'] = read_image_from_path(os.path.join(images_path, image_name))
|
173 |
+
faces = find_faces(player['image'], face_det_tresh)
|
174 |
+
if faces:
|
175 |
+
player['face'] = faces[0]
|
176 |
+
|
177 |
+
update_progress((i+1)/len(players[team_state]), f'Reading avatars of {team_state} team...')
|
178 |
+
|
179 |
+
return players
|
180 |
+
|
181 |
+
def find_distance(base_face, check_face):
|
182 |
+
result = DeepFace.verify(base_face, check_face, enforce_detection=False)
|
183 |
+
return result['distance']
|
184 |
+
|
185 |
+
def read_image_from_path(path):
|
186 |
+
return cv2.imread(path)
|
187 |
+
|
188 |
+
def read_images_from_path(path):
|
189 |
+
images = []
|
190 |
+
|
191 |
+
files = os.listdir(path)
|
192 |
+
update_progress(0, 'Reading photos...')
|
193 |
+
|
194 |
+
for i, filename in enumerate(files):
|
195 |
+
if filename.endswith(".jpg"):
|
196 |
+
image = read_image_from_path(os.path.join(path, filename))
|
197 |
+
|
198 |
+
if image is not None:
|
199 |
+
images.append(image)
|
200 |
+
|
201 |
+
update_progress((i+1)/len(files), 'Reading photos...')
|
202 |
+
|
203 |
+
return images
|
204 |
+
|
205 |
+
def cv2_to_reportlab(cv2_image):
|
206 |
+
buffer = BytesIO()
|
207 |
+
_, buffer = cv2.imencode(".jpg", cv2_image)
|
208 |
+
io_buf = BytesIO(buffer)
|
209 |
+
return Image(io_buf)
|
210 |
+
|
211 |
+
def find_faces(image, face_det_tresh):
|
212 |
+
outputs = model(image)
|
213 |
+
faces = []
|
214 |
+
for box in outputs[0].boxes:
|
215 |
+
if float(box.conf) >= face_det_tresh:
|
216 |
+
x, y, w, h = [int(coord) for coord in box.xywh[0]]
|
217 |
+
x_center, y_center = x + w / 2, y + h / 2
|
218 |
+
x1 = int(x_center - w)
|
219 |
+
y1 = int(y_center - h)
|
220 |
+
crop_img = image[y1:y1+h, x1:x1+w]
|
221 |
+
faces.append(crop_img)
|
222 |
+
return faces
|
223 |
+
|
224 |
+
def is_face_exists(players, face, face_dist_tresh):
|
225 |
+
for team_state in players.keys():
|
226 |
+
for player in players[team_state]:
|
227 |
+
if 'face' in player:
|
228 |
+
distance = find_distance(player['face'], face)
|
229 |
+
if distance <= face_dist_tresh:
|
230 |
+
return player['id'], player['face']
|
231 |
+
return None, None
|
232 |
+
|
233 |
+
def add_players_table(elements, players):
|
234 |
+
data = [
|
235 |
+
["Player ID", "Name", "Position", "Avatar", "Face"]
|
236 |
+
]
|
237 |
+
for team_state in players.keys():
|
238 |
+
update_progress(0, f"Creating dump of {team_state}'s squad...")
|
239 |
+
for i, player in enumerate(players[team_state]):
|
240 |
+
face = cv2_to_reportlab(player['face'])
|
241 |
+
avatar = cv2_to_reportlab(player['image'])
|
242 |
+
line = [
|
243 |
+
player['id'],
|
244 |
+
player['name'],
|
245 |
+
player['position'],
|
246 |
+
avatar,
|
247 |
+
face
|
248 |
+
]
|
249 |
+
data.append(line)
|
250 |
+
update_progress((i+1)/len(players[team_state]), f"Creating dump of {team_state}'s squad...")
|
251 |
+
|
252 |
+
# Create the table
|
253 |
+
table = Table(data)
|
254 |
+
table.setStyle(style_table)
|
255 |
+
elements.append(table)
|
256 |
+
|
257 |
+
return elements
|
258 |
+
|
259 |
+
def check_faces(elements, photos, players, face_det_tresh, face_dist_tresh):
|
260 |
+
data = [
|
261 |
+
["Face", "Player ID", "Player Face"]
|
262 |
+
]
|
263 |
+
|
264 |
+
update_progress(0, 'Comparing faces...')
|
265 |
+
for i, photo in enumerate(photos):
|
266 |
+
faces = find_faces(photo, face_det_tresh)
|
267 |
+
for j, face in enumerate(faces):
|
268 |
+
player_id, player_face = is_face_exists(players, face, face_dist_tresh)
|
269 |
+
face = cv2_to_reportlab(face)
|
270 |
+
tmp_arr = [face, player_id]
|
271 |
+
if player_face is not None:
|
272 |
+
player_face = cv2_to_reportlab(player_face)
|
273 |
+
tmp_arr.append(player_face)
|
274 |
+
data.append(tmp_arr)
|
275 |
+
update_progress((j+1)/len(faces), 'Comparing faces...')
|
276 |
+
# Create the table
|
277 |
+
table = Table(data)
|
278 |
+
table.setStyle(style_table)
|
279 |
+
|
280 |
+
# Add table to elements list
|
281 |
+
elements.append(table)
|
282 |
+
|
283 |
+
return elements
|
284 |
+
|
285 |
+
def update_progress(percent, description):
|
286 |
+
progress_bar.progress(percent)
|
287 |
+
progress_status_text.text(description)
|
288 |
+
|
289 |
+
|
290 |
+
def process(token, afl_link, face_dist_tresh, face_det_tresh):
|
291 |
+
update_progress(0, 'Connecting to vk...')
|
292 |
+
vk_session = vk_api.VkApi(token=token)
|
293 |
+
vk = vk_session.get_api()
|
294 |
+
update_progress(100, 'Connected to vk')
|
295 |
+
|
296 |
+
update_progress(0, 'Getting information from afl...')
|
297 |
+
response = requests.get(afl_link)
|
298 |
+
update_progress(100, 'Got information from afl')
|
299 |
+
|
300 |
+
update_progress(0, 'Getting information about photos...')
|
301 |
+
photos = find_photos(response.text, vk)
|
302 |
+
update_progress(100, 'Got information about photos')
|
303 |
+
|
304 |
+
players = get_players(response.text)
|
305 |
+
result = download_images(photos, players)
|
306 |
+
photos = read_images_from_path(result['photos_path'])
|
307 |
+
players = load_players_avatars(players, result['players_path'], face_det_tresh)
|
308 |
+
|
309 |
+
table_file = os.path.join(result['temp_path'], 'table.pdf')
|
310 |
+
|
311 |
+
doc = SimpleDocTemplate(table_file, pagesize=letter)
|
312 |
+
|
313 |
+
elements = []
|
314 |
+
elements = check_faces(elements, photos, players, face_det_tresh, face_dist_tresh)
|
315 |
+
elements = add_players_table(elements, players)
|
316 |
+
|
317 |
+
doc.build(elements)
|
318 |
+
|
319 |
+
with open(table_file, 'rb') as file:
|
320 |
+
pdf_bytes = file.read()
|
321 |
+
|
322 |
+
shutil.rmtree(result['folder_name'])
|
323 |
+
|
324 |
+
return pdf_bytes
|
325 |
+
|
326 |
+
|
327 |
+
|
328 |
+
st.set_page_config(page_title='New App Name')
|
329 |
+
st.title("My Awesome App")
|
330 |
+
|
331 |
+
# Add a logo to the sidebar
|
332 |
+
logo_url = "https://example.com/logo.png" # URL or local file path of your logo image
|
333 |
+
st.sidebar.image(logo_url, width=100)
|
334 |
+
|
335 |
+
# Add a description in the sidebar
|
336 |
+
app_description = "This is a description of my app."
|
337 |
+
st.sidebar.write(app_description)
|
338 |
+
|
339 |
+
# Get the user input
|
340 |
+
access_token = st.text_input("Your VK API access token")
|
341 |
+
|
342 |
+
# Define the description and hyperlink
|
343 |
+
description = "You can obtain your token from"
|
344 |
+
link = "https://vkhost.github.io/"
|
345 |
+
|
346 |
+
# Create the Markdown string with the hyperlink
|
347 |
+
markdown_str = f"{description}: [{link}]({link})"
|
348 |
+
|
349 |
+
# Display the description with the hyperlink
|
350 |
+
st.markdown(markdown_str)
|
351 |
+
|
352 |
+
afl_url = st.text_input("AFL url")
|
353 |
+
description = "Example"
|
354 |
+
link = "https://afl.ru/football/afl-moscow-8x8/afl-cup-krasnaya-presnya-3097/matches/463676"
|
355 |
+
markdown_str = f"{description}: [{link}]({link})"
|
356 |
+
st.markdown(markdown_str)
|
357 |
+
|
358 |
+
face_det_tresh = st.slider('Select a value:', 0.0, 1.0, FACE_DET_TRESH, 0.1)
|
359 |
+
face_dist_tresh = st.slider('Select a value:', 0.0, 1.0, FACE_DIST_TRESH, 0.1)
|
360 |
+
|
361 |
+
button_clicked = st.button("Process")
|
362 |
+
|
363 |
+
if button_clicked:
|
364 |
+
progress_bar = st.progress(0)
|
365 |
+
progress_status_text = st.empty()
|
366 |
+
pdf_bytes = process(access_token, afl_url, face_det_tresh, face_dist_tresh)
|
367 |
+
st.download_button(label='Download PDF', data=pdf_bytes, file_name='output.pdf')
|
config.json
ADDED
@@ -0,0 +1,8 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
{
|
2 |
+
"FACE_DIST_TRESH": 0.1,
|
3 |
+
"FACE_DET_TRESH": 0.3,
|
4 |
+
"YOLO_WEIGHTS_URL": "https://github.com/akanametov/yolov8-face/releases/download/v0.0.0/yolov8n-face.pt",
|
5 |
+
"AVATARS_URI": "https://6ff87ac8-1c01-4a5d-8145-f60a24de5ae8.selcdn.net/api/img/players/PLAYER_ID.jpg?version=0",
|
6 |
+
"APP_NAME": "AFL-Face-Checker",
|
7 |
+
"APP_DESCRIPTION": "This service helps to check faces from photos!"
|
8 |
+
}
|
requirements.txt
ADDED
@@ -0,0 +1,8 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
deepface
|
2 |
+
ultralytics
|
3 |
+
googletrans==3.1.0a0
|
4 |
+
reportlab
|
5 |
+
vk_api
|
6 |
+
beautifulsoup4
|
7 |
+
omegaconf
|
8 |
+
lxml
|