Spaces:
Sleeping
Sleeping
vvv-knyazeva
commited on
Commit
•
5f88b95
1
Parent(s):
4a74e03
Upload 3 files
Browse files- books_6000.csv +0 -0
- requirements(1).txt +6 -0
- stri.py +83 -0
books_6000.csv
ADDED
The diff for this file is too large to render.
See raw diff
|
|
requirements(1).txt
ADDED
@@ -0,0 +1,6 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
streamlit==1.23.1
|
2 |
+
torch==2.0.1
|
3 |
+
numpy==1.23.5
|
4 |
+
pandas==1.5.3
|
5 |
+
transformers==4.30.0
|
6 |
+
regex==2022.10.31
|
stri.py
ADDED
@@ -0,0 +1,83 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
import streamlit as st
|
2 |
+
import torch
|
3 |
+
import numpy as np
|
4 |
+
import pandas as pd
|
5 |
+
from transformers import AutoTokenizer, AutoModel
|
6 |
+
import re
|
7 |
+
|
8 |
+
st.title("Книжные рекомендации")
|
9 |
+
|
10 |
+
# Загрузка модели и токенизатора
|
11 |
+
model_name = "cointegrated/rubert-tiny2"
|
12 |
+
tokenizer = AutoTokenizer.from_pretrained(model_name)
|
13 |
+
model = AutoModel.from_pretrained(model_name, output_hidden_states=True)
|
14 |
+
|
15 |
+
# Загрузка датасета и аннотаций к книгам
|
16 |
+
books = pd.read_csv('books_6000.csv')
|
17 |
+
books.dropna(inplace=True)
|
18 |
+
|
19 |
+
|
20 |
+
books = books[books['annotation'].apply(lambda x: len(x.split()) >= 10)]
|
21 |
+
books.drop_duplicates(subset='title', keep='first', inplace=True)
|
22 |
+
books = books.reset_index(drop=True)
|
23 |
+
|
24 |
+
|
25 |
+
def data_preprocessing(text: str) -> str:
|
26 |
+
text = re.sub(r'http\S+', " ", text) # удаляем ссылки
|
27 |
+
text = re.sub(r'@\w+', ' ', text) # удаляем упоминания пользователей
|
28 |
+
text = re.sub(r'#\w+', ' ', text) # удаляем хэштеги
|
29 |
+
text = re.sub(r'<.*?>', ' ', text) # html tags
|
30 |
+
return text
|
31 |
+
|
32 |
+
|
33 |
+
for i in ['author', 'title', 'annotation']:
|
34 |
+
books[i] = books[i].apply(data_preprocessing)
|
35 |
+
|
36 |
+
annot = books['annotation']
|
37 |
+
|
38 |
+
# Получение эмбеддингов аннотаций каждой книги в датасете
|
39 |
+
max_len = 128
|
40 |
+
token_annot = annot.apply(lambda x: tokenizer.encode(x, add_special_tokens=True,
|
41 |
+
truncation=True, max_length=max_len))
|
42 |
+
|
43 |
+
padded = np.array([i + [0] * (max_len - len(i)) for i in token_annot.values]) # заполним недостающую длину нулями
|
44 |
+
attention_mask = np.where(padded != 0, 1, 0) # создадим маску, отметим где есть значения а где пустота
|
45 |
+
# Переведем numpy массивы в тензоры PyTorch
|
46 |
+
input_ids = torch.tensor(padded, dtype=torch.long)
|
47 |
+
attention_mask = torch.tensor(attention_mask, dtype=torch.long)
|
48 |
+
|
49 |
+
book_embeddings = []
|
50 |
+
for inputs, attention_masks in zip(input_ids, attention_mask):
|
51 |
+
with torch.no_grad():
|
52 |
+
book_embedding = model(inputs.unsqueeze(0), attention_mask=attention_masks.unsqueeze(0))
|
53 |
+
book_embedding = book_embedding[0][:, 0, :]#.detach().cpu().numpy()
|
54 |
+
book_embeddings.append(np.squeeze(book_embedding))
|
55 |
+
|
56 |
+
# Определение запроса пользователя
|
57 |
+
query = st.text_input("Введите запрос")
|
58 |
+
query_tokens = tokenizer.encode(query, add_special_tokens=True,
|
59 |
+
truncation=True, max_length=max_len)
|
60 |
+
|
61 |
+
query_padded = np.array(query_tokens + [0] * (max_len - len(query_tokens)))
|
62 |
+
query_mask = np.where(query_padded != 0, 1, 0)
|
63 |
+
|
64 |
+
# Переведем numpy массивы в тензоры PyTorch
|
65 |
+
query_padded = torch.tensor(query_padded, dtype=torch.long)
|
66 |
+
query_mask = torch.tensor(query_mask, dtype=torch.long)
|
67 |
+
|
68 |
+
with torch.no_grad():
|
69 |
+
query_embedding = model(query_padded.unsqueeze(0), query_mask.unsqueeze(0))
|
70 |
+
query_embedding = query_embedding[0][:, 0, :].detach().cpu().numpy()
|
71 |
+
|
72 |
+
# Вычисление косинусного расстояния между эмбеддингом запроса и каждой аннотацией
|
73 |
+
cosine_similarities = torch.nn.functional.cosine_similarity(
|
74 |
+
query_embedding.squeeze(0),
|
75 |
+
torch.stack(book_embeddings)
|
76 |
+
)
|
77 |
+
|
78 |
+
cosine_similarities = cosine_similarities.numpy()
|
79 |
+
|
80 |
+
indices = np.argsort(cosine_similarities)[::-1] # Сортировка по убыванию
|
81 |
+
|
82 |
+
for i in indices[:10]:
|
83 |
+
st.write(books['title'][i])
|