Spaces:
Sleeping
Sleeping
Vladislawoo
commited on
Commit
•
4f93011
1
Parent(s):
fdba767
Upload app.py
Browse files
app.py
ADDED
@@ -0,0 +1,75 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
import streamlit as st
|
2 |
+
import pandas as pd
|
3 |
+
import torch
|
4 |
+
import numpy as np
|
5 |
+
from tqdm import tqdm
|
6 |
+
from transformers import AutoTokenizer, AutoModel
|
7 |
+
import faiss
|
8 |
+
|
9 |
+
model_name = "cointegrated/rubert-tiny2"
|
10 |
+
tokenizer = AutoTokenizer.from_pretrained(model_name)
|
11 |
+
model = AutoModel.from_pretrained(model_name)
|
12 |
+
|
13 |
+
df = pd.read_csv('final_data.csv')
|
14 |
+
|
15 |
+
MAX_LEN = 300
|
16 |
+
|
17 |
+
def embed_bert_cls(text, model=model, tokenizer=tokenizer):
|
18 |
+
t = tokenizer(text,
|
19 |
+
padding=True,
|
20 |
+
truncation=True,
|
21 |
+
return_tensors='pt',
|
22 |
+
max_length=MAX_LEN)
|
23 |
+
with torch.no_grad():
|
24 |
+
model_output = model(**{k: v.to(model.device) for k, v in t.items()})
|
25 |
+
embeddings = model_output.last_hidden_state[:, 0, :]
|
26 |
+
embeddings = torch.nn.functional.normalize(embeddings)
|
27 |
+
return embeddings[0].cpu().squeeze()
|
28 |
+
|
29 |
+
embeddings = np.loadtxt('embeddings.txt')
|
30 |
+
embeddings_tensor = [torch.tensor(embedding) for embedding in embeddings]
|
31 |
+
|
32 |
+
# Создание индекса Faiss
|
33 |
+
embeddings_matrix = np.stack(embeddings)
|
34 |
+
index = faiss.IndexFlatIP(embeddings_matrix.shape[1])
|
35 |
+
index.add(embeddings_matrix)
|
36 |
+
|
37 |
+
st.title('Приложение для рекомендации книг')
|
38 |
+
|
39 |
+
text = st.text_input('Введите запрос:')
|
40 |
+
num_results = st.number_input('Введите количество рекомендаций:', min_value=1, max_value=50, value=3)
|
41 |
+
|
42 |
+
|
43 |
+
# Add a button to trigger the recommendation process
|
44 |
+
recommend_button = st.button('Получить рекомендации')
|
45 |
+
|
46 |
+
if text and recommend_button: # Check if the user entered text and clicked the button
|
47 |
+
|
48 |
+
# Встраивание запроса и поиск ближайших векторов с использованием Faiss
|
49 |
+
query_embedding = embed_bert_cls(text)
|
50 |
+
query_embedding = query_embedding.numpy().astype('float32')
|
51 |
+
_, indices = index.search(np.expand_dims(query_embedding, axis=0), num_results)
|
52 |
+
|
53 |
+
st.subheader('Топ рекомендуемых книг:')
|
54 |
+
for i in indices[0]:
|
55 |
+
recommended_embedding = embeddings_tensor[i].numpy() # Вектор рекомендованной книги
|
56 |
+
similarity = np.dot(query_embedding, recommended_embedding) # Косинусное сходство
|
57 |
+
similarity_percent = similarity * 100
|
58 |
+
|
59 |
+
col1, col2 = st.columns([1, 3])
|
60 |
+
|
61 |
+
with col1:
|
62 |
+
st.image(df['image'][i], use_column_width=True)
|
63 |
+
|
64 |
+
with col2:
|
65 |
+
st.write(f"**Название книги:** {df['title'][i]}")
|
66 |
+
st.write(f"**Автор:** {df['author'][i]}")
|
67 |
+
st.write(f"**Описание:** {df['annotation'][i]}")
|
68 |
+
st.write(f"**Оценка сходства:** {similarity_percent:.2f}%")
|
69 |
+
|
70 |
+
st.write("---")
|
71 |
+
|
72 |
+
|
73 |
+
|
74 |
+
|
75 |
+
|