SuriyaSureshkumar commited on
Commit
327b9c5
Β·
verified Β·
1 Parent(s): b456c53
Files changed (1) hide show
  1. src/streamlit_app.py +154 -38
src/streamlit_app.py CHANGED
@@ -1,40 +1,156 @@
1
- import altair as alt
2
- import numpy as np
3
- import pandas as pd
4
  import streamlit as st
 
5
 
6
- """
7
- # Welcome to Streamlit!
8
-
9
- Edit `/streamlit_app.py` to customize this app to your heart's desire :heart:.
10
- If you have any questions, checkout our [documentation](https://docs.streamlit.io) and [community
11
- forums](https://discuss.streamlit.io).
12
-
13
- In the meantime, below is an example of what you can do with just a few lines of code:
14
- """
15
-
16
- num_points = st.slider("Number of points in spiral", 1, 10000, 1100)
17
- num_turns = st.slider("Number of turns in spiral", 1, 300, 31)
18
-
19
- indices = np.linspace(0, 1, num_points)
20
- theta = 2 * np.pi * num_turns * indices
21
- radius = indices
22
-
23
- x = radius * np.cos(theta)
24
- y = radius * np.sin(theta)
25
-
26
- df = pd.DataFrame({
27
- "x": x,
28
- "y": y,
29
- "idx": indices,
30
- "rand": np.random.randn(num_points),
31
- })
32
-
33
- st.altair_chart(alt.Chart(df, height=700, width=700)
34
- .mark_point(filled=True)
35
- .encode(
36
- x=alt.X("x", axis=None),
37
- y=alt.Y("y", axis=None),
38
- color=alt.Color("idx", legend=None, scale=alt.Scale()),
39
- size=alt.Size("rand", legend=None, scale=alt.Scale(range=[1, 150])),
40
- ))
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
  import streamlit as st
2
+ import requests
3
 
4
+ API_BASE = "https://news-recommender-system-o7n3.onrender.com"
5
+
6
+ # ---------------- Session State Initialization ----------------
7
+ if "token" not in st.session_state:
8
+ st.session_state.token = None
9
+ if "page" not in st.session_state:
10
+ st.session_state.page = "Login"
11
+
12
+ # ------------------ API Call Helpers ------------------
13
+
14
+ def login_api(email, password):
15
+ res = requests.post(f"{API_BASE}/login", json={"email": email, "password": password})
16
+ return res.json(), res.status_code
17
+
18
+ def register_api(username, email, password):
19
+ res = requests.post(f"{API_BASE}/register", json={
20
+ "username": username,
21
+ "email": email,
22
+ "password": password
23
+ })
24
+ return res.json(), res.status_code
25
+
26
+ def get_news():
27
+ headers = {"Authorization": f"Bearer {st.session_state.token}"}
28
+ res = requests.get(f"{API_BASE}/news", headers=headers)
29
+ return res.json()
30
+
31
+ def get_recommendations():
32
+ headers = {"Authorization": f"Bearer {st.session_state.token}"}
33
+ res = requests.get(f"{API_BASE}/recommend", headers=headers)
34
+ return res.json()
35
+
36
+ def like_article(news_id):
37
+ headers = {"Authorization": f"Bearer {st.session_state.token}"}
38
+ res = requests.post(f"{API_BASE}/like/{news_id}", headers=headers)
39
+ return res.json()
40
+
41
+ # ------------------ Page Functions ------------------
42
+
43
+ def login():
44
+ st.title("πŸ” Login")
45
+ email = st.text_input("Email")
46
+ password = st.text_input("Password", type="password")
47
+ if st.button("Login"):
48
+ data, code = login_api(email, password)
49
+ if code == 200:
50
+ st.session_state.token = data['token']
51
+ st.session_state.page = "Articles"
52
+ st.success("Login successful!")
53
+ st.rerun()
54
+ else:
55
+ st.error(data.get("error", "Login failed"))
56
+
57
+ def register():
58
+ st.title("πŸ“ Register")
59
+ username = st.text_input("Username")
60
+ email = st.text_input("Email")
61
+ password = st.text_input("Password", type="password")
62
+ if st.button("Register"):
63
+ data, code = register_api(username, email, password)
64
+ if code == 201:
65
+ st.session_state.token = data['token']
66
+ st.session_state.page = "Articles"
67
+ st.success("Registration successful!")
68
+ st.rerun()
69
+ else:
70
+ st.error(data.get("error", "Registration failed"))
71
+
72
+ def show_articles(news_list):
73
+ st.title("πŸ“° Your News Feed")
74
+
75
+ # Initialize liked_news in session state
76
+ if "liked_news" not in st.session_state:
77
+ st.session_state.liked_news = set()
78
+
79
+ for article in news_list:
80
+ with st.container():
81
+ st.subheader(article['title'])
82
+ st.write(article['description'])
83
+ st.caption(f"Category: {article['category']}")
84
+
85
+ # Disable like button if already liked
86
+ if article['id'] in st.session_state.liked_news:
87
+ st.button("βœ… Liked", key=f"liked_{article['id']}", disabled=True)
88
+ else:
89
+ if st.button("πŸ‘ Like", key=f"like_{article['id']}"):
90
+ like_article(article['id']) # Call API to like
91
+ st.session_state.liked_news.add(article['id']) # Track locally
92
+ st.success("Liked!")
93
+
94
+
95
+ def articles_page():
96
+ news_list = get_recommendations()
97
+ if not news_list:
98
+ st.info("No news found.")
99
+ return
100
+ show_articles(news_list)
101
+
102
+
103
+ # ------------------ Main Navigation Logic ------------------
104
+
105
+ def main():
106
+ st.sidebar.title("🧭 Navigation")
107
+
108
+ # Ensure session state variables are initialized
109
+ if "token" not in st.session_state:
110
+ st.session_state.token = None
111
+ if "page" not in st.session_state:
112
+ st.session_state.page = "Login"
113
+
114
+ if st.session_state.token: # User is logged in
115
+ nav_options = ["Articles", "Recommendations", "Logout"]
116
+
117
+ if st.session_state.page not in nav_options:
118
+ st.session_state.page = "Articles"
119
+
120
+ choice = st.sidebar.radio("Go to", nav_options, index=nav_options.index(st.session_state.page))
121
+
122
+ if choice == "Articles":
123
+ st.session_state.page = "Articles"
124
+ articles_page()
125
+
126
+ elif choice == "Recommendations":
127
+ st.session_state.page = "Recommendations"
128
+ news_list = get_recommendations()
129
+ show_articles(news_list)
130
+
131
+
132
+ elif choice == "Logout":
133
+ st.session_state.token = None
134
+ st.session_state.page = "Login"
135
+ st.success("βœ… Logged out successfully.")
136
+ st.rerun()
137
+
138
+ else: # User is not logged in
139
+ nav_options = ["Login", "Register"]
140
+
141
+ if st.session_state.page not in nav_options:
142
+ st.session_state.page = "Login"
143
+
144
+ choice = st.sidebar.radio("Go to", nav_options, index=nav_options.index(st.session_state.page))
145
+
146
+ if choice == "Login":
147
+ st.session_state.page = "Login"
148
+ login()
149
+
150
+ elif choice == "Register":
151
+ st.session_state.page = "Register"
152
+ register()
153
+
154
+ # ------------- Entry Point -------------
155
+ if __name__ == "__main__":
156
+ main()