Upload 3 files
Browse files- app.py +700 -373
- 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
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 27 |
|
| 28 |
-
#
|
| 29 |
-
|
| 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 |
-
|
| 58 |
-
#
|
| 59 |
-
def enhance_font_awesome_layout(html_code: str) -> str:
|
| 60 |
-
"""Font Awesome ใขใคใณใณใฎ่กจ็คบใบใฌใไฟฎๆญฃใใ่ฟฝๅ CSS ใๆฟๅ
ฅ"""
|
| 61 |
fa_fix_css = """
|
| 62 |
<style>
|
| 63 |
-
/* Font Awesome
|
| 64 |
-
[class*="fa-"]{
|
| 65 |
-
display:inline-block!important;
|
| 66 |
-
|
| 67 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 68 |
}
|
| 69 |
-
|
| 70 |
-
|
| 71 |
-
|
|
|
|
|
|
|
|
|
|
| 72 |
}
|
| 73 |
-
|
| 74 |
-
|
| 75 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 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 |
-
|
| 83 |
-
|
| 84 |
-
|
| 85 |
-
|
|
|
|
|
|
|
|
|
|
| 86 |
if head_end > 0:
|
| 87 |
return html_code[:head_end] + fa_fix_css + html_code[head_end:]
|
| 88 |
-
|
| 89 |
-
|
| 90 |
-
|
| 91 |
-
|
| 92 |
-
|
| 93 |
-
|
| 94 |
-
|
| 95 |
-
|
| 96 |
-
|
| 97 |
-
|
| 98 |
-
|
| 99 |
-
|
| 100 |
-
|
| 101 |
-
|
| 102 |
-
|
| 103 |
-
|
| 104 |
-
|
| 105 |
-
|
| 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 |
-
|
| 113 |
-
|
| 114 |
-
|
| 115 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 116 |
)
|
| 117 |
-
|
| 118 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 119 |
except Exception as e:
|
| 120 |
-
logger.error(f"
|
| 121 |
-
raise
|
| 122 |
-
|
| 123 |
-
|
| 124 |
-
|
| 125 |
-
|
| 126 |
-
|
| 127 |
-
|
| 128 |
-
|
| 129 |
-
|
| 130 |
-
|
| 131 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 132 |
data = gray.getdata()
|
| 133 |
-
|
| 134 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 135 |
pixels = list(data)
|
| 136 |
-
pixels = [pixels[i *
|
| 137 |
-
|
| 138 |
-
|
| 139 |
-
|
| 140 |
-
|
| 141 |
-
|
| 142 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 143 |
return image
|
| 144 |
-
|
| 145 |
-
|
| 146 |
-
|
| 147 |
-
|
| 148 |
-
|
| 149 |
-
|
| 150 |
-
|
| 151 |
-
#
|
| 152 |
-
|
| 153 |
-
|
| 154 |
-
|
| 155 |
-
|
| 156 |
-
|
| 157 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 158 |
try:
|
| 159 |
-
with tempfile.NamedTemporaryFile(
|
| 160 |
-
|
| 161 |
-
|
| 162 |
-
|
| 163 |
-
|
| 164 |
-
|
| 165 |
-
|
| 166 |
-
|
| 167 |
-
|
| 168 |
-
|
| 169 |
-
|
| 170 |
-
|
| 171 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 172 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 173 |
WebDriverWait(driver, 15).until(
|
| 174 |
EC.presence_of_element_located((By.TAG_NAME, "body"))
|
| 175 |
)
|
| 176 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 177 |
|
| 178 |
-
|
| 179 |
-
|
| 180 |
-
|
| 181 |
-
|
| 182 |
-
|
| 183 |
-
|
| 184 |
-
|
| 185 |
-
|
| 186 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 187 |
time.sleep(1)
|
| 188 |
|
| 189 |
-
#
|
| 190 |
-
|
| 191 |
-
|
| 192 |
-
|
| 193 |
-
|
| 194 |
-
|
| 195 |
-
|
| 196 |
-
)
|
| 197 |
-
|
| 198 |
-
|
| 199 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 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"
|
| 209 |
-
|
|
|
|
| 210 |
finally:
|
|
|
|
| 211 |
if driver:
|
| 212 |
try:
|
| 213 |
driver.quit()
|
| 214 |
-
|
| 215 |
-
|
|
|
|
| 216 |
if tmp_path and os.path.exists(tmp_path):
|
| 217 |
-
|
| 218 |
-
|
| 219 |
-
|
| 220 |
-
|
| 221 |
-
|
| 222 |
-
|
| 223 |
-
|
| 224 |
-
|
| 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 |
-
|
| 313 |
-
|
| 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 |
-
#
|
|
|
|
| 332 |
gradio_dir = os.path.dirname(gr.__file__)
|
| 333 |
-
|
| 334 |
-
|
| 335 |
-
|
| 336 |
-
|
| 337 |
-
|
| 338 |
-
|
| 339 |
-
|
| 340 |
-
|
| 341 |
-
|
| 342 |
-
|
| 343 |
-
|
| 344 |
-
|
| 345 |
-
|
| 346 |
-
|
| 347 |
-
|
| 348 |
-
|
| 349 |
-
|
| 350 |
-
|
| 351 |
-
|
| 352 |
-
)
|
| 353 |
-
|
| 354 |
-
|
| 355 |
-
|
| 356 |
-
|
| 357 |
-
|
| 358 |
-
|
| 359 |
-
|
| 360 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 361 |
|
|
|
|
|
|
|
|
|
|
|
|
|
| 362 |
|
| 363 |
-
|
| 364 |
-
|
| 365 |
-
|
| 366 |
-
|
| 367 |
-
|
| 368 |
-
)
|
| 369 |
-
|
| 370 |
-
|
| 371 |
-
|
| 372 |
-
|
| 373 |
-
|
| 374 |
-
|
| 375 |
-
|
| 376 |
-
|
| 377 |
-
|
| 378 |
-
|
| 379 |
-
|
| 380 |
-
|
| 381 |
-
|
| 382 |
-
|
| 383 |
-
|
| 384 |
-
|
| 385 |
-
|
| 386 |
-
|
| 387 |
-
|
| 388 |
-
)
|
| 389 |
-
|
| 390 |
-
|
| 391 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 392 |
)
|
| 393 |
-
|
| 394 |
-
|
| 395 |
-
|
|
|
|
| 396 |
|
| 397 |
|
| 398 |
-
|
| 399 |
-
|
| 400 |
-
|
| 401 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 402 |
with gr.Row():
|
| 403 |
-
|
| 404 |
-
["
|
| 405 |
-
|
| 406 |
-
|
| 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 |
-
|
| 423 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 424 |
return [
|
| 425 |
-
|
| 426 |
-
|
| 427 |
]
|
| 428 |
|
| 429 |
-
input_mode.change(
|
| 430 |
-
|
| 431 |
-
|
| 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 |
-
|
| 444 |
-
|
| 445 |
-
|
| 446 |
-
|
| 447 |
-
|
| 448 |
-
"""
|
| 449 |
)
|
| 450 |
|
| 451 |
-
#
|
| 452 |
-
|
| 453 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 454 |
app = gr.mount_gradio_app(app, iface, path="/")
|
| 455 |
|
| 456 |
-
#
|
| 457 |
-
# โช ็ดๆฅๅฎ่กๆ
|
| 458 |
-
# โโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโ
|
| 459 |
if __name__ == "__main__":
|
| 460 |
import uvicorn
|
| 461 |
-
|
| 462 |
-
|
| 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==
|
| 3 |
Pillow
|
| 4 |
fastapi
|
| 5 |
uvicorn[standard]
|
| 6 |
-
google-
|
| 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 ---
|