|
import gradio as gr |
|
import requests |
|
from datetime import datetime, timedelta |
|
|
|
|
|
API_KEY = "AIzaSyB8wNdEL8-SAvelRq-zenLLU-cUEmsj7uE" |
|
SEARCH_ENGINE_ID = "362030334819-vd4cpdvm1mecdbbu2ue41s3ldlc41365.apps.googleusercontent.com" |
|
|
|
|
|
COUNTRIES = { |
|
'United States': 'countryUS', 'United Kingdom': 'countryGB', 'India': 'countryIN', |
|
'Australia': 'countryAU', 'Canada': 'countryCA', 'Germany': 'countryDE', |
|
'France': 'countryFR', 'Italy': 'countryIT', 'Spain': 'countryES', 'Brazil': 'countryBR', |
|
'Mexico': 'countryMX', 'Argentina': 'countryAR', 'Japan': 'countryJP', |
|
'South Korea': 'countryKR', 'Russia': 'countryRU', 'China': 'countryCN', |
|
'Netherlands': 'countryNL', 'Sweden': 'countrySE', 'Poland': 'countryPL', 'Turkey': 'countryTR' |
|
} |
|
|
|
def search_news(keyword, country): |
|
|
|
one_day_ago = (datetime.now() - timedelta(days=1)).strftime("%Y-%m-%d") |
|
|
|
|
|
url = "https://www.googleapis.com/customsearch/v1" |
|
params = { |
|
'key': API_KEY, |
|
'cx': SEARCH_ENGINE_ID, |
|
'q': keyword, |
|
'dateRestrict': 'd1', |
|
'lr': 'lang_en', |
|
'sort': 'date', |
|
'num': 10, |
|
'siteSearch': 'news.google.com', |
|
} |
|
|
|
if country != 'All Countries': |
|
params['cr'] = COUNTRIES[country] |
|
|
|
|
|
response = requests.get(url, params=params) |
|
results = response.json() |
|
|
|
|
|
formatted_results = "" |
|
if 'items' in results: |
|
for item in results['items']: |
|
title = item['title'] |
|
link = item['link'] |
|
snippet = item['snippet'] |
|
formatted_results += f"<h3><a href='{link}' target='_blank'>{title}</a></h3>" |
|
formatted_results += f"<p>{snippet}</p><br>" |
|
else: |
|
formatted_results = f"No news found for '{keyword}' in {country} within the last 24 hours." |
|
|
|
return formatted_results |
|
|
|
|
|
iface = gr.Interface( |
|
fn=search_news, |
|
inputs=[ |
|
gr.Textbox(label="Enter keyword (in English)"), |
|
gr.Dropdown(choices=['All Countries'] + list(COUNTRIES.keys()), label="Select Country") |
|
], |
|
outputs=gr.HTML(), |
|
title="Google News Search", |
|
description="Search for news articles from the last 24 hours using Google Custom Search API." |
|
) |
|
|
|
|
|
iface.launch() |