gskdsrikrishna commited on
Commit
77e730a
Β·
verified Β·
1 Parent(s): 41075e0

Update news.py

Browse files
Files changed (1) hide show
  1. news.py +40 -116
news.py CHANGED
@@ -4,123 +4,47 @@ import pandas as pd
4
  import matplotlib.pyplot as plt
5
  from datetime import datetime, timedelta
6
 
7
- # Set page configuration
8
- st.set_page_config(page_title="News Fetcher", layout="wide")
9
 
10
- # Define supported countries
11
- COUNTRIES = {
12
- 'us': 'United States', 'in': 'India', 'gb': 'United Kingdom',
13
- 'ca': 'Canada', 'au': 'Australia', 'de': 'Germany',
14
- 'fr': 'France', 'it': 'Italy', 'jp': 'Japan', 'cn': 'China',
15
- 'br': 'Brazil', 'za': 'South Africa', 'ru': 'Russia'
16
- }
17
-
18
- # Define important queries
19
- IMPORTANT_QUERIES = [
20
- "COVID-19", "Technology", "Politics", "Economy", "Health",
21
- "Environment", "Sports", "Entertainment", "Science", "Education", "Travel"
22
- ]
23
-
24
- # Define available languages
25
- LANGUAGES = {
26
- 'en': 'English', 'es': 'Spanish', 'fr': 'French',
27
- 'de': 'German', 'it': 'Italian', 'pt': 'Portuguese',
28
- 'ar': 'Arabic', 'zh': 'Chinese', 'hi': 'Hindi', 'te': 'Telugu'
29
- }
30
-
31
- # Fetch news articles from News API
32
- def get_news(api_key, query, country, language, from_date, to_date):
33
- url = 'https://newsapi.org/v2/everything'
34
- params = {
35
- 'apiKey': api_key, 'q': query, 'from': from_date,
36
- 'to': to_date, 'language': language, 'pageSize': 20
37
  }
38
 
39
- try:
40
- response = requests.get(url, params=params)
41
- response.raise_for_status()
42
- news_data = response.json()
43
- return news_data.get('articles', [])
44
- except requests.exceptions.RequestException as e:
45
- st.error(f"Error fetching news: {e}")
46
- return []
47
-
48
- # Save articles to session state for favorites
49
- def save_favorite(article):
50
- if "favorites" not in st.session_state:
51
- st.session_state.favorites = []
52
- st.session_state.favorites.append(article)
53
- st.success("Article saved to favorites!")
54
-
55
- # UI Layout
56
- st.title("πŸ“° News Fetcher")
57
- st.sidebar.title("βš™ Settings")
58
-
59
- # Store last seen timestamp
60
- if 'last_seen' not in st.session_state:
61
- st.session_state.last_seen = datetime.now()
62
- last_seen = st.session_state.last_seen
63
- st.sidebar.write(f"πŸ“… Last accessed: {last_seen.strftime('%Y-%m-%d %H:%M:%S')}")
64
-
65
- # Language selection
66
- selected_lang = st.sidebar.selectbox("🌍 Language", list(LANGUAGES.keys()), format_func=lambda x: LANGUAGES[x])
67
-
68
- # Country selection
69
- selected_country = st.sidebar.selectbox("🏳️ Country", list(COUNTRIES.keys()), format_func=lambda x: COUNTRIES[x])
70
-
71
- # Sidebar buttons for important queries
72
- st.sidebar.header("πŸ”₯ Trending Topics")
73
- for topic in IMPORTANT_QUERIES:
74
- if st.sidebar.button(topic):
75
- st.session_state.query = topic
76
-
77
- # User query input
78
- query = st.text_input("πŸ” Search for news:", value=st.session_state.get('query', ''))
79
-
80
- # Date range selection
81
- st.sidebar.header("πŸ“† Date Range")
82
- from_date = st.sidebar.date_input("From", value=datetime.now() - timedelta(days=7))
83
- to_date = st.sidebar.date_input("To", value=datetime.now())
84
-
85
- # Fetch news button
86
- if st.button("πŸ”„ Fetch News"):
87
- API_KEY = "your_newsapi_key_here" # Replace with your actual News API key
88
- articles = get_news(API_KEY, query, selected_country, selected_lang, from_date, to_date)
89
-
90
- if articles:
91
- for article in articles:
92
- st.subheader(article['title'])
93
- st.markdown(f"**πŸ“° Source:** {article['source']['name']} | **⏳ Published:** {article['publishedAt']}")
94
- st.write(article['description'] or "No description available")
95
- st.markdown(f"[πŸ“– Read more]({article['url']})")
96
-
97
- # Favorite button for each article
98
- if st.button(f"⭐ Save: {article['title'][:30]}", key=article['title']):
99
- save_favorite(article)
100
-
101
- st.markdown("---")
102
-
103
- # Data visualization
104
- pub_dates = [article['publishedAt'][:10] for article in articles]
105
- date_counts = pd.Series(pub_dates).value_counts().sort_index()
106
-
107
- st.subheader("πŸ“Š News Trends Over Time")
108
- plt.figure(figsize=(10, 5))
109
- plt.plot(date_counts.index, date_counts.values, marker='o', color='teal')
110
- plt.xlabel('Date')
111
- plt.ylabel('Number of Articles')
112
- plt.title('Frequency of Articles Over Time')
113
- plt.xticks(rotation=45)
114
- st.pyplot(plt)
115
- else:
116
- st.warning("No news articles found.")
117
-
118
- # Display saved favorites
119
- st.sidebar.subheader("⭐ Saved Articles")
120
- if "favorites" in st.session_state and st.session_state.favorites:
121
- for fav in st.session_state.favorites:
122
- st.sidebar.write(f"πŸ”Ή {fav['title'][:40]}...")
123
 
124
- # Footer
125
- st.markdown("---")
126
- st.markdown(f"Developed by SriKrishna | Β© 2025 | All rights reserved | Last accessed: {last_seen.strftime('%Y-%m-%d %H:%M:%S')}", unsafe_allow_html=True)
 
4
  import matplotlib.pyplot as plt
5
  from datetime import datetime, timedelta
6
 
7
+ def run():
8
+ st.title("News Fetcher")
9
 
10
+ # Define country options
11
+ countries = {
12
+ 'us': 'United States', 'in': 'India', 'gb': 'United Kingdom',
13
+ 'ca': 'Canada', 'au': 'Australia', 'de': 'Germany'
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
14
  }
15
 
16
+ # Sidebar selections
17
+ st.sidebar.title("Filters")
18
+ country = st.sidebar.selectbox("Select country", list(countries.keys()), format_func=lambda x: countries[x])
19
+ query = st.sidebar.text_input("Search for news")
20
+
21
+ # Date range selection
22
+ from_date = st.sidebar.date_input("From", datetime.now() - timedelta(days=7))
23
+ to_date = st.sidebar.date_input("To", datetime.now())
24
+
25
+ # Fetch news function
26
+ def get_news(api_key, query, country, from_date, to_date):
27
+ url = 'https://newsapi.org/v2/everything'
28
+ params = {'apiKey': api_key, 'q': query, 'from': from_date, 'to': to_date, 'language': 'en', 'pageSize': 10}
29
+ try:
30
+ response = requests.get(url, params=params)
31
+ response.raise_for_status()
32
+ return response.json().get("articles", [])
33
+ except requests.exceptions.RequestException as e:
34
+ st.error(f"Error fetching news: {e}")
35
+ return []
36
+
37
+ # API Key (replace with your own)
38
+ API_KEY = "your_news_api_key"
39
+
40
+ if st.sidebar.button("Fetch News"):
41
+ articles = get_news(API_KEY, query, country, from_date, to_date)
42
+ if articles:
43
+ for article in articles:
44
+ st.subheader(article["title"])
45
+ st.write(article["description"])
46
+ st.markdown(f"[Read more]({article['url']})")
47
+ st.write("---")
48
+ else:
49
+ st.write("No articles found.")
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
50