tomo2chin2 commited on
Commit
874b482
ยท
verified ยท
1 Parent(s): 59cef9f

Upload 3 files

Browse files
Files changed (2) hide show
  1. app.py +700 -373
  2. requirements.txt +6 -2
app.py CHANGED
@@ -1,18 +1,5 @@
1
- # โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€
2
- # ๅŸบๆœฌใƒฉใ‚คใƒ–ใƒฉใƒช
3
- # โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€
4
- import os
5
- import time
6
- import tempfile
7
- import logging
8
- from io import BytesIO
9
- from typing import List, Optional
10
-
11
- # โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€
12
- # ใ‚ตใƒผใƒ‰ใƒ‘ใƒผใƒ†ใ‚ฃ
13
- # โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€
14
  import gradio as gr
15
- from fastapi import FastAPI, HTTPException
16
  from fastapi.responses import StreamingResponse
17
  from fastapi.staticfiles import StaticFiles
18
  from fastapi.middleware.cors import CORSMiddleware
@@ -23,303 +10,556 @@ from selenium.webdriver.common.by import By
23
  from selenium.webdriver.support.ui import WebDriverWait
24
  from selenium.webdriver.support import expected_conditions as EC
25
  from PIL import Image
26
- from huggingface_hub import hf_hub_download
 
 
 
 
 
27
 
28
- # โ–ถ ๆ–ฐใ—ใ„ Gemini SDK
29
- from google import genai # googleโ€‘genai โ‰ฅ1.11.0
30
- from google.genai import types # ๅž‹ใ‚ชใƒ–ใ‚ธใ‚งใ‚ฏใƒˆ
31
 
32
- # โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€
33
  # ใƒญใ‚ฎใƒณใ‚ฐ่จญๅฎš
34
- # โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€
35
  logging.basicConfig(level=logging.INFO)
36
  logger = logging.getLogger(__name__)
37
 
38
- # โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€
39
- # Pydantic ใƒขใƒ‡ใƒซ
40
- # โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€
41
  class GeminiRequest(BaseModel):
 
42
  text: str
43
- extension_percentage: float = 10.0
44
- temperature: float = 0.5
45
- trim_whitespace: bool = True
46
- style: str = "standard"
47
-
48
 
49
  class ScreenshotRequest(BaseModel):
 
50
  html_code: str
51
- extension_percentage: float = 10.0
52
- trim_whitespace: bool = True
53
- style: str = "standard"
54
-
55
-
56
- # โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€
57
- # โ‘  Font Awesome ใƒฌใ‚คใ‚ขใ‚ฆใƒˆ่ชฟๆ•ด
58
- # โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€
59
- def enhance_font_awesome_layout(html_code: str) -> str:
60
- """Font Awesome ใ‚ขใ‚คใ‚ณใƒณใฎ่กจ็คบใ‚บใƒฌใ‚’ไฟฎๆญฃใ™ใ‚‹่ฟฝๅŠ  CSS ใ‚’ๆŒฟๅ…ฅ"""
61
  fa_fix_css = """
62
  <style>
63
- /* Font Awesome icon tweaks */
64
- [class*="fa-"]{
65
- display:inline-block!important;
66
- vertical-align:middle!important;
67
- margin-right:8px!important;
 
 
 
 
 
 
 
68
  }
69
- h1 [class*="fa-"],h2 [class*="fa-"],h3 [class*="fa-"],
70
- h4 [class*="fa-"],h5 [class*="fa-"],h6 [class*="fa-"]{
71
- margin-right:10px!important;
 
 
 
72
  }
73
- .fa+span,.fas+span,.far+span,.fab+span,
74
- span+.fa,span+.fas,span+.far,span+.fab{
75
- display:inline-block!important;margin-left:5px!important;
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
76
  }
77
- li [class*="fa-"],p [class*="fa-"]{margin-right:10px!important;}
78
- .inline-icon{display:inline-flex!important;align-items:center!important;}
79
- [class*="fa-"]+span{display:inline-block!important;vertical-align:middle!important;}
80
  </style>
81
  """
82
- if "<head>" in html_code:
83
- return html_code.replace("</head>", f"{fa_fix_css}</head>")
84
- elif "<html" in html_code:
85
- head_end = html_code.find("</head>")
 
 
 
86
  if head_end > 0:
87
  return html_code[:head_end] + fa_fix_css + html_code[head_end:]
88
- body_start = html_code.find("<body")
89
- if body_start > 0:
90
- return html_code[:body_start] + f"<head>{fa_fix_css}</head>" + html_code[body_start:]
91
- return f"<html><head>{fa_fix_css}</head>{html_code}</html>"
92
-
93
-
94
- # โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€
95
- # โ‘ก ใ‚ทใ‚นใƒ†ใƒ ใƒ—ใƒญใƒณใƒ—ใƒˆ่ชญใฟ่พผใฟ
96
- # โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€
97
- def load_system_instruction(style: str = "standard") -> str:
98
- """style ใ”ใจใฎ prompt.txt ใ‚’ใƒญใƒผใ‚ซใƒซ or HF Hub ใ‹ใ‚‰ๅ–ๅพ—"""
99
- styles = ["standard", "cute", "resort", "cool", "dental"]
100
- if style not in styles:
101
- logger.warning(f"็„กๅŠนใชใ‚นใ‚ฟใ‚คใƒซ '{style}' โ†’ 'standard' ใ‚’ไฝฟ็”จ")
102
- style = "standard"
103
-
104
- # ใƒญใƒผใ‚ซใƒซ first
105
- local_path = os.path.join(os.path.dirname(__file__), style, "prompt.txt")
106
- if os.path.exists(local_path):
107
- with open(local_path, encoding="utf-8") as f:
108
- return f.read()
109
-
110
- # HF Hub fallback
111
  try:
112
- file_path = hf_hub_download(
113
- repo_id="tomo2chin2/GURAREKOstlyle",
114
- filename=f"{style}/prompt.txt",
115
- repo_type="dataset",
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
116
  )
117
- with open(file_path, encoding="utf-8") as f:
118
- return f.read()
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
119
  except Exception as e:
120
- logger.error(f"prompt.txt ๅ–ๅพ—ๅคฑๆ•—: {e}")
121
- raise
122
-
123
-
124
- # โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€
125
- # โ‘ข ็”ปๅƒใฎ็ฉบ็™ฝใƒˆใƒชใƒŸใƒณใ‚ฐ
126
- # โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€
127
- def trim_image_whitespace(
128
- image: Image.Image, threshold: int = 250, padding: int = 10
129
- ) -> Image.Image:
130
- """็™ฝไฝ™็™ฝใ‚’ๆคœๅ‡บใ—ใƒ‘ใƒ‡ใ‚ฃใƒณใ‚ฐใ‚’ๆฎ‹ใ—ใฆๅˆ‡ใ‚Š่ฉฐใ‚ใ‚‹"""
131
- gray = image.convert("L")
 
 
 
 
 
 
 
 
132
  data = gray.getdata()
133
- w, h = gray.size
134
- min_x, min_y, max_x, max_y = w, h, 0, 0
 
 
 
 
 
135
  pixels = list(data)
136
- pixels = [pixels[i * w : (i + 1) * w] for i in range(h)]
137
- for y in range(h):
138
- for x in range(w):
139
- if pixels[y][x] < threshold:
140
- min_x, min_y = min(min_x, x), min(min_y, y)
141
- max_x, max_y = max(max_x, x), max(max_y, y)
142
- if min_x > max_x:
 
 
 
 
 
 
 
143
  return image
144
- min_x, min_y = max(0, min_x - padding), max(0, min_y - padding)
145
- max_x, max_y = min(w - 1, max_x + padding), min(h - 1, max_y + padding)
146
- return image.crop((min_x, min_y, max_x + 1, max_y + 1))
147
-
148
-
149
- # โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€
150
- # โ‘ฃ Selenium ใงใƒ•ใƒซใƒšใƒผใ‚ธ SS ็”Ÿๆˆ
151
- # โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€
152
- def render_fullpage_screenshot(
153
- html_code: str, extension_percentage: float = 6.0, trim_whitespace: bool = True
154
- ) -> Image.Image:
155
- """HTML ๆ–‡ๅญ—ๅˆ— โ†’ fullโ€‘page PNG โ†’ PIL.Image"""
156
- tmp_path: Optional[str] = None
157
- driver: Optional[webdriver.Chrome] = None
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
158
  try:
159
- with tempfile.NamedTemporaryFile(
160
- suffix=".html", delete=False, mode="w", encoding="utf-8"
161
- ) as tmp:
162
- tmp.write(html_code)
163
- tmp_path = tmp.name
164
- options = Options()
165
- options.add_argument("--headless")
166
- options.add_argument("--no-sandbox")
167
- options.add_argument("--disable-dev-shm-usage")
168
- options.add_argument("--force-device-scale-factor=1")
169
- driver = webdriver.Chrome(options=options)
170
- driver.set_window_size(1200, 1000)
171
- driver.get(f"file://{tmp_path}")
 
 
 
 
 
 
 
 
 
 
 
172
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
173
  WebDriverWait(driver, 15).until(
174
  EC.presence_of_element_located((By.TAG_NAME, "body"))
175
  )
176
- time.sleep(3) # ๅˆๆœŸใƒญใƒผใƒ‰ๅพ…ใก
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
177
 
178
- # ็ธฆใ‚นใ‚ฏใƒญใƒผใƒซใ—ใฆใƒฌใƒณใƒ€ใƒชใƒณใ‚ฐ็ขบๅฎš
179
- total = driver.execute_script(
180
- "return Math.max(document.body.scrollHeight, document.documentElement.scrollHeight);"
181
- )
182
- vp = driver.execute_script("return window.innerHeight;")
183
- for i in range(max(1, total // vp) + 1):
184
- driver.execute_script(f"window.scrollTo(0, {i*(vp-200)});")
185
- time.sleep(0.2)
186
- driver.execute_script("window.scrollTo(0,0);")
 
 
 
 
 
 
 
 
 
 
 
 
 
 
187
  time.sleep(1)
188
 
189
- # ๅ…จไฝ“้ซ˜ใ•ใซไฝ™็™ฝใ‚’่ฟฝๅŠ 
190
- total = driver.execute_script(
191
- "return Math.max(document.body.scrollHeight, document.documentElement.scrollHeight);"
192
- )
193
- height = int(total * (1 + extension_percentage / 100))
194
- width = driver.execute_script(
195
- "return Math.max(document.documentElement.scrollWidth, document.body.scrollWidth);"
196
- )
197
- height = min(max(height, 100), 4000)
198
- width = min(max(width, 100), 2000)
199
- driver.set_window_size(width, height)
 
 
 
 
 
200
  time.sleep(0.5)
 
201
 
 
 
202
  png = driver.get_screenshot_as_png()
 
 
 
203
  img = Image.open(BytesIO(png))
 
 
 
204
  if trim_whitespace:
205
  img = trim_image_whitespace(img, threshold=248, padding=20)
 
 
206
  return img
 
207
  except Exception as e:
208
- logger.error(f"Screenshot Error: {e}", exc_info=True)
209
- return Image.new("RGB", (1, 1), (0, 0, 0))
 
210
  finally:
 
211
  if driver:
212
  try:
213
  driver.quit()
214
- except Exception:
215
- pass
 
216
  if tmp_path and os.path.exists(tmp_path):
217
- os.remove(tmp_path)
218
-
219
-
220
- # โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€
221
- # โ‘ค Gemini โ†’ HTML ็”Ÿๆˆ
222
- # โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€
223
- def _genai_client(api_key: str) -> genai.Client:
224
- return genai.Client(api_key=api_key)
225
-
226
-
227
- def _default_safety() -> List[types.SafetySetting]:
228
- return [
229
- types.SafetySetting(
230
- category="HARM_CATEGORY_HARASSMENT", threshold="BLOCK_MEDIUM_AND_ABOVE"
231
- ),
232
- types.SafetySetting(
233
- category="HARM_CATEGORY_HATE_SPEECH", threshold="BLOCK_MEDIUM_AND_ABOVE"
234
- ),
235
- types.SafetySetting(
236
- category="HARM_CATEGORY_SEXUALLY_EXPLICIT", threshold="BLOCK_MEDIUM_AND_ABOVE"
237
- ),
238
- types.SafetySetting(
239
- category="HARM_CATEGORY_DANGEROUS_CONTENT", threshold="BLOCK_MEDIUM_AND_ABOVE"
240
- ),
241
- ]
242
-
243
-
244
- def generate_html_from_text(
245
- text: str, temperature: float = 0.3, style: str = "standard"
246
- ) -> str:
247
- """
248
- Gemini ใƒขใƒ‡ใƒซใ‹ใ‚‰ HTML ใ‚ณใƒผใƒ‰ใ‚’่ฟ”ใ™ใ€‚
249
- * ็’ฐๅขƒๅค‰ๆ•ฐ GEMINI_MODEL ใŒ geminiโ€‘2.5โ€‘flash-previewโ€‘04-17 ใฎๅ ดๅˆ
250
- -> thinking_budget=0 ใ‚’ไป˜ใ‘ใฆๅ‘ผใณๅ‡บใ—
251
- """
252
- api_key = os.getenv("GEMINI_API_KEY")
253
- if not api_key:
254
- raise ValueError("GEMINI_API_KEY ใŒ่จญๅฎšใ•ใ‚Œใฆใ„ใพใ›ใ‚“")
255
- model_name = os.getenv("GEMINI_MODEL", "gemini-1.5-pro")
256
- client = _genai_client(api_key)
257
-
258
- gen_cfg = types.GenerationConfig(
259
- temperature=temperature,
260
- top_p=0.7,
261
- top_k=20,
262
- max_output_tokens=8192,
263
- candidate_count=1,
264
- )
265
- safety_cfg = _default_safety()
266
- think_cfg = (
267
- types.ThinkingConfig(thinking_budget=0)
268
- if model_name == "gemini-2.5-flash-preview-04-17"
269
- else None
270
- )
271
-
272
- req_cfg_kwargs = dict(
273
- generation_config=gen_cfg,
274
- safety_settings=safety_cfg,
275
- )
276
- if think_cfg:
277
- req_cfg_kwargs["thinking_config"] = think_cfg
278
-
279
- req_cfg = types.GenerateContentConfig(**req_cfg_kwargs)
280
-
281
- prompt = f"{load_system_instruction(style)}\n\n{text}"
282
- logger.info(
283
- f"Gemini request โ†’ model={model_name}, temp={temperature}, thinking_budget={0 if think_cfg else None}"
284
- )
285
-
286
- rsp = client.models.generate_content(
287
- model=model_name, contents=prompt, config=req_cfg
288
- )
289
- raw = rsp.text or ""
290
-
291
- start = raw.find("```html")
292
- end = raw.rfind("```")
293
- if 0 <= start < end:
294
- html_code = raw[start + 7 : end].strip()
295
- return enhance_font_awesome_layout(html_code)
296
-
297
- logger.warning("```html``` ใƒ–ใƒญใƒƒใ‚ฏใชใ—ใ€‚็”Ÿใƒฌใ‚นใƒใƒณใ‚นใ‚’่ฟ”ใ—ใพใ™")
298
- return raw
299
-
300
-
301
- # โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€
302
- # โ‘ฅ ใƒ†ใ‚ญใ‚นใƒˆ โ†’ ใ‚นใ‚ฏใƒชใƒผใƒณใ‚ทใƒงใƒƒใƒˆ็ตฑๅˆ
303
- # โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€
304
- def text_to_screenshot(
305
- text: str,
306
- extension_percentage: float,
307
- temperature: float = 0.3,
308
- trim_whitespace: bool = True,
309
- style: str = "standard",
310
- ) -> Image.Image:
311
  try:
312
- html = generate_html_from_text(text, temperature, style)
313
- return render_fullpage_screenshot(html, extension_percentage, trim_whitespace)
314
- except Exception as e:
315
- logger.error(e, exc_info=True)
316
- return Image.new("RGB", (1, 1), (0, 0, 0))
317
 
 
 
 
 
 
318
 
319
- # โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€
320
- # โ‘ฆ FastAPI ใ‚ปใƒƒใƒˆใ‚ขใƒƒใƒ—
321
- # โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€
322
  app = FastAPI()
 
 
323
  app.add_middleware(
324
  CORSMiddleware,
325
  allow_origins=["*"],
@@ -328,136 +568,223 @@ app.add_middleware(
328
  allow_headers=["*"],
329
  )
330
 
331
- # Gradio ใฎ้™็š„ใƒ•ใ‚กใ‚คใƒซใ‚’ใƒžใ‚ฆใƒณใƒˆ
 
332
  gradio_dir = os.path.dirname(gr.__file__)
333
- for sub in [
334
- ("static", "templates/frontend/static"),
335
- ("_app", "templates/frontend/_app"),
336
- ("assets", "templates/frontend/assets"),
337
- ("cdn", "templates/cdn"),
338
- ]:
339
- target = os.path.join(gradio_dir, sub[1])
340
- if os.path.exists(target):
341
- app.mount(f"/{sub[0]}", StaticFiles(directory=target), name=sub[0])
342
- logger.info(f"Mounted /{sub[0]} โ†’ {target}")
343
-
344
- # โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€
345
- # โ‘ง API ใ‚จใƒณใƒ‰ใƒใ‚คใƒณใƒˆ
346
- # โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€
347
- @app.post(
348
- "/api/screenshot",
349
- response_class=StreamingResponse,
350
- tags=["Screenshot"],
351
- summary="HTML โ†’ Fullโ€‘page Screenshot",
352
- )
353
- async def api_render_screenshot(req: ScreenshotRequest):
354
- img = render_fullpage_screenshot(
355
- req.html_code, req.extension_percentage, req.trim_whitespace
356
- )
357
- buf = BytesIO()
358
- img.save(buf, format="PNG")
359
- buf.seek(0)
360
- return StreamingResponse(buf, media_type="image/png")
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
361
 
 
 
 
 
362
 
363
- @app.post(
364
- "/api/text-to-screenshot",
365
- response_class=StreamingResponse,
366
- tags=["Screenshot", "Gemini"],
367
- summary="Text โ†’ Gemini โ†’ Infographic Screenshot",
368
- )
369
- async def api_text_to_screenshot(req: GeminiRequest):
370
- img = text_to_screenshot(
371
- req.text,
372
- req.extension_percentage,
373
- req.temperature,
374
- req.trim_whitespace,
375
- req.style,
376
- )
377
- buf = BytesIO()
378
- img.save(buf, format="PNG")
379
- buf.seek(0)
380
- return StreamingResponse(buf, media_type="image/png")
381
-
382
-
383
- # โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€
384
- # โ‘จ Gradio UI
385
- # โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€
386
- def process_input(
387
- input_mode, input_text, extension_percentage, temperature, trim_whitespace, style
388
- ):
389
- if input_mode == "HTMLๅ…ฅๅŠ›":
390
- return render_fullpage_screenshot(
391
- input_text, extension_percentage, trim_whitespace
 
 
 
 
 
392
  )
393
- return text_to_screenshot(
394
- input_text, extension_percentage, temperature, trim_whitespace, style
395
- )
 
396
 
397
 
398
- with gr.Blocks(title="Full Page Screenshot + Gemini 2.5 Flash") as iface:
399
- gr.Markdown("## HTML ใƒ“ใƒฅใƒผใ‚ข & ใƒ†ใ‚ญใ‚นใƒˆ โ†’ ใ‚คใƒณใƒ•ใ‚ฉใ‚ฐใƒฉใƒ•ใ‚ฃใƒƒใ‚ฏ")
400
- input_mode = gr.Radio(["HTMLๅ…ฅๅŠ›", "ใƒ†ใ‚ญใ‚นใƒˆๅ…ฅๅŠ›"], value="HTMLๅ…ฅๅŠ›", label="ๅ…ฅๅŠ›ใƒขใƒผใƒ‰")
401
- input_text = gr.Textbox(lines=15, label="ๅ…ฅๅŠ›")
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
402
  with gr.Row():
403
- style_dd = gr.Dropdown(
404
- ["standard", "cute", "resort", "cool", "dental"],
405
- value="standard",
406
- label="ใƒ‡ใ‚ถใ‚คใƒณใ‚นใ‚ฟใ‚คใƒซ",
407
- visible=False,
408
  )
409
- extension_slider = gr.Slider(0, 30, 10, label="ไธŠไธ‹้ซ˜ใ•ๆ‹กๅผต็އ(%)")
410
- temperature_slider = gr.Slider(
411
- 0.0,
412
- 1.0,
413
- 0.5,
414
- step=0.1,
415
- label="็”Ÿๆˆๆธฉๅบฆ",
416
- visible=False,
417
- )
418
- trim_cb = gr.Checkbox(value=True, label="ไฝ™็™ฝ่‡ชๅ‹•ใƒˆใƒชใƒŸใƒณใ‚ฐ")
419
- btn = gr.Button("็”Ÿๆˆ")
420
- out_img = gr.Image(type="pil", label="ใ‚นใ‚ฏใƒชใƒผใƒณใ‚ทใƒงใƒƒใƒˆ")
421
 
422
- def _vis(mode):
423
- is_text = mode == "ใƒ†ใ‚ญใ‚นใƒˆๅ…ฅๅŠ›"
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
424
  return [
425
- {"visible": is_text, "__type__": "update"},
426
- {"visible": is_text, "__type__": "update"},
427
  ]
428
 
429
- input_mode.change(_vis, input_mode, [temperature_slider, style_dd])
430
- btn.click(
431
- process_input,
432
- [
433
- input_mode,
434
- input_text,
435
- extension_slider,
436
- temperature_slider,
437
- trim_cb,
438
- style_dd,
439
- ],
440
- out_img,
441
  )
442
 
443
- gr.Markdown(
444
- f"""
445
- ### ็’ฐๅขƒ
446
- * ไฝฟ็”จใƒขใƒ‡ใƒซ: `{os.getenv('GEMINI_MODEL', 'gemini-1.5-pro')}`
447
- * thinking_budget=0 ใฏ `gemini-2.5-flash-preview-04-17` ไฝฟ็”จๆ™‚ใฎใฟ่‡ชๅ‹•ไป˜ไธŽ
448
- """
449
  )
450
 
451
- # โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€
452
- # โ‘ฉ FastAPI ใซ Gradio ใ‚’ใƒžใ‚ฆใƒณใƒˆ
453
- # โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€
 
 
 
 
 
 
 
 
 
 
454
  app = gr.mount_gradio_app(app, iface, path="/")
455
 
456
- # โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€
457
- # โ‘ช ็›ดๆŽฅๅฎŸ่กŒๆ™‚
458
- # โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€
459
  if __name__ == "__main__":
460
  import uvicorn
461
-
462
- logger.info("Starting dev server at http://localhost:7860")
463
- uvicorn.run(app, host="0.0.0.0", port=7860)
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
  import gradio as gr
2
+ from fastapi import FastAPI, HTTPException, Body
3
  from fastapi.responses import StreamingResponse
4
  from fastapi.staticfiles import StaticFiles
5
  from fastapi.middleware.cors import CORSMiddleware
 
10
  from selenium.webdriver.support.ui import WebDriverWait
11
  from selenium.webdriver.support import expected_conditions as EC
12
  from PIL import Image
13
+ from io import BytesIO
14
+ import tempfile
15
+ import time
16
+ import os
17
+ import logging
18
+ from huggingface_hub import hf_hub_download # ่ฟฝๅŠ : HuggingFace Hubใ‹ใ‚‰ใƒ•ใ‚กใ‚คใƒซใ‚’็›ดๆŽฅใƒ€ใ‚ฆใƒณใƒญใƒผใƒ‰
19
 
20
+ # ๆญฃใ—ใ„Gemini้–ข้€ฃใฎใ‚คใƒณใƒใƒผใƒˆ
21
+ import google.generativeai as genai
 
22
 
 
23
  # ใƒญใ‚ฎใƒณใ‚ฐ่จญๅฎš
 
24
  logging.basicConfig(level=logging.INFO)
25
  logger = logging.getLogger(__name__)
26
 
27
+ # --- Gemini็ตฑๅˆ ---
 
 
28
  class GeminiRequest(BaseModel):
29
+ """Geminiใธใฎใƒชใ‚ฏใ‚จใ‚นใƒˆใƒ‡ใƒผใ‚ฟใƒขใƒ‡ใƒซ"""
30
  text: str
31
+ extension_percentage: float = 10.0 # ใƒ‡ใƒ•ใ‚ฉใƒซใƒˆๅ€ค10%
32
+ temperature: float = 0.5 # ใƒ‡ใƒ•ใ‚ฉใƒซใƒˆๅ€คใ‚’0.5ใซ่จญๅฎš
33
+ trim_whitespace: bool = True # ไฝ™็™ฝใƒˆใƒชใƒŸใƒณใ‚ฐใ‚ชใƒ—ใ‚ทใƒงใƒณ๏ผˆใƒ‡ใƒ•ใ‚ฉใƒซใƒˆๆœ‰ๅŠน๏ผ‰
34
+ style: str = "standard" # ใƒ‡ใƒ•ใ‚ฉใƒซใƒˆใฏstandard
 
35
 
36
  class ScreenshotRequest(BaseModel):
37
+ """ใ‚นใ‚ฏใƒชใƒผใƒณใ‚ทใƒงใƒƒใƒˆใƒชใ‚ฏใ‚จใ‚นใƒˆใƒขใƒ‡ใƒซ"""
38
  html_code: str
39
+ extension_percentage: float = 10.0 # ใƒ‡ใƒ•ใ‚ฉใƒซใƒˆๅ€ค10%
40
+ trim_whitespace: bool = True # ไฝ™็™ฝใƒˆใƒชใƒŸใƒณใ‚ฐใ‚ชใƒ—ใ‚ทใƒงใƒณ๏ผˆใƒ‡ใƒ•ใ‚ฉใƒซใƒˆๆœ‰ๅŠน๏ผ‰
41
+ style: str = "standard" # ใƒ‡ใƒ•ใ‚ฉใƒซใƒˆใฏstandard
42
+
43
+ # HTMLใฎFont Awesomeใƒฌใ‚คใ‚ขใ‚ฆใƒˆใ‚’ๆ”นๅ–„ใ™ใ‚‹้–ขๆ•ฐ
44
+ def enhance_font_awesome_layout(html_code):
45
+ """Font Awesomeใƒฌใ‚คใ‚ขใ‚ฆใƒˆใ‚’ๆ”นๅ–„ใ™ใ‚‹CSSใ‚’่ฟฝๅŠ """
46
+ # CSSใ‚’่ฟฝๅŠ 
 
 
47
  fa_fix_css = """
48
  <style>
49
+ /* Font Awesomeใ‚ขใ‚คใ‚ณใƒณใฎใƒฌใ‚คใ‚ขใ‚ฆใƒˆไฟฎๆญฃ */
50
+ [class*="fa-"] {
51
+ display: inline-block !important;
52
+ margin-right: 8px !important;
53
+ vertical-align: middle !important;
54
+ }
55
+
56
+ /* ใƒ†ใ‚ญใ‚นใƒˆๅ†…ใฎใ‚ขใ‚คใ‚ณใƒณไฝ็ฝฎ่ชฟๆ•ด */
57
+ h1 [class*="fa-"], h2 [class*="fa-"], h3 [class*="fa-"],
58
+ h4 [class*="fa-"], h5 [class*="fa-"], h6 [class*="fa-"] {
59
+ vertical-align: middle !important;
60
+ margin-right: 10px !important;
61
  }
62
+
63
+ /* ็‰นๅฎšใƒ‘ใ‚ฟใƒผใƒณใฎไฟฎๆญฃ */
64
+ .fa + span, .fas + span, .far + span, .fab + span,
65
+ span + .fa, span + .fas, span + .far + span {
66
+ display: inline-block !important;
67
+ margin-left: 5px !important;
68
  }
69
+
70
+ /* ใ‚ซใƒผใƒ‰ๅ†…ใ‚ขใ‚คใ‚ณใƒณไฟฎๆญฃ */
71
+ .card [class*="fa-"], .card-body [class*="fa-"] {
72
+ float: none !important;
73
+ clear: none !important;
74
+ position: relative !important;
75
+ }
76
+
77
+ /* ใ‚ขใ‚คใ‚ณใƒณใจๆ–‡ๅญ—ใŒ้‡ใชใ‚‹ๅ ดๅˆใฎ่ชฟๆ•ด */
78
+ li [class*="fa-"], p [class*="fa-"] {
79
+ margin-right: 10px !important;
80
+ }
81
+
82
+ /* ใ‚คใƒณใƒฉใ‚คใƒณใ‚ขใ‚คใ‚ณใƒณใฎใ‚นใƒšใƒผใ‚ทใƒณใ‚ฐ */
83
+ .inline-icon {
84
+ display: inline-flex !important;
85
+ align-items: center !important;
86
+ justify-content: flex-start !important;
87
+ }
88
+
89
+ /* ใ‚ขใ‚คใ‚ณใƒณๅพŒใฎใƒ†ใ‚ญใ‚นใƒˆ */
90
+ [class*="fa-"] + span {
91
+ display: inline-block !important;
92
+ vertical-align: middle !important;
93
  }
 
 
 
94
  </style>
95
  """
96
+
97
+ # headใ‚ฟใ‚ฐใŒใ‚ใ‚‹ๅ ดๅˆใฏใใฎไธญใซ่ฟฝๅŠ 
98
+ if '<head>' in html_code:
99
+ return html_code.replace('</head>', f'{fa_fix_css}</head>')
100
+ # HTMLใ‚ฟใ‚ฐใŒใ‚ใ‚‹ๅ ดๅˆใฏใใฎๅพŒใซ่ฟฝๅŠ 
101
+ elif '<html' in html_code:
102
+ head_end = html_code.find('</head>')
103
  if head_end > 0:
104
  return html_code[:head_end] + fa_fix_css + html_code[head_end:]
105
+ else:
106
+ body_start = html_code.find('<body')
107
+ if body_start > 0:
108
+ return html_code[:body_start] + f'<head>{fa_fix_css}</head>' + html_code[body_start:]
109
+
110
+ # ใฉใกใ‚‰ใ‚‚ใชใ„ๅ ดๅˆใฏๅ…ˆ้ ญใซ่ฟฝๅŠ 
111
+ return f'<html><head>{fa_fix_css}</head>' + html_code + '</html>'
112
+
113
+ def load_system_instruction(style="standard"):
114
+ """
115
+ ๆŒ‡ๅฎšใ•ใ‚ŒใŸใ‚นใ‚ฟใ‚คใƒซใฎใ‚ทใ‚นใƒ†ใƒ ใ‚คใƒณใ‚นใƒˆใƒฉใ‚ฏใ‚ทใƒงใƒณใ‚’่ชญใฟ่พผใ‚€
116
+
117
+ Args:
118
+ style: ไฝฟ็”จใ™ใ‚‹ใ‚นใ‚ฟใ‚คใƒซๅ (standard, cute, resort, cool, dental)
119
+
120
+ Returns:
121
+ ่ชญใฟ่พผใพใ‚ŒใŸใ‚ทใ‚นใƒ†ใƒ ใ‚คใƒณใ‚นใƒˆใƒฉใ‚ฏใ‚ทใƒงใƒณ
122
+ """
 
 
 
 
 
123
  try:
124
+ # ๆœ‰ๅŠนใชใ‚นใ‚ฟใ‚คใƒซไธ€่ฆง
125
+ valid_styles = ["standard", "cute", "resort", "cool", "dental"]
126
+
127
+ # ใ‚นใ‚ฟใ‚คใƒซใฎๆคœ่จผ
128
+ if style not in valid_styles:
129
+ logger.warning(f"็„กๅŠนใชใ‚นใ‚ฟใ‚คใƒซ '{style}' ใŒๆŒ‡ๅฎšใ•ใ‚Œใพใ—ใŸใ€‚ใƒ‡ใƒ•ใ‚ฉใƒซใƒˆใฎ 'standard' ใ‚’ไฝฟ็”จใ—ใพใ™ใ€‚")
130
+ style = "standard"
131
+
132
+ logger.info(f"ใ‚นใ‚ฟใ‚คใƒซ '{style}' ใฎใ‚ทใ‚นใƒ†ใƒ ใ‚คใƒณใ‚นใƒˆใƒฉใ‚ฏใ‚ทใƒงใƒณใ‚’่ชญใฟ่พผใฟใพใ™")
133
+
134
+ # ใพใšใ€ใƒญใƒผใ‚ซใƒซใฎใ‚นใ‚ฟใ‚คใƒซใƒ‡ใ‚ฃใƒฌใ‚ฏใƒˆใƒชๅ†…ใฎprompt.txtใ‚’็ขบ่ช
135
+ local_path = os.path.join(os.path.dirname(__file__), style, "prompt.txt")
136
+
137
+ # ใƒญใƒผใ‚ซใƒซใƒ•ใ‚กใ‚คใƒซใŒๅญ˜ๅœจใ™ใ‚‹ๅ ดๅˆใฏใใ‚Œใ‚’ไฝฟ็”จ
138
+ if os.path.exists(local_path):
139
+ logger.info(f"ใƒญใƒผใ‚ซใƒซใƒ•ใ‚กใ‚คใƒซใ‚’ไฝฟ็”จ: {local_path}")
140
+ with open(local_path, 'r', encoding='utf-8') as file:
141
+ instruction = file.read()
142
+ return instruction
143
+
144
+ # HuggingFaceใƒชใƒใ‚ธใƒˆใƒชใ‹ใ‚‰ใฎใƒ•ใ‚กใ‚คใƒซ่ชญใฟ่พผใฟใ‚’่ฉฆ่กŒ
145
+ try:
146
+ # ใ‚นใ‚ฟใ‚คใƒซๅ›บๆœ‰ใฎใƒ•ใ‚กใ‚คใƒซใƒ‘ใ‚นใ‚’ๆŒ‡ๅฎš
147
+ file_path = hf_hub_download(
148
+ repo_id="tomo2chin2/GURAREKOstlyle",
149
+ filename=f"{style}/prompt.txt",
150
+ repo_type="dataset"
151
+ )
152
+
153
+ logger.info(f"ใ‚นใ‚ฟใ‚คใƒซ '{style}' ใฎใƒ—ใƒญใƒณใƒ—ใƒˆใ‚’HuggingFaceใ‹ใ‚‰่ชญใฟ่พผใฟใพใ—ใŸ: {file_path}")
154
+ with open(file_path, 'r', encoding='utf-8') as file:
155
+ instruction = file.read()
156
+ return instruction
157
+
158
+ except Exception as style_error:
159
+ # ใ‚นใ‚ฟใ‚คใƒซๅ›บๆœ‰ใƒ•ใ‚กใ‚คใƒซใฎ่ชญใฟ่พผใฟใซๅคฑๆ•—ใ—ใŸๅ ดๅˆใ€ใƒ‡ใƒ•ใ‚ฉใƒซใƒˆใฎprompt.txtใ‚’ไฝฟ็”จ
160
+ logger.warning(f"ใ‚นใ‚ฟใ‚คใƒซ '{style}' ใฎใƒ—ใƒญใƒณใƒ—ใƒˆ่ชญใฟ่พผใฟใซๅคฑๆ•—: {str(style_error)}")
161
+ logger.info("ใƒ‡ใƒ•ใ‚ฉใƒซใƒˆใฎprompt.txtใ‚’่ชญใฟ่พผใฟใพใ™")
162
+
163
+ file_path = hf_hub_download(
164
+ repo_id="tomo2chin2/GURAREKOstlyle",
165
+ filename="prompt.txt",
166
+ repo_type="dataset"
167
+ )
168
+
169
+ with open(file_path, 'r', encoding='utf-8') as file:
170
+ instruction = file.read()
171
+
172
+ logger.info("ใƒ‡ใƒ•ใ‚ฉใƒซใƒˆใฎใ‚ทใ‚นใƒ†ใƒ ใ‚คใƒณใ‚นใƒˆใƒฉใ‚ฏใ‚ทใƒงใƒณใ‚’่ชญใฟ่พผใฟใพใ—ใŸ")
173
+ return instruction
174
+
175
+ except Exception as e:
176
+ error_msg = f"ใ‚ทใ‚นใƒ†ใƒ ใ‚คใƒณใ‚นใƒˆใƒฉใ‚ฏใ‚ทใƒงใƒณใฎ่ชญใฟ่พผใฟใซๅคฑๆ•—: {str(e)}"
177
+ logger.error(error_msg)
178
+ raise ValueError(error_msg)
179
+
180
+ def generate_html_from_text(text, temperature=0.3, style="standard"):
181
+ """ใƒ†ใ‚ญใ‚นใƒˆใ‹ใ‚‰HTMLใ‚’็”Ÿๆˆใ™ใ‚‹"""
182
+ try:
183
+ # APIใ‚ญใƒผใฎๅ–ๅพ—ใจ่จญๅฎš
184
+ api_key = os.environ.get("GEMINI_API_KEY")
185
+ if not api_key:
186
+ logger.error("GEMINI_API_KEY ็’ฐๅขƒๅค‰ๆ•ฐใŒ่จญๅฎšใ•ใ‚Œใฆใ„ใพใ›ใ‚“")
187
+ raise ValueError("GEMINI_API_KEY ็’ฐๅขƒๅค‰ๆ•ฐใŒ่จญๅฎšใ•ใ‚Œใฆใ„ใพใ›ใ‚“")
188
+
189
+ # ใƒขใƒ‡ใƒซๅใฎๅ–ๅพ—๏ผˆ็’ฐๅขƒๅค‰ๆ•ฐใ‹ใ‚‰ใ€ใชใ‘ใ‚Œใฐใƒ‡ใƒ•ใ‚ฉใƒซใƒˆๅ€ค๏ผ‰
190
+ model_name = os.environ.get("GEMINI_MODEL", "gemini-1.5-pro")
191
+ logger.info(f"ไฝฟ็”จใ™ใ‚‹Geminiใƒขใƒ‡ใƒซ: {model_name}")
192
+
193
+ # Gemini APIใฎ่จญๅฎš
194
+ genai.configure(api_key=api_key)
195
+
196
+ # ๆŒ‡ๅฎšใ•ใ‚ŒใŸใ‚นใ‚ฟใ‚คใƒซใฎใ‚ทใ‚นใƒ†ใƒ ใ‚คใƒณใ‚นใƒˆใƒฉใ‚ฏใ‚ทใƒงใƒณใ‚’่ชญใฟ่พผใ‚€
197
+ system_instruction = load_system_instruction(style)
198
+
199
+ # ใƒขใƒ‡ใƒซๅˆๆœŸๅŒ–
200
+ logger.info(f"Gemini APIใซใƒชใ‚ฏใ‚จใ‚นใƒˆใ‚’้€ไฟก: ใƒ†ใ‚ญใ‚นใƒˆ้•ทใ• = {len(text)}, ๆธฉๅบฆ = {temperature}, ใ‚นใ‚ฟใ‚คใƒซ = {style}")
201
+
202
+ # ใƒขใƒ‡ใƒซๅˆๆœŸๅŒ–
203
+ model = genai.GenerativeModel(model_name)
204
+
205
+ # ็”Ÿๆˆ่จญๅฎš - ใฐใ‚‰ใคใใ‚’ๆธ›ใ‚‰ใ™ใŸใ‚ใซ่จญๅฎšใ‚’่ชฟๆ•ด
206
+ generation_config = {
207
+ "temperature": temperature, # ใ‚ˆใ‚ŠไฝŽใ„ๆธฉๅบฆใ‚’่จญๅฎš
208
+ "top_p": 0.7, # 0.95ใ‹ใ‚‰0.7ใซไธ‹ใ’ใฆๅ‡บๅŠ›ใฎๅคšๆง˜ๆ€งใ‚’ๅˆถ้™
209
+ "top_k": 20, # 64ใ‹ใ‚‰20ใซไธ‹ใ’ใฆๅ€™่ฃœใ‚’็ตžใ‚‹
210
+ "max_output_tokens": 8192,
211
+ "candidate_count": 1 # ๅ€™่ฃœใฏ1ใคใ ใ‘็”Ÿๆˆ
212
+ }
213
+
214
+ # ๅฎ‰ๅ…จ่จญๅฎš - ใƒ‡ใƒ•ใ‚ฉใƒซใƒˆใฎๅฎ‰ๅ…จ่จญๅฎšใ‚’ไฝฟ็”จ
215
+ safety_settings = [
216
+ {
217
+ "category": "HARM_CATEGORY_HARASSMENT",
218
+ "threshold": "BLOCK_MEDIUM_AND_ABOVE"
219
+ },
220
+ {
221
+ "category": "HARM_CATEGORY_HATE_SPEECH",
222
+ "threshold": "BLOCK_MEDIUM_AND_ABOVE"
223
+ },
224
+ {
225
+ "category": "HARM_CATEGORY_SEXUALLY_EXPLICIT",
226
+ "threshold": "BLOCK_MEDIUM_AND_ABOVE"
227
+ },
228
+ {
229
+ "category": "HARM_CATEGORY_DANGEROUS_CONTENT",
230
+ "threshold": "BLOCK_MEDIUM_AND_ABOVE"
231
+ }
232
+ ]
233
+
234
+ # ใƒ—ใƒญใƒณใƒ—ใƒˆๆง‹็ฏ‰
235
+ prompt = f"{system_instruction}\n\n{text}"
236
+
237
+ # ใ‚ณใƒณใƒ†ใƒณใƒ„็”Ÿๆˆ
238
+ response = model.generate_content(
239
+ prompt,
240
+ generation_config=generation_config,
241
+ safety_settings=safety_settings
242
  )
243
+
244
+ # ใƒฌใ‚นใƒใƒณใ‚นใ‹ใ‚‰HTMLใ‚’ๆŠฝๅ‡บ
245
+ raw_response = response.text
246
+
247
+ # HTMLใ‚ฟใ‚ฐ้ƒจๅˆ†ใ ใ‘ใ‚’ๆŠฝๅ‡บ๏ผˆ```html ใจ ``` ใฎ้–“๏ผ‰
248
+ html_start = raw_response.find("```html")
249
+ html_end = raw_response.rfind("```")
250
+
251
+ if html_start != -1 and html_end != -1 and html_start < html_end:
252
+ html_start += 7 # "```html" ใฎ้•ทใ•ๅˆ†้€ฒใ‚ใ‚‹
253
+ html_code = raw_response[html_start:html_end].strip()
254
+ logger.info(f"HTMLใฎ็”ŸๆˆใซๆˆๅŠŸ: ้•ทใ• = {len(html_code)}")
255
+
256
+ # Font Awesomeใฎใƒฌใ‚คใ‚ขใ‚ฆใƒˆๆ”นๅ–„
257
+ html_code = enhance_font_awesome_layout(html_code)
258
+ logger.info("Font Awesomeใƒฌใ‚คใ‚ขใ‚ฆใƒˆใฎๆœ€้ฉๅŒ–ใ‚’้ฉ็”จใ—ใพใ—ใŸ")
259
+
260
+ return html_code
261
+ else:
262
+ # HTMLใ‚ฟใ‚ฐใŒ่ฆ‹ใคใ‹ใ‚‰ใชใ„ๅ ดๅˆใ€ใƒฌใ‚นใƒใƒณใ‚นๅ…จไฝ“ใ‚’่ฟ”ใ™
263
+ logger.warning("ใƒฌใ‚นใƒใƒณใ‚นใ‹ใ‚‰ ```html ``` ใ‚ฟใ‚ฐใŒ่ฆ‹ใคใ‹ใ‚Šใพใ›ใ‚“ใงใ—ใŸใ€‚ๅ…จใƒ†ใ‚ญใ‚นใƒˆใ‚’่ฟ”ใ—ใพใ™ใ€‚")
264
+ return raw_response
265
+
266
  except Exception as e:
267
+ logger.error(f"HTML็”Ÿๆˆไธญใซใ‚จใƒฉใƒผใŒ็™บ็”Ÿ: {e}", exc_info=True)
268
+ raise Exception(f"Gemini APIใงใฎHTML็”Ÿๆˆใซๅคฑๆ•—ใ—ใพใ—ใŸ: {e}")
269
+
270
+ # ็”ปๅƒใ‹ใ‚‰ไฝ™ๅˆ†ใช็ฉบ็™ฝ้ ˜ๅŸŸใ‚’ใƒˆใƒชใƒŸใƒณใ‚ฐใ™ใ‚‹้–ขๆ•ฐ
271
+ def trim_image_whitespace(image, threshold=250, padding=10):
272
+ """
273
+ ็”ปๅƒใ‹ใ‚‰ไฝ™ๅˆ†ใช็™ฝใ„็ฉบ็™ฝใ‚’ใƒˆใƒชใƒŸใƒณใ‚ฐใ™ใ‚‹
274
+
275
+ Args:
276
+ image: PIL.Image - ๅ…ฅๅŠ›็”ปๅƒ
277
+ threshold: int - ใฉใฎๆ˜Žใ‚‹ใ•ไปฅไธŠใ‚’็ฉบ็™ฝใจๅˆคๆ–ญใ™ใ‚‹ใ‹ (0-255)
278
+ padding: int - ใƒˆใƒชใƒŸใƒณใ‚ฐๅพŒใซๆฎ‹ใ™ไฝ™็™ฝใฎใƒ”ใ‚ฏใ‚ปใƒซๆ•ฐ
279
+
280
+ Returns:
281
+ ใƒˆใƒชใƒŸใƒณใ‚ฐใ•ใ‚ŒใŸPIL.Image
282
+ """
283
+ # ใ‚ฐใƒฌใƒผใ‚นใ‚ฑใƒผใƒซใซๅค‰ๆ›
284
+ gray = image.convert('L')
285
+
286
+ # ใƒ”ใ‚ฏใ‚ปใƒซใƒ‡ใƒผใ‚ฟใ‚’้…ๅˆ—ใจใ—ใฆๅ–ๅพ—
287
  data = gray.getdata()
288
+ width, height = gray.size
289
+
290
+ # ๆœ‰ๅŠน็ฏ„ๅ›ฒใ‚’่ฆ‹ใคใ‘ใ‚‹
291
+ min_x, min_y = width, height
292
+ max_x = max_y = 0
293
+
294
+ # ใƒ”ใ‚ฏใ‚ปใƒซใƒ‡ใƒผใ‚ฟใ‚’2ๆฌกๅ…ƒ้…ๅˆ—ใซๅค‰ๆ›ใ—ใฆๅ‡ฆ็†
295
  pixels = list(data)
296
+ pixels = [pixels[i * width:(i + 1) * width] for i in range(height)]
297
+
298
+ # ๅ„่กŒใ‚’ใ‚นใ‚ญใƒฃใƒณใ—ใฆ้ž็ฉบ็™ฝใƒ”ใ‚ฏใ‚ปใƒซใ‚’่ฆ‹ใคใ‘ใ‚‹
299
+ for y in range(height):
300
+ for x in range(width):
301
+ if pixels[y][x] < threshold: # ้ž็ฉบ็™ฝใƒ”ใ‚ฏใ‚ปใƒซ
302
+ min_x = min(min_x, x)
303
+ min_y = min(min_y, y)
304
+ max_x = max(max_x, x)
305
+ max_y = max(max_y, y)
306
+
307
+ # ๅขƒ็•Œๅค–ใฎใƒˆใƒชใƒŸใƒณใ‚ฐใฎๅ ดๅˆใฏใ‚จใƒฉใƒผ
308
+ if min_x > max_x or min_y > max_y:
309
+ logger.warning("ใƒˆใƒชใƒŸใƒณใ‚ฐ้ ˜ๅŸŸใŒ่ฆ‹ใคใ‹ใ‚Šใพใ›ใ‚“ใ€‚ๅ…ƒใฎ็”ปๅƒใ‚’่ฟ”ใ—ใพใ™ใ€‚")
310
  return image
311
+
312
+ # ใƒ‘ใƒ‡ใ‚ฃใƒณใ‚ฐใ‚’่ฟฝๅŠ 
313
+ min_x = max(0, min_x - padding)
314
+ min_y = max(0, min_y - padding)
315
+ max_x = min(width - 1, max_x + padding)
316
+ max_y = min(height - 1, max_y + padding)
317
+
318
+ # ็”ปๅƒใ‚’ใƒˆใƒชใƒŸใƒณใ‚ฐ
319
+ trimmed = image.crop((min_x, min_y, max_x + 1, max_y + 1))
320
+
321
+ logger.info(f"็”ปๅƒใ‚’ใƒˆใƒชใƒŸใƒณใ‚ฐใ—ใพใ—ใŸ: ๅ…ƒใ‚ตใ‚คใ‚บ {width}x{height} โ†’ ใƒˆใƒชใƒŸใƒณใ‚ฐๅพŒ {trimmed.width}x{trimmed.height}")
322
+ return trimmed
323
+
324
+ # ้žๅŒๆœŸใ‚นใ‚ฏใƒชใƒ—ใƒˆใ‚’ไฝฟใ‚ใšใ€ๅŒๆœŸ็š„ใชใ‚นใ‚ฏใƒชใƒ—ใƒˆใฎใฟไฝฟ็”จใ™ใ‚‹ๆ”นๅ–„็‰ˆ
325
+
326
+ def render_fullpage_screenshot(html_code: str, extension_percentage: float = 6.0,
327
+ trim_whitespace: bool = True) -> Image.Image:
328
+ """
329
+ Renders HTML code to a full-page screenshot using Selenium.
330
+
331
+ Args:
332
+ html_code: The HTML source code string.
333
+ extension_percentage: Percentage of extra space to add vertically.
334
+ trim_whitespace: Whether to trim excess whitespace from the image.
335
+
336
+ Returns:
337
+ A PIL Image object of the screenshot.
338
+ """
339
+ tmp_path = None
340
+ driver = None
341
+
342
+ # 1) Save HTML code to a temporary file
343
  try:
344
+ with tempfile.NamedTemporaryFile(suffix=".html", delete=False, mode='w', encoding='utf-8') as tmp_file:
345
+ tmp_path = tmp_file.name
346
+ tmp_file.write(html_code)
347
+ logger.info(f"HTML saved to temporary file: {tmp_path}")
348
+ except Exception as e:
349
+ logger.error(f"Error writing temporary HTML file: {e}")
350
+ return Image.new('RGB', (1, 1), color=(0, 0, 0))
351
+
352
+ # 2) Headless Chrome(Chromium) options
353
+ options = Options()
354
+ options.add_argument("--headless")
355
+ options.add_argument("--no-sandbox")
356
+ options.add_argument("--disable-dev-shm-usage")
357
+ options.add_argument("--force-device-scale-factor=1")
358
+ options.add_argument("--disable-features=NetworkService")
359
+ options.add_argument("--dns-prefetch-disable")
360
+ # ็’ฐๅขƒๅค‰ๆ•ฐใ‹ใ‚‰WebDriverใƒ‘ใ‚นใ‚’ๅ–ๅพ—๏ผˆไปปๆ„๏ผ‰
361
+ webdriver_path = os.environ.get("CHROMEDRIVER_PATH")
362
+ if webdriver_path and os.path.exists(webdriver_path):
363
+ logger.info(f"Using CHROMEDRIVER_PATH: {webdriver_path}")
364
+ service = webdriver.ChromeService(executable_path=webdriver_path)
365
+ else:
366
+ logger.info("CHROMEDRIVER_PATH not set or invalid, using default PATH lookup.")
367
+ service = None # Use default behavior
368
 
369
+ try:
370
+ logger.info("Initializing WebDriver...")
371
+ if service:
372
+ driver = webdriver.Chrome(service=service, options=options)
373
+ else:
374
+ driver = webdriver.Chrome(options=options)
375
+ logger.info("WebDriver initialized.")
376
+
377
+ # 3) ๅˆๆœŸใ‚ฆใ‚ฃใƒณใƒ‰ใ‚ฆใ‚ตใ‚คใ‚บใ‚’่จญๅฎš
378
+ initial_width = 1200
379
+ initial_height = 1000
380
+ driver.set_window_size(initial_width, initial_height)
381
+ file_url = "file://" + tmp_path
382
+ logger.info(f"Navigating to {file_url}")
383
+ driver.get(file_url)
384
+
385
+ # 4) ใƒšใƒผใ‚ธ่ชญใฟ่พผใฟๅพ…ๆฉŸ
386
+ logger.info("Waiting for body element...")
387
  WebDriverWait(driver, 15).until(
388
  EC.presence_of_element_located((By.TAG_NAME, "body"))
389
  )
390
+ logger.info("Body element found. Waiting for resource loading...")
391
+
392
+ # 5) ๅŸบๆœฌ็š„ใชใƒชใ‚ฝใƒผใ‚น่ชญใฟ่พผใฟๅพ…ๆฉŸ - ใ‚ฟใ‚คใƒ ใ‚ขใ‚ฆใƒˆๅ›ž้ฟ
393
+ time.sleep(3)
394
+
395
+ # Font Awesome่ชญใฟ่พผใฟ็ขบ่ช - ้žๅŒๆœŸใ‚’ไฝฟใ‚ใชใ„
396
+ logger.info("Checking for Font Awesome resources...")
397
+ fa_count = driver.execute_script("""
398
+ var icons = document.querySelectorAll('.fa, .fas, .far, .fab, [class*="fa-"]');
399
+ return icons.length;
400
+ """)
401
+ logger.info(f"Found {fa_count} Font Awesome elements")
402
+
403
+ # ใƒชใ‚ฝใƒผใ‚น่ชญใฟ่พผใฟ็Šถๆ…‹ใ‚’็ขบ่ช
404
+ doc_ready = driver.execute_script("return document.readyState;")
405
+ logger.info(f"Document ready state: {doc_ready}")
406
+
407
+ # Font AwesomeใŒๅคšใ„ๅ ดๅˆใฏ่ฟฝๅŠ ๅพ…ๆฉŸ
408
+ if fa_count > 50:
409
+ logger.info("Many Font Awesome icons detected, waiting additional time")
410
+ time.sleep(2)
411
+
412
+ # 6) ใ‚ณใƒณใƒ†ใƒณใƒ„ใƒฌใƒณใƒ€ใƒชใƒณใ‚ฐใฎใŸใ‚ใฎใ‚นใ‚ฏใƒญใƒผใƒซๅ‡ฆ็† - ๅŒๆœŸ็š„ใซๅฎŸ่กŒ
413
+ logger.info("Performing content rendering scroll...")
414
+ total_height = driver.execute_script("return Math.max(document.body.scrollHeight, document.documentElement.scrollHeight);")
415
+ viewport_height = driver.execute_script("return window.innerHeight;")
416
+ scrolls_needed = max(1, total_height // viewport_height)
417
+
418
+ for i in range(scrolls_needed + 1):
419
+ scroll_pos = i * (viewport_height - 200) # ใ‚ชใƒผใƒใƒผใƒฉใƒƒใƒ—ใ•ใ›ใ‚‹
420
+ driver.execute_script(f"window.scrollTo(0, {scroll_pos});")
421
+ time.sleep(0.2) # ็Ÿญใ„ๅพ…ๆฉŸ
422
+
423
+ # ใƒˆใƒƒใƒ—ใซๆˆปใ‚‹
424
+ driver.execute_script("window.scrollTo(0, 0);")
425
+ time.sleep(0.5)
426
+ logger.info("Scroll rendering completed")
427
+
428
+ # 7) ใ‚นใ‚ฏใƒญใƒผใƒซใƒใƒผใ‚’้ž่กจ็คบใซ
429
+ driver.execute_script("""
430
+ document.documentElement.style.overflow = 'hidden';
431
+ document.body.style.overflow = 'hidden';
432
+ """)
433
+ logger.info("Scrollbars hidden")
434
+
435
+ # 8) ใƒšใƒผใ‚ธใฎๅฏธๆณ•ใ‚’ๅ–ๅพ—
436
+ dimensions = driver.execute_script("""
437
+ return {
438
+ width: Math.max(
439
+ document.documentElement.scrollWidth,
440
+ document.documentElement.offsetWidth,
441
+ document.documentElement.clientWidth,
442
+ document.body ? document.body.scrollWidth : 0,
443
+ document.body ? document.body.offsetWidth : 0,
444
+ document.body ? document.body.clientWidth : 0
445
+ ),
446
+ height: Math.max(
447
+ document.documentElement.scrollHeight,
448
+ document.documentElement.offsetHeight,
449
+ document.documentElement.clientHeight,
450
+ document.body ? document.body.scrollHeight : 0,
451
+ document.body ? document.body.offsetHeight : 0,
452
+ document.body ? document.body.clientHeight : 0
453
+ )
454
+ };
455
+ """)
456
+ scroll_width = dimensions['width']
457
+ scroll_height = dimensions['height']
458
+ logger.info(f"Detected dimensions: width={scroll_width}, height={scroll_height}")
459
+
460
+ # ๅ†ๆคœ่จผ - ็Ÿญใ„ใ‚นใ‚ฏใƒญใƒผใƒซใงๅ†็ขบ่ช
461
+ driver.execute_script("window.scrollTo(0, document.body.scrollHeight);")
462
+ time.sleep(0.5)
463
+ driver.execute_script("window.scrollTo(0, 0);")
464
+ time.sleep(0.5)
465
 
466
+ dimensions_after = driver.execute_script("return {height: Math.max(document.documentElement.scrollHeight, document.body.scrollHeight)};")
467
+ scroll_height = max(scroll_height, dimensions_after['height'])
468
+ logger.info(f"After scroll check, height={scroll_height}")
469
+
470
+ # ๆœ€ๅฐ/ๆœ€ๅคงๅ€คใฎ่จญๅฎš
471
+ scroll_width = max(scroll_width, 100)
472
+ scroll_height = max(scroll_height, 100)
473
+ scroll_width = min(scroll_width, 2000)
474
+ scroll_height = min(scroll_height, 4000)
475
+
476
+ # 9) ใƒฌใ‚คใ‚ขใ‚ฆใƒˆๅฎ‰ๅฎšๅŒ–ใฎใŸใ‚ใฎๅ˜็ด”ใชๅพ…ๆฉŸ - ใ‚ฟใ‚คใƒ ใ‚ขใ‚ฆใƒˆๅ›ž้ฟ
477
+ logger.info("Waiting for layout stabilization...")
478
+ time.sleep(2)
479
+
480
+ # 10) ้ซ˜ใ•ใซไฝ™็™ฝใ‚’่ฟฝๅŠ 
481
+ adjusted_height = int(scroll_height * (1 + extension_percentage / 100.0))
482
+ adjusted_height = max(adjusted_height, scroll_height, 100)
483
+ logger.info(f"Adjusted height calculated: {adjusted_height} (extension: {extension_percentage}%)")
484
+
485
+ # 11) ใ‚ฆใ‚ฃใƒณใƒ‰ใ‚ฆใ‚ตใ‚คใ‚บใ‚’่ชฟๆ•ด
486
+ adjusted_width = scroll_width
487
+ logger.info(f"Resizing window to: width={adjusted_width}, height={adjusted_height}")
488
+ driver.set_window_size(adjusted_width, adjusted_height)
489
  time.sleep(1)
490
 
491
+ # ใƒชใ‚ฝใƒผใ‚น็Šถๆ…‹ใ‚’็ขบ่ช - ๅŒๆœŸ็š„ใ‚นใ‚ฏใƒชใƒ—ใƒˆ
492
+ resource_state = driver.execute_script("""
493
+ return {
494
+ readyState: document.readyState,
495
+ resourcesComplete: !document.querySelector('img:not([complete])') &&
496
+ !document.querySelector('link[rel="stylesheet"]:not([loaded])')
497
+ };
498
+ """)
499
+ logger.info(f"Resource state: {resource_state}")
500
+
501
+ if resource_state['readyState'] != 'complete':
502
+ logger.info("Document still loading, waiting additional time...")
503
+ time.sleep(1)
504
+
505
+ # ใƒˆใƒƒใƒ—ใซใ‚นใ‚ฏใƒญใƒผใƒซ
506
+ driver.execute_script("window.scrollTo(0, 0);")
507
  time.sleep(0.5)
508
+ logger.info("Scrolled to top.")
509
 
510
+ # 12) ใ‚นใ‚ฏใƒชใƒผใƒณใ‚ทใƒงใƒƒใƒˆๅ–ๅพ—
511
+ logger.info("Taking screenshot...")
512
  png = driver.get_screenshot_as_png()
513
+ logger.info("Screenshot taken successfully.")
514
+
515
+ # PIL็”ปๅƒใซๅค‰ๆ›
516
  img = Image.open(BytesIO(png))
517
+ logger.info(f"Screenshot dimensions: {img.width}x{img.height}")
518
+
519
+ # ไฝ™็™ฝใƒˆใƒชใƒŸใƒณใ‚ฐ
520
  if trim_whitespace:
521
  img = trim_image_whitespace(img, threshold=248, padding=20)
522
+ logger.info(f"Trimmed dimensions: {img.width}x{img.height}")
523
+
524
  return img
525
+
526
  except Exception as e:
527
+ logger.error(f"Error during screenshot generation: {e}", exc_info=True)
528
+ # Return a small black image on error
529
+ return Image.new('RGB', (1, 1), color=(0, 0, 0))
530
  finally:
531
+ logger.info("Cleaning up...")
532
  if driver:
533
  try:
534
  driver.quit()
535
+ logger.info("WebDriver quit successfully.")
536
+ except Exception as e:
537
+ logger.error(f"Error quitting WebDriver: {e}", exc_info=True)
538
  if tmp_path and os.path.exists(tmp_path):
539
+ try:
540
+ os.remove(tmp_path)
541
+ logger.info(f"Temporary file {tmp_path} removed.")
542
+ except Exception as e:
543
+ logger.error(f"Error removing temporary file {tmp_path}: {e}", exc_info=True)
544
+
545
+ # --- Geminiใ‚’ไฝฟใฃใŸๆ–ฐใ—ใ„้–ขๆ•ฐ ---
546
+ def text_to_screenshot(text: str, extension_percentage: float, temperature: float = 0.3,
547
+ trim_whitespace: bool = True, style: str = "standard") -> Image.Image:
548
+ """ใƒ†ใ‚ญใ‚นใƒˆใ‚’Gemini APIใงHTMLใซๅค‰ๆ›ใ—ใ€ใ‚นใ‚ฏใƒชใƒผใƒณใ‚ทใƒงใƒƒใƒˆใ‚’็”Ÿๆˆใ™ใ‚‹็ตฑๅˆ้–ขๆ•ฐ"""
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
549
  try:
550
+ # 1. ใƒ†ใ‚ญใ‚นใƒˆใ‹ใ‚‰HTMLใ‚’็”Ÿๆˆ๏ผˆๆธฉๅบฆใƒ‘ใƒฉใƒกใƒผใ‚ฟใจใ‚นใ‚ฟใ‚คใƒซใ‚‚ๆธกใ™๏ผ‰
551
+ html_code = generate_html_from_text(text, temperature, style)
 
 
 
552
 
553
+ # 2. HTMLใ‹ใ‚‰ใ‚นใ‚ฏใƒชใƒผใƒณใ‚ทใƒงใƒƒใƒˆใ‚’็”Ÿๆˆ
554
+ return render_fullpage_screenshot(html_code, extension_percentage, trim_whitespace)
555
+ except Exception as e:
556
+ logger.error(f"ใƒ†ใ‚ญใ‚นใƒˆใ‹ใ‚‰ใ‚นใ‚ฏใƒชใƒผใƒณใ‚ทใƒงใƒƒใƒˆ็”Ÿๆˆไธญใซใ‚จใƒฉใƒผใŒ็™บ็”Ÿ: {e}", exc_info=True)
557
+ return Image.new('RGB', (1, 1), color=(0, 0, 0)) # ใ‚จใƒฉใƒผๆ™‚ใฏ้ป’็”ปๅƒ
558
 
559
+ # --- FastAPI Setup ---
 
 
560
  app = FastAPI()
561
+
562
+ # CORS่จญๅฎšใ‚’่ฟฝๅŠ 
563
  app.add_middleware(
564
  CORSMiddleware,
565
  allow_origins=["*"],
 
568
  allow_headers=["*"],
569
  )
570
 
571
+ # ้™็š„ใƒ•ใ‚กใ‚คใƒซใฎใ‚ตใƒผใƒ“ใƒณใ‚ฐ่จญๅฎš
572
+ # Gradioใฎใƒ‡ใ‚ฃใƒฌใ‚ฏใƒˆใƒชใ‚’ๆŽข็ดขใ—ใฆใ‚ขใ‚ปใƒƒใƒˆใ‚’่ฆ‹ใคใ‘ใ‚‹
573
  gradio_dir = os.path.dirname(gr.__file__)
574
+ logger.info(f"Gradio version: {gr.__version__}")
575
+ logger.info(f"Gradio directory: {gradio_dir}")
576
+
577
+ # ๅŸบๆœฌ็š„ใช้™็š„ใƒ•ใ‚กใ‚คใƒซใƒ‡ใ‚ฃใƒฌใ‚ฏใƒˆใƒชใ‚’ใƒžใ‚ฆใƒณใƒˆ
578
+ static_dir = os.path.join(gradio_dir, "templates", "frontend", "static")
579
+ if os.path.exists(static_dir):
580
+ logger.info(f"Mounting static directory: {static_dir}")
581
+ app.mount("/static", StaticFiles(directory=static_dir), name="static")
582
+
583
+ # _appใƒ‡ใ‚ฃใƒฌใ‚ฏใƒˆใƒชใ‚’ๆŽขใ™๏ผˆๆ–ฐใ—ใ„SvelteKitใƒ™ใƒผใ‚นใฎใƒ•ใƒญใƒณใƒˆใ‚จใƒณใƒ‰็”จ๏ผ‰
584
+ app_dir = os.path.join(gradio_dir, "templates", "frontend", "_app")
585
+ if os.path.exists(app_dir):
586
+ logger.info(f"Mounting _app directory: {app_dir}")
587
+ app.mount("/_app", StaticFiles(directory=app_dir), name="_app")
588
+
589
+ # assetsใƒ‡ใ‚ฃใƒฌใ‚ฏใƒˆใƒชใ‚’ๆŽขใ™
590
+ assets_dir = os.path.join(gradio_dir, "templates", "frontend", "assets")
591
+ if os.path.exists(assets_dir):
592
+ logger.info(f"Mounting assets directory: {assets_dir}")
593
+ app.mount("/assets", StaticFiles(directory=assets_dir), name="assets")
594
+
595
+ # cdnใƒ‡ใ‚ฃใƒฌใ‚ฏใƒˆใƒชใŒใ‚ใ‚Œใฐ่ฟฝๅŠ 
596
+ cdn_dir = os.path.join(gradio_dir, "templates", "cdn")
597
+ if os.path.exists(cdn_dir):
598
+ logger.info(f"Mounting cdn directory: {cdn_dir}")
599
+ app.mount("/cdn", StaticFiles(directory=cdn_dir), name="cdn")
600
+
601
+
602
+ # API Endpoint for screenshot generation
603
+ @app.post("/api/screenshot",
604
+ response_class=StreamingResponse,
605
+ tags=["Screenshot"],
606
+ summary="Render HTML to Full Page Screenshot",
607
+ description="Takes HTML code and an optional vertical extension percentage, renders it using a headless browser, and returns the full-page screenshot as a PNG image.")
608
+ async def api_render_screenshot(request: ScreenshotRequest):
609
+ """
610
+ API endpoint to render HTML and return a screenshot.
611
+ """
612
+ try:
613
+ logger.info(f"API request received. Extension: {request.extension_percentage}%")
614
+ # Run the blocking Selenium code in a separate thread (FastAPI handles this)
615
+ pil_image = render_fullpage_screenshot(
616
+ request.html_code,
617
+ request.extension_percentage,
618
+ request.trim_whitespace
619
+ )
620
 
621
+ if pil_image.size == (1, 1):
622
+ logger.error("Screenshot generation failed, returning 1x1 error image.")
623
+ # Optionally return a proper error response instead of 1x1 image
624
+ # raise HTTPException(status_code=500, detail="Failed to generate screenshot")
625
 
626
+ # Convert PIL Image to PNG bytes
627
+ img_byte_arr = BytesIO()
628
+ pil_image.save(img_byte_arr, format='PNG')
629
+ img_byte_arr.seek(0) # Go to the start of the BytesIO buffer
630
+
631
+ logger.info("Returning screenshot as PNG stream.")
632
+ return StreamingResponse(img_byte_arr, media_type="image/png")
633
+
634
+ except Exception as e:
635
+ logger.error(f"API Error: {e}", exc_info=True)
636
+ raise HTTPException(status_code=500, detail=f"Internal Server Error: {e}")
637
+
638
+ # --- ๆ–ฐใ—ใ„Gemini API้€ฃๆบใ‚จใƒณใƒ‰ใƒใ‚คใƒณใƒˆ ---
639
+ @app.post("/api/text-to-screenshot",
640
+ response_class=StreamingResponse,
641
+ tags=["Screenshot", "Gemini"],
642
+ summary="ใƒ†ใ‚ญใ‚นใƒˆใ‹ใ‚‰ใ‚คใƒณใƒ•ใ‚ฉใ‚ฐใƒฉใƒ•ใ‚ฃใƒƒใ‚ฏใ‚’็”Ÿๆˆ",
643
+ description="ใƒ†ใ‚ญใ‚นใƒˆใ‚’Gemini APIใ‚’ไฝฟใฃใฆHTMLใ‚คใƒณใƒ•ใ‚ฉใ‚ฐใƒฉใƒ•ใ‚ฃใƒƒใ‚ฏใซๅค‰ๆ›ใ—ใ€ใ‚นใ‚ฏใƒชใƒผใƒณใ‚ทใƒงใƒƒใƒˆใจใ—ใฆ่ฟ”ใ—ใพใ™ใ€‚")
644
+ async def api_text_to_screenshot(request: GeminiRequest):
645
+ """
646
+ ใƒ†ใ‚ญใ‚นใƒˆใ‹ใ‚‰HTMLใ‚คใƒณใƒ•ใ‚ฉใ‚ฐใƒฉใƒ•ใ‚ฃใƒƒใ‚ฏใ‚’็”Ÿๆˆใ—ใฆใ‚นใ‚ฏใƒชใƒผใƒณใ‚ทใƒงใƒƒใƒˆใ‚’่ฟ”ใ™APIใ‚จใƒณใƒ‰ใƒใ‚คใƒณใƒˆ
647
+ """
648
+ try:
649
+ logger.info(f"ใƒ†ใ‚ญใ‚นใƒˆโ†’ใ‚นใ‚ฏใƒชใƒผใƒณใ‚ทใƒงใƒƒใƒˆAPIใƒชใ‚ฏใ‚จใ‚นใƒˆๅ—ไฟกใ€‚ใƒ†ใ‚ญใ‚นใƒˆ้•ทใ•: {len(request.text)}, "
650
+ f"ๆ‹กๅผต็އ: {request.extension_percentage}%, ๆธฉๅบฆ: {request.temperature}, "
651
+ f"ใ‚นใ‚ฟใ‚คใƒซ: {request.style}")
652
+
653
+ # ใƒ†ใ‚ญใ‚นใƒˆใ‹ใ‚‰HTMLใ‚’็”Ÿๆˆใ—ใฆใ‚นใ‚ฏใƒชใƒผใƒณใ‚ทใƒงใƒƒใƒˆใ‚’ไฝœๆˆ๏ผˆๆธฉๅบฆใƒ‘ใƒฉใƒกใƒผใ‚ฟใจใ‚นใ‚ฟใ‚คใƒซใ‚‚ๆธกใ™๏ผ‰
654
+ pil_image = text_to_screenshot(
655
+ request.text,
656
+ request.extension_percentage,
657
+ request.temperature,
658
+ request.trim_whitespace,
659
+ request.style
660
  )
661
+
662
+ if pil_image.size == (1, 1):
663
+ logger.error("ใ‚นใ‚ฏใƒชใƒผใƒณใ‚ทใƒงใƒƒใƒˆ็”Ÿๆˆใซๅคฑๆ•—ใ—ใพใ—ใŸใ€‚1x1ใ‚จใƒฉใƒผ็”ปๅƒใ‚’่ฟ”ใ—ใพใ™ใ€‚")
664
+ # raise HTTPException(status_code=500, detail="ใ‚นใ‚ฏใƒชใƒผใƒณใ‚ทใƒงใƒƒใƒˆ็”Ÿๆˆใซๅคฑๆ•—ใ—ใพใ—ใŸ")
665
 
666
 
667
+ # PIL็”ปๅƒใ‚’PNGใƒใ‚คใƒˆใซๅค‰ๆ›
668
+ img_byte_arr = BytesIO()
669
+ pil_image.save(img_byte_arr, format='PNG')
670
+ img_byte_arr.seek(0) # BytesIOใƒใƒƒใƒ•ใ‚กใฎๅ…ˆ้ ญใซๆˆปใ‚‹
671
+
672
+ logger.info("ใ‚นใ‚ฏใƒชใƒผใƒณใ‚ทใƒงใƒƒใƒˆใ‚’PNGใ‚นใƒˆใƒชใƒผใƒ ใจใ—ใฆ่ฟ”ใ—ใพใ™ใ€‚")
673
+ return StreamingResponse(img_byte_arr, media_type="image/png")
674
+
675
+ except Exception as e:
676
+ logger.error(f"API Error: {e}", exc_info=True)
677
+ raise HTTPException(status_code=500, detail=f"Internal Server Error: {e}")
678
+
679
+ # --- Gradio Interface Definition ---
680
+ # ๅ…ฅๅŠ›ใƒขใƒผใƒ‰ใฎ้ธๆŠž็”จRadioใ‚ณใƒณใƒใƒผใƒใƒณใƒˆ
681
+ def process_input(input_mode, input_text, extension_percentage, temperature, trim_whitespace, style):
682
+ """ๅ…ฅๅŠ›ใƒขใƒผใƒ‰ใซๅฟœใ˜ใฆ้ฉๅˆ‡ใชๅ‡ฆ็†ใ‚’่กŒใ†"""
683
+ if input_mode == "HTMLๅ…ฅๅŠ›":
684
+ # HTMLใƒขใƒผใƒ‰ใฎๅ ดๅˆใฏๆ—ขๅญ˜ใฎๅ‡ฆ็†๏ผˆใ‚นใ‚ฟใ‚คใƒซใฏไฝฟใ‚ใชใ„๏ผ‰
685
+ return render_fullpage_screenshot(input_text, extension_percentage, trim_whitespace)
686
+ else:
687
+ # ใƒ†ใ‚ญใ‚นใƒˆๅ…ฅๅŠ›ใƒขใƒผใƒ‰ใฎๅ ดๅˆใฏGemini APIใ‚’ไฝฟ็”จ
688
+ return text_to_screenshot(input_text, extension_percentage, temperature, trim_whitespace, style)
689
+
690
+ # Gradio UIใฎๅฎš็พฉ
691
+ with gr.Blocks(title="Full Page Screenshot (ใƒ†ใ‚ญใ‚นใƒˆๅค‰ๆ›ๅฏพๅฟœ)", theme=gr.themes.Base()) as iface:
692
+ gr.Markdown("# HTMLใƒ“ใƒฅใƒผใ‚ข & ใƒ†ใ‚ญใ‚นใƒˆโ†’ใ‚คใƒณใƒ•ใ‚ฉใ‚ฐใƒฉใƒ•ใ‚ฃใƒƒใ‚ฏๅค‰ๆ›")
693
+ gr.Markdown("HTMLใ‚ณใƒผใƒ‰ใ‚’ใƒฌใƒณใƒ€ใƒชใƒณใ‚ฐใ™ใ‚‹ใ‹ใ€ใƒ†ใ‚ญใ‚นใƒˆใ‚’Gemini APIใงใ‚คใƒณใƒ•ใ‚ฉใ‚ฐใƒฉใƒ•ใ‚ฃใƒƒใ‚ฏใซๅค‰ๆ›ใ—ใฆ็”ปๅƒใจใ—ใฆๅ–ๅพ—ใ—ใพใ™ใ€‚")
694
+
695
  with gr.Row():
696
+ input_mode = gr.Radio(
697
+ ["HTMLๅ…ฅๅŠ›", "ใƒ†ใ‚ญใ‚นใƒˆๅ…ฅๅŠ›"],
698
+ label="ๅ…ฅๅŠ›ใƒขใƒผใƒ‰",
699
+ value="HTMLๅ…ฅๅŠ›"
 
700
  )
 
 
 
 
 
 
 
 
 
 
 
 
701
 
702
+ # ๅ…ฑ็”จใฎใƒ†ใ‚ญใ‚นใƒˆใƒœใƒƒใ‚ฏใ‚น
703
+ input_text = gr.Textbox(
704
+ lines=15,
705
+ label="ๅ…ฅๅŠ›",
706
+ placeholder="HTMLใ‚ณใƒผใƒ‰ใพใŸใฏใƒ†ใ‚ญใ‚นใƒˆใ‚’ๅ…ฅๅŠ›ใ—ใฆใใ ใ•ใ„ใ€‚ๅ…ฅๅŠ›ใƒขใƒผใƒ‰ใซๅฟœใ˜ใฆๅ‡ฆ็†ใ•ใ‚Œใพใ™ใ€‚"
707
+ )
708
+
709
+ with gr.Row():
710
+ with gr.Column(scale=1):
711
+ # ใ‚นใ‚ฟใ‚คใƒซ้ธๆŠžใƒ‰ใƒญใƒƒใƒ—ใƒ€ใ‚ฆใƒณ
712
+ style_dropdown = gr.Dropdown(
713
+ choices=["standard", "cute", "resort", "cool", "dental"],
714
+ value="standard",
715
+ label="ใƒ‡ใ‚ถใ‚คใƒณใ‚นใ‚ฟใ‚คใƒซ",
716
+ info="ใƒ†ใ‚ญใ‚นใƒˆโ†’HTMLๅค‰ๆ›ๆ™‚ใฎใƒ‡ใ‚ถใ‚คใƒณใƒ†ใƒผใƒžใ‚’้ธๆŠžใ—ใพใ™",
717
+ visible=False # ใƒ†ใ‚ญใ‚นใƒˆๅ…ฅๅŠ›ใƒขใƒผใƒ‰ใฎๆ™‚ใ ใ‘่กจ็คบ
718
+ )
719
+
720
+ with gr.Column(scale=2):
721
+ extension_percentage = gr.Slider(
722
+ minimum=0,
723
+ maximum=30,
724
+ step=1.0,
725
+ value=10, # ใƒ‡ใƒ•ใ‚ฉใƒซใƒˆๅ€ค10%
726
+ label="ไธŠไธ‹้ซ˜ใ•ๆ‹กๅผต็އ๏ผˆ%๏ผ‰"
727
+ )
728
+
729
+ # ๆธฉๅบฆ่ชฟๆ•ดใ‚นใƒฉใ‚คใƒ€ใƒผ๏ผˆใƒ†ใ‚ญใ‚นใƒˆใƒขใƒผใƒ‰ๆ™‚ใฎใฟ่กจ็คบ๏ผ‰
730
+ temperature = gr.Slider(
731
+ minimum=0.0,
732
+ maximum=1.0,
733
+ step=0.1,
734
+ value=0.5, # ใƒ‡ใƒ•ใ‚ฉใƒซใƒˆๅ€คใ‚’0.5ใซ่จญๅฎš
735
+ label="็”Ÿๆˆๆ™‚ใฎๆธฉๅบฆ๏ผˆไฝŽใ„=ไธ€่ฒซๆ€ง้ซ˜ใ€้ซ˜ใ„=ๅ‰ต้€ ๆ€ง้ซ˜๏ผ‰",
736
+ visible=False # ๆœ€ๅˆใฏ้ž่กจ็คบ
737
+ )
738
+
739
+ # ไฝ™็™ฝใƒˆใƒชใƒŸใƒณใ‚ฐใ‚ชใƒ—ใ‚ทใƒงใƒณ
740
+ trim_whitespace = gr.Checkbox(
741
+ label="ไฝ™็™ฝใ‚’่‡ชๅ‹•ใƒˆใƒชใƒŸใƒณใ‚ฐ",
742
+ value=True,
743
+ info="็”Ÿๆˆใ•ใ‚Œใ‚‹็”ปๅƒใ‹ใ‚‰ไฝ™ๅˆ†ใช็ฉบ็™ฝ้ ˜ๅŸŸใ‚’่‡ชๅ‹•็š„ใซๅ‰Š้™คใ—ใพใ™"
744
+ )
745
+
746
+ submit_btn = gr.Button("็”Ÿๆˆ")
747
+ output_image = gr.Image(type="pil", label="ใƒšใƒผใ‚ธๅ…จไฝ“ใฎใ‚นใ‚ฏใƒชใƒผใƒณใ‚ทใƒงใƒƒใƒˆ")
748
+
749
+ # ๅ…ฅๅŠ›ใƒขใƒผใƒ‰ๅค‰ๆ›ดๆ™‚ใฎใ‚คใƒ™ใƒณใƒˆๅ‡ฆ็†๏ผˆใƒ†ใ‚ญใ‚นใƒˆใƒขใƒผใƒ‰ๆ™‚ใฎใฟๆธฉๅบฆใ‚นใƒฉใ‚คใƒ€ใƒผใจใ‚นใ‚ฟใ‚คใƒซใƒ‰ใƒญใƒƒใƒ—ใƒ€ใ‚ฆใƒณใ‚’่กจ็คบ๏ผ‰
750
+ def update_controls_visibility(mode):
751
+ # Gradio 4.x็”จใฎใ‚ขใƒƒใƒ—ใƒ‡ใƒผใƒˆๆ–นๆณ•
752
+ is_text_mode = mode == "ใƒ†ใ‚ญใ‚นใƒˆๅ…ฅๅŠ›"
753
  return [
754
+ gr.update(visible=is_text_mode), # temperature
755
+ gr.update(visible=is_text_mode), # style_dropdown
756
  ]
757
 
758
+ input_mode.change(
759
+ fn=update_controls_visibility,
760
+ inputs=input_mode,
761
+ outputs=[temperature, style_dropdown]
 
 
 
 
 
 
 
 
762
  )
763
 
764
+ # ็”Ÿๆˆใƒœใ‚ฟใƒณใ‚ฏใƒชใƒƒใ‚ฏๆ™‚ใฎใ‚คใƒ™ใƒณใƒˆๅ‡ฆ็†
765
+ submit_btn.click(
766
+ fn=process_input,
767
+ inputs=[input_mode, input_text, extension_percentage, temperature, trim_whitespace, style_dropdown],
768
+ outputs=output_image
 
769
  )
770
 
771
+ # ็’ฐๅขƒๅค‰ๆ•ฐๆƒ…ๅ ฑใ‚’่กจ็คบ
772
+ gemini_model = os.environ.get("GEMINI_MODEL", "gemini-1.5-pro")
773
+ gr.Markdown(f"""
774
+ ## APIใ‚จใƒณใƒ‰ใƒใ‚คใƒณใƒˆ
775
+ - `/api/screenshot` - HTMLใ‚ณใƒผใƒ‰ใ‹ใ‚‰ใ‚นใ‚ฏใƒชใƒผใƒณใ‚ทใƒงใƒƒใƒˆใ‚’็”Ÿๆˆ
776
+ - `/api/text-to-screenshot` - ใƒ†ใ‚ญใ‚นใƒˆใ‹ใ‚‰ใ‚คใƒณใƒ•ใ‚ฉใ‚ฐใƒฉใƒ•ใ‚ฃใƒƒใ‚ฏใ‚นใ‚ฏใƒชใƒผใƒณใ‚ทใƒงใƒƒใƒˆใ‚’็”Ÿๆˆ
777
+
778
+ ## ่จญๅฎšๆƒ…ๅ ฑ
779
+ - ไฝฟ็”จใƒขใƒ‡ใƒซ: {gemini_model} (็’ฐๅขƒๅค‰ๆ•ฐ GEMINI_MODEL ใงๅค‰ๆ›ดๅฏ่ƒฝ)
780
+ - ๅฏพๅฟœใ‚นใ‚ฟใ‚คใƒซ: standard, cute, resort, cool, dental
781
+ """)
782
+
783
+ # --- Mount Gradio App onto FastAPI ---
784
  app = gr.mount_gradio_app(app, iface, path="/")
785
 
786
+ # --- Run with Uvicorn (for local testing) ---
 
 
787
  if __name__ == "__main__":
788
  import uvicorn
789
+ logger.info("Starting Uvicorn server for local development...")
790
+ uvicorn.run(app, host="0.0.0.0", port=7860)
 
requirements.txt CHANGED
@@ -1,7 +1,11 @@
 
 
1
  selenium
2
- gradio==5.25.2
3
  Pillow
4
  fastapi
5
  uvicorn[standard]
6
- google-genai>=1.11.0
7
  huggingface_hub
 
 
 
1
+ # --- START OF FILE requirements.txt ---
2
+
3
  selenium
4
+ gradio==4.19.2
5
  Pillow
6
  fastapi
7
  uvicorn[standard]
8
+ google-generativeai
9
  huggingface_hub
10
+
11
+ # --- END OF FILE requirements.txt ---