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|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import streamlit as st
|
| 2 |
+
import requests
|
| 3 |
+
from bs4 import BeautifulSoup
|
| 4 |
+
from openai import OpenAI
|
| 5 |
+
from dotenv import load_dotenv
|
| 6 |
+
import os
|
| 7 |
+
from urllib.parse import urljoin, urlparse
|
| 8 |
+
from pymongo import MongoClient
|
| 9 |
+
from bson.objectid import ObjectId
|
| 10 |
+
import time
|
| 11 |
+
import threading
|
| 12 |
+
|
| 13 |
+
# Load environment variables from .env file
|
| 14 |
+
load_dotenv()
|
| 15 |
+
|
| 16 |
+
# Set up OpenAI client
|
| 17 |
+
client = OpenAI(api_key=os.getenv("OPENAI_API_KEY"))
|
| 18 |
+
|
| 19 |
+
# MongoDB setup
|
| 20 |
+
MONGO_URI = os.getenv("MONGO_URI")
|
| 21 |
+
mongo_client = MongoClient(MONGO_URI)
|
| 22 |
+
db = mongo_client.website_summarizer
|
| 23 |
+
|
| 24 |
+
# User management functions
|
| 25 |
+
def add_user(username, password):
|
| 26 |
+
if db.users.find_one({"username": username}):
|
| 27 |
+
return False
|
| 28 |
+
db.users.insert_one({
|
| 29 |
+
"username": username,
|
| 30 |
+
"password": password,
|
| 31 |
+
"update_interval": 3 * 3600 # Default to 3 hours in seconds
|
| 32 |
+
})
|
| 33 |
+
return True
|
| 34 |
+
|
| 35 |
+
def check_user(username, password):
|
| 36 |
+
user = db.users.find_one({"username": username, "password": password})
|
| 37 |
+
return user is not None
|
| 38 |
+
|
| 39 |
+
def get_user_settings(username):
|
| 40 |
+
user = db.users.find_one({"username": username})
|
| 41 |
+
return user.get("update_interval", 3 * 3600) if user else 3 * 3600
|
| 42 |
+
|
| 43 |
+
def update_user_settings(username, update_interval):
|
| 44 |
+
db.users.update_one(
|
| 45 |
+
{"username": username},
|
| 46 |
+
{"$set": {"update_interval": update_interval}}
|
| 47 |
+
)
|
| 48 |
+
|
| 49 |
+
def summarize_text(text):
|
| 50 |
+
try:
|
| 51 |
+
response = client.chat.completions.create(
|
| 52 |
+
model="gpt-4o-mini",
|
| 53 |
+
messages=[
|
| 54 |
+
{"role": "system", "content": "You are a helpful assistant that summarizes text."},
|
| 55 |
+
{"role": "user", "content": f"Summarize the key points of this text in 5-10 bullet points: {text[:4000]}"}
|
| 56 |
+
]
|
| 57 |
+
)
|
| 58 |
+
return response.choices[0].message.content
|
| 59 |
+
except Exception as e:
|
| 60 |
+
return None
|
| 61 |
+
|
| 62 |
+
def scrape_and_summarize(url):
|
| 63 |
+
try:
|
| 64 |
+
response = requests.get(url, timeout=10)
|
| 65 |
+
response.raise_for_status()
|
| 66 |
+
soup = BeautifulSoup(response.text, 'html.parser')
|
| 67 |
+
|
| 68 |
+
title = soup.title.string if soup.title else "No title found"
|
| 69 |
+
|
| 70 |
+
for script in soup(["script", "style"]):
|
| 71 |
+
script.decompose()
|
| 72 |
+
|
| 73 |
+
text = soup.get_text(separator=' ', strip=True)
|
| 74 |
+
|
| 75 |
+
summary = summarize_text(text)
|
| 76 |
+
|
| 77 |
+
if summary:
|
| 78 |
+
return {"title": title, "url": url, "summary": summary, "summarized": True}
|
| 79 |
+
else:
|
| 80 |
+
return {"title": title, "url": url, "summary": "Summary could not be generated.", "summarized": False}
|
| 81 |
+
except Exception as e:
|
| 82 |
+
return {"title": "Error", "url": url, "summary": f"Error processing the URL: {str(e)}", "summarized": False}
|
| 83 |
+
|
| 84 |
+
def scrape_multiple_urls(main_url, limit=10):
|
| 85 |
+
try:
|
| 86 |
+
response = requests.get(main_url, timeout=10)
|
| 87 |
+
response.raise_for_status()
|
| 88 |
+
soup = BeautifulSoup(response.text, 'html.parser')
|
| 89 |
+
|
| 90 |
+
links = soup.find_all('a', href=True)
|
| 91 |
+
urls_to_scrape = []
|
| 92 |
+
|
| 93 |
+
for link in links:
|
| 94 |
+
if len(urls_to_scrape) >= limit:
|
| 95 |
+
break
|
| 96 |
+
|
| 97 |
+
href = link['href']
|
| 98 |
+
full_url = urljoin(main_url, href)
|
| 99 |
+
|
| 100 |
+
# Only include URLs from the same domain
|
| 101 |
+
if urlparse(full_url).netloc == urlparse(main_url).netloc:
|
| 102 |
+
urls_to_scrape.append(full_url)
|
| 103 |
+
|
| 104 |
+
results = []
|
| 105 |
+
for url in urls_to_scrape:
|
| 106 |
+
result = scrape_and_summarize(url)
|
| 107 |
+
results.append(result)
|
| 108 |
+
|
| 109 |
+
return results
|
| 110 |
+
except Exception as e:
|
| 111 |
+
return [{"title": "Error", "url": main_url, "summary": f"Error processing the main URL: {str(e)}", "summarized": False}]
|
| 112 |
+
|
| 113 |
+
def save_urls(username, main_url):
|
| 114 |
+
results = scrape_multiple_urls(main_url)
|
| 115 |
+
main_result = results[0] # Assume the first result is the main URL
|
| 116 |
+
db.user_urls.insert_one({
|
| 117 |
+
"username": username,
|
| 118 |
+
"url": main_result["url"],
|
| 119 |
+
"title": main_result["title"],
|
| 120 |
+
"summarized": main_result["summarized"],
|
| 121 |
+
"summary": main_result["summary"],
|
| 122 |
+
"sub_urls": results[1:] # Store other URLs as sub_urls
|
| 123 |
+
})
|
| 124 |
+
return len(results)
|
| 125 |
+
|
| 126 |
+
def get_user_urls(username):
|
| 127 |
+
return list(db.user_urls.find({"username": username}))
|
| 128 |
+
|
| 129 |
+
def delete_url(url_id):
|
| 130 |
+
db.user_urls.delete_one({"_id": ObjectId(url_id)})
|
| 131 |
+
|
| 132 |
+
def get_feed(username):
|
| 133 |
+
return list(db.user_urls.find({"username": username, "summarized": True}))
|
| 134 |
+
|
| 135 |
+
def summarize_url(url_doc):
|
| 136 |
+
result = scrape_and_summarize(url_doc['url'])
|
| 137 |
+
db.user_urls.update_one(
|
| 138 |
+
{"_id": url_doc['_id']},
|
| 139 |
+
{"$set": {
|
| 140 |
+
"title": result["title"],
|
| 141 |
+
"summarized": result["summarized"],
|
| 142 |
+
"summary": result["summary"]
|
| 143 |
+
}}
|
| 144 |
+
)
|
| 145 |
+
return result["summarized"]
|
| 146 |
+
|
| 147 |
+
def summarize_multiple_urls(username, limit=10):
|
| 148 |
+
unsummarized_urls = list(db.user_urls.find({"username": username, "summarized": False}).limit(limit))
|
| 149 |
+
summarized_count = 0
|
| 150 |
+
error_count = 0
|
| 151 |
+
results = []
|
| 152 |
+
for url_doc in unsummarized_urls:
|
| 153 |
+
result = scrape_and_summarize(url_doc['url'])
|
| 154 |
+
result['url'] = url_doc['url'] # Add the URL to the result
|
| 155 |
+
db.user_urls.update_one(
|
| 156 |
+
{"_id": url_doc['_id']},
|
| 157 |
+
{"$set": {
|
| 158 |
+
"title": result["title"],
|
| 159 |
+
"summarized": result["summarized"],
|
| 160 |
+
"summary": result["summary"],
|
| 161 |
+
"url": url_doc['url']
|
| 162 |
+
}}
|
| 163 |
+
)
|
| 164 |
+
if result["summarized"]:
|
| 165 |
+
summarized_count += 1
|
| 166 |
+
results.append(result)
|
| 167 |
+
else:
|
| 168 |
+
error_count += 1
|
| 169 |
+
return summarized_count, error_count, results
|
| 170 |
+
|
| 171 |
+
# Add this function to update summaries periodically
|
| 172 |
+
def update_summaries(username, interval):
|
| 173 |
+
while True:
|
| 174 |
+
time.sleep(interval)
|
| 175 |
+
with st.spinner("Updating summaries..."):
|
| 176 |
+
summarized_count, error_count, _ = summarize_multiple_urls(username)
|
| 177 |
+
st.success(f"Updated {summarized_count} summaries. {error_count} errors occurred.")
|
| 178 |
+
|
| 179 |
+
st.set_page_config(layout="wide", page_title="Website Links Summarizer")
|
| 180 |
+
|
| 181 |
+
# Session state
|
| 182 |
+
if 'logged_in' not in st.session_state:
|
| 183 |
+
st.session_state.logged_in = False
|
| 184 |
+
st.session_state.username = None
|
| 185 |
+
|
| 186 |
+
# Initialize session state variables
|
| 187 |
+
if 'update_interval' not in st.session_state:
|
| 188 |
+
st.session_state.update_interval = 3 * 3600 # Default to 3 hours in seconds
|
| 189 |
+
|
| 190 |
+
# Login/Signup sidebar
|
| 191 |
+
with st.sidebar:
|
| 192 |
+
st.title("User Authentication")
|
| 193 |
+
if not st.session_state.logged_in:
|
| 194 |
+
choice = st.radio("Login/Signup", ["Login", "Sign Up"])
|
| 195 |
+
username = st.text_input("Username")
|
| 196 |
+
password = st.text_input("Password", type="password")
|
| 197 |
+
|
| 198 |
+
if choice == "Sign Up":
|
| 199 |
+
if st.button("Sign Up"):
|
| 200 |
+
if username and password:
|
| 201 |
+
if add_user(username, password):
|
| 202 |
+
st.success("Account created successfully!")
|
| 203 |
+
else:
|
| 204 |
+
st.error("Username already exists.")
|
| 205 |
+
else:
|
| 206 |
+
st.error("Please enter both username and password.")
|
| 207 |
+
else:
|
| 208 |
+
if st.button("Login"):
|
| 209 |
+
if check_user(username, password):
|
| 210 |
+
st.session_state.logged_in = True
|
| 211 |
+
st.session_state.username = username
|
| 212 |
+
st.session_state.update_interval = get_user_settings(username)
|
| 213 |
+
st.success("Logged in successfully!")
|
| 214 |
+
st.rerun()
|
| 215 |
+
else:
|
| 216 |
+
st.error("Invalid username or password.")
|
| 217 |
+
else:
|
| 218 |
+
st.write(f"Logged in as {st.session_state.username}")
|
| 219 |
+
if st.button("Logout"):
|
| 220 |
+
st.session_state.logged_in = False
|
| 221 |
+
st.session_state.username = None
|
| 222 |
+
st.rerun()
|
| 223 |
+
|
| 224 |
+
# Main app
|
| 225 |
+
if st.session_state.logged_in:
|
| 226 |
+
tab1, tab2, tab3 = st.tabs(["Dashboard", "Feed", "Settings"])
|
| 227 |
+
|
| 228 |
+
with tab1:
|
| 229 |
+
st.header("URL Dashboard")
|
| 230 |
+
|
| 231 |
+
col1, col2 = st.columns([3, 1])
|
| 232 |
+
|
| 233 |
+
with col1:
|
| 234 |
+
# Add new URL
|
| 235 |
+
new_url = st.text_input("Enter a new URL to save:")
|
| 236 |
+
if st.button("Add URL"):
|
| 237 |
+
if new_url:
|
| 238 |
+
with st.spinner("Adding URL and generating summaries..."):
|
| 239 |
+
num_added = save_urls(st.session_state.username, new_url)
|
| 240 |
+
st.success(f"Added main URL and found {num_added - 1} related URLs successfully!")
|
| 241 |
+
st.rerun()
|
| 242 |
+
else:
|
| 243 |
+
st.warning("Please enter a valid URL.")
|
| 244 |
+
|
| 245 |
+
with col2:
|
| 246 |
+
# Summarize 10 Links button
|
| 247 |
+
if st.button("Summarize 10 Links"):
|
| 248 |
+
with st.spinner("Summarizing up to 10 unsummarized URLs..."):
|
| 249 |
+
summarized_count, error_count, results = summarize_multiple_urls(st.session_state.username)
|
| 250 |
+
st.success(f"Summarized {summarized_count} URL(s)!")
|
| 251 |
+
if error_count > 0:
|
| 252 |
+
st.warning(f"Failed to summarize {error_count} URL(s).")
|
| 253 |
+
|
| 254 |
+
# Display the summarized links
|
| 255 |
+
if results:
|
| 256 |
+
st.subheader("Recently Summarized URLs")
|
| 257 |
+
for result in results:
|
| 258 |
+
with st.expander(result["title"]):
|
| 259 |
+
st.markdown(f"**URL:** [{result['url']}]({result['url']})")
|
| 260 |
+
st.write("**Summary:**")
|
| 261 |
+
st.markdown(result["summary"])
|
| 262 |
+
|
| 263 |
+
st.rerun()
|
| 264 |
+
|
| 265 |
+
# Display saved URLs
|
| 266 |
+
st.subheader("Your Saved URLs")
|
| 267 |
+
user_urls = get_user_urls(st.session_state.username)
|
| 268 |
+
|
| 269 |
+
for url in user_urls:
|
| 270 |
+
with st.expander(url.get("title", url["url"])):
|
| 271 |
+
st.markdown(f"**URL:** [{url['url']}]({url['url']})")
|
| 272 |
+
st.write(f"**Status:** {'Summarized' if url.get('summarized', False) else 'Not summarized'}")
|
| 273 |
+
st.write("**Summary:**")
|
| 274 |
+
summary = url.get('summary', 'No summary available.')
|
| 275 |
+
st.markdown(summary)
|
| 276 |
+
|
| 277 |
+
# Display sub-urls if available
|
| 278 |
+
if 'sub_urls' in url and url['sub_urls']:
|
| 279 |
+
st.write("**Related URLs:**")
|
| 280 |
+
for sub_url in url['sub_urls']:
|
| 281 |
+
st.markdown(f"- [{sub_url['url']}]({sub_url['url']})")
|
| 282 |
+
if sub_url.get('summarized', False):
|
| 283 |
+
st.markdown(f" Summary: {sub_url.get('summary', 'No summary available.')}")
|
| 284 |
+
|
| 285 |
+
col1, col2 = st.columns([3, 1])
|
| 286 |
+
with col1:
|
| 287 |
+
if st.button("Delete", key=f"delete_{url['_id']}"):
|
| 288 |
+
delete_url(url['_id'])
|
| 289 |
+
st.rerun()
|
| 290 |
+
with col2:
|
| 291 |
+
if not url.get('summarized', False):
|
| 292 |
+
if st.button("Summarize", key=f"summarize_{url['_id']}"):
|
| 293 |
+
with st.spinner("Summarizing..."):
|
| 294 |
+
if summarize_url(url):
|
| 295 |
+
st.success("Summary generated!")
|
| 296 |
+
else:
|
| 297 |
+
st.error("Failed to generate summary.")
|
| 298 |
+
st.rerun()
|
| 299 |
+
|
| 300 |
+
with tab2:
|
| 301 |
+
st.header("Your Feed")
|
| 302 |
+
feed_items = get_feed(st.session_state.username)
|
| 303 |
+
|
| 304 |
+
for item in feed_items:
|
| 305 |
+
with st.expander(item.get("title", item["url"])):
|
| 306 |
+
st.markdown(f"**URL:** [{item['url']}]({item['url']})")
|
| 307 |
+
summary = item.get('summary', 'No summary available.')
|
| 308 |
+
st.markdown(summary)
|
| 309 |
+
|
| 310 |
+
# Display related URLs if available
|
| 311 |
+
if 'sub_urls' in item and item['sub_urls']:
|
| 312 |
+
st.write("**Related URLs:**")
|
| 313 |
+
for sub_url in item['sub_urls']:
|
| 314 |
+
st.markdown(f"- [{sub_url['url']}]({sub_url['url']})")
|
| 315 |
+
if sub_url.get('summarized', False):
|
| 316 |
+
st.markdown(f" Summary: {sub_url.get('summary', 'No summary available.')}")
|
| 317 |
+
|
| 318 |
+
if not feed_items:
|
| 319 |
+
st.info("Your feed is empty. Add some URLs in the Dashboard to see their summaries here!")
|
| 320 |
+
|
| 321 |
+
with tab3:
|
| 322 |
+
st.header("Settings")
|
| 323 |
+
update_interval_hours = st.number_input("Update interval (hours)", min_value=1, value=st.session_state.update_interval // 3600, step=1)
|
| 324 |
+
if st.button("Save Settings"):
|
| 325 |
+
new_interval = update_interval_hours * 3600 # Convert hours to seconds
|
| 326 |
+
st.session_state.update_interval = new_interval
|
| 327 |
+
update_user_settings(st.session_state.username, new_interval)
|
| 328 |
+
st.success("Settings saved!")
|
| 329 |
+
|
| 330 |
+
if 'update_thread' not in st.session_state:
|
| 331 |
+
st.session_state.update_thread = threading.Thread(
|
| 332 |
+
target=update_summaries,
|
| 333 |
+
args=(st.session_state.username, st.session_state.update_interval),
|
| 334 |
+
daemon=True
|
| 335 |
+
)
|
| 336 |
+
st.session_state.update_thread.start()
|
| 337 |
+
|
| 338 |
+
else:
|
| 339 |
+
st.warning("Please log in to use the Website Links Summarizer.")
|
| 340 |
+
|
| 341 |
+
# Add this at the end of the script
|
| 342 |
+
if st.session_state.get('update_thread'):
|
| 343 |
+
st.session_state.update_thread.join(timeout=0)
|