tomo2chin2 commited on
Commit
350e08a
ยท
verified ยท
1 Parent(s): 3bd9c3f

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +383 -700
app.py CHANGED
@@ -1,5 +1,28 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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,556 +33,303 @@ from selenium.webdriver.common.by import By
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,223 +338,136 @@ app.add_middleware(
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)
 
 
1
+
2
+ """
3
+ Fullโ€‘page HTML renderer & Gemini 2.5 Flash textโ€‘toโ€‘infographic generator
4
+ โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€
5
+ * Gradio 5.x UI + FastAPI backend
6
+ * Seleniumโ€‘Chrome headless fullโ€‘page screenshot
7
+ * Gemini 1.5โ€‘pro ใ€œ 2.5โ€‘flashโ€‘previewโ€‘04โ€‘17 ๅฏพๅฟœ
8
+ โ€‘ 2.5โ€‘flash ใฎใจใใ ใ‘ thinking_budget=0 ใ‚’่‡ชๅ‹•ไป˜ไธŽ
9
+ """
10
+
11
+ # โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€
12
+ # ๅŸบๆœฌใƒฉใ‚คใƒ–ใƒฉใƒช
13
+ # โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€
14
+ import os
15
+ import time
16
+ import tempfile
17
+ import logging
18
+ from io import BytesIO
19
+ from typing import List, Optional
20
+
21
+ # โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€
22
+ # ใ‚ตใƒผใƒ‰ใƒ‘ใƒผใƒ†ใ‚ฃ
23
+ # โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€
24
  import gradio as gr
25
+ from fastapi import FastAPI, HTTPException
26
  from fastapi.responses import StreamingResponse
27
  from fastapi.staticfiles import StaticFiles
28
  from fastapi.middleware.cors import CORSMiddleware
 
33
  from selenium.webdriver.support.ui import WebDriverWait
34
  from selenium.webdriver.support import expected_conditions as EC
35
  from PIL import Image
36
+ from huggingface_hub import hf_hub_download
 
 
 
 
 
37
 
38
+ # โ–ถ ๆ–ฐใ—ใ„ Gemini SDK
39
+ from google import genai # googleโ€‘genai โ‰ฅ1.11.0
40
+ from google.genai import types # ๅž‹ใ‚ชใƒ–ใ‚ธใ‚งใ‚ฏใƒˆ
41
 
42
+ # โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€
43
  # ใƒญใ‚ฎใƒณใ‚ฐ่จญๅฎš
44
+ # โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€
45
  logging.basicConfig(level=logging.INFO)
46
  logger = logging.getLogger(__name__)
47
 
48
+ # โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€
49
+ # Pydantic ใƒขใƒ‡ใƒซ
50
+ # โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€
51
  class GeminiRequest(BaseModel):
 
52
  text: str
53
+ extension_percentage: float = 10.0
54
+ temperature: float = 0.5
55
+ trim_whitespace: bool = True
56
+ style: str = "standard"
57
+
58
 
59
  class ScreenshotRequest(BaseModel):
 
60
  html_code: str
61
+ extension_percentage: float = 10.0
62
+ trim_whitespace: bool = True
63
+ style: str = "standard"
64
+
65
+
66
+ # โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€
67
+ # โ‘  Font Awesome ใƒฌใ‚คใ‚ขใ‚ฆใƒˆ่ชฟๆ•ด
68
+ # โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€
69
+ def enhance_font_awesome_layout(html_code: str) -> str:
70
+ """Font Awesome ใ‚ขใ‚คใ‚ณใƒณใฎ่กจ็คบใ‚บใƒฌใ‚’ไฟฎๆญฃใ™ใ‚‹่ฟฝๅŠ  CSS ใ‚’ๆŒฟๅ…ฅ"""
71
  fa_fix_css = """
72
  <style>
73
+ /* Font Awesome icon tweaks */
74
+ [class*="fa-"]{
75
+ display:inline-block!important;
76
+ vertical-align:middle!important;
77
+ margin-right:8px!important;
78
  }
79
+ h1 [class*="fa-"],h2 [class*="fa-"],h3 [class*="fa-"],
80
+ h4 [class*="fa-"],h5 [class*="fa-"],h6 [class*="fa-"]{
81
+ margin-right:10px!important;
 
 
 
82
  }
83
+ .fa+span,.fas+span,.far+span,.fab+span,
84
+ span+.fa,span+.fas,span+.far,span+.fab{
85
+ display:inline-block!important;margin-left:5px!important;
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
86
  }
87
+ li [class*="fa-"],p [class*="fa-"]{margin-right:10px!important;}
88
+ .inline-icon{display:inline-flex!important;align-items:center!important;}
89
+ [class*="fa-"]+span{display:inline-block!important;vertical-align:middle!important;}
90
  </style>
91
  """
92
+ if "<head>" in html_code:
93
+ return html_code.replace("</head>", f"{fa_fix_css}</head>")
94
+ elif "<html" in html_code:
95
+ head_end = html_code.find("</head>")
 
 
 
96
  if head_end > 0:
97
  return html_code[:head_end] + fa_fix_css + html_code[head_end:]
98
+ body_start = html_code.find("<body")
99
+ if body_start > 0:
100
+ return html_code[:body_start] + f"<head>{fa_fix_css}</head>" + html_code[body_start:]
101
+ return f"<html><head>{fa_fix_css}</head>{html_code}</html>"
102
+
103
+
104
+ # โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€
105
+ # โ‘ก ใ‚ทใ‚นใƒ†ใƒ ใƒ—ใƒญใƒณใƒ—ใƒˆ่ชญใฟ่พผใฟ
106
+ # โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€
107
+ def load_system_instruction(style: str = "standard") -> str:
108
+ """style ใ”ใจใฎ prompt.txt ใ‚’ใƒญใƒผใ‚ซใƒซ or HF Hub ใ‹ใ‚‰ๅ–ๅพ—"""
109
+ styles = ["standard", "cute", "resort", "cool", "dental"]
110
+ if style not in styles:
111
+ logger.warning(f"็„กๅŠนใชใ‚นใ‚ฟใ‚คใƒซ '{style}' โ†’ 'standard' ใ‚’ไฝฟ็”จ")
112
+ style = "standard"
113
+
114
+ # ใƒญใƒผใ‚ซใƒซ first
115
+ local_path = os.path.join(os.path.dirname(__file__), style, "prompt.txt")
116
+ if os.path.exists(local_path):
117
+ with open(local_path, encoding="utf-8") as f:
118
+ return f.read()
119
+
120
+ # HF Hub fallback
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
121
  try:
122
+ file_path = hf_hub_download(
123
+ repo_id="tomo2chin2/GURAREKOstlyle",
124
+ filename=f"{style}/prompt.txt",
125
+ repo_type="dataset",
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
126
  )
127
+ with open(file_path, encoding="utf-8") as f:
128
+ return f.read()
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
129
  except Exception as e:
130
+ logger.error(f"prompt.txt ๅ–ๅพ—ๅคฑๆ•—: {e}")
131
+ raise
132
+
133
+
134
+ # โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€
135
+ # โ‘ข ็”ปๅƒใฎ็ฉบ็™ฝใƒˆใƒชใƒŸใƒณใ‚ฐ
136
+ # โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€
137
+ def trim_image_whitespace(
138
+ image: Image.Image, threshold: int = 250, padding: int = 10
139
+ ) -> Image.Image:
140
+ """็™ฝไฝ™็™ฝใ‚’ๆคœๅ‡บใ—ใƒ‘ใƒ‡ใ‚ฃใƒณใ‚ฐใ‚’ๆฎ‹ใ—ใฆๅˆ‡ใ‚Š่ฉฐใ‚ใ‚‹"""
141
+ gray = image.convert("L")
 
 
 
 
 
 
 
 
142
  data = gray.getdata()
143
+ w, h = gray.size
144
+ min_x, min_y, max_x, max_y = w, h, 0, 0
 
 
 
 
 
145
  pixels = list(data)
146
+ pixels = [pixels[i * w : (i + 1) * w] for i in range(h)]
147
+ for y in range(h):
148
+ for x in range(w):
149
+ if pixels[y][x] < threshold:
150
+ min_x, min_y = min(min_x, x), min(min_y, y)
151
+ max_x, max_y = max(max_x, x), max(max_y, y)
152
+ if min_x > max_x:
 
 
 
 
 
 
 
153
  return image
154
+ min_x, min_y = max(0, min_x - padding), max(0, min_y - padding)
155
+ max_x, max_y = min(w - 1, max_x + padding), min(h - 1, max_y + padding)
156
+ return image.crop((min_x, min_y, max_x + 1, max_y + 1))
157
+
158
+
159
+ # โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€
160
+ # โ‘ฃ Selenium ใงใƒ•ใƒซใƒšใƒผใ‚ธ SS ็”Ÿๆˆ
161
+ # โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€
162
+ def render_fullpage_screenshot(
163
+ html_code: str, extension_percentage: float = 6.0, trim_whitespace: bool = True
164
+ ) -> Image.Image:
165
+ """HTML ๆ–‡ๅญ—ๅˆ— โ†’ fullโ€‘page PNG โ†’ PIL.Image"""
166
+ tmp_path: Optional[str] = None
167
+ driver: Optional[webdriver.Chrome] = None
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
168
  try:
169
+ with tempfile.NamedTemporaryFile(
170
+ suffix=".html", delete=False, mode="w", encoding="utf-8"
171
+ ) as tmp:
172
+ tmp.write(html_code)
173
+ tmp_path = tmp.name
174
+ options = Options()
175
+ options.add_argument("--headless")
176
+ options.add_argument("--no-sandbox")
177
+ options.add_argument("--disable-dev-shm-usage")
178
+ options.add_argument("--force-device-scale-factor=1")
179
+ driver = webdriver.Chrome(options=options)
180
+ driver.set_window_size(1200, 1000)
181
+ driver.get(f"file://{tmp_path}")
 
 
 
 
 
 
 
 
 
 
 
182
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
183
  WebDriverWait(driver, 15).until(
184
  EC.presence_of_element_located((By.TAG_NAME, "body"))
185
  )
186
+ time.sleep(3) # ๅˆๆœŸใƒญใƒผใƒ‰ๅพ…ใก
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
187
 
188
+ # ็ธฆใ‚นใ‚ฏใƒญใƒผใƒซใ—ใฆใƒฌใƒณใƒ€ใƒชใƒณใ‚ฐ็ขบๅฎš
189
+ total = driver.execute_script(
190
+ "return Math.max(document.body.scrollHeight, document.documentElement.scrollHeight);"
191
+ )
192
+ vp = driver.execute_script("return window.innerHeight;")
193
+ for i in range(max(1, total // vp) + 1):
194
+ driver.execute_script(f"window.scrollTo(0, {i*(vp-200)});")
195
+ time.sleep(0.2)
196
+ driver.execute_script("window.scrollTo(0,0);")
 
 
 
 
 
 
 
 
 
 
 
 
 
 
197
  time.sleep(1)
198
 
199
+ # ๅ…จไฝ“้ซ˜ใ•ใซไฝ™็™ฝใ‚’่ฟฝๅŠ 
200
+ total = driver.execute_script(
201
+ "return Math.max(document.body.scrollHeight, document.documentElement.scrollHeight);"
202
+ )
203
+ height = int(total * (1 + extension_percentage / 100))
204
+ width = driver.execute_script(
205
+ "return Math.max(document.documentElement.scrollWidth, document.body.scrollWidth);"
206
+ )
207
+ height = min(max(height, 100), 4000)
208
+ width = min(max(width, 100), 2000)
209
+ driver.set_window_size(width, height)
 
 
 
 
 
210
  time.sleep(0.5)
 
211
 
 
 
212
  png = driver.get_screenshot_as_png()
 
 
 
213
  img = Image.open(BytesIO(png))
 
 
 
214
  if trim_whitespace:
215
  img = trim_image_whitespace(img, threshold=248, padding=20)
 
 
216
  return img
 
217
  except Exception as e:
218
+ logger.error(f"Screenshot Error: {e}", exc_info=True)
219
+ return Image.new("RGB", (1, 1), (0, 0, 0))
 
220
  finally:
 
221
  if driver:
222
  try:
223
  driver.quit()
224
+ except Exception:
225
+ pass
 
226
  if tmp_path and os.path.exists(tmp_path):
227
+ os.remove(tmp_path)
228
+
229
+
230
+ # โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€
231
+ # โ‘ค Gemini โ†’ HTML ็”Ÿๆˆ
232
+ # โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€
233
+ def _genai_client(api_key: str) -> genai.Client:
234
+ return genai.Client(api_key=api_key)
235
+
236
+
237
+ def _default_safety() -> List[types.SafetySetting]:
238
+ return [
239
+ types.SafetySetting(
240
+ category="HARM_CATEGORY_HARASSMENT", threshold="BLOCK_MEDIUM_AND_ABOVE"
241
+ ),
242
+ types.SafetySetting(
243
+ category="HARM_CATEGORY_HATE_SPEECH", threshold="BLOCK_MEDIUM_AND_ABOVE"
244
+ ),
245
+ types.SafetySetting(
246
+ category="HARM_CATEGORY_SEXUALLY_EXPLICIT", threshold="BLOCK_MEDIUM_AND_ABOVE"
247
+ ),
248
+ types.SafetySetting(
249
+ category="HARM_CATEGORY_DANGEROUS_CONTENT", threshold="BLOCK_MEDIUM_AND_ABOVE"
250
+ ),
251
+ ]
252
+
253
+
254
+ def generate_html_from_text(
255
+ text: str, temperature: float = 0.3, style: str = "standard"
256
+ ) -> str:
257
+ """
258
+ Gemini ใƒขใƒ‡ใƒซใ‹ใ‚‰ HTML ใ‚ณใƒผใƒ‰ใ‚’่ฟ”ใ™ใ€‚
259
+ * ็’ฐๅขƒๅค‰ๆ•ฐ GEMINI_MODEL ใŒ geminiโ€‘2.5โ€‘flash-previewโ€‘04-17 ใฎๅ ดๅˆ
260
+ -> thinking_budget=0 ใ‚’ไป˜ใ‘ใฆๅ‘ผใณๅ‡บใ—
261
+ """
262
+ api_key = os.getenv("GEMINI_API_KEY")
263
+ if not api_key:
264
+ raise ValueError("GEMINI_API_KEY ใŒ่จญๅฎšใ•ใ‚Œใฆใ„ใพใ›ใ‚“")
265
+ model_name = os.getenv("GEMINI_MODEL", "gemini-1.5-pro")
266
+ client = _genai_client(api_key)
267
+
268
+ gen_cfg = types.GenerationConfig(
269
+ temperature=temperature,
270
+ top_p=0.7,
271
+ top_k=20,
272
+ max_output_tokens=8192,
273
+ candidate_count=1,
274
+ )
275
+ safety_cfg = _default_safety()
276
+ think_cfg = (
277
+ types.ThinkingConfig(thinking_budget=0)
278
+ if model_name == "gemini-2.5-flash-preview-04-17"
279
+ else None
280
+ )
281
+
282
+ req_cfg_kwargs = dict(
283
+ generation_config=gen_cfg,
284
+ safety_settings=safety_cfg,
285
+ )
286
+ if think_cfg:
287
+ req_cfg_kwargs["thinking_config"] = think_cfg
288
+
289
+ req_cfg = types.GenerateContentConfig(**req_cfg_kwargs)
290
 
291
+ prompt = f"{load_system_instruction(style)}\n\n{text}"
292
+ logger.info(
293
+ f"Gemini request โ†’ model={model_name}, temp={temperature}, thinking_budget={0 if think_cfg else None}"
294
+ )
295
+
296
+ rsp = client.models.generate_content(
297
+ model=model_name, contents=prompt, config=req_cfg
298
+ )
299
+ raw = rsp.text or ""
300
+
301
+ start = raw.find("```html")
302
+ end = raw.rfind("```")
303
+ if 0 <= start < end:
304
+ html_code = raw[start + 7 : end].strip()
305
+ return enhance_font_awesome_layout(html_code)
306
+
307
+ logger.warning("```html``` ใƒ–ใƒญใƒƒใ‚ฏใชใ—ใ€‚็”Ÿใƒฌใ‚นใƒใƒณใ‚นใ‚’่ฟ”ใ—ใพใ™")
308
+ return raw
309
+
310
+
311
+ # โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€
312
+ # โ‘ฅ ใƒ†ใ‚ญใ‚นใƒˆ โ†’ ใ‚นใ‚ฏใƒชใƒผใƒณใ‚ทใƒงใƒƒใƒˆ็ตฑๅˆ
313
+ # โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€
314
+ def text_to_screenshot(
315
+ text: str,
316
+ extension_percentage: float,
317
+ temperature: float = 0.3,
318
+ trim_whitespace: bool = True,
319
+ style: str = "standard",
320
+ ) -> Image.Image:
321
+ try:
322
+ html = generate_html_from_text(text, temperature, style)
323
+ return render_fullpage_screenshot(html, extension_percentage, trim_whitespace)
324
  except Exception as e:
325
+ logger.error(e, exc_info=True)
326
+ return Image.new("RGB", (1, 1), (0, 0, 0))
327
 
 
 
328
 
329
+ # โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€
330
+ # โ‘ฆ FastAPI ใ‚ปใƒƒใƒˆใ‚ขใƒƒใƒ—
331
+ # โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€
332
+ app = FastAPI()
333
  app.add_middleware(
334
  CORSMiddleware,
335
  allow_origins=["*"],
 
338
  allow_headers=["*"],
339
  )
340
 
341
+ # Gradio ใฎ้™็š„ใƒ•ใ‚กใ‚คใƒซใ‚’ใƒžใ‚ฆใƒณใƒˆ
 
342
  gradio_dir = os.path.dirname(gr.__file__)
343
+ for sub in [
344
+ ("static", "templates/frontend/static"),
345
+ ("_app", "templates/frontend/_app"),
346
+ ("assets", "templates/frontend/assets"),
347
+ ("cdn", "templates/cdn"),
348
+ ]:
349
+ target = os.path.join(gradio_dir, sub[1])
350
+ if os.path.exists(target):
351
+ app.mount(f"/{sub[0]}", StaticFiles(directory=target), name=sub[0])
352
+ logger.info(f"Mounted /{sub[0]} โ†’ {target}")
353
+
354
+ # โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€
355
+ # โ‘ง API ใ‚จใƒณใƒ‰ใƒใ‚คใƒณใƒˆ
356
+ # โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€
357
+ @app.post(
358
+ "/api/screenshot",
359
+ response_class=StreamingResponse,
360
+ tags=["Screenshot"],
361
+ summary="HTML โ†’ Fullโ€‘page Screenshot",
362
+ )
363
+ async def api_render_screenshot(req: ScreenshotRequest):
364
+ img = render_fullpage_screenshot(
365
+ req.html_code, req.extension_percentage, req.trim_whitespace
366
+ )
367
+ buf = BytesIO()
368
+ img.save(buf, format="PNG")
369
+ buf.seek(0)
370
+ return StreamingResponse(buf, media_type="image/png")
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
371
 
 
 
 
372
 
373
+ @app.post(
374
+ "/api/text-to-screenshot",
375
+ response_class=StreamingResponse,
376
+ tags=["Screenshot", "Gemini"],
377
+ summary="Text โ†’ Gemini โ†’ Infographic Screenshot",
378
+ )
379
+ async def api_text_to_screenshot(req: GeminiRequest):
380
+ img = text_to_screenshot(
381
+ req.text,
382
+ req.extension_percentage,
383
+ req.temperature,
384
+ req.trim_whitespace,
385
+ req.style,
386
+ )
387
+ buf = BytesIO()
388
+ img.save(buf, format="PNG")
389
+ buf.seek(0)
390
+ return StreamingResponse(buf, media_type="image/png")
391
+
392
+
393
+ # โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€
394
+ # โ‘จ Gradio UI
395
+ # โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€
396
+ def process_input(
397
+ input_mode, input_text, extension_percentage, temperature, trim_whitespace, style
398
+ ):
399
  if input_mode == "HTMLๅ…ฅๅŠ›":
400
+ return render_fullpage_screenshot(
401
+ input_text, extension_percentage, trim_whitespace
 
 
 
 
 
 
 
 
 
 
 
 
 
 
402
  )
403
+ return text_to_screenshot(
404
+ input_text, extension_percentage, temperature, trim_whitespace, style
 
 
 
 
405
  )
406
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
407
 
408
+ with gr.Blocks(title="Full Page Screenshot + Gemini 2.5 Flash") as iface:
409
+ gr.Markdown("## HTML ใƒ“ใƒฅใƒผใ‚ข & ใƒ†ใ‚ญใ‚นใƒˆ โ†’ ใ‚คใƒณใƒ•ใ‚ฉใ‚ฐใƒฉใƒ•ใ‚ฃใƒƒใ‚ฏ")
410
+ input_mode = gr.Radio(["HTMLๅ…ฅๅŠ›", "ใƒ†ใ‚ญใ‚นใƒˆๅ…ฅๅŠ›"], value="HTMLๅ…ฅๅŠ›", label="ๅ…ฅๅŠ›ใƒขใƒผใƒ‰")
411
+ input_text = gr.Textbox(lines=15, label="ๅ…ฅๅŠ›")
412
+ with gr.Row():
413
+ style_dd = gr.Dropdown(
414
+ ["standard", "cute", "resort", "cool", "dental"],
415
+ value="standard",
416
+ label="ใƒ‡ใ‚ถใ‚คใƒณใ‚นใ‚ฟใ‚คใƒซ",
417
+ visible=False,
418
+ )
419
+ extension_slider = gr.Slider(0, 30, 10, label="ไธŠไธ‹้ซ˜ใ•ๆ‹กๅผต็އ(%)")
420
+ temperature_slider = gr.Slider(
421
+ 0.0,
422
+ 1.0,
423
+ 0.5,
424
+ step=0.1,
425
+ label="็”Ÿๆˆๆธฉๅบฆ",
426
+ visible=False,
427
+ )
428
+ trim_cb = gr.Checkbox(value=True, label="ไฝ™็™ฝ่‡ชๅ‹•ใƒˆใƒชใƒŸใƒณใ‚ฐ")
429
+ btn = gr.Button("็”Ÿๆˆ")
430
+ out_img = gr.Image(type="pil", label="ใ‚นใ‚ฏใƒชใƒผใƒณใ‚ทใƒงใƒƒใƒˆ")
431
 
432
+ def _vis(mode):
433
+ is_text = mode == "ใƒ†ใ‚ญใ‚นใƒˆๅ…ฅๅŠ›"
 
 
434
  return [
435
+ {"visible": is_text, "__type__": "update"},
436
+ {"visible": is_text, "__type__": "update"},
437
  ]
438
 
439
+ input_mode.change(_vis, input_mode, [temperature_slider, style_dd])
440
+ btn.click(
441
+ process_input,
442
+ [
443
+ input_mode,
444
+ input_text,
445
+ extension_slider,
446
+ temperature_slider,
447
+ trim_cb,
448
+ style_dd,
449
+ ],
450
+ out_img,
451
  )
452
 
453
+ gr.Markdown(
454
+ f"""
455
+ ### ็’ฐๅขƒ
456
+ * ไฝฟ็”จใƒขใƒ‡ใƒซ: `{os.getenv('GEMINI_MODEL', 'gemini-1.5-pro')}`
457
+ * thinking_budget=0 ใฏ `gemini-2.5-flash-preview-04-17` ไฝฟ็”จๆ™‚ใฎใฟ่‡ชๅ‹•ไป˜ไธŽ
458
+ """
459
  )
460
 
461
+ # โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€
462
+ # โ‘ฉ FastAPI ใซ Gradio ใ‚’ใƒžใ‚ฆใƒณใƒˆ
463
+ # โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€
 
 
 
 
 
 
 
 
 
 
464
  app = gr.mount_gradio_app(app, iface, path="/")
465
 
466
+ # โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€
467
+ # โ‘ช ็›ดๆŽฅๅฎŸ่กŒๆ™‚
468
+ # โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€
469
  if __name__ == "__main__":
470
  import uvicorn
471
+
472
+ logger.info("Starting dev server at http://localhost:7860")
473
+ uvicorn.run(app, host="0.0.0.0", port=7860)