Spaces:
Building
Building
import gradio as gr | |
import requests | |
from bs4 import BeautifulSoup | |
from datetime import datetime, timedelta | |
import pytz | |
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 = f"https://news.google.com/search?q={keyword}&hl=en-{country_code}&gl={country_code}&ceid={country_code}:en" | |
try: | |
response = requests.get(base_url, timeout=10) | |
response.raise_for_status() | |
except requests.RequestException as e: | |
return f"Error fetching news: {str(e)}" | |
soup = BeautifulSoup(response.text, 'html.parser') | |
articles = soup.find_all('article') | |
time_threshold = datetime.now(pytz.utc) - timedelta(hours=48) | |
filtered_news = [] | |
for article in articles: | |
title_elem = article.find('h3', class_='ipQwMb ekueJc RD0gLb') | |
link_elem = article.find('a', class_='VDXfz') | |
time_elem = article.find('time', class_='WW6dff uQIVzc Sksgp') | |
if title_elem and link_elem and time_elem: | |
title = title_elem.text | |
link = f"https://news.google.com{link_elem['href'][1:]}" | |
pub_time = datetime.fromtimestamp(int(time_elem['datetime'])/1000, pytz.utc) | |
if pub_time > time_threshold: | |
filtered_news.append(f"Title: {title}\nLink: {link}\nDate: {pub_time}\n") | |
if filtered_news: | |
return "\n".join(filtered_news) | |
else: | |
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.") | |
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="Google News Search", | |
description="Search for news articles from the last 48 hours using Google News." | |
) | |
iface.launch() |