import gradio as gr import requests from datetime import datetime, timedelta import json # NewsAPI key (이것을 실제 API 키로 대체해야 합니다) API_KEY = "37d83e266422487b8b2e4cb6e1ff0aa6" def get_news(keyword): base_url = "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' } 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}' within the last 48 hours.
" f"Try a different keyword or check back later.

") html_output = f"

News results for '{keyword}'

" for article in articles[:10]: # 최대 10개의 기사만 표시 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"""

{title}

{source}

{pub_date.strftime('%Y-%m-%d %H:%M:%S')}

""" return html_output iface = gr.Interface( fn=get_news, inputs=[ gr.Textbox(label="Enter keyword") ], outputs=gr.HTML(), title="Visual News Search", description="Search for news articles from the last 48 hours using NewsAPI.", theme=gr.themes.Soft() ) iface.launch()