File size: 2,100 Bytes
ad0f104 18c9d60 ab30506 68a8b0c ab30506 18c9d60 68a8b0c 18c9d60 ab30506 9a82749 18c9d60 68a8b0c 18c9d60 f42fdaf 68a8b0c f42fdaf 68a8b0c f42fdaf 68a8b0c ab30506 68a8b0c f42fdaf ab30506 68a8b0c ab30506 18c9d60 ab30506 ad0f104 ab30506 68a8b0c ad0f104 ab30506 |
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 |
import gradio as gr
import requests
from datetime import datetime, timedelta
# NewsAPI key (์ด๊ฒ์ ์ค์ API ํค๋ก ๋์ฒดํด์ผ ํฉ๋๋ค)
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"
# 48์๊ฐ ์ ์ ๋ ์ง๋ฅผ ISO ํ์์ผ๋ก ์ป๊ธฐ
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() |