Spaces:
Running
on
CPU Upgrade
Running
on
CPU Upgrade
File size: 3,188 Bytes
ad0f104 18c9d60 ab30506 1d7a9d5 68a8b0c ab30506 1d7a9d5 68a8b0c aa8bc02 1d7a9d5 68a8b0c 1d7a9d5 f42fdaf 68a8b0c f42fdaf 68a8b0c f42fdaf b659602 f42fdaf 68a8b0c b659602 68a8b0c ab30506 68a8b0c b659602 ab30506 1d7a9d5 68a8b0c b659602 68a8b0c b659602 68a8b0c ab30506 1d7a9d5 ad0f104 b659602 1d7a9d5 b659602 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 71 72 73 74 75 76 77 78 79 80 81 82 83 84 |
import gradio as gr
import requests
from datetime import datetime, timedelta
import pycountry
# NewsAPI key (이것을 실제 API 키로 대체해야 합니다)
API_KEY = "37d83e266422487b8b2e4cb6e1ff0aa6"
# 국가 코드 리스트
COUNTRY_CODES = "ae ar at au be bg br ca ch cn co cu cz de eg fr gb gr hk hu id ie il in it jp kr lt lv ma mx my ng nl no nz ph pl pt ro rs ru sa se sg si sk th tr tw ua us ve za".split()
# 국가 코드와 이름 매핑
COUNTRIES = {'all': 'All Countries'}
for code in COUNTRY_CODES:
try:
country = pycountry.countries.get(alpha_2=code.upper())
COUNTRIES[code] = country.name
except AttributeError:
COUNTRIES[code] = code.upper() # 국가 이름을 찾지 못한 경우 코드를 대문자로 사용
def get_news(keyword, article_count, country):
base_url = "https://newsapi.org/v2/top-headlines" if country != 'all' else "https://newsapi.org/v2/everything"
two_days_ago = (datetime.utcnow() - timedelta(hours=48)).isoformat()
params = {
'apiKey': API_KEY,
'q': keyword,
'from': two_days_ago,
'language': 'en',
'sortBy': 'publishedAt',
'pageSize': article_count
}
if country != 'all':
params['country'] = country
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"<p style='color: red;'>Error fetching news: {str(e)}</p>"
if news_data['status'] != 'ok':
return f"<p style='color: red;'>API Error: {news_data.get('message', 'Unknown error occurred')}</p>"
articles = news_data['articles']
if not articles:
return (f"<p>No recent news found for the keyword '<strong>{keyword}</strong>' within the last 48 hours.<br>"
f"Try a different keyword or check back later.</p>")
html_output = f"<h2>News results for '{keyword}' in {COUNTRIES[country]}</h2>"
for article in articles:
title = article['title']
link = article['url']
pub_date = datetime.strptime(article['publishedAt'], "%Y-%m-%dT%H:%M:%SZ")
source = article.get('source', {}).get('name', 'Unknown Source')
html_output += f"""
<div style='margin-bottom: 20px; padding: 10px; border: 1px solid #ddd; border-radius: 5px;'>
<h3><a href='{link}' target='_blank' style='text-decoration: none; color: #1a0dab;'>{title}</a></h3>
<p style='color: #006621;'>{source}</p>
<p style='color: #545454;'>{pub_date.strftime('%Y-%m-%d %H:%M:%S')}</p>
</div>
"""
return html_output
iface = gr.Interface(
fn=get_news,
inputs=[
gr.Textbox(label="Enter keyword"),
gr.Slider(minimum=10, maximum=100, step=10, value=10, label="Number of Articles"),
gr.Dropdown(choices=list(COUNTRIES.values()), value="All Countries", label="Select Country")
],
outputs=gr.HTML(),
title="Enhanced Visual News Search",
description="Search for news articles from the last 48 hours using NewsAPI.",
theme=gr.themes.Soft()
)
iface.launch() |