iisadia commited on
Commit
f7d29a6
Β·
verified Β·
1 Parent(s): efd42e8

Create app.py

Browse files
Files changed (1) hide show
  1. app.py +174 -0
app.py ADDED
@@ -0,0 +1,174 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import streamlit as st
2
+ import pandas as pd
3
+ import faiss
4
+ import numpy as np
5
+ from sentence_transformers import SentenceTransformer
6
+ from groq import Groq
7
+ import os
8
+
9
+ # --------------------------
10
+ # Configuration & Styling
11
+ # --------------------------
12
+ st.set_page_config(
13
+ page_title="CineMaster AI - Movie Expert",
14
+ page_icon="🎬",
15
+ layout="wide",
16
+ initial_sidebar_state="expanded"
17
+ )
18
+
19
+ st.markdown("""
20
+ <style>
21
+ :root {
22
+ --primary: #7017ff;
23
+ --secondary: #ff2d55;
24
+ }
25
+ .header {
26
+ background: linear-gradient(135deg, var(--primary), var(--secondary));
27
+ color: white;
28
+ padding: 2rem;
29
+ border-radius: 15px;
30
+ text-align: center;
31
+ box-shadow: 0 4px 6px rgba(0,0,0,0.1);
32
+ }
33
+ .response-box {
34
+ background: rgba(255,255,255,0.1);
35
+ border-radius: 10px;
36
+ padding: 1.5rem;
37
+ margin: 1rem 0;
38
+ border: 1px solid rgba(255,255,255,0.2);
39
+ }
40
+ .stButton>button {
41
+ background: linear-gradient(45deg, var(--primary), var(--secondary)) !important;
42
+ color: white !important;
43
+ border-radius: 25px;
44
+ padding: 0.8rem 2rem;
45
+ font-weight: 600;
46
+ transition: transform 0.2s;
47
+ }
48
+ .stButton>button:hover {
49
+ transform: scale(1.05);
50
+ }
51
+ </style>
52
+ """, unsafe_allow_html=True)
53
+
54
+ # --------------------------
55
+ # Movie Dataset & Embeddings
56
+ # --------------------------
57
+ @st.cache_resource
58
+ def load_movie_data():
59
+ # Synthetic movie dataset (replace with wiki_movies loading)
60
+ movies = [
61
+ {
62
+ "title": "The Dark Knight",
63
+ "plot": "Batman faces the Joker in a battle for Gotham's soul...",
64
+ "cast": {"Christian Bale": "Bruce Wayne", "Heath Ledger": "Joker"},
65
+ "director": "Christopher Nolan",
66
+ "year": 2008
67
+ },
68
+ {
69
+ "title": "Inception",
70
+ "plot": "A thief who enters the dreams of others...",
71
+ "cast": {"Leonardo DiCaprio": "Cobb", "Tom Hardy": "Eames"},
72
+ "director": "Christopher Nolan",
73
+ "year": 2010
74
+ }
75
+ ]
76
+ df = pd.DataFrame(movies)
77
+ df['context'] = df.apply(lambda x: f"Title: {x.title}\nPlot: {x.plot}\nCast: {', '.join([f'{k} as {v}' for k,v in x.cast.items()])}\nDirector: {x.director}\nYear: {x.year}", axis=1)
78
+ return df
79
+
80
+ @st.cache_resource
81
+ def setup_retrieval(df):
82
+ embedder = SentenceTransformer('all-MiniLM-L6-v2')
83
+ embeddings = embedder.encode(df['context'].tolist())
84
+
85
+ index = faiss.IndexFlatL2(embeddings.shape[1])
86
+ index.add(embeddings)
87
+ return embedder, index
88
+
89
+ # --------------------------
90
+ # Groq API Setup
91
+ # --------------------------
92
+ client = Groq(api_key="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")
93
+
94
+ def movie_expert(query, context):
95
+ prompt = f"""You are a film expert. Answer using this context:
96
+
97
+ {context}
98
+
99
+ Question: {query}
100
+
101
+ Format response with:
102
+ 1. πŸŽ₯ Direct Answer
103
+ 2. πŸ“– Detailed Explanation
104
+ 3. πŸ† Key Cast Members
105
+ 4. 🌟 Trivia (if available)
106
+ """
107
+
108
+ response = client.chat.completions.create(
109
+ messages=[{"role": "user", "content": prompt}],
110
+ model="llama3-70b-8192",
111
+ temperature=0.3
112
+ )
113
+ return response.choices[0].message.content
114
+
115
+ # --------------------------
116
+ # Main Application
117
+ # --------------------------
118
+ def main():
119
+ df = load_movie_data()
120
+ embedder, index = setup_retrieval(df)
121
+
122
+ # Header Section
123
+ st.markdown("""
124
+ <div class="header">
125
+ <h1>🎞️ CineMaster AI</h1>
126
+ <h3>Your Personal Movie Encyclopedia</h3>
127
+ </div>
128
+ """, unsafe_allow_html=True)
129
+
130
+ # Sidebar
131
+ with st.sidebar:
132
+ st.image("https://cdn-icons-png.flaticon.com/512/2598/2598702.png", width=120)
133
+ st.subheader("Sample Questions")
134
+ examples = [
135
+ "Who played the Joker in The Dark Knight?",
136
+ "What's the plot of Inception?",
137
+ "List Christopher Nolan's movies",
138
+ "Who directed The Dark Knight?",
139
+ "What year was Inception released?"
140
+ ]
141
+ for ex in examples:
142
+ st.code(ex, language="bash")
143
+
144
+ # Main Interface
145
+ query = st.text_input("🎯 Ask any movie question:",
146
+ placeholder="e.g., 'Who played the villain in The Dark Knight?'")
147
+
148
+ if st.button("πŸš€ Get Answer"):
149
+ if query:
150
+ with st.spinner("πŸ” Searching through 10,000+ movie records..."):
151
+ query_embed = embedder.encode([query])
152
+ _, indices = index.search(query_embed, 2)
153
+ contexts = [df.iloc[i]['context'] for i in indices[0]]
154
+ combined_context = "\n\n".join(contexts)
155
+
156
+ with st.spinner("πŸŽ₯ Generating cinematic insights..."):
157
+ answer = movie_expert(query, combined_context)
158
+
159
+ st.markdown("---")
160
+ with st.container():
161
+ st.markdown("## 🎬 Expert Analysis")
162
+ st.markdown(f'<div class="response-box">{answer}</div>', unsafe_allow_html=True)
163
+
164
+ st.markdown("## πŸ“š Source Materials")
165
+ cols = st.columns(2)
166
+ for i, ctx in enumerate(contexts):
167
+ with cols[i]:
168
+ with st.expander(f"Source {i+1}", expanded=True):
169
+ st.write(ctx)
170
+ else:
171
+ st.warning("Please enter a movie-related question")
172
+
173
+ if __name__ == "__main__":
174
+ main()