Spaces:
Paused
Paused
Update app.py
Browse files123454 unmodified lines1011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645652 unmodified lines568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790import gradio as grfrom fastapi import FastAPI, HTTPException, Bodyfrom fastapi.responses import StreamingResponsefrom fastapi.staticfiles import StaticFilesfrom fastapi.middleware.cors import CORSMiddleware4 unmodified linesfrom selenium.webdriver.support.ui import WebDriverWaitfrom selenium.webdriver.support import expected_conditions as ECfrom PIL import Imagefrom io import BytesIOimport tempfileimport timeimport osimport loggingfrom huggingface_hub import hf_hub_download # ่ฟฝๅ : HuggingFace Hubใใใใกใคใซใ็ดๆฅใใฆใณใญใผใ# ๆญฃใใGemini้ข้ฃใฎใคใณใใผใimport google.generativeai as genai# ใญใฎใณใฐ่จญๅฎlogging.basicConfig(level=logging.INFO)logger = logging.getLogger(__name__)# --- Gemini็ตฑๅ ---class GeminiRequest(BaseModel):"""Geminiใธใฎใชใฏใจในใใใผใฟใขใใซ"""text: strextension_percentage: float = 10.0 # ใใใฉใซใๅค10%temperature: float = 0.5 # ใใใฉใซใๅคใ0.5ใซ่จญๅฎtrim_whitespace: bool = True # ไฝ็ฝใใชใใณใฐใชใใทใงใณ๏ผใใใฉใซใๆๅน๏ผstyle: str = "standard" # ใใใฉใซใใฏstandardclass ScreenshotRequest(BaseModel):"""ในใฏใชใผใณใทใงใใใชใฏใจในใใขใใซ"""html_code: strextension_percentage: float = 10.0 # ใใใฉใซใๅค10%trim_whitespace: bool = True # ไฝ็ฝใใชใใณใฐใชใใทใงใณ๏ผใใใฉใซใๆๅน๏ผstyle: str = "standard" # ใใใฉใซใใฏstandard# HTMLใฎFont Awesomeใฌใคใขใฆใใๆนๅใใ้ขๆฐdef enhance_font_awesome_layout(html_code):"""Font AwesomeใฌใคใขใฆใใๆนๅใใCSSใ่ฟฝๅ """# CSSใ่ฟฝๅfa_fix_css = """<style>/* Font Awesomeใขใคใณใณใฎใฌใคใขใฆใไฟฎๆญฃ */[class*="fa-"] {display: inline-block !important;margin-right: 8px !important;vertical-align: middle !important;}/* ใใญในใๅ ใฎใขใคใณใณไฝ็ฝฎ่ชฟๆด */h1 [class*="fa-"], h2 [class*="fa-"], h3 [class*="fa-"],h4 [class*="fa-"], h5 [class*="fa-"], h6 [class*="fa-"] {vertical-align: middle !important;margin-right: 10px !important;}/* ็นๅฎใใฟใผใณใฎไฟฎๆญฃ */.fa + span, .fas + span, .far + span, .fab + span,span + .fa, span + .fas, span + .far + span {display: inline-block !important;margin-left: 5px !important;}/* ใซใผใๅ ใขใคใณใณไฟฎๆญฃ */.card [class*="fa-"], .card-body [class*="fa-"] {float: none !important;clear: none !important;position: relative !important;}/* ใขใคใณใณใจๆๅญใ้ใชใๅ ดๅใฎ่ชฟๆด */li [class*="fa-"], p [class*="fa-"] {margin-right: 10px !important;}/* ใคใณใฉใคใณใขใคใณใณใฎในใใผใทใณใฐ */.inline-icon {display: inline-flex !important;align-items: center !important;justify-content: flex-start !important;}/* ใขใคใณใณๅพใฎใใญในใ */[class*="fa-"] + span {display: inline-block !important;vertical-align: middle !important;}</style>"""# headใฟใฐใใใๅ ดๅใฏใใฎไธญใซ่ฟฝๅif '<head>' in html_code:return html_code.replace('</head>', f'{fa_fix_css}</head>')# HTMLใฟใฐใใใๅ ดๅใฏใใฎๅพใซ่ฟฝๅelif '<html' in html_code:head_end = html_code.find('</head>')if head_end > 0:return html_code[:head_end] + fa_fix_css + html_code[head_end:]else:body_start = html_code.find('<body')if body_start > 0:return html_code[:body_start] + f'<head>{fa_fix_css}</head>' + html_code[body_start:]# ใฉใกใใใชใๅ ดๅใฏๅ ้ ญใซ่ฟฝๅreturn f'<html><head>{fa_fix_css}</head>' + html_code + '</html>'def load_system_instruction(style="standard"):"""ๆๅฎใใใในใฟใคใซใฎใทในใใ ใคใณในใใฉใฏใทใงใณใ่ชญใฟ่พผใArgs:style: ไฝฟ็จใใในใฟใคใซๅ (standard, cute, resort, cool, dental)Returns:่ชญใฟ่พผใพใใใทในใใ ใคใณในใใฉใฏใทใงใณ"""try:# ๆๅนใชในใฟใคใซไธ่ฆงvalid_styles = ["standard", "cute", "resort", "cool", "dental"]# ในใฟใคใซใฎๆค่จผif style not in valid_styles:logger.warning(f"็กๅนใชในใฟใคใซ '{style}' ใๆๅฎใใใพใใใใใใฉใซใใฎ 'standard' ใไฝฟ็จใใพใใ")style = "standard"logger.info(f"ในใฟใคใซ '{style}' ใฎใทในใใ ใคใณในใใฉใฏใทใงใณใ่ชญใฟ่พผใฟใพใ")# ใพใใใญใผใซใซใฎในใฟใคใซใใฃใฌใฏใใชๅ ใฎprompt.txtใ็ขบ่ชlocal_path = os.path.join(os.path.dirname(__file__), style, "prompt.txt")# ใญใผใซใซใใกใคใซใๅญๅจใใๅ ดๅใฏใใใไฝฟ็จif os.path.exists(local_path):logger.info(f"ใญใผใซใซใใกใคใซใไฝฟ็จ: {local_path}")with open(local_path, 'r', encoding='utf-8') as file:instruction = file.read()return instruction# HuggingFaceใชใใธใใชใใใฎใใกใคใซ่ชญใฟ่พผใฟใ่ฉฆ่กtry:# ในใฟใคใซๅบๆใฎใใกใคใซใในใๆๅฎfile_path = hf_hub_download(repo_id="tomo2chin2/GURAREKOstlyle",filename=f"{style}/prompt.txt",repo_type="dataset")logger.info(f"ในใฟใคใซ '{style}' ใฎใใญใณใใใHuggingFaceใใ่ชญใฟ่พผใฟใพใใ: {file_path}")with open(file_path, 'r', encoding='utf-8') as file:instruction = file.read()return instructionexcept Exception as style_error:# ในใฟใคใซๅบๆใใกใคใซใฎ่ชญใฟ่พผใฟใซๅคฑๆใใๅ ดๅใใใใฉใซใใฎprompt.txtใไฝฟ็จlogger.warning(f"ในใฟใคใซ '{style}' ใฎใใญใณใใ่ชญใฟ่พผใฟใซๅคฑๆ: {str(style_error)}")logger.info("ใใใฉใซใใฎprompt.txtใ่ชญใฟ่พผใฟใพใ")file_path = hf_hub_download(repo_id="tomo2chin2/GURAREKOstlyle",filename="prompt.txt",repo_type="dataset")with open(file_path, 'r', encoding='utf-8') as file:instruction = file.read()logger.info("ใใใฉใซใใฎใทในใใ ใคใณในใใฉใฏใทใงใณใ่ชญใฟ่พผใฟใพใใ")return instructionexcept Exception as e:error_msg = f"ใทในใใ ใคใณในใใฉใฏใทใงใณใฎ่ชญใฟ่พผใฟใซๅคฑๆ: {str(e)}"logger.error(error_msg)raise ValueError(error_msg)def generate_html_from_text(text, temperature=0.3, style="standard"):"""ใใญในใใใHTMLใ็ๆใใ"""try:# APIใญใผใฎๅๅพใจ่จญๅฎapi_key = os.environ.get("GEMINI_API_KEY")if not api_key:logger.error("GEMINI_API_KEY ็ฐๅขๅคๆฐใ่จญๅฎใใใฆใใพใใ")raise ValueError("GEMINI_API_KEY ็ฐๅขๅคๆฐใ่จญๅฎใใใฆใใพใใ")# ใขใใซๅใฎๅๅพ๏ผ็ฐๅขๅคๆฐใใใใชใใใฐใใใฉใซใๅค๏ผmodel_name = os.environ.get("GEMINI_MODEL", "gemini-1.5-pro")logger.info(f"ไฝฟ็จใใGeminiใขใใซ: {model_name}")# Gemini APIใฎ่จญๅฎgenai.configure(api_key=api_key)# ๆๅฎใใใในใฟใคใซใฎใทในใใ ใคใณในใใฉใฏใทใงใณใ่ชญใฟ่พผใsystem_instruction = load_system_instruction(style)# ใขใใซๅๆๅlogger.info(f"Gemini APIใซใชใฏใจในใใ้ไฟก: ใใญในใ้ทใ = {len(text)}, ๆธฉๅบฆ = {temperature}, ในใฟใคใซ = {style}")# ใขใใซๅๆๅmodel = genai.GenerativeModel(model_name)# ็ๆ่จญๅฎ - ใฐใใคใใๆธใใใใใซ่จญๅฎใ่ชฟๆดgeneration_config = {"temperature": temperature, # ใใไฝใๆธฉๅบฆใ่จญๅฎ"top_p": 0.7, # 0.95ใใ0.7ใซไธใใฆๅบๅใฎๅคๆงๆงใๅถ้"top_k": 20, # 64ใใ20ใซไธใใฆๅ่ฃใ็ตใ"max_output_tokens": 8192,"candidate_count": 1 # ๅ่ฃใฏ1ใคใ ใ็ๆ}# ๅฎๅ จ่จญๅฎ - ใใใฉใซใใฎๅฎๅ จ่จญๅฎใไฝฟ็จsafety_settings = [{"category": "HARM_CATEGORY_HARASSMENT","threshold": "BLOCK_MEDIUM_AND_ABOVE"},{"category": "HARM_CATEGORY_HATE_SPEECH","threshold": "BLOCK_MEDIUM_AND_ABOVE"},{"category": "HARM_CATEGORY_SEXUALLY_EXPLICIT","threshold": "BLOCK_MEDIUM_AND_ABOVE"},{"category": "HARM_CATEGORY_DANGEROUS_CONTENT","threshold": "BLOCK_MEDIUM_AND_ABOVE"}]# ใใญใณใใๆง็ฏprompt = f"{system_instruction}\n\n{text}"# ใณใณใใณใ็ๆresponse = model.generate_content(prompt,generation_config=generation_config,safety_settings=safety_settings)# ใฌในใใณในใใHTMLใๆฝๅบraw_response = response.text# HTMLใฟใฐ้จๅใ ใใๆฝๅบ๏ผ```html ใจ ``` ใฎ้๏ผhtml_start = raw_response.find("```html")html_end = raw_response.rfind("```")if html_start != -1 and html_end != -1 and html_start < html_end:html_start += 7 # "```html" ใฎ้ทใๅ้ฒใใhtml_code = raw_response[html_start:html_end].strip()logger.info(f"HTMLใฎ็ๆใซๆๅ: ้ทใ = {len(html_code)}")# Font Awesomeใฎใฌใคใขใฆใๆนๅhtml_code = enhance_font_awesome_layout(html_code)logger.info("Font Awesomeใฌใคใขใฆใใฎๆ้ฉๅใ้ฉ็จใใพใใ")return html_codeelse:# HTMLใฟใฐใ่ฆใคใใใชใๅ ดๅใใฌในใใณในๅ จไฝใ่ฟใlogger.warning("ใฌในใใณในใใ ```html ``` ใฟใฐใ่ฆใคใใใพใใใงใใใๅ จใ๏ฟฝ๏ฟฝ๏ฟฝในใใ่ฟใใพใใ")return raw_responseexcept Exception as e:logger.error(f"HTML็ๆไธญใซใจใฉใผใ็บ็: {e}", exc_info=True)raise Exception(f"Gemini APIใงใฎHTML็ๆใซๅคฑๆใใพใใ: {e}")# ็ปๅใใไฝๅใช็ฉบ็ฝ้ ๅใใใชใใณใฐใใ้ขๆฐdef trim_image_whitespace(image, threshold=250, padding=10):"""็ปๅใใไฝๅใช็ฝใ็ฉบ็ฝใใใชใใณใฐใใArgs:image: PIL.Image - ๅ ฅๅ็ปๅthreshold: int - ใฉใฎๆใใไปฅไธใ็ฉบ็ฝใจๅคๆญใใใ (0-255)padding: int - ใใชใใณใฐๅพใซๆฎใไฝ็ฝใฎใใฏใปใซๆฐReturns:ใใชใใณใฐใใใPIL.Image"""# ใฐใฌใผในใฑใผใซใซๅคๆgray = image.convert('L')# ใใฏใปใซใใผใฟใ้ ๅใจใใฆๅๅพdata = gray.getdata()width, height = gray.size# ๆๅน็ฏๅฒใ่ฆใคใใmin_x, min_y = width, heightmax_x = max_y = 0# ใใฏใปใซใใผใฟใ2ๆฌกๅ ้ ๅใซๅคๆใใฆๅฆ็pixels = list(data)pixels = [pixels[i * width:(i + 1) * width] for i in range(height)]# ๅ่กใในใญใฃใณใใฆ้็ฉบ็ฝใใฏใปใซใ่ฆใคใใfor y in range(height):for x in range(width):if pixels[y][x] < threshold: # ้็ฉบ็ฝใใฏใปใซmin_x = min(min_x, x)min_y = min(min_y, y)max_x = max(max_x, x)max_y = max(max_y, y)# ๅข็ๅคใฎใใชใใณใฐใฎๅ ดๅใฏใจใฉใผif min_x > max_x or min_y > max_y:logger.warning("ใใชใใณใฐ้ ๅใ่ฆใคใใใพใใใๅ ใฎ็ปๅใ่ฟใใพใใ")return image# ใใใฃใณใฐใ่ฟฝๅmin_x = max(0, min_x - padding)min_y = max(0, min_y - padding)max_x = min(width - 1, max_x + padding)max_y = min(height - 1, max_y + padding)# ็ปๅใใใชใใณใฐtrimmed = image.crop((min_x, min_y, max_x + 1, max_y + 1))logger.info(f"็ปๅใใใชใใณใฐใใพใใ: ๅ ใตใคใบ {width}x{height} โ ใใชใใณใฐๅพ {trimmed.width}x{trimmed.height}")return trimmed# ้ๅๆในใฏใชใใใไฝฟใใใๅๆ็ใชในใฏใชใใใฎใฟไฝฟ็จใใๆนๅ็def render_fullpage_screenshot(html_code: str, extension_percentage: float = 6.0,trim_whitespace: bool = True) -> Image.Image:"""Renders HTML code to a full-page screenshot using Selenium.Args:html_code: The HTML source code string.extension_percentage: Percentage of extra space to add vertically.trim_whitespace: Whether to trim excess whitespace from the image.Returns:A PIL Image object of the screenshot."""tmp_path = Nonedriver = None# 1) Save HTML code to a temporary filetry:with tempfile.NamedTemporaryFile(suffix=".html", delete=False, mode='w', encoding='utf-8') as tmp_file:tmp_path = tmp_file.nametmp_file.write(html_code)logger.info(f"HTML saved to temporary file: {tmp_path}")except Exception as e:logger.error(f"Error writing temporary HTML file: {e}")return Image.new('RGB', (1, 1), color=(0, 0, 0))# 2) Headless Chrome(Chromium) optionsoptions = Options()options.add_argument("--headless")options.add_argument("--no-sandbox")options.add_argument("--disable-dev-shm-usage")options.add_argument("--force-device-scale-factor=1")options.add_argument("--disable-features=NetworkService")options.add_argument("--dns-prefetch-disable")# ็ฐๅขๅคๆฐใใWebDriverใในใๅๅพ๏ผไปปๆ๏ผwebdriver_path = os.environ.get("CHROMEDRIVER_PATH")if webdriver_path and os.path.exists(webdriver_path):logger.info(f"Using CHROMEDRIVER_PATH: {webdriver_path}")service = webdriver.ChromeService(executable_path=webdriver_path)else:logger.info("CHROMEDRIVER_PATH not set or invalid, using default PATH lookup.")service = None # Use default behaviortry:logger.info("Initializing WebDriver...")if service:driver = webdriver.Chrome(service=service, options=options)else:driver = webdriver.Chrome(options=options)logger.info("WebDriver initialized.")# 3) ๅๆใฆใฃใณใใฆใตใคใบใ่จญๅฎinitial_width = 1200initial_height = 1000driver.set_window_size(initial_width, initial_height)file_url = "file://" + tmp_pathlogger.info(f"Navigating to {file_url}")driver.get(file_url)# 4) ใใผใธ่ชญใฟ่พผใฟๅพ ๆฉlogger.info("Waiting for body element...")WebDriverWait(driver, 15).until(EC.presence_of_element_located((By.TAG_NAME, "body")))logger.info("Body element found. Waiting for resource loading...")# 5) ๅบๆฌ็ใชใชใฝใผใน่ชญใฟ่พผใฟๅพ ๆฉ - ใฟใคใ ใขใฆใๅ้ฟtime.sleep(3)# Font Awesome่ชญใฟ่พผใฟ็ขบ่ช - ้ๅๆใไฝฟใใชใlogger.info("Checking for Font Awesome resources...")fa_count = driver.execute_script("""var icons = document.querySelectorAll('.fa, .fas, .far, .fab, [class*="fa-"]');return icons.length;""")logger.info(f"Found {fa_count} Font Awesome elements")# ใชใฝใผใน่ชญใฟ่พผใฟ็ถๆ ใ็ขบ่ชdoc_ready = driver.execute_script("return document.readyState;")logger.info(f"Document ready state: {doc_ready}")# Font Awesomeใๅคใๅ ดๅใฏ่ฟฝๅ ๅพ ๆฉif fa_count > 50:logger.info("Many Font Awesome icons detected, waiting additional time")time.sleep(2)# 6) ใณใณใใณใใฌใณใใชใณใฐใฎใใใฎในใฏใญใผใซๅฆ็ - ๅๆ็ใซๅฎ่กlogger.info("Performing content rendering scroll...")total_height = driver.execute_script("return Math.max(document.body.scrollHeight, document.documentElement.scrollHeight);")viewport_height = driver.execute_script("return window.innerHeight;")scrolls_needed = max(1, total_height // viewport_height)for i in range(scrolls_needed + 1):scroll_pos = i * (viewport_height - 200) # ใชใผใใผใฉใใใใใdriver.execute_script(f"window.scrollTo(0, {scroll_pos});")time.sleep(0.2) # ็ญใๅพ ๆฉ# ใใใใซๆปใdriver.execute_script("window.scrollTo(0, 0);")time.sleep(0.5)logger.info("Scroll rendering completed")# 7) ในใฏใญใผใซใใผใ้่กจ็คบใซdriver.execute_script("""document.documentElement.style.overflow = 'hidden';document.body.style.overflow = 'hidden';""")logger.info("Scrollbars hidden")# 8) ใใผใธใฎๅฏธๆณใๅๅพdimensions = driver.execute_script("""return {width: Math.max(document.documentElement.scrollWidth,document.documentElement.offsetWidth,document.documentElement.clientWidth,document.body ? document.body.scrollWidth : 0,document.body ? document.body.offsetWidth : 0,document.body ? document.body.clientWidth : 0),height: Math.max(document.documentElement.scrollHeight,document.documentElement.offsetHeight,document.documentElement.clientHeight,document.body ? document.body.scrollHeight : 0,document.body ? document.body.offsetHeight : 0,document.body ? document.body.clientHeight : 0)};""")scroll_width = dimensions['width']scroll_height = dimensions['height']logger.info(f"Detected dimensions: width={scroll_width}, height={scroll_height}")# ๅๆค่จผ - ็ญใในใฏใญใผใซใงๅ็ขบ่ชdriver.execute_script("window.scrollTo(0, document.body.scrollHeight);")time.sleep(0.5)driver.execute_script("window.scrollTo(0, 0);")time.sleep(0.5)dimensions_after = driver.execute_script("return {height: Math.max(document.documentElement.scrollHeight, document.body.scrollHeight)};")scroll_height = max(scroll_height, dimensions_after['height'])logger.info(f"After scroll check, height={scroll_height}")# ๆๅฐ/ๆๅคงๅคใฎ่จญๅฎscroll_width = max(scroll_width, 100)scroll_height = max(scroll_height, 100)scroll_width = min(scroll_width, 2000)scroll_height = min(scroll_height, 4000)# 9) ใฌใคใขใฆใๅฎๅฎๅใฎใใใฎๅ็ดใชๅพ ๆฉ - ใฟใคใ ใขใฆใๅ้ฟlogger.info("Waiting for layout stabilization...")time.sleep(2)# 10) ้ซใใซไฝ็ฝใ่ฟฝๅadjusted_height = int(scroll_height * (1 + extension_percentage / 100.0))adjusted_height = max(adjusted_height, scroll_height, 100)logger.info(f"Adjusted height calculated: {adjusted_height} (extension: {extension_percentage}%)")# 11) ใฆใฃใณใใฆใตใคใบใ่ชฟๆดadjusted_width = scroll_widthlogger.info(f"Resizing window to: width={adjusted_width}, height={adjusted_height}")driver.set_window_size(adjusted_width, adjusted_height)time.sleep(1)# ใชใฝใผใน็ถๆ ใ็ขบ่ช - ๅๆ็ในใฏใชใใresource_state = driver.execute_script("""return {readyState: document.readyState,resourcesComplete: !document.querySelector('img:not([complete])') &&!document.querySelector('link[rel="stylesheet"]:not([loaded])')};""")logger.info(f"Resource state: {resource_state}")if resource_state['readyState'] != 'complete':logger.info("Document still loading, waiting additional time...")time.sleep(1)# ใใใใซในใฏใญใผใซdriver.execute_script("window.scrollTo(0, 0);")time.sleep(0.5)logger.info("Scrolled to top.")# 12) ในใฏใชใผใณใทใงใใๅๅพlogger.info("Taking screenshot...")png = driver.get_screenshot_as_png()logger.info("Screenshot taken successfully.")# PIL็ปๅใซๅคๆimg = Image.open(BytesIO(png))logger.info(f"Screenshot dimensions: {img.width}x{img.height}")# ไฝ็ฝใใชใใณใฐif trim_whitespace:img = trim_image_whitespace(img, threshold=248, padding=20)logger.info(f"Trimmed dimensions: {img.width}x{img.height}")return imgexcept Exception as e:logger.error(f"Error during screenshot generation: {e}", exc_info=True)# Return a small black image on errorreturn Image.new('RGB', (1, 1), color=(0, 0, 0))finally:logger.info("Cleaning up...")if driver:try:driver.quit()logger.info("WebDriver quit successfully.")except Exception as e:logger.error(f"Error quitting WebDriver: {e}", exc_info=True)if tmp_path and os.path.exists(tmp_path):try:os.remove(tmp_path)logger.info(f"Temporary file {tmp_path} removed.")except Exception as e:logger.error(f"Error removing temporary file {tmp_path}: {e}", exc_info=True)# --- Geminiใไฝฟใฃใๆฐใใ้ขๆฐ ---def text_to_screenshot(text: str, extension_percentage: float, temperature: float = 0.3,trim_whitespace: bool = True, style: str = "standard") -> Image.Image:"""ใใญในใใGemini APIใงHTMLใซๅคๆใใในใฏใชใผใณใทใงใใใ็ๆใใ็ตฑๅ้ขๆฐ"""try:# 1. ใใญในใใใHTMLใ็ๆ๏ผๆธฉๅบฆใใฉใกใผใฟใจในใฟใคใซใๆธกใ๏ผhtml_code = generate_html_from_text(text, temperature, style)# 2. HTMLใใในใฏใชใผใณใทใงใใใ็ๆreturn render_fullpage_screenshot(html_code, extension_percentage, trim_whitespace)except Exception as e:logger.error(f"ใใญในใใใในใฏใชใผใณใทใงใใ็ๆไธญใซใจใฉใผใ็บ็: {e}", exc_info=True)return Image.new('RGB', (1, 1), color=(0, 0, 0)) # ใจใฉใผๆใฏ้ป็ปๅ# --- FastAPI Setup ---app = FastAPI()# CORS่จญๅฎใ่ฟฝๅapp.add_middleware(CORSMiddleware,allow_origins=["*"],2 unmodified linesallow_headers=["*"],)# ้็ใใกใคใซใฎใตใผใใณใฐ่จญๅฎ# Gradioใฎใใฃใฌใฏใใชใๆข็ดขใใฆใขใปใใใ่ฆใคใใgradio_dir = os.path.dirname(gr.__file__)logger.info(f"Gradio version: {gr.__version__}")logger.info(f"Gradio directory: {gradio_dir}")# ๅบๆฌ็ใช้็ใใกใคใซใใฃใฌใฏใใชใใใฆใณใstatic_dir = os.path.join(gradio_dir, "templates", "frontend", "static")if os.path.exists(static_dir):logger.info(f"Mounting static directory: {static_dir}")app.mount("/static", StaticFiles(directory=static_dir), name="static")# _appใใฃใฌใฏใใชใๆขใ๏ผๆฐใใSvelteKitใใผในใฎใใญใณใใจใณใ็จ๏ผapp_dir = os.path.join(gradio_dir, "templates", "frontend", "_app")if os.path.exists(app_dir):logger.info(f"Mounting _app directory: {app_dir}")app.mount("/_app", StaticFiles(directory=app_dir), name="_app")# assetsใใฃใฌใฏใใชใๆขใassets_dir = os.path.join(gradio_dir, "templates", "frontend", "assets")if os.path.exists(assets_dir):logger.info(f"Mounting assets directory: {assets_dir}")app.mount("/assets", StaticFiles(directory=assets_dir), name="assets")# cdnใใฃใฌใฏใใชใใใใฐ่ฟฝๅcdn_dir = os.path.join(gradio_dir, "templates", "cdn")if os.path.exists(cdn_dir):logger.info(f"Mounting cdn directory: {cdn_dir}")app.mount("/cdn", StaticFiles(directory=cdn_dir), name="cdn")# API Endpoint for screenshot generation@app.post("/api/screenshot",response_class=StreamingResponse,tags=["Screenshot"],summary="Render HTML to Full Page Screenshot",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.")async def api_render_screenshot(request: ScreenshotRequest):"""API endpoint to render HTML and return a screenshot."""try:logger.info(f"API request received. Extension: {request.extension_percentage}%")# Run the blocking Selenium code in a separate thread (FastAPI handles this)pil_image = render_fullpage_screenshot(request.html_code,request.extension_percentage,request.trim_whitespace)if pil_image.size == (1, 1):logger.error("Screenshot generation failed, returning 1x1 error image.")# Optionally return a proper error response instead of 1x1 image# raise HTTPException(status_code=500, detail="Failed to generate screenshot")# Convert PIL Image to PNG bytesimg_byte_arr = BytesIO()pil_image.save(img_byte_arr, format='PNG')img_byte_arr.seek(0) # Go to the start of the BytesIO bufferlogger.info("Returning screenshot as PNG stream.")return StreamingResponse(img_byte_arr, media_type="image/png")except Exception as e:logger.error(f"API Error: {e}", exc_info=True)raise HTTPException(status_code=500, detail=f"Internal Server Error: {e}")# --- ๆฐใใGemini API้ฃๆบใจใณใใใคใณใ ---@app.post("/api/text-to-screenshot",response_class=StreamingResponse,tags=["Screenshot", "Gemini"],summary="ใใญในใใใใคใณใใฉใฐใฉใใฃใใฏใ็ๆ",description="ใใญในใใGemini APIใไฝฟใฃใฆHTMLใคใณใใฉใฐใฉใใฃใใฏใซๅคๆใใในใฏใชใผใณใทใงใใใจใใฆ่ฟใใพใใ")async def api_text_to_screenshot(request: GeminiRequest):"""ใใญในใใใHTMLใคใณใใฉใฐใฉใใฃใใฏใ็ๆใใฆในใฏใชใผใณใทใงใใใ่ฟใAPIใจใณใใใคใณใ"""try:logger.info(f"ใใญในใโในใฏใชใผใณใทใงใใAPIใชใฏใจในใๅไฟกใใใญในใ้ทใ: {len(request.text)}, "f"ๆกๅผต็: {request.extension_percentage}%, ๆธฉๅบฆ: {request.temperature}, "f"ในใฟใคใซ: {request.style}")# ใใญในใใใHTMLใ็ๆใใฆในใฏใชใผใณใทใงใใใไฝๆ๏ผๆธฉๅบฆใใฉใกใผใฟใจในใฟใคใซใๆธกใ๏ผpil_image = text_to_screenshot(request.text,request.extension_percentage,request.temperature,request.trim_whitespace,request.style)if pil_image.size == (1, 1):logger.error("ในใฏใชใผใณใทใงใใ็ๆใซๅคฑๆใใพใใใ1x1ใจใฉใผ็ปๅใ่ฟใใพใใ")# raise HTTPException(status_code=500, detail="ในใฏใชใผใณใทใงใใ็ๆใซๅคฑๆใใพใใ")# PIL็ปๅใPNGใใคใใซๅคๆimg_byte_arr = BytesIO()pil_image.save(img_byte_arr, format='PNG')img_byte_arr.seek(0) # BytesIOใใใใกใฎๅ ้ ญใซๆปใlogger.info("ในใฏใชใผใณใทใงใใใPNGในใใชใผใ ใจใใฆ่ฟใใพใใ")return StreamingResponse(img_byte_arr, media_type="image/png")except Exception as e:logger.error(f"API Error: {e}", exc_info=True)raise HTTPException(status_code=500, detail=f"Internal Server Error: {e}")# --- Gradio Interface Definition ---# ๅ ฅๅใขใผใใฎ้ธๆ็จRadioใณใณใใผใใณใdef process_input(input_mode, input_text, extension_percentage, temperature, trim_whitespace, style):"""ๅ ฅๅใขใผใใซๅฟใใฆ้ฉๅใชๅฆ็ใ่กใ"""if input_mode == "HTMLๅ ฅๅ":# HTMLใขใผใใฎๅ ดๅใฏๆขๅญใฎๅฆ็๏ผในใฟใคใซใฏไฝฟใใชใ๏ผreturn render_fullpage_screenshot(input_text, extension_percentage, trim_whitespace)else:# ใใญในใๅ ฅๅใขใผใใฎๅ ดๅใฏGemini APIใไฝฟ็จreturn text_to_screenshot(input_text, extension_percentage, temperature, trim_whitespace, style)# Gradio UIใฎๅฎ็พฉwith gr.Blocks(title="Full Page Screenshot (ใใญในใๅคๆๅฏพๅฟ)", theme=gr.themes.Base()) as iface:gr.Markdown("# HTMLใใฅใผใข & ใใญในใโใคใณใใฉใฐใฉใใฃใใฏๅคๆ")gr.Markdown("HTMLใณใผใใใฌใณใใชใณใฐใใใใใใญในใใGemini APIใงใคใณใใฉใฐใฉใใฃใใฏใซๅคๆใใฆ็ปๅใจใใฆๅๅพใใพใใ")with gr.Row():input_mode = gr.Radio(["HTMLๅ ฅๅ", "ใใญในใๅ ฅๅ"],label="ๅ ฅๅใขใผใ",value="HTMLๅ ฅๅ")# ๅ ฑ็จใฎใใญในใใใใฏในinput_text = gr.Textbox(lines=15,label="ๅ ฅๅ",placeholder="HTMLใณใผใใพใใฏใใญในใใๅ ฅๅใใฆใใ ใใใๅ ฅๅใขใผใใซๅฟใใฆๅฆ็ใใใพใใ")with gr.Row():with gr.Column(scale=1):# ในใฟใคใซ้ธๆใใญใใใใฆใณstyle_dropdown = gr.Dropdown(choices=["standard", "cute", "resort", "cool", "dental"],value="standard",label="ใใถใคใณในใฟใคใซ",info="ใใญในใโHTMLๅคๆๆใฎใใถใคใณใใผใใ้ธๆใใพใ",visible=False # ใใญในใๅ ฅๅใขใผใใฎๆใ ใ่กจ็คบ)with gr.Column(scale=2):extension_percentage = gr.Slider(minimum=0,maximum=30,step=1.0,value=10, # ใใใฉใซใๅค10%label="ไธไธ้ซใๆกๅผต็๏ผ%๏ผ")# ๆธฉๅบฆ่ชฟๆดในใฉใคใใผ๏ผใใญในใใขใผใๆใฎใฟ่กจ็คบ๏ผtemperature = gr.Slider(minimum=0.0,maximum=1.0,step=0.1,value=0.5, # ใใใฉใซใๅคใ0.5ใซ่จญๅฎlabel="็ๆๆใฎๆธฉๅบฆ๏ผไฝใ=ไธ่ฒซๆง้ซใ้ซใ=ๅต้ ๆง้ซ๏ผ",visible=False # ๆๅใฏ้่กจ๏ฟฝ๏ฟฝ๏ฟฝ)# ไฝ็ฝใใชใใณใฐใชใใทใงใณtrim_whitespace = gr.Checkbox(label="ไฝ็ฝใ่ชๅใใชใใณใฐ",value=True,info="็ๆใใใ็ปๅใใไฝๅใช็ฉบ็ฝ้ ๅใ่ชๅ็ใซๅ้คใใพใ")submit_btn = gr.Button("็ๆ")output_image = gr.Image(type="pil", label="ใใผใธๅ จไฝใฎในใฏใชใผใณใทใงใใ")# ๅ ฅๅใขใผใๅคๆดๆใฎใคใใณใๅฆ็๏ผใใญในใใขใผใๆใฎใฟๆธฉๅบฆในใฉใคใใผใจในใฟใคใซใใญใใใใฆใณใ่กจ็คบ๏ผdef update_controls_visibility(mode):# Gradio 4.x็จใฎใขใใใใผใๆนๆณis_text_mode = mode == "ใใญในใๅ ฅๅ"return [gr.update(visible=is_text_mode), # temperaturegr.update(visible=is_text_mode), # style_dropdown]input_mode.change(fn=update_controls_visibility,inputs=input_mode,outputs=[temperature, style_dropdown])# ็ๆใใฟใณใฏใชใใฏๆใฎใคใใณใๅฆ็submit_btn.click(fn=process_input,inputs=[input_mode, input_text, extension_percentage, temperature, trim_whitespace, style_dropdown],outputs=output_image)# ็ฐๅขๅคๆฐๆ ๅ ฑใ่กจ็คบgemini_model = os.environ.get("GEMINI_MODEL", "gemini-1.5-pro")gr.Markdown(f"""## APIใจใณใใใคใณใ- `/api/screenshot` - HTMLใณใผใใใในใฏใชใผใณใทใงใใใ็ๆ- `/api/text-to-screenshot` - ใใญในใใใใคใณใใฉใฐใฉใใฃใใฏในใฏใชใผใณใทใงใใใ็ๆ## ่จญๅฎๆ ๅ ฑ- ไฝฟ็จใขใใซ: {gemini_model} (็ฐๅขๅคๆฐ GEMINI_MODEL ใงๅคๆดๅฏ่ฝ)- ๅฏพๅฟในใฟใคใซ: standard, cute, resort, cool, dental""")# --- Mount Gradio App onto FastAPI ---app = gr.mount_gradio_app(app, iface, path="/")# --- Run with Uvicorn (for local testing) ---if __name__ == "__main__":import uvicornlogger.info("Starting Uvicorn server for local development...")uvicorn.run(app, host="0.0.0.0", port=7860)123456789101112131415161718192021222324252627284 unmodified lines333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343352 unmodified lines338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473"""Fullโpage HTML renderer & Gemini 2.5 Flash textโtoโinfographic generatorโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโ* Gradio 5.x UI + FastAPI backend* SeleniumโChrome headless fullโpage screenshot* Gemini 1.5โpro ใ 2.5โflashโpreviewโ04โ17 ๅฏพๅฟโ 2.5โflash ใฎใจใใ ใ thinking_budget=0 ใ่ชๅไปไธ"""# โโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโ# ๅบๆฌใฉใคใใฉใช# โโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโimport osimport timeimport tempfileimport loggingfrom io import BytesIOfrom typing import List, Optional# โโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโ# ใตใผใใใผใใฃ# โโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโimport gradio as grfrom fastapi import FastAPI, HTTPExceptionfrom fastapi.responses import StreamingResponsefrom fastapi.staticfiles import StaticFilesfrom fastapi.middleware.cors import CORSMiddleware4 unmodified linesfrom selenium.webdriver.support.ui import WebDriverWaitfrom selenium.webdriver.support import expected_conditions as ECfrom PIL import Imagefrom huggingface_hub import hf_hub_download# โถ ๆฐใใ Gemini SDKfrom google import genai # googleโgenai โฅ1.11.0from google.genai import types # ๅใชใใธใงใฏใ# โโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโ# ใญใฎใณใฐ่จญๅฎ# โโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโlogging.basicConfig(level=logging.INFO)logger = logging.getLogger(__name__)# โโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโ# Pydantic ใขใใซ# โโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโclass GeminiRequest(BaseModel):text: strextension_percentage: float = 10.0temperature: float = 0.5trim_whitespace: bool = Truestyle: str = "standard"class ScreenshotRequest(BaseModel):html_code: strextension_percentage: float = 10.0trim_whitespace: bool = Truestyle: str = "standard"# โโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโ# โ Font Awesome ใฌใคใขใฆใ่ชฟๆด# โโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโdef enhance_font_awesome_layout(html_code: str) -> str:"""Font Awesome ใขใคใณใณใฎ่กจ็คบใบใฌใไฟฎๆญฃใใ่ฟฝๅ CSS ใๆฟๅ ฅ"""fa_fix_css = """<style>/* Font Awesome icon tweaks */[class*="fa-"]{display:inline-block!important;vertical-align:middle!important;margin-right:8px!important;}h1 [class*="fa-"],h2 [class*="fa-"],h3 [class*="fa-"],h4 [class*="fa-"],h5 [class*="fa-"],h6 [class*="fa-"]{margin-right:10px!important;}.fa+span,.fas+span,.far+span,.fab+span,span+.fa,span+.fas,span+.far,span+.fab{display:inline-block!important;margin-left:5px!important;}li [class*="fa-"],p [class*="fa-"]{margin-right:10px!important;}.inline-icon{display:inline-flex!important;align-items:center!important;}[class*="fa-"]+span{display:inline-block!important;vertical-align:middle!important;}</style>"""if "<head>" in html_code:return html_code.replace("</head>", f"{fa_fix_css}</head>")elif "<html" in html_code:head_end = html_code.find("</head>")if head_end > 0:return html_code[:head_end] + fa_fix_css + html_code[head_end:]body_start = html_code.find("<body")if body_start > 0:return html_code[:body_start] + f"<head>{fa_fix_css}</head>" + html_code[body_start:]return f"<html><head>{fa_fix_css}</head>{html_code}</html>"# โโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโ# โก ใทในใใ ใใญใณใใ่ชญใฟ่พผใฟ# โโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโdef load_system_instruction(style: str = "standard") -> str:"""style ใใจใฎ prompt.txt ใใญใผใซใซ or HF Hub ใใๅๅพ"""styles = ["standard", "cute", "resort", "cool", "dental"]if style not in styles:logger.warning(f"็กๅนใชในใฟใคใซ '{style}' โ 'standard' ใไฝฟ็จ")style = "standard"# ใญใผใซใซ firstlocal_path = os.path.join(os.path.dirname(__file__), style, "prompt.txt")if os.path.exists(local_path):with open(local_path, encoding="utf-8") as f:return f.read()# HF Hub fallbacktry:file_path = hf_hub_download(repo_id="tomo2chin2/GURAREKOstlyle",filename=f"{style}/prompt.txt",repo_type="dataset",)with open(file_path, encoding="utf-8") as f:return f.read()except Exception as e:logger.error(f"prompt.txt ๅๅพๅคฑๆ: {e}")raise# โโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโ# โข ็ปๅใฎ็ฉบ็ฝใใชใใณใฐ# โโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโdef trim_image_whitespace(image: Image.Image, threshold: int = 250, padding: int = 10) -> Image.Image:"""็ฝไฝ็ฝใๆคๅบใใใใฃใณใฐใๆฎใใฆๅใ่ฉฐใใ"""gray = image.convert("L")data = gray.getdata()w, h = gray.sizemin_x, min_y, max_x, max_y = w, h, 0, 0pixels = list(data)pixels = [pixels[i * w : (i + 1) * w] for i in range(h)]for y in range(h):for x in range(w):if pixels[y][x] < threshold:min_x, min_y = min(min_x, x), min(min_y, y)max_x, max_y = max(max_x, x), max(max_y, y)if min_x > max_x:return imagemin_x, min_y = max(0, min_x - padding), max(0, min_y - padding)max_x, max_y = min(w - 1, max_x + padding), min(h - 1, max_y + padding)return image.crop((min_x, min_y, max_x + 1, max_y + 1))# โโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโ# โฃ Selenium ใงใใซใใผใธ SS ็ๆ# โโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโdef render_fullpage_screenshot(html_code: str, extension_percentage: float = 6.0, trim_whitespace: bool = True) -> Image.Image:"""HTML ๆๅญๅ โ fullโpage PNG โ PIL.Image"""tmp_path: Optional[str] = Nonedriver: Optional[webdriver.Chrome] = Nonetry:with tempfile.NamedTemporaryFile(suffix=".html", delete=False, mode="w", encoding="utf-8") as tmp:tmp.write(html_code)tmp_path = tmp.nameoptions = Options()options.add_argument("--headless")options.add_argument("--no-sandbox")options.add_argument("--disable-dev-shm-usage")options.add_argument("--force-device-scale-factor=1")driver = webdriver.Chrome(options=options)driver.set_window_size(1200, 1000)driver.get(f"file://{tmp_path}")WebDriverWait(driver, 15).until(EC.presence_of_element_located((By.TAG_NAME, "body")))time.sleep(3) # ๅๆใญใผใๅพ ใก# ็ธฆในใฏใญใผใซใใฆใฌใณใใชใณใฐ็ขบๅฎtotal = driver.execute_script("return Math.max(document.body.scrollHeight, document.documentElement.scrollHeight);")vp = driver.execute_script("return window.innerHeight;")for i in range(max(1, total // vp) + 1):driver.execute_script(f"window.scrollTo(0, {i*(vp-200)});")time.sleep(0.2)driver.execute_script("window.scrollTo(0,0);")time.sleep(1)# ๅ จไฝ้ซใใซไฝ็ฝใ่ฟฝๅtotal = driver.execute_script("return Math.max(document.body.scrollHeight, document.documentElement.scrollHeight);")height = int(total * (1 + extension_percentage / 100))width = driver.execute_script("return Math.max(document.documentElement.scrollWidth, document.body.scrollWidth);")height = min(max(height, 100), 4000)width = min(max(width, 100), 2000)driver.set_window_size(width, height)time.sleep(0.5)png = driver.get_screenshot_as_png()img = Image.open(BytesIO(png))if trim_whitespace:img = trim_image_whitespace(img, threshold=248, padding=20)return imgexcept Exception as e:logger.error(f"Screenshot Error: {e}", exc_info=True)return Image.new("RGB", (1, 1), (0, 0, 0))finally:if driver:try:driver.quit()except Exception:passif tmp_path and os.path.exists(tmp_path):os.remove(tmp_path)# โโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโ# โค Gemini โ HTML ็ๆ# โโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโdef _genai_client(api_key: str) -> genai.Client:return genai.Client(api_key=api_key)def _default_safety() -> List[types.SafetySetting]:return [types.SafetySetting(category="HARM_CATEGORY_HARASSMENT", threshold="BLOCK_MEDIUM_AND_ABOVE"),types.SafetySetting(category="HARM_CATEGORY_HATE_SPEECH", threshold="BLOCK_MEDIUM_AND_ABOVE"),types.SafetySetting(category="HARM_CATEGORY_SEXUALLY_EXPLICIT", threshold="BLOCK_MEDIUM_AND_ABOVE"),types.SafetySetting(category="HARM_CATEGORY_DANGEROUS_CONTENT", threshold="BLOCK_MEDIUM_AND_ABOVE"),]def generate_html_from_text(text: str, temperature: float = 0.3, style: str = "standard") -> str:"""Gemini ใขใใซใใ HTML ใณใผใใ่ฟใใ* ็ฐๅขๅคๆฐ GEMINI_MODEL ใ geminiโ2.5โflash-previewโ04-17 ใฎๅ ดๅ-> thinking_budget=0 ใไปใใฆๅผใณๅบใ"""api_key = os.getenv("GEMINI_API_KEY")if not api_key:raise ValueError("GEMINI_API_KEY ใ่จญๅฎใใใฆใใพใใ")model_name = os.getenv("GEMINI_MODEL", "gemini-1.5-pro")client = _genai_client(api_key)gen_cfg = types.GenerationConfig(temperature=temperature,top_p=0.7,top_k=20,max_output_tokens=8192,candidate_count=1,)safety_cfg = _default_safety()think_cfg = (types.ThinkingConfig(thinking_budget=0)if model_name == "gemini-2.5-flash-preview-04-17"else None)req_cfg_kwargs = dict(generation_config=gen_cfg,safety_settings=safety_cfg,)if think_cfg:req_cfg_kwargs["thinking_config"] = think_cfgreq_cfg = types.GenerateContentConfig(**req_cfg_kwargs)prompt = f"{load_system_instruction(style)}\n\n{text}"logger.info(f"Gemini request โ model={model_name}, temp={temperature}, thinking_budget={0 if think_cfg else None}")rsp = client.models.generate_content(model=model_name, contents=prompt, config=req_cfg)raw = rsp.text or ""start = raw.find("```html")end = raw.rfind("```")if 0 <= start < end:html_code = raw[start + 7 : end].strip()return enhance_font_awesome_layout(html_code)logger.warning("```html``` ใใญใใฏใชใใ็ใฌในใใณในใ่ฟใใพใ")return raw# โโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโ# โฅ ใใญในใ โ ในใฏใชใผใณใทใงใใ็ตฑๅ# โโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโdef text_to_screenshot(text: str,extension_percentage: float,temperature: float = 0.3,trim_whitespace: bool = True,style: str = "standard",) -> Image.Image:try:html = generate_html_from_text(text, temperature, style)return render_fullpage_screenshot(html, extension_percentage, trim_whitespace)except Exception as e:logger.error(e, exc_info=True)return Image.new("RGB", (1, 1), (0, 0, 0))# โโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโ# โฆ FastAPI ใปใใใขใใ# โโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโapp = FastAPI()app.add_middleware(CORSMiddleware,allow_origins=["*"],2 unmodified linesallow_headers=["*"],)# Gradio ใฎ้็ใใกใคใซใใใฆใณใgradio_dir = os.path.dirname(gr.__file__)for sub in [("static", "templates/frontend/static"),("_app", "templates/frontend/_app"),("assets", "templates/frontend/assets"),("cdn", "templates/cdn"),]:target = os.path.join(gradio_dir, sub[1])if os.path.exists(target):app.mount(f"/{sub[0]}", StaticFiles(directory=target), name=sub[0])logger.info(f"Mounted /{sub[0]} โ {target}")# โโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโ# โง API ใจใณใใใคใณใ# โโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโ@app.post("/api/screenshot",response_class=StreamingResponse,tags=["Screenshot"],summary="HTML โ Fullโpage Screenshot",)async def api_render_screenshot(req: ScreenshotRequest):img = render_fullpage_screenshot(req.html_code, req.extension_percentage, req.trim_whitespace)buf = BytesIO()img.save(buf, format="PNG")buf.seek(0)return StreamingResponse(buf, media_type="image/png")@app.post("/api/text-to-screenshot",response_class=StreamingResponse,tags=["Screenshot", "Gemini"],summary="Text โ Gemini โ Infographic Screenshot",)async def api_text_to_screenshot(req: GeminiRequest):img = text_to_screenshot(req.text,req.extension_percentage,req.temperature,req.trim_whitespace,req.style,)buf = BytesIO()img.save(buf, format="PNG")buf.seek(0)return StreamingResponse(buf, media_type="image/png")# โโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโ# โจ Gradio UI# โโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโdef process_input(input_mode, input_text, extension_percentage, temperature, trim_whitespace, style):if input_mode == "HTMLๅ ฅๅ":return render_fullpage_screenshot(input_text, extension_percentage, trim_whitespace)return text_to_screenshot(input_text, extension_percentage, temperature, trim_whitespace, style)with gr.Blocks(title="Full Page Screenshot + Gemini 2.5 Flash") as iface:gr.Markdown("## HTML ใใฅใผใข & ใใญในใ โ ใคใณใใฉใฐใฉใใฃใใฏ")input_mode = gr.Radio(["HTMLๅ ฅๅ", "ใใญในใๅ ฅๅ"], value="HTMLๅ ฅๅ", label="ๅ ฅๅใขใผใ")input_text = gr.Textbox(lines=15, label="ๅ ฅๅ")with gr.Row():style_dd = gr.Dropdown(["standard", "cute", "resort", "cool", "dental"],value="standard",label="ใใถใคใณในใฟใคใซ",visible=False,)extension_slider = gr.Slider(0, 30, 10, label="ไธไธ้ซใๆกๅผต็(%)")temperature_slider = gr.Slider(0.0,1.0,0.5,step=0.1,label="็ๆๆธฉๅบฆ",visible=False,)trim_cb = gr.Checkbox(value=True, label="ไฝ็ฝ่ชๅใใชใใณใฐ")btn = gr.Button("็ๆ")out_img = gr.Image(type="pil", label="ในใฏใชใผใณใทใงใใ")def _vis(mode):is_text = mode == "ใใญในใๅ ฅๅ"return [{"visible": is_text, "__type__": "update"},{"visible": is_text, "__type__": "update"},]input_mode.change(_vis, input_mode, [temperature_slider, style_dd])btn.click(process_input,[input_mode,input_text,extension_slider,temperature_slider,trim_cb,style_dd,],out_img,)gr.Markdown(f"""### ็ฐๅข* ไฝฟ็จใขใใซ: `{os.getenv('GEMINI_MODEL', 'gemini-1.5-pro')}`* thinking_budget=0 ใฏ `gemini-2.5-flash-preview-04-17` ไฝฟ็จๆใฎใฟ่ชๅไปไธ""")# โโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโ# โฉ FastAPI ใซ Gradio ใใใฆใณใ# โโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโapp = gr.mount_gradio_app(app, iface, path="/")# โโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโ# โช ็ดๆฅๅฎ่กๆ# โโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโif __name__ == "__main__":import uvicornlogger.info("Starting dev server at http://localhost:7860")uvicorn.run(app, host="0.0.0.0", port=7860)
app.py+383-700