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
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
import os
|
2 |
+
import firebase_admin
|
3 |
+
from firebase_admin import credentials, firestore
|
4 |
+
from dotenv import load_dotenv, find_dotenv
|
5 |
+
from datetime import date
|
6 |
+
import logging
|
7 |
+
import json
|
8 |
+
import streamlit as st
|
9 |
+
|
10 |
+
# Set up logging configuration.
|
11 |
+
logging.basicConfig(
|
12 |
+
format="%(asctime)s [%(levelname)s] %(message)s",
|
13 |
+
level=logging.INFO
|
14 |
+
)
|
15 |
+
|
16 |
+
# --------------- Firebase Initialization Functions ---------------
|
17 |
+
|
18 |
+
def initialize_environment():
|
19 |
+
"""
|
20 |
+
Loads environment variables from the .env file.
|
21 |
+
"""
|
22 |
+
logging.info("Loading ")
|
23 |
+
dotenv_path = find_dotenv()
|
24 |
+
load_dotenv(dotenv_path)
|
25 |
+
logging.info(f"Environment variables loaded from {dotenv_path}")
|
26 |
+
|
27 |
+
def initialize_firebase():
|
28 |
+
"""
|
29 |
+
Initializes Firebase using credentials.
|
30 |
+
Returns a Firestore client.
|
31 |
+
"""
|
32 |
+
|
33 |
+
if not firebase_admin._apps:
|
34 |
+
data = json.loads(os.getenv("firebase_detailed_cred"))
|
35 |
+
cred = credentials.Certificate(data)
|
36 |
+
firebase_admin.initialize_app(cred)
|
37 |
+
logging.info("Firebase initialized using provided credentials.")
|
38 |
+
else:
|
39 |
+
logging.info("Firebase already initialized.")
|
40 |
+
return firestore.client()
|
41 |
+
|
42 |
+
# # --------------- Firestore Query Function ---------------
|
43 |
+
# def fetch_news_firestore(start_date: str, end_date: str, categories, keyword, db_client):
|
44 |
+
# """
|
45 |
+
# Queries Firestore for news articles in the "ProcessedNews" collection that
|
46 |
+
# match the provided date range and categories.
|
47 |
+
# Performs client-side filtering for keywords.
|
48 |
+
# Limits the results to 100 articles.
|
49 |
+
# """
|
50 |
+
# logging.info(f"Querying Firestore for articles from {start_date} to {end_date}.")
|
51 |
+
# query = db_client.collection("ProcessedNews") \
|
52 |
+
# .where("Date", ">=", start_date) \
|
53 |
+
# .where("Date", "<=", end_date) \
|
54 |
+
# .limit(100)
|
55 |
+
|
56 |
+
# if categories:
|
57 |
+
# logging.info(f"Filtering by categories: {categories}")
|
58 |
+
# query = query.where("category", "in", categories)
|
59 |
+
|
60 |
+
# docs = query.stream()
|
61 |
+
# results = []
|
62 |
+
# for doc in docs:
|
63 |
+
# data = doc.to_dict()
|
64 |
+
# results.append(data)
|
65 |
+
# logging.info(f"Retrieved {len(results)} articles from Firestore before keyword filtering.")
|
66 |
+
|
67 |
+
# if keyword:
|
68 |
+
# kw = keyword.lower()
|
69 |
+
# results = [
|
70 |
+
# article for article in results
|
71 |
+
# if kw in article.get("title", "").lower() or kw in article.get("summary", "").lower()
|
72 |
+
# ]
|
73 |
+
# logging.info(f"{len(results)} articles remain after keyword filtering with keyword '{keyword}'.")
|
74 |
+
# return results
|
75 |
+
|
76 |
+
|
77 |
+
from firebase_admin.firestore import FieldFilter
|
78 |
+
from datetime import datetime
|
79 |
+
|
80 |
+
def fetch_news_firestore(start_date: str, end_date: str, categories, keyword, db_client):
|
81 |
+
"""
|
82 |
+
Queries Firestore for news articles using correct filter syntax and date handling,
|
83 |
+
and removes duplicate articles based on the "title" field.
|
84 |
+
"""
|
85 |
+
logging.info(f"Querying Firestore for articles from {start_date} to {end_date}.")
|
86 |
+
|
87 |
+
# Convert input dates to datetime objects
|
88 |
+
try:
|
89 |
+
start_date_dt = datetime.strptime(start_date, '%Y-%m-%d')
|
90 |
+
end_date_dt = datetime.strptime(end_date, '%Y-%m-%d')
|
91 |
+
except ValueError as e:
|
92 |
+
logging.error(f"Invalid date format: {e}. Use YYYY-MM-DD.")
|
93 |
+
return []
|
94 |
+
|
95 |
+
# Assuming 'Date' is stored as a string in Firestore. Adjust if using Timestamp.
|
96 |
+
start_date_str = start_date_dt.strftime('%Y-%m-%d')
|
97 |
+
end_date_str = end_date_dt.strftime('%Y-%m-%d')
|
98 |
+
|
99 |
+
# Build query with FieldFilter
|
100 |
+
query = db_client.collection("ProcessedNews")
|
101 |
+
query = query.where(filter=FieldFilter("Date", ">=", start_date_str))
|
102 |
+
query = query.where(filter=FieldFilter("Date", "<=", end_date_str))
|
103 |
+
query = query.limit(100)
|
104 |
+
|
105 |
+
if categories:
|
106 |
+
logging.info(f"Filtering by categories: {categories}")
|
107 |
+
query = query.where(filter=FieldFilter("category", "in", categories))
|
108 |
+
|
109 |
+
docs = query.stream()
|
110 |
+
results = [doc.to_dict() for doc in docs]
|
111 |
+
logging.info(f"Retrieved {len(results)} articles from Firestore before keyword filtering.")
|
112 |
+
|
113 |
+
# Keyword filtering remains the same
|
114 |
+
if keyword:
|
115 |
+
kw = keyword.lower()
|
116 |
+
results = [
|
117 |
+
article for article in results
|
118 |
+
if kw in article.get("title", "").lower() or kw in article.get("summary", "").lower()
|
119 |
+
]
|
120 |
+
logging.info(f"{len(results)} articles remain after keyword filtering.")
|
121 |
+
|
122 |
+
# Remove duplicate articles based on title:
|
123 |
+
unique_results = []
|
124 |
+
seen_titles = set()
|
125 |
+
for article in results:
|
126 |
+
title = article.get("title", "").strip()
|
127 |
+
# Only add article if title is non-empty and hasn't been seen yet
|
128 |
+
if title and title not in seen_titles:
|
129 |
+
seen_titles.add(title)
|
130 |
+
unique_results.append(article)
|
131 |
+
logging.info(f"{len(unique_results)} unique articles remain after duplicate removal.")
|
132 |
+
|
133 |
+
return unique_results
|
134 |
+
|
135 |
+
|
136 |
+
|
137 |
+
|
138 |
+
|
139 |
+
# --------------- Streamlit UI & Styles ---------------
|
140 |
+
def local_css(css_text):
|
141 |
+
st.markdown(f'<style>{css_text}</style>', unsafe_allow_html=True)
|
142 |
+
|
143 |
+
light_mode_styles = """
|
144 |
+
/* Global Styles for Light Mode */
|
145 |
+
body, .stApp {
|
146 |
+
background-color: #f8f9fa !important;
|
147 |
+
color: #212529 !important;
|
148 |
+
font-family: 'Helvetica Neue', Helvetica, Arial, sans-serif;
|
149 |
+
}
|
150 |
+
|
151 |
+
/* Overall text decoration */
|
152 |
+
h1, h2, h3, h4, h5, h6 {
|
153 |
+
text-shadow: 1px 1px 2px rgba(0,0,0,0.1);
|
154 |
+
font-weight: 700;
|
155 |
+
}
|
156 |
+
.container h2 {
|
157 |
+
text-align: center;
|
158 |
+
text-transform: uppercase;
|
159 |
+
color: #FF7E5F;
|
160 |
+
border-bottom: 2px solid #FF7E5F;
|
161 |
+
padding-bottom: 0.5rem;
|
162 |
+
margin-bottom: 1.5rem;
|
163 |
+
}
|
164 |
+
p {
|
165 |
+
font-size: 1rem;
|
166 |
+
line-height: 1.6;
|
167 |
+
margin-bottom: 1rem;
|
168 |
+
}
|
169 |
+
a {
|
170 |
+
text-decoration: underline;
|
171 |
+
transition: color 0.2s ease;
|
172 |
+
}
|
173 |
+
a:hover {
|
174 |
+
color: #FF7E5F;
|
175 |
+
}
|
176 |
+
|
177 |
+
/* Main Container */
|
178 |
+
.container {
|
179 |
+
max-width: 800px;
|
180 |
+
margin: 2rem auto;
|
181 |
+
padding: 0 1rem;
|
182 |
+
}
|
183 |
+
|
184 |
+
/* Hero Section with Brighter Orange */
|
185 |
+
.hero {
|
186 |
+
background: linear-gradient(135deg, rgba(255,140,0,0.9), rgba(255,69,0,0.9)),
|
187 |
+
url('https://images.unsplash.com/photo-1529257414775-5d6c2509fbe6?fit=crop&w=1600&q=80');
|
188 |
+
background-size: cover;
|
189 |
+
background-position: center;
|
190 |
+
border-radius: 12px;
|
191 |
+
padding: 6rem 2rem;
|
192 |
+
text-align: center;
|
193 |
+
color: #fff;
|
194 |
+
box-shadow: 0 4px 20px rgba(0,0,0,0.2);
|
195 |
+
animation: fadeIn 1s ease-in-out;
|
196 |
+
}
|
197 |
+
@keyframes fadeIn {
|
198 |
+
from { opacity: 0; transform: translateY(20px); }
|
199 |
+
to { opacity: 1; transform: translateY(0); }
|
200 |
+
}
|
201 |
+
.hero h1 {
|
202 |
+
font-size: 3rem;
|
203 |
+
margin-bottom: 1.5rem;
|
204 |
+
text-transform: uppercase;
|
205 |
+
letter-spacing: 2px;
|
206 |
+
}
|
207 |
+
.hero p {
|
208 |
+
font-size: 1.3rem;
|
209 |
+
max-width: 800px;
|
210 |
+
margin: 0 auto;
|
211 |
+
line-height: 1.6;
|
212 |
+
}
|
213 |
+
|
214 |
+
/* News Cards with Enhanced Shadow & Animation */
|
215 |
+
.news-container {
|
216 |
+
display: flex;
|
217 |
+
flex-direction: column;
|
218 |
+
gap: 2.5rem;
|
219 |
+
margin-bottom: 2rem;
|
220 |
+
}
|
221 |
+
.news-card {
|
222 |
+
background-color: #fff;
|
223 |
+
color: #212529;
|
224 |
+
border-radius: 8px;
|
225 |
+
border-left: 4px solid #FF7E5F;
|
226 |
+
box-shadow: 0 4px 10px rgba(0,0,0,0.1);
|
227 |
+
padding: 1.5rem;
|
228 |
+
transition: transform 0.3s ease, box-shadow 0.3s ease;
|
229 |
+
margin-bottom: 1rem;
|
230 |
+
}
|
231 |
+
.news-card:hover {
|
232 |
+
transform: translateY(-5px) scale(1.03);
|
233 |
+
box-shadow: 0 8px 16px rgba(255,126,95,0.3);
|
234 |
+
}
|
235 |
+
.news-card h2 {
|
236 |
+
font-size: 1.2rem;
|
237 |
+
margin-bottom: 0.5rem;
|
238 |
+
}
|
239 |
+
.news-card .meta {
|
240 |
+
font-size: 0.9rem;
|
241 |
+
color: #6c757d;
|
242 |
+
margin-bottom: 0.8rem;
|
243 |
+
}
|
244 |
+
.news-card p {
|
245 |
+
font-size: 0.95rem;
|
246 |
+
line-height: 1.4;
|
247 |
+
}
|
248 |
+
.news-card a {
|
249 |
+
color: #007bff;
|
250 |
+
text-decoration: none;
|
251 |
+
font-weight: 500;
|
252 |
+
}
|
253 |
+
"""
|
254 |
+
|
255 |
+
# --------------- Main App ---------------
|
256 |
+
def main():
|
257 |
+
st.set_page_config(page_title="Modern News Feed", layout="centered")
|
258 |
+
st.sidebar.title("Refine Your Feed")
|
259 |
+
local_css(light_mode_styles)
|
260 |
+
|
261 |
+
# Initialize Firebase and environment variables once.
|
262 |
+
if "db_client" not in st.session_state:
|
263 |
+
initialize_environment()
|
264 |
+
st.session_state.db_client = initialize_firebase()
|
265 |
+
|
266 |
+
db_client = st.session_state.db_client
|
267 |
+
|
268 |
+
# Sidebar filters.
|
269 |
+
today_date = date.today()
|
270 |
+
default_start = today_date.replace(day=1)
|
271 |
+
default_end = today_date
|
272 |
+
|
273 |
+
date_range = st.sidebar.date_input("Select Date Range", [default_start, default_end])
|
274 |
+
if len(date_range) != 2:
|
275 |
+
st.sidebar.error("Please select both a start and an end date.")
|
276 |
+
return
|
277 |
+
|
278 |
+
start_date_obj, end_date_obj = date_range
|
279 |
+
start_date_str = start_date_obj.strftime("%Y-%m-%d")
|
280 |
+
end_date_str = end_date_obj.strftime("%Y-%m-%d")
|
281 |
+
|
282 |
+
categories_list = ["World", "Sports", "Business", "Sci/Tech", "Politics", "Entertainment","Others"]
|
283 |
+
selected_categories = st.sidebar.multiselect("Select Categories", options=categories_list)
|
284 |
+
keyword = st.sidebar.text_input("Search Keywords")
|
285 |
+
|
286 |
+
# Two sidebar buttons.
|
287 |
+
col1, col2 = st.sidebar.columns(2)
|
288 |
+
with col1:
|
289 |
+
get_news = st.button("Get News")
|
290 |
+
with col2:
|
291 |
+
clear_news = st.button("Clear News")
|
292 |
+
|
293 |
+
# When "Get News" is pressed, query Firestore.
|
294 |
+
if get_news:
|
295 |
+
logging.info("Get News button pressed.")
|
296 |
+
st.session_state.news_pressed = True
|
297 |
+
with st.spinner("Fetching articles..."):
|
298 |
+
articles = fetch_news_firestore(start_date_str, end_date_str, selected_categories, keyword, db_client)
|
299 |
+
st.session_state.articles = articles
|
300 |
+
logging.info(f"{len(articles)} articles stored in session state after filtering.")
|
301 |
+
|
302 |
+
# When "Clear News" is pressed, clear the session.
|
303 |
+
if clear_news:
|
304 |
+
logging.info("Clear News button pressed. Clearing articles and flags.")
|
305 |
+
st.session_state.pop("articles", None)
|
306 |
+
st.session_state.pop("news_pressed", None)
|
307 |
+
|
308 |
+
# --------------- MAIN CONTENT ---------------
|
309 |
+
st.markdown("<div class='container'>", unsafe_allow_html=True)
|
310 |
+
|
311 |
+
# If Get News has been pressed, show results or an info message.
|
312 |
+
if st.session_state.get("news_pressed", False):
|
313 |
+
articles_to_show = st.session_state.get("articles", [])
|
314 |
+
if articles_to_show:
|
315 |
+
st.markdown("## Explore the Stories That Matter")
|
316 |
+
st.success(f"Found {len(articles_to_show)} articles")
|
317 |
+
st.markdown("<div class='news-container'>", unsafe_allow_html=True)
|
318 |
+
for article in articles_to_show:
|
319 |
+
st.markdown(f"""
|
320 |
+
<div class="news-card">
|
321 |
+
<h2>{article.get("title", "No Title")}</h2>
|
322 |
+
<div class="meta">
|
323 |
+
<strong>Date:</strong> {article.get("Date", "Unknown")}
|
324 |
+
<strong>Category:</strong> {article.get("category", "Uncategorized")}
|
325 |
+
</div>
|
326 |
+
<p>{article.get("summary", "No Summary Available")}</p>
|
327 |
+
{'<a href="' + article.get("url", "#") + '" target="_blank">Read More</a>' if article.get("url") else ""}
|
328 |
+
</div>
|
329 |
+
""", unsafe_allow_html=True)
|
330 |
+
st.markdown("</div>", unsafe_allow_html=True)
|
331 |
+
else:
|
332 |
+
st.info("No news meet the requirement. Please adjust your filters and try again.")
|
333 |
+
logging.info("No articles found matching the filters.")
|
334 |
+
else:
|
335 |
+
# If Get News hasn't been pressed, show the hero section.
|
336 |
+
st.markdown("""
|
337 |
+
<div class="hero">
|
338 |
+
<h1>News Spotlight</h1>
|
339 |
+
<p>Discover fresh stories and insights that ignite your curiosity. Your journey into groundbreaking news starts here.</p>
|
340 |
+
</div>
|
341 |
+
""", unsafe_allow_html=True)
|
342 |
+
|
343 |
+
st.markdown("</div>", unsafe_allow_html=True)
|
344 |
+
|
345 |
+
if __name__ == "__main__":
|
346 |
+
main()
|