hanjunjung commited on
Commit ·
98dfff6
1
Parent(s): b44da90
[fix]
Browse files- app.py +467 -1237
- requirements.txt +2 -1
app.py
CHANGED
|
@@ -3,19 +3,24 @@ import time
|
|
| 3 |
import base64
|
| 4 |
import json
|
| 5 |
import traceback
|
| 6 |
-
import
|
| 7 |
from typing import Tuple, Optional
|
| 8 |
import gradio as gr
|
| 9 |
import anthropic
|
| 10 |
-
from
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 11 |
from concurrent.futures import ThreadPoolExecutor
|
| 12 |
-
import
|
| 13 |
|
| 14 |
# Hugging Face Space 환경 확인
|
| 15 |
IS_HUGGINGFACE = os.getenv("SPACE_ID") is not None
|
| 16 |
print(f'IS_HUGGINGFACE = {IS_HUGGINGFACE}')
|
| 17 |
|
| 18 |
-
# Claude API 설정
|
| 19 |
ANTHROPIC_API_KEY = os.getenv("ANTHROPIC_API_KEY")
|
| 20 |
|
| 21 |
if not ANTHROPIC_API_KEY:
|
|
@@ -23,34 +28,6 @@ if not ANTHROPIC_API_KEY:
|
|
| 23 |
else:
|
| 24 |
print("Claude API 키 확인 완료")
|
| 25 |
|
| 26 |
-
# Playwright 브라우저 설치 (최초 1회)
|
| 27 |
-
async def install_playwright_browsers():
|
| 28 |
-
if IS_HUGGINGFACE:
|
| 29 |
-
try:
|
| 30 |
-
print("Playwright 브라우저 설치 중...")
|
| 31 |
-
import subprocess
|
| 32 |
-
result = subprocess.run(["playwright", "install", "chromium"], capture_output=True, text=True)
|
| 33 |
-
if result.returncode == 0:
|
| 34 |
-
print("Playwright Chromium 설치 완료")
|
| 35 |
-
return True
|
| 36 |
-
else:
|
| 37 |
-
print(f"Playwright 설치 실패: {result.stderr}")
|
| 38 |
-
return False
|
| 39 |
-
except Exception as e:
|
| 40 |
-
print(f"Playwright 설치 중 오류: {e}")
|
| 41 |
-
return False
|
| 42 |
-
return True
|
| 43 |
-
|
| 44 |
-
# 시작 시 Playwright 브라우저 설치
|
| 45 |
-
if IS_HUGGINGFACE:
|
| 46 |
-
try:
|
| 47 |
-
browser_installed = asyncio.run(install_playwright_browsers())
|
| 48 |
-
if not browser_installed:
|
| 49 |
-
print("Playwright 브라우저 설치에 실패했지만 계속 진행합니다...")
|
| 50 |
-
except Exception as e:
|
| 51 |
-
print(f"Playwright 초기화 오류: {e}")
|
| 52 |
-
|
| 53 |
-
# Claude 클라이언트를 생성
|
| 54 |
def create_claude_client():
|
| 55 |
try:
|
| 56 |
client = anthropic.Anthropic(api_key=ANTHROPIC_API_KEY)
|
|
@@ -60,81 +37,290 @@ def create_claude_client():
|
|
| 60 |
print(f"Claude API 클라이언트 생성 실패: {e}")
|
| 61 |
return None
|
| 62 |
|
| 63 |
-
|
| 64 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 65 |
def __init__(self):
|
| 66 |
-
|
| 67 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 68 |
|
| 69 |
-
|
| 70 |
-
|
| 71 |
try:
|
| 72 |
-
if
|
| 73 |
-
|
| 74 |
|
| 75 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 76 |
|
| 77 |
-
|
| 78 |
-
self.browser = await self.playwright.chromium.launch(
|
| 79 |
-
headless=True,
|
| 80 |
-
args=[
|
| 81 |
-
"--no-sandbox",
|
| 82 |
-
"--disable-dev-shm-usage",
|
| 83 |
-
"--disable-gpu",
|
| 84 |
-
"--disable-software-rasterizer",
|
| 85 |
-
"--memory-pressure-off",
|
| 86 |
-
"--disable-background-timer-throttling",
|
| 87 |
-
"--disable-backgrounding-occluded-windows",
|
| 88 |
-
"--disable-renderer-backgrounding",
|
| 89 |
-
"--disable-features=TranslateUI",
|
| 90 |
-
"--disable-ipc-flooding-protection",
|
| 91 |
-
"--disable-web-security",
|
| 92 |
-
"--lang=ko",
|
| 93 |
-
"--accept-lang=ko-KR,ko;q=0.9,en"
|
| 94 |
-
]
|
| 95 |
-
)
|
| 96 |
|
| 97 |
-
|
| 98 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 99 |
|
| 100 |
-
#
|
| 101 |
-
|
| 102 |
|
| 103 |
-
#
|
| 104 |
-
|
| 105 |
-
|
| 106 |
-
|
| 107 |
|
| 108 |
-
print("Playwright 브라우저 초기화 성공")
|
| 109 |
return True
|
| 110 |
|
| 111 |
except Exception as e:
|
| 112 |
-
print(f"
|
| 113 |
return False
|
| 114 |
|
| 115 |
-
|
| 116 |
-
|
| 117 |
-
for selector in selectors:
|
| 118 |
try:
|
| 119 |
-
|
| 120 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 121 |
except:
|
| 122 |
continue
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 123 |
return False
|
| 124 |
|
| 125 |
-
|
| 126 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 127 |
try:
|
| 128 |
region_selectors = [
|
| 129 |
-
"button[aria-label
|
| 130 |
-
"button[aria-label
|
| 131 |
-
"span
|
| 132 |
]
|
| 133 |
|
| 134 |
-
if not
|
| 135 |
return False
|
| 136 |
|
| 137 |
-
|
| 138 |
|
| 139 |
region_mapping = {
|
| 140 |
"전세계": ["전 세계", "Worldwide"],
|
|
@@ -146,12 +332,11 @@ class GoogleTrendsAutomator:
|
|
| 146 |
if target_region in region_mapping:
|
| 147 |
for region_text in region_mapping[target_region]:
|
| 148 |
region_option_selectors = [
|
| 149 |
-
f"span
|
| 150 |
-
f"text
|
| 151 |
-
f"*:has-text('{region_text}')"
|
| 152 |
]
|
| 153 |
|
| 154 |
-
if
|
| 155 |
return True
|
| 156 |
|
| 157 |
return False
|
|
@@ -160,18 +345,18 @@ class GoogleTrendsAutomator:
|
|
| 160 |
print(f"지역 변경 실패: {e}")
|
| 161 |
return False
|
| 162 |
|
| 163 |
-
|
| 164 |
-
|
| 165 |
try:
|
| 166 |
period_selectors = [
|
| 167 |
-
"button[aria-label
|
| 168 |
-
"span
|
| 169 |
]
|
| 170 |
|
| 171 |
-
if not
|
| 172 |
return False
|
| 173 |
|
| 174 |
-
|
| 175 |
|
| 176 |
period_mapping = {
|
| 177 |
"지난 1시간": ["지난 1시간"],
|
|
@@ -183,12 +368,11 @@ class GoogleTrendsAutomator:
|
|
| 183 |
if target_period in period_mapping:
|
| 184 |
for period_text in period_mapping[target_period]:
|
| 185 |
period_option_selectors = [
|
| 186 |
-
f"span
|
| 187 |
-
f"text
|
| 188 |
-
f"*:has-text('{period_text}')"
|
| 189 |
]
|
| 190 |
|
| 191 |
-
if
|
| 192 |
return True
|
| 193 |
|
| 194 |
return False
|
|
@@ -197,18 +381,18 @@ class GoogleTrendsAutomator:
|
|
| 197 |
print(f"기간 변경 실패: {e}")
|
| 198 |
return False
|
| 199 |
|
| 200 |
-
|
| 201 |
-
|
| 202 |
try:
|
| 203 |
category_selectors = [
|
| 204 |
-
"button[aria-label
|
| 205 |
-
"span
|
| 206 |
]
|
| 207 |
|
| 208 |
-
if not
|
| 209 |
return False
|
| 210 |
|
| 211 |
-
|
| 212 |
|
| 213 |
category_mapping = {
|
| 214 |
"게임": ["게임"],
|
|
@@ -223,12 +407,11 @@ class GoogleTrendsAutomator:
|
|
| 223 |
if target_category in category_mapping:
|
| 224 |
for category_text in category_mapping[target_category]:
|
| 225 |
category_option_selectors = [
|
| 226 |
-
f"span
|
| 227 |
-
f"text
|
| 228 |
-
f"*:has-text('{category_text}')"
|
| 229 |
]
|
| 230 |
|
| 231 |
-
if
|
| 232 |
return True
|
| 233 |
|
| 234 |
return False
|
|
@@ -237,107 +420,87 @@ class GoogleTrendsAutomator:
|
|
| 237 |
print(f"카테고리 변경 실패: {e}")
|
| 238 |
return False
|
| 239 |
|
| 240 |
-
|
| 241 |
-
|
| 242 |
-
error_msg = ""
|
| 243 |
|
| 244 |
-
|
| 245 |
-
|
| 246 |
-
progress_callback("브라우저 초기화 중...")
|
| 247 |
-
|
| 248 |
-
# 브라우저 설정
|
| 249 |
-
if not await self.setup_browser(progress_callback):
|
| 250 |
-
return None, False, "브라우저 설정 실패"
|
| 251 |
-
|
| 252 |
-
if progress_callback:
|
| 253 |
-
progress_callback("Google Trends 페이지 접속 중...")
|
| 254 |
-
|
| 255 |
-
# Google Trends 접속
|
| 256 |
-
await self.page.goto("https://trends.google.com/trending?geo=KR&hl=ko", wait_until="domcontentloaded")
|
| 257 |
-
|
| 258 |
-
# 로딩 대기
|
| 259 |
-
wait_time = 4000 if IS_HUGGINGFACE else 2000
|
| 260 |
-
await self.page.wait_for_timeout(wait_time)
|
| 261 |
-
|
| 262 |
-
if progress_callback:
|
| 263 |
-
progress_callback("페이지 로딩 완료, 설정 변경 시작...")
|
| 264 |
|
| 265 |
-
# 페이지 준비 확인
|
| 266 |
try:
|
| 267 |
-
|
| 268 |
-
|
| 269 |
-
|
| 270 |
-
|
| 271 |
-
|
| 272 |
-
|
| 273 |
-
|
| 274 |
-
if region != "대한민국":
|
| 275 |
-
if progress_callback:
|
| 276 |
-
progress_callback(f"지역을 {region}으로 변경 중...")
|
| 277 |
-
if await self.change_region(region):
|
| 278 |
-
changes_made.append(f"지역: {region}")
|
| 279 |
-
await self.page.wait_for_timeout(500)
|
| 280 |
else:
|
| 281 |
-
|
| 282 |
-
|
| 283 |
-
|
|
|
|
| 284 |
if progress_callback:
|
| 285 |
-
progress_callback(
|
| 286 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 287 |
changes_made.append(f"기간: {period}")
|
| 288 |
-
|
| 289 |
-
else:
|
| 290 |
-
error_msg += f"기간 변경 실패 ({period})\n"
|
| 291 |
-
|
| 292 |
-
if category != "모든 ���테고리":
|
| 293 |
-
if progress_callback:
|
| 294 |
-
progress_callback(f"카테고리를 {category}로 변경 중...")
|
| 295 |
-
if await self.change_category(category):
|
| 296 |
changes_made.append(f"카테고리: {category}")
|
| 297 |
-
|
| 298 |
-
|
| 299 |
-
error_msg
|
| 300 |
-
|
| 301 |
-
|
| 302 |
-
|
| 303 |
-
|
| 304 |
-
|
| 305 |
-
|
| 306 |
-
|
| 307 |
-
|
| 308 |
-
|
| 309 |
-
|
| 310 |
-
|
| 311 |
-
|
| 312 |
-
|
| 313 |
-
|
| 314 |
-
|
| 315 |
-
|
| 316 |
-
|
| 317 |
-
|
| 318 |
-
|
| 319 |
-
|
| 320 |
-
|
| 321 |
-
|
| 322 |
-
|
| 323 |
-
|
| 324 |
-
|
| 325 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 326 |
|
| 327 |
-
# Claude API로 스크린샷 분석
|
| 328 |
def analyze_with_claude(screenshot_b64: str, region: str, period: str, category: str) -> str:
|
|
|
|
| 329 |
try:
|
| 330 |
-
# API 키 체크
|
| 331 |
if not ANTHROPIC_API_KEY or ANTHROPIC_API_KEY == "your_api_key_here":
|
| 332 |
return """
|
| 333 |
<div style="color: red; padding: 20px; border: 1px solid red; border-radius: 5px;">
|
| 334 |
<h3>API 키 오류</h3>
|
| 335 |
<p><strong>ANTHROPIC_API_KEY가 설정되지 않았습니다!</strong></p>
|
| 336 |
-
<p>Hugging Face Space Settings에서 Secret을 추가해주세요.</p>
|
| 337 |
</div>
|
| 338 |
"""
|
| 339 |
|
| 340 |
-
# Claude 클라이언트 생성
|
| 341 |
claude_client = create_claude_client()
|
| 342 |
|
| 343 |
if claude_client is None:
|
|
@@ -348,7 +511,6 @@ def analyze_with_claude(screenshot_b64: str, region: str, period: str, category:
|
|
| 348 |
</div>
|
| 349 |
"""
|
| 350 |
|
| 351 |
-
# 간결한 프롬프트 (속도 최적화)
|
| 352 |
prompt = f"""
|
| 353 |
이 Google Trends 스크린샷을 분석해주세요.
|
| 354 |
설정: {region} | {period} | {category}
|
|
@@ -358,11 +520,10 @@ def analyze_with_claude(screenshot_b64: str, region: str, period: str, category:
|
|
| 358 |
2. 주요 트렌드 키워드 3-5개의 특징 설명
|
| 359 |
3. 카테고리별 특이사항 (있는 경우)
|
| 360 |
|
| 361 |
-
HTML 형태로 깔끔하게 정리하고,
|
| 362 |
한글 텍스트를 정확히 읽어서 분석해주세요.
|
| 363 |
"""
|
| 364 |
|
| 365 |
-
# Claude API 호출 (빠른 설정)
|
| 366 |
message = claude_client.messages.create(
|
| 367 |
model="claude-3-5-sonnet-20241022",
|
| 368 |
max_tokens=1000,
|
|
@@ -397,23 +558,16 @@ HTML 형태로 깔끔하게 정리하고, 이모지를 사용하지 않고 시
|
|
| 397 |
</div>
|
| 398 |
"""
|
| 399 |
|
| 400 |
-
|
| 401 |
-
|
| 402 |
-
automator = GoogleTrendsAutomator()
|
| 403 |
-
return asyncio.run(automator.capture_trends(region, period, category, progress_callback))
|
| 404 |
-
|
| 405 |
-
def main_analysis(region: str, period: str, category: str):
|
| 406 |
-
# 실시간 스트리밍 분석 함수 (Generator)
|
| 407 |
|
| 408 |
start_time = time.time()
|
| 409 |
|
| 410 |
-
# 1단계: 시작 메시지
|
| 411 |
yield f"""
|
| 412 |
<div style="text-align: center; padding: 20px; background: linear-gradient(135deg, #667eea 0%, #764ba2 100%); color: white; border-radius: 10px; margin-bottom: 20px;">
|
| 413 |
-
<h3>Google Trends 분석
|
| 414 |
<p><strong>설정:</strong> {region} | {period} | {category}</p>
|
| 415 |
-
<p>
|
| 416 |
-
{'<p style="font-size: 12px; opacity: 0.8;">Hugging Face Space 환경에서 실행 중</p>' if IS_HUGGINGFACE else ''}
|
| 417 |
</div>
|
| 418 |
"""
|
| 419 |
|
|
@@ -423,37 +577,32 @@ def main_analysis(region: str, period: str, category: str):
|
|
| 423 |
progress_status["current"] = message
|
| 424 |
|
| 425 |
try:
|
| 426 |
-
#
|
| 427 |
if not ANTHROPIC_API_KEY or ANTHROPIC_API_KEY == "your_api_key_here":
|
| 428 |
yield """
|
| 429 |
-
<div style="color:
|
| 430 |
-
<h3>API 키 누락</h3>
|
| 431 |
<p><strong>ANTHROPIC_API_KEY가 설정되지 않았습니다!</strong></p>
|
| 432 |
-
<p><strong>해결 방법:</strong> Hugging Face Space Settings에서 Secret을 추가해주세요.</p>
|
| 433 |
</div>
|
| 434 |
"""
|
| 435 |
-
return
|
| 436 |
|
| 437 |
-
#
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 438 |
yield f"""
|
| 439 |
<div style="text-align: center; padding: 15px; background: linear-gradient(135deg, #4CAF50 0%, #45a049 100%); color: white; border-radius: 10px; margin-bottom: 15px;">
|
| 440 |
-
<h4>1단계:
|
| 441 |
-
|
| 442 |
-
</div>
|
| 443 |
-
|
| 444 |
-
<div style="padding: 15px; background-color: #f8f9fa; border-radius: 5px; margin-bottom: 15px;">
|
| 445 |
-
<p><strong>진행 중:</strong> 브라우저 드라이버 설정 및 페이지 로딩...</p>
|
| 446 |
-
{'<p style="font-size: 12px; color: #666;">Playwright 브라우저 초기화 중...</p>' if IS_HUGGINGFACE else ''}
|
| 447 |
</div>
|
| 448 |
"""
|
| 449 |
|
| 450 |
-
# 4단계: Google Trends 자동화 실행
|
| 451 |
-
print(f"분석 시작: {region} | {period} | {category}")
|
| 452 |
-
|
| 453 |
# 브라우저 작업을 별도 스레드에서 실행
|
| 454 |
with ThreadPoolExecutor(max_workers=1) as executor:
|
| 455 |
future = executor.submit(
|
| 456 |
-
|
| 457 |
region, period, category, progress_callback
|
| 458 |
)
|
| 459 |
|
|
@@ -464,13 +613,9 @@ def main_analysis(region: str, period: str, category: str):
|
|
| 464 |
elapsed = time.time() - start_time
|
| 465 |
yield f"""
|
| 466 |
<div style="text-align: center; padding: 15px; background: linear-gradient(135deg, #4CAF50 0%, #45a049 100%); color: white; border-radius: 10px; margin-bottom: 15px;">
|
| 467 |
-
<h4>
|
| 468 |
-
<p>
|
| 469 |
-
|
| 470 |
-
|
| 471 |
-
<div style="padding: 15px; background-color: #f8f9fa; border-radius: 5px; margin-bottom: 15px;">
|
| 472 |
-
<p><strong>현재 작업:</strong> {current_progress}</p>
|
| 473 |
-
<p><strong>경과 시간:</strong> {elapsed:.1f}초</p>
|
| 474 |
</div>
|
| 475 |
"""
|
| 476 |
time.sleep(0.5)
|
|
@@ -483,90 +628,105 @@ def main_analysis(region: str, period: str, category: str):
|
|
| 483 |
if not success:
|
| 484 |
yield f"""
|
| 485 |
<div style="color: red; padding: 20px; border: 1px solid red; border-radius: 5px;">
|
| 486 |
-
<h3>Google Trends
|
| 487 |
<pre style="background-color: #fff5f5; padding: 15px; border-radius: 5px; margin: 15px 0;">
|
| 488 |
{status_msg}
|
| 489 |
</pre>
|
| 490 |
-
<p><strong>해결 방법:</strong></p>
|
| 491 |
-
<ul>
|
| 492 |
-
<li>Playwright 브라우저 설치 확인</li>
|
| 493 |
-
<li>Space를 재시작해보세요</li>
|
| 494 |
-
<li>잠시 후 다시 시도해보세요</li>
|
| 495 |
-
</ul>
|
| 496 |
</div>
|
| 497 |
"""
|
| 498 |
return
|
| 499 |
|
| 500 |
-
# AI 분석
|
| 501 |
yield f"""
|
| 502 |
<div style="text-align: center; padding: 15px; background: linear-gradient(135deg, #4CAF50 0%, #45a049 100%); color: white; border-radius: 10px; margin-bottom: 15px;">
|
| 503 |
-
<h4>
|
| 504 |
-
<p>
|
| 505 |
</div>
|
| 506 |
|
| 507 |
<div style="text-align: center; padding: 15px; background: linear-gradient(135deg, #FF6B6B 0%, #FF8E8E 100%); color: white; border-radius: 10px; margin-bottom: 15px;">
|
| 508 |
-
<h4>
|
| 509 |
-
<p>
|
| 510 |
-
<p style="font-size: 14px; opacity: 0.9;">약 10-20초 소요 예상</p>
|
| 511 |
</div>
|
| 512 |
"""
|
| 513 |
|
| 514 |
-
#
|
| 515 |
-
|
| 516 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 517 |
|
| 518 |
total_time = time.time() - start_time
|
| 519 |
|
| 520 |
# 최종 결과
|
| 521 |
yield f"""
|
| 522 |
<div style="text-align: center; padding: 15px; background: linear-gradient(135deg, #4CAF50 0%, #45a049 100%); color: white; border-radius: 10px; margin-bottom: 20px;">
|
| 523 |
-
<h3>분석 완료
|
| 524 |
-
<p><strong>설정:</strong> {region} | {period} | {category}</p>
|
| 525 |
-
<p><strong>총 소요 시간:</strong> {total_time:.1f}초</p>
|
| 526 |
</div>
|
| 527 |
|
| 528 |
{analysis_result}
|
| 529 |
|
| 530 |
<div style="margin-top: 20px; padding: 15px; background: linear-gradient(135deg, #667eea 0%, #764ba2 100%); color: white; border-radius: 10px; text-align: center;">
|
| 531 |
<p style="margin: 0; font-size: 14px;">
|
| 532 |
-
<strong>다
|
| 533 |
-
|
| 534 |
</p>
|
| 535 |
</div>
|
| 536 |
|
| 537 |
<div style="margin-top: 15px; padding: 10px; background-color: #f9f9f9; border-radius: 5px; font-size: 12px; color: #666; text-align: center;">
|
| 538 |
-
<p style="margin: 5px 0;"><strong>
|
| 539 |
-
<p style="margin: 5px 0;"><strong>
|
| 540 |
-
<p style="margin: 5px 0;"><strong>
|
| 541 |
</div>
|
| 542 |
"""
|
| 543 |
|
| 544 |
-
print(f"
|
| 545 |
|
| 546 |
except Exception as e:
|
| 547 |
error_details = traceback.format_exc()
|
| 548 |
-
print(f"
|
| 549 |
|
| 550 |
yield f"""
|
| 551 |
<div style="color: red; padding: 20px; border: 1px solid red; border-radius: 5px;">
|
| 552 |
<h3>오류 발생</h3>
|
| 553 |
<p><strong>오류:</strong> {str(e)}</p>
|
| 554 |
<details>
|
| 555 |
-
<summary>상세 오류 정보
|
| 556 |
<pre style="background-color: #f5f5f5; padding: 10px; margin-top: 10px; overflow-x: auto; font-size: 11px;">
|
| 557 |
{error_details}
|
| 558 |
</pre>
|
| 559 |
</details>
|
| 560 |
-
<p><strong>해결 방법:</strong>
|
| 561 |
</div>
|
| 562 |
"""
|
| 563 |
|
| 564 |
-
|
| 565 |
-
|
| 566 |
|
| 567 |
with gr.Blocks(
|
| 568 |
theme=gr.themes.Soft(),
|
| 569 |
-
title="Google Trends
|
| 570 |
css="""
|
| 571 |
.gradio-container {
|
| 572 |
max-width: 1200px !important;
|
|
@@ -577,142 +737,114 @@ def create_interface():
|
|
| 577 |
"""
|
| 578 |
) as interface:
|
| 579 |
|
| 580 |
-
|
| 581 |
-
gr.HTML(f"""
|
| 582 |
<div style="text-align: center; padding: 20px; background: linear-gradient(90deg, #667eea 0%, #764ba2 100%); color: white; border-radius: 10px; margin-bottom: 20px;">
|
| 583 |
-
<h1>Google Trends
|
| 584 |
-
<p>
|
| 585 |
-
<p style="font-size: 14px; opacity: 0.9;">
|
| 586 |
-
{'<p style="font-size: 12px; opacity: 0.7;">Hugging Face Space (Playwright 브라우저)</p>' if IS_HUGGINGFACE else ''}
|
| 587 |
</div>
|
| 588 |
""")
|
| 589 |
|
| 590 |
-
# API 키 상태 표시
|
| 591 |
-
if not ANTHROPIC_API_KEY:
|
| 592 |
-
gr.HTML("""
|
| 593 |
-
<div style="color: red; padding: 15px; border: 1px solid red; border-radius: 5px; margin-bottom: 20px;">
|
| 594 |
-
<h3>설정 필요</h3>
|
| 595 |
-
<p><strong>ANTHROPIC_API_KEY가 설정되지 않았습니다!</strong></p>
|
| 596 |
-
<p>Hugging Face Space Settings에서 Secret을 추가해주세요.</p>
|
| 597 |
-
</div>
|
| 598 |
-
""")
|
| 599 |
-
|
| 600 |
-
# 입력 섹션
|
| 601 |
with gr.Row():
|
| 602 |
with gr.Column(scale=1):
|
| 603 |
region_input = gr.Dropdown(
|
| 604 |
choices=["대한민국", "전세계", "미국", "일본", "중국"],
|
| 605 |
value="대한민국",
|
| 606 |
-
label="지역 선택"
|
| 607 |
-
info="분석할 지역을 선택하세요"
|
| 608 |
)
|
| 609 |
|
| 610 |
with gr.Column(scale=1):
|
| 611 |
period_input = gr.Dropdown(
|
| 612 |
choices=["지난 24시간", "지난 1시간", "지난 4시간", "지난 1일", "지난 7일"],
|
| 613 |
value="지난 7일",
|
| 614 |
-
label="기간 선택"
|
| 615 |
-
info="트렌드 분석 기간을 선택하세요"
|
| 616 |
)
|
| 617 |
|
| 618 |
with gr.Column(scale=1):
|
| 619 |
category_input = gr.Dropdown(
|
| 620 |
choices=["모든 카테고리", "게임", "건강", "기술", "스포츠", "엔터테인먼트", "뉴스", "비즈니스"],
|
| 621 |
value="모든 카테고리",
|
| 622 |
-
label="카테고리 선택"
|
| 623 |
-
info="관심 분야를 선택하세요"
|
| 624 |
)
|
| 625 |
|
| 626 |
-
# 분석 버튼
|
| 627 |
analyze_btn = gr.Button(
|
| 628 |
-
"
|
| 629 |
variant="primary",
|
| 630 |
size="lg"
|
| 631 |
)
|
| 632 |
|
| 633 |
-
# 결과 출력
|
| 634 |
output = gr.HTML(
|
| 635 |
label="실시간 분석 결과",
|
| 636 |
-
value=
|
| 637 |
<div style="text-align: center; padding: 20px; border: 2px dashed #ccc; border-radius: 10px; color: #666;">
|
| 638 |
-
<h3>분석 대기 중</h3>
|
| 639 |
-
<p>
|
| 640 |
-
<p
|
| 641 |
-
|
| 642 |
</div>
|
| 643 |
"""
|
| 644 |
)
|
| 645 |
|
| 646 |
-
# 이벤트 연결
|
| 647 |
analyze_btn.click(
|
| 648 |
-
fn=
|
| 649 |
inputs=[region_input, period_input, category_input],
|
| 650 |
outputs=output,
|
| 651 |
show_progress="hidden"
|
| 652 |
)
|
| 653 |
|
| 654 |
-
# 사용법 안내
|
| 655 |
gr.HTML("""
|
| 656 |
<div style="margin-top: 30px; padding: 20px; background: linear-gradient(135deg, #a8edea 0%, #fed6e3 100%); border-radius: 10px;">
|
| 657 |
-
<h3 style="margin-top: 0; color: #333;">
|
| 658 |
<div style="display: grid; grid-template-columns: 1fr 1fr; gap: 20px; color: #555;">
|
| 659 |
<div>
|
| 660 |
-
<h4>
|
| 661 |
<ul style="margin: 0; padding-left: 20px;">
|
| 662 |
-
<li>
|
| 663 |
-
<li>
|
| 664 |
-
<li>
|
| 665 |
</ul>
|
| 666 |
</div>
|
| 667 |
<div>
|
| 668 |
-
<h4>
|
| 669 |
<ul style="margin: 0; padding-left: 20px;">
|
| 670 |
-
<li>
|
| 671 |
-
<li>
|
| 672 |
-
<li>
|
| 673 |
</ul>
|
| 674 |
</div>
|
| 675 |
</div>
|
| 676 |
</div>
|
| 677 |
""")
|
| 678 |
-
|
| 679 |
-
# Footer
|
| 680 |
-
gr.HTML(f"""
|
| 681 |
-
<div style="text-align: center; margin-top: 20px; padding: 15px; color: #666; border-top: 1px solid #eee;">
|
| 682 |
-
<p><strong>사용법:</strong> 원하는 설정을 선택하고 분석 버튼을 클릭하세요</p>
|
| 683 |
-
<p><strong>속도:</strong> 점차적으로 개선 예정입니다.</p>
|
| 684 |
-
<p><strong>Powered by:</strong> Google Trends + Claude AI + 실시간 스트리밍</p>
|
| 685 |
-
{'<p style="font-size: 12px;">Running on Hugging Face Spaces with Playwright Browser</p>' if IS_HUGGINGFACE else ''}
|
| 686 |
-
</div>
|
| 687 |
-
""")
|
| 688 |
|
| 689 |
return interface
|
| 690 |
|
| 691 |
-
#
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 692 |
if __name__ == "__main__":
|
| 693 |
print("=" * 50)
|
| 694 |
-
print("Google Trends
|
| 695 |
-
print(f"실행 환경: {'Hugging Face Space' if IS_HUGGINGFACE else 'Local'}")
|
| 696 |
print("=" * 50)
|
| 697 |
|
| 698 |
-
# API 키 확인
|
| 699 |
if not ANTHROPIC_API_KEY or ANTHROPIC_API_KEY == "your_api_key_here":
|
| 700 |
-
print("ANTHROPIC_API_KEY
|
| 701 |
-
if IS_HUGGINGFACE:
|
| 702 |
-
print("Hugging Face Space Settings에서 Secret을 추가해주세요!")
|
| 703 |
-
print("이 상태로도 앱은 실행되지만, 분석 기능은 작동하지 않습니다.")
|
| 704 |
-
print("=" * 50)
|
| 705 |
else:
|
| 706 |
print("Claude API 키 확인됨")
|
| 707 |
|
| 708 |
-
|
| 709 |
-
|
| 710 |
-
app = create_interface()
|
| 711 |
|
| 712 |
-
# 환경별 실행 설정
|
| 713 |
if os.getenv("SPACE_ID"):
|
| 714 |
-
|
| 715 |
-
print("Hugging Face Space 환경에서 실행 중...")
|
| 716 |
app.launch(
|
| 717 |
server_name="0.0.0.0",
|
| 718 |
server_port=7860,
|
|
@@ -720,914 +852,12 @@ if __name__ == "__main__":
|
|
| 720 |
show_api=False
|
| 721 |
)
|
| 722 |
else:
|
| 723 |
-
|
| 724 |
-
|
| 725 |
-
|
| 726 |
-
|
| 727 |
-
|
| 728 |
-
|
| 729 |
-
|
| 730 |
-
|
| 731 |
-
|
| 732 |
-
server_port=7860,
|
| 733 |
-
show_error=True,
|
| 734 |
-
show_api=False,
|
| 735 |
-
share=False,
|
| 736 |
-
inbrowser=True,
|
| 737 |
-
quiet=False
|
| 738 |
-
)
|
| 739 |
-
except KeyboardInterrupt:
|
| 740 |
-
print("\n\nGoogle Trends 분석기가 종료")
|
| 741 |
-
print("감사합니다!")
|
| 742 |
-
except Exception as e:
|
| 743 |
-
print(f"\n서버 실행 중 오류: {e}")
|
| 744 |
-
print("포트 7860이 이미 사용 중인지 확인")
|
| 745 |
-
|
| 746 |
-
|
| 747 |
-
|
| 748 |
-
|
| 749 |
-
|
| 750 |
-
# import os
|
| 751 |
-
# import time
|
| 752 |
-
# import base64
|
| 753 |
-
# import json
|
| 754 |
-
# import traceback
|
| 755 |
-
# from typing import Tuple, Optional
|
| 756 |
-
# import gradio as gr
|
| 757 |
-
# import anthropic
|
| 758 |
-
# from selenium import webdriver
|
| 759 |
-
# from selenium.webdriver.chrome.options import Options
|
| 760 |
-
# from selenium.webdriver.common.by import By
|
| 761 |
-
# from selenium.webdriver.support.ui import WebDriverWait
|
| 762 |
-
# from selenium.webdriver.support import expected_conditions as EC
|
| 763 |
-
# from selenium.common.exceptions import TimeoutException, NoSuchElementException
|
| 764 |
-
# from concurrent.futures import ThreadPoolExecutor
|
| 765 |
-
# import threading
|
| 766 |
-
|
| 767 |
-
# # Hugging Face Space 환경 확인
|
| 768 |
-
# IS_HUGGINGFACE = os.getenv("SPACE_ID") is not None
|
| 769 |
-
# print(f'IS_HUGGINGFACE = {IS_HUGGINGFACE}')
|
| 770 |
-
|
| 771 |
-
# # Claude API 설정 (Hugging Face Secrets에서 가져오기)
|
| 772 |
-
# ANTHROPIC_API_KEY = os.getenv("ANTHROPIC_API_KEY")
|
| 773 |
-
|
| 774 |
-
# if not ANTHROPIC_API_KEY:
|
| 775 |
-
# print("ANTHROPIC_API_KEY가 설정되지 않음, Secret 확인 필요")
|
| 776 |
-
# else:
|
| 777 |
-
# print("Claude API 키 확인 완료")
|
| 778 |
-
|
| 779 |
-
# # Claude 클라이언트를 생성
|
| 780 |
-
# def create_claude_client():
|
| 781 |
-
# try:
|
| 782 |
-
# client = anthropic.Anthropic(api_key=ANTHROPIC_API_KEY)
|
| 783 |
-
# print("Claude API 클라이언트 생성 성공")
|
| 784 |
-
# return client
|
| 785 |
-
# except Exception as e:
|
| 786 |
-
# print(f"Claude API 클라이언트 생성 실패: {e}")
|
| 787 |
-
# return None
|
| 788 |
-
|
| 789 |
-
# # Google Trends 자동화 클래스
|
| 790 |
-
# class GoogleTrendsAutomator:
|
| 791 |
-
# def __init__(self):
|
| 792 |
-
# self.driver = None
|
| 793 |
-
|
| 794 |
-
# # Chrome 드라이버 설정
|
| 795 |
-
# def setup_driver(self):
|
| 796 |
-
# options = Options()
|
| 797 |
-
|
| 798 |
-
# # Hugging Face Space 환경 설정
|
| 799 |
-
# if IS_HUGGINGFACE:
|
| 800 |
-
# print("Hugging Face Space 환경, 헤드리스 모드로 실행")
|
| 801 |
-
# options.add_argument("--headless=new") # 새로운 헤드리스 모드
|
| 802 |
-
# options.add_argument("--no-sandbox")
|
| 803 |
-
# options.add_argument("--disable-dev-shm-usage")
|
| 804 |
-
# options.add_argument("--disable-gpu")
|
| 805 |
-
# options.add_argument("--disable-software-rasterizer")
|
| 806 |
-
# options.add_argument("--remote-debugging-port=9222")
|
| 807 |
-
# else:
|
| 808 |
-
# options.add_argument("--headless")
|
| 809 |
-
|
| 810 |
-
# # # 환경별 설정
|
| 811 |
-
# # if os.getenv("SPACE_ID"): # Hugging Face Space
|
| 812 |
-
# # options.add_argument("--headless")
|
| 813 |
-
# # options.add_argument("--no-sandbox")
|
| 814 |
-
# # options.add_argument("--disable-dev-shm-usage")
|
| 815 |
-
# # options.add_argument("--disable-gpu")
|
| 816 |
-
# # else: # 로컬 환경
|
| 817 |
-
# # options.add_argument("--headless")
|
| 818 |
-
|
| 819 |
-
# # 속도 최적화 설정
|
| 820 |
-
# options.add_argument("--window-size=1280,720") # 해상도 줄임
|
| 821 |
-
# options.add_argument("--disable-blink-features=AutomationControlled")
|
| 822 |
-
# options.add_argument("--disable-extensions")
|
| 823 |
-
# options.add_argument("--disable-web-security")
|
| 824 |
-
# options.add_argument("--allow-running-insecure-content")
|
| 825 |
-
# options.add_argument("--disable-background-timer-throttling")
|
| 826 |
-
# options.add_argument("--disable-backgrounding-occluded-windows")
|
| 827 |
-
# options.add_argument("--disable-renderer-backgrounding")
|
| 828 |
-
# options.add_argument("--disable-features=TranslateUI")
|
| 829 |
-
# options.add_argument("--disable-ipc-flooding-protection")
|
| 830 |
-
|
| 831 |
-
# # 네트워크 최적화
|
| 832 |
-
# options.add_argument("--aggressive-cache-discard")
|
| 833 |
-
# options.add_argument("--disable-background-networking")
|
| 834 |
-
|
| 835 |
-
# # 메모리 최적화
|
| 836 |
-
# options.add_argument("--memory-pressure-off")
|
| 837 |
-
# # options.add_argument("--max_old_space_size=4096")
|
| 838 |
-
# options.add_argument("--max_old_space_size=2048")# 메모리 제한
|
| 839 |
-
|
| 840 |
-
# # 이미지/CSS 비활성화로 로딩 속도 향상
|
| 841 |
-
# prefs = {
|
| 842 |
-
# "profile.managed_default_content_settings.images": 2, # 이미지 차단
|
| 843 |
-
# "profile.default_content_setting_values.notifications": 2, # 알림 차단
|
| 844 |
-
# }
|
| 845 |
-
# options.add_experimental_option("prefs", prefs)
|
| 846 |
-
|
| 847 |
-
# # 봇 감지 회피
|
| 848 |
-
# options.add_argument("--user-agent=Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/120.0.0.0 Safari/537.36")
|
| 849 |
-
# options.add_experimental_option("excludeSwitches", ["enable-automation"])
|
| 850 |
-
# options.add_experimental_option('useAutomationExtension', False)
|
| 851 |
-
|
| 852 |
-
# # 언어 설정
|
| 853 |
-
# options.add_argument("--lang=ko")
|
| 854 |
-
# options.add_argument("--accept-lang=ko-KR,ko;q=0.9,en;q=0.8")
|
| 855 |
-
|
| 856 |
-
# try:
|
| 857 |
-
# # Hugging Face 환경에서는 webdriver-manager 우선 사용
|
| 858 |
-
# if IS_HUGGINGFACE:
|
| 859 |
-
# try:
|
| 860 |
-
# from webdriver_manager.chrome import ChromeDriverManager
|
| 861 |
-
# from selenium.webdriver.chrome.service import Service
|
| 862 |
-
|
| 863 |
-
# print("ChromeDriver 자동 설치 중...")
|
| 864 |
-
# service = Service(ChromeDriverManager().install())
|
| 865 |
-
# self.driver = webdriver.Chrome(service=service, options=options)
|
| 866 |
-
# print("ChromeDriver 설치 및 초기화 성공")
|
| 867 |
-
|
| 868 |
-
# except Exception as e:
|
| 869 |
-
# print(f"webdriver-manager 설치 실패: {e}")
|
| 870 |
-
# # 시스템 ChromeDriver 시도
|
| 871 |
-
# try:
|
| 872 |
-
# self.driver = webdriver.Chrome(options=options)
|
| 873 |
-
# print("시스템 ChromeDriver 사용 성공")
|
| 874 |
-
# except Exception as sys_e:
|
| 875 |
-
# print(f"시스템 ChromeDriver도 실패: {sys_e}")
|
| 876 |
-
# return False
|
| 877 |
-
# else:
|
| 878 |
-
# # 로컬 환경
|
| 879 |
-
# try:
|
| 880 |
-
# from webdriver_manager.chrome import ChromeDriverManager
|
| 881 |
-
# from selenium.webdriver.chrome.service import Service
|
| 882 |
-
|
| 883 |
-
# service = Service(ChromeDriverManager().install())
|
| 884 |
-
# self.driver = webdriver.Chrome(service=service, options=options)
|
| 885 |
-
# print("로컬 ChromeDriver 설치 성공")
|
| 886 |
-
# except:
|
| 887 |
-
# self.driver = webdriver.Chrome(options=options)
|
| 888 |
-
# print("로컬 시스템 ChromeDriver 사용")
|
| 889 |
-
# # # 여러 방법으로 ChromeDriver 시도
|
| 890 |
-
# # driver_created = False
|
| 891 |
-
|
| 892 |
-
# # # 방법 1: webdriver-manager 사용
|
| 893 |
-
# # try:
|
| 894 |
-
# # from webdriver_manager.chrome import ChromeDriverManager
|
| 895 |
-
# # from selenium.webdriver.chrome.service import Service
|
| 896 |
-
|
| 897 |
-
# # service = Service(ChromeDriverManager().install())
|
| 898 |
-
# # self.driver = webdriver.Chrome(service=service, options=options)
|
| 899 |
-
# # print("webdriver-manager로 ChromeDriver 자동 설치 성공")
|
| 900 |
-
# # driver_created = True
|
| 901 |
-
|
| 902 |
-
# # except Exception as wm_error:
|
| 903 |
-
# # print(f"webdriver-manager 실패: {wm_error}")
|
| 904 |
-
|
| 905 |
-
# # # 방법 2: 시스템 ChromeDriver 사용
|
| 906 |
-
# # if not driver_created:
|
| 907 |
-
# # try:
|
| 908 |
-
# # self.driver = webdriver.Chrome(options=options)
|
| 909 |
-
# # print("시스템 ChromeDriver 사용 성공")
|
| 910 |
-
# # driver_created = True
|
| 911 |
-
# # except Exception as sys_error:
|
| 912 |
-
# # print(f"시스템 ChromeDriver 실패: {sys_error}")
|
| 913 |
-
|
| 914 |
-
# # if not driver_created:
|
| 915 |
-
# # print("모든 ChromeDriver 초기화 방법 실패")
|
| 916 |
-
# # return False
|
| 917 |
-
|
| 918 |
-
# # 타임아웃 설정 (속도 최적화)
|
| 919 |
-
# self.driver.set_page_load_timeout(15) # 페이지 로딩 타임아웃 15초
|
| 920 |
-
# self.driver.implicitly_wait(2) # 요소 대기 시간 2초로 단축
|
| 921 |
-
|
| 922 |
-
# # 봇 감지 방지 스크립트
|
| 923 |
-
# try:
|
| 924 |
-
# self.driver.execute_script("""
|
| 925 |
-
# Object.defineProperty(navigator, 'webdriver', {get: () => undefined});
|
| 926 |
-
# Object.defineProperty(navigator, 'plugins', {get: () => [1, 2, 3, 4, 5]});
|
| 927 |
-
# Object.defineProperty(navigator, 'languages', {get: () => ['ko-KR', 'ko', 'en']});
|
| 928 |
-
# """)
|
| 929 |
-
# except Exception as script_error:
|
| 930 |
-
# print(f"봇 감지 방지 스크립트 실패 (무시): {script_error}")
|
| 931 |
-
|
| 932 |
-
# return True
|
| 933 |
-
|
| 934 |
-
# except Exception as e:
|
| 935 |
-
# print(f"드라이버 설정 최종 실패: {e}")
|
| 936 |
-
# return False
|
| 937 |
-
|
| 938 |
-
# # 빠르게 Element 찾기, Timeout 단축 고려
|
| 939 |
-
# def safe_find_element(self, selectors: list, timeout: int = 3):
|
| 940 |
-
# for selector_type, selector in selectors:
|
| 941 |
-
# try:
|
| 942 |
-
# if selector_type == "xpath":
|
| 943 |
-
# element = WebDriverWait(self.driver, timeout).until(
|
| 944 |
-
# EC.presence_of_element_located((By.XPATH, selector))
|
| 945 |
-
# )
|
| 946 |
-
# elif selector_type == "css":
|
| 947 |
-
# element = WebDriverWait(self.driver, timeout).until(
|
| 948 |
-
# EC.presence_of_element_located((By.CSS_SELECTOR, selector))
|
| 949 |
-
# )
|
| 950 |
-
# elif selector_type == "text":
|
| 951 |
-
# element = WebDriverWait(self.driver, timeout).until(
|
| 952 |
-
# EC.presence_of_element_located((By.XPATH, f"//*[contains(text(), '{selector}')]"))
|
| 953 |
-
# )
|
| 954 |
-
|
| 955 |
-
# if element:
|
| 956 |
-
# return element
|
| 957 |
-
# except:
|
| 958 |
-
# continue
|
| 959 |
-
# return None
|
| 960 |
-
|
| 961 |
-
# # 즉시 클릭
|
| 962 |
-
# def safe_click(self, selectors: list, timeout: int = 3) -> bool:
|
| 963 |
-
# element = self.safe_find_element(selectors, timeout)
|
| 964 |
-
# if element:
|
| 965 |
-
# try:
|
| 966 |
-
# # JavaScript 클릭 우선 시도 (더 빠름)
|
| 967 |
-
# self.driver.execute_script("arguments[0].click();", element)
|
| 968 |
-
# return True
|
| 969 |
-
# except:
|
| 970 |
-
# try:
|
| 971 |
-
# element.click()
|
| 972 |
-
# return True
|
| 973 |
-
# except:
|
| 974 |
-
# return False
|
| 975 |
-
# return False
|
| 976 |
-
|
| 977 |
-
# # 병렬로 설정 변경 시도
|
| 978 |
-
# def parallel_change_settings(self, region: str, period: str, category: str, progress_callback=None) -> dict:
|
| 979 |
-
# results = {
|
| 980 |
-
# 'region': False,
|
| 981 |
-
# 'period': False,
|
| 982 |
-
# 'category': False,
|
| 983 |
-
# 'errors': []
|
| 984 |
-
# }
|
| 985 |
-
|
| 986 |
-
# # 순차적으로 변경 (병렬은 selenium에서 안전하지 않음)
|
| 987 |
-
# try:
|
| 988 |
-
# if region != "대한민국":
|
| 989 |
-
# if progress_callback:
|
| 990 |
-
# progress_callback("지역 설정 변경 중...")
|
| 991 |
-
# results['region'] = self.change_region(region)
|
| 992 |
-
# time.sleep(0.5) # 최소 대기
|
| 993 |
-
# else:
|
| 994 |
-
# results['region'] = True
|
| 995 |
-
|
| 996 |
-
# if period != "지난 24시간":
|
| 997 |
-
# if progress_callback:
|
| 998 |
-
# progress_callback("기간 설정 변경 중...")
|
| 999 |
-
# results['period'] = self.change_time_period(period)
|
| 1000 |
-
# time.sleep(0.5) # 최소 대기
|
| 1001 |
-
# else:
|
| 1002 |
-
# results['period'] = True
|
| 1003 |
-
|
| 1004 |
-
# if category != "모든 카테고리":
|
| 1005 |
-
# if progress_callback:
|
| 1006 |
-
# progress_callback("카테고리 설정 변경 중...")
|
| 1007 |
-
# results['category'] = self.change_category(category)
|
| 1008 |
-
# time.sleep(0.5) # 최소 대기
|
| 1009 |
-
# else:
|
| 1010 |
-
# results['category'] = True
|
| 1011 |
-
|
| 1012 |
-
# except Exception as e:
|
| 1013 |
-
# results['errors'].append(str(e))
|
| 1014 |
-
|
| 1015 |
-
# return results
|
| 1016 |
-
|
| 1017 |
-
# # 지역 변경
|
| 1018 |
-
# def change_region(self, target_region: str) -> bool:
|
| 1019 |
-
# try:
|
| 1020 |
-
# region_selectors = [
|
| 1021 |
-
# ("xpath", "//button[@aria-label='대한민국, 위치 선택']"),
|
| 1022 |
-
# ("xpath", "//button[contains(@aria-label, '위치 선택')]"),
|
| 1023 |
-
# ("xpath", "//span[contains(text(), '대한민국')]//parent::button"),
|
| 1024 |
-
# ]
|
| 1025 |
-
|
| 1026 |
-
# if not self.safe_click(region_selectors):
|
| 1027 |
-
# return False
|
| 1028 |
-
|
| 1029 |
-
# time.sleep(1) # 대기 시간 단축
|
| 1030 |
-
|
| 1031 |
-
# region_mapping = {
|
| 1032 |
-
# "전세계": ["전 세계", "Worldwide"],
|
| 1033 |
-
# "미국": ["미국", "United States"],
|
| 1034 |
-
# "일본": ["일본", "Japan"],
|
| 1035 |
-
# "중국": ["중국", "China"]
|
| 1036 |
-
# }
|
| 1037 |
-
|
| 1038 |
-
# if target_region in region_mapping:
|
| 1039 |
-
# for region_text in region_mapping[target_region]:
|
| 1040 |
-
# region_option_selectors = [
|
| 1041 |
-
# ("xpath", f"//span[contains(text(), '{region_text}')]"),
|
| 1042 |
-
# ("xpath", f"//*[contains(text(), '{region_text}')]"),
|
| 1043 |
-
# ]
|
| 1044 |
-
|
| 1045 |
-
# if self.safe_click(region_option_selectors, timeout=2):
|
| 1046 |
-
# return True
|
| 1047 |
-
|
| 1048 |
-
# return False
|
| 1049 |
-
|
| 1050 |
-
# except Exception as e:
|
| 1051 |
-
# print(f"지역 변경 실패: {e}")
|
| 1052 |
-
# return False
|
| 1053 |
-
|
| 1054 |
-
# # 기간 변경
|
| 1055 |
-
# def change_time_period(self, target_period: str) -> bool:
|
| 1056 |
-
# try:
|
| 1057 |
-
# period_selectors = [
|
| 1058 |
-
# ("xpath", "//button[contains(@aria-label, '기간 선택')]"),
|
| 1059 |
-
# ("xpath", "//span[contains(text(), '지난 24시간')]//parent::button"),
|
| 1060 |
-
# ]
|
| 1061 |
-
|
| 1062 |
-
# if not self.safe_click(period_selectors):
|
| 1063 |
-
# return False
|
| 1064 |
-
|
| 1065 |
-
# time.sleep(1) # 대기 시간 단축
|
| 1066 |
-
|
| 1067 |
-
# period_mapping = {
|
| 1068 |
-
# "지난 1시간": ["지난 1시간"],
|
| 1069 |
-
# "지난 4시간": ["지난 4시간"],
|
| 1070 |
-
# "지난 1일": ["지난 1일"],
|
| 1071 |
-
# "지난 7일": ["지난 7일", "지난 주"]
|
| 1072 |
-
# }
|
| 1073 |
-
|
| 1074 |
-
# if target_period in period_mapping:
|
| 1075 |
-
# for period_text in period_mapping[target_period]:
|
| 1076 |
-
# period_option_selectors = [
|
| 1077 |
-
# ("xpath", f"//span[contains(text(), '{period_text}')]"),
|
| 1078 |
-
# ("xpath", f"//*[contains(text(), '{period_text}')]"),
|
| 1079 |
-
# ]
|
| 1080 |
-
|
| 1081 |
-
# if self.safe_click(period_option_selectors, timeout=2):
|
| 1082 |
-
# return True
|
| 1083 |
-
|
| 1084 |
-
# return False
|
| 1085 |
-
|
| 1086 |
-
# except Exception as e:
|
| 1087 |
-
# print(f"기간 변경 실패: {e}")
|
| 1088 |
-
# return False
|
| 1089 |
-
|
| 1090 |
-
# # 카테고리 변경
|
| 1091 |
-
# def change_category(self, target_category: str) -> bool:
|
| 1092 |
-
# try:
|
| 1093 |
-
# category_selectors = [
|
| 1094 |
-
# ("xpath", "//button[contains(@aria-label, '카테고리 선택')]"),
|
| 1095 |
-
# ("xpath", "//span[contains(text(), '모든 카테고리')]//parent::button"),
|
| 1096 |
-
# ]
|
| 1097 |
-
|
| 1098 |
-
# if not self.safe_click(category_selectors):
|
| 1099 |
-
# return False
|
| 1100 |
-
|
| 1101 |
-
# time.sleep(1) # 대기 시간 단축
|
| 1102 |
-
|
| 1103 |
-
# category_mapping = {
|
| 1104 |
-
# "게임": ["게임"],
|
| 1105 |
-
# "건강": ["건강"],
|
| 1106 |
-
# "기술": ["컴퓨터 및 전자제품", "기술"],
|
| 1107 |
-
# "스포츠": ["스포츠"],
|
| 1108 |
-
# "엔터테인먼트": ["예술 및 엔터테인먼트", "엔터테인먼트"],
|
| 1109 |
-
# "뉴스": ["뉴스"],
|
| 1110 |
-
# "비즈니스": ["비즈니스"]
|
| 1111 |
-
# }
|
| 1112 |
-
|
| 1113 |
-
# if target_category in category_mapping:
|
| 1114 |
-
# for category_text in category_mapping[target_category]:
|
| 1115 |
-
# category_option_selectors = [
|
| 1116 |
-
# ("xpath", f"//span[contains(text(), '{category_text}')]"),
|
| 1117 |
-
# ("xpath", f"//*[contains(text(), '{category_text}')]"),
|
| 1118 |
-
# ]
|
| 1119 |
-
|
| 1120 |
-
# if self.safe_click(category_option_selectors, timeout=2):
|
| 1121 |
-
# return True
|
| 1122 |
-
|
| 1123 |
-
# return False
|
| 1124 |
-
|
| 1125 |
-
# except Exception as e:
|
| 1126 |
-
# print(f"카테고리 변경 실패: {e}")
|
| 1127 |
-
# return False
|
| 1128 |
-
|
| 1129 |
-
# # Google Trends 캡처
|
| 1130 |
-
# def capture_trends(self, region: str, period: str, category: str, progress_callback=None) -> Tuple[Optional[str], bool, str]:
|
| 1131 |
-
# error_msg = ""
|
| 1132 |
-
|
| 1133 |
-
# try:
|
| 1134 |
-
# if progress_callback:
|
| 1135 |
-
# progress_callback("브라우저 드라이버 초기화 중...")
|
| 1136 |
-
|
| 1137 |
-
# # 드라이버 설정
|
| 1138 |
-
# if not self.setup_driver():
|
| 1139 |
-
# return None, False, "브라우저 드라이버 설정 실패"
|
| 1140 |
-
|
| 1141 |
-
# if progress_callback:
|
| 1142 |
-
# progress_callback("Google Trends 페이지 접속 중...")
|
| 1143 |
-
|
| 1144 |
-
# # Google Trends 접속 (한국어 직접 URL)
|
| 1145 |
-
# self.driver.get("https://trends.google.com/trending?geo=KR&hl=ko")
|
| 1146 |
-
|
| 1147 |
-
# # 최소한의 로딩 대기 (1초로 단축)
|
| 1148 |
-
# time.sleep(1)
|
| 1149 |
-
|
| 1150 |
-
# if progress_callback:
|
| 1151 |
-
# progress_callback("페이지 로딩 완료, 설정 변경 시작...")
|
| 1152 |
-
|
| 1153 |
-
# # 페이지 준비 확인 (빠른 체크)
|
| 1154 |
-
# try:
|
| 1155 |
-
# WebDriverWait(self.driver, 5).until(
|
| 1156 |
-
# EC.presence_of_element_located((By.TAG_NAME, "button"))
|
| 1157 |
-
# )
|
| 1158 |
-
# except TimeoutException:
|
| 1159 |
-
# pass # 계속 진행
|
| 1160 |
-
|
| 1161 |
-
# # 설정 변경 (병렬 처리)
|
| 1162 |
-
# settings_result = self.parallel_change_settings(region, period, category, progress_callback)
|
| 1163 |
-
|
| 1164 |
-
# # 결과 확인
|
| 1165 |
-
# changes_made = []
|
| 1166 |
-
# if settings_result['region']:
|
| 1167 |
-
# changes_made.append(f"지역: {region}")
|
| 1168 |
-
# if settings_result['period']:
|
| 1169 |
-
# changes_made.append(f"기간: {period}")
|
| 1170 |
-
# if settings_result['category']:
|
| 1171 |
-
# changes_made.append(f"카테고리: {category}")
|
| 1172 |
-
|
| 1173 |
-
# if settings_result['errors']:
|
| 1174 |
-
# error_msg = "\n".join(settings_result['errors'])
|
| 1175 |
-
|
| 1176 |
-
# if progress_callback:
|
| 1177 |
-
# progress_callback("설정 변경 완료, 데이터 가져오는중...")
|
| 1178 |
-
|
| 1179 |
-
# # 최종 데이터 로딩 대기 (1초로 단축)
|
| 1180 |
-
# time.sleep(1)
|
| 1181 |
-
|
| 1182 |
-
# # 스크린샷 촬영 (필요한 영역만)
|
| 1183 |
-
# screenshot = self.driver.get_screenshot_as_png()
|
| 1184 |
-
# screenshot_b64 = base64.b64encode(screenshot).decode()
|
| 1185 |
-
|
| 1186 |
-
# success_msg = f"설정 완료: {', '.join(changes_made) if changes_made else '기본 설정 사용'}"
|
| 1187 |
-
|
| 1188 |
-
# return screenshot_b64, True, success_msg + ("\n" + error_msg if error_msg else "")
|
| 1189 |
-
|
| 1190 |
-
# except Exception as e:
|
| 1191 |
-
# error_msg = f"오류 발생: {str(e)}"
|
| 1192 |
-
# return None, False, error_msg
|
| 1193 |
-
|
| 1194 |
-
# finally:
|
| 1195 |
-
# if self.driver:
|
| 1196 |
-
# self.driver.quit()
|
| 1197 |
-
|
| 1198 |
-
# # Claude API로 스크린샷 분석
|
| 1199 |
-
# def analyze_with_claude(screenshot_b64: str, region: str, period: str, category: str) -> str:
|
| 1200 |
-
# try:
|
| 1201 |
-
# # API 키 체크
|
| 1202 |
-
# if not ANTHROPIC_API_KEY or ANTHROPIC_API_KEY == "your_api_key_here":
|
| 1203 |
-
# return """
|
| 1204 |
-
# <div style="color: red; padding: 20px; border: 1px solid red; border-radius: 5px;">
|
| 1205 |
-
# <h3>API 키 오류</h3>
|
| 1206 |
-
# <p><strong>ANTHROPIC_API_KEY가 설정되지 않았습니다!</strong></p>
|
| 1207 |
-
# </div>
|
| 1208 |
-
# """
|
| 1209 |
-
|
| 1210 |
-
# # Claude 클라이언트 생성
|
| 1211 |
-
# claude_client = create_claude_client()
|
| 1212 |
-
|
| 1213 |
-
# if claude_client is None:
|
| 1214 |
-
# return """
|
| 1215 |
-
# <div style="color: red; padding: 20px; border: 1px solid red; border-radius: 5px;">
|
| 1216 |
-
# <h3>Claude API 연결 실패</h3>
|
| 1217 |
-
# <p>API 연결에 문제가 있습니다. 잠시 후 다시 시도해주세요.</p>
|
| 1218 |
-
# </div>
|
| 1219 |
-
# """
|
| 1220 |
-
|
| 1221 |
-
# # 간결한 프롬프트 (속도 최적화)
|
| 1222 |
-
# prompt = f"""
|
| 1223 |
-
# 이 Google Trends 스크린샷을 분석해주세요.
|
| 1224 |
-
# 설정: {region} | {period} | {category}
|
| 1225 |
-
|
| 1226 |
-
# 다음을 HTML 표 형태로 정확하게 정리해주세요:
|
| 1227 |
-
# 1. 실시간 인기 검색어 상위 10개 (순위, 검색어, 검색량, 상승률)
|
| 1228 |
-
# 2. 주요 트렌드 키워드 3-5개의 특징 설명
|
| 1229 |
-
# 3. 카테고리별 특이사항 (있는 경우)
|
| 1230 |
-
|
| 1231 |
-
# HTML 형태로 깔끔하게 정리하고, 이모지를 사용하지 않고 시각적으로 만들어주세요.
|
| 1232 |
-
# 한글 텍스트를 정확히 읽어서 분석해주세요.
|
| 1233 |
-
# """
|
| 1234 |
-
|
| 1235 |
-
# # Claude API 호출 (빠른 설정)
|
| 1236 |
-
# message = claude_client.messages.create(
|
| 1237 |
-
# model="claude-3-5-sonnet-20241022",
|
| 1238 |
-
# max_tokens=1000, # 토큰 수 줄여서 속도 향상
|
| 1239 |
-
# messages=[
|
| 1240 |
-
# {
|
| 1241 |
-
# "role": "user",
|
| 1242 |
-
# "content": [
|
| 1243 |
-
# {
|
| 1244 |
-
# "type": "text",
|
| 1245 |
-
# "text": prompt
|
| 1246 |
-
# },
|
| 1247 |
-
# {
|
| 1248 |
-
# "type": "image",
|
| 1249 |
-
# "source": {
|
| 1250 |
-
# "type": "base64",
|
| 1251 |
-
# "media_type": "image/png",
|
| 1252 |
-
# "data": screenshot_b64
|
| 1253 |
-
# }
|
| 1254 |
-
# }
|
| 1255 |
-
# ]
|
| 1256 |
-
# }
|
| 1257 |
-
# ]
|
| 1258 |
-
# )
|
| 1259 |
-
|
| 1260 |
-
# return message.content[0].text
|
| 1261 |
-
|
| 1262 |
-
# except Exception as e:
|
| 1263 |
-
# return f"""
|
| 1264 |
-
# <div style="color: red; padding: 20px; border: 1px solid red; border-radius: 5px;">
|
| 1265 |
-
# <h3>Claude API 분석 실패</h3>
|
| 1266 |
-
# <p><strong>오류:</strong> {str(e)}</p>
|
| 1267 |
-
# </div>
|
| 1268 |
-
# """
|
| 1269 |
-
|
| 1270 |
-
# def main_analysis(region: str, period: str, category: str):
|
| 1271 |
-
# """실시간 스트리밍 분석 함수 (Generator)"""
|
| 1272 |
-
|
| 1273 |
-
# start_time = time.time()
|
| 1274 |
-
|
| 1275 |
-
# # 1단계: 시작 메시지
|
| 1276 |
-
# yield f"""
|
| 1277 |
-
# <div style="text-align: center; padding: 20px; background: linear-gradient(135deg, #667eea 0%, #764ba2 100%); color: white; border-radius: 10px; margin-bottom: 20px;">
|
| 1278 |
-
# <h3>Google Trends 분석 시작!</h3>
|
| 1279 |
-
# <p><strong>설정:</strong> {region} | {period} | {category}</p>
|
| 1280 |
-
# <p>실시간으로 진행 상황을 업데이트합니다...</p>
|
| 1281 |
-
# </div>
|
| 1282 |
-
# """
|
| 1283 |
-
|
| 1284 |
-
# progress_status = {"current": ""}
|
| 1285 |
-
|
| 1286 |
-
# def progress_callback(message):
|
| 1287 |
-
# progress_status["current"] = message
|
| 1288 |
-
|
| 1289 |
-
# try:
|
| 1290 |
-
# # 2단계: API 키 확인
|
| 1291 |
-
# if not ANTHROPIC_API_KEY or ANTHROPIC_API_KEY == "your_api_key_here":
|
| 1292 |
-
# yield """
|
| 1293 |
-
# <div style="color: red; padding: 20px; border: 1px solid red; border-radius: 5px;">
|
| 1294 |
-
# <h3> API 키 누락</h3>
|
| 1295 |
-
# <p><strong>ANTHROPIC_API_KEY가 설정되지 않았습니다!</strong></p>
|
| 1296 |
-
# <p><strong>해결 방법:</strong> .env 파일에 API 키를 설정하고 앱을 재시작하세요.</p>
|
| 1297 |
-
# </div>
|
| 1298 |
-
# """
|
| 1299 |
-
# return
|
| 1300 |
-
|
| 1301 |
-
# # 3단계: 브라우저 실행 알림
|
| 1302 |
-
# yield f"""
|
| 1303 |
-
# <div style="text-align: center; padding: 15px; background: linear-gradient(135deg, #4CAF50 0%, #45a049 100%); color: white; border-radius: 10px; margin-bottom: 15px;">
|
| 1304 |
-
# <h4> 1단계: 시작합니다! 입력하신 조건을 확인합니다...</h4>
|
| 1305 |
-
# <p>Connect Start...</p>
|
| 1306 |
-
# </div>
|
| 1307 |
-
|
| 1308 |
-
# <div style="padding: 15px; background-color: #f8f9fa; border-radius: 5px; margin-bottom: 15px;">
|
| 1309 |
-
# <p> <strong>진행 중:</strong> 브라우저 드라이버 설정 및 페이지 로딩...</p>
|
| 1310 |
-
# </div>
|
| 1311 |
-
# """
|
| 1312 |
-
|
| 1313 |
-
# # 4단계: Google Trends 자동화 실행
|
| 1314 |
-
# print(f" 분석 시작: {region} | {period} | {category}")
|
| 1315 |
-
# automator = GoogleTrendsAutomator()
|
| 1316 |
-
|
| 1317 |
-
# # 5단계: 설정 변경 알림
|
| 1318 |
-
# if region != "대한민국" or period != "지난 24시간" or category != "모든 카테고리":
|
| 1319 |
-
# yield f"""
|
| 1320 |
-
# <div style="text-align: center; padding: 15px; background: linear-gradient(135deg, #4CAF50 0%, #45a049 100%); color: white; border-radius: 10px; margin-bottom: 15px;">
|
| 1321 |
-
# <h4>자동화 시작</h4>
|
| 1322 |
-
# <p>In Running...</p>
|
| 1323 |
-
# </div>
|
| 1324 |
-
|
| 1325 |
-
# <div style="padding: 15px; background-color: #e3f2fd; border-radius: 5px; margin-bottom: 15px;">
|
| 1326 |
-
# <p><strong>설정 변경 중:</strong></p>
|
| 1327 |
-
# <ul style="margin: 10px 0;">
|
| 1328 |
-
# {"<li>지역: " + region + "</li>" if region != "대한민국" else ""}
|
| 1329 |
-
# {"<li>기간: " + period + "</li>" if period != "지난 24시간" else ""}
|
| 1330 |
-
# {"<li>카테고리: " + category + "</li>" if category != "모든 카테고리" else ""}
|
| 1331 |
-
# </ul>
|
| 1332 |
-
# </div>
|
| 1333 |
-
# """
|
| 1334 |
-
|
| 1335 |
-
# # 브라우저 작업을 별도 스레드에서 실행
|
| 1336 |
-
# with ThreadPoolExecutor(max_workers=1) as executor:
|
| 1337 |
-
# future = executor.submit(
|
| 1338 |
-
# automator.capture_trends,
|
| 1339 |
-
# region, period, category, progress_callback
|
| 1340 |
-
# )
|
| 1341 |
-
|
| 1342 |
-
# # 진행 상황 업데이트
|
| 1343 |
-
# while not future.done():
|
| 1344 |
-
# current_progress = progress_status["current"]
|
| 1345 |
-
# if current_progress:
|
| 1346 |
-
# elapsed = time.time() - start_time
|
| 1347 |
-
# yield f"""
|
| 1348 |
-
# <div style="text-align: center; padding: 15px; background: linear-gradient(135deg, #4CAF50 0%, #45a049 100%); color: white; border-radius: 10px; margin-bottom: 15px;">
|
| 1349 |
-
# <h4>자동화 시작</h4>
|
| 1350 |
-
# <p>In Running...</p>
|
| 1351 |
-
# </div>
|
| 1352 |
-
|
| 1353 |
-
# <div style="padding: 15px; background-color: #f8f9fa; border-radius: 5px; margin-bottom: 15px;">
|
| 1354 |
-
# <p><strong>진행 중:</strong> {current_progress}</p>
|
| 1355 |
-
# <p><strong>경과 시간:</strong> {elapsed:.1f}초</p>
|
| 1356 |
-
# </div>
|
| 1357 |
-
# """
|
| 1358 |
-
# time.sleep(0.5)
|
| 1359 |
-
|
| 1360 |
-
# # 결과 받기
|
| 1361 |
-
# screenshot_b64, success, status_msg = future.result()
|
| 1362 |
-
|
| 1363 |
-
# browser_time = time.time() - start_time
|
| 1364 |
-
|
| 1365 |
-
# if not success:
|
| 1366 |
-
# yield f"""
|
| 1367 |
-
# <div style="color: red; padding: 20px; border: 1px solid red; border-radius: 5px;">
|
| 1368 |
-
# <h3>Google Trends 접속 실패</h3>
|
| 1369 |
-
# <pre style="background-color: #fff5f5; padding: 15px; border-radius: 5px; margin: 15px 0;">
|
| 1370 |
-
# {status_msg}
|
| 1371 |
-
# </pre>
|
| 1372 |
-
# <p><strong>해결 방법:</strong> Chrome 브라우저와 ChromeDriver를 설치하고 다시 시도하세요.</p>
|
| 1373 |
-
# </div>
|
| 1374 |
-
# """
|
| 1375 |
-
# return
|
| 1376 |
-
|
| 1377 |
-
# # 6단계: 스크린샷 완료 및 AI 분석 시작
|
| 1378 |
-
# yield f"""
|
| 1379 |
-
# <div style="text-align: center; padding: 15px; background: linear-gradient(135deg, #4CAF50 0%, #45a049 100%); color: white; border-radius: 10px; margin-bottom: 15px;">
|
| 1380 |
-
# <h4>2단계: 입력하신 데이터를 확인했고, 조건에 맞는 데이터를 가져옵니다...</h4>
|
| 1381 |
-
# <p>Google Trends 데이터를 성공적으로 캡처했습니다.</p>
|
| 1382 |
-
# </div>
|
| 1383 |
-
|
| 1384 |
-
# <div style="text-align: center; padding: 15px; background: linear-gradient(135deg, #FF6B6B 0%, #FF8E8E 100%); color: white; border-radius: 10px; margin-bottom: 15px;">
|
| 1385 |
-
# <h4>3단계: AI 분석 진행 중...</h4>
|
| 1386 |
-
# <p>Claude AI가 트렌드 데이터를 분석하고 있습니다.</p>
|
| 1387 |
-
# <p style="font-size: 14px; opacity: 0.9;">약 10-20초 소요 예상</p>
|
| 1388 |
-
# </div>
|
| 1389 |
-
# """
|
| 1390 |
-
|
| 1391 |
-
# # 7단계: Claude API 분석
|
| 1392 |
-
# ai_start_time = time.time()
|
| 1393 |
-
# print("실시간 인기 검색어 데이터를 가져왔고, Claude 분석 시작합니다...")
|
| 1394 |
-
|
| 1395 |
-
# # AI 분석을 별도 스레드에서 실행
|
| 1396 |
-
# with ThreadPoolExecutor(max_workers=1) as executor:
|
| 1397 |
-
# ai_future = executor.submit(
|
| 1398 |
-
# analyze_with_claude,
|
| 1399 |
-
# screenshot_b64, region, period, category
|
| 1400 |
-
# )
|
| 1401 |
-
|
| 1402 |
-
# # AI 분석 진행 상황 표시
|
| 1403 |
-
# while not ai_future.done():
|
| 1404 |
-
# ai_elapsed = time.time() - ai_start_time
|
| 1405 |
-
# total_elapsed = time.time() - start_time
|
| 1406 |
-
# yield f"""
|
| 1407 |
-
# <div style="text-align: center; padding: 15px; background: linear-gradient(135deg, #4CAF50 0%, #45a049 100%); color: white; border-radius: 10px; margin-bottom: 15px;">
|
| 1408 |
-
# <h4>📸 2단계: 입력하신 데이터를 확인했고, 조건에 맞는 데이터를 가져옵니다...</h4>
|
| 1409 |
-
# <p>Google Trends 데이터를 성공적으로 캡처했습니다.</p>
|
| 1410 |
-
# </div>
|
| 1411 |
-
|
| 1412 |
-
# <div style="text-align: center; padding: 15px; background: linear-gradient(135deg, #FF6B6B 0%, #FF8E8E 100%); color: white; border-radius: 10px; margin-bottom: 15px;">
|
| 1413 |
-
# <h4>3단계: AI 분석 진행 중...</h4>
|
| 1414 |
-
# <p>Claude AI가 트렌드 데이터를 분석하고 있습니다. ({ai_elapsed:.1f}초)</p>
|
| 1415 |
-
# <p style="font-size: 14px; opacity: 0.9;">총 경과 시간: {total_elapsed:.1f}초</p>
|
| 1416 |
-
# </div>
|
| 1417 |
-
# """
|
| 1418 |
-
# time.sleep(0.5)
|
| 1419 |
-
|
| 1420 |
-
# analysis_result = ai_future.result()
|
| 1421 |
-
|
| 1422 |
-
# ai_time = time.time() - ai_start_time
|
| 1423 |
-
# total_time = time.time() - start_time
|
| 1424 |
-
|
| 1425 |
-
# # 8단계: 최종 결과 출력
|
| 1426 |
-
# yield f"""
|
| 1427 |
-
# <div style="text-align: center; padding: 15px; background: linear-gradient(135deg, #4CAF50 0%, #45a049 100%); color: white; border-radius: 10px; margin-bottom: 20px;">
|
| 1428 |
-
# <h3> 분석 완료!</h3>
|
| 1429 |
-
# <p><strong>설정:</strong> {region} | {period} | {category}</p>
|
| 1430 |
-
# <p>모든 단계가 성공적으로 완료되었습니다.</p>
|
| 1431 |
-
# </div>
|
| 1432 |
-
|
| 1433 |
-
# {analysis_result}
|
| 1434 |
-
|
| 1435 |
-
# <div style="margin-top: 20px; padding: 15px; background: linear-gradient(135deg, #667eea 0%, #764ba2 100%); color: white; border-radius: 10px; text-align: center;">
|
| 1436 |
-
# <p style="margin: 0; font-size: 14px;">
|
| 1437 |
-
# <strong>다른 설정으로 다시 분석하시겠습니까?</strong><br>
|
| 1438 |
-
# 위의 설정을 변경하고 다시 버튼을 클릭하세요!
|
| 1439 |
-
# </p>
|
| 1440 |
-
# </div>
|
| 1441 |
-
|
| 1442 |
-
# <div style="margin-top: 15px; padding: 10px; background-color: #f9f9f9; border-radius: 5px; font-size: 12px; color: #666; text-align: center;">
|
| 1443 |
-
# <p style="margin: 5px 0;"> <strong>분석 완료 시간:</strong> 약 15-30초</p>
|
| 1444 |
-
# <p style="margin: 5px 0;"> <strong>AI 엔진:</strong> Claude 3.5 Sonnet</p>
|
| 1445 |
-
# <p style="margin: 5px 0;"> <strong>데이터 출처:</strong> Google Trends 실시간 스크린샷</p>
|
| 1446 |
-
# </div>
|
| 1447 |
-
# """
|
| 1448 |
-
|
| 1449 |
-
# print("전체 분석 프로세스 완료!")
|
| 1450 |
-
|
| 1451 |
-
# except Exception as e:
|
| 1452 |
-
# error_details = traceback.format_exc()
|
| 1453 |
-
# print(f"메인 분석 중 예외 발생: {e}")
|
| 1454 |
-
|
| 1455 |
-
# yield f"""
|
| 1456 |
-
# <div style="color: red; padding: 20px; border: 1px solid red; border-radius: 5px;">
|
| 1457 |
-
# <h3>오류 발생</h3>
|
| 1458 |
-
# <p><strong>오류:</strong> {str(e)}</p>
|
| 1459 |
-
# <details>
|
| 1460 |
-
# <summary>상세 오류 정보 (클릭하여 펼치기)</summary>
|
| 1461 |
-
# <pre style="background-color: #f5f5f5; padding: 10px; margin-top: 10px; overflow-x: auto; font-size: 11px;">
|
| 1462 |
-
# {error_details}
|
| 1463 |
-
# </pre>
|
| 1464 |
-
# </details>
|
| 1465 |
-
# <p><strong>해결 방법:</strong> 페이지를 새로고침하고 다시 시도하세요.</p>
|
| 1466 |
-
# </div>
|
| 1467 |
-
# """
|
| 1468 |
-
|
| 1469 |
-
# # Gradio 인터페이스 (실시간 스트리밍 형태로)
|
| 1470 |
-
# def create_interface():
|
| 1471 |
-
|
| 1472 |
-
# with gr.Blocks(
|
| 1473 |
-
# theme=gr.themes.Soft(),
|
| 1474 |
-
# title="Google Trends 실시간 분석기",
|
| 1475 |
-
# css="""
|
| 1476 |
-
# .gradio-container {
|
| 1477 |
-
# max-width: 1200px !important;
|
| 1478 |
-
# }
|
| 1479 |
-
# .output-html {
|
| 1480 |
-
# max-height: none !important;
|
| 1481 |
-
# }
|
| 1482 |
-
# """
|
| 1483 |
-
# ) as interface:
|
| 1484 |
-
|
| 1485 |
-
# # Header
|
| 1486 |
-
# gr.HTML("""
|
| 1487 |
-
# <div style="text-align: center; padding: 20px; background: linear-gradient(90deg, #667eea 0%, #764ba2 100%); color: white; border-radius: 10px; margin-bottom: 20px;">
|
| 1488 |
-
# <h1>Google Trends 실시간 분석기</h1>
|
| 1489 |
-
# <p>Google Trends��� 실시간 인기 검색어를 AI가 자동으로 분석합니다</p>
|
| 1490 |
-
# <p style="font-size: 14px; opacity: 0.9;">개선된 방식으로 단계별 진행상황을 확인할 수 있습니다.</p>
|
| 1491 |
-
# </div>
|
| 1492 |
-
# """)
|
| 1493 |
-
|
| 1494 |
-
# # 입력 섹션
|
| 1495 |
-
# with gr.Row():
|
| 1496 |
-
# with gr.Column(scale=1):
|
| 1497 |
-
# region_input = gr.Dropdown(
|
| 1498 |
-
# choices=["대한민국", "전세계", "미국", "일본", "중국"],
|
| 1499 |
-
# value="대한민국",
|
| 1500 |
-
# label="지역 선택",
|
| 1501 |
-
# info="분석할 지역을 선택하세요"
|
| 1502 |
-
# )
|
| 1503 |
-
|
| 1504 |
-
# with gr.Column(scale=1):
|
| 1505 |
-
# period_input = gr.Dropdown(
|
| 1506 |
-
# choices=["지난 24시간", "지난 1시간", "지난 4시간", "지난 1일", "지난 7일"],
|
| 1507 |
-
# value="지난 7일",
|
| 1508 |
-
# label="기간 선택",
|
| 1509 |
-
# info="트렌드 분석 기간을 선택하세요"
|
| 1510 |
-
# )
|
| 1511 |
-
|
| 1512 |
-
# with gr.Column(scale=1):
|
| 1513 |
-
# category_input = gr.Dropdown(
|
| 1514 |
-
# choices=["모든 카테고리", "게임", "건강", "기술", "스포츠", "엔터테인먼트", "뉴스", "비즈니스"],
|
| 1515 |
-
# value="모든 카테고리",
|
| 1516 |
-
# label="카테고리 선택",
|
| 1517 |
-
# info="관심 분야를 선택하세요"
|
| 1518 |
-
# )
|
| 1519 |
-
|
| 1520 |
-
# # 분석 버튼
|
| 1521 |
-
# analyze_btn = gr.Button(
|
| 1522 |
-
# "실시간 트렌드 분석 시작 (빠른 스트리밍 모드)",
|
| 1523 |
-
# variant="primary",
|
| 1524 |
-
# size="lg"
|
| 1525 |
-
# )
|
| 1526 |
-
|
| 1527 |
-
# # 진행 상황 및 결과 출력
|
| 1528 |
-
# output = gr.HTML(
|
| 1529 |
-
# label="실시간 분석 결과",
|
| 1530 |
-
# value="""
|
| 1531 |
-
# <div style="text-align: center; padding: 20px; border: 2px dashed #ccc; border-radius: 10px; color: #666;">
|
| 1532 |
-
# <h3>분석 대기 중</h3>
|
| 1533 |
-
# <p>위의 설정을 선택하고 '실시간 트렌드 분석 시작' 버튼을 클릭하세요!</p>
|
| 1534 |
-
# <p style="font-size: 14px;">개선된 방식으로 <strong>15-30초</strong>만에 분석이 완료됩니다.</p>
|
| 1535 |
-
# </div>
|
| 1536 |
-
# """
|
| 1537 |
-
# )
|
| 1538 |
-
|
| 1539 |
-
# # 이벤트 연결 (Generator 함수로 실시간 스트리밍)
|
| 1540 |
-
# analyze_btn.click(
|
| 1541 |
-
# fn=main_analysis,
|
| 1542 |
-
# inputs=[region_input, period_input, category_input],
|
| 1543 |
-
# outputs=output,
|
| 1544 |
-
# show_progress="hidden" # 내장 진행률 표시 숨김 (자체 스트리밍 사용)
|
| 1545 |
-
# )
|
| 1546 |
-
|
| 1547 |
-
# # 사용법 안내
|
| 1548 |
-
# gr.HTML("""
|
| 1549 |
-
# <div style="margin-top: 30px; padding: 20px; background: linear-gradient(135deg, #a8edea 0%, #fed6e3 100%); border-radius: 10px;">
|
| 1550 |
-
# <h3 style="margin-top: 0; color: #333;"> 새로운 기능!</h3>
|
| 1551 |
-
# <div style="display: grid; grid-template-columns: 1fr 1fr; gap: 20px; color: #555;">
|
| 1552 |
-
# <div>
|
| 1553 |
-
# <h4> 실시간 스트리밍</h4>
|
| 1554 |
-
# <ul style="margin: 0; padding-left: 20px;">
|
| 1555 |
-
# <li>브라우저 실행 상태 실시간 표시</li>
|
| 1556 |
-
# <li>설정 변경 과정 단계별 확인</li>
|
| 1557 |
-
# <li>AI 분석 진행상황 표시</li>
|
| 1558 |
-
# </ul>
|
| 1559 |
-
# </div>
|
| 1560 |
-
# <div>
|
| 1561 |
-
# <h4> 속도 최적화</h4>
|
| 1562 |
-
# <ul style="margin: 0; padding-left: 20px;">
|
| 1563 |
-
# <li>대기 시간 단축 </li>
|
| 1564 |
-
# <li>불필요한 로딩 시간 제거</li>
|
| 1565 |
-
# <li>효율적인 데이터 처리</li>
|
| 1566 |
-
# </ul>
|
| 1567 |
-
# </div>
|
| 1568 |
-
# </div>
|
| 1569 |
-
# </div>
|
| 1570 |
-
# """)
|
| 1571 |
-
|
| 1572 |
-
# # footer
|
| 1573 |
-
# gr.HTML("""
|
| 1574 |
-
# <div style="text-align: center; margin-top: 20px; padding: 15px; color: #666; border-top: 1px solid #eee;">
|
| 1575 |
-
# <p> <strong>사용법:</strong> 원하는 설정을 선택하고 분석 버튼을 클릭하세요</p>
|
| 1576 |
-
# <p> <strong>속도:</strong> 점차적으로 개선 예정입니다.</p>
|
| 1577 |
-
# <p> <strong>Powered by:</strong> Google Trends + Claude AI + 실시간 스트리밍</p>
|
| 1578 |
-
# </div>
|
| 1579 |
-
# """)
|
| 1580 |
-
|
| 1581 |
-
# return interface
|
| 1582 |
-
|
| 1583 |
-
# # 메인 실행
|
| 1584 |
-
# if __name__ == "__main__":
|
| 1585 |
-
# print("=" * 50)
|
| 1586 |
-
# print("Google Trends 실시간 분석기 시작!")
|
| 1587 |
-
# print("=" * 50)
|
| 1588 |
-
|
| 1589 |
-
# # API 키 확인
|
| 1590 |
-
# if not ANTHROPIC_API_KEY or ANTHROPIC_API_KEY == "your_api_key_here":
|
| 1591 |
-
# print(" ANTHROPIC_API_KEY가 설정되지 않음")
|
| 1592 |
-
# print("\n 이 상태로도 앱은 실행되지만, 분석 기능은 작동하지 않는다.")
|
| 1593 |
-
# print("=" * 50)
|
| 1594 |
-
# else:
|
| 1595 |
-
# print(" Claude API 키 확인됨")
|
| 1596 |
-
|
| 1597 |
-
# # 인터페이스 생성 및 실행
|
| 1598 |
-
# print(" Gradio ��� 인터페이스 준비 중...")
|
| 1599 |
-
# app = create_interface()
|
| 1600 |
-
|
| 1601 |
-
# # 환경별 실행 설정
|
| 1602 |
-
# if os.getenv("SPACE_ID"):
|
| 1603 |
-
# # Hugging Face Space 환경
|
| 1604 |
-
# print(" Hugging Face Space 환경에서 실행 중...")
|
| 1605 |
-
# app.launch(
|
| 1606 |
-
# server_name="0.0.0.0",
|
| 1607 |
-
# server_port=7860,
|
| 1608 |
-
# show_error=True,
|
| 1609 |
-
# show_api=False
|
| 1610 |
-
# )
|
| 1611 |
-
# else:
|
| 1612 |
-
# # 로컬 환경
|
| 1613 |
-
# print(" 로컬 서버 시작 중...")
|
| 1614 |
-
# print(" 브라우저에서 http://localhost:7860 으로 접속")
|
| 1615 |
-
# print(" 종료하려면 Ctrl+C")
|
| 1616 |
-
# print("=" * 50)
|
| 1617 |
-
|
| 1618 |
-
# try:
|
| 1619 |
-
# app.launch(
|
| 1620 |
-
# server_name="127.0.0.1",
|
| 1621 |
-
# server_port=7860,
|
| 1622 |
-
# show_error=True,
|
| 1623 |
-
# show_api=False,
|
| 1624 |
-
# share=False, # 로컬에서는 공개 링크 비활성화
|
| 1625 |
-
# inbrowser=True, # 자동으로 브라우저 열기
|
| 1626 |
-
# quiet=False # 상세 로그 표시
|
| 1627 |
-
# )
|
| 1628 |
-
# except KeyboardInterrupt:
|
| 1629 |
-
# print("\n\nGoogle Trends 분석기가 종료")
|
| 1630 |
-
# print("감사합니다! ")
|
| 1631 |
-
# except Exception as e:
|
| 1632 |
-
# print(f"\n 서버 실행 중 오류: {e}")
|
| 1633 |
-
# print("포트 7860이 이미 사용 중인지 확인")
|
|
|
|
| 3 |
import base64
|
| 4 |
import json
|
| 5 |
import traceback
|
| 6 |
+
import threading
|
| 7 |
from typing import Tuple, Optional
|
| 8 |
import gradio as gr
|
| 9 |
import anthropic
|
| 10 |
+
from selenium import webdriver
|
| 11 |
+
from selenium.webdriver.chrome.options import Options
|
| 12 |
+
from selenium.webdriver.common.by import By
|
| 13 |
+
from selenium.webdriver.support.ui import WebDriverWait
|
| 14 |
+
from selenium.webdriver.support import expected_conditions as EC
|
| 15 |
+
from selenium.common.exceptions import TimeoutException, NoSuchElementException, WebDriverException
|
| 16 |
from concurrent.futures import ThreadPoolExecutor
|
| 17 |
+
from datetime import datetime
|
| 18 |
|
| 19 |
# Hugging Face Space 환경 확인
|
| 20 |
IS_HUGGINGFACE = os.getenv("SPACE_ID") is not None
|
| 21 |
print(f'IS_HUGGINGFACE = {IS_HUGGINGFACE}')
|
| 22 |
|
| 23 |
+
# Claude API 설정
|
| 24 |
ANTHROPIC_API_KEY = os.getenv("ANTHROPIC_API_KEY")
|
| 25 |
|
| 26 |
if not ANTHROPIC_API_KEY:
|
|
|
|
| 28 |
else:
|
| 29 |
print("Claude API 키 확인 완료")
|
| 30 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 31 |
def create_claude_client():
|
| 32 |
try:
|
| 33 |
client = anthropic.Anthropic(api_key=ANTHROPIC_API_KEY)
|
|
|
|
| 37 |
print(f"Claude API 클라이언트 생성 실패: {e}")
|
| 38 |
return None
|
| 39 |
|
| 40 |
+
class PersistentGoogleTrendsAutomator:
|
| 41 |
+
"""브라우저를 계속 유지하는 Google Trends 자동화 클래스"""
|
| 42 |
+
|
| 43 |
+
_instance = None
|
| 44 |
+
_lock = threading.Lock()
|
| 45 |
+
|
| 46 |
+
def __new__(cls):
|
| 47 |
+
if cls._instance is None:
|
| 48 |
+
with cls._lock:
|
| 49 |
+
if cls._instance is None:
|
| 50 |
+
cls._instance = super(PersistentGoogleTrendsAutomator, cls).__new__(cls)
|
| 51 |
+
cls._instance._initialized = False
|
| 52 |
+
return cls._instance
|
| 53 |
+
|
| 54 |
def __init__(self):
|
| 55 |
+
if not self._initialized:
|
| 56 |
+
self.driver = None
|
| 57 |
+
self.is_browser_ready = False
|
| 58 |
+
self.last_used = time.time()
|
| 59 |
+
self.browser_lock = threading.Lock()
|
| 60 |
+
self.initialization_lock = threading.Lock()
|
| 61 |
+
self._initialized = True
|
| 62 |
+
print("PersistentGoogleTrendsAutomator 싱글톤 인스턴스 생성")
|
| 63 |
+
|
| 64 |
+
def setup_driver(self):
|
| 65 |
+
"""브라우저 드라이버 설정 (최초 1회만)"""
|
| 66 |
+
with self.initialization_lock:
|
| 67 |
+
if self.driver is not None and self.is_browser_ready:
|
| 68 |
+
print("기존 브라우저 재사용")
|
| 69 |
+
return True
|
| 70 |
+
|
| 71 |
+
print("새 브라우저 인스턴스 생성 중...")
|
| 72 |
+
|
| 73 |
+
options = Options()
|
| 74 |
+
|
| 75 |
+
# Hugging Face Space 환경 설정
|
| 76 |
+
if IS_HUGGINGFACE:
|
| 77 |
+
print("Hugging Face Space 환경, 헤드리스 모드")
|
| 78 |
+
options.add_argument("--headless=new")
|
| 79 |
+
options.add_argument("--no-sandbox")
|
| 80 |
+
options.add_argument("--disable-dev-shm-usage")
|
| 81 |
+
options.add_argument("--disable-gpu")
|
| 82 |
+
options.add_argument("--disable-software-rasterizer")
|
| 83 |
+
options.add_argument("--remote-debugging-port=9222")
|
| 84 |
+
else:
|
| 85 |
+
options.add_argument("--headless")
|
| 86 |
+
|
| 87 |
+
# 성능 최적화 설정
|
| 88 |
+
options.add_argument("--window-size=1280,720")
|
| 89 |
+
options.add_argument("--disable-blink-features=AutomationControlled")
|
| 90 |
+
options.add_argument("--disable-extensions")
|
| 91 |
+
options.add_argument("--disable-web-security")
|
| 92 |
+
options.add_argument("--allow-running-insecure-content")
|
| 93 |
+
options.add_argument("--disable-background-timer-throttling")
|
| 94 |
+
options.add_argument("--disable-backgrounding-occluded-windows")
|
| 95 |
+
options.add_argument("--disable-renderer-backgrounding")
|
| 96 |
+
options.add_argument("--disable-features=TranslateUI")
|
| 97 |
+
options.add_argument("--disable-ipc-flooding-protection")
|
| 98 |
+
|
| 99 |
+
# 네트워크 최적화
|
| 100 |
+
options.add_argument("--aggressive-cache-discard")
|
| 101 |
+
options.add_argument("--disable-background-networking")
|
| 102 |
+
|
| 103 |
+
# 메모리 최적화
|
| 104 |
+
options.add_argument("--memory-pressure-off")
|
| 105 |
+
options.add_argument("--max_old_space_size=2048")
|
| 106 |
+
|
| 107 |
+
# 이미지/CSS 비활성화
|
| 108 |
+
prefs = {
|
| 109 |
+
"profile.managed_default_content_settings.images": 2,
|
| 110 |
+
"profile.default_content_setting_values.notifications": 2,
|
| 111 |
+
}
|
| 112 |
+
options.add_experimental_option("prefs", prefs)
|
| 113 |
+
|
| 114 |
+
# 봇 감지 회피
|
| 115 |
+
options.add_argument("--user-agent=Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/120.0.0.0 Safari/537.36")
|
| 116 |
+
options.add_experimental_option("excludeSwitches", ["enable-automation"])
|
| 117 |
+
options.add_experimental_option('useAutomationExtension', False)
|
| 118 |
+
|
| 119 |
+
# 언어 설정
|
| 120 |
+
options.add_argument("--lang=ko")
|
| 121 |
+
options.add_argument("--accept-lang=ko-KR,ko;q=0.9,en;q=0.8")
|
| 122 |
+
|
| 123 |
+
try:
|
| 124 |
+
# 드라이버 생성
|
| 125 |
+
if IS_HUGGINGFACE:
|
| 126 |
+
try:
|
| 127 |
+
from webdriver_manager.chrome import ChromeDriverManager
|
| 128 |
+
from selenium.webdriver.chrome.service import Service
|
| 129 |
+
|
| 130 |
+
service = Service(ChromeDriverManager().install())
|
| 131 |
+
self.driver = webdriver.Chrome(service=service, options=options)
|
| 132 |
+
print("ChromeDriver 자동 설치 성공")
|
| 133 |
+
except Exception as e:
|
| 134 |
+
print(f"webdriver-manager 실패: {e}")
|
| 135 |
+
self.driver = webdriver.Chrome(options=options)
|
| 136 |
+
print("시스템 ChromeDriver 사용")
|
| 137 |
+
else:
|
| 138 |
+
try:
|
| 139 |
+
from webdriver_manager.chrome import ChromeDriverManager
|
| 140 |
+
from selenium.webdriver.chrome.service import Service
|
| 141 |
+
|
| 142 |
+
service = Service(ChromeDriverManager().install())
|
| 143 |
+
self.driver = webdriver.Chrome(service=service, options=options)
|
| 144 |
+
except:
|
| 145 |
+
self.driver = webdriver.Chrome(options=options)
|
| 146 |
+
|
| 147 |
+
# 타임아웃 설정
|
| 148 |
+
self.driver.set_page_load_timeout(20)
|
| 149 |
+
self.driver.implicitly_wait(3)
|
| 150 |
+
|
| 151 |
+
# Google Trends 페이지 최초 로딩
|
| 152 |
+
print("Google Trends 페이지 최초 로딩 중...")
|
| 153 |
+
self.driver.get("https://trends.google.com/trending?geo=KR&hl=ko")
|
| 154 |
+
|
| 155 |
+
# 페이지 로딩 완료 대기
|
| 156 |
+
WebDriverWait(self.driver, 10).until(
|
| 157 |
+
EC.presence_of_element_located((By.TAG_NAME, "body"))
|
| 158 |
+
)
|
| 159 |
+
|
| 160 |
+
# 봇 감지 방지 스크립트
|
| 161 |
+
try:
|
| 162 |
+
self.driver.execute_script("""
|
| 163 |
+
Object.defineProperty(navigator, 'webdriver', {get: () => undefined});
|
| 164 |
+
Object.defineProperty(navigator, 'plugins', {get: () => [1, 2, 3, 4, 5]});
|
| 165 |
+
Object.defineProperty(navigator, 'languages', {get: () => ['ko-KR', 'ko', 'en']});
|
| 166 |
+
""")
|
| 167 |
+
except Exception as script_error:
|
| 168 |
+
print(f"봇 감지 방지 스크립트 실패 (무시): {script_error}")
|
| 169 |
+
|
| 170 |
+
self.is_browser_ready = True
|
| 171 |
+
self.last_used = time.time()
|
| 172 |
+
print("브라우저 초기화 완료 및 페이지 로딩 성공")
|
| 173 |
+
return True
|
| 174 |
+
|
| 175 |
+
except Exception as e:
|
| 176 |
+
print(f"드라이버 설정 실패: {e}")
|
| 177 |
+
self.cleanup_driver()
|
| 178 |
+
return False
|
| 179 |
+
|
| 180 |
+
def cleanup_driver(self):
|
| 181 |
+
"""브라우저 정리"""
|
| 182 |
+
try:
|
| 183 |
+
if self.driver:
|
| 184 |
+
self.driver.quit()
|
| 185 |
+
print("브라우저 종료")
|
| 186 |
+
except:
|
| 187 |
+
pass
|
| 188 |
+
finally:
|
| 189 |
+
self.driver = None
|
| 190 |
+
self.is_browser_ready = False
|
| 191 |
|
| 192 |
+
def check_browser_health(self):
|
| 193 |
+
"""브라우저 상태 확인 및 필요시 복구"""
|
| 194 |
try:
|
| 195 |
+
if not self.driver:
|
| 196 |
+
return False
|
| 197 |
|
| 198 |
+
# 간단한 상태 체크
|
| 199 |
+
current_url = self.driver.current_url
|
| 200 |
+
if "trends.google.com" not in current_url:
|
| 201 |
+
print("브라우저가 잘못된 페이지에 있음, 복구 중...")
|
| 202 |
+
self.driver.get("https://trends.google.com/trending?geo=KR&hl=ko")
|
| 203 |
+
time.sleep(2)
|
| 204 |
|
| 205 |
+
return True
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 206 |
|
| 207 |
+
except WebDriverException as e:
|
| 208 |
+
print(f"브라우저 상태 확인 실패: {e}")
|
| 209 |
+
return False
|
| 210 |
+
|
| 211 |
+
def refresh_and_wait(self):
|
| 212 |
+
"""페이지 새로고침 및 대기 (빠른 데이터 갱신)"""
|
| 213 |
+
try:
|
| 214 |
+
print("페이지 새로고침으로 최신 데이터 갱신...")
|
| 215 |
+
self.driver.refresh()
|
| 216 |
|
| 217 |
+
# 최소한의 로딩 대기
|
| 218 |
+
time.sleep(2)
|
| 219 |
|
| 220 |
+
# 페이지 준비 확인
|
| 221 |
+
WebDriverWait(self.driver, 5).until(
|
| 222 |
+
EC.presence_of_element_located((By.TAG_NAME, "button"))
|
| 223 |
+
)
|
| 224 |
|
|
|
|
| 225 |
return True
|
| 226 |
|
| 227 |
except Exception as e:
|
| 228 |
+
print(f"페이지 새로고침 실패: {e}")
|
| 229 |
return False
|
| 230 |
|
| 231 |
+
def safe_find_element(self, selectors: list, timeout: int = 3):
|
| 232 |
+
"""안전한 요소 찾기"""
|
| 233 |
+
for selector_type, selector in selectors:
|
| 234 |
try:
|
| 235 |
+
if selector_type == "xpath":
|
| 236 |
+
element = WebDriverWait(self.driver, timeout).until(
|
| 237 |
+
EC.presence_of_element_located((By.XPATH, selector))
|
| 238 |
+
)
|
| 239 |
+
elif selector_type == "css":
|
| 240 |
+
element = WebDriverWait(self.driver, timeout).until(
|
| 241 |
+
EC.presence_of_element_located((By.CSS_SELECTOR, selector))
|
| 242 |
+
)
|
| 243 |
+
elif selector_type == "text":
|
| 244 |
+
element = WebDriverWait(self.driver, timeout).until(
|
| 245 |
+
EC.presence_of_element_located((By.XPATH, f"//*[contains(text(), '{selector}')]"))
|
| 246 |
+
)
|
| 247 |
+
|
| 248 |
+
if element:
|
| 249 |
+
return element
|
| 250 |
except:
|
| 251 |
continue
|
| 252 |
+
return None
|
| 253 |
+
|
| 254 |
+
def safe_click(self, selectors: list, timeout: int = 3) -> bool:
|
| 255 |
+
"""안전한 클릭"""
|
| 256 |
+
element = self.safe_find_element(selectors, timeout)
|
| 257 |
+
if element:
|
| 258 |
+
try:
|
| 259 |
+
self.driver.execute_script("arguments[0].click();", element)
|
| 260 |
+
return True
|
| 261 |
+
except:
|
| 262 |
+
try:
|
| 263 |
+
element.click()
|
| 264 |
+
return True
|
| 265 |
+
except:
|
| 266 |
+
return False
|
| 267 |
return False
|
| 268 |
|
| 269 |
+
def change_settings_fast(self, region: str, period: str, category: str, progress_callback=None) -> dict:
|
| 270 |
+
"""빠른 설정 변경 (기존 브라우저 활용)"""
|
| 271 |
+
results = {
|
| 272 |
+
'region': False,
|
| 273 |
+
'period': False,
|
| 274 |
+
'category': False,
|
| 275 |
+
'errors': []
|
| 276 |
+
}
|
| 277 |
+
|
| 278 |
+
try:
|
| 279 |
+
# 설정 변경 전 페이지 새로고침으로 최신 상태 확보
|
| 280 |
+
self.refresh_and_wait()
|
| 281 |
+
|
| 282 |
+
if region != "대한민국":
|
| 283 |
+
if progress_callback:
|
| 284 |
+
progress_callback(f"지역을 {region}으로 변경 중...")
|
| 285 |
+
results['region'] = self.change_region(region)
|
| 286 |
+
time.sleep(0.5)
|
| 287 |
+
else:
|
| 288 |
+
results['region'] = True
|
| 289 |
+
|
| 290 |
+
if period != "지난 24시간":
|
| 291 |
+
if progress_callback:
|
| 292 |
+
progress_callback(f"기간을 {period}로 변경 중...")
|
| 293 |
+
results['period'] = self.change_time_period(period)
|
| 294 |
+
time.sleep(0.5)
|
| 295 |
+
else:
|
| 296 |
+
results['period'] = True
|
| 297 |
+
|
| 298 |
+
if category != "모든 카테고리":
|
| 299 |
+
if progress_callback:
|
| 300 |
+
progress_callback(f"카테고리를 {category}로 변경 중...")
|
| 301 |
+
results['category'] = self.change_category(category)
|
| 302 |
+
time.sleep(0.5)
|
| 303 |
+
else:
|
| 304 |
+
results['category'] = True
|
| 305 |
+
|
| 306 |
+
except Exception as e:
|
| 307 |
+
results['errors'].append(str(e))
|
| 308 |
+
|
| 309 |
+
return results
|
| 310 |
+
|
| 311 |
+
def change_region(self, target_region: str) -> bool:
|
| 312 |
+
"""지역 변경"""
|
| 313 |
try:
|
| 314 |
region_selectors = [
|
| 315 |
+
("xpath", "//button[@aria-label='대한민국, 위치 선택']"),
|
| 316 |
+
("xpath", "//button[contains(@aria-label, '위치 선택')]"),
|
| 317 |
+
("xpath", "//span[contains(text(), '대한민국')]//parent::button"),
|
| 318 |
]
|
| 319 |
|
| 320 |
+
if not self.safe_click(region_selectors):
|
| 321 |
return False
|
| 322 |
|
| 323 |
+
time.sleep(1)
|
| 324 |
|
| 325 |
region_mapping = {
|
| 326 |
"전세계": ["전 세계", "Worldwide"],
|
|
|
|
| 332 |
if target_region in region_mapping:
|
| 333 |
for region_text in region_mapping[target_region]:
|
| 334 |
region_option_selectors = [
|
| 335 |
+
("xpath", f"//span[contains(text(), '{region_text}')]"),
|
| 336 |
+
("xpath", f"//*[contains(text(), '{region_text}')]"),
|
|
|
|
| 337 |
]
|
| 338 |
|
| 339 |
+
if self.safe_click(region_option_selectors, timeout=2):
|
| 340 |
return True
|
| 341 |
|
| 342 |
return False
|
|
|
|
| 345 |
print(f"지역 변경 실패: {e}")
|
| 346 |
return False
|
| 347 |
|
| 348 |
+
def change_time_period(self, target_period: str) -> bool:
|
| 349 |
+
"""기간 변경"""
|
| 350 |
try:
|
| 351 |
period_selectors = [
|
| 352 |
+
("xpath", "//button[contains(@aria-label, '기간 선택')]"),
|
| 353 |
+
("xpath", "//span[contains(text(), '지난 24시간')]//parent::button"),
|
| 354 |
]
|
| 355 |
|
| 356 |
+
if not self.safe_click(period_selectors):
|
| 357 |
return False
|
| 358 |
|
| 359 |
+
time.sleep(1)
|
| 360 |
|
| 361 |
period_mapping = {
|
| 362 |
"지난 1시간": ["지난 1시간"],
|
|
|
|
| 368 |
if target_period in period_mapping:
|
| 369 |
for period_text in period_mapping[target_period]:
|
| 370 |
period_option_selectors = [
|
| 371 |
+
("xpath", f"//span[contains(text(), '{period_text}')]"),
|
| 372 |
+
("xpath", f"//*[contains(text(), '{period_text}')]"),
|
|
|
|
| 373 |
]
|
| 374 |
|
| 375 |
+
if self.safe_click(period_option_selectors, timeout=2):
|
| 376 |
return True
|
| 377 |
|
| 378 |
return False
|
|
|
|
| 381 |
print(f"기간 변경 실패: {e}")
|
| 382 |
return False
|
| 383 |
|
| 384 |
+
def change_category(self, target_category: str) -> bool:
|
| 385 |
+
"""카테고리 변경"""
|
| 386 |
try:
|
| 387 |
category_selectors = [
|
| 388 |
+
("xpath", "//button[contains(@aria-label, '카테고리 선택')]"),
|
| 389 |
+
("xpath", "//span[contains(text(), '모든 카테고리')]//parent::button"),
|
| 390 |
]
|
| 391 |
|
| 392 |
+
if not self.safe_click(category_selectors):
|
| 393 |
return False
|
| 394 |
|
| 395 |
+
time.sleep(1)
|
| 396 |
|
| 397 |
category_mapping = {
|
| 398 |
"게임": ["게임"],
|
|
|
|
| 407 |
if target_category in category_mapping:
|
| 408 |
for category_text in category_mapping[target_category]:
|
| 409 |
category_option_selectors = [
|
| 410 |
+
("xpath", f"//span[contains(text(), '{category_text}')]"),
|
| 411 |
+
("xpath", f"//*[contains(text(), '{category_text}')]"),
|
|
|
|
| 412 |
]
|
| 413 |
|
| 414 |
+
if self.safe_click(category_option_selectors, timeout=2):
|
| 415 |
return True
|
| 416 |
|
| 417 |
return False
|
|
|
|
| 420 |
print(f"카테고리 변경 실패: {e}")
|
| 421 |
return False
|
| 422 |
|
| 423 |
+
def capture_trends_fast(self, region: str, period: str, category: str, progress_callback=None) -> Tuple[Optional[str], bool, str]:
|
| 424 |
+
"""빠른 트렌드 캡처 (브라우저 재사용)"""
|
|
|
|
| 425 |
|
| 426 |
+
with self.browser_lock: # 동시 접근 방지
|
| 427 |
+
error_msg = ""
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 428 |
|
|
|
|
| 429 |
try:
|
| 430 |
+
# 브라우저 상태 확인
|
| 431 |
+
if not self.is_browser_ready or not self.check_browser_health():
|
| 432 |
+
if progress_callback:
|
| 433 |
+
progress_callback("브라우저 초기화 중... (최초 실행시만)")
|
| 434 |
+
|
| 435 |
+
if not self.setup_driver():
|
| 436 |
+
return None, False, "브라우저 드라이버 설정 실패"
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 437 |
else:
|
| 438 |
+
if progress_callback:
|
| 439 |
+
progress_callback("기존 브라우저 재사용 중...")
|
| 440 |
+
|
| 441 |
+
# 설정 변경
|
| 442 |
if progress_callback:
|
| 443 |
+
progress_callback("설정 변경 및 데이터 갱신 중...")
|
| 444 |
+
|
| 445 |
+
settings_result = self.change_settings_fast(region, period, category, progress_callback)
|
| 446 |
+
|
| 447 |
+
# 결과 확인
|
| 448 |
+
changes_made = []
|
| 449 |
+
if settings_result['region']:
|
| 450 |
+
changes_made.append(f"지역: {region}")
|
| 451 |
+
if settings_result['period']:
|
| 452 |
changes_made.append(f"기간: {period}")
|
| 453 |
+
if settings_result['category']:
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 454 |
changes_made.append(f"카테고리: {category}")
|
| 455 |
+
|
| 456 |
+
if settings_result['errors']:
|
| 457 |
+
error_msg = "\n".join(settings_result['errors'])
|
| 458 |
+
|
| 459 |
+
if progress_callback:
|
| 460 |
+
progress_callback("최신 데이터 로딩 완료, 스크린샷 캡처 중...")
|
| 461 |
+
|
| 462 |
+
# 최종 데이터 로딩 대기
|
| 463 |
+
time.sleep(1)
|
| 464 |
+
|
| 465 |
+
# 스크린샷 촬영
|
| 466 |
+
screenshot = self.driver.get_screenshot_as_png()
|
| 467 |
+
screenshot_b64 = base64.b64encode(screenshot).decode()
|
| 468 |
+
|
| 469 |
+
# 사용 시간 업데이트
|
| 470 |
+
self.last_used = time.time()
|
| 471 |
+
|
| 472 |
+
success_msg = f"설정 완료: {', '.join(changes_made) if changes_made else '기본 설정 사용'}"
|
| 473 |
+
|
| 474 |
+
return screenshot_b64, True, success_msg + ("\n" + error_msg if error_msg else "")
|
| 475 |
+
|
| 476 |
+
except Exception as e:
|
| 477 |
+
error_msg = f"오류 발생: {str(e)}"
|
| 478 |
+
# 오류 발생시 브라우저 재시작 시도
|
| 479 |
+
print(f"오류로 인한 브라우저 재시작: {e}")
|
| 480 |
+
self.cleanup_driver()
|
| 481 |
+
return None, False, error_msg
|
| 482 |
+
|
| 483 |
+
# 글로벌 자동화 인스턴스 (싱글톤)
|
| 484 |
+
automator_instance = None
|
| 485 |
+
|
| 486 |
+
def get_automator():
|
| 487 |
+
"""자동화 인스턴스 가져오기"""
|
| 488 |
+
global automator_instance
|
| 489 |
+
if automator_instance is None:
|
| 490 |
+
automator_instance = PersistentGoogleTrendsAutomator()
|
| 491 |
+
return automator_instance
|
| 492 |
|
|
|
|
| 493 |
def analyze_with_claude(screenshot_b64: str, region: str, period: str, category: str) -> str:
|
| 494 |
+
"""Claude API로 스크린샷 분석"""
|
| 495 |
try:
|
|
|
|
| 496 |
if not ANTHROPIC_API_KEY or ANTHROPIC_API_KEY == "your_api_key_here":
|
| 497 |
return """
|
| 498 |
<div style="color: red; padding: 20px; border: 1px solid red; border-radius: 5px;">
|
| 499 |
<h3>API 키 오류</h3>
|
| 500 |
<p><strong>ANTHROPIC_API_KEY가 설정되지 않았습니다!</strong></p>
|
|
|
|
| 501 |
</div>
|
| 502 |
"""
|
| 503 |
|
|
|
|
| 504 |
claude_client = create_claude_client()
|
| 505 |
|
| 506 |
if claude_client is None:
|
|
|
|
| 511 |
</div>
|
| 512 |
"""
|
| 513 |
|
|
|
|
| 514 |
prompt = f"""
|
| 515 |
이 Google Trends 스크린샷을 분석해주세요.
|
| 516 |
설정: {region} | {period} | {category}
|
|
|
|
| 520 |
2. 주요 트렌드 키워드 3-5개의 특징 설명
|
| 521 |
3. 카테고리별 특이사항 (있는 경우)
|
| 522 |
|
| 523 |
+
HTML 형태로 깔끔하게 정리하고, 시각적으로 만들어주세요.
|
| 524 |
한글 텍스트를 정확히 읽어서 분석해주세요.
|
| 525 |
"""
|
| 526 |
|
|
|
|
| 527 |
message = claude_client.messages.create(
|
| 528 |
model="claude-3-5-sonnet-20241022",
|
| 529 |
max_tokens=1000,
|
|
|
|
| 558 |
</div>
|
| 559 |
"""
|
| 560 |
|
| 561 |
+
def persistent_browser_analysis(region: str, period: str, category: str):
|
| 562 |
+
"""브라우저 재사용 분석 함수"""
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 563 |
|
| 564 |
start_time = time.time()
|
| 565 |
|
|
|
|
| 566 |
yield f"""
|
| 567 |
<div style="text-align: center; padding: 20px; background: linear-gradient(135deg, #667eea 0%, #764ba2 100%); color: white; border-radius: 10px; margin-bottom: 20px;">
|
| 568 |
+
<h3>브라우저 재사용 Google Trends 분석</h3>
|
| 569 |
<p><strong>설정:</strong> {region} | {period} | {category}</p>
|
| 570 |
+
<p>첫 실행: 15-20초 | 이후 실행: 5-10초</p>
|
|
|
|
| 571 |
</div>
|
| 572 |
"""
|
| 573 |
|
|
|
|
| 577 |
progress_status["current"] = message
|
| 578 |
|
| 579 |
try:
|
| 580 |
+
# API 키 확인
|
| 581 |
if not ANTHROPIC_API_KEY or ANTHROPIC_API_KEY == "your_api_key_here":
|
| 582 |
yield """
|
| 583 |
+
<div style="color: orange; padding: 20px; border: 1px solid orange; border-radius: 5px;">
|
| 584 |
+
<h3>API 키 누락 - 스크린샷만 캡처</h3>
|
| 585 |
<p><strong>ANTHROPIC_API_KEY가 설정되지 않았습니다!</strong></p>
|
|
|
|
| 586 |
</div>
|
| 587 |
"""
|
|
|
|
| 588 |
|
| 589 |
+
# 자동화 인스턴스 가져오기
|
| 590 |
+
automator = get_automator()
|
| 591 |
+
|
| 592 |
+
# 첫 실행인지 확인
|
| 593 |
+
is_first_run = not automator.is_browser_ready
|
| 594 |
+
|
| 595 |
yield f"""
|
| 596 |
<div style="text-align: center; padding: 15px; background: linear-gradient(135deg, #4CAF50 0%, #45a049 100%); color: white; border-radius: 10px; margin-bottom: 15px;">
|
| 597 |
+
<h4>1단계: {"브라우저 초기화" if is_first_run else "기존 브라우저 재사용"}</h4>
|
| 598 |
+
<p>{"최초 실행이므로 브라우저를 새로 시작합니다" if is_first_run else "이미 실행 중인 브라우저를 재사용합니다"}</p>
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 599 |
</div>
|
| 600 |
"""
|
| 601 |
|
|
|
|
|
|
|
|
|
|
| 602 |
# 브라우저 작업을 별도 스레드에서 실행
|
| 603 |
with ThreadPoolExecutor(max_workers=1) as executor:
|
| 604 |
future = executor.submit(
|
| 605 |
+
automator.capture_trends_fast,
|
| 606 |
region, period, category, progress_callback
|
| 607 |
)
|
| 608 |
|
|
|
|
| 613 |
elapsed = time.time() - start_time
|
| 614 |
yield f"""
|
| 615 |
<div style="text-align: center; padding: 15px; background: linear-gradient(135deg, #4CAF50 0%, #45a049 100%); color: white; border-radius: 10px; margin-bottom: 15px;">
|
| 616 |
+
<h4>1단계: {"브라우저 초기화" if is_first_run else "기존 브라우저 재사용"}</h4>
|
| 617 |
+
<p>{current_progress}</p>
|
| 618 |
+
<p>경과 시간: {elapsed:.1f}초</p>
|
|
|
|
|
|
|
|
|
|
|
|
|
| 619 |
</div>
|
| 620 |
"""
|
| 621 |
time.sleep(0.5)
|
|
|
|
| 628 |
if not success:
|
| 629 |
yield f"""
|
| 630 |
<div style="color: red; padding: 20px; border: 1px solid red; border-radius: 5px;">
|
| 631 |
+
<h3>Google Trends 캡처 실패</h3>
|
| 632 |
<pre style="background-color: #fff5f5; padding: 15px; border-radius: 5px; margin: 15px 0;">
|
| 633 |
{status_msg}
|
| 634 |
</pre>
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 635 |
</div>
|
| 636 |
"""
|
| 637 |
return
|
| 638 |
|
| 639 |
+
# 2단계: AI 분석
|
| 640 |
yield f"""
|
| 641 |
<div style="text-align: center; padding: 15px; background: linear-gradient(135deg, #4CAF50 0%, #45a049 100%); color: white; border-radius: 10px; margin-bottom: 15px;">
|
| 642 |
+
<h4>1단계 완료: 스크린샷 캡처 성공 ({browser_time:.1f}초)</h4>
|
| 643 |
+
<p>{status_msg}</p>
|
| 644 |
</div>
|
| 645 |
|
| 646 |
<div style="text-align: center; padding: 15px; background: linear-gradient(135deg, #FF6B6B 0%, #FF8E8E 100%); color: white; border-radius: 10px; margin-bottom: 15px;">
|
| 647 |
+
<h4>2단계: Claude AI 분석 중...</h4>
|
| 648 |
+
<p>트렌드 데이터를 분석하고 있습니다</p>
|
|
|
|
| 649 |
</div>
|
| 650 |
"""
|
| 651 |
|
| 652 |
+
# AI 분석 실행
|
| 653 |
+
ai_start_time = time.time()
|
| 654 |
+
|
| 655 |
+
with ThreadPoolExecutor(max_workers=1) as executor:
|
| 656 |
+
ai_future = executor.submit(
|
| 657 |
+
analyze_with_claude,
|
| 658 |
+
screenshot_b64, region, period, category
|
| 659 |
+
)
|
| 660 |
+
|
| 661 |
+
while not ai_future.done():
|
| 662 |
+
ai_elapsed = time.time() - ai_start_time
|
| 663 |
+
total_elapsed = time.time() - start_time
|
| 664 |
+
yield f"""
|
| 665 |
+
<div style="text-align: center; padding: 15px; background: linear-gradient(135deg, #4CAF50 0%, #45a049 100%); color: white; border-radius: 10px; margin-bottom: 15px;">
|
| 666 |
+
<h4>1단계 완료: 스크린샷 캡처 성공 ({browser_time:.1f}초)</h4>
|
| 667 |
+
<p>{status_msg}</p>
|
| 668 |
+
</div>
|
| 669 |
+
|
| 670 |
+
<div style="text-align: center; padding: 15px; background: linear-gradient(135deg, #FF6B6B 0%, #FF8E8E 100%); color: white; border-radius: 10px; margin-bottom: 15px;">
|
| 671 |
+
<h4>2단계: Claude AI 분석 중... ({ai_elapsed:.1f}초)</h4>
|
| 672 |
+
<p>총 경과 시간: {total_elapsed:.1f}초</p>
|
| 673 |
+
</div>
|
| 674 |
+
"""
|
| 675 |
+
time.sleep(0.5)
|
| 676 |
+
|
| 677 |
+
analysis_result = ai_future.result()
|
| 678 |
|
| 679 |
total_time = time.time() - start_time
|
| 680 |
|
| 681 |
# 최종 결과
|
| 682 |
yield f"""
|
| 683 |
<div style="text-align: center; padding: 15px; background: linear-gradient(135deg, #4CAF50 0%, #45a049 100%); color: white; border-radius: 10px; margin-bottom: 20px;">
|
| 684 |
+
<h3>분석 완료 ({total_time:.1f}초)</h3>
|
| 685 |
+
<p><strong>성능:</strong> {"첫 실행" if is_first_run else "브라우저 재사용"} | <strong>설정:</strong> {region} | {period} | {category}</p>
|
|
|
|
| 686 |
</div>
|
| 687 |
|
| 688 |
{analysis_result}
|
| 689 |
|
| 690 |
<div style="margin-top: 20px; padding: 15px; background: linear-gradient(135deg, #667eea 0%, #764ba2 100%); color: white; border-radius: 10px; text-align: center;">
|
| 691 |
<p style="margin: 0; font-size: 14px;">
|
| 692 |
+
<strong>다음 분석은 더욱 빠릅니다!</strong><br>
|
| 693 |
+
브라우저가 이미 실행 중이므로 5-10초만에 완료됩니다
|
| 694 |
</p>
|
| 695 |
</div>
|
| 696 |
|
| 697 |
<div style="margin-top: 15px; padding: 10px; background-color: #f9f9f9; border-radius: 5px; font-size: 12px; color: #666; text-align: center;">
|
| 698 |
+
<p style="margin: 5px 0;"><strong>브라우저 상태:</strong> {"새로 시작됨" if is_first_run else "재사용됨"}</p>
|
| 699 |
+
<p style="margin: 5px 0;"><strong>분석 시간:</strong> {total_time:.1f}초</p>
|
| 700 |
+
<p style="margin: 5px 0;"><strong>다음 예상 시간:</strong> 5-10초</p>
|
| 701 |
</div>
|
| 702 |
"""
|
| 703 |
|
| 704 |
+
print(f"브라우저 재사용 분석 완료: {total_time:.1f}초")
|
| 705 |
|
| 706 |
except Exception as e:
|
| 707 |
error_details = traceback.format_exc()
|
| 708 |
+
print(f"분석 중 예외 발생: {e}")
|
| 709 |
|
| 710 |
yield f"""
|
| 711 |
<div style="color: red; padding: 20px; border: 1px solid red; border-radius: 5px;">
|
| 712 |
<h3>오류 발생</h3>
|
| 713 |
<p><strong>오류:</strong> {str(e)}</p>
|
| 714 |
<details>
|
| 715 |
+
<summary>상세 오류 정보</summary>
|
| 716 |
<pre style="background-color: #f5f5f5; padding: 10px; margin-top: 10px; overflow-x: auto; font-size: 11px;">
|
| 717 |
{error_details}
|
| 718 |
</pre>
|
| 719 |
</details>
|
| 720 |
+
<p><strong>해결 방법:</strong> 페이지를 새로고침하고 다시 시도하세요.</p>
|
| 721 |
</div>
|
| 722 |
"""
|
| 723 |
|
| 724 |
+
def create_persistent_interface():
|
| 725 |
+
"""브라우저 재사용 Gradio 인터페이스"""
|
| 726 |
|
| 727 |
with gr.Blocks(
|
| 728 |
theme=gr.themes.Soft(),
|
| 729 |
+
title="브라우저 재사용 Google Trends 분석기",
|
| 730 |
css="""
|
| 731 |
.gradio-container {
|
| 732 |
max-width: 1200px !important;
|
|
|
|
| 737 |
"""
|
| 738 |
) as interface:
|
| 739 |
|
| 740 |
+
gr.HTML("""
|
|
|
|
| 741 |
<div style="text-align: center; padding: 20px; background: linear-gradient(90deg, #667eea 0%, #764ba2 100%); color: white; border-radius: 10px; margin-bottom: 20px;">
|
| 742 |
+
<h1>브라우저 재사용 Google Trends 분석기</h1>
|
| 743 |
+
<p><strong>혁신적 성능 개선:</strong> 브라우저를 계속 켜두고 재사용하여 속도 향상</p>
|
| 744 |
+
<p style="font-size: 14px; opacity: 0.9;">첫 실행: 15-20초 | 이후 실행: 5-10초</p>
|
|
|
|
| 745 |
</div>
|
| 746 |
""")
|
| 747 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 748 |
with gr.Row():
|
| 749 |
with gr.Column(scale=1):
|
| 750 |
region_input = gr.Dropdown(
|
| 751 |
choices=["대한민국", "전세계", "미국", "일본", "중국"],
|
| 752 |
value="대한민국",
|
| 753 |
+
label="지역 선택"
|
|
|
|
| 754 |
)
|
| 755 |
|
| 756 |
with gr.Column(scale=1):
|
| 757 |
period_input = gr.Dropdown(
|
| 758 |
choices=["지난 24시간", "지난 1시간", "지난 4시간", "지난 1일", "지난 7일"],
|
| 759 |
value="지난 7일",
|
| 760 |
+
label="기간 선택"
|
|
|
|
| 761 |
)
|
| 762 |
|
| 763 |
with gr.Column(scale=1):
|
| 764 |
category_input = gr.Dropdown(
|
| 765 |
choices=["모든 카테고리", "게임", "건강", "기술", "스포츠", "엔터테인먼트", "뉴스", "비즈니스"],
|
| 766 |
value="모든 카테고리",
|
| 767 |
+
label="카테고리 선택"
|
|
|
|
| 768 |
)
|
| 769 |
|
|
|
|
| 770 |
analyze_btn = gr.Button(
|
| 771 |
+
"브라우저 재사용 분석 시작",
|
| 772 |
variant="primary",
|
| 773 |
size="lg"
|
| 774 |
)
|
| 775 |
|
|
|
|
| 776 |
output = gr.HTML(
|
| 777 |
label="실시간 분석 결과",
|
| 778 |
+
value="""
|
| 779 |
<div style="text-align: center; padding: 20px; border: 2px dashed #ccc; border-radius: 10px; color: #666;">
|
| 780 |
+
<h3>브라우저 재사용 분석기 대기 중</h3>
|
| 781 |
+
<p><strong>첫 실행:</strong> 브라우저 초기화로 15-20초 소요</p>
|
| 782 |
+
<p><strong>이후 실행:</strong> 브라우저 재사용으로 5-10초 완료</p>
|
| 783 |
+
<p style="font-size: 14px;">위의 설정을 선택하고 버튼을 클릭하세요!</p>
|
| 784 |
</div>
|
| 785 |
"""
|
| 786 |
)
|
| 787 |
|
|
|
|
| 788 |
analyze_btn.click(
|
| 789 |
+
fn=persistent_browser_analysis,
|
| 790 |
inputs=[region_input, period_input, category_input],
|
| 791 |
outputs=output,
|
| 792 |
show_progress="hidden"
|
| 793 |
)
|
| 794 |
|
|
|
|
| 795 |
gr.HTML("""
|
| 796 |
<div style="margin-top: 30px; padding: 20px; background: linear-gradient(135deg, #a8edea 0%, #fed6e3 100%); border-radius: 10px;">
|
| 797 |
+
<h3 style="margin-top: 0; color: #333;">브라우저 재사용의 장점</h3>
|
| 798 |
<div style="display: grid; grid-template-columns: 1fr 1fr; gap: 20px; color: #555;">
|
| 799 |
<div>
|
| 800 |
+
<h4>성능 향상</h4>
|
| 801 |
<ul style="margin: 0; padding-left: 20px;">
|
| 802 |
+
<li>두 번째부터 8-15초 단축</li>
|
| 803 |
+
<li>브라우저 초기화 시간 제거</li>
|
| 804 |
+
<li>페이지 로딩 시간 최소화</li>
|
| 805 |
</ul>
|
| 806 |
</div>
|
| 807 |
<div>
|
| 808 |
+
<h4>자원 효율성</h4>
|
| 809 |
<ul style="margin: 0; padding-left: 20px;">
|
| 810 |
+
<li>메모리 사용량 최적화</li>
|
| 811 |
+
<li>CPU 부하 감소</li>
|
| 812 |
+
<li>안정적인 세션 유지</li>
|
| 813 |
</ul>
|
| 814 |
</div>
|
| 815 |
</div>
|
| 816 |
</div>
|
| 817 |
""")
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 818 |
|
| 819 |
return interface
|
| 820 |
|
| 821 |
+
# 앱 종료시 브라우저 정리
|
| 822 |
+
import atexit
|
| 823 |
+
|
| 824 |
+
def cleanup_on_exit():
|
| 825 |
+
"""앱 종료시 브라우저 정리"""
|
| 826 |
+
global automator_instance
|
| 827 |
+
if automator_instance:
|
| 828 |
+
automator_instance.cleanup_driver()
|
| 829 |
+
print("앱 종료: 브라우저 정리 완료")
|
| 830 |
+
|
| 831 |
+
atexit.register(cleanup_on_exit)
|
| 832 |
+
|
| 833 |
if __name__ == "__main__":
|
| 834 |
print("=" * 50)
|
| 835 |
+
print("브라우저 재사용 Google Trends 분석기 시작")
|
|
|
|
| 836 |
print("=" * 50)
|
| 837 |
|
|
|
|
| 838 |
if not ANTHROPIC_API_KEY or ANTHROPIC_API_KEY == "your_api_key_here":
|
| 839 |
+
print("ANTHROPIC_API_KEY 미설정 - 스크린샷만 캡처")
|
|
|
|
|
|
|
|
|
|
|
|
|
| 840 |
else:
|
| 841 |
print("Claude API 키 확인됨")
|
| 842 |
|
| 843 |
+
print("브라우저 재사용 Gradio 인터페이스 준비 중...")
|
| 844 |
+
app = create_persistent_interface()
|
|
|
|
| 845 |
|
|
|
|
| 846 |
if os.getenv("SPACE_ID"):
|
| 847 |
+
print("Hugging Face Space 환경에서 실행")
|
|
|
|
| 848 |
app.launch(
|
| 849 |
server_name="0.0.0.0",
|
| 850 |
server_port=7860,
|
|
|
|
| 852 |
show_api=False
|
| 853 |
)
|
| 854 |
else:
|
| 855 |
+
print("로컬 서버 시작: http://localhost:7860")
|
| 856 |
+
app.launch(
|
| 857 |
+
server_name="127.0.0.1",
|
| 858 |
+
server_port=7860,
|
| 859 |
+
show_error=True,
|
| 860 |
+
show_api=False,
|
| 861 |
+
share=False,
|
| 862 |
+
inbrowser=True
|
| 863 |
+
)
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
requirements.txt
CHANGED
|
@@ -1,5 +1,6 @@
|
|
| 1 |
gradio==4.44.0
|
| 2 |
anthropic==0.34.0
|
| 3 |
-
|
|
|
|
| 4 |
python-dotenv==1.0.0
|
| 5 |
Pillow==10.4.0
|
|
|
|
| 1 |
gradio==4.44.0
|
| 2 |
anthropic==0.34.0
|
| 3 |
+
selenium==4.15.0
|
| 4 |
+
webdriver-manager==4.0.1
|
| 5 |
python-dotenv==1.0.0
|
| 6 |
Pillow==10.4.0
|