saherPervaiz commited on
Commit
7016b34
Β·
verified Β·
1 Parent(s): 10a3f71

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +74 -77
app.py CHANGED
@@ -1,97 +1,94 @@
1
  import streamlit as st
 
2
  import requests
 
3
 
4
- # Replace this with your actual News API key
5
- API_KEY = "fe1e6bcbbf384b3e9220a7a1138805e0" # πŸ”‘ Add your NewsAPI.org API key here
 
 
6
 
7
- publisher_articles = []
 
 
 
 
 
 
 
 
 
 
 
 
8
 
9
- def fetch_news(topic, keyword):
10
- query = f"{topic} {keyword}" if keyword else topic
11
- url = f"https://newsapi.org/v2/everything?q={query}&apiKey={API_KEY}"
 
12
  response = requests.get(url)
 
13
  if response.status_code == 200:
14
- return response.json().get("articles", [])
15
  else:
16
- st.error("Failed to fetch news. Check your API key or internet connection.")
17
  return []
18
 
19
- def main():
20
- st.title("πŸ“° News Aggregator")
21
- st.write("Publish and subscribe to topics to get the latest updates!")
22
-
23
- menu = ["Home", "Publisher Panel", "Subscriber Panel"]
24
- choice = st.sidebar.selectbox("Choose a panel:", menu)
25
-
26
- if choice == "Home":
27
- st.header("Welcome to the News Aggregator!")
28
- st.write("Navigate to the **Publisher Panel** to add news articles or to the **Subscriber Panel** to view articles.")
29
 
30
- elif choice == "Publisher Panel":
31
- st.header("πŸ“ Publisher Panel")
32
- st.write("Publish articles to relevant topics.")
33
-
34
- title = st.text_input("Article Title:")
35
- description = st.text_area("Article Description:")
36
- link = st.text_input("Article Link:")
37
- topic = st.selectbox("Select Topic:", ["Sports", "Politics", "Technology", "Entertainment", "Health", "Science"])
38
 
39
- if st.button("Publish Article"):
40
- if title and description and link and topic:
41
- publisher_articles.append({"title": title, "description": description, "link": link, "topic": topic})
42
- st.success(f"Article on '{topic}' published successfully!")
43
- else:
44
- st.warning("Please fill in all fields before publishing.")
45
 
46
- elif choice == "Subscriber Panel":
47
- st.header("πŸ”” Subscriber Panel")
48
- st.write("Subscribe to topics and view news articles.")
49
-
50
- topics = ["Sports", "Politics", "Technology", "Entertainment", "Health", "Science"]
51
- selected_topics = st.multiselect("Select topics to subscribe to:", topics)
52
- keyword_filter = st.text_input("πŸ” Enter a keyword to filter news:")
53
 
54
- if st.button("Fetch News"):
55
- if not selected_topics:
56
- st.warning("Please select at least one topic to subscribe to.")
57
- else:
58
- # Notify user about subscription
59
- st.success(f"πŸ”” You have subscribed to: {', '.join(selected_topics)}")
60
- st.info("Fetching news articles...")
61
 
62
- all_articles = []
 
 
63
 
64
- # Fetch publisher articles for selected topics
65
- for article in publisher_articles:
66
- if article["topic"] in selected_topics:
67
- all_articles.append(article)
68
-
69
- # Fetch external news articles from API
70
- for topic in selected_topics:
71
- fetched_articles = fetch_news(topic, keyword_filter)
72
- for article in fetched_articles:
73
- all_articles.append({
74
- "title": article.get("title", "No Title"),
75
- "description": article.get("description", "No Description"),
76
- "link": article.get("url", "#"),
77
- "topic": topic
78
- })
79
 
80
- # Filter articles by keyword if provided
81
- if keyword_filter:
82
- all_articles = [a for a in all_articles if keyword_filter.lower() in a["title"].lower()]
 
83
 
84
- if all_articles:
85
- st.success(f"Found {len(all_articles)} articles!")
86
- for article in all_articles:
87
- st.subheader(article["title"])
88
- st.write(article["description"])
89
- st.write(f"Topic: {article['topic']}")
90
- st.write(f"[Read more]({article['link']})")
91
- st.write("---")
92
- else:
93
- st.info("No articles found for the selected topics or keyword.")
 
94
 
95
- if __name__ == "__main__":
96
- main()
 
 
 
 
 
 
 
 
 
 
 
97
 
 
 
 
1
  import streamlit as st
2
+ import sqlite3
3
  import requests
4
+ from datetime import datetime
5
 
6
+ # Connect to the SQLite database
7
+ def connect_db():
8
+ conn = sqlite3.connect("news_aggregator.db")
9
+ return conn
10
 
11
+ # Function to create or update the articles in the database
12
+ def insert_article(title, description, link, topic, date_published):
13
+ conn = connect_db()
14
+ cursor = conn.cursor()
15
+
16
+ # Insert article into the database
17
+ cursor.execute('''
18
+ INSERT INTO articles (title, description, link, topic, date_published)
19
+ VALUES (?, ?, ?, ?, ?)
20
+ ''', (title, description, link, topic, date_published))
21
+
22
+ conn.commit()
23
+ conn.close()
24
 
25
+ # Function to fetch news articles from an API (e.g., NewsAPI)
26
+ def fetch_news_api(topic, keyword):
27
+ api_key = 'fe1e6bcbbf384b3e9220a7a1138805e0' # Replace with your News API key
28
+ url = f'https://newsapi.org/v2/everything?q={keyword}&category={topic}&apiKey={api_key}'
29
  response = requests.get(url)
30
+
31
  if response.status_code == 200:
32
+ return response.json()['articles']
33
  else:
 
34
  return []
35
 
36
+ # Function to fetch articles from the database based on topic and filter
37
+ def fetch_articles_from_db(topic, keyword_filter=None):
38
+ conn = connect_db()
39
+ cursor = conn.cursor()
 
 
 
 
 
 
40
 
41
+ query = 'SELECT * FROM articles WHERE topic=?'
42
+ params = (topic,)
 
 
 
 
 
 
43
 
44
+ if keyword_filter:
45
+ query += ' AND description LIKE ?'
46
+ params = (topic, f'%{keyword_filter}%')
 
 
 
47
 
48
+ cursor.execute(query, params)
49
+ articles = cursor.fetchall()
50
+ conn.close()
 
 
 
 
51
 
52
+ return articles
 
 
 
 
 
 
53
 
54
+ # Streamlit UI code
55
+ def main():
56
+ st.title("News Aggregator")
57
 
58
+ # Topic selection
59
+ topic = st.selectbox("Select Topic", ['Sports', 'Politics', 'Technology'])
60
+ keyword_filter = st.text_input("Filter by Keyword")
 
 
 
 
 
 
 
 
 
 
 
 
61
 
62
+ # Fetch news articles
63
+ if st.button("Fetch News"):
64
+ # First, fetch from News API
65
+ articles = fetch_news_api(topic, keyword_filter)
66
 
67
+ # Insert the fetched articles into the database
68
+ for article in articles:
69
+ insert_article(
70
+ article['title'],
71
+ article['description'],
72
+ article['url'],
73
+ topic,
74
+ article['publishedAt']
75
+ )
76
+
77
+ st.success(f"Fetched {len(articles)} articles from News API.")
78
 
79
+ # Fetch and display articles from the database
80
+ st.subheader("Articles from Database")
81
+ fetched_articles = fetch_articles_from_db(topic, keyword_filter)
82
+
83
+ if fetched_articles:
84
+ for article in fetched_articles:
85
+ st.write(f"**Title**: {article[1]}")
86
+ st.write(f"**Description**: {article[2]}")
87
+ st.write(f"**Link**: {article[3]}")
88
+ st.write(f"**Published**: {article[5]}")
89
+ st.write("---")
90
+ else:
91
+ st.write("No articles found for this topic.")
92
 
93
+ if __name__ == '__main__':
94
+ main()