File size: 3,847 Bytes
09ebcd0
 
158b524
95cb946
2efa0ec
09ebcd0
1b298f9
5890b4c
 
1b298f9
95cb946
1b298f9
95cb946
 
 
 
1b298f9
 
95cb946
 
 
 
b403d83
95cb946
 
1b298f9
95cb946
1b298f9
d68e8a7
2efa0ec
 
 
1b298f9
 
 
ac9df44
2efa0ec
 
 
 
1b298f9
 
b403d83
95cb946
 
 
 
 
 
 
 
 
ac9df44
95cb946
1b298f9
95cb946
 
 
 
 
 
2efa0ec
95cb946
2efa0ec
95cb946
 
 
2efa0ec
1b298f9
95cb946
 
 
 
ac9df44
95cb946
158b524
95cb946
 
 
68a8b0c
158b524
 
1b298f9
68a8b0c
1b298f9
ab30506
b403d83
ab30506
1b298f9
b403d83
ad0f104
b659602
1b298f9
2efa0ec
ad0f104
 
94b1606
 
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
85
86
87
88
89
90
91
92
93
94
95
96
97
98
import gradio as gr
import requests
import json
from functools import lru_cache
from datetime import datetime, timedelta

# Google Custom Search API ํ‚ค์™€ ๊ฒ€์ƒ‰ ์—”์ง„ ID
API_KEY = "AIzaSyB8wNdEL8-SAvelRq-zenLLU-cUEmsj7uE"
SEARCH_ENGINE_ID = "c01abc75e1b95483d"

# ์ง€์›๋˜๋Š” ๊ตญ๊ฐ€ ๋ฆฌ์ŠคํŠธ
COUNTRIES = {
    'United States': 'US', 'United Kingdom': 'GB', 'Canada': 'CA', 'Australia': 'AU', 'India': 'IN',
    'Germany': 'DE', 'France': 'FR', 'Japan': 'JP', 'South Korea': 'KR', 'Brazil': 'BR',
    'Mexico': 'MX', 'Spain': 'ES', 'Italy': 'IT', 'Netherlands': 'NL', 'Russia': 'RU',
    'Sweden': 'SE', 'Switzerland': 'CH', 'Poland': 'PL', 'Turkey': 'TR', 'Saudi Arabia': 'SA'
}

@lru_cache(maxsize=100)
def cached_search(cache_key):
    return search_news_impl(*json.loads(cache_key))

def search_news(keyword, country):
    cache_key = json.dumps((keyword, country))
    return cached_search(cache_key)

def search_news_impl(keyword, country):
    url = "https://www.googleapis.com/customsearch/v1"
    
    # 24์‹œ๊ฐ„ ์ „ ๋‚ ์งœ ๊ณ„์‚ฐ
    one_day_ago = (datetime.utcnow() - timedelta(days=1)).strftime("%Y-%m-%d")
    
    params = {
        'key': API_KEY,
        'cx': SEARCH_ENGINE_ID,
        'q': keyword,
        'dateRestrict': 'd1',  # ์ตœ๊ทผ 1์ผ ๋‚ด ๊ฒฐ๊ณผ๋งŒ
        'sort': 'date',  # ๋‚ ์งœ์ˆœ ์ •๋ ฌ
        'num': 10,  # ๊ฒฐ๊ณผ ์ˆ˜
        'tbm': 'nws',  # ๋‰ด์Šค ๊ฒ€์ƒ‰์œผ๋กœ ์ œํ•œ
    }

    if country != 'All Countries':
        params['gl'] = COUNTRIES[country]

    try:
        response = requests.get(url, params=params)
        response.raise_for_status()
        results = response.json()

        debug_info = f"API Request URL: {response.url}\n"
        debug_info += f"API Response Status: {response.status_code}\n"
        debug_info += f"API Response Headers: {json.dumps(dict(response.headers), indent=2)}\n"
        debug_info += f"API Response Body: {json.dumps(results, indent=2)}\n"

        formatted_results = ""
        if 'items' in results:
            for item in results['items']:
                title = item['title']
                link = item['link']
                snippet = item.get('snippet', 'No snippet available')
                published_date = item.get('pagemap', {}).get('metatags', [{}])[0].get('article:published_time', 'Unknown date')
                formatted_results += f"<h3><a href='{link}' target='_blank'>{title}</a></h3>"
                formatted_results += f"<p>Published: {published_date}</p>"
                formatted_results += f"<p>{snippet}</p><br>"
            formatted_results += f"<p>Total results: {len(results['items'])}</p>"
        else:
            formatted_results = f"No news found for '{keyword}' in {country} within the last 24 hours."

    except requests.exceptions.HTTPError as e:
        formatted_results = f"An error occurred: {str(e)}"
        debug_info = f"Error: {str(e)}\n"
        debug_info += f"API Response Status: {e.response.status_code}\n"
        debug_info += f"API Response Headers: {json.dumps(dict(e.response.headers), indent=2)}\n"
        debug_info += f"API Response Body: {e.response.text}\n"

    except Exception as e:
        formatted_results = f"An unexpected error occurred: {str(e)}"
        debug_info = f"Unexpected Error: {str(e)}\n"

    formatted_results += f"<details><summary>Debug Info</summary><pre>{debug_info}</pre></details>"

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