Spaces:
Sleeping
Sleeping
app file
Browse files
app.py
ADDED
|
@@ -0,0 +1,48 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import streamlit as st
|
| 2 |
+
import pandas as pd
|
| 3 |
+
import numpy as np
|
| 4 |
+
import torch
|
| 5 |
+
from transformers import AutoTokenizer, AutoModel
|
| 6 |
+
from sklearn.metrics.pairwise import pairwise_distances, cosine_similarity
|
| 7 |
+
|
| 8 |
+
tokenizer = AutoTokenizer.from_pretrained("cointegrated/rubert-tiny2")
|
| 9 |
+
model = AutoModel.from_pretrained("cointegrated/rubert-tiny2")
|
| 10 |
+
|
| 11 |
+
df = pd.read_csv('data_final.csv')
|
| 12 |
+
|
| 13 |
+
MAX_LEN = 300
|
| 14 |
+
|
| 15 |
+
# @st.cache_resource
|
| 16 |
+
def embed_bert_cls(text, model, tokenizer):
|
| 17 |
+
t = tokenizer(text, padding=True, truncation=True, return_tensors='pt', max_length=MAX_LEN)
|
| 18 |
+
with torch.no_grad():
|
| 19 |
+
model_output = model(**{k: v.to(model.device) for k, v in t.items()})
|
| 20 |
+
embeddings = model_output.last_hidden_state[:, 0, :]
|
| 21 |
+
embeddings = torch.nn.functional.normalize(embeddings)
|
| 22 |
+
return embeddings[0].cpu().numpy()
|
| 23 |
+
|
| 24 |
+
books_vector = np.loadtxt('vectors.txt')
|
| 25 |
+
|
| 26 |
+
st.title('Приложение для рекомендации книг')
|
| 27 |
+
|
| 28 |
+
text = st.text_input('Введите запрос:')
|
| 29 |
+
num_results = st.number_input('Введите количество рекомендаций:', min_value=1, max_value=50, value=1)
|
| 30 |
+
|
| 31 |
+
recommend_button = st.button('Найти')
|
| 32 |
+
|
| 33 |
+
if text and recommend_button:
|
| 34 |
+
user_text_pred = embed_bert_cls(text, model, tokenizer)
|
| 35 |
+
list_ = pairwise_distances(user_text_pred.reshape(1, -1), books_vector).argsort()[0][:num_results]
|
| 36 |
+
|
| 37 |
+
st.subheader('Топ рекомендуемых книг:')
|
| 38 |
+
|
| 39 |
+
for i in list_:
|
| 40 |
+
col_1, col_2 = st.columns([1, 3])
|
| 41 |
+
|
| 42 |
+
with col_1:
|
| 43 |
+
st.image(df['image_url'][i], use_column_width=True)
|
| 44 |
+
with col_2:
|
| 45 |
+
st.write(f'Название книги: {df["title"][i]}')
|
| 46 |
+
st.write(f'Название книги: {df["author"][i]}')
|
| 47 |
+
st.write(f'Название книги: {df["annotation"][i]}')
|
| 48 |
+
st.write(f'{df["page_url"][i]}')
|