File size: 3,886 Bytes
34e52df
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
import streamlit as st
import pandas as pd
import torch
from transformers import BertTokenizer, BertModel
import faiss
import numpy as np
import re
import nltk
from nltk.corpus import stopwords

# Загрузка стоп-слов для английского языка
nltk.download('stopwords')
stop_words = set(stopwords.words('english'))

@st.cache_data
def load_data(url):
    df = pd.read_csv(url)
    return df

@st.cache_data
def embedding_and_index():
    embeddings_array = np.load('data/embeddings_eng.npy')
    index = faiss.read_index('data/desc_faiss_index_eng.index')
    return embeddings_array, index

@st.cache_data
def load_model():
    model = BertModel.from_pretrained('bert-base-uncased')
    return model

def clean_text(text):
    text = text.lower()
    text = re.sub(r'[^\w\s]', '', text)
    text = ' '.join(word for word in text.split() if word not in stop_words)
    
    return text

st.header("Selection of films by description✏️🔍")

# Загрузка данных
tokenizer = BertTokenizer.from_pretrained('bert-base-uncased')
df = load_data('data/eng_data.csv')
embeddings_array, index = embedding_and_index()
model = load_model()

# Пользовательский ввод
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 🤗'")

if st.button("Search🔍🎦"):
    if user_input:
        def encode_description(description, tokenizer, model):
            tokens = tokenizer(description, return_tensors="pt")
            with torch.no_grad():
                outputs = model(**tokens)
            embeddings = outputs.last_hidden_state.mean(dim=1)
            return embeddings.cpu().numpy().astype('float32')
        
        # Применяем очистку текста к пользовательскому вводу
        cleaned_input = clean_text(user_input)
        
        # Векторизация очищенного запроса
        input_embedding = encode_description(cleaned_input, tokenizer, model)

        # Поиск с использованием Faiss
        _, sorted_indices = index.search(input_embedding.reshape(1, -1), 5)

        # Используйте индексы для извлечения строк из DataFrame
        recs = df.iloc[sorted_indices[0]].reset_index(drop=True)
        recs.index = recs.index + 1

        # Вывод рекомендованных фильмов с изображениями
        st.subheader("Recommended movies 🎉:")
        for i in range(5):
            st.markdown(f"<span style='font-size:{20}px; color:purple'>{recs['movie_title'].iloc[i]}</span>", unsafe_allow_html=True)
        # Создаем две колонки: одну для текста, другую для изображения
            col1, col2 = st.columns([2, 1])
    
        # В  колонке отображаем название фильма, описание, роли и ссылку
            col1.info(recs['description'].iloc[i])
            col1.markdown(f"**You can watch the film [here]({recs['page_url'].iloc[i]})**")
    
        # В  колонке отображаем изображение
            col2.image(recs['image_url'].iloc[i], caption=recs['movie_title'].iloc[i], width=200)
        with st.sidebar:
            st.info("""
                 #### Were we able to help you with the choice? 
                """)
            feedback = st.text_input('Share with us')
        
            feedback_button = st.button("Send feedback", key="feedback_button")
        
        if feedback_button and feedback:
            feedback_container.success("Thank you, every day we try to be better for you 💟")
        elif feedback_button:
            feedback_container.warning("Please enter a review before submitting")