Spaces:
Building
Building
import gradio as gr | |
import requests | |
from datetime import datetime, timedelta | |
# Google Custom Search API ํค์ ๊ฒ์ ์์ง ID | |
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): | |
# 24์๊ฐ ์ ๋ ์ง ๊ณ์ฐ | |
one_day_ago = (datetime.now() - timedelta(days=1)).strftime("%Y-%m-%d") | |
# API ์์ฒญ URL ๋ฐ ๋งค๊ฐ๋ณ์ ์ค์ | |
url = "https://www.googleapis.com/customsearch/v1" | |
params = { | |
'key': API_KEY, | |
'cx': SEARCH_ENGINE_ID, | |
'q': keyword, | |
'dateRestrict': 'd1', # ์ต๊ทผ 1์ผ ๋ด ๊ฒฐ๊ณผ๋ง | |
'lr': 'lang_en', # ์์ด ๊ฒฐ๊ณผ๋ง | |
'sort': 'date', # ๋ ์ง์ ์ ๋ ฌ | |
'num': 10, # ์ต๋ 10๊ฐ ๊ฒฐ๊ณผ | |
'siteSearch': 'news.google.com', # Google News๋ก ์ ํ | |
} | |
if country != 'All Countries': | |
params['cr'] = COUNTRIES[country] | |
# API ์์ฒญ | |
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 | |
# Gradio ์ธํฐํ์ด์ค ์์ฑ | |
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() |