RMakushkin commited on
Commit
a18e62f
1 Parent(s): 56252f7

Upload 13 files

Browse files
.gitattributes CHANGED
@@ -33,3 +33,4 @@ saved_model/**/* filter=lfs diff=lfs merge=lfs -text
33
  *.zip filter=lfs diff=lfs merge=lfs -text
34
  *.zst filter=lfs diff=lfs merge=lfs -text
35
  *tfevents* filter=lfs diff=lfs merge=lfs -text
 
 
33
  *.zip filter=lfs diff=lfs merge=lfs -text
34
  *.zst filter=lfs diff=lfs merge=lfs -text
35
  *tfevents* filter=lfs diff=lfs merge=lfs -text
36
+ images/ser2.png filter=lfs diff=lfs merge=lfs -text
images/.DS_Store ADDED
Binary file (6.15 kB). View file
 
images/1.jpeg ADDED
images/2.jpeg ADDED
images/3.jpeg ADDED
images/4.jpeg ADDED
images/5.jpeg ADDED
images/mem.jpg ADDED
images/ser2.png ADDED

Git LFS Details

  • SHA256: 035a31442decd33706b2ffff57c59ef4a2363970e4c2c9e91d6a5efef4dd9191
  • Pointer size: 132 Bytes
  • Size of remote file: 1.34 MB
pages/.DS_Store ADDED
Binary file (6.15 kB). View file
 
pages/01_🎥_Serials.py ADDED
@@ -0,0 +1,105 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import streamlit as st
2
+ import pandas as pd
3
+ import numpy as np
4
+ import ast
5
+ import random
6
+ import torch
7
+ import time
8
+ from joblib import load
9
+
10
+ from transformers import BertTokenizer, BertModel
11
+ from sklearn.metrics.pairwise import cosine_similarity
12
+ # import faiss
13
+ """
14
+ ## Сервис умного поиска сериалов 📽️
15
+ """
16
+
17
+ # Читаем вектора сериалов
18
+ embeddings = np.loadtxt('data/embs.txt')
19
+ # Указываем пути к сохраненным модели и токенизатору
20
+ model_path = "model"
21
+ tokenizer_path = "tokenizer"
22
+ # Загружаем модель
23
+ loaded_model = BertModel.from_pretrained(model_path)
24
+ # Загружаем токенизатор
25
+ loaded_tokenizer = BertTokenizer.from_pretrained(tokenizer_path)
26
+
27
+ df = pd.read_csv('data/data.csv')
28
+ df['ganres'] = df['ganres'].apply(lambda x: ast.literal_eval(x))
29
+ df['description'] = df['description'].astype(str)
30
+
31
+ st.write(f'<p style="font-family: Arial, sans-serif; font-size: 24px; ">Наш сервис насчитывает \
32
+ {len(df)} лучших сериалов</p>', unsafe_allow_html=True)
33
+
34
+ st.image('images/ser2.png')
35
+
36
+ ganres_lst = sorted(['драма', 'документальный', 'биография', 'комедия', 'фэнтези', 'приключения', 'для детей', 'мультсериалы',
37
+ 'мелодрама', 'боевик', 'детектив', 'фантастика', 'триллер', 'семейный', 'криминал', 'исторический', 'музыкальные',
38
+ 'мистика', 'аниме', 'ужасы', 'спорт', 'скетч-шоу', 'военный', 'для взрослых', 'вестерн'])
39
+
40
+ st.sidebar.header('Панель инструментов :gear:')
41
+ choice_g = st.sidebar.multiselect("Выберите жанры", options=ganres_lst)
42
+ n = st.sidebar.selectbox("Количество отображаемых элементов на странице", options=[5, 10, 15, 20, 30])
43
+ st.sidebar.info("📚 Для наилучшего соответствия, запрос должен быть максимально развернутым")
44
+
45
+ text = st.text_input('Введите описание для рекомендации')
46
+
47
+ # Векторизуем запрос
48
+ loaded_model.eval()
49
+ tokens = loaded_tokenizer(text, return_tensors="pt", padding=True, truncation=True)
50
+ start_time = time.time()
51
+ tokens = {key: value.to(loaded_model.device) for key, value in tokens.items()}
52
+
53
+ # Передача токенов в модель для получения эмбеддингов
54
+ with torch.no_grad():
55
+ output = loaded_model(**tokens)
56
+
57
+ # Эмбеддинги получаются из последнего скрытого состояния
58
+ user_embedding = output.last_hidden_state.mean(dim=1).squeeze().cpu().detach().numpy()
59
+ cosine_similarities = cosine_similarity(embeddings, user_embedding.reshape(1, -1))
60
+
61
+ button = st.button('Отправить запрос', type="primary")
62
+
63
+ if text and button:
64
+
65
+ if len(choice_g) == 0:
66
+ choice_g = ganres_lst
67
+ # random = random.sample(range(len(df)), 50)
68
+ top_ind = np.unravel_index(np.argsort(cosine_similarities, axis=None)[-30:][::-1], cosine_similarities.shape)
69
+ confidence = cosine_similarities[top_ind]
70
+ top_ind = list(top_ind[0])
71
+ conf_dict = {}
72
+ for value, conf in zip(top_ind, confidence):
73
+ conf_dict[int(value)] = conf
74
+ # st.write(conf_dict)
75
+ output_dict = {}
76
+ for i in top_ind:
77
+ for ganre in df['ganres'][i]:
78
+ if ganre in choice_g:
79
+ output_dict[i] = df['ganres'][i]
80
+ # st.write('output_dict')
81
+ sorted_lst = sorted(output_dict.items(), key=lambda x: len(set(x[1]) & set(choice_g)), reverse=True)
82
+ n_lst = [i[0] for i in sorted_lst[:n]]
83
+ st.write(f'<p style="font-family: Arial, sans-serif; font-size: 18px; text-align: center;"><strong>Всего подобранных \
84
+ рекомендаций {len(sorted_lst)}</strong></p>', unsafe_allow_html=True)
85
+ st.write('\n')
86
+
87
+ # Отображение изображений и названий
88
+ for i in n_lst:
89
+ col1, col2 = st.columns([2, 5])
90
+ with col1:
91
+ st.image(df['poster'][i], width=200)
92
+ with col2:
93
+ st.write(f"***Название:*** {df['title'][i]}")
94
+ st.write(f"***Жанр:*** {', '.join(df['ganres'][i])}")
95
+ st.write(f"***Описание:*** {df['description'][i]}")
96
+ # similarity = float(confidence)
97
+ # st.write(f"***Cosine Similarity : {round(similarity, 3)}***")
98
+ st.markdown(f"[***ссылка на сериал***]({df['url'][i]})")
99
+ st.write(f"")
100
+ end_time = time.time()
101
+ st.write(f"<small>*Степень соответствия по косинусному сходству: {conf_dict[i]:.4f}*</small>", unsafe_allow_html=True)
102
+ st.markdown(
103
+ "<hr style='border: 2px solid #000; margin-top: 10px; margin-bottom: 10px;'>",
104
+ unsafe_allow_html=True
105
+ )
pages/02_🔥_Results.py ADDED
@@ -0,0 +1,34 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import streamlit as st
2
+ from PIL import Image, ImageOps
3
+ import matplotlib.pyplot as plt
4
+
5
+ st.write("""
6
+ ## 📝 Итоги проекта Рекомендательные системы.
7
+ """)
8
+ """
9
+ ###### 1. Парсинг профильных сайтов, итоговый с kino.mail.ru.
10
+ """
11
+
12
+ st.image('images/mem.jpg', width=400)
13
+
14
+ """
15
+ ###### 2. Сбор и анализ информации с киносервисов. Формирование датасета. Итоговый размер - 14939 объектов.
16
+ """
17
+ col1, col2 = st.columns(2)
18
+
19
+ with col1:
20
+ st.image('images/1.jpeg')
21
+
22
+ with col2:
23
+ st.image('images/2.jpeg')
24
+ # st.image('images/1.png')
25
+
26
+ """
27
+ ###### 3. Предобработка данных от лишных символов и пропусков.
28
+ """
29
+ st.image('images/3.jpeg')
30
+ st.image('images/4.jpeg')
31
+
32
+ """
33
+ ###### 4. Векторизация с использованием модели RuBERT (Russian, cased, 12-layer, 768-hidden, 12-heads, 180M parameters)
34
+ """
pages/__init__.py ADDED
File without changes
pages/__pycache__/__init__.cpython-310.pyc ADDED
Binary file (203 Bytes). View file