tomo2chin2's picture
Update app.py
178eeaf verified
raw
history blame
50.2 kB
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 re
# 正しいGemini関連のインポート
import google.generativeai as genai
# ロギング設定
logging.basicConfig(level=logging.INFO)
logger = logging.getLogger(__name__)
# --- Gemini統合 ---
class GeminiRequest(BaseModel):
"""Geminiへのリクエストデータモデル"""
text: str
extension_percentage: float = 6.0 # デフォルト値6%
temperature: float = 1.0 # デフォルト値1.0の温度パラメータ
trim_whitespace: bool = True # 余白トリミングオプション(デフォルト有効)
layout_type: str = "standard" # レイアウトタイプ(standard, spaced, compact)
class ScreenshotRequest(BaseModel):
"""スクリーンショットリクエストモデル"""
html_code: str
extension_percentage: float = 6.0 # デフォルト値6%
trim_whitespace: bool = True # 余白トリミングオプション(デフォルト有効)
def generate_html_from_text(text, temperature=1.0, layout_type="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)
# レイアウトタイプに応じた追加設定
layout_adjustments = ""
if layout_type == "spaced":
layout_adjustments = """
## 特別なスタイル設定
- 全てのテキスト要素には最低2rem以上の行間と要素間マージンを設定する
- 各カードのパディングを1.5倍に増やす
- 箇条書きリストのアイテム間は1.5emの間隔を確保する
- すべての文字サイズを15%大きくする
- 内容量に応じて自動的にグリッドやフレックスレイアウトを調整する
- テキストが重ならないように要素間に十分なスペースを強制的に設ける
"""
elif layout_type == "compact":
layout_adjustments = """
## 特別なスタイル設定
- レイアウトをよりコンパクトに配置
- 小さめのアイコンサイズを使用(標準の75%)
- フォントサイズを10%小さく設定
- テキスト量が多い場合は自動的に複数列に分割表示
"""
# レイアウト崩れ防止のための追加指示
layout_improvements = """
## 重要なレイアウト指示(必ず守ってください)
- カード要素は必ずdisplay: gridまたはflexboxで配置してください
- カードの配置は絶対位置(position: absolute)を使わず、フロー配置を使ってください
- 各カードには以下のスタイルを必ず適用してください:
```css
.card {
position: relative;
clear: both;
display: flex;
flex-direction: column;
margin: 1.5rem 0;
padding: 1.2rem;
height: auto;
overflow: visible;
box-sizing: border-box;
}
```
- 兄弟要素間のマージンは必ず以下のように設定してください:
```css
.card + .card,
.section + .section,
.info-box + .info-box,
.row + .row {
margin-top: 2rem;
}
```
- コンテナの高さは自動的に調整されるようにしてください:
```css
.container, .row, .column {
height: auto;
overflow: hidden;
display: flex;
flex-direction: column;
}
```
- グリッドレイアウトを使用する場合は明示的な行の高さを設定してください:
```css
.grid {
display: grid;
grid-template-columns: repeat(auto-fit, minmax(300px, 1fr));
grid-gap: 2rem;
grid-auto-rows: minmax(min-content, auto);
}
```
- すべてのテキスト要素に余白を設定してください:
```css
p, h1, h2, h3, h4, h5, h6, li {
margin-bottom: 1rem;
line-height: 1.6;
}
```
"""
# システムプロンプト(強化版)
system_instruction = f"""# グラフィックレコーディング風インフォグラフィック変換プロンプト V3
## 目的
以下の内容を、超一流デザイナーが作成したような、日本語で完璧なグラフィックレコーディング風の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%
- 重要な要素は中央寄り、補足情報は周辺部に配置
{layout_improvements}
## レイアウト崩れ防止のための追加設定
- テキストが重ならないようにカードやセクション間に十分なマージンを設定(最低25px)
- テキスト量に応じて自動的に要素の高さが伸びるフレックスレイアウトを採用
- テキストが多い場合は自動的にフォントサイズを調整する機能を実装
- スマートスペーシング:内容量に応じて自動的に間隔を調整
- 以下のCSSを必ず追加して、テキストの重なりを防止する:
```css
.card, .section, .info-box {{
overflow: hidden;
display: flex;
flex-direction: column;
margin-bottom: 1.5rem;
min-height: fit-content;
}}
.card-content {{
flex: 1;
display: flex;
flex-direction: column;
}}
.card-title {{
font-weight: bold;
margin-bottom: 0.75rem;
line-height: 1.4;
}}
.card-text {{
line-height: 1.6;
margin-bottom: 0.5rem;
}}
.info-item {{
margin-bottom: 0.75rem;
line-height: 1.5;
}}
li {{
margin-bottom: 0.5rem;
line-height: 1.5;
}}
p {{
margin-bottom: 0.75rem;
line-height: 1.5;
}}
```
## 自動テキスト調整機能
以下のJavaScriptを必ず追加して、テキスト量に応じたフォントサイズの自動調整を行う:
```html
<script>
document.addEventListener('DOMContentLoaded', function() {{
// カード内のテキスト量に基づいてフォントサイズを調整
const cards = document.querySelectorAll('.card, .section, .info-box');
cards.forEach(card => {{
const cardContent = card.querySelector('.card-content') || card;
const textLength = cardContent.textContent.length;
// テキスト量に応じてフォントサイズを調整
if (textLength > 200) {{
card.style.fontSize = '0.9em';
}}
if (textLength > 300) {{
card.style.fontSize = '0.85em';
}}
// カード内の要素間の余白を確保
const elements = card.querySelectorAll('p, h3, h4, ul, ol, .info-item');
elements.forEach(el => {{
el.style.marginBottom = '0.75rem';
el.style.lineHeight = '1.5';
}});
}});
}});
</script>
```
{layout_adjustments}
## グラフィックレコーディング表現技法
- テキストと視覚要素のバランスを重視(文字情報の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)}, 温度 = {temperature}, レイアウトタイプ = {layout_type}")
# モデル初期化とフォールバック処理
try:
model = genai.GenerativeModel(model_name)
except Exception as e:
# 指定されたモデルが使用できない場合はフォールバック
fallback_model = "gemini-pro"
logger.warning(f"{model_name}が利用できません: {e}, フォールバックモデル{fallback_model}を使用します")
model = genai.GenerativeModel(fallback_model)
# 生成設定
generation_config = {
"temperature": temperature, # パラメータとして受け取った温度を設定
"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
)
# レスポンスから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)}")
# HTML後処理:テキスト重なり防止のためのクラス・スタイル追加
html_code = enhance_html_for_layout(html_code)
return html_code
else:
# HTMLタグが見つからない場合、レスポンス全体を返す
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}")
# HTMLを後処理してレイアウト崩れを防止する関数
def enhance_html_for_layout(html_code):
"""HTMLを後処理してレイアウト崩れを防止するための調整を行う(強化版)"""
try:
# 基本的なスタイルとスクリプトが含まれているか確認
base_styles_needed = True
base_scripts_needed = True
if "<style>" in html_code:
style_pos = html_code.find("</style>")
if style_pos != -1:
# カード要素のスタイルが含まれているか確認
if ".card" in html_code[:style_pos] and "flex-direction: column" in html_code[:style_pos]:
base_styles_needed = False
# レイアウト崩れ防止用の強化CSSを追加
enhanced_css = """
/* --- レイアウト崩れ防止強化スタイル --- */
.card, .section, .info-box {
position: relative !important;
display: flex !important;
flex-direction: column !important;
margin: 1.5rem 0 !important;
padding: 1.2rem !important;
height: auto !important;
min-height: fit-content !important;
overflow: visible !important;
box-sizing: border-box !important;
z-index: 1 !important;
clear: both !important;
}
/* フローティング要素のクリア */
.clearfix::after {
content: "" !important;
display: table !important;
clear: both !important;
}
/* コンテナ要素の高さ自動調整 */
.container, .row, .column {
height: auto !important;
overflow: hidden !important;
position: relative !important;
}
/* グリッドレイアウトの調整 */
.grid {
display: grid !important;
grid-template-columns: repeat(auto-fit, minmax(300px, 1fr)) !important;
grid-gap: 2rem !important;
grid-auto-rows: minmax(min-content, auto) !important;
}
/* マージンとパディングの強制 */
p, h1, h2, h3, h4, h5, h6, li {
margin-bottom: 1rem !important;
line-height: 1.6 !important;
}
/* 重なり解消のための特別なスタイル */
body {
overflow-x: hidden !important;
}
.card + .card, .section + .section, .info-box + .info-box {
margin-top: 2rem !important;
}
/* モバイル表示の改善 */
@media (max-width: 768px) {
.card, .section, .info-box {
width: 100% !important;
margin-left: 0 !important;
margin-right: 0 !important;
}
}
"""
# スタイルタグの閉じ直前に挿入
html_code = html_code[:style_pos] + enhanced_css + html_code[style_pos:]
# スタイルが存在しない場合は新たに追加
if base_styles_needed and "<style>" not in html_code:
head_end_pos = html_code.find("</head>")
if head_end_pos != -1:
base_styles = """
<style>
/* ベーススタイル - レイアウト崩れ防止 */
.card, .section, .info-box {
position: relative !important;
display: flex !important;
flex-direction: column !important;
margin: 1.5rem 0 !important;
padding: 1.2rem !important;
height: auto !important;
min-height: fit-content !important;
overflow: visible !important;
box-sizing: border-box !important;
z-index: 1 !important;
clear: both !important;
}
.card-content {
flex: 1 !important;
display: flex !important;
flex-direction: column !important;
}
.container, .row, .column {
height: auto !important;
overflow: hidden !important;
position: relative !important;
}
p, h1, h2, h3, h4, h5, h6, li {
margin-bottom: 1rem !important;
line-height: 1.6 !important;
}
/* 重なり解消のための特別なスタイル */
body {
overflow-x: hidden !important;
}
.card + .card, .section + .section, .info-box + .info-box {
margin-top: 2rem !important;
}
</style>
"""
html_code = html_code[:head_end_pos] + base_styles + html_code[head_end_pos:]
# 自動レイアウト修正用のスクリプトを強化
if "</body>" in html_code:
has_stabilize_script = "stabilizeLayout" in html_code
if not has_stabilize_script:
body_end_pos = html_code.find("</body>")
if body_end_pos != -1:
enhanced_script = """
<script>
// レイアウト安定化のための強化スクリプト
function stabilizeLayout() {
// カードの重なりを解消
document.querySelectorAll('.card, .section, .info-box').forEach(card => {
// 位置を相対指定に強制
card.style.position = 'relative';
// z-indexをカード間で競合しないよう設定
card.style.zIndex = '1';
// マージンを強制的に設定
card.style.marginBottom = '2rem';
card.style.marginTop = '1rem';
// 浮動要素のクリア
let clearDiv = document.createElement('div');
clearDiv.style.clear = 'both';
clearDiv.style.height = '1px';
card.parentNode.insertBefore(clearDiv, card.nextSibling);
// クリアフィックスクラスを追加
card.classList.add('clearfix');
});
// 親要素の高さを適切に設定
document.querySelectorAll('.row, .container, .column').forEach(container => {
container.style.overflow = 'hidden';
container.style.height = 'auto';
container.classList.add('clearfix');
// 子要素の合計高さを取得して設定
let totalHeight = 0;
Array.from(container.children).forEach(child => {
if (child.offsetHeight) {
totalHeight += child.offsetHeight +
parseInt(getComputedStyle(child).marginTop || 0) +
parseInt(getComputedStyle(child).marginBottom || 0);
}
});
if (totalHeight > 0) {
container.style.minHeight = (totalHeight + 50) + 'px';
}
});
// テキスト量に基づいてフォントサイズを調整
document.querySelectorAll('.card, .section, .info-box').forEach(card => {
const cardContent = card.querySelector('.card-content') || card;
const textLength = cardContent.textContent.length;
// テキスト量に応じてフォントサイズを調整
if (textLength > 200) {
card.style.fontSize = '0.9em';
}
if (textLength > 300) {
card.style.fontSize = '0.85em';
}
// カード内の要素間の余白を確保
const elements = card.querySelectorAll('p, h3, h4, ul, ol, .info-item');
elements.forEach(el => {
el.style.marginBottom = '0.75rem';
el.style.lineHeight = '1.5';
});
});
}
// DOMContentLoadedイベントで実行
document.addEventListener('DOMContentLoaded', stabilizeLayout);
// 安全のためにウィンドウロード時にも実行
window.addEventListener('load', stabilizeLayout);
// 1秒後に再度実行して安定化を確実にする
setTimeout(stabilizeLayout, 1000);
</script>
"""
html_code = html_code[:body_end_pos] + enhanced_script + html_code[body_end_pos:]
# カードコンテナのクラス追加
html_code = re.sub(r'<div class="([^"]*)"([^>]*)>', lambda m: f'<div class="{m.group(1)} card clearfix"{m.group(2)}>', html_code)
# ボディタグにクラス追加
if "<body" in html_code and "clearfix" not in html_code:
html_code = html_code.replace("<body", '<body class="clearfix"')
return html_code
except Exception as e:
logger.warning(f"HTMLの後処理中にエラーが発生しました: {e}")
return html_code # エラー時は元のHTMLを返す
# 画像から余分な空白領域をトリミングする関数
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, height
max_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
# --- Core Screenshot Logic ---
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 (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 file
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)) # エラー時は黒画像
# 2) Headless Chrome(Chromium) options
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")
# Font Awesomeが読み込まれない場合があるため、読み込み待機時間を長く設定
options.add_argument("--disable-features=NetworkService")
options.add_argument("--dns-prefetch-disable")
# 新規追加:CORSエラー防止のためのフラグ
options.add_argument("--disable-web-security")
options.add_argument("--allow-file-access-from-files")
try:
logger.info("Initializing WebDriver...")
driver = webdriver.Chrome(options=options)
logger.info("WebDriver initialized.")
# 3) 初期ウィンドウサイズを設定(コンテンツの種類に関わらず同じサイズ)
initial_width = 1200
initial_height = 1000
driver.set_window_size(initial_width, initial_height)
file_url = "file://" + tmp_path
logger.info(f"Navigating to {file_url}")
driver.get(file_url)
# 4) Wait for page load with extended timeout
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...")
# リソース読み込みの待機時間(増加:8→10秒)
time.sleep(10) # 十分な待機時間
# 5) Hide scrollbars via CSS
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}")
# 6) Get full page dimensions accurately with improved script
try:
# より正確なページ寸法を取得するためのJavaScriptコード
dimensions_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
)
};
"""
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, 4000) # 最大高さ
except Exception as e:
logger.error(f"Error getting page dimensions: {e}")
# フォールバックとしてデフォルト値を設定
scroll_width = 1200
scroll_height = 1000
logger.warning(f"Falling back to dimensions: width={scroll_width}, height={scroll_height}")
# 7) Calculate adjusted height with user-specified margin
adjusted_height = int(scroll_height * (1 + extension_percentage / 100.0))
# Ensure adjusted height is not excessively large or small
adjusted_height = max(adjusted_height, scroll_height, 100) # 最小高さを確保
logger.info(f"Adjusted height calculated: {adjusted_height} (extension: {extension_percentage}%)")
# 8) Set window size to full page dimensions
adjusted_width = scroll_width
logger.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...")
# レイアウト安定化のための待機(増加:6→8秒)
time.sleep(8) # 統一した待機時間
# 外部リソースの読み込み状態を確認
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(3) # 待機時間増加:2→3秒
except Exception as e:
logger.warning(f"Error checking resource state: {e}")
# レイアウト崩れ修正のためのJavaScriptを実行
try:
# レイアウト安定化のための強化JavaScriptを実行
stabilize_script = """
// カードの重なりを解消するための修正
document.querySelectorAll('.card, .section, .info-box').forEach(card => {
// 位置を相対指定に強制
card.style.position = 'relative';
// z-indexをカード間で競合しないよう設定
card.style.zIndex = '1';
// マージンを強制的に設定
card.style.marginBottom = '2rem';
card.style.marginTop = '1rem';
// 浮動要素のクリア
let clearDiv = document.createElement('div');
clearDiv.style.clear = 'both';
clearDiv.style.height = '1px';
card.parentNode.insertBefore(clearDiv, card.nextSibling);
});
// 親要素の高さを適切に設定
document.querySelectorAll('.row, .container, .column').forEach(container => {
container.style.overflow = 'hidden';
container.style.height = 'auto';
// 子要素の合計高さを取得して設定
let totalHeight = 0;
Array.from(container.children).forEach(child => {
if (child.offsetHeight) {
totalHeight += child.offsetHeight +
parseInt(getComputedStyle(child).marginTop || 0) +
parseInt(getComputedStyle(child).marginBottom || 0);
}
});
if (totalHeight > 0) {
container.style.minHeight = (totalHeight + 50) + 'px';
}
});
// テキスト量に基づいてフォントサイズを調整
document.querySelectorAll('.card, .section, .info-box').forEach(card => {
const cardContent = card.querySelector('.card-content') || card;
const textLength = cardContent.textContent.length;
// テキスト量に応じてフォントサイズを調整
if (textLength > 200) {
card.style.fontSize = '0.9em';
}
if (textLength > 300) {
card.style.fontSize = '0.85em';
}
// カード内の要素間の余白を確保
const elements = card.querySelectorAll('p, h3, h4, ul, ol, .info-item');
elements.forEach(el => {
el.style.marginBottom = '0.75rem';
el.style.lineHeight = '1.5';
});
});
// 完了通知
return "Layout stabilization completed";
"""
stabilize_result = driver.execute_script(stabilize_script)
logger.info(f"Layout stabilization: {stabilize_result}")
# 安定化後の追加待機
time.sleep(2)
except Exception as e:
logger.warning(f"Failed to execute layout fix script: {e}")
# Scroll to top just in case
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}")
# 9) Take screenshot
logger.info("Taking screenshot...")
png = driver.get_screenshot_as_png()
logger.info("Screenshot taken successfully.")
# Convert to PIL Image
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 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)) # Return black 1x1 image on error
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}")
# --- Geminiを使った新しい関数 ---
def text_to_screenshot(text: str, extension_percentage: float, temperature: float = 1.0,
trim_whitespace: bool = True, layout_type: str = "standard") -> Image.Image:
"""テキストをGemini APIでHTMLに変換し、スクリーンショットを生成する統合関数"""
try:
# 1. テキストからHTMLを生成(温度パラメータとレイアウトタイプも渡す)
html_code = generate_html_from_text(text, temperature, layout_type)
# 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=["*"],
allow_credentials=True,
allow_methods=["*"],
allow_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 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 bytes
img_byte_arr = BytesIO()
pil_image.save(img_byte_arr, format='PNG')
img_byte_arr.seek(0) # Go to the start of the BytesIO buffer
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}")
# --- 新しい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)}, 拡張率: {request.extension_percentage}%, 温度: {request.temperature}, レイアウト: {request.layout_type}")
# テキストからHTMLを生成してスクリーンショットを作成(温度パラメータとレイアウトタイプも渡す)
pil_image = text_to_screenshot(
request.text,
request.extension_percentage,
request.temperature,
request.trim_whitespace,
request.layout_type
)
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, layout_type):
"""入力モードに応じて適切な処理を行う"""
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, layout_type)
# 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):
extension_percentage = gr.Slider(
minimum=0,
maximum=30,
step=1.0,
value=6, # デフォルト値6%
label="上下高さ拡張率(%)"
)
# 温度調整スライダー(テキストモード時のみ表示)
temperature = gr.Slider(
minimum=0.0,
maximum=1.4,
step=0.1,
value=1.0, # デフォルト値1.0
label="生成時の温度(創造性)",
visible=False # 最初は非表示
)
# 余白トリミングオプション
trim_whitespace = gr.Checkbox(
label="余白を自動トリミング",
value=True,
info="生成される画像から余分な空白領域を自動的に削除します"
)
with gr.Column(scale=1):
# 新機能:レイアウトタイプの選択(テキストモード時のみ表示)
layout_type = gr.Radio(
["standard", "spaced", "compact"],
label="レイアウトタイプ",
value="standard",
info="standard: 標準レイアウト, spaced: 広々レイアウト, compact: コンパクトレイアウト",
visible=False
)
submit_btn = gr.Button("生成", variant="primary")
output_image = gr.Image(type="pil", label="ページ全体のスクリーンショット")
# 入力モード変更時のイベント処理(テキストモード時のみ温度スライダーとレイアウトタイプを表示)
def update_ui_visibility(mode):
return [
{"visible": mode == "テキスト入力", "__type__": "update"}, # temperature
{"visible": mode == "テキスト入力", "__type__": "update"} # layout_type
]
input_mode.change(
fn=update_ui_visibility,
inputs=input_mode,
outputs=[temperature, layout_type]
)
# 生成ボタンクリック時のイベント処理
submit_btn.click(
fn=process_input,
inputs=[input_mode, input_text, extension_percentage, temperature, trim_whitespace, layout_type],
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: 標準レイアウト
- spaced: 広々レイアウト(テキストが重なりやすい場合に推奨)
- compact: コンパクトレイアウト(テキストが少ない場合に推奨)
""")
# --- Mount Gradio App onto FastAPI ---
app = gr.mount_gradio_app(app, iface, path="/")
# --- Run with Uvicorn (for local testing) ---
if __name__ == "__main__":
import uvicorn
logger.info("Starting Uvicorn server for local development...")
uvicorn.run(app, host="0.0.0.0", port=7860)