|
import gradio as gr |
|
import requests |
|
from datetime import datetime, timedelta |
|
|
|
|
|
API_KEY = "37d83e266422487b8b2e4cb6e1ff0aa6" |
|
|
|
SUPPORTED_COUNTRIES = { |
|
'United States': 'us', |
|
'United Kingdom': 'gb', |
|
'Australia': 'au', |
|
'India': 'in', |
|
'Canada': 'ca' |
|
} |
|
|
|
def get_news(country, keyword): |
|
country_code = SUPPORTED_COUNTRIES.get(country) |
|
if not country_code: |
|
return "Selected country is not supported." |
|
|
|
base_url = "https://newsapi.org/v2/top-headlines" |
|
|
|
|
|
two_days_ago = (datetime.utcnow() - timedelta(hours=48)).isoformat() |
|
|
|
params = { |
|
'apiKey': API_KEY, |
|
'country': country_code, |
|
'q': keyword, |
|
'from': two_days_ago, |
|
'language': 'en' |
|
} |
|
|
|
try: |
|
response = requests.get(base_url, params=params, timeout=10) |
|
response.raise_for_status() |
|
news_data = response.json() |
|
except requests.RequestException as e: |
|
return f"Error fetching news: {str(e)}" |
|
|
|
if news_data['status'] != 'ok': |
|
return f"API Error: {news_data.get('message', 'Unknown error occurred')}" |
|
|
|
articles = news_data['articles'] |
|
|
|
if not articles: |
|
return (f"No recent news found for the keyword '{keyword}' in {country} " |
|
f"within the last 48 hours.\nTry a different keyword or check back later.") |
|
|
|
filtered_news = [] |
|
for article in articles: |
|
title = article['title'] |
|
link = article['url'] |
|
pub_date = datetime.strptime(article['publishedAt'], "%Y-%m-%dT%H:%M:%SZ") |
|
filtered_news.append(f"Title: {title}\nLink: {link}\nDate: {pub_date}\n") |
|
|
|
return "\n".join(filtered_news) |
|
|
|
iface = gr.Interface( |
|
fn=get_news, |
|
inputs=[ |
|
gr.Dropdown(choices=list(SUPPORTED_COUNTRIES.keys()), label="Select Country"), |
|
gr.Textbox(label="Enter keyword") |
|
], |
|
outputs="text", |
|
title="News Search", |
|
description="Search for news articles from the last 48 hours using NewsAPI." |
|
) |
|
|
|
iface.launch() |