-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathstreamlit_app.py
240 lines (188 loc) · 8.18 KB
/
streamlit_app.py
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
import streamlit as st
import requests
from dotenv import load_dotenv
import os
from datetime import datetime,timedelta
import pandas as pd
from modules import utils
import numpy as np
from openai import OpenAI
# import seaborn as sns
# import matplotlib.pyplot as plt
# import numpy as np
load_dotenv()
is_logged_in = False
if 'is_logged_in' not in st.session_state:
st.session_state['is_logged_in'] = False
# Helper function to format the selectbox options for places
def format_select_option(pair):
return f"{pair[0]} ({pair[1]})"
def login():
# Set background image
# st.markdown(f'<style>body{{background-image: url({page_bg}); background-size: cover;}}</style>', unsafe_allow_html=True)
global is_logged_in
st.title('CineSphere')
st.subheader('Welcome to CineSphere! Please Login to proceed.')
# Get user input
email = st.text_input("Email")
password = st.text_input("Password", type="password")
# Login button
if st.button("Login"):
# Check if login is valid
data = {
"grant_type": "password",
"username": email,
"password": password
}
#check if access token required as such
if utils.get_user(email, password):
st.success("Logged in!")
st.session_state['is_logged_in'] = True
st.session_state['email'] = email
st.session_state['password'] = password
else:
st.error("Incorrect email or password")
def signup():
# Set background image
# st.markdown(f'<style>body{{background-image: url({page_bg}); background-size: cover;}}</style>', unsafe_allow_html=True)
st.subheader('Signup')
# Get user input
email = st.text_input("Email")
password = st.text_input("Password", type="password")
confirm_password = st.text_input("Confirm Password", type="password")
create_account = st.button("Create Account")
if "create_account_state" not in st.session_state:
st.session_state.create_account_state = False
# Signup button
if create_account:
# Check if password matches
if password != confirm_password:
st.error("Passwords do not match")
else:
if not utils.check_user(email):
utils.create_user(email, password)
if utils.get_user(email, password) :
st.success("Signed up! Please complete the onboarding process below.")
st.session_state.create_account_state = True
else:
st.error("Error signing up")
else:
st.error("Email already exists")
def home_page():
# Set background image
# st.markdown(f'<style>body{{background-image: url({home_bg}); background-size: cover;}}</style>', unsafe_allow_html=True)
st.markdown("# CineSphere")
# Create a menu with the options
# menu = ["Home", "Login", "Signup"]
# choice = st.sidebar.selectbox("Select an option", menu)
# if choice == "Login":
# login()
# elif choice == "Signup":
# signup()
def chat_interface_page():
# Set background image
# st.markdown(f'<style>body{{background-image: url({page_bg}); background-size: cover;}}</style>', unsafe_allow_html=True)
client = OpenAI(api_key=os.environ["OPENAI_API_KEY"])
st.markdown("# CineSphere")
st.subheader('Have a question? Ask us anything! 🎥')
st.text('Just so you know, we can answer any questions related to movies,\n give recommendations based on movies, actors and even the plot! ')
# Initialize chat history
if "messages" not in st.session_state:
st.session_state.messages = []
# Display chat messages from history on app rerun
for message in st.session_state.messages:
with st.chat_message(message["role"]):
st.markdown(message["content"])
# Accept user input
if prompt := st.chat_input("What is up?"):
# Add user message to chat history
st.session_state.messages.append({"role": "user", "content": prompt})
# Display user message in chat message container
with st.chat_message("user"):
st.markdown(prompt)
response = utils.chat_bot(prompt)
st.session_state.messages.append({"role": "assistant", "content": response})
# Display assistant response in chat message container
with st.chat_message("assistant"):
st.markdown(response)
if st.button("Clear Chat History"):
st.session_state.messages = []
st.experimental_rerun()
def onboarding_page():
st.markdown("# CineSphere")
st.subheader('Onboarding! 🎥')
st.text('Please select your favorite movies to get started! 🍿🎬🎥')
df = utils.get_sample_movies()
df['posterLink'] = df['movieId'].apply(lambda x : utils.getImage(x))
num_cols = 5
cols = st.columns(num_cols)
selected_movies = []
selected_movie_ids = []
with st.form('movie_selection_form'):
for i, (_, row) in enumerate(df.iterrows()):
with cols[i % 5]:
st.image(row['posterLink'], use_column_width=True)
if st.checkbox(f"{row['movieName']}", key=f"checkbox_{row['movieId']}"):
selected_movies.append(row['movieName'])
selected_movie_ids.append(row['movieId'])
st.write("You selected the following movies:")
for movie in selected_movies:
st.write(f"- {movie}")
# Display the selected movies
if st.form_submit_button("Submit"):
utils.save_preferences(selected_movie_ids,st.session_state['email'],st.session_state['password'])
st.write("Preferences saved successfully! Check your recommendations on the next page! 🎉")
def recommendations_page():
st.markdown("# CineSphere")
st.subheader('Recommendations! 🎥')
st.text('Here are some movies you might like! 🍿')
similarity = utils.generate_recommendations(st.session_state['email'],st.session_state['password'])
# Split the DataFrame into buckets of size 10
buckets = np.array_split(similarity, len(similarity) // 10)
if 'current_bucket_index' not in st.session_state:
st.session_state.current_bucket_index = 0
current_bucket = buckets[st.session_state.current_bucket_index]
cols = st.columns(5)
for i, (_, row) in enumerate(current_bucket.iterrows()):
with cols[i % 5]:
st.image(row['posterLink'], use_column_width=True)
st.write(row['Movie2'])
# Add a "Refresh" button to show the next bucket
if st.button("Refresh"):
st.session_state.current_bucket_index = (st.session_state.current_bucket_index + 1) % len(buckets)
pages = {
"Home": home_page,
"Question? Chat it out": chat_interface_page,
"Recommendations": recommendations_page,
"Onboarding": onboarding_page,
}
# Define the Streamlit app
def main():
st.set_page_config(
page_title="CineSphere",page_icon=":popcorn:" ,layout="wide"
)
st.sidebar.title("Navigation")
# Render the navigation sidebar
if st.session_state['is_logged_in']==True:
selection = st.sidebar.radio(
"Go to", ["Home","Onboarding","Recommendations","Question? Chat it out","Log Out"]
)
else:
selection = st.sidebar.radio("Go to", ["Sign In", "Sign Up"])
# Render the selected page or perform logout
if selection == "Log Out":
st.session_state.clear()
st.sidebar.success("You have successfully logged out!")
st.experimental_rerun()
elif selection == "Sign In":
token = login()
if token is not None:
st.session_state.token = token
st.experimental_rerun()
elif selection == "Sign Up":
signup()
else:
page = pages[selection]
page()
if __name__ == "__main__":
main()