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