File size: 10,128 Bytes
77bc382
c880be9
77bc382
 
 
 
2884d17
77bc382
35153f5
77bc382
35153f5
 
77bc382
35153f5
 
 
 
 
 
 
 
 
b562f6e
35153f5
 
 
 
b562f6e
35153f5
b562f6e
35153f5
2b6f1b5
 
77bc382
 
2b6f1b5
 
 
c880be9
2b6f1b5
 
 
c880be9
2b6f1b5
 
 
 
35e2342
 
2b6f1b5
 
 
 
 
c880be9
2b6f1b5
 
 
 
 
 
 
 
 
 
 
2d4ed1c
 
2b6f1b5
 
 
 
c880be9
2b6f1b5
 
 
c880be9
 
2b6f1b5
 
c880be9
2b6f1b5
 
 
 
 
 
 
c880be9
2b6f1b5
c880be9
2b6f1b5
 
c880be9
2b6f1b5
c880be9
2b6f1b5
 
 
 
 
 
c880be9
2b6f1b5
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
c880be9
2b6f1b5
 
77bc382
 
 
2b6f1b5
77bc382
 
 
 
 
 
 
 
 
 
 
 
c880be9
2b6f1b5
c880be9
 
 
77bc382
c880be9
77bc382
c880be9
2b6f1b5
c880be9
 
77bc382
2b6f1b5
77bc382
2b6f1b5
 
c880be9
 
 
 
2b6f1b5
c880be9
77bc382
 
2b6f1b5
 
 
 
 
 
 
77bc382
2b6f1b5
77bc382
2b6f1b5
 
 
 
 
 
 
b562f6e
 
35153f5
c880be9
 
77bc382
7700aba
 
 
 
 
 
77bc382
7700aba
 
 
 
 
2b6f1b5
e5bf8d9
2b6f1b5
 
35153f5
 
 
7700aba
2b6f1b5
b562f6e
7700aba
35153f5
7700aba
2b6f1b5
 
77bc382
c880be9
2b6f1b5
77bc382
c880be9
2b6f1b5
 
c880be9
 
 
2b6f1b5
 
 
 
 
 
 
c880be9
 
77bc382
2b6f1b5
77bc382
2b6f1b5
 
 
 
 
 
 
 
2d4ed1c
 
2b6f1b5
 
 
 
 
 
 
2d4ed1c
 
2b6f1b5
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
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
import streamlit as st
import json, os, torch, faiss
import numpy as np
import pandas as pd
import torch.nn as nn
from sentence_transformers import SentenceTransformer
import os

from openai import OpenAI

# ─── Configuration & Privacy Setup ───────────────────────────────────────
client = None 

# 1. Fetch OpenRouter Key
OR_KEY = None
if "OPENROUTER_API_KEY" in st.secrets:
    OR_KEY = st.secrets["OPENROUTER_API_KEY"]
elif "OPENROUTER_API_KEY" in os.environ:
    OR_KEY = os.environ["OPENROUTER_API_KEY"]

# 2. Initialize the OpenRouter client using the OpenAI library
if OR_KEY:
    try:
        client = OpenAI(
            base_url="https://openrouter.ai/api/v1",
            api_key=OR_KEY,
        )
    except Exception as e:
        st.error(f"Failed to initialize OpenRouter client: {e}")
else:
    st.error("OPENROUTER_API_KEY not found in Secrets or Environment Variables.")

# ─── Professional Minimalist UI (Claude-Inspired) ──────────────────────────
st.markdown("""
<style>
    @import url('https://fonts.googleapis.com/css2?family=Inter:wght@300;400;500;600&display=swap');

    /* Global Reset */
    html, body, [class*="css"] {
        font-family: 'Inter', sans-serif !important;
        background-color: #FBFBFB !important;
        color: #1F1F1F;
    }

    /* Minimalist Header */
    .main-header {
        font-size: 1.5rem;
        font-weight: 600;
        letter-spacing: -0.02em;
        padding: 2rem 0 0.5rem 0;
        text-align: left;
        color: #111;
        border-bottom: 1px solid #EEE;
        margin-bottom: 2rem;
    }

    /* Chat Container Tweaks */
    .stChatMessage {
        background-color: transparent !important;
        border: none !important;
        padding: 1rem 0 !important;
    }

    /* AI Message Styling */
    .stChatMessage[data-testid="stChatMessageAssistant"] {
        border-bottom: 1px solid #F0F0F0 !important;
    }

    /* Movie Result Card - The "Sleek" Look */
    .movie-container {
        margin: 1.5rem 0;
        padding: 1.2rem;
        background: #FFFFFF;
        border: 1px solid #E5E5E5;
        border-radius: 8px;
        transition: border 0.3s ease;
    }
    
    .movie-container:hover {
        border: 1px solid #B5B5B5;
    }

    .movie-row {
        display: flex;
        justify-content: space-between;
        align-items: flex-start;
    }

    .movie-title {
        font-size: 1.05rem;
        font-weight: 600;
        color: #111;
        margin-bottom: 4px;
    }

    .movie-rating {
        font-size: 0.9rem;
        font-weight: 500;
        color: #666;
        background: #F0F0F0;
        padding: 2px 8px;
        border-radius: 4px;
    }

    .movie-genres {
        font-size: 0.8rem;
        color: #888;
        font-weight: 400;
        margin-bottom: 8px;
        text-transform: uppercase;
        letter-spacing: 0.03em;
    }

    .movie-description {
        font-size: 0.9rem;
        color: #444;
        line-height: 1.5;
        margin-top: 8px;
        border-left: 2px solid #EEE;
        padding-left: 12px;
    }

    /* Hide Default Streamlit Elements */
    #MainMenu, footer, header { visibility: hidden; }
    .stChatInputContainer { padding-bottom: 2rem !important; }

</style>
""", unsafe_allow_html=True)

# ─── Logic (Matrix Factorization & Engine) ──────────────────────────────
class MatrixFactorization(nn.Module):
    def __init__(self, n_users, n_items, emb_dim=100):
        super().__init__()
        self.user_emb = nn.Embedding(n_users, emb_dim)
        self.item_emb = nn.Embedding(n_items, emb_dim)
        self.user_bias = nn.Embedding(n_users, 1)
        self.item_bias = nn.Embedding(n_items, 1)
        self.global_mean = nn.Parameter(torch.zeros(1))
    def forward(self, user, item):
        dot = (self.user_emb(user) * self.item_emb(item)).sum(1)
        return dot + self.user_bias(user).squeeze() + self.item_bias(item).squeeze() + self.global_mean

class HybridEngine:
    def __init__(self, master_df, mf_model, n_u, n_i, index, embedder, id_map, alpha=0.3):
        self.master_df, self.mf_model = master_df.set_index('movieId'), mf_model
        self.n_u, self.n_i, self.index = n_u, n_i, index
        self.embedder, self.id_map, self.alpha = embedder, id_map, alpha

    def recommend(self, query, user_id=42, top_k=3):
        q_emb = self.embedder.encode([query], normalize_embeddings=True)
        scores, indices = self.index.search(q_emb.astype(np.float32), 40)
        candidates = []
        for idx, sem_sc in zip(indices[0], scores[0]):
            mid = self.id_map[idx]
            with torch.no_grad():
                cf_sc = self.mf_model(torch.tensor([user_id % self.n_u]), torch.tensor([mid % self.n_i])).item()
            cf_norm = (max(0.5, min(5.0, cf_sc)) - 0.5) / 4.5
            final_score = (self.alpha * float(sem_sc)) + ((1 - self.alpha) * cf_norm)
            candidates.append((mid, final_score))
        candidates.sort(key=lambda x: x[1], reverse=True)
        res = []
        for mid, _ in candidates[:top_k]:
            row = self.master_df.loc[mid]
            res.append({'title': row['title'], 'genres': row['genres_text'], 'rating': float(row['vote_average']), 'overview': row['overview']})
        return res

@st.cache_resource
def load_data():
    master_df = pd.read_parquet("master_df.parquet")
    ratings = pd.read_parquet("ratings_filtered.parquet")
    index = faiss.read_index("faiss_index.bin")
    with open("movie_id_map.json") as f: id_map = {int(k): v for k, v in json.load(f).items()}
    embedder = SentenceTransformer("all-MiniLM-L6-v2")
    state_dict = torch.load("mf_model.pt", map_location="cpu", weights_only=True)
    n_u, n_i = state_dict['user_emb.weight'].shape[0], state_dict['item_emb.weight'].shape[0]
    mf_model = MatrixFactorization(n_u, n_i)
    mf_model.load_state_dict(state_dict)
    mf_model.eval()
    return HybridEngine(master_df, mf_model, n_u, n_i, index, embedder, id_map), ratings, master_df

engine, ratings_df, master_full = load_data()

# ─── Groq Reasoning (Claude-style Personality) ──────────────────────────
def get_ai_explanation(query, movies, user_id):
    if client is None:
        return "Our AI concierge is currently offline, but these matches suit your request perfectly."

    top_mids = ratings_df[ratings_df['userId'] == user_id].sort_values('rating', ascending=False).head(3)['movieId'].tolist()
    history = [master_full[master_full['movieId'] == mid].iloc[0]['title'] for mid in top_mids if mid in master_full['movieId'].values]
    
    movie_context = "\n".join([f"- {m['title']}: {m['overview'][:150]}..." for m in movies])
    hist_text = ", ".join(history) if history else "a variety of critically acclaimed cinema"

    prompt = f"""You are a professional film concierge. 
    User current request: "{query}"
    User historical taste: {hist_text}
    
    Recommendations:
    {movie_context}
    
    Task: In 2 elegant, sophisticated sentences, explain why these films bridge the gap between their history and their current request. 
    Do not list movie titles or use robotic phrases like 'I recommend'. Talk about themes and mood."""

    try:
        chat = client.chat.completions.create(
            messages=[{"role": "user", "content": prompt}],
            # You can use any free model on OpenRouter here! 
            # This is the free Llama-3 8B model:
            model="meta-llama/llama-3-8b-instruct:free",
            temperature=0.6
        )
        return chat.choices[0].message.content
    except Exception as e:
        print(f"OPENROUTER API ERROR: {e}")
        return "Based on your request and historical preferences, these selections offer a unique blend of narrative resonance and stylistic flair."
# ─── UI Rendering ────────────────────────────────────────────────────────
st.markdown('<div class="main-header">CineGuide Concierge</div>', unsafe_allow_html=True)

if "messages" not in st.session_state:
    st.session_state.messages = []

for m in st.session_state.messages:
    with st.chat_message(m["role"]):
        st.markdown(m["content"])
        if "movies" in m:
            for movie in m["movies"]:
                st.markdown(f"""
                <div class="movie-container">
                    <div class="movie-row">
                        <div class="movie-title">{movie['title']}</div>
                        <div class="movie-rating">{movie['rating']} / 10</div>
                    </div>
                    <div class="movie-genres">{movie['genres']}</div>
                    <div class="movie-description">{movie['overview'][:180]}...</div>
                </div>
                """, unsafe_allow_html=True)

if prompt := st.chat_input("Ask me for a recommendation..."):
    st.session_state.messages.append({"role": "user", "content": prompt})
    with st.chat_message("user"):
        st.markdown(prompt)

    with st.chat_message("assistant"):
        with st.spinner("Thinking..."):
            recs = engine.recommend(prompt)
            explanation = get_ai_explanation(prompt, recs, 42)
            st.markdown(explanation)
            for movie in recs:
                st.markdown(f"""
                <div class="movie-container">
                    <div class="movie-row">
                        <div class="movie-title">{movie['title']}</div>
                        <div class="movie-rating">{movie['rating']} / 10</div>
                    </div>
                    <div class="movie-genres">{movie['genres']}</div>
                    <div class="movie-description">{movie['overview'][:180]}...</div>
                </div>
                """, unsafe_allow_html=True)
            st.session_state.messages.append({"role": "assistant", "content": explanation, "movies": recs})