saherPervaiz commited on
Commit
935239e
Β·
verified Β·
1 Parent(s): f14f5f2

Update app.py

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