File size: 2,565 Bytes
09ebcd0
 
 
 
1b298f9
77e4df8
 
1b298f9
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
f166d5c
1b298f9
68a8b0c
1b298f9
68a8b0c
1b298f9
ab30506
1b298f9
ab30506
1b298f9
 
ad0f104
b659602
1b298f9
 
ad0f104
 
1b298f9
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

# 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()