Spaces:
Sleeping
Sleeping
HaggiVaggi
commited on
Commit
•
60dd5b6
1
Parent(s):
dcf8f31
Create Selection of films by description✏️🔍.py
Browse files
pages/Selection of films by description✏️🔍.py
ADDED
@@ -0,0 +1,96 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
import streamlit as st
|
2 |
+
import pandas as pd
|
3 |
+
import torch
|
4 |
+
from transformers import BertTokenizer, BertModel
|
5 |
+
import faiss
|
6 |
+
import numpy as np
|
7 |
+
import re
|
8 |
+
import nltk
|
9 |
+
from nltk.corpus import stopwords
|
10 |
+
|
11 |
+
# Загрузка стоп-слов для английского языка
|
12 |
+
nltk.download('stopwords')
|
13 |
+
stop_words = set(stopwords.words('english'))
|
14 |
+
|
15 |
+
@st.cache_data
|
16 |
+
def load_data(url):
|
17 |
+
df = pd.read_csv(url)
|
18 |
+
return df
|
19 |
+
|
20 |
+
@st.cache_data
|
21 |
+
def embedding_and_index():
|
22 |
+
embeddings_array = np.load('data/embeddings_eng.npy')
|
23 |
+
index = faiss.read_index('data/desc_faiss_index_eng.index')
|
24 |
+
return embeddings_array, index
|
25 |
+
|
26 |
+
@st.cache_data
|
27 |
+
def load_model():
|
28 |
+
model = BertModel.from_pretrained('bert-base-uncased')
|
29 |
+
return model
|
30 |
+
|
31 |
+
def clean_text(text):
|
32 |
+
text = text.lower()
|
33 |
+
text = re.sub(r'[^\w\s]', '', text)
|
34 |
+
text = ' '.join(word for word in text.split() if word not in stop_words)
|
35 |
+
|
36 |
+
return text
|
37 |
+
|
38 |
+
st.header("Selection of films by description✏️🔍")
|
39 |
+
|
40 |
+
# Загрузка данных
|
41 |
+
tokenizer = BertTokenizer.from_pretrained('bert-base-uncased')
|
42 |
+
df = load_data('data/eng_data.csv')
|
43 |
+
embeddings_array, index = embedding_and_index()
|
44 |
+
model = load_model()
|
45 |
+
|
46 |
+
# Пользовательский ввод
|
47 |
+
user_input = st.text_input("Enter a movie description:", value="", help="The more detailed your description is, the more accurately we can choose a film for you 🤗'")
|
48 |
+
|
49 |
+
if st.button("Search🔍🎦"):
|
50 |
+
if user_input:
|
51 |
+
def encode_description(description, tokenizer, model):
|
52 |
+
tokens = tokenizer(description, return_tensors="pt")
|
53 |
+
with torch.no_grad():
|
54 |
+
outputs = model(**tokens)
|
55 |
+
embeddings = outputs.last_hidden_state.mean(dim=1)
|
56 |
+
return embeddings.cpu().numpy().astype('float32')
|
57 |
+
|
58 |
+
# Применяем очистку текста к пользовательскому вводу
|
59 |
+
cleaned_input = clean_text(user_input)
|
60 |
+
|
61 |
+
# Векторизация очищенного запроса
|
62 |
+
input_embedding = encode_description(cleaned_input, tokenizer, model)
|
63 |
+
|
64 |
+
# Поиск с использованием Faiss
|
65 |
+
_, sorted_indices = index.search(input_embedding.reshape(1, -1), 5)
|
66 |
+
|
67 |
+
# Используйте индексы для извлечения строк из DataFrame
|
68 |
+
recs = df.iloc[sorted_indices[0]].reset_index(drop=True)
|
69 |
+
recs.index = recs.index + 1
|
70 |
+
|
71 |
+
# Вывод рекомендованных фильмов с изображениями
|
72 |
+
st.subheader("Recommended movies 🎉:")
|
73 |
+
for i in range(5):
|
74 |
+
st.markdown(f"<span style='font-size:{20}px; color:purple'>{recs['movie_title'].iloc[i]}</span>", unsafe_allow_html=True)
|
75 |
+
# Создаем две колонки: одну для текста, другую для изображения
|
76 |
+
col1, col2 = st.columns([2, 1])
|
77 |
+
|
78 |
+
# В колонке отображаем название фильма, описание, роли и ссылку
|
79 |
+
col1.info(recs['description'].iloc[i])
|
80 |
+
col1.markdown(f"**Actors:** {recs['actors'].iloc[i]}")
|
81 |
+
col1.markdown(f"**You can watch the film [here]({recs['page_url'].iloc[i]})**")
|
82 |
+
|
83 |
+
# В колонке отображаем изображение
|
84 |
+
col2.image(recs['image_url'].iloc[i], caption=recs['movie_title'].iloc[i], width=200)
|
85 |
+
with st.sidebar:
|
86 |
+
st.info("""
|
87 |
+
#### Were we able to help you with the choice?
|
88 |
+
""")
|
89 |
+
feedback = st.text_input('Share with us')
|
90 |
+
|
91 |
+
feedback_button = st.button("Send feedback", key="feedback_button")
|
92 |
+
|
93 |
+
if feedback_button and feedback:
|
94 |
+
feedback_container.success("Thank you, every day we try to be better for you 💟")
|
95 |
+
elif feedback_button:
|
96 |
+
feedback_container.warning("Please enter a review before submitting")
|