Spaces:
Running
Running
import streamlit as st | |
import sqlite3 | |
import requests | |
from datetime import datetime | |
# Connect to the SQLite database | |
def connect_db(): | |
conn = sqlite3.connect("news_aggregator.db") | |
return conn | |
# Function to create or update the articles in the database | |
def insert_article(title, description, link, topic, date_published): | |
conn = connect_db() | |
cursor = conn.cursor() | |
# Insert article into the database | |
cursor.execute(''' | |
INSERT INTO articles (title, description, link, topic, date_published) | |
VALUES (?, ?, ?, ?, ?) | |
''', (title, description, link, topic, date_published)) | |
conn.commit() | |
conn.close() | |
# Function to fetch news articles from an API (e.g., NewsAPI) | |
def fetch_news_api(topic, keyword): | |
api_key = 'fe1e6bcbbf384b3e9220a7a1138805e0' # Replace with your News API key | |
url = f'https://newsapi.org/v2/everything?q={keyword}&category={topic}&apiKey={api_key}' | |
response = requests.get(url) | |
if response.status_code == 200: | |
return response.json()['articles'] | |
else: | |
return [] | |
# Function to fetch articles from the database based on topic and filter | |
def fetch_articles_from_db(topic, keyword_filter=None): | |
conn = connect_db() | |
cursor = conn.cursor() | |
query = 'SELECT * FROM articles WHERE topic=?' | |
params = (topic,) | |
if keyword_filter: | |
query += ' AND description LIKE ?' | |
params = (topic, f'%{keyword_filter}%') | |
cursor.execute(query, params) | |
articles = cursor.fetchall() | |
conn.close() | |
return articles | |
# Streamlit UI code | |
def main(): | |
st.title("News Aggregator") | |
# Topic selection | |
topic = st.selectbox("Select Topic", ['Sports', 'Politics', 'Technology']) | |
keyword_filter = st.text_input("Filter by Keyword") | |
# Fetch news articles | |
if st.button("Fetch News"): | |
# First, fetch from News API | |
articles = fetch_news_api(topic, keyword_filter) | |
# Insert the fetched articles into the database | |
for article in articles: | |
insert_article( | |
article['title'], | |
article['description'], | |
article['url'], | |
topic, | |
article['publishedAt'] | |
) | |
st.success(f"Fetched {len(articles)} articles from News API.") | |
# Fetch and display articles from the database | |
st.subheader("Articles from Database") | |
fetched_articles = fetch_articles_from_db(topic, keyword_filter) | |
if fetched_articles: | |
for article in fetched_articles: | |
st.write(f"**Title**: {article[1]}") | |
st.write(f"**Description**: {article[2]}") | |
st.write(f"**Link**: {article[3]}") | |
st.write(f"**Published**: {article[5]}") | |
st.write("---") | |
else: | |
st.write("No articles found for this topic.") | |
if __name__ == '__main__': | |
main() | |