| | import gradio as gr |
| | from fastapi import FastAPI, HTTPException, Body |
| | from fastapi.responses import StreamingResponse |
| | from fastapi.staticfiles import StaticFiles |
| | from fastapi.middleware.cors import CORSMiddleware |
| | from pydantic import BaseModel |
| | from selenium import webdriver |
| | from selenium.webdriver.chrome.options import Options |
| | from selenium.webdriver.common.by import By |
| | from selenium.webdriver.support.ui import WebDriverWait |
| | from selenium.webdriver.support import expected_conditions as EC |
| | from PIL import Image |
| | from io import BytesIO |
| | import tempfile |
| | import time |
| | import os |
| | import logging |
| |
|
| | |
| | import google.generativeai as genai |
| |
|
| | |
| | logging.basicConfig(level=logging.INFO) |
| | logger = logging.getLogger(__name__) |
| |
|
| | |
| | class GeminiRequest(BaseModel): |
| | """Geminiへのリクエストデータモデル""" |
| | text: str |
| | extension_percentage: float = 8.0 |
| |
|
| | def generate_html_from_text(text): |
| | """テキストからHTMLを生成する""" |
| | try: |
| | |
| | api_key = os.environ.get("GEMINI_API_KEY") |
| | if not api_key: |
| | logger.error("GEMINI_API_KEY 環境変数が設定されていません") |
| | raise ValueError("GEMINI_API_KEY 環境変数が設定されていません") |
| | |
| | |
| | genai.configure(api_key=api_key) |
| | |
| | |
| | system_instruction = """# グラフィックレコーディング風インフォグラフィック変換プロンプト V2 |
| | ## 目的 |
| | 以下の内容を、超一流デザイナーが作成したような、日本語で完璧なグラフィックレコーディング風のHTMLインフォグラフィックに変換してください。情報設計とビジュアルデザインの両面で最高水準を目指します。 |
| | 手書き風の図形やFont Awesomeアイコンを大きく活用して内容を視覚的かつ直感的に表現します。 |
| | |
| | ## デザイン仕様 |
| | ### 1. カラースキーム |
| | ``` |
| | <palette> |
| | <color name='MysticLibrary-1' rgb='2E578C' r='46' g='87' b='140' /> |
| | <color name='MysticLibrary-2' rgb='182D40' r='24' g='45' b='64' /> |
| | <color name='MysticLibrary-3' rgb='BF807A' r='191' g='128' b='122' /> |
| | <color name='MysticLibrary-4' rgb='592A2A' r='89' g='42' b='42' /> |
| | <color name='MysticLibrary-5' rgb='F2F2F2' r='242' g='242' b='242' /> |
| | </palette> |
| | ``` |
| | ### 2. グラフィックレコーディング要素 |
| | - 左上から右へ、上から下へと情報を順次配置 |
| | - 日本語の手書き風フォントの使用(Yomogi, Zen Kurenaido, Kaisei Decol) |
| | - 手描き風の囲み線、矢印、バナー、吹き出し |
| | - テキストと視覚要素(Font Awesomeアイコン、シンプルな図形)の組み合わせ |
| | - Font Awesomeアイコンは各セクションの内容を表現するものを大きく(2x〜3x)表示 |
| | - キーワードごとに関連するFont Awesomeアイコンを隣接配置 |
| | - キーワードの強調(色付き下線、マーカー効果、Font Awesomeによる装飾) |
| | - 関連する概念を線や矢印で接続し、接続部にもFont Awesomeアイコン(fa-arrow-right, fa-connection等)を挿入 |
| | - Font Awesomeアニメーション効果(fa-beat, fa-bounce, fa-fade, fa-flip, fa-shake, fa-spin)を適切に活用 |
| | - 重要なポイントには「fa-circle-exclamation」や「fa-lightbulb」などのアイコンを目立つ大きさで配置 |
| | - 数値やデータには「fa-chart-line」や「fa-percent」などの関連アイコンを添える |
| | - 感情や状態を表すには表情アイコン(fa-face-smile, fa-face-frown等)を活用 |
| | - アイコンにホバー効果(色変化、サイズ変化)を付与 |
| | - 背景にはFont Awesomeの薄いパターンを配置(fa-shapes等を透過度を下げて配置) |
| | ### 3. アニメーション効果 |
| | - Font Awesomeアイコンに連動するアニメーション(fa-beat, fa-bounce, fa-fade等) |
| | - 重要キーワード出現時のハイライト効果(グラデーション変化) |
| | - 接続線や矢印の流れるようなアニメーション |
| | - アイコンの回転・拡大縮小アニメーション(特に注目させたい箇所) |
| | - 背景グラデーションの緩やかな変化 |
| | - スクロールに連動した要素の出現効果 |
| | - クリック/タップでアイコンが反応する効果 |
| | ### 4. タイポグラフィ |
| | - タイトル:32px、グラデーション効果、太字、Font Awesomeアイコンを左右に配置 |
| | - サブタイトル:16px、#475569、関連するFont Awesomeアイコンを添える |
| | - セクション見出し:18px、# 1e40af、左側にFont Awesomeアイコンを必ず配置し、アイコンにはアニメーション効果 |
| | - 本文:14px、#334155、行間1.4、重要キーワードには関連するFont Awesomeアイコンを小さく添える |
| | - フォント指定: |
| | ```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. レイアウト |
| | - ヘッダー:左揃えタイトル(大きなFont Awesomeアイコンを添える)+右揃え日付/出典 |
| | - 3カラム構成:左側33%、中央33%、右側33% |
| | - カード型コンポーネント:白背景、角丸12px、微細シャドウ、右上にFont Awesomeアイコンを配置 |
| | - セクション間の適切な余白と階層構造(階層を示すFont Awesomeアイコンを活用) |
| | - 適切にグラスモーフィズムを活用(背後にぼかしたFont Awesomeアイコンを配置) |
| | - 横幅は100% |
| | - 重要な要素は中央寄り、補足情報は周辺部に配置 |
| | ## グラフィックレコーディング表現技法 |
| | - テキストと視覚要素のバランスを重視(文字情報の50%以上をFont Awesomeアイコンで視覚的に補完) |
| | - キーワードを囲み線や色で強調し、関連するFont Awesomeアイコンを必ず添える |
| | - 概念ごとに最適なFont Awesomeアイコンを選定(抽象的な概念には複数の関連アイコンを組み合わせて表現) |
| | - 数値データは簡潔なグラフや図表で表現し、データ種類に応じたFont Awesomeアイコン(fa-chart-pie, fa-chart-column等)を配置 |
| | - 接続線や矢印で情報間の関係性を明示し、関係性の種類に応じたアイコン(fa-link, fa-code-branch等)を添える |
| | - 余白を効果的に活用して視認性を確保(余白にも薄いFont Awesomeパターンを配置可) |
| | - コントラストと色の使い分けでメリハリを付け、カラースキームに沿ったアイコン色を活用 |
| | ## Font Awesomeアイコン活用ガイドライン |
| | - 概念カテゴリー別の推奨アイコン: |
| | - 時間・順序:fa-clock, fa-hourglass, fa-calendar, fa-timeline |
| | - 場所・位置:fa-location-dot, fa-map, fa-compass, fa-globe |
| | - 人物・組織:fa-user, fa-users, fa-building, fa-sitemap |
| | - 行動・活動:fa-person-running, fa-gears, fa-hammer, fa-rocket |
| | - 思考・アイデア:fa-brain, fa-lightbulb, fa-thought-bubble, fa-comments |
| | - 感情・状態:fa-face-smile, fa-face-sad-tear, fa-heart, fa-temperature-half |
| | - 成長・変化:fa-seedling, fa-arrow-trend-up, fa-chart-line, fa-diagram-project |
| | - 問題・課題:fa-triangle-exclamation, fa-circle-question, fa-bug, fa-ban |
| | - 解決・成功:fa-check, fa-trophy, fa-handshake, fa-key |
| | - アイコンサイズの使い分け: |
| | - 主要概念:3x(fa-3x) |
| | - 重要キーワード:2x(fa-2x) |
| | - 補足情報:1x(標準サイズ) |
| | - 装飾的要素:lg(fa-lg) |
| | - アニメーション効果の適切な使い分け: |
| | - 注目喚起:fa-beat, fa-shake |
| | - 継続的プロセス:fa-spin, fa-pulse |
| | - 状態変化:fa-flip, fa-fade |
| | - 新規情報:fa-bounce |
| | ## 全体的な指針 |
| | - 読み手が自然に視線を移動できる配置(Font Awesomeアイコンで視線誘導) |
| | - 情報の階層と関連性を視覚的に明確化(階層ごとにアイコンのサイズや色を変える) |
| | - 手書き風の要素とFont Awesomeアイコンを組み合わせて親しみやすさとプロフェッショナル感を両立 |
| | - 大きなFont Awesomeアイコンを活用した視覚的な記憶に残るデザイン(各セクションに象徴的なアイコンを配置) |
| | - フッターに出典情報と関連するFont Awesomeアイコン(fa-book, fa-citation等)を明記 |
| | ## 変換する文章/記事 |
| | ーーー<ユーザーが入力(または添付)>ーーー""" |
| | |
| | |
| | logger.info(f"Gemini APIにリクエストを送信: テキスト長さ = {len(text)}") |
| | |
| | |
| | try: |
| | models = genai.list_models() |
| | logger.info(f"利用可能なモデル: {[m.name for m in models if 'gemini' in m.name]}") |
| | except Exception as e: |
| | logger.warning(f"モデル一覧取得エラー: {e}") |
| | |
| | |
| | try: |
| | model = genai.GenerativeModel('gemini-1.5-pro') |
| | except Exception as e: |
| | logger.warning(f"gemini-1.5-proモデル利用不可: {e}, gemini-proを試します") |
| | model = genai.GenerativeModel('gemini-pro') |
| | |
| | |
| | generation_config = { |
| | "temperature": 0.7, |
| | "top_p": 0.95, |
| | "top_k": 64, |
| | "max_output_tokens": 8192, |
| | } |
| | |
| | |
| | prompt = f"{system_instruction}\n\n{text}" |
| | |
| | |
| | response = model.generate_content( |
| | prompt, |
| | generation_config=generation_config |
| | ) |
| | |
| | |
| | raw_response = response.text |
| | |
| | |
| | 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_code = raw_response[html_start:html_end].strip() |
| | logger.info(f"HTMLの生成に成功: 長さ = {len(html_code)}") |
| | return html_code |
| | else: |
| | |
| | logger.warning("レスポンスから```html```タグが見つかりませんでした。全テキストを返します。") |
| | return raw_response |
| | |
| | except Exception as e: |
| | logger.error(f"HTML生成中にエラーが発生: {e}", exc_info=True) |
| | raise Exception(f"Gemini APIでのHTML生成に失敗しました: {e}") |
| |
|
| | |
| | def render_fullpage_screenshot(html_code: str, extension_percentage: float) -> 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 (e.g., 4 means 4% total). |
| | |
| | Returns: |
| | A PIL Image object of the screenshot. Returns a 1x1 black image on error. |
| | """ |
| | tmp_path = None |
| | driver = None |
| |
|
| | |
| | try: |
| | with tempfile.NamedTemporaryFile(suffix=".html", delete=False, mode='w', encoding='utf-8') as tmp_file: |
| | tmp_path = tmp_file.name |
| | tmp_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)) |
| |
|
| | |
| | options = 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") |
| | |
| | |
| | |
| |
|
| | try: |
| | logger.info("Initializing WebDriver...") |
| | driver = webdriver.Chrome(options=options) |
| | logger.info("WebDriver initialized.") |
| |
|
| | |
| | driver.set_window_size(1200, 800) |
| | file_url = "file://" + tmp_path |
| | logger.info(f"Navigating to {file_url}") |
| | driver.get(file_url) |
| |
|
| | |
| | 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 potential resource loading...") |
| | time.sleep(3) |
| |
|
| | |
| | try: |
| | 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}") |
| |
|
| | |
| | try: |
| | scroll_width = driver.execute_script( |
| | "return Math.max(document.body.scrollWidth, document.documentElement.scrollWidth, document.body.offsetWidth, document.documentElement.offsetWidth)" |
| | ) |
| | scroll_height = driver.execute_script( |
| | "return Math.max(document.body.scrollHeight, document.documentElement.scrollHeight, document.body.offsetHeight, document.documentElement.offsetHeight)" |
| | ) |
| | logger.info(f"Detected dimensions: width={scroll_width}, height={scroll_height}") |
| | |
| | scroll_width = max(scroll_width, 100) |
| | scroll_height = max(scroll_height, 100) |
| |
|
| | except Exception as e: |
| | logger.error(f"Error getting page dimensions: {e}") |
| | |
| | scroll_width = 1200 |
| | scroll_height = 800 |
| | logger.warning(f"Falling back to dimensions: width={scroll_width}, height={scroll_height}") |
| |
|
| | |
| | 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}%)") |
| |
|
| | |
| | logger.info(f"Resizing window to: width={scroll_width}, height={adjusted_height}") |
| | driver.set_window_size(scroll_width, adjusted_height) |
| | logger.info("Waiting for layout stabilization after resize...") |
| | time.sleep(3) |
| |
|
| | |
| | try: |
| | 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}") |
| |
|
| | |
| | logger.info("Taking screenshot...") |
| | png = driver.get_screenshot_as_png() |
| | logger.info("Screenshot taken successfully.") |
| |
|
| | |
| | img = Image.open(BytesIO(png)) |
| | return img |
| |
|
| | except 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)) |
| | 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}") |
| | 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}") |
| |
|
| | |
| | def text_to_screenshot(text: str, extension_percentage: float) -> Image.Image: |
| | """テキストをGemini APIでHTMLに変換し、スクリーンショットを生成する統合関数""" |
| | try: |
| | |
| | html_code = generate_html_from_text(text) |
| | |
| | |
| | return render_fullpage_screenshot(html_code, extension_percentage) |
| | except Exception as e: |
| | logger.error(f"テキストからスクリーンショット生成中にエラーが発生: {e}", exc_info=True) |
| | return Image.new('RGB', (1, 1), color=(0, 0, 0)) |
| |
|
| | |
| | app = FastAPI() |
| |
|
| | |
| | app.add_middleware( |
| | CORSMiddleware, |
| | allow_origins=["*"], |
| | allow_credentials=True, |
| | allow_methods=["*"], |
| | allow_headers=["*"], |
| | ) |
| |
|
| | |
| | |
| | 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_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_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_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") |
| |
|
| | |
| | class ScreenshotRequest(BaseModel): |
| | html_code: str |
| | extension_percentage: float = 8.0 |
| |
|
| | |
| | @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}%") |
| | |
| | pil_image = render_fullpage_screenshot( |
| | request.html_code, |
| | request.extension_percentage |
| | ) |
| |
|
| | if pil_image.size == (1, 1): |
| | logger.error("Screenshot generation failed, returning 1x1 image.") |
| | |
| | |
| |
|
| | |
| | img_byte_arr = BytesIO() |
| | pil_image.save(img_byte_arr, format='PNG') |
| | img_byte_arr.seek(0) |
| |
|
| | logger.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}") |
| |
|
| | |
| | @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)}, 拡張率: {request.extension_percentage}%") |
| | |
| | |
| | pil_image = text_to_screenshot( |
| | request.text, |
| | request.extension_percentage |
| | ) |
| |
|
| | if pil_image.size == (1, 1): |
| | logger.error("スクリーンショット生成に失敗しました。1x1画像を返します。") |
| | |
| |
|
| | |
| | img_byte_arr = BytesIO() |
| | pil_image.save(img_byte_arr, format='PNG') |
| | img_byte_arr.seek(0) |
| |
|
| | 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}") |
| |
|
| | |
| | |
| | def process_input(input_mode, html_input, text_input, extension_percentage): |
| | """入力モードに応じて適切な処理を行う""" |
| | if input_mode == "HTML入力": |
| | |
| | return render_fullpage_screenshot(html_input, extension_percentage) |
| | else: |
| | |
| | return text_to_screenshot(text_input, extension_percentage) |
| |
|
| | |
| | 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入力" |
| | ) |
| | |
| | with gr.Tabs(): |
| | with gr.TabItem("HTML入力"): |
| | html_input = gr.Textbox( |
| | lines=15, |
| | label="HTMLコード入力", |
| | placeholder="<!DOCTYPE html>\n<html>\n<head>\n <title>Example</title>\n</head>\n<body>\n <h1>Hello World</h1>\n</body>\n</html>" |
| | ) |
| | |
| | with gr.TabItem("テキスト入力"): |
| | text_input = gr.Textbox( |
| | lines=15, |
| | label="テキスト入力 (Geminiで変換)", |
| | placeholder="ここにテキストを入力すると、Gemini APIによってグラフィカルなHTMLに変換されます。" |
| | ) |
| | |
| | extension_percentage = gr.Slider( |
| | minimum=0, |
| | maximum=20, |
| | step=1.0, |
| | value=8, |
| | label="上下高さ拡張率(%)" |
| | ) |
| | |
| | submit_btn = gr.Button("生成") |
| | output_image = gr.Image(type="pil", label="ページ全体のスクリーンショット") |
| | |
| | submit_btn.click( |
| | fn=process_input, |
| | inputs=[input_mode, html_input, text_input, extension_percentage], |
| | outputs=output_image |
| | ) |
| | |
| | gr.Markdown(""" |
| | ## APIエンドポイント |
| | - `/api/screenshot` - HTMLコードからスクリーンショットを生成 |
| | - `/api/text-to-screenshot` - テキストからインフォグラフィックスクリーンショットを生成 |
| | """) |
| |
|
| | |
| | app = gr.mount_gradio_app(app, iface, path="/") |
| |
|
| | |
| | if __name__ == "__main__": |
| | import uvicorn |
| | logger.info("Starting Uvicorn server for local development...") |
| | uvicorn.run(app, host="0.0.0.0", port=7860) |