Spaces:
Runtime error
Runtime error
Update stri.py
Browse files
stri.py
CHANGED
|
@@ -3,6 +3,7 @@ import torch
|
|
| 3 |
import numpy as np
|
| 4 |
import pandas as pd
|
| 5 |
from transformers import AutoTokenizer, AutoModel
|
|
|
|
| 6 |
|
| 7 |
st.title("Книжные рекомендации")
|
| 8 |
|
|
@@ -13,53 +14,73 @@ model = AutoModel.from_pretrained(model_name, output_hidden_states=True)
|
|
| 13 |
|
| 14 |
# Загрузка датасета и аннотаций к книгам
|
| 15 |
books = pd.read_csv('book_train.csv')
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 16 |
annot = books['annotation']
|
| 17 |
|
| 18 |
-
#
|
| 19 |
-
|
| 20 |
-
|
| 21 |
-
|
| 22 |
-
|
| 23 |
-
|
| 24 |
-
|
| 25 |
-
|
| 26 |
-
|
| 27 |
-
|
| 28 |
-
|
| 29 |
-
with torch.no_grad():
|
| 30 |
-
outputs = model(**annotation_tokens)
|
| 31 |
-
hidden_states = outputs.hidden_states
|
| 32 |
-
last_hidden_state = hidden_states[-1]
|
| 33 |
-
embeddings.append(torch.mean(last_hidden_state, dim=1).squeeze())
|
| 34 |
-
|
| 35 |
-
# Получение эмбеддинга запроса от пользователя
|
| 36 |
-
query = st.text_input("Введите запрос")
|
| 37 |
-
query_tokens = tokenizer.encode_plus(
|
| 38 |
-
query,
|
| 39 |
-
add_special_tokens=True,
|
| 40 |
-
max_length=128,
|
| 41 |
-
pad_to_max_length=True,
|
| 42 |
-
return_tensors='pt'
|
| 43 |
-
)
|
| 44 |
|
| 45 |
-
# Проверка, был ли введен запрос
|
| 46 |
-
if query:
|
| 47 |
-
with torch.no_grad():
|
| 48 |
-
query_outputs = model(**query_tokens)
|
| 49 |
-
query_hidden_states = query_outputs.hidden_states
|
| 50 |
-
query_last_hidden_state = query_hidden_states[-1]
|
| 51 |
-
query_embedding = torch.mean(query_last_hidden_state, dim=1).squeeze()
|
| 52 |
|
| 53 |
-
|
| 54 |
-
|
| 55 |
-
|
| 56 |
-
|
| 57 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 58 |
|
| 59 |
-
|
| 60 |
|
| 61 |
-
|
| 62 |
|
| 63 |
-
|
| 64 |
-
|
| 65 |
-
st.write(books['title'][i])
|
|
|
|
| 3 |
import numpy as np
|
| 4 |
import pandas as pd
|
| 5 |
from transformers import AutoTokenizer, AutoModel
|
| 6 |
+
import re
|
| 7 |
|
| 8 |
st.title("Книжные рекомендации")
|
| 9 |
|
|
|
|
| 14 |
|
| 15 |
# Загрузка датасета и аннотаций к книгам
|
| 16 |
books = pd.read_csv('book_train.csv')
|
| 17 |
+
books.dropna(inplace=True)
|
| 18 |
+
|
| 19 |
+
books = books.reset_index(drop=True)
|
| 20 |
+
books = books[books['annotation'].apply(lambda x: len(x.split()) >= 10)]
|
| 21 |
+
books.drop_duplicates(subset='title', keep='first', inplace=True)
|
| 22 |
+
books.reset_index(drop=True)
|
| 23 |
+
|
| 24 |
+
|
| 25 |
+
|
| 26 |
+
def data_preprocessing(text: str) -> str:
|
| 27 |
+
text = re.sub(r'http\S+', " ", text) # удаляем ссылки
|
| 28 |
+
text = re.sub(r'@\w+',' ',text) # удаляем упоминания пользователей
|
| 29 |
+
text = re.sub(r'#\w+', ' ', text) # удаляем хэштеги
|
| 30 |
+
# text = re.sub(r'\d+', ' ', text) # удаляем числа
|
| 31 |
+
# text = text.translate(str.maketrans('', '', string.punctuation))
|
| 32 |
+
text = re.sub(r'<.*?>',' ', text) # html tags
|
| 33 |
+
return
|
| 34 |
+
|
| 35 |
+
for i in ['author', 'title', 'annotation']:
|
| 36 |
+
books[i] = books[i].apply(data_preprocessing)
|
| 37 |
+
|
| 38 |
annot = books['annotation']
|
| 39 |
|
| 40 |
+
# Получение эмбеддингов аннотаций каждой книги в датасете
|
| 41 |
+
max_len = 128
|
| 42 |
+
token_annot = annot.apply(lambda x: tokenizer.encode(x, add_special_tokens=True, \
|
| 43 |
+
truncation=True, max_length=max_len))
|
| 44 |
+
|
| 45 |
+
padded = np.array([i + [0]*(max_len-len(i)) for i in token_annot.values]) # заполним недостающую длину нулями
|
| 46 |
+
attention_mask = np.where(padded != 0, 1, 0) # создадим маску, отметим где есть значения а где пустота
|
| 47 |
+
# Переведем numpy массивы в тензоры PyTorch
|
| 48 |
+
input_ids = torch.tensor(padded, dtype=torch.long)
|
| 49 |
+
attention_mask = torch.tensor(attention_mask, dtype=torch.long)
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 50 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 51 |
|
| 52 |
+
book_embeddings = []
|
| 53 |
+
for inputs, attention_masks in zip(input_ids, attention_mask):
|
| 54 |
+
with torch.inference_mode():
|
| 55 |
+
book_embedding = model(inputs.unsqueeze(0), attention_mask=attention_masks.unsqueeze(0))
|
| 56 |
+
book_embedding = book_embedding[0][:,0,:] #.detach().cpu().numpy()
|
| 57 |
+
book_embeddings.append(np.squeeze(book_embedding))
|
| 58 |
+
|
| 59 |
+
# Определение запроса пользователя
|
| 60 |
+
query = "В Америке началась Гражданская война"
|
| 61 |
+
query_tokens = tokenizer.encode(query, add_special_tokens=True, \
|
| 62 |
+
truncation=True, max_length=max_len)
|
| 63 |
+
|
| 64 |
+
query_padded = np.array(query_tokens + [0]*(max_len-len(query_tokens)))
|
| 65 |
+
query_mask = np.where(query_padded != 0, 1, 0)
|
| 66 |
+
|
| 67 |
+
# Переведем numpy массивы в тензоры PyTorch
|
| 68 |
+
query_padded = torch.tensor(query_padded, dtype=torch.long)
|
| 69 |
+
query_mask = torch.tensor(query_mask, dtype=torch.long)
|
| 70 |
+
|
| 71 |
+
with torch.inference_mode():
|
| 72 |
+
query_embedding = model(query_padded.unsqueeze(0), query_mask.unsqueeze(0)) #[0].squeeze()
|
| 73 |
+
query_embedding = query_embedding[0][:,0,:] #.detach().cpu().numpy()
|
| 74 |
+
|
| 75 |
+
# Вычисление косинусного расстояния между эмбеддингом запроса и каждой аннотацией
|
| 76 |
+
cosine_similarities = torch.nn.functional.cosine_similarity(
|
| 77 |
+
query_embedding.squeeze(0),
|
| 78 |
+
torch.stack(book_embeddings)
|
| 79 |
+
)
|
| 80 |
|
| 81 |
+
cosine_similarities = cosine_similarities.numpy()
|
| 82 |
|
| 83 |
+
indices = np.argsort(cosine_similarities)[::-1] # Сортировка по убыванию
|
| 84 |
|
| 85 |
+
for i in indices[:10]:
|
| 86 |
+
st.write(books['title'][i])
|
|
|