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