import gradio as gr import requests import json from datetime import datetime, timedelta import pandas as pd API_KEY = "V38CNn4HXpLtynJQyOeoUensTEYoFy8PBUxKpDqAW1pawT1vfJ2BWtPQ98h6" MAJOR_COUNTRIES = [ "United States", "United Kingdom", "Canada", "Australia", "Germany", "France", "Japan", "South Korea", "China", "India", "Brazil", "Mexico", "Russia", "Italy", "Spain", "Netherlands", "Sweden", "Switzerland", "Norway", "Denmark", "Finland", "Belgium", "Austria", "New Zealand", "Ireland", "Singapore", "Hong Kong", "Israel", "United Arab Emirates", "Saudi Arabia", "South Africa", "Turkey", "Egypt", "Poland", "Czech Republic", "Hungary", "Greece", "Portugal", "Argentina", "Chile", "Colombia", "Peru", "Venezuela", "Thailand", "Malaysia", "Indonesia", "Philippines", "Vietnam", "Pakistan", "Bangladesh" ] def search_serphouse(query, country, page, num_result): url = "https://api.serphouse.com/serp/live" now = datetime.utcnow() yesterday = now - timedelta(days=1) date_range = f"{yesterday.strftime('%Y-%m-%d')},{now.strftime('%Y-%m-%d')}" payload = { "data": { "q": query, "domain": "google.com", "loc": country, "lang": "en", "device": "desktop", "serp_type": "news", "page": str(page), "verbatim": "1", "num": str(num_result), "date_range": date_range } } headers = { "accept": "application/json", "content-type": "application/json", "authorization": f"Bearer {API_KEY}" } try: response = requests.post(url, json=payload, headers=headers) response.raise_for_status() return response.json() except requests.RequestException as e: error_msg = f"Error: {str(e)}" if response.text: error_msg += f"\nResponse content: {response.text}" return {"error": error_msg} def format_results(results): debug_info = f"Raw API Response:\n{json.dumps(results, indent=2, ensure_ascii=False)}\n\n" if isinstance(results, dict) and "error" in results: return pd.DataFrame({"Error": [results["error"]]}), debug_info try: if not isinstance(results, dict): raise ValueError("결과가 사전 형식이 아닙니다.") if "results" not in results: raise ValueError("'results' 키가 응답에 없습니다.") news_results = results.get("results", {}) if isinstance(news_results, dict): news_results = news_results.get("news", []) elif isinstance(news_results, list): news_results = news_results else: news_results = [] debug_info += f"뉴스 결과 수: {len(news_results)}\n" debug_info += f"뉴스 결과 구조: {type(news_results)}\n" if not news_results: return pd.DataFrame({"Message": ["검색 결과가 없습니다."]}), debug_info formatted_results = [] for result in news_results: formatted_results.append({ "제목": result.get("title", "제목 없음"), "링크": result.get("url", "#"), "내용": result.get("snippet", "내용 없음"), "출처": result.get("channel", "알 수 없음"), "시간": result.get("time", "알 수 없는 시간") }) return pd.DataFrame(formatted_results), debug_info except Exception as e: error_message = f"결과 처리 중 오류 발생: {str(e)}" debug_info += f"Error: {error_message}\n" debug_info += f"Results structure: {type(results)}\n" if isinstance(results, dict): debug_info += f"Results keys: {results.keys()}\n" return pd.DataFrame({"Error": [error_message]}), debug_info def serphouse_search(query, country, page, num_result): results = search_serphouse(query, country, page, num_result) df_results, debug_info = format_results(results) return df_results, debug_info css = """ footer { visibility: hidden; } """ iface = gr.Interface( fn=serphouse_search, inputs=[ gr.Textbox(label="검색어"), gr.Dropdown(MAJOR_COUNTRIES, label="국가"), gr.Slider(1, 10, 1, label="페이지"), gr.Slider(1, 100, 10, label="결과 수") ], outputs=[ gr.Dataframe(label="뉴스 결과"), gr.Textbox(label="디버그 정보", lines=10) ], title="24시간 이내 뉴스 검색 인터페이스", description="검색어를 입력하고 국가를 선택하여 24시간 이내의 뉴스 결과를 가져옵니다.", theme="Nymbo/Nymbo_Theme", css=css ) iface.launch(auth=("gini","pick"))