Spaces:
Paused
Paused
Update app.py
Browse files
app.py
CHANGED
|
@@ -10,7 +10,6 @@ from selenium.webdriver.chrome.options import Options
|
|
| 10 |
from selenium.webdriver.common.by import By
|
| 11 |
from selenium.webdriver.support.ui import WebDriverWait
|
| 12 |
from selenium.webdriver.support import expected_conditions as EC
|
| 13 |
-
# TimeoutException と JavascriptException をインポート
|
| 14 |
from selenium.common.exceptions import TimeoutException, JavascriptException
|
| 15 |
from PIL import Image
|
| 16 |
from io import BytesIO
|
|
@@ -18,86 +17,38 @@ import tempfile
|
|
| 18 |
import time
|
| 19 |
import os
|
| 20 |
import logging
|
| 21 |
-
|
| 22 |
-
# 正しいGemini関連のインポート
|
| 23 |
import google.generativeai as genai
|
| 24 |
|
| 25 |
-
# ロギング設定
|
| 26 |
logging.basicConfig(level=logging.INFO)
|
| 27 |
logger = logging.getLogger(__name__)
|
| 28 |
|
| 29 |
-
# ---
|
| 30 |
class GeminiRequest(BaseModel):
|
| 31 |
-
"""Geminiへのリクエストデータモデル"""
|
| 32 |
text: str
|
| 33 |
-
extension_percentage: float = 6.0
|
| 34 |
-
temperature: float = 0.3
|
| 35 |
-
trim_whitespace: bool = True
|
| 36 |
|
| 37 |
class ScreenshotRequest(BaseModel):
|
| 38 |
-
"""スクリーンショットリクエストモデル"""
|
| 39 |
html_code: str
|
| 40 |
-
extension_percentage: float = 6.0
|
| 41 |
-
trim_whitespace: bool = True
|
| 42 |
|
| 43 |
-
#
|
| 44 |
def enhance_font_awesome_layout(html_code):
|
| 45 |
-
"""Font Awesomeレイアウトを改善するCSSを追加"""
|
| 46 |
-
# CSSを追加
|
| 47 |
fa_fix_css = """
|
| 48 |
<style>
|
| 49 |
-
|
| 50 |
-
[class*="fa-"] {
|
| 51 |
-
|
| 52 |
-
|
| 53 |
-
|
| 54 |
-
}
|
| 55 |
-
|
| 56 |
-
/* テキスト内のアイコン位置調整 */
|
| 57 |
-
h1 [class*="fa-"], h2 [class*="fa-"], h3 [class*="fa-"],
|
| 58 |
-
h4 [class*="fa-"], h5 [class*="fa-"], h6 [class*="fa-"] {
|
| 59 |
-
vertical-align: middle !important;
|
| 60 |
-
margin-right: 10px !important;
|
| 61 |
-
}
|
| 62 |
-
|
| 63 |
-
/* 特定パターンの修正 */
|
| 64 |
-
.fa + span, .fas + span, .far + span, .fab + span,
|
| 65 |
-
span + .fa, span + .fas, span + .far, span + .fab {
|
| 66 |
-
display: inline-block !important;
|
| 67 |
-
margin-left: 5px !important;
|
| 68 |
-
}
|
| 69 |
-
|
| 70 |
-
/* カード内アイコン修正 */
|
| 71 |
-
.card [class*="fa-"], .card-body [class*="fa-"] {
|
| 72 |
-
float: none !important;
|
| 73 |
-
clear: none !important;
|
| 74 |
-
position: relative !important;
|
| 75 |
-
}
|
| 76 |
-
|
| 77 |
-
/* アイコンと文字が重なる場合の調整 */
|
| 78 |
-
li [class*="fa-"], p [class*="fa-"] {
|
| 79 |
-
margin-right: 10px !important;
|
| 80 |
-
}
|
| 81 |
-
|
| 82 |
-
/* インラインアイコンのスペーシング */
|
| 83 |
-
.inline-icon {
|
| 84 |
-
display: inline-flex !important;
|
| 85 |
-
align-items: center !important;
|
| 86 |
-
justify-content: flex-start !important;
|
| 87 |
-
}
|
| 88 |
-
|
| 89 |
-
/* アイコン後のテキスト */
|
| 90 |
-
[class*="fa-"] + span {
|
| 91 |
-
display: inline-block !important;
|
| 92 |
-
vertical-align: middle !important;
|
| 93 |
-
}
|
| 94 |
</style>
|
| 95 |
"""
|
| 96 |
-
|
| 97 |
-
# headタグがある場合はその中に追加
|
| 98 |
if '<head>' in html_code:
|
| 99 |
return html_code.replace('</head>', f'{fa_fix_css}</head>')
|
| 100 |
-
# HTMLタグがある場合はその後に追加
|
| 101 |
elif '<html' in html_code:
|
| 102 |
head_end = html_code.find('</head>')
|
| 103 |
if head_end > 0:
|
|
@@ -106,178 +57,32 @@ def enhance_font_awesome_layout(html_code):
|
|
| 106 |
body_start = html_code.find('<body')
|
| 107 |
if body_start > 0:
|
| 108 |
return html_code[:body_start] + f'<head>{fa_fix_css}</head>' + html_code[body_start:]
|
| 109 |
-
|
| 110 |
-
# どちらもない場合は先頭に追加
|
| 111 |
return f'<html><head>{fa_fix_css}</head>' + html_code + '</html>'
|
| 112 |
|
| 113 |
def generate_html_from_text(text, temperature=0.3):
|
| 114 |
-
"""テキストからHTMLを生成する"""
|
| 115 |
try:
|
| 116 |
-
# APIキーの取得と設定
|
| 117 |
api_key = os.environ.get("GEMINI_API_KEY")
|
| 118 |
if not api_key:
|
| 119 |
logger.error("GEMINI_API_KEY 環境変数が設定されていません")
|
| 120 |
raise ValueError("GEMINI_API_KEY 環境変数が設定されていません")
|
| 121 |
-
|
| 122 |
-
# モデル名の取得(環境変数から、なければデフォルト値)
|
| 123 |
model_name = os.environ.get("GEMINI_MODEL", "gemini-1.5-pro")
|
| 124 |
logger.info(f"使用するGeminiモデル: {model_name}")
|
| 125 |
-
|
| 126 |
-
# Gemini APIの設定
|
| 127 |
genai.configure(api_key=api_key)
|
| 128 |
-
|
| 129 |
-
# システムプロンプト(変更なし)
|
| 130 |
-
system_instruction = """# グラフィックレコーディング風インフォグラフィック変換プロンプト V2
|
| 131 |
-
## 目的
|
| 132 |
-
以下の内容を、超一流デザイナーが作成したような、日本語で完璧なグラフィックレコーディング風のHTMLインフォグラフィックに変換してください。情報設計とビジュアルデザインの両面で最高水準を目指します。
|
| 133 |
-
手書き風の図形やFont Awesomeアイコンを大きく活用して内容を視覚的かつ直感的に表現します。
|
| 134 |
-
|
| 135 |
-
## デザイン仕様
|
| 136 |
-
### 1. カラースキーム
|
| 137 |
-
```
|
| 138 |
-
<palette>
|
| 139 |
-
<color name='MysticLibrary-1' rgb='2E578C' r='46' g='87' b='140' />
|
| 140 |
-
<color name='MysticLibrary-2' rgb='182D40' r='24' g='45' b='64' />
|
| 141 |
-
<color name='MysticLibrary-3' rgb='BF807A' r='191' g='128' b='122' />
|
| 142 |
-
<color name='MysticLibrary-4' rgb='592A2A' r='89' g='42' b='42' />
|
| 143 |
-
<color name='MysticLibrary-5' rgb='F2F2F2' r='242' g='242' b='242' />
|
| 144 |
-
</palette>
|
| 145 |
-
```
|
| 146 |
-
### 2. グラフィックレコーディング要素
|
| 147 |
-
- 左上から右へ、上から下へと情報を順次配置
|
| 148 |
-
- 日本語の手書き風フォントの使用(Yomogi, Zen Kurenaido, Kaisei Decol)
|
| 149 |
-
- 手描き風の囲み線、矢印、バナー、吹き出し
|
| 150 |
-
- テキストと視覚要素(Font Awesomeアイコン、シンプルな図形)の組み合わせ
|
| 151 |
-
- Font Awesomeアイコンは各セクションの内容を表現するものを大きく(2x〜3x)表示
|
| 152 |
-
- キーワードごとに関連するFont Awesomeアイコンを隣接配置
|
| 153 |
-
- キーワードの強調(色付き下線、マーカー効果、Font Awesomeによる装飾)
|
| 154 |
-
- 関連する概念を線や矢印で接続し、接続部にもFont Awesomeアイコン(fa-arrow-right, fa-connection等)を挿入
|
| 155 |
-
- Font Awesomeアニメーション効果(fa-beat, fa-bounce, fa-fade, fa-flip, fa-shake, fa-spin)を適切に活用
|
| 156 |
-
- 重要なポイントには「fa-circle-exclamation」や「fa-lightbulb」などのアイコンを目立つ大きさで配置
|
| 157 |
-
- 数値やデータには「fa-chart-line」や「fa-percent」などの関連アイコンを添える
|
| 158 |
-
- 感情や状態を表すには表情アイコン(fa-face-smile, fa-face-frown等)を活用
|
| 159 |
-
- アイコンにホバー効果(色変化、サイズ変化)を付与
|
| 160 |
-
- 背景にはFont Awesomeの薄いパターンを配置(fa-shapes等を透過度を下げて配置)
|
| 161 |
-
### 3. アニメーション効果
|
| 162 |
-
- Font Awesomeアイコンに連動するアニメーション(fa-beat, fa-bounce, fa-fade等)
|
| 163 |
-
- 重要キーワード出現時のハイライト効果(グラデーション変化)
|
| 164 |
-
- 接続線や矢印の流れるようなアニメーション
|
| 165 |
-
- アイコンの回転・拡大縮小アニメーション(特に注目させたい箇所)
|
| 166 |
-
- 背景グラデーションの緩やかな変化
|
| 167 |
-
- スクロールに連動した要素の出現効果
|
| 168 |
-
- クリック/タップでアイコンが反応する効果
|
| 169 |
-
### 4. タイポグラフィ
|
| 170 |
-
- タイトル:32px、グラデーション効果、太字、Font Awesomeアイコンを左右に配置
|
| 171 |
-
- サブタイトル:16px、#475569、関連するFont Awesomeアイコンを添える
|
| 172 |
-
- セクション見出し:18px、# 1e40af、左側にFont Awesomeアイコンを必ず配置し、アイコンにはアニメーション効果
|
| 173 |
-
- 本文:14px、#334155、行間1.4、重要キーワードには関連するFont Awesomeアイコンを小さく添える
|
| 174 |
-
- フォント指定:
|
| 175 |
-
```html
|
| 176 |
-
<style>
|
| 177 |
-
@ import url('https ://fonts.googleapis.com/css2?family=Kaisei+Decol&family=Yomogi&family=Zen+Kurenaido&display=swap');
|
| 178 |
-
@ import url('https ://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.4.0/css/all.min.css');
|
| 179 |
-
</style>
|
| 180 |
-
```
|
| 181 |
-
### 5. レイアウト
|
| 182 |
-
- ヘッダー:左揃えタイトル(大きなFont Awesomeアイコンを添える)+右揃え日付/出典
|
| 183 |
-
- 2カラム構成:左側50%、右側50%
|
| 184 |
-
- カード型コンポーネント:白背景、角丸12px、微細シャドウ、右上にFont Awesomeアイコンを配置
|
| 185 |
-
- セクション間の適切な余白と階層構造(階層を示すFont Awesomeアイコンを活用)
|
| 186 |
-
- 適切にグラスモーフィズムを活用(背後にぼかしたFont Awesomeアイコンを配置)
|
| 187 |
-
- 横幅は100%
|
| 188 |
-
- 重要な要素は中央寄り、補足情報は周辺部に配置
|
| 189 |
-
|
| 190 |
-
### 重要なレイアウト注意事項
|
| 191 |
-
- Font Awesomeアイコンと文字が重ならないよう適切なマージンを設定する
|
| 192 |
-
- アイコンには必ず`margin-right: 10px;`や`margin-left: 10px;`などの余白を設定する
|
| 193 |
-
- アイコンと文字列は必ず`display: inline-block;`または`display: inline-flex;`で配置し、`align-items: center;`を使用する
|
| 194 |
-
- 複数のアイコンを配置する場合は十分な余白を確保する
|
| 195 |
-
- レイアウト崩れを防ぐために、親要素には`overflow: hidden;`を適用する
|
| 196 |
-
- アイコンの配置はコンテンツフローを妨げないよう注意する
|
| 197 |
-
- カード内でのアイコン配置は、絶対位置指定ではなく相対位置で設定する
|
| 198 |
-
- モバイル表示も考慮し、レスポンシブ対応を徹底する
|
| 199 |
-
|
| 200 |
-
## グラフィックレコーディング表現技法
|
| 201 |
-
- テキストと視覚要素のバランスを重視(文字情報の50%以上をFont Awesomeアイコンで視覚的に補完)
|
| 202 |
-
- キーワードを囲み線や色で強調し、関連するFont Awesomeアイコンを必ず添える
|
| 203 |
-
- 概念ごとに最適なFont Awesomeアイコンを選定(抽象的な概念には複数の関連アイコンを組み合わせて表現)
|
| 204 |
-
- 数値データは簡潔なグラフや図表で表現し、データ種類に応じたFont Awesomeアイコン(fa-chart-pie, fa-chart-column等)を配置
|
| 205 |
-
- 接続線や矢印で情報間の関係性を明示し、関係性の種類に応じたアイコン(fa-link, fa-code-branch等)を添える
|
| 206 |
-
- 余白を効果的に活用して視認性を確保(余白にも薄いFont Awesomeパターンを配置可)
|
| 207 |
-
- コントラストと色の使い分けでメリハリを付け、カラースキームに沿ったアイコン色を活用
|
| 208 |
-
## Font Awesomeアイコン活用ガイドライン
|
| 209 |
-
- 概念カテゴリー別の推奨アイコン:
|
| 210 |
-
- 時間・順序:fa-clock, fa-hourglass, fa-calendar, fa-timeline
|
| 211 |
-
- 場所・位置:fa-location-dot, fa-map, fa-compass, fa-globe
|
| 212 |
-
- 人物・組織:fa-user, fa-users, fa-building, fa-sitemap
|
| 213 |
-
- 行動・活動:fa-person-running, fa-gears, fa-hammer, fa-rocket
|
| 214 |
-
- 思考・アイデア:fa-brain, fa-lightbulb, fa-thought-bubble, fa-comments
|
| 215 |
-
- 感情・状態:fa-face-smile, fa-face-sad-tear, fa-heart, fa-temperature-half
|
| 216 |
-
- 成長・変化:fa-seedling, fa-arrow-trend-up, fa-chart-line, fa-diagram-project
|
| 217 |
-
- 問題・課題:fa-triangle-exclamation, fa-circle-question, fa-bug, fa-ban
|
| 218 |
-
- 解決・成功:fa-check, fa-trophy, fa-handshake, fa-key
|
| 219 |
-
- アイコンサイズの使い分け:
|
| 220 |
-
- 主要概念:3x(fa-3x)
|
| 221 |
-
- 重要キーワード:2x(fa-2x)
|
| 222 |
-
- 補足情報:1x(標準サイズ)
|
| 223 |
-
- 装飾的要素:lg(fa-lg)
|
| 224 |
-
- アニメーション効果の適切な使い分け:
|
| 225 |
-
- 注目喚起:fa-beat, fa-shake
|
| 226 |
-
- 継続的プロセス:fa-spin, fa-pulse
|
| 227 |
-
- 状態変化:fa-flip, fa-fade
|
| 228 |
-
- 新規情報:fa-bounce
|
| 229 |
-
## 全体的な指針
|
| 230 |
-
- 読み手が自然に視線を移動できる配置(Font Awesomeアイコンで視線誘導)
|
| 231 |
-
- 情報の階層と関連性を視覚的に明確化(階層ごとにアイコンのサイズや色を変える)
|
| 232 |
-
- 手書き風の要素とFont Awesomeアイコンを組み合わせて親しみやすさとプロフェッショナル感を両立
|
| 233 |
-
- 大きなFont Awesomeアイコンを活用した視覚的な記憶に残るデザイン(各セクションに象徴的なアイコンを配置)
|
| 234 |
-
- フッターに出典情報と関連するFont Awesomeアイコン(fa-book, fa-citation等)を明記
|
| 235 |
-
## 変換する文章/記事
|
| 236 |
-
ーーー<ユーザーが入力(または添付)>ーーー"""
|
| 237 |
-
|
| 238 |
-
# モデルを初期化して処理
|
| 239 |
logger.info(f"Gemini APIにリクエストを送信: テキスト長さ = {len(text)}, 温度 = {temperature}")
|
| 240 |
-
|
| 241 |
-
# モデル初期化とフォールバック処理
|
| 242 |
try:
|
| 243 |
model = genai.GenerativeModel(model_name)
|
| 244 |
except Exception as e:
|
| 245 |
fallback_model = "gemini-pro"
|
| 246 |
logger.warning(f"{model_name}が利用できません: {e}, フォールバックモデル{fallback_model}を使用します")
|
| 247 |
model = genai.GenerativeModel(fallback_model)
|
| 248 |
-
|
| 249 |
-
|
| 250 |
-
generation_config = {
|
| 251 |
-
"temperature": temperature,
|
| 252 |
-
"top_p": 0.7,
|
| 253 |
-
"top_k": 20,
|
| 254 |
-
"max_output_tokens": 8192,
|
| 255 |
-
"candidate_count": 1
|
| 256 |
-
}
|
| 257 |
-
|
| 258 |
-
# 安全設定 (変更なし)
|
| 259 |
-
safety_settings = [
|
| 260 |
-
{"category": "HARM_CATEGORY_HARASSMENT", "threshold": "BLOCK_MEDIUM_AND_ABOVE"},
|
| 261 |
-
{"category": "HARM_CATEGORY_HATE_SPEECH", "threshold": "BLOCK_MEDIUM_AND_ABOVE"},
|
| 262 |
-
{"category": "HARM_CATEGORY_SEXUALLY_EXPLICIT", "threshold": "BLOCK_MEDIUM_AND_ABOVE"},
|
| 263 |
-
{"category": "HARM_CATEGORY_DANGEROUS_CONTENT", "threshold": "BLOCK_MEDIUM_AND_ABOVE"}
|
| 264 |
-
]
|
| 265 |
-
|
| 266 |
-
# プロンプト構築
|
| 267 |
prompt = f"{system_instruction}\n\n{text}"
|
| 268 |
-
|
| 269 |
-
# コンテンツ生成
|
| 270 |
-
response = model.generate_content(
|
| 271 |
-
prompt,
|
| 272 |
-
generation_config=generation_config,
|
| 273 |
-
safety_settings=safety_settings
|
| 274 |
-
)
|
| 275 |
-
|
| 276 |
-
# レスポンスからHTMLを抽出 (変更なし)
|
| 277 |
raw_response = response.text
|
| 278 |
html_start = raw_response.find("```html")
|
| 279 |
html_end = raw_response.rfind("```")
|
| 280 |
-
|
| 281 |
if html_start != -1 and html_end != -1 and html_start < html_end:
|
| 282 |
html_start += 7
|
| 283 |
html_code = raw_response[html_start:html_end].strip()
|
|
@@ -288,13 +93,12 @@ def generate_html_from_text(text, temperature=0.3):
|
|
| 288 |
else:
|
| 289 |
logger.warning("レスポンスから```html```タグが見つかりませんでした。全テキストを返します。")
|
| 290 |
return raw_response
|
| 291 |
-
|
| 292 |
except Exception as e:
|
| 293 |
logger.error(f"HTML生成中にエラーが発生: {e}", exc_info=True)
|
| 294 |
raise Exception(f"Gemini APIでのHTML生成に失敗しました: {e}")
|
| 295 |
|
| 296 |
-
# 画像から余分な空白領域をトリミングする関数 (変更なし)
|
| 297 |
def trim_image_whitespace(image, threshold=250, padding=10):
|
|
|
|
| 298 |
gray = image.convert('L')
|
| 299 |
data = gray.getdata()
|
| 300 |
width, height = gray.size
|
|
@@ -320,40 +124,32 @@ def trim_image_whitespace(image, threshold=250, padding=10):
|
|
| 320 |
logger.info(f"画像をトリミングしました: 元サイズ {width}x{height} → トリミング後 {trimmed.width}x{trimmed.height}")
|
| 321 |
return trimmed
|
| 322 |
|
| 323 |
-
# --- Core Screenshot Logic ---
|
| 324 |
def render_fullpage_screenshot(html_code: str, extension_percentage: float = 6.0,
|
| 325 |
trim_whitespace: bool = True) -> Image.Image:
|
| 326 |
-
"""
|
| 327 |
-
Renders HTML code to a full-page screenshot using Selenium.
|
| 328 |
-
"""
|
| 329 |
tmp_path = None
|
| 330 |
driver = None
|
| 331 |
-
|
| 332 |
-
# 1) Save HTML code to a temporary file (変更なし)
|
| 333 |
try:
|
|
|
|
| 334 |
with tempfile.NamedTemporaryFile(suffix=".html", delete=False, mode='w', encoding='utf-8') as tmp_file:
|
| 335 |
tmp_path = tmp_file.name
|
| 336 |
tmp_file.write(html_code)
|
| 337 |
logger.info(f"HTML saved to temporary file: {tmp_path}")
|
| 338 |
-
except Exception as e:
|
| 339 |
-
logger.error(f"Error writing temporary HTML file: {e}")
|
| 340 |
-
return Image.new('RGB', (1, 1), color=(0, 0, 0))
|
| 341 |
|
| 342 |
-
|
| 343 |
-
|
| 344 |
-
|
| 345 |
-
|
| 346 |
-
|
| 347 |
-
|
| 348 |
-
|
| 349 |
-
|
| 350 |
|
| 351 |
-
try:
|
| 352 |
logger.info("Initializing WebDriver...")
|
| 353 |
driver = webdriver.Chrome(options=options)
|
| 354 |
logger.info("WebDriver initialized.")
|
| 355 |
|
| 356 |
-
# 3)
|
| 357 |
initial_width = 1200
|
| 358 |
initial_height = 1000
|
| 359 |
driver.set_window_size(initial_width, initial_height)
|
|
@@ -363,63 +159,77 @@ def render_fullpage_screenshot(html_code: str, extension_percentage: float = 6.0
|
|
| 363 |
|
| 364 |
# 4) Wait for body (変更なし)
|
| 365 |
logger.info("Waiting for body element...")
|
| 366 |
-
WebDriverWait(driver, 15).until(
|
| 367 |
-
EC.presence_of_element_located((By.TAG_NAME, "body"))
|
| 368 |
-
)
|
| 369 |
logger.info("Body element found. Waiting for potential resource loading...")
|
| 370 |
time.sleep(3)
|
| 371 |
|
| 372 |
-
# 5)
|
| 373 |
try:
|
|
|
|
| 374 |
resource_check_script = """
|
| 375 |
-
|
| 376 |
-
|
| 377 |
const checkFontAwesome = () => {
|
| 378 |
const icons = document.querySelectorAll('.fa, .fas, .far, .fab, [class*="fa-"]');
|
| 379 |
if (icons.length > 0) {
|
| 380 |
document.fonts.ready.then(() => {
|
| 381 |
-
setTimeout(resolve, 1000);
|
| 382 |
});
|
| 383 |
} else {
|
| 384 |
-
document.fonts.ready.then(() => setTimeout(resolve, 500));
|
| 385 |
}
|
| 386 |
};
|
| 387 |
if (document.readyState === 'complete') {
|
| 388 |
checkFontAwesome();
|
| 389 |
} else {
|
| 390 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 391 |
}
|
|
|
|
|
|
|
|
|
|
| 392 |
});
|
| 393 |
-
})();
|
| 394 |
"""
|
| 395 |
logger.info("Waiting for Font Awesome and other resources to load...")
|
| 396 |
-
driver.set_script_timeout(
|
| 397 |
-
#
|
| 398 |
-
|
| 399 |
-
|
| 400 |
-
|
| 401 |
-
|
| 402 |
-
logger.warning(f"Resource loading check failed: {e}. Using fallback wait.")
|
| 403 |
time.sleep(8)
|
| 404 |
-
except Exception as e:
|
| 405 |
logger.error(f"Unexpected error during resource check: {e}", exc_info=True)
|
| 406 |
time.sleep(8)
|
| 407 |
|
| 408 |
-
# 6) Ensure content rendering
|
| 409 |
try:
|
| 410 |
scroll_script = """
|
| 411 |
-
|
| 412 |
-
|
| 413 |
const pageHeight = Math.max(
|
| 414 |
document.documentElement.scrollHeight || 0,
|
| 415 |
document.body ? document.body.scrollHeight || 0 : 0
|
| 416 |
);
|
| 417 |
const viewportHeight = window.innerHeight || document.documentElement.clientHeight || 800;
|
| 418 |
-
|
|
|
|
| 419 |
let currentPos = 0;
|
|
|
|
|
|
|
| 420 |
|
| 421 |
const scrollDown = () => {
|
| 422 |
-
|
|
|
|
|
|
|
| 423 |
window.scrollTo(0, 0);
|
| 424 |
setTimeout(resolve, 300);
|
| 425 |
return;
|
|
@@ -427,80 +237,62 @@ def render_fullpage_screenshot(html_code: str, extension_percentage: float = 6.0
|
|
| 427 |
|
| 428 |
if (currentPos < pageHeight) {
|
| 429 |
window.scrollTo(0, currentPos);
|
|
|
|
|
|
|
|
|
|
| 430 |
currentPos += scrollStep;
|
| 431 |
-
|
| 432 |
-
|
|
|
|
|
|
|
| 433 |
setTimeout(() => {
|
| 434 |
-
window.scrollTo(0, 0);
|
| 435 |
setTimeout(resolve, 300);
|
| 436 |
}, 150);
|
| 437 |
} else {
|
| 438 |
-
setTimeout(scrollDown, 100);
|
| 439 |
}
|
| 440 |
} else {
|
| 441 |
-
window.scrollTo(0, 0);
|
| 442 |
setTimeout(resolve, 300);
|
| 443 |
}
|
| 444 |
};
|
|
|
|
| 445 |
setTimeout(scrollDown, 100);
|
|
|
|
|
|
|
|
|
|
| 446 |
});
|
| 447 |
-
})();
|
| 448 |
"""
|
| 449 |
-
logger.info("Ensuring all content is rendered...")
|
| 450 |
-
driver.set_script_timeout(
|
| 451 |
-
|
| 452 |
-
full_script = f"const callback = arguments[arguments.length - 1]; ({scroll_script}).then(callback);"
|
| 453 |
-
driver.execute_async_script(full_script)
|
| 454 |
logger.info("Content rendering scroll finished.")
|
| 455 |
-
except (TimeoutException, JavascriptException) as e:
|
| 456 |
-
logger.warning(f"Content rendering
|
| 457 |
try:
|
| 458 |
driver.execute_script("window.scrollTo(0, 0);")
|
| 459 |
except Exception as scroll_err:
|
| 460 |
logger.error(f"Could not scroll to top after render check failure: {scroll_err}")
|
| 461 |
-
time.sleep(3)
|
| 462 |
-
except Exception as e:
|
| 463 |
logger.error(f"Unexpected error during content rendering scroll: {e}", exc_info=True)
|
| 464 |
time.sleep(3)
|
| 465 |
|
| 466 |
# 7) Hide scrollbars (変更なし)
|
| 467 |
try:
|
| 468 |
-
driver.execute_script(
|
| 469 |
-
"document.documentElement.style.overflow = 'hidden';"
|
| 470 |
-
"document.body.style.overflow = 'hidden';"
|
| 471 |
-
)
|
| 472 |
logger.info("Scrollbars hidden via JS.")
|
| 473 |
except Exception as e:
|
| 474 |
logger.warning(f"Could not hide scrollbars via JS: {e}")
|
| 475 |
|
| 476 |
-
# 8) Get
|
| 477 |
try:
|
| 478 |
-
dimensions_script = """
|
| 479 |
-
return {
|
| 480 |
-
width: Math.max(
|
| 481 |
-
document.documentElement.scrollWidth || 0,
|
| 482 |
-
document.documentElement.offsetWidth || 0,
|
| 483 |
-
document.documentElement.clientWidth || 0,
|
| 484 |
-
document.body ? document.body.scrollWidth || 0 : 0,
|
| 485 |
-
document.body ? document.body.offsetWidth || 0 : 0,
|
| 486 |
-
document.body ? document.body.clientWidth || 0 : 0
|
| 487 |
-
),
|
| 488 |
-
height: Math.max(
|
| 489 |
-
document.documentElement.scrollHeight || 0,
|
| 490 |
-
document.documentElement.offsetHeight || 0,
|
| 491 |
-
document.documentElement.clientHeight || 0,
|
| 492 |
-
document.body ? document.body.scrollHeight || 0 : 0,
|
| 493 |
-
document.body ? document.body.offsetHeight || 0 : 0,
|
| 494 |
-
document.body ? document.body.clientHeight || 0 : 0
|
| 495 |
-
)
|
| 496 |
-
};
|
| 497 |
-
"""
|
| 498 |
dimensions = driver.execute_script(dimensions_script)
|
| 499 |
scroll_width = dimensions['width']
|
| 500 |
scroll_height = dimensions['height']
|
| 501 |
logger.info(f"Detected dimensions: width={scroll_width}, height={scroll_height}")
|
| 502 |
-
|
| 503 |
-
# スクロール検証 (エラーハンドリング追加)
|
| 504 |
try:
|
| 505 |
driver.execute_script("window.scrollTo(0, document.body.scrollHeight);")
|
| 506 |
time.sleep(1)
|
|
@@ -511,23 +303,21 @@ def render_fullpage_screenshot(html_code: str, extension_percentage: float = 6.0
|
|
| 511 |
logger.info(f"After scroll check, height={scroll_height}")
|
| 512 |
except Exception as scroll_e:
|
| 513 |
logger.warning(f"Error during dimension scroll check: {scroll_e}")
|
| 514 |
-
|
| 515 |
scroll_width = max(scroll_width, 100)
|
| 516 |
scroll_height = max(scroll_height, 100)
|
| 517 |
scroll_width = min(scroll_width, 2000)
|
| 518 |
scroll_height = min(scroll_height, 4000)
|
| 519 |
-
|
| 520 |
except Exception as e:
|
| 521 |
logger.error(f"Error getting page dimensions: {e}")
|
| 522 |
scroll_width = 1200
|
| 523 |
scroll_height = 1000
|
| 524 |
logger.warning(f"Falling back to dimensions: width={scroll_width}, height={scroll_height}")
|
| 525 |
|
| 526 |
-
# 9) Layout stability check (修正:
|
| 527 |
try:
|
| 528 |
stability_script = """
|
| 529 |
-
|
| 530 |
-
|
| 531 |
let lastHeight = 0;
|
| 532 |
let lastWidth = 0;
|
| 533 |
let stableCount = 0;
|
|
@@ -538,53 +328,55 @@ def render_fullpage_screenshot(html_code: str, extension_percentage: float = 6.0
|
|
| 538 |
checkCount++;
|
| 539 |
if (checkCount > maxChecks) {
|
| 540 |
console.warn('Layout stability check reached max attempts.');
|
| 541 |
-
resolve(false);
|
| 542 |
return;
|
| 543 |
}
|
| 544 |
-
|
| 545 |
const bodyExists = document.body && typeof document.body.offsetHeight === 'number' && typeof document.body.offsetWidth === 'number';
|
| 546 |
if (!bodyExists) {
|
| 547 |
console.warn('Document body not fully available yet for stability check.');
|
| 548 |
setTimeout(checkStability, 250);
|
| 549 |
return;
|
| 550 |
}
|
| 551 |
-
|
| 552 |
const currentHeight = document.body.offsetHeight;
|
| 553 |
const currentWidth = document.body.offsetWidth;
|
| 554 |
|
|
|
|
| 555 |
if (currentHeight === 0 || currentWidth === 0) {
|
| 556 |
-
stableCount = 0;
|
| 557 |
-
lastHeight = 0;
|
| 558 |
-
lastWidth = 0;
|
| 559 |
console.warn('Body dimensions are zero, waiting...');
|
| 560 |
setTimeout(checkStability, 250);
|
| 561 |
return;
|
| 562 |
}
|
| 563 |
-
|
| 564 |
if (currentHeight === lastHeight && currentWidth === lastWidth) {
|
| 565 |
stableCount++;
|
| 566 |
-
if (stableCount >= 3) {
|
| 567 |
console.log('Layout deemed stable.');
|
| 568 |
-
resolve(true);
|
| 569 |
return;
|
| 570 |
}
|
| 571 |
} else {
|
|
|
|
| 572 |
stableCount = 0;
|
| 573 |
lastHeight = currentHeight;
|
| 574 |
lastWidth = currentWidth;
|
| 575 |
console.log(`Layout changed: ${lastWidth}x${lastHeight}. Resetting stability count.`);
|
| 576 |
}
|
|
|
|
| 577 |
setTimeout(checkStability, 200);
|
| 578 |
};
|
|
|
|
| 579 |
setTimeout(checkStability, 100);
|
|
|
|
|
|
|
|
|
|
| 580 |
});
|
| 581 |
-
})();
|
| 582 |
"""
|
| 583 |
logger.info("Checking layout stability...")
|
| 584 |
driver.set_script_timeout(20)
|
| 585 |
-
#
|
| 586 |
-
|
| 587 |
-
stable = driver.execute_async_script(full_script)
|
| 588 |
|
| 589 |
if stable:
|
| 590 |
logger.info("Layout is stable")
|
|
@@ -595,34 +387,28 @@ def render_fullpage_screenshot(html_code: str, extension_percentage: float = 6.0
|
|
| 595 |
except TimeoutException:
|
| 596 |
logger.warning("Layout stability check timed out. Proceeding anyway.")
|
| 597 |
time.sleep(2)
|
| 598 |
-
except JavascriptException as e:
|
| 599 |
-
logger.error(f"Javascript error during layout stability check: {e}", exc_info=
|
| 600 |
time.sleep(2)
|
| 601 |
except Exception as e:
|
| 602 |
logger.error(f"Unexpected error during layout stability check: {e}", exc_info=True)
|
| 603 |
time.sleep(2)
|
| 604 |
|
| 605 |
-
# 10) Calculate
|
| 606 |
adjusted_height = int(scroll_height * (1 + extension_percentage / 100.0))
|
| 607 |
adjusted_height = max(adjusted_height, scroll_height, 100)
|
| 608 |
logger.info(f"Adjusted height calculated: {adjusted_height} (extension: {extension_percentage}%)")
|
| 609 |
|
| 610 |
-
# 11)
|
| 611 |
adjusted_width = scroll_width
|
| 612 |
logger.info(f"Resizing window to: width={adjusted_width}, height={adjusted_height}")
|
| 613 |
driver.set_window_size(adjusted_width, adjusted_height)
|
| 614 |
logger.info("Waiting for layout stabilization after resize...")
|
| 615 |
time.sleep(4)
|
| 616 |
|
| 617 |
-
# Resource state check (
|
| 618 |
try:
|
| 619 |
-
resource_state = driver.execute_script("""
|
| 620 |
-
return {
|
| 621 |
-
readyState: document.readyState,
|
| 622 |
-
resourcesComplete: !document.querySelector('img:not([complete])') &&
|
| 623 |
-
!document.querySelector('link[rel="stylesheet"]:not([loaded])')
|
| 624 |
-
};
|
| 625 |
-
""")
|
| 626 |
logger.info(f"Resource state: {resource_state}")
|
| 627 |
if resource_state['readyState'] != 'complete':
|
| 628 |
logger.info("Document still loading, waiting additional time...")
|
|
@@ -630,7 +416,7 @@ def render_fullpage_screenshot(html_code: str, extension_percentage: float = 6.0
|
|
| 630 |
except Exception as e:
|
| 631 |
logger.warning(f"Error checking resource state: {e}")
|
| 632 |
|
| 633 |
-
# Scroll to top (
|
| 634 |
try:
|
| 635 |
driver.execute_script("window.scrollTo(0, 0)")
|
| 636 |
time.sleep(1)
|
|
@@ -667,7 +453,7 @@ def render_fullpage_screenshot(html_code: str, extension_percentage: float = 6.0
|
|
| 667 |
except Exception as e:
|
| 668 |
logger.error(f"Error removing temporary file {tmp_path}: {e}")
|
| 669 |
|
| 670 |
-
# ---
|
| 671 |
def text_to_screenshot(text: str, extension_percentage: float, temperature: float = 0.3, trim_whitespace: bool = True) -> Image.Image:
|
| 672 |
try:
|
| 673 |
html_code = generate_html_from_text(text, temperature)
|
|
@@ -676,47 +462,30 @@ def text_to_screenshot(text: str, extension_percentage: float, temperature: floa
|
|
| 676 |
logger.error(f"テキストからスクリーンショット生成中にエラーが発生: {e}", exc_info=True)
|
| 677 |
return Image.new('RGB', (1, 1), color=(0, 0, 0))
|
| 678 |
|
| 679 |
-
# --- FastAPI Setup
|
| 680 |
app = FastAPI()
|
| 681 |
-
app.add_middleware(
|
| 682 |
-
|
| 683 |
-
allow_origins=["*"],
|
| 684 |
-
allow_credentials=True,
|
| 685 |
-
allow_methods=["*"],
|
| 686 |
-
allow_headers=["*"],
|
| 687 |
-
)
|
| 688 |
gradio_dir = os.path.dirname(gr.__file__)
|
| 689 |
logger.info(f"Gradio version: {gr.__version__}")
|
| 690 |
logger.info(f"Gradio directory: {gradio_dir}")
|
|
|
|
| 691 |
static_dir = os.path.join(gradio_dir, "templates", "frontend", "static")
|
| 692 |
-
if os.path.exists(static_dir):
|
| 693 |
-
logger.info(f"Mounting static directory: {static_dir}")
|
| 694 |
-
app.mount("/static", StaticFiles(directory=static_dir), name="static")
|
| 695 |
app_dir = os.path.join(gradio_dir, "templates", "frontend", "_app")
|
| 696 |
-
if os.path.exists(app_dir):
|
| 697 |
-
logger.info(f"Mounting _app directory: {app_dir}")
|
| 698 |
-
app.mount("/_app", StaticFiles(directory=app_dir), name="_app")
|
| 699 |
assets_dir = os.path.join(gradio_dir, "templates", "frontend", "assets")
|
| 700 |
-
if os.path.exists(assets_dir):
|
| 701 |
-
logger.info(f"Mounting assets directory: {assets_dir}")
|
| 702 |
-
app.mount("/assets", StaticFiles(directory=assets_dir), name="assets")
|
| 703 |
cdn_dir = os.path.join(gradio_dir, "templates", "cdn")
|
| 704 |
-
if os.path.exists(cdn_dir):
|
| 705 |
-
logger.info(f"Mounting cdn directory: {cdn_dir}")
|
| 706 |
-
app.mount("/cdn", StaticFiles(directory=cdn_dir), name="cdn")
|
| 707 |
|
| 708 |
-
|
| 709 |
-
@app.post("/api/screenshot", response_class=StreamingResponse, tags=["Screenshot"]
|
| 710 |
async def api_render_screenshot(request: ScreenshotRequest):
|
| 711 |
try:
|
| 712 |
logger.info(f"API request received. Extension: {request.extension_percentage}%")
|
| 713 |
-
pil_image = render_fullpage_screenshot(
|
| 714 |
-
|
| 715 |
-
request.extension_percentage,
|
| 716 |
-
request.trim_whitespace
|
| 717 |
-
)
|
| 718 |
-
if pil_image.size == (1, 1):
|
| 719 |
-
logger.error("Screenshot generation failed, returning 1x1 image.")
|
| 720 |
img_byte_arr = BytesIO()
|
| 721 |
pil_image.save(img_byte_arr, format='PNG')
|
| 722 |
img_byte_arr.seek(0)
|
|
@@ -726,19 +495,12 @@ async def api_render_screenshot(request: ScreenshotRequest):
|
|
| 726 |
logger.error(f"API Error: {e}", exc_info=True)
|
| 727 |
raise HTTPException(status_code=500, detail=f"Internal Server Error: {e}")
|
| 728 |
|
| 729 |
-
|
| 730 |
-
@app.post("/api/text-to-screenshot", response_class=StreamingResponse, tags=["Screenshot", "Gemini"], summary="テキストからインフォグラフィックを生成")
|
| 731 |
async def api_text_to_screenshot(request: GeminiRequest):
|
| 732 |
try:
|
| 733 |
logger.info(f"テキスト→スクリーンショットAPIリクエスト受信。テキスト長さ: {len(request.text)}, 拡張率: {request.extension_percentage}%, 温度: {request.temperature}")
|
| 734 |
-
pil_image = text_to_screenshot(
|
| 735 |
-
|
| 736 |
-
request.extension_percentage,
|
| 737 |
-
request.temperature,
|
| 738 |
-
request.trim_whitespace
|
| 739 |
-
)
|
| 740 |
-
if pil_image.size == (1, 1):
|
| 741 |
-
logger.error("スクリーンショット生成に失敗しました。1x1画像を返します。")
|
| 742 |
img_byte_arr = BytesIO()
|
| 743 |
pil_image.save(img_byte_arr, format='PNG')
|
| 744 |
img_byte_arr.seek(0)
|
|
@@ -748,7 +510,7 @@ async def api_text_to_screenshot(request: GeminiRequest):
|
|
| 748 |
logger.error(f"API Error: {e}", exc_info=True)
|
| 749 |
raise HTTPException(status_code=500, detail=f"Internal Server Error: {e}")
|
| 750 |
|
| 751 |
-
# --- Gradio Interface Definition
|
| 752 |
def process_input(input_mode, input_text, extension_percentage, temperature, trim_whitespace):
|
| 753 |
if input_mode == "HTML入力":
|
| 754 |
return render_fullpage_screenshot(input_text, extension_percentage, trim_whitespace)
|
|
@@ -781,11 +543,9 @@ with gr.Blocks(title="Full Page Screenshot (テキスト変換対応)", theme=gr
|
|
| 781 |
- 使用モデル: {gemini_model} (環境変数 GEMINI_MODEL で変更可能)
|
| 782 |
""")
|
| 783 |
|
| 784 |
-
# --- Mount Gradio App
|
| 785 |
app = gr.mount_gradio_app(app, iface, path="/")
|
| 786 |
-
|
| 787 |
-
# --- Run with Uvicorn (for local testing) --- (変更なし)
|
| 788 |
if __name__ == "__main__":
|
| 789 |
import uvicorn
|
| 790 |
logger.info("Starting Uvicorn server for local development...")
|
| 791 |
-
uvicorn.run(app, host="0.0.0.0", port=7860)
|
|
|
|
| 10 |
from selenium.webdriver.common.by import By
|
| 11 |
from selenium.webdriver.support.ui import WebDriverWait
|
| 12 |
from selenium.webdriver.support import expected_conditions as EC
|
|
|
|
| 13 |
from selenium.common.exceptions import TimeoutException, JavascriptException
|
| 14 |
from PIL import Image
|
| 15 |
from io import BytesIO
|
|
|
|
| 17 |
import time
|
| 18 |
import os
|
| 19 |
import logging
|
|
|
|
|
|
|
| 20 |
import google.generativeai as genai
|
| 21 |
|
|
|
|
| 22 |
logging.basicConfig(level=logging.INFO)
|
| 23 |
logger = logging.getLogger(__name__)
|
| 24 |
|
| 25 |
+
# --- モデル定義 (変更なし) ---
|
| 26 |
class GeminiRequest(BaseModel):
|
|
|
|
| 27 |
text: str
|
| 28 |
+
extension_percentage: float = 6.0
|
| 29 |
+
temperature: float = 0.3
|
| 30 |
+
trim_whitespace: bool = True
|
| 31 |
|
| 32 |
class ScreenshotRequest(BaseModel):
|
|
|
|
| 33 |
html_code: str
|
| 34 |
+
extension_percentage: float = 6.0
|
| 35 |
+
trim_whitespace: bool = True
|
| 36 |
|
| 37 |
+
# --- ヘルパー関数 (変更なし) ---
|
| 38 |
def enhance_font_awesome_layout(html_code):
|
|
|
|
|
|
|
| 39 |
fa_fix_css = """
|
| 40 |
<style>
|
| 41 |
+
[class*="fa-"] { display: inline-block !important; margin-right: 8px !important; vertical-align: middle !important; }
|
| 42 |
+
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; }
|
| 43 |
+
.fa + span, .fas + span, .far + span, .fab + span, span + .fa, span + .fas, span + .far, span + .fab { display: inline-block !important; margin-left: 5px !important; }
|
| 44 |
+
.card [class*="fa-"], .card-body [class*="fa-"] { float: none !important; clear: none !important; position: relative !important; }
|
| 45 |
+
li [class*="fa-"], p [class*="fa-"] { margin-right: 10px !important; }
|
| 46 |
+
.inline-icon { display: inline-flex !important; align-items: center !important; justify-content: flex-start !important; }
|
| 47 |
+
[class*="fa-"] + span { display: inline-block !important; vertical-align: middle !important; }
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 48 |
</style>
|
| 49 |
"""
|
|
|
|
|
|
|
| 50 |
if '<head>' in html_code:
|
| 51 |
return html_code.replace('</head>', f'{fa_fix_css}</head>')
|
|
|
|
| 52 |
elif '<html' in html_code:
|
| 53 |
head_end = html_code.find('</head>')
|
| 54 |
if head_end > 0:
|
|
|
|
| 57 |
body_start = html_code.find('<body')
|
| 58 |
if body_start > 0:
|
| 59 |
return html_code[:body_start] + f'<head>{fa_fix_css}</head>' + html_code[body_start:]
|
|
|
|
|
|
|
| 60 |
return f'<html><head>{fa_fix_css}</head>' + html_code + '</html>'
|
| 61 |
|
| 62 |
def generate_html_from_text(text, temperature=0.3):
|
|
|
|
| 63 |
try:
|
|
|
|
| 64 |
api_key = os.environ.get("GEMINI_API_KEY")
|
| 65 |
if not api_key:
|
| 66 |
logger.error("GEMINI_API_KEY 環境変数が設定されていません")
|
| 67 |
raise ValueError("GEMINI_API_KEY 環境変数が設定されていません")
|
|
|
|
|
|
|
| 68 |
model_name = os.environ.get("GEMINI_MODEL", "gemini-1.5-pro")
|
| 69 |
logger.info(f"使用するGeminiモデル: {model_name}")
|
|
|
|
|
|
|
| 70 |
genai.configure(api_key=api_key)
|
| 71 |
+
system_instruction = """... (プロンプトは変更なし) ...""" # 省略
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 72 |
logger.info(f"Gemini APIにリクエストを送信: テキスト長さ = {len(text)}, 温度 = {temperature}")
|
|
|
|
|
|
|
| 73 |
try:
|
| 74 |
model = genai.GenerativeModel(model_name)
|
| 75 |
except Exception as e:
|
| 76 |
fallback_model = "gemini-pro"
|
| 77 |
logger.warning(f"{model_name}が利用できません: {e}, フォールバックモデル{fallback_model}を使用します")
|
| 78 |
model = genai.GenerativeModel(fallback_model)
|
| 79 |
+
generation_config = {"temperature": temperature, "top_p": 0.7, "top_k": 20, "max_output_tokens": 8192, "candidate_count": 1}
|
| 80 |
+
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"}]
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 81 |
prompt = f"{system_instruction}\n\n{text}"
|
| 82 |
+
response = model.generate_content(prompt, generation_config=generation_config, safety_settings=safety_settings)
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 83 |
raw_response = response.text
|
| 84 |
html_start = raw_response.find("```html")
|
| 85 |
html_end = raw_response.rfind("```")
|
|
|
|
| 86 |
if html_start != -1 and html_end != -1 and html_start < html_end:
|
| 87 |
html_start += 7
|
| 88 |
html_code = raw_response[html_start:html_end].strip()
|
|
|
|
| 93 |
else:
|
| 94 |
logger.warning("レスポンスから```html```タグが見つかりませんでした。全テキストを返します。")
|
| 95 |
return raw_response
|
|
|
|
| 96 |
except Exception as e:
|
| 97 |
logger.error(f"HTML生成中にエラーが発生: {e}", exc_info=True)
|
| 98 |
raise Exception(f"Gemini APIでのHTML生成に失敗しました: {e}")
|
| 99 |
|
|
|
|
| 100 |
def trim_image_whitespace(image, threshold=250, padding=10):
|
| 101 |
+
# (変更なし)
|
| 102 |
gray = image.convert('L')
|
| 103 |
data = gray.getdata()
|
| 104 |
width, height = gray.size
|
|
|
|
| 124 |
logger.info(f"画像をトリミングしました: 元サイズ {width}x{height} → トリミング後 {trimmed.width}x{trimmed.height}")
|
| 125 |
return trimmed
|
| 126 |
|
| 127 |
+
# --- Core Screenshot Logic (修正箇所あり) ---
|
| 128 |
def render_fullpage_screenshot(html_code: str, extension_percentage: float = 6.0,
|
| 129 |
trim_whitespace: bool = True) -> Image.Image:
|
|
|
|
|
|
|
|
|
|
| 130 |
tmp_path = None
|
| 131 |
driver = None
|
|
|
|
|
|
|
| 132 |
try:
|
| 133 |
+
# 1) Save HTML (変更なし)
|
| 134 |
with tempfile.NamedTemporaryFile(suffix=".html", delete=False, mode='w', encoding='utf-8') as tmp_file:
|
| 135 |
tmp_path = tmp_file.name
|
| 136 |
tmp_file.write(html_code)
|
| 137 |
logger.info(f"HTML saved to temporary file: {tmp_path}")
|
|
|
|
|
|
|
|
|
|
| 138 |
|
| 139 |
+
# 2) Options (変更なし)
|
| 140 |
+
options = Options()
|
| 141 |
+
options.add_argument("--headless")
|
| 142 |
+
options.add_argument("--no-sandbox")
|
| 143 |
+
options.add_argument("--disable-dev-shm-usage")
|
| 144 |
+
options.add_argument("--force-device-scale-factor=1")
|
| 145 |
+
options.add_argument("--disable-features=NetworkService")
|
| 146 |
+
options.add_argument("--dns-prefetch-disable")
|
| 147 |
|
|
|
|
| 148 |
logger.info("Initializing WebDriver...")
|
| 149 |
driver = webdriver.Chrome(options=options)
|
| 150 |
logger.info("WebDriver initialized.")
|
| 151 |
|
| 152 |
+
# 3) Navigate (変更なし)
|
| 153 |
initial_width = 1200
|
| 154 |
initial_height = 1000
|
| 155 |
driver.set_window_size(initial_width, initial_height)
|
|
|
|
| 159 |
|
| 160 |
# 4) Wait for body (変更なし)
|
| 161 |
logger.info("Waiting for body element...")
|
| 162 |
+
WebDriverWait(driver, 15).until(EC.presence_of_element_located((By.TAG_NAME, "body")))
|
|
|
|
|
|
|
| 163 |
logger.info("Body element found. Waiting for potential resource loading...")
|
| 164 |
time.sleep(3)
|
| 165 |
|
| 166 |
+
# 5) Resource check (修正: 標準的なasync script形式)
|
| 167 |
try:
|
| 168 |
+
# スクリプト本体: Promiseを作成し、最後にcallbackを呼ぶ
|
| 169 |
resource_check_script = """
|
| 170 |
+
const callback = arguments[arguments.length - 1];
|
| 171 |
+
new Promise((resolve) => {
|
| 172 |
const checkFontAwesome = () => {
|
| 173 |
const icons = document.querySelectorAll('.fa, .fas, .far, .fab, [class*="fa-"]');
|
| 174 |
if (icons.length > 0) {
|
| 175 |
document.fonts.ready.then(() => {
|
| 176 |
+
setTimeout(resolve, 1000); // フォント読み込み後少し待つ
|
| 177 |
});
|
| 178 |
} else {
|
| 179 |
+
document.fonts.ready.then(() => setTimeout(resolve, 500)); // アイコンなくてもフォント待機
|
| 180 |
}
|
| 181 |
};
|
| 182 |
if (document.readyState === 'complete') {
|
| 183 |
checkFontAwesome();
|
| 184 |
} else {
|
| 185 |
+
// loadイベントを待つ
|
| 186 |
+
window.addEventListener('load', checkFontAwesome, { once: true });
|
| 187 |
+
// 念のためタイムアウトも設定 (例: 10秒)
|
| 188 |
+
setTimeout(() => {
|
| 189 |
+
// loadイベントが発火しなかった場合でもresolveする
|
| 190 |
+
if (!document.fonts || document.fonts.status !== 'loaded') {
|
| 191 |
+
console.warn('Resource check fallback timeout reached.');
|
| 192 |
+
}
|
| 193 |
+
resolve();
|
| 194 |
+
}, 10000);
|
| 195 |
}
|
| 196 |
+
}).then(() => callback(true)).catch((err) => {
|
| 197 |
+
console.error('Resource check script error:', err);
|
| 198 |
+
callback(false); // エラー時はfalseを返す
|
| 199 |
});
|
|
|
|
| 200 |
"""
|
| 201 |
logger.info("Waiting for Font Awesome and other resources to load...")
|
| 202 |
+
driver.set_script_timeout(20) # スクリプト自体のタイムアウト
|
| 203 |
+
# スクリプト文字列をそのまま渡す
|
| 204 |
+
driver.execute_async_script(resource_check_script)
|
| 205 |
+
logger.info("Resources loaded successfully (or timed out)")
|
| 206 |
+
except (TimeoutException, JavascriptException) as e:
|
| 207 |
+
logger.warning(f"Resource loading check failed or timed out: {e}. Using fallback wait.")
|
|
|
|
| 208 |
time.sleep(8)
|
| 209 |
+
except Exception as e:
|
| 210 |
logger.error(f"Unexpected error during resource check: {e}", exc_info=True)
|
| 211 |
time.sleep(8)
|
| 212 |
|
| 213 |
+
# 6) Ensure content rendering (修正: 標準的なasync script形式)
|
| 214 |
try:
|
| 215 |
scroll_script = """
|
| 216 |
+
const callback = arguments[arguments.length - 1];
|
| 217 |
+
new Promise(resolve => {
|
| 218 |
const pageHeight = Math.max(
|
| 219 |
document.documentElement.scrollHeight || 0,
|
| 220 |
document.body ? document.body.scrollHeight || 0 : 0
|
| 221 |
);
|
| 222 |
const viewportHeight = window.innerHeight || document.documentElement.clientHeight || 800;
|
| 223 |
+
// ステップが0以下にならないように最低1pxは確保
|
| 224 |
+
const scrollStep = Math.max(1, Math.floor(viewportHeight * 0.8));
|
| 225 |
let currentPos = 0;
|
| 226 |
+
const maxScrolls = 50; // 無限ループ防止
|
| 227 |
+
let scrollCount = 0;
|
| 228 |
|
| 229 |
const scrollDown = () => {
|
| 230 |
+
scrollCount++;
|
| 231 |
+
if (!document.body || pageHeight <= 0 || scrollCount > maxScrolls) {
|
| 232 |
+
if (scrollCount > maxScrolls) console.warn('Max scrolls reached in rendering check.');
|
| 233 |
window.scrollTo(0, 0);
|
| 234 |
setTimeout(resolve, 300);
|
| 235 |
return;
|
|
|
|
| 237 |
|
| 238 |
if (currentPos < pageHeight) {
|
| 239 |
window.scrollTo(0, currentPos);
|
| 240 |
+
// スクロール位置が意図通りか確認 (稀に動かないことがあるため)
|
| 241 |
+
const actualScrollY = window.scrollY;
|
| 242 |
+
// 少し下にスクロールしたと仮定して次の位置を計算
|
| 243 |
currentPos += scrollStep;
|
| 244 |
+
|
| 245 |
+
// スクロール位置が変わらない、または終端近くなら終了処理へ
|
| 246 |
+
if (actualScrollY >= pageHeight - viewportHeight || currentPos >= pageHeight ) {
|
| 247 |
+
window.scrollTo(0, pageHeight); // 最後に一番下まで
|
| 248 |
setTimeout(() => {
|
| 249 |
+
window.scrollTo(0, 0); // トップに戻す
|
| 250 |
setTimeout(resolve, 300);
|
| 251 |
}, 150);
|
| 252 |
} else {
|
| 253 |
+
setTimeout(scrollDown, 100); // 次のスクロール
|
| 254 |
}
|
| 255 |
} else {
|
| 256 |
+
window.scrollTo(0, 0); // トップに戻す
|
| 257 |
setTimeout(resolve, 300);
|
| 258 |
}
|
| 259 |
};
|
| 260 |
+
// 初回実行
|
| 261 |
setTimeout(scrollDown, 100);
|
| 262 |
+
}).then(() => callback(true)).catch((err) => {
|
| 263 |
+
console.error('Scroll script error:', err);
|
| 264 |
+
callback(false);
|
| 265 |
});
|
|
|
|
| 266 |
"""
|
| 267 |
+
logger.info("Ensuring all content is rendered by scrolling...")
|
| 268 |
+
driver.set_script_timeout(30) # スクロールは時間がかかる可能性があるので長め
|
| 269 |
+
driver.execute_async_script(scroll_script)
|
|
|
|
|
|
|
| 270 |
logger.info("Content rendering scroll finished.")
|
| 271 |
+
except (TimeoutException, JavascriptException) as e:
|
| 272 |
+
logger.warning(f"Content rendering scroll failed or timed out: {e}. Scrolling to top and waiting.")
|
| 273 |
try:
|
| 274 |
driver.execute_script("window.scrollTo(0, 0);")
|
| 275 |
except Exception as scroll_err:
|
| 276 |
logger.error(f"Could not scroll to top after render check failure: {scroll_err}")
|
| 277 |
+
time.sleep(3)
|
| 278 |
+
except Exception as e:
|
| 279 |
logger.error(f"Unexpected error during content rendering scroll: {e}", exc_info=True)
|
| 280 |
time.sleep(3)
|
| 281 |
|
| 282 |
# 7) Hide scrollbars (変更なし)
|
| 283 |
try:
|
| 284 |
+
driver.execute_script("document.documentElement.style.overflow = 'hidden'; document.body.style.overflow = 'hidden';")
|
|
|
|
|
|
|
|
|
|
| 285 |
logger.info("Scrollbars hidden via JS.")
|
| 286 |
except Exception as e:
|
| 287 |
logger.warning(f"Could not hide scrollbars via JS: {e}")
|
| 288 |
|
| 289 |
+
# 8) Get dimensions (変更なし)
|
| 290 |
try:
|
| 291 |
+
dimensions_script = """... (変更なし) ...""" # 省略
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 292 |
dimensions = driver.execute_script(dimensions_script)
|
| 293 |
scroll_width = dimensions['width']
|
| 294 |
scroll_height = dimensions['height']
|
| 295 |
logger.info(f"Detected dimensions: width={scroll_width}, height={scroll_height}")
|
|
|
|
|
|
|
| 296 |
try:
|
| 297 |
driver.execute_script("window.scrollTo(0, document.body.scrollHeight);")
|
| 298 |
time.sleep(1)
|
|
|
|
| 303 |
logger.info(f"After scroll check, height={scroll_height}")
|
| 304 |
except Exception as scroll_e:
|
| 305 |
logger.warning(f"Error during dimension scroll check: {scroll_e}")
|
|
|
|
| 306 |
scroll_width = max(scroll_width, 100)
|
| 307 |
scroll_height = max(scroll_height, 100)
|
| 308 |
scroll_width = min(scroll_width, 2000)
|
| 309 |
scroll_height = min(scroll_height, 4000)
|
|
|
|
| 310 |
except Exception as e:
|
| 311 |
logger.error(f"Error getting page dimensions: {e}")
|
| 312 |
scroll_width = 1200
|
| 313 |
scroll_height = 1000
|
| 314 |
logger.warning(f"Falling back to dimensions: width={scroll_width}, height={scroll_height}")
|
| 315 |
|
| 316 |
+
# 9) Layout stability check (修正: 標準的なasync script形式)
|
| 317 |
try:
|
| 318 |
stability_script = """
|
| 319 |
+
const callback = arguments[arguments.length - 1];
|
| 320 |
+
new Promise((resolve) => {
|
| 321 |
let lastHeight = 0;
|
| 322 |
let lastWidth = 0;
|
| 323 |
let stableCount = 0;
|
|
|
|
| 328 |
checkCount++;
|
| 329 |
if (checkCount > maxChecks) {
|
| 330 |
console.warn('Layout stability check reached max attempts.');
|
| 331 |
+
resolve(false); // 安定しなかった
|
| 332 |
return;
|
| 333 |
}
|
| 334 |
+
// body要素とそのプロパティの存在を確認
|
| 335 |
const bodyExists = document.body && typeof document.body.offsetHeight === 'number' && typeof document.body.offsetWidth === 'number';
|
| 336 |
if (!bodyExists) {
|
| 337 |
console.warn('Document body not fully available yet for stability check.');
|
| 338 |
setTimeout(checkStability, 250);
|
| 339 |
return;
|
| 340 |
}
|
|
|
|
| 341 |
const currentHeight = document.body.offsetHeight;
|
| 342 |
const currentWidth = document.body.offsetWidth;
|
| 343 |
|
| 344 |
+
// サイズ0も不安定とみなす
|
| 345 |
if (currentHeight === 0 || currentWidth === 0) {
|
| 346 |
+
stableCount = 0; lastHeight = 0; lastWidth = 0;
|
|
|
|
|
|
|
| 347 |
console.warn('Body dimensions are zero, waiting...');
|
| 348 |
setTimeout(checkStability, 250);
|
| 349 |
return;
|
| 350 |
}
|
| 351 |
+
// サイズが前回と同じかチェック
|
| 352 |
if (currentHeight === lastHeight && currentWidth === lastWidth) {
|
| 353 |
stableCount++;
|
| 354 |
+
if (stableCount >= 3) { // 3回連続で安定
|
| 355 |
console.log('Layout deemed stable.');
|
| 356 |
+
resolve(true); // 安定した
|
| 357 |
return;
|
| 358 |
}
|
| 359 |
} else {
|
| 360 |
+
// サイズが変わったらリセット
|
| 361 |
stableCount = 0;
|
| 362 |
lastHeight = currentHeight;
|
| 363 |
lastWidth = currentWidth;
|
| 364 |
console.log(`Layout changed: ${lastWidth}x${lastHeight}. Resetting stability count.`);
|
| 365 |
}
|
| 366 |
+
// 次のチェック
|
| 367 |
setTimeout(checkStability, 200);
|
| 368 |
};
|
| 369 |
+
// 初回チェック開始
|
| 370 |
setTimeout(checkStability, 100);
|
| 371 |
+
}).then(result => callback(result)).catch((err) => {
|
| 372 |
+
console.error('Stability check script error:', err);
|
| 373 |
+
callback(false); // エラー時はfalse
|
| 374 |
});
|
|
|
|
| 375 |
"""
|
| 376 |
logger.info("Checking layout stability...")
|
| 377 |
driver.set_script_timeout(20)
|
| 378 |
+
# スクリプトを実行し、結果を受け取る
|
| 379 |
+
stable = driver.execute_async_script(stability_script)
|
|
|
|
| 380 |
|
| 381 |
if stable:
|
| 382 |
logger.info("Layout is stable")
|
|
|
|
| 387 |
except TimeoutException:
|
| 388 |
logger.warning("Layout stability check timed out. Proceeding anyway.")
|
| 389 |
time.sleep(2)
|
| 390 |
+
except JavascriptException as e:
|
| 391 |
+
logger.error(f"Javascript error during layout stability check: {e}", exc_info=False) # スタックトレースは冗長なのでFalseに
|
| 392 |
time.sleep(2)
|
| 393 |
except Exception as e:
|
| 394 |
logger.error(f"Unexpected error during layout stability check: {e}", exc_info=True)
|
| 395 |
time.sleep(2)
|
| 396 |
|
| 397 |
+
# 10) Calculate height (変更なし)
|
| 398 |
adjusted_height = int(scroll_height * (1 + extension_percentage / 100.0))
|
| 399 |
adjusted_height = max(adjusted_height, scroll_height, 100)
|
| 400 |
logger.info(f"Adjusted height calculated: {adjusted_height} (extension: {extension_percentage}%)")
|
| 401 |
|
| 402 |
+
# 11) Resize window and wait (変更なし)
|
| 403 |
adjusted_width = scroll_width
|
| 404 |
logger.info(f"Resizing window to: width={adjusted_width}, height={adjusted_height}")
|
| 405 |
driver.set_window_size(adjusted_width, adjusted_height)
|
| 406 |
logger.info("Waiting for layout stabilization after resize...")
|
| 407 |
time.sleep(4)
|
| 408 |
|
| 409 |
+
# Resource state check (変更なし)
|
| 410 |
try:
|
| 411 |
+
resource_state = driver.execute_script("return { readyState: document.readyState, resourcesComplete: !document.querySelector('img:not([complete])') && !document.querySelector('link[rel=\"stylesheet\"]:not([loaded])') };")
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 412 |
logger.info(f"Resource state: {resource_state}")
|
| 413 |
if resource_state['readyState'] != 'complete':
|
| 414 |
logger.info("Document still loading, waiting additional time...")
|
|
|
|
| 416 |
except Exception as e:
|
| 417 |
logger.warning(f"Error checking resource state: {e}")
|
| 418 |
|
| 419 |
+
# Scroll to top (変更なし)
|
| 420 |
try:
|
| 421 |
driver.execute_script("window.scrollTo(0, 0)")
|
| 422 |
time.sleep(1)
|
|
|
|
| 453 |
except Exception as e:
|
| 454 |
logger.error(f"Error removing temporary file {tmp_path}: {e}")
|
| 455 |
|
| 456 |
+
# --- text_to_screenshot 関数 (変更なし) ---
|
| 457 |
def text_to_screenshot(text: str, extension_percentage: float, temperature: float = 0.3, trim_whitespace: bool = True) -> Image.Image:
|
| 458 |
try:
|
| 459 |
html_code = generate_html_from_text(text, temperature)
|
|
|
|
| 462 |
logger.error(f"テキストからスクリーンショット生成中にエラーが発生: {e}", exc_info=True)
|
| 463 |
return Image.new('RGB', (1, 1), color=(0, 0, 0))
|
| 464 |
|
| 465 |
+
# --- FastAPI Setup & Endpoints (変更なし) ---
|
| 466 |
app = FastAPI()
|
| 467 |
+
app.add_middleware(CORSMiddleware, allow_origins=["*"], allow_credentials=True, allow_methods=["*"], allow_headers=["*"])
|
| 468 |
+
# Static file mounting (変更なし)
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 469 |
gradio_dir = os.path.dirname(gr.__file__)
|
| 470 |
logger.info(f"Gradio version: {gr.__version__}")
|
| 471 |
logger.info(f"Gradio directory: {gradio_dir}")
|
| 472 |
+
# ... (static, _app, assets, cdnのマウント処理は省略) ...
|
| 473 |
static_dir = os.path.join(gradio_dir, "templates", "frontend", "static")
|
| 474 |
+
if os.path.exists(static_dir): app.mount("/static", StaticFiles(directory=static_dir), name="static")
|
|
|
|
|
|
|
| 475 |
app_dir = os.path.join(gradio_dir, "templates", "frontend", "_app")
|
| 476 |
+
if os.path.exists(app_dir): app.mount("/_app", StaticFiles(directory=app_dir), name="_app")
|
|
|
|
|
|
|
| 477 |
assets_dir = os.path.join(gradio_dir, "templates", "frontend", "assets")
|
| 478 |
+
if os.path.exists(assets_dir): app.mount("/assets", StaticFiles(directory=assets_dir), name="assets")
|
|
|
|
|
|
|
| 479 |
cdn_dir = os.path.join(gradio_dir, "templates", "cdn")
|
| 480 |
+
if os.path.exists(cdn_dir): app.mount("/cdn", StaticFiles(directory=cdn_dir), name="cdn")
|
|
|
|
|
|
|
| 481 |
|
| 482 |
+
|
| 483 |
+
@app.post("/api/screenshot", response_class=StreamingResponse, tags=["Screenshot"])
|
| 484 |
async def api_render_screenshot(request: ScreenshotRequest):
|
| 485 |
try:
|
| 486 |
logger.info(f"API request received. Extension: {request.extension_percentage}%")
|
| 487 |
+
pil_image = render_fullpage_screenshot(request.html_code, request.extension_percentage, request.trim_whitespace)
|
| 488 |
+
if pil_image.size == (1, 1): logger.error("Screenshot generation failed, returning 1x1 image.")
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 489 |
img_byte_arr = BytesIO()
|
| 490 |
pil_image.save(img_byte_arr, format='PNG')
|
| 491 |
img_byte_arr.seek(0)
|
|
|
|
| 495 |
logger.error(f"API Error: {e}", exc_info=True)
|
| 496 |
raise HTTPException(status_code=500, detail=f"Internal Server Error: {e}")
|
| 497 |
|
| 498 |
+
@app.post("/api/text-to-screenshot", response_class=StreamingResponse, tags=["Screenshot", "Gemini"])
|
|
|
|
| 499 |
async def api_text_to_screenshot(request: GeminiRequest):
|
| 500 |
try:
|
| 501 |
logger.info(f"テキスト→スクリーンショットAPIリクエスト受信。テキスト長さ: {len(request.text)}, 拡張率: {request.extension_percentage}%, 温度: {request.temperature}")
|
| 502 |
+
pil_image = text_to_screenshot(request.text, request.extension_percentage, request.temperature, request.trim_whitespace)
|
| 503 |
+
if pil_image.size == (1, 1): logger.error("スクリーンショット生成に失敗しました。1x1画像を返します。")
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 504 |
img_byte_arr = BytesIO()
|
| 505 |
pil_image.save(img_byte_arr, format='PNG')
|
| 506 |
img_byte_arr.seek(0)
|
|
|
|
| 510 |
logger.error(f"API Error: {e}", exc_info=True)
|
| 511 |
raise HTTPException(status_code=500, detail=f"Internal Server Error: {e}")
|
| 512 |
|
| 513 |
+
# --- Gradio Interface Definition (変更なし) ---
|
| 514 |
def process_input(input_mode, input_text, extension_percentage, temperature, trim_whitespace):
|
| 515 |
if input_mode == "HTML入力":
|
| 516 |
return render_fullpage_screenshot(input_text, extension_percentage, trim_whitespace)
|
|
|
|
| 543 |
- 使用モデル: {gemini_model} (環境変数 GEMINI_MODEL で変更可能)
|
| 544 |
""")
|
| 545 |
|
| 546 |
+
# --- Mount Gradio App & Run (変更なし) ---
|
| 547 |
app = gr.mount_gradio_app(app, iface, path="/")
|
|
|
|
|
|
|
| 548 |
if __name__ == "__main__":
|
| 549 |
import uvicorn
|
| 550 |
logger.info("Starting Uvicorn server for local development...")
|
| 551 |
+
uvicorn.run(app, host="0.0.0.0", port=7860)
|