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
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import streamlit as st
|
| 2 |
+
import requests
|
| 3 |
+
import feedparser
|
| 4 |
+
from datetime import datetime
|
| 5 |
+
from openai import OpenAI # The OpenAI library is used, but configured for OpenRouter
|
| 6 |
+
from openai import APIStatusError, RateLimitError, AuthenticationError, APIConnectionError
|
| 7 |
+
from deep_translator import GoogleTranslator
|
| 8 |
+
from bs4 import BeautifulSoup
|
| 9 |
+
from dotenv import load_dotenv # Import for loading environment variables
|
| 10 |
+
import os # Import for accessing environment variables
|
| 11 |
+
|
| 12 |
+
# --- CONFIG ------------------------------------------------------------------
|
| 13 |
+
|
| 14 |
+
# Load environment variables from .env file
|
| 15 |
+
load_dotenv()
|
| 16 |
+
|
| 17 |
+
# --- IMPORTANT: HOW TO SET UP YOUR YOUR OPENROUTER API KEY ---
|
| 18 |
+
# 1. Create a file named `.env` in the same directory as your Python script.
|
| 19 |
+
# 2. Add the following line to the `.env` file:
|
| 20 |
+
# OPENROUTER_API_KEY="YOUR_OPENROUTER_API_KEY_HERE"
|
| 21 |
+
# 3. Replace "YOUR_OPENROUTER_API_KEY_HERE" with your actual API key from OpenRouter.
|
| 22 |
+
# 4. Make sure to keep your `.env` file out of version control (e.g., add it to .gitignore).
|
| 23 |
+
# --------------------------------------------------------
|
| 24 |
+
|
| 25 |
+
LANGUAGES = {
|
| 26 |
+
"en": {"en": "English", "hi": "Hindi", "te": "Telugu"},
|
| 27 |
+
"hi": {"en": "अंग्रेज़ी", "hi": "हिंदी", "te": "तेలుగు"},
|
| 28 |
+
"te": {"en": "ఆంగ్లం", "hi": "హిందీ", "te": "తెలుగు"},
|
| 29 |
+
}
|
| 30 |
+
|
| 31 |
+
translations = {
|
| 32 |
+
"en": {
|
| 33 |
+
"title": "🕰️ Timescope",
|
| 34 |
+
"description": "Get today's headlines and explore history — all in one place.",
|
| 35 |
+
"on_this_day": "📅 On This Day in History",
|
| 36 |
+
"pick_date": "Pick a date",
|
| 37 |
+
"language": "🌐 Language",
|
| 38 |
+
"events": "Events:",
|
| 39 |
+
"no_events": "No events found for this date.",
|
| 40 |
+
"todays_headlines": "📢 Today's Headlines by Category",
|
| 41 |
+
"couldnt_load_news": "❌ Couldn’t load news. Please check your internet.",
|
| 42 |
+
"refresh_news": "🔄 Refresh News",
|
| 43 |
+
"ask_ai": "🤖 Ask Timescope AI",
|
| 44 |
+
"ask_placeholder": "Ask anything about history, world news, or events:",
|
| 45 |
+
"answer": "**Answer:** ",
|
| 46 |
+
"ai_error": "❌ AI Assistant Error:", # Changed to be more general for AI
|
| 47 |
+
"unsupported_onthisday": "Sorry, 'On This Day' is not available in this language.",
|
| 48 |
+
"read_more": "Read more"
|
| 49 |
+
},
|
| 50 |
+
"hi": {
|
| 51 |
+
"title": "🕰️ टाइमस्कोप",
|
| 52 |
+
"description": "आज की सुर्खियाँ और इतिहास एक ही स्थान पर देखें।",
|
| 53 |
+
"on_this_day": "📅 आज के दिन का इतिहास",
|
| 54 |
+
"pick_date": "तारीख चुनें",
|
| 55 |
+
"language": "🌐 भाषा",
|
| 56 |
+
"events": "घटनाएँ:",
|
| 57 |
+
"no_events": "इस तारीख के लिए कोई घटना नहीं मिली।",
|
| 58 |
+
"todays_headlines": "📢 आज की प्रमुख खबरें (श्रेणी अनुसार)",
|
| 59 |
+
"couldnt_load_news": "❌ खबरें लोड नहीं हो सकीं। कृपया अपना इंटरनेट जांचें।",
|
| 60 |
+
"refresh_news": "🔄 खबरें रीफ़्रेश करें",
|
| 61 |
+
"ask_ai": "🤖 टाइमस्कोप एआई से पूछें",
|
| 62 |
+
"ask_placeholder": "इतिहास, विश्व समाचार या घटनाओं के बारे में कुछ भी पूछें:",
|
| 63 |
+
"answer": "**उत्तर:** ",
|
| 64 |
+
"ai_error": "❌ AI सहायक त्रुटि:", # Changed
|
| 65 |
+
"unsupported_onthisday": "क्षमा करें, 'आज के दिन' इस भाषा में उपलब्ध नहीं है।",
|
| 66 |
+
"read_more": "और पढ़ें"
|
| 67 |
+
},
|
| 68 |
+
"te": {
|
| 69 |
+
"title": "🕰️ టైమ్స్కోప్",
|
| 70 |
+
"description": "ఈ రోజు ముఖ్యాంశాలు మరియు చరిత్రను ఒకే చోట అన్వేషించండి.",
|
| 71 |
+
"on_this_day": "📅 ఈ రోజు చరిత్రలో",
|
| 72 |
+
"pick_date": "తేదీ ఎంచుకోండి",
|
| 73 |
+
"language": "🌐 భాష",
|
| 74 |
+
"events": "ఈవెంట్స్:",
|
| 75 |
+
"no_events": "ఈ తేదీకి ఈవెంట్స్ లభించలేదు.",
|
| 76 |
+
"todays_headlines": "📢 ఈ రోజు ముఖ్యాంశాలు (వర్గం ద్వారా)",
|
| 77 |
+
"couldnt_load_news": "❌ వార్తలు లోడ్ కాలేకపోయాయి. దయచేసి మీ ఇంటర్నెట్ను తనిఖీ చేయండి.",
|
| 78 |
+
"refresh_news": "🔄 వార్తలను రీఫ్రెష్ చేయండి",
|
| 79 |
+
"ask_ai": "🤖 టైమ్స్కోప్ AI ను అడగండి",
|
| 80 |
+
"ask_placeholder": "చరిత్ర, ప్రపంచ వార్తలు లేదా ఈవెంట్స్ గురించి ఏదైనా అడగండి:",
|
| 81 |
+
"answer": "**సమాధానం:** ",
|
| 82 |
+
"ai_error": "❌ AI సహాయ లోపం:", # Changed
|
| 83 |
+
"unsupported_onthisday": "క్షమించండి, 'ఈ రోజు చరిత్రలో' ఈ భాషలో అందుబాటులో లేదు.",
|
| 84 |
+
"read_more": "ఇంకా చదవండి"
|
| 85 |
+
}
|
| 86 |
+
}
|
| 87 |
+
|
| 88 |
+
CATEGORY_FEEDS = {
|
| 89 |
+
"World": "http://feeds.bbci.co.uk/news/world/rss.xml",
|
| 90 |
+
"Technology": "http://feeds.bbci.co.uk/news/technology/rss.xml",
|
| 91 |
+
"Business": "http://feeds.bbci.co.uk/news/business/rss.xml",
|
| 92 |
+
"Politics": "http://feeds.bbci.co.uk/news/politics/rss.xml",
|
| 93 |
+
"Health": "http://feeds.bbci.co.uk/news/health/rss.xml",
|
| 94 |
+
"Science": "http://feeds.bbci.co.uk/news/science_and_environment/rss.xml",
|
| 95 |
+
"Entertainment": "http://feeds.bbci.co.uk/news/entertainment_and_arts/rss.xml",
|
| 96 |
+
"Sports": "https://feeds.bbci.co.uk/sport/rss.xml"
|
| 97 |
+
}
|
| 98 |
+
|
| 99 |
+
# --- OpenAI/OpenRouter Client Setup ------------------------------------------
|
| 100 |
+
|
| 101 |
+
openrouter_api_key = "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" # Load from .env
|
| 102 |
+
|
| 103 |
+
DEFAULT_AI_MODEL = "mistralai/mistral-7b-instruct" # Recommended general-purpose model for OpenRouter
|
| 104 |
+
|
| 105 |
+
# --- Initialize OpenAI client for OpenRouter
|
| 106 |
+
if not openrouter_api_key:
|
| 107 |
+
st.warning("OpenRouter API Key not found! AI Assistant functionality will be limited.")
|
| 108 |
+
# Initialize with a dummy key and base_url so the app doesn't crash if key is missing.
|
| 109 |
+
# The actual error for missing key will be caught in the try-except block for AI calls.
|
| 110 |
+
client = OpenAI(
|
| 111 |
+
base_url="https://openrouter.ai/api/v1",
|
| 112 |
+
api_key="sk-dummy-key-for-no-ai"
|
| 113 |
+
)
|
| 114 |
+
else:
|
| 115 |
+
client = OpenAI(
|
| 116 |
+
base_url="https://openrouter.ai/api/v1",
|
| 117 |
+
api_key=openrouter_api_key
|
| 118 |
+
)
|
| 119 |
+
|
| 120 |
+
# --- Streamlit Page Configuration --------------------------------------------
|
| 121 |
+
|
| 122 |
+
st.set_page_config("Timescope", layout="wide")
|
| 123 |
+
|
| 124 |
+
# Initialize session state for chat history and language
|
| 125 |
+
if 'chat_history' not in st.session_state:
|
| 126 |
+
st.session_state['chat_history'] = []
|
| 127 |
+
if 'lang_code' not in st.session_state:
|
| 128 |
+
st.session_state['lang_code'] = 'en'
|
| 129 |
+
|
| 130 |
+
|
| 131 |
+
# --- Custom CSS for fixed AI Assistant and general styling -------------------
|
| 132 |
+
st.markdown("""
|
| 133 |
+
<style>
|
| 134 |
+
body {
|
| 135 |
+
background-color: #f4f8fc;
|
| 136 |
+
}
|
| 137 |
+
.main {
|
| 138 |
+
color: #003366;
|
| 139 |
+
font-family: 'Segoe UI', sans-serif;
|
| 140 |
+
}
|
| 141 |
+
.stSpinner > div > div {
|
| 142 |
+
border-top-color: #003366;
|
| 143 |
+
}
|
| 144 |
+
|
| 145 |
+
/* Adjust padding for the main content to avoid overlap with fixed assistant */
|
| 146 |
+
.st-emotion-cache-z5fcl4 { /* Common class for the main content block (may vary) */
|
| 147 |
+
padding-top: 50px; /* Space from very top */
|
| 148 |
+
padding-bottom: 250px; /* Increased padding for fixed bottom assistant */
|
| 149 |
+
}
|
| 150 |
+
|
| 151 |
+
/* Top right controls (language, refresh) */
|
| 152 |
+
.top-right-controls {
|
| 153 |
+
display: flex;
|
| 154 |
+
align-items: center;
|
| 155 |
+
gap: 10px; /* Space between controls */
|
| 156 |
+
justify-content: flex-end; /* Align to the right */
|
| 157 |
+
margin-top: -30px; /* Pull up to align with title */
|
| 158 |
+
margin-right: 20px; /* Padding from right edge */
|
| 159 |
+
}
|
| 160 |
+
.top-right-controls .stButton button {
|
| 161 |
+
background-color: #0056b3;
|
| 162 |
+
color: white;
|
| 163 |
+
border-radius: 50%; /* Make it round */
|
| 164 |
+
width: 40px; /* Fixed width */
|
| 165 |
+
height: 40px; /* Fixed height */
|
| 166 |
+
display: flex;
|
| 167 |
+
align-items: center;
|
| 168 |
+
justify-content: center;
|
| 169 |
+
padding: 0; /* Remove internal padding */
|
| 170 |
+
font-size: 1.2em; /* Icon size */
|
| 171 |
+
box-shadow: 0 2px 5px rgba(0,0,0,0.2);
|
| 172 |
+
}
|
| 173 |
+
.top-right-controls .stButton button:hover {
|
| 174 |
+
background-color: #003366;
|
| 175 |
+
}
|
| 176 |
+
/* Style for language selectbox to appear like a button/icon */
|
| 177 |
+
.top-right-controls .stSelectbox [data-testid="stSelectbox"] {
|
| 178 |
+
width: 60px; /* Adjust width as needed for icon */
|
| 179 |
+
}
|
| 180 |
+
.top-right-controls .stSelectbox [data-testid="stSelectbox"] > div > div {
|
| 181 |
+
background-color: #0056b3;
|
| 182 |
+
color: white;
|
| 183 |
+
border-radius: 50%;
|
| 184 |
+
width: 40px;
|
| 185 |
+
height: 40px;
|
| 186 |
+
display: flex;
|
| 187 |
+
align-items: center;
|
| 188 |
+
justify-content: center;
|
| 189 |
+
padding: 0;
|
| 190 |
+
font-size: 1.2em;
|
| 191 |
+
box-shadow: 0 2px 5px rgba(0,0,0,0.2);
|
| 192 |
+
cursor: pointer;
|
| 193 |
+
}
|
| 194 |
+
.top-right-controls .stSelectbox [data-testid="stSelectbox"] > div > div:hover {
|
| 195 |
+
background-color: #003366;
|
| 196 |
+
}
|
| 197 |
+
.top-right-controls .stSelectbox [data-testid="stSelectbox"] .st-bh { /* Target the displayed value */
|
| 198 |
+
color: white !important; /* Ensure text is white */
|
| 199 |
+
font-size: 1.2em; /* Size for language symbol */
|
| 200 |
+
text-align: center;
|
| 201 |
+
flex-grow: 1; /* Make it take full space */
|
| 202 |
+
}
|
| 203 |
+
.top-right-controls .stSelectbox [data-testid="stSelectbox"] .st-cg { /* Target dropdown arrow */
|
| 204 |
+
color: white !important;
|
| 205 |
+
}
|
| 206 |
+
|
| 207 |
+
/* Category Tabs Styling */
|
| 208 |
+
.stTabs [data-testid="stTab"] {
|
| 209 |
+
font-size: 1.1em;
|
| 210 |
+
font-weight: bold;
|
| 211 |
+
color: #003366;
|
| 212 |
+
background-color: #e9f2fb;
|
| 213 |
+
border-radius: 8px 8px 0 0;
|
| 214 |
+
margin-right: 5px;
|
| 215 |
+
padding: 10px 15px;
|
| 216 |
+
border-bottom: 3px solid transparent;
|
| 217 |
+
transition: all 0.2s ease-in-out;
|
| 218 |
+
}
|
| 219 |
+
.stTabs [data-testid="stTab"]:hover {
|
| 220 |
+
background-color: #d6e8f8;
|
| 221 |
+
border-bottom-color: #0056b3;
|
| 222 |
+
}
|
| 223 |
+
.stTabs [data-testid="stTab"][aria-selected="true"] {
|
| 224 |
+
background-color: #0056b3;
|
| 225 |
+
color: white;
|
| 226 |
+
border-bottom-color: #003366;
|
| 227 |
+
box-shadow: 0 -2px 8px rgba(0,0,0,0.1);
|
| 228 |
+
}
|
| 229 |
+
.stTabs [data-testid="stTabGrid"] {
|
| 230 |
+
background-color: #f0f8ff; /* Background for the tab content area */
|
| 231 |
+
border-radius: 0 8px 8px 8px;
|
| 232 |
+
padding: 20px;
|
| 233 |
+
box-shadow: 0 4px 10px rgba(0,0,0,0.05);
|
| 234 |
+
}
|
| 235 |
+
|
| 236 |
+
|
| 237 |
+
/* Custom CSS for news cards */
|
| 238 |
+
.news-card {
|
| 239 |
+
padding: 15px;
|
| 240 |
+
margin-bottom: 15px; /* Spacing between rows of cards */
|
| 241 |
+
border-radius: 8px;
|
| 242 |
+
/* Gradient background for cards */
|
| 243 |
+
background-image: linear-gradient(to bottom right, #e9f2fb, #d6e8f8);
|
| 244 |
+
border: 1px solid #a7d0f7; /* Subtle border */
|
| 245 |
+
box-shadow: 0 4px 8px rgba(0,0,0,0.1); /* More prominent shadow for cards */
|
| 246 |
+
height: 100%; /* Ensure cards in a row have same height */
|
| 247 |
+
display: flex;
|
| 248 |
+
flex-direction: column;
|
| 249 |
+
justify-content: space-between; /* Pushes content to top, buttons to bottom */
|
| 250 |
+
overflow: hidden; /* Ensures content stays within the card */
|
| 251 |
+
}
|
| 252 |
+
.news-card h4 {
|
| 253 |
+
color: #003366; /* Dark blue title */
|
| 254 |
+
margin-top: 0;
|
| 255 |
+
margin-bottom: 10px;
|
| 256 |
+
font-size: 1.2em; /* Slightly larger title */
|
| 257 |
+
}
|
| 258 |
+
.news-card p {
|
| 259 |
+
color: #333333; /* Darker gray text */
|
| 260 |
+
font-size: 0.9em;
|
| 261 |
+
line-height: 1.5;
|
| 262 |
+
margin-bottom: 15px; /* Space between text and buttons */
|
| 263 |
+
flex-grow: 1; /* Allows text to take available space */
|
| 264 |
+
}
|
| 265 |
+
/* Styling for Streamlit link buttons within cards */
|
| 266 |
+
.news-card a[data-testid="stLinkButton"] { /* Target the Streamlit link button wrapper */
|
| 267 |
+
width: 100%; /* Make link button full width */
|
| 268 |
+
margin-top: 5px; /* Space between elements */
|
| 269 |
+
margin-bottom: 5px; /* Space from bottom of card */
|
| 270 |
+
display: block; /* Ensure it behaves as a block */
|
| 271 |
+
}
|
| 272 |
+
.news-card a[data-testid="stLinkButton"] > div { /* Target the internal div/content of st.link_button */
|
| 273 |
+
width: 100%;
|
| 274 |
+
background-color: #6c757d !important; /* Grey for link button */
|
| 275 |
+
color: white !important;
|
| 276 |
+
border-radius: 5px;
|
| 277 |
+
padding: 8px 12px;
|
| 278 |
+
border: none;
|
| 279 |
+
cursor: pointer;
|
| 280 |
+
text-align: center;
|
| 281 |
+
text-decoration: none !important;
|
| 282 |
+
display: inline-block; /* Keep as inline-block or block as per preference */
|
| 283 |
+
}
|
| 284 |
+
.news-card a[data-testid="stLinkButton"] > div:hover {
|
| 285 |
+
background-color: #5a6268 !important;
|
| 286 |
+
}
|
| 287 |
+
|
| 288 |
+
|
| 289 |
+
/* CSS for the fixed assistant container (at the bottom) */
|
| 290 |
+
#fixed-assistant-container {
|
| 291 |
+
position: fixed;
|
| 292 |
+
bottom: 0px; /* Position at the bottom */
|
| 293 |
+
left: 0; /* Align with the left edge of the viewport */
|
| 294 |
+
width: 100%;
|
| 295 |
+
background-color: #f4f8fc; /* Match body background */
|
| 296 |
+
/* Fixed padding-left to account for sidebar width (approx 270px for default Streamlit sidebar) */
|
| 297 |
+
padding: 15px 15px 15px 270px;
|
| 298 |
+
box-shadow: 0 -2px 10px rgba(0,0,0,0.1); /* Shadow at the top */
|
| 299 |
+
z-index: 9999;
|
| 300 |
+
box-sizing: border-box; /* Include padding in width calculation */
|
| 301 |
+
}
|
| 302 |
+
/* Style for chat history display within the fixed container */
|
| 303 |
+
#fixed-assistant-container .chat-history-display {
|
| 304 |
+
height: 120px; /* Fixed height for scrollable chat */
|
| 305 |
+
overflow-y: auto; /* Enable scrolling */
|
| 306 |
+
background-color: #e9f2fb;
|
| 307 |
+
border: 1px solid #a7d0f7;
|
| 308 |
+
border-radius: 8px;
|
| 309 |
+
padding: 10px;
|
| 310 |
+
margin-bottom: 10px;
|
| 311 |
+
font-size: 0.9em;
|
| 312 |
+
line-height: 1.4;
|
| 313 |
+
}
|
| 314 |
+
#fixed-assistant-container .chat-history-display p {
|
| 315 |
+
margin-bottom: 5px; /* Space between chat lines */
|
| 316 |
+
}
|
| 317 |
+
#fixed-assistant-container .stTextInput > div > div {
|
| 318 |
+
width: 100%; /* Make the input field take full width of its parent */
|
| 319 |
+
}
|
| 320 |
+
</style>
|
| 321 |
+
""", unsafe_allow_html=True)
|
| 322 |
+
|
| 323 |
+
|
| 324 |
+
# --- Language selection in sidebar ---
|
| 325 |
+
lang_code = st.session_state.get('lang_code', 'en') # Ensure lang_code is defined before use
|
| 326 |
+
lang_options = [LANGUAGES[lang_code][code] for code in LANGUAGES[lang_code]]
|
| 327 |
+
lang_codes = list(LANGUAGES[lang_code].keys())
|
| 328 |
+
t = translations[lang_code] # Define t before using it
|
| 329 |
+
selected_lang_display = st.sidebar.selectbox(
|
| 330 |
+
t['language'], # Use translated label
|
| 331 |
+
lang_options,
|
| 332 |
+
index=lang_codes.index(lang_code),
|
| 333 |
+
key="language_select"
|
| 334 |
+
)
|
| 335 |
+
selected_lang_code = lang_codes[lang_options.index(selected_lang_display)]
|
| 336 |
+
if selected_lang_code != lang_code:
|
| 337 |
+
st.session_state['lang_code'] = selected_lang_code
|
| 338 |
+
st.rerun()
|
| 339 |
+
lang_code = st.session_state['lang_code']
|
| 340 |
+
t = translations[lang_code] # Update translator after potential language change
|
| 341 |
+
|
| 342 |
+
# --- On This Day Feature -----------------------------------------------------
|
| 343 |
+
|
| 344 |
+
st.sidebar.header(t['on_this_day'])
|
| 345 |
+
selected_date = st.sidebar.date_input(t['pick_date'], datetime.today())
|
| 346 |
+
|
| 347 |
+
@st.cache_data(ttl=3600) # Cache for 1 hour
|
| 348 |
+
def fetch_on_this_day(month, day, lang_code_for_wiki):
|
| 349 |
+
url = f"https://{lang_code_for_wiki}.wikipedia.org/api/rest_v1/feed/onthisday/events/{month}/{day}"
|
| 350 |
+
try:
|
| 351 |
+
res = requests.get(url, timeout=5)
|
| 352 |
+
if res.status_code == 404: # Wikipedia API returns 404 if language is not supported for OnThisDay
|
| 353 |
+
return None
|
| 354 |
+
res.raise_for_status()
|
| 355 |
+
return res.json().get("events", [])
|
| 356 |
+
except requests.exceptions.RequestException as e:
|
| 357 |
+
st.sidebar.error(f"Error fetching historical events: {e}")
|
| 358 |
+
return []
|
| 359 |
+
except Exception as e:
|
| 360 |
+
st.sidebar.error(f"An unexpected error occurred while fetching historical events: {e}")
|
| 361 |
+
return []
|
| 362 |
+
|
| 363 |
+
supported_onthisday_langs = ['en', 'es', 'fr', 'de', 'ru', 'pt'] # Common languages with OTD pages
|
| 364 |
+
|
| 365 |
+
if lang_code in supported_onthisday_langs:
|
| 366 |
+
events = fetch_on_this_day(selected_date.month, selected_date.day, lang_code)
|
| 367 |
+
else:
|
| 368 |
+
st.sidebar.info(t['unsupported_onthisday'])
|
| 369 |
+
events = fetch_on_this_day(selected_date.month, selected_date.day, 'en') # Fallback to English
|
| 370 |
+
|
| 371 |
+
if events:
|
| 372 |
+
st.sidebar.subheader(t['events'])
|
| 373 |
+
for ev in events[:6]: # Limit to 6 events for brevity
|
| 374 |
+
event_text = ev['text']
|
| 375 |
+
# Only translate if the fetched language was English and target is different or if fallback to English occurred
|
| 376 |
+
if lang_code != 'en' and (lang_code not in supported_onthisday_langs or lang_code == 'en'):
|
| 377 |
+
try:
|
| 378 |
+
event_text = GoogleTranslator(source='en', target=lang_code).translate(event_text)
|
| 379 |
+
except Exception as e:
|
| 380 |
+
pass # Fallback to original text on error
|
| 381 |
+
st.sidebar.markdown(f"**{ev['year']}** — {event_text}")
|
| 382 |
+
if ev.get("pages"):
|
| 383 |
+
p = ev["pages"][0]
|
| 384 |
+
title = p["titles"]["normalized"]
|
| 385 |
+
url = p["content_urls"]["desktop"]["page"]
|
| 386 |
+
# Only translate if the fetched language was English and target is different or if fallback to English occurred
|
| 387 |
+
if lang_code != 'en' and (lang_code not in supported_onthisday_langs or lang_code == 'en'):
|
| 388 |
+
try:
|
| 389 |
+
title = GoogleTranslator(source='en', target=lang_code).translate(title)
|
| 390 |
+
except Exception as e:
|
| 391 |
+
pass # Fallback to original title on error
|
| 392 |
+
st.sidebar.markdown(f"[🔗 {title}]({url})")
|
| 393 |
+
else:
|
| 394 |
+
if lang_code in supported_onthisday_langs: # Only show 'no events' if the language is supported
|
| 395 |
+
st.sidebar.info(t['no_events'])
|
| 396 |
+
|
| 397 |
+
|
| 398 |
+
# --- Main App Title and Description ------------------------------------------
|
| 399 |
+
|
| 400 |
+
st.title(t['title'])
|
| 401 |
+
st.markdown(t['description'])
|
| 402 |
+
st.markdown("---")
|
| 403 |
+
|
| 404 |
+
# --- News Fetching and Display Functions -------------------------------------
|
| 405 |
+
|
| 406 |
+
@st.cache_data(ttl=600) # Cache for 10 minutes
|
| 407 |
+
def fetch_rss_entries(url):
|
| 408 |
+
headers = {'User-Agent': 'Mozilla/5.0'}
|
| 409 |
+
try:
|
| 410 |
+
resp = requests.get(url, headers=headers, timeout=10)
|
| 411 |
+
resp.raise_for_status()
|
| 412 |
+
feed = feedparser.parse(resp.content)
|
| 413 |
+
return feed.entries if feed.entries else None
|
| 414 |
+
except Exception as e:
|
| 415 |
+
print("RSS error:", e) # For debugging in console
|
| 416 |
+
return None
|
| 417 |
+
|
| 418 |
+
def translate_text(text, target_lang):
|
| 419 |
+
if target_lang == 'en':
|
| 420 |
+
return text
|
| 421 |
+
try:
|
| 422 |
+
return GoogleTranslator(source='auto', target=target_lang).translate(text) # Auto-detect source language
|
| 423 |
+
except Exception:
|
| 424 |
+
return text
|
| 425 |
+
|
| 426 |
+
def get_image_from_entry(entry):
|
| 427 |
+
# Try media:content first
|
| 428 |
+
if hasattr(entry, "media_content"):
|
| 429 |
+
for media in entry.media_content:
|
| 430 |
+
if "url" in media:
|
| 431 |
+
return media["url"]
|
| 432 |
+
# Fallback to looking in links with image type
|
| 433 |
+
if hasattr(entry, "links"):
|
| 434 |
+
for link in entry.links:
|
| 435 |
+
if hasattr(link, "type") and "image" in link.type:
|
| 436 |
+
return link.href
|
| 437 |
+
return None
|
| 438 |
+
|
| 439 |
+
def clean_html(raw_html):
|
| 440 |
+
if not raw_html:
|
| 441 |
+
return ""
|
| 442 |
+
soup = BeautifulSoup(raw_html, "html.parser")
|
| 443 |
+
return soup.get_text(separator=" ", strip=True)
|
| 444 |
+
|
| 445 |
+
def display_news_cards_in_two_columns(news_items):
|
| 446 |
+
col1, col2 = st.columns(2)
|
| 447 |
+
card_style = (
|
| 448 |
+
"background-color: #add8e6; border-radius: 10px; padding: 10px; "
|
| 449 |
+
"margin-bottom: 10px; color: #002244; font-family: sans-serif;"
|
| 450 |
+
)
|
| 451 |
+
for i, item in enumerate(news_items):
|
| 452 |
+
with col1 if i % 2 == 0 else col2:
|
| 453 |
+
content = ""
|
| 454 |
+
if item["image"]:
|
| 455 |
+
content += f'<img src="{item["image"]}" style="width:100%; border-radius: 8px; margin-bottom: 0.5em;" />'
|
| 456 |
+
content += f"""<h4 style="margin-bottom: 0.5em;">{item['title']}</h4>"""
|
| 457 |
+
if item["summary"]:
|
| 458 |
+
content += f"""<div style="margin-bottom: 0.5em;">{item["summary"]}</div>"""
|
| 459 |
+
st.markdown(
|
| 460 |
+
f"<div style='{card_style}'>{content}</div>",
|
| 461 |
+
unsafe_allow_html=True
|
| 462 |
+
)
|
| 463 |
+
st.markdown(
|
| 464 |
+
f"[{t['read_more']}]({item['url']})",
|
| 465 |
+
unsafe_allow_html=False
|
| 466 |
+
)
|
| 467 |
+
|
| 468 |
+
# --- News Display Section ----------------------------------------------------
|
| 469 |
+
|
| 470 |
+
st.header(t['todays_headlines'])
|
| 471 |
+
tabs = st.tabs(list(CATEGORY_FEEDS.keys()))
|
| 472 |
+
for tab, (cat, feed_url) in zip(tabs, CATEGORY_FEEDS.items()):
|
| 473 |
+
with tab:
|
| 474 |
+
st.subheader(cat)
|
| 475 |
+
entries = fetch_rss_entries(feed_url)
|
| 476 |
+
if not entries:
|
| 477 |
+
st.error(t['couldnt_load_news'])
|
| 478 |
+
else:
|
| 479 |
+
news_items = []
|
| 480 |
+
for e in entries[:8]: # Limit to 8 articles per category
|
| 481 |
+
title = translate_text(e.title, lang_code)
|
| 482 |
+
summary = getattr(e, "summary", getattr(e, "description", ""))
|
| 483 |
+
summary = clean_html(summary)
|
| 484 |
+
summary = translate_text(summary, lang_code) if summary else ""
|
| 485 |
+
image_url = get_image_from_entry(e)
|
| 486 |
+
news_items.append({
|
| 487 |
+
"title": title,
|
| 488 |
+
"summary": summary,
|
| 489 |
+
"image": image_url,
|
| 490 |
+
"url": e.link
|
| 491 |
+
})
|
| 492 |
+
display_news_cards_in_two_columns(news_items)
|
| 493 |
+
|
| 494 |
+
# Refresh button
|
| 495 |
+
if st.button(t['refresh_news']):
|
| 496 |
+
st.cache_data.clear() # Clear all caches including RSS feeds
|
| 497 |
+
st.session_state['chat_history'] = [] # Clear AI chat history too
|
| 498 |
+
st.rerun()
|
| 499 |
+
|
| 500 |
+
# --- AI Assistant Section ----------------------------------------------------
|
| 501 |
+
|
| 502 |
+
# Fixed position container for the AI assistant
|
| 503 |
+
st.markdown("<div id='fixed-assistant-container'>", unsafe_allow_html=True)
|
| 504 |
+
|
| 505 |
+
st.header(t['ask_ai'])
|
| 506 |
+
|
| 507 |
+
# Display chat history
|
| 508 |
+
with st.container():
|
| 509 |
+
st.markdown("<div class='chat-history-display'>", unsafe_allow_html=True)
|
| 510 |
+
if not st.session_state.chat_history:
|
| 511 |
+
st.markdown("Say hello! I'm your Timescope Assistant, ready to help you explore news and history.")
|
| 512 |
+
for msg in st.session_state.chat_history:
|
| 513 |
+
role_label = "🧑💻 You" if msg["role"] == "user" else "🤖 Assistant"
|
| 514 |
+
st.markdown(f"**{role_label}:** {translate_text(msg['content'], lang_code)}") # Translate history too
|
| 515 |
+
st.markdown("</div>", unsafe_allow_html=True)
|
| 516 |
+
|
| 517 |
+
# Input form for the AI assistant
|
| 518 |
+
with st.form("chat_form", clear_on_submit=True):
|
| 519 |
+
user_input = st.text_input(t['ask_placeholder'],
|
| 520 |
+
key="assistant_input",
|
| 521 |
+
label_visibility="collapsed",
|
| 522 |
+
placeholder=t['ask_placeholder']) # Use translated placeholder
|
| 523 |
+
send_button = st.form_submit_button("Send")
|
| 524 |
+
|
| 525 |
+
if send_button and user_input:
|
| 526 |
+
# Add user message to history
|
| 527 |
+
st.session_state.chat_history.append({"role": "user", "content": user_input})
|
| 528 |
+
|
| 529 |
+
with st.spinner("Thinking..."):
|
| 530 |
+
try:
|
| 531 |
+
# Check if API key is truly available before making the call
|
| 532 |
+
if not openrouter_api_key or openrouter_api_key == "sk-dummy-key-for-no-ai":
|
| 533 |
+
st.error(f"{t['ai_error']} OpenRouter API Key is not set. Please add it to your `.env` file.")
|
| 534 |
+
else:
|
| 535 |
+
# Build the messages list first
|
| 536 |
+
messages = [
|
| 537 |
+
{"role": "system", "content": translate_text('You are a helpful assistant about world news and history.', lang_code)}
|
| 538 |
+
] + [
|
| 539 |
+
{"role": m["role"], "content": m["content"]} for m in st.session_state.chat_history
|
| 540 |
+
]
|
| 541 |
+
resp = client.chat.completions.create(
|
| 542 |
+
model=DEFAULT_AI_MODEL, # Use the OpenRouter model
|
| 543 |
+
messages=messages,
|
| 544 |
+
max_tokens=1000, # Max tokens to control response length and cost
|
| 545 |
+
)
|
| 546 |
+
assistant_response = resp.choices[0].message.content.strip()
|
| 547 |
+
st.session_state.chat_history.append({"role": "assistant", "content": assistant_response}) # Store original response
|
| 548 |
+
# No need to display directly here, it will be rerendered by st.markdown in history display
|
| 549 |
+
st.rerun() # Rerun to update chat history display
|
| 550 |
+
except Exception as e:
|
| 551 |
+
if isinstance(e, RateLimitError):
|
| 552 |
+
st.error(f"{t['ai_error']} You've hit a rate limit. Please wait a moment and try again.")
|
| 553 |
+
st.error(f"{t['ai_error']} You've hit a rate limit. Please wait a moment and try again.")
|
| 554 |
+
elif isinstance(e, AuthenticationError):
|
| 555 |
+
st.error(f"{t['ai_error']} Authentication failed. Please check your OpenRouter API key in your `.env` file.")
|
| 556 |
+
elif isinstance(e, APIConnectionError):
|
| 557 |
+
st.error(f"{t['ai_error']} Could not connect to the AI service. Please check your internet connection or the OpenRouter API status.")
|
| 558 |
+
elif isinstance(e, APIStatusError):
|
| 559 |
+
# This handles the 402 error for credits as well as other API errors
|
| 560 |
+
st.error(f"{t['ai_error']} An API error occurred: {e.status_code} - {e.response.text if hasattr(e.response, 'text') else str(e)}")
|
| 561 |
+
else:
|
| 562 |
+
st.error(f"{t['ai_error']} An unexpected error occurred: {e}")
|
| 563 |
+
st.session_state.chat_history.append({"role": "assistant", "content": f"Error: {e}"}) # Add error to history
|
| 564 |
+
st.rerun() # Rerun to display error in history
|
| 565 |
+
|
| 566 |
+
st.markdown("</div>", unsafe_allow_html=True) # Close fixed-assistant-container
|