lenawilli commited on
Commit
d65a0f7
Β·
verified Β·
1 Parent(s): e293f84

Update src/streamlit_app.py

Browse files
Files changed (1) hide show
  1. src/streamlit_app.py +92 -58
src/streamlit_app.py CHANGED
@@ -11,76 +11,110 @@ MOVIES_PATH = os.path.join(BASE_DIR, "movies.csv")
11
  @st.cache_data
12
  def load_movies():
13
  df = pd.read_csv(MOVIES_PATH)
14
- return df["title"].dropna().unique().tolist()
 
 
 
15
 
16
  # Initialize session state
17
- if "movies" not in st.session_state:
18
- st.session_state.movies = []
19
- st.session_state.queue = []
20
- st.session_state.index = 0
21
  st.session_state.rated = []
22
- st.session_state.skipped = 0
23
- st.session_state.max_questions = 5
24
- st.session_state.finished = False
25
- st.session_state.show_slider = True
26
 
 
27
  st.markdown("""
28
  <style>
29
- html, body, [class*="css"] {
30
- background-color: #0d1b2a !important;
31
- color: white !important;
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
32
  }
33
  </style>
 
 
 
 
 
 
 
 
 
 
 
 
 
 
34
  """, unsafe_allow_html=True)
35
 
36
- st.title("🎬 Movie Recommender")
37
- st.write("Rate a few movies to get personalized recommendations")
38
 
39
- if not st.session_state.movies:
40
- movie_titles = load_movies()
41
- random.shuffle(movie_titles)
42
- st.session_state.movies = movie_titles
 
 
 
43
 
44
- if st.session_state.show_slider:
45
- with st.container():
46
- st.subheader("How many movies do you want to rate?")
47
- st.session_state.max_questions = st.slider("Select number of movies", 1, 15, 5)
48
- if st.button("Start Rating"):
49
- st.session_state.queue = st.session_state.movies.copy()
50
- st.session_state.show_slider = False
 
 
51
  st.rerun()
52
- elif st.session_state.finished or st.session_state.index >= len(st.session_state.queue):
53
- st.subheader("🍿 Top 10 Recommendations")
54
- st.write("Based on your preferences, we suggest:")
55
- remaining = [m for m in st.session_state.movies if m not in [r["movie"] for r in st.session_state.rated]]
56
- recommendations = random.sample(remaining, min(10, len(remaining)))
57
- for i, movie in enumerate(recommendations, 1):
58
- score = round(random.uniform(75, 100), 1)
59
- st.markdown(f"**#{i}. {movie}** β€” Match score: `{score}%`")
60
-
61
- if st.button("πŸ”„ Start Over"):
62
- for key in ["movies", "queue", "index", "rated", "skipped", "max_questions", "finished", "show_slider"]:
63
- st.session_state.pop(key, None)
64
- st.rerun()
65
- else:
66
- movie = st.session_state.queue[st.session_state.index]
67
-
68
- st.markdown(f"### 🎞️ Movie #{len(st.session_state.rated) + 1} of {st.session_state.max_questions}")
69
- st.markdown(f"## **{movie}**")
70
-
71
- col1, col2, col3 = st.columns([1, 1, 1])
72
- with col1:
73
- if st.button("πŸ‘ Like"):
74
- st.session_state.rated.append({"movie": movie, "rating": "like"})
75
- st.session_state.index += 1
76
- with col2:
77
- if st.button("πŸ‘Ž Dislike"):
78
- st.session_state.rated.append({"movie": movie, "rating": "dislike"})
79
- st.session_state.index += 1
80
- with col3:
81
- if st.button("⏭ Didn't Watch"):
82
  st.session_state.index += 1
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
83
 
84
- if len(st.session_state.rated) >= st.session_state.max_questions:
85
- st.session_state.finished = True
86
- st.rerun()
 
 
 
 
 
 
 
 
 
11
  @st.cache_data
12
  def load_movies():
13
  df = pd.read_csv(MOVIES_PATH)
14
+ return df.dropna(subset=["title"])
15
+
16
+ movie_df = load_movies()
17
+ movie_titles = movie_df["title"].unique().tolist()
18
 
19
  # Initialize session state
20
+ if "rated" not in st.session_state:
 
 
 
21
  st.session_state.rated = []
22
+ if "quiz_history" not in st.session_state:
23
+ st.session_state.quiz_history = []
 
 
24
 
25
+ # Navigation bar
26
  st.markdown("""
27
  <style>
28
+ .nav-bar {
29
+ display: flex;
30
+ justify-content: space-between;
31
+ align-items: center;
32
+ background-color: #1b263b;
33
+ padding: 1rem;
34
+ }
35
+ .nav-item {
36
+ color: white;
37
+ font-size: 20px;
38
+ text-decoration: none;
39
+ margin: 0 1rem;
40
+ cursor: pointer;
41
+ }
42
+ .search-bar {
43
+ width: 50%;
44
+ padding: 0.5rem;
45
+ font-size: 16px;
46
  }
47
  </style>
48
+ <div class="nav-bar">
49
+ <span class="nav-item" onclick="window.location.href='/'">🏠 Home</span>
50
+ <input type="text" id="search" class="search-bar" placeholder="Search movies..." onkeyup="filterMovies()">
51
+ <span class="nav-item" onclick="window.location.href='/?recommend=true'">🎯 Quiz</span>
52
+ </div>
53
+ <script>
54
+ function filterMovies() {
55
+ const input = document.getElementById('search').value.toLowerCase();
56
+ const elements = document.querySelectorAll('.movie-option');
57
+ elements.forEach(el => {
58
+ el.style.display = el.textContent.toLowerCase().includes(input) ? 'block' : 'none';
59
+ });
60
+ }
61
+ </script>
62
  """, unsafe_allow_html=True)
63
 
64
+ page = st.query_params.get("recommend")
 
65
 
66
+ if page:
67
+ # Quiz Flow
68
+ if "queue" not in st.session_state:
69
+ random.shuffle(movie_titles)
70
+ st.session_state.queue = movie_titles.copy()
71
+ st.session_state.index = 0
72
+ st.session_state.rated = []
73
 
74
+ if st.session_state.index >= len(st.session_state.queue):
75
+ st.subheader("🍿 Top 10 Recommendations")
76
+ remaining = [m for m in movie_titles if m not in [r["movie"] for r in st.session_state.rated]]
77
+ recommendations = random.sample(remaining, min(10, len(remaining)))
78
+ for i, movie in enumerate(recommendations, 1):
79
+ st.markdown(f"**#{i}. {movie}** β€” Match score: `{round(random.uniform(75, 100), 1)}%`")
80
+ st.session_state.quiz_history.append(st.session_state.rated.copy())
81
+ if st.button("πŸ”„ Start Over"):
82
+ del st.session_state.queue
83
  st.rerun()
84
+ else:
85
+ movie = st.session_state.queue[st.session_state.index]
86
+ st.markdown(f"### 🎞️ Movie #{len(st.session_state.rated) + 1}")
87
+ st.markdown(f"## **{movie}**")
88
+ rating = st.radio("Rate this movie", [1, 2, 3, 4, 5], horizontal=True)
89
+ if st.button("Submit Rating"):
90
+ st.session_state.rated.append({"movie": movie, "rating": rating})
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
91
  st.session_state.index += 1
92
+ st.rerun()
93
+ else:
94
+ # Home Page
95
+ st.title("🏠 Welcome to MovieMatch")
96
+ st.subheader("Your past quiz results")
97
+ for i, result in enumerate(st.session_state.quiz_history):
98
+ st.markdown(f"**Quiz {i+1} Summary:**")
99
+ for r in result:
100
+ st.markdown(f"- {r['movie']}: ⭐ {r['rating']}")
101
+ st.subheader("Overall summary")
102
+ all_ratings = [r for result in st.session_state.quiz_history for r in result]
103
+ summary_df = pd.DataFrame(all_ratings)
104
+ if not summary_df.empty:
105
+ avg_rating = summary_df.groupby("movie")["rating"].mean().sort_values(ascending=False)
106
+ st.write(avg_rating.reset_index().rename(columns={"rating": "Average Rating"}))
107
+ else:
108
+ st.info("No ratings yet.")
109
 
110
+ st.subheader("Search & Rate")
111
+ query = st.text_input("Search for a movie")
112
+ if query:
113
+ matches = [m for m in movie_titles if query.lower() in m.lower()]
114
+ for match in matches:
115
+ with st.expander(match):
116
+ st.write("Short description placeholder")
117
+ rate = st.radio(f"Rate {match}", [1, 2, 3, 4, 5], key=match)
118
+ if st.button(f"Submit {match}", key=f"submit_{match}"):
119
+ st.session_state.rated.append({"movie": match, "rating": rate})
120
+ st.success(f"Thanks for rating {match} ⭐{rate}")