openfree commited on
Commit
c09b1cf
β€’
1 Parent(s): 09f2264

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +40 -20
app.py CHANGED
@@ -18,14 +18,16 @@ from pathlib import Path
18
  CACHE_DIR = Path("screenshot_cache")
19
  CACHE_DIR.mkdir(exist_ok=True)
20
 
21
- def get_cached_screenshot(url: str) -> str:
22
- """μΊμ‹œλœ μŠ€ν¬λ¦°μƒ· κ°€μ Έμ˜€κΈ° λ˜λŠ” μƒˆλ‘œ 생성"""
23
- cache_file = CACHE_DIR / f"{base64.b64encode(url.encode()).decode()}.png"
24
-
25
- if cache_file.exists():
26
- with open(cache_file, "rb") as f:
27
- return base64.b64encode(f.read()).decode()
28
-
 
 
29
  options = webdriver.ChromeOptions()
30
  options.add_argument('--headless')
31
  options.add_argument('--no-sandbox')
@@ -35,18 +37,37 @@ def get_cached_screenshot(url: str) -> str:
35
  try:
36
  driver = webdriver.Chrome(options=options)
37
  driver.get(url)
38
- WebDriverWait(driver, 10).until(
39
- EC.presence_of_element_located((By.TAG_NAME, "body"))
40
- )
 
 
 
 
 
 
 
 
 
 
 
 
 
41
  screenshot = driver.get_screenshot_as_png()
 
 
 
 
42
 
43
- # μΊμ‹œ 파일 μ €μž₯
44
- with open(cache_file, "wb") as f:
45
- f.write(screenshot)
46
-
47
- return base64.b64encode(screenshot).decode()
 
 
48
  except Exception as e:
49
- print(f"Screenshot error for {url}: {str(e)}")
50
  return None
51
  finally:
52
  if 'driver' in locals():
@@ -109,8 +130,7 @@ def get_trending_spaces(progress=gr.Progress()) -> Tuple[str, str]:
109
  response.raise_for_status()
110
  spaces = response.json()
111
 
112
- # μ’‹μ•„μš” 수둜 μ •λ ¬ν•˜κ³  μƒμœ„ 10개만 선택
113
- spaces.sort(key=lambda x: x.get('likes', 0), reverse=True)
114
  top_spaces = spaces[:10]
115
 
116
  progress(0.1, desc="Creating gallery...")
@@ -125,7 +145,7 @@ def get_trending_spaces(progress=gr.Progress()) -> Tuple[str, str]:
125
  likes = format(space.get('likes', 0), ',')
126
  created = space.get('createdAt', '').split('T')[0]
127
 
128
- screenshot = get_cached_screenshot(space_url)
129
  bg_color = f"rgba({random.randint(230,255)}, {random.randint(230,255)}, {random.randint(230,255)}, 0.8)"
130
 
131
  html_content += f"""
 
18
  CACHE_DIR = Path("screenshot_cache")
19
  CACHE_DIR.mkdir(exist_ok=True)
20
 
21
+ import time # time.sleep() μ‚¬μš©μ„ μœ„ν•΄ μΆ”κ°€
22
+
23
+ def take_screenshot(url):
24
+ """μ›Ήμ‚¬μ΄νŠΈ μŠ€ν¬λ¦°μƒ· 촬영 ν•¨μˆ˜ (λ‘œλ”© λŒ€κΈ° μ‹œκ°„ μΆ”κ°€)"""
25
+ if url in SCREENSHOT_CACHE:
26
+ return SCREENSHOT_CACHE[url]
27
+
28
+ if not url.startswith('http'):
29
+ url = f"https://{url}"
30
+
31
  options = webdriver.ChromeOptions()
32
  options.add_argument('--headless')
33
  options.add_argument('--no-sandbox')
 
37
  try:
38
  driver = webdriver.Chrome(options=options)
39
  driver.get(url)
40
+
41
+ # λͺ…μ‹œμ  λŒ€κΈ°: body μš”μ†Œκ°€ λ‘œλ“œλ  λ•ŒκΉŒμ§€ λŒ€κΈ° (μ΅œλŒ€ 10초)
42
+ try:
43
+ WebDriverWait(driver, 10).until(
44
+ EC.presence_of_element_located((By.TAG_NAME, "body"))
45
+ )
46
+ except TimeoutException:
47
+ print(f"νŽ˜μ΄μ§€ λ‘œλ”© νƒ€μž„μ•„μ›ƒ: {url}")
48
+
49
+ # μΆ”κ°€ λŒ€κΈ° μ‹œκ°„ (1초)
50
+ time.sleep(1)
51
+
52
+ # JavaScript μ‹€ν–‰ μ™„λ£Œ λŒ€κΈ°
53
+ driver.execute_script("return document.readyState") == "complete"
54
+
55
+ # μŠ€ν¬λ¦°μƒ· 촬영
56
  screenshot = driver.get_screenshot_as_png()
57
+ img = Image.open(BytesIO(screenshot))
58
+ buffered = BytesIO()
59
+ img.save(buffered, format="PNG")
60
+ base64_image = base64.b64encode(buffered.getvalue()).decode()
61
 
62
+ # μΊμ‹œμ— μ €μž₯
63
+ SCREENSHOT_CACHE[url] = base64_image
64
+ return base64_image
65
+
66
+ except WebDriverException as e:
67
+ print(f"μŠ€ν¬λ¦°μƒ· 촬영 μ‹€νŒ¨: {str(e)} for URL: {url}")
68
+ return None
69
  except Exception as e:
70
+ print(f"μ˜ˆμƒμΉ˜ λͺ»ν•œ 였λ₯˜: {str(e)} for URL: {url}")
71
  return None
72
  finally:
73
  if 'driver' in locals():
 
130
  response.raise_for_status()
131
  spaces = response.json()
132
 
133
+ # μƒμœ„ 10개만 선택 (원본 μˆœμ„œ μœ μ§€)
 
134
  top_spaces = spaces[:10]
135
 
136
  progress(0.1, desc="Creating gallery...")
 
145
  likes = format(space.get('likes', 0), ',')
146
  created = space.get('createdAt', '').split('T')[0]
147
 
148
+ screenshot = take_screenshot(space_url)
149
  bg_color = f"rgba({random.randint(230,255)}, {random.randint(230,255)}, {random.randint(230,255)}, 0.8)"
150
 
151
  html_content += f"""