Spaces:
Paused
Paused
Update app.py
Browse files170 unmodified lines1711721731741751761771785 unmodified lines184185186187188189190191192193194195196197198199163 unmodified lines3633643653663673683693701 unmodified line3723733743753763773783793803813823833843853 unmodified lines3893903913923933943951 unmodified line3973983994004014022 unmodified lines4054064074084094104111 unmodified line41341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947012 unmodified lines4834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615628 unmodified lines571572573574575576577217 unmodified lines795796797798170 unmodified lines- フォント指定:```html<style>@ import url('https ://fonts.googleapis.com/css2?family=Kaisei+Decol&family=Yomogi&family=Zen+Kurenaido&display=swap');@ import url('https ://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.4.0/css/all.min.css');</style>```### 5. レイアウト5 unmodified lines- 横幅は100%- 重要な要素は中央寄り、補足情報は周辺部に配置### 重要なレイアウト注意事項- Font Awesomeアイコンと文字が重ならないよう適切なマージンを設定する- アイコンには必ず`margin-right: 10px;`や`margin-left: 10px;`などの余白を設定する- アイコンと文字列は必ず`display: inline-block;`または`display: inline-flex;`で配置し、`align-items: center;`を使用する- 複数のアイコンを配置する場合は十分な余白を確保する- レイアウト崩れを防ぐために、親要素には`overflow: hidden;`を適用する- アイコンの配置はコンテンツフローを妨げないよう注意する- カード内でのアイコン配置は、絶対位置指定ではなく相対位置で設定する- モバイル表示も考慮し、レスポンシブ対応を徹底する## グラフィックレコーディング表現技法- テキストと視覚要素のバランスを重視(文字情報の50%以上をFont Awesomeアイコンで視覚的に補完)- キーワードを囲み線や色で強調し、関連するFont Awesomeアイコンを必ず添える163 unmodified lineslogger.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:"""1 unmodified lineArgs: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:3 unmodified lineslogger.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()1 unmodified lineoptions.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")2 unmodified linesdriver = webdriver.Chrome(options=options)logger.info("WebDriver initialized.")# 3) 初期ウィンドウサイズを設定initial_width = 1200initial_height = 1000driver.set_window_size(initial_width, initial_height)1 unmodified linelogger.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,12 unmodified linesdocument.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}")return Image.new('RGB', (1, 1), color=(0, 0, 0))finally:logger.info("Cleaning up...")if driver:8 unmodified lineslogger.info(f"Temporary file {tmp_path} removed.")except Exception as e:logger.error(f"Error removing temporary file {tmp_path}: {e}")# --- Geminiを使った新しい関数 ---def text_to_screenshot(text: str, extension_percentage: float, temperature: float = 0.3, trim_whitespace: bool = True) -> Image.Image:"""テキストをGemini APIでHTMLに変換し、スクリーンショットを生成する統合関数"""217 unmodified linesif __name__ == "__main__":import uvicornlogger.info("Starting Uvicorn server for local development...")uvicorn.run(app, host="0.0.0.0", port=7860)170 unmodified lines1711721731741751761771785 unmodified lines184185186187188189163 unmodified lines3533543553563573583591 unmodified line3613623633643653663673683693703713723733743 unmodified lines3783793803813823833841 unmodified line3863873883893903913922 unmodified lines3953963973983994004011 unmodified line40340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849912 unmodified lines5125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476488 unmodified lines657658659660661662663217 unmodified lines881882883884170 unmodified lines- フォント指定:```html<style>@ import url('https://fonts.googleapis.com/css2?family=Kaisei+Decol&family=Yomogi&family=Zen+Kurenaido&display=swap');@ import url('https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.4.0/css/all.min.css');</style>```### 5. レイアウト5 unmodified lines- 横幅は100%- 重要な要素は中央寄り、補足情報は周辺部に配置## グラフィックレコーディング表現技法- テキストと視覚要素のバランスを重視(文字情報の50%以上をFont Awesomeアイコンで視覚的に補完)- キーワードを囲み線や色で強調し、関連するFont Awesomeアイコンを必ず添える163 unmodified lineslogger.info(f"画像をトリミングしました: 元サイズ {width}x{height} → トリミング後 {trimmed.width}x{trimmed.height}")return trimmed# --- Core Screenshot Logic ---def render_fullpage_screenshot(html_code: str, extension_percentage: float = 6.0,trim_whitespace: bool = True) -> Image.Image:"""1 unmodified lineArgs:html_code: The HTML source code string.extension_percentage: Percentage of extra space to add vertically (e.g., 4 means 4% total).trim_whitespace: Whether to trim excess whitespace from the image.Returns:A PIL Image object of the screenshot. Returns a 1x1 black image on error."""tmp_path = None # 初期化driver = None # 初期化# 1) Save HTML code to a temporary filetry:3 unmodified lineslogger.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()1 unmodified lineoptions.add_argument("--no-sandbox")options.add_argument("--disable-dev-shm-usage")options.add_argument("--force-device-scale-factor=1")# Font Awesomeが読み込まれない場合があるため、読み込み待機時間を長く設定options.add_argument("--disable-features=NetworkService")options.add_argument("--dns-prefetch-disable")2 unmodified linesdriver = webdriver.Chrome(options=options)logger.info("WebDriver initialized.")# 3) 初期ウィンドウサイズを設定(コンテンツの種類に関わらず同じサイズ)initial_width = 1200initial_height = 1000driver.set_window_size(initial_width, initial_height)1 unmodified linelogger.info(f"Navigating to {file_url}")driver.get(file_url)# 4) Wait for page load with extended timeoutlogger.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 potential resource loading...")# リソース読み込みの待機時間time.sleep(3) # 初期待機# 5) Font Awesomeと外部リソースの読み込み完了を確認try:# 修正後のresource_check_script: arrow functionを廃止し、function式に置換resource_check_script = """return new Promise(function(resolve) {function checkFontAwesome() {var icons = document.querySelectorAll('.fa, .fas, .far, .fab, [class*=\\"fa-\\" ]');if (icons.length > 0) {console.log('Font Awesome icons found:', icons.length);document.fonts.ready.then(function() {console.log('All fonts loaded');setTimeout(resolve, 1000);});} else {document.fonts.ready.then(function() { setTimeout(resolve, 500); });}}if (document.readyState === 'complete') {checkFontAwesome();} else {window.addEventListener('load', checkFontAwesome);}});"""logger.info("Waiting for Font Awesome and other resources to load...")driver.set_script_timeout(15) # 15秒のタイムアウトdriver.execute_async_script("const callback = arguments[arguments.length - 1]; " + resource_check_script.strip() + ".then(callback);")logger.info("Resources loaded successfully")except Exception as e:logger.warning(f"Resource loading check failed: {e}. Using fallback wait.")time.sleep(8) # より長い待機時間を設定# 6) スクロールを制御してコンテンツ全体が描画されるようにするtry:// 修正後のscroll_script: function式に置換scroll_script = """return new Promise(function(resolve) {var height = Math.max(document.documentElement.scrollHeight,document.body.scrollHeight);var viewportHeight = window.innerHeight;var scrollStep = Math.floor(viewportHeight * 0.8);var currentPos = 0;function scrollDown() {if (currentPos < height) {window.scrollTo(0, currentPos);currentPos += scrollStep;setTimeout(scrollDown, 100);} else {window.scrollTo(0, 0);setTimeout(resolve, 300);}}scrollDown();});"""logger.info("Ensuring all content is rendered...")driver.execute_async_script("const callback = arguments[arguments.length - 1]; " + scroll_script.strip() + ".then(callback);")except Exception as e:logger.warning(f"Content rendering check failed: {e}")# スクロールを元の位置に戻すdriver.execute_script("window.scrollTo(0, 0);")time.sleep(1)# 7) Hide scrollbars via CSStry:driver.execute_script("document.documentElement.style.overflow = 'hidden';""document.body.style.overflow = 'hidden';")logger.info("Scrollbars hidden via JS.")except Exception as e:logger.warning(f"Could not hide scrollbars via JS: {e}")# 8) Get full page dimensions accurately with improved scripttry:// より正確なページ寸法を取得するためのJavaScriptコードdimensions_script = """return {width: Math.max(document.documentElement.scrollWidth,12 unmodified linesdocument.body ? document.body.clientHeight : 0)};"""dimensions = driver.execute_script(dimensions_script)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(1) # スクロール完了を待つdriver.execute_script("window.scrollTo(0, 0);")time.sleep(1) # 元の位置に戻す# 再検証dimensions_after_scroll = driver.execute_script(dimensions_script)scroll_height = max(scroll_height, dimensions_after_scroll['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, 6000) # 最大高さexcept Exception as e:logger.error(f"Error getting page dimensions: {e}")# フォールバックとしてデフォルト値を設定scroll_width = 1200scroll_height = 1000logger.warning(f"Falling back to dimensions: width={scroll_width}, height={scroll_height}")# 9) レイアウト安定化の確認try:// 修正後のstability_script: arrow functionをfunction式に置換stability_script = """return new Promise(function(resolve) {var lastHeight = document.body.offsetHeight;var lastWidth = document.body.offsetWidth;var stableCount = 0;function checkStability() {var currentHeight = document.body.offsetHeight;var currentWidth = document.body.offsetWidth;if (currentHeight === lastHeight && currentWidth === lastWidth) {stableCount++;if (stableCount >= 3) {resolve(true);return;}} else {stableCount = 0;lastHeight = currentHeight;lastWidth = currentWidth;}setTimeout(checkStability, 200);}checkStability();});"""logger.info("Checking layout stability...")driver.execute_async_script("const callback = arguments[arguments.length - 1]; " + stability_script.strip() + ".then(callback);")logger.info("Layout is stable")except Exception as e:logger.warning(f"Layout stability check failed: {e}")time.sleep(2) # 追加待機# 10) Calculate adjusted height with user-specified marginadjusted_height = int(scroll_height * (1 + extension_percentage / 100.0))# Ensure adjusted height is not excessively large or smalladjusted_height = max(adjusted_height, scroll_height, 100) # 最小高さを確保logger.info(f"Adjusted height calculated: {adjusted_height} (extension: {extension_percentage}%)")# 11) Set window size to full page dimensionsadjusted_width = scroll_widthlogger.info(f"Resizing window to: width={adjusted_width}, height={adjusted_height}")driver.set_window_size(adjusted_width, adjusted_height)logger.info("Waiting for layout stabilization after resize...")# レイアウト安定化のための待機time.sleep(4) # 統一した待機時間# 外部リソースの読み込み状態を確認try: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(2)except Exception as e:logger.warning(f"Error checking resource state: {e}")# Scroll to top just in casetry:driver.execute_script("window.scrollTo(0, 0)")time.sleep(1)logger.info("Scrolled to top.")except Exception as e:logger.warning(f"Could not scroll to top: {e}")# 12) Take screenshotlogger.info("Taking screenshot...")png = driver.get_screenshot_as_png()logger.info("Screenshot taken successfully.")# Convert to PIL Imageimg = 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"An error occurred during screenshot generation: {e}", exc_info=True)return Image.new('RGB', (1, 1), color=(0, 0, 0)) # Return black 1x1 image on errorfinally:logger.info("Cleaning up...")if driver:8 unmodified lineslogger.info(f"Temporary file {tmp_path} removed.")except Exception as e:logger.error(f"Error removing temporary file {tmp_path}: {e}")# --- Geminiを使った新しい関数 ---def text_to_screenshot(text: str, extension_percentage: float, temperature: float = 0.3, trim_whitespace: bool = True) -> Image.Image:"""テキストをGemini APIでHTMLに変換し、スクリーンショットを生成する統合関数"""217 unmodified linesif __name__ == "__main__":import uvicornlogger.info("Starting Uvicorn server for local development...")uvicorn.run(app, host="0.0.0.0", port=7860)
app.py+199-113