Spaces:
Paused
Paused
Update app.py
Browse files
app.py
CHANGED
|
@@ -15,7 +15,6 @@ import tempfile
|
|
| 15 |
import time
|
| 16 |
import os
|
| 17 |
import logging
|
| 18 |
-
import re
|
| 19 |
|
| 20 |
# 正しいGemini関連のインポート
|
| 21 |
import google.generativeai as genai
|
|
@@ -31,7 +30,6 @@ class GeminiRequest(BaseModel):
|
|
| 31 |
extension_percentage: float = 6.0 # デフォルト値6%
|
| 32 |
temperature: float = 1.0 # デフォルト値1.0の温度パラメータ
|
| 33 |
trim_whitespace: bool = True # 余白トリミングオプション(デフォルト有効)
|
| 34 |
-
layout_type: str = "standard" # レイアウトタイプ(standard, spaced, compact)
|
| 35 |
|
| 36 |
class ScreenshotRequest(BaseModel):
|
| 37 |
"""スクリーンショットリクエストモデル"""
|
|
@@ -39,7 +37,77 @@ class ScreenshotRequest(BaseModel):
|
|
| 39 |
extension_percentage: float = 6.0 # デフォルト値6%
|
| 40 |
trim_whitespace: bool = True # 余白トリミングオプション(デフォルト有効)
|
| 41 |
|
| 42 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 43 |
"""テキストからHTMLを生成する"""
|
| 44 |
try:
|
| 45 |
# APIキーの取得と設定
|
|
@@ -55,88 +123,8 @@ def generate_html_from_text(text, temperature=1.0, layout_type="standard"):
|
|
| 55 |
# Gemini APIの設定
|
| 56 |
genai.configure(api_key=api_key)
|
| 57 |
|
| 58 |
-
#
|
| 59 |
-
|
| 60 |
-
if layout_type == "spaced":
|
| 61 |
-
layout_adjustments = """
|
| 62 |
-
## 特別なスタイル設定
|
| 63 |
-
- 全てのテキスト要素には最低2rem以上の行間と要素間マージンを設定する
|
| 64 |
-
- 各カードのパディングを1.5倍に増やす
|
| 65 |
-
- 箇条書きリストのアイテム間は1.5emの間隔を確保する
|
| 66 |
-
- すべての文字サイズを15%大きくする
|
| 67 |
-
- 内容量に応じて自動的にグリッドやフレックスレイアウトを調整する
|
| 68 |
-
- テキストが重ならないように要素間に十分なスペースを強制的に設ける
|
| 69 |
-
"""
|
| 70 |
-
elif layout_type == "compact":
|
| 71 |
-
layout_adjustments = """
|
| 72 |
-
## 特別なスタイル設定
|
| 73 |
-
- レイアウトをよりコンパクトに配置
|
| 74 |
-
- 小さめのアイコンサイズを使用(標準の75%)
|
| 75 |
-
- フォントサイズを10%小さく設定
|
| 76 |
-
- テキスト量が多い場合は自動的に複数列に分割表示
|
| 77 |
-
"""
|
| 78 |
-
|
| 79 |
-
# レイアウト崩れ防止のための追加指示
|
| 80 |
-
layout_improvements = """
|
| 81 |
-
## 重要なレイアウト指示(必ず守ってください)
|
| 82 |
-
- カード要素は必ずdisplay: gridまたはflexboxで配置してください
|
| 83 |
-
- カードの配置は絶対位置(position: absolute)を使わず、フロー配置を使ってください
|
| 84 |
-
- 各カードには以下のスタイルを必ず適用してください:
|
| 85 |
-
```css
|
| 86 |
-
.card {
|
| 87 |
-
position: relative;
|
| 88 |
-
clear: both;
|
| 89 |
-
display: flex;
|
| 90 |
-
flex-direction: column;
|
| 91 |
-
margin: 1.5rem 0;
|
| 92 |
-
padding: 1.2rem;
|
| 93 |
-
height: auto;
|
| 94 |
-
overflow: visible;
|
| 95 |
-
box-sizing: border-box;
|
| 96 |
-
}
|
| 97 |
-
```
|
| 98 |
-
|
| 99 |
-
- 兄弟要素間のマージンは必ず以下のように設定してください:
|
| 100 |
-
```css
|
| 101 |
-
.card + .card,
|
| 102 |
-
.section + .section,
|
| 103 |
-
.info-box + .info-box,
|
| 104 |
-
.row + .row {
|
| 105 |
-
margin-top: 2rem;
|
| 106 |
-
}
|
| 107 |
-
```
|
| 108 |
-
|
| 109 |
-
- コンテナの高さは自動的に調整されるようにしてください:
|
| 110 |
-
```css
|
| 111 |
-
.container, .row, .column {
|
| 112 |
-
height: auto;
|
| 113 |
-
overflow: hidden;
|
| 114 |
-
display: flex;
|
| 115 |
-
flex-direction: column;
|
| 116 |
-
}
|
| 117 |
-
```
|
| 118 |
-
|
| 119 |
-
- グリッドレイアウトを使用する場合は明示的な行の高さを設定してください:
|
| 120 |
-
```css
|
| 121 |
-
.grid {
|
| 122 |
-
display: grid;
|
| 123 |
-
grid-template-columns: repeat(auto-fit, minmax(300px, 1fr));
|
| 124 |
-
grid-gap: 2rem;
|
| 125 |
-
grid-auto-rows: minmax(min-content, auto);
|
| 126 |
-
}
|
| 127 |
-
```
|
| 128 |
-
|
| 129 |
-
- すべてのテキスト要素に余白を設定してください:
|
| 130 |
-
```css
|
| 131 |
-
p, h1, h2, h3, h4, h5, h6, li {
|
| 132 |
-
margin-bottom: 1rem;
|
| 133 |
-
line-height: 1.6;
|
| 134 |
-
}
|
| 135 |
-
```
|
| 136 |
-
"""
|
| 137 |
-
|
| 138 |
-
# システムプロンプト(強化版)
|
| 139 |
-
system_instruction = f"""# グラフィックレコーディング風インフォグラフィック変換プロンプト V3
|
| 140 |
## 目的
|
| 141 |
以下の内容を、超一流デザイナーが作成したような、日本語で完璧なグラフィックレコーディング風のHTMLインフォグラフィックに変換してください。情報設計とビジュアルデザインの両面で最高水準を目指します。
|
| 142 |
手書き風の図形やFont Awesomeアイコンを大きく活用して内容を視覚的かつ直感的に表現します。
|
|
@@ -183,8 +171,8 @@ def generate_html_from_text(text, temperature=1.0, layout_type="standard"):
|
|
| 183 |
- フォント指定:
|
| 184 |
```html
|
| 185 |
<style>
|
| 186 |
-
@import url('https://fonts.googleapis.com/css2?family=Kaisei+Decol&family=Yomogi&family=Zen+Kurenaido&display=swap');
|
| 187 |
-
@import url('https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.4.0/css/all.min.css');
|
| 188 |
</style>
|
| 189 |
```
|
| 190 |
### 5. レイアウト
|
|
@@ -196,81 +184,15 @@ def generate_html_from_text(text, temperature=1.0, layout_type="standard"):
|
|
| 196 |
- 横幅は100%
|
| 197 |
- 重要な要素は中央寄り、補足情報は周辺部に配置
|
| 198 |
|
| 199 |
-
|
| 200 |
-
|
| 201 |
-
|
| 202 |
-
-
|
| 203 |
-
-
|
| 204 |
-
-
|
| 205 |
-
-
|
| 206 |
-
-
|
| 207 |
-
|
| 208 |
-
.card, .section, .info-box {{
|
| 209 |
-
overflow: hidden;
|
| 210 |
-
display: flex;
|
| 211 |
-
flex-direction: column;
|
| 212 |
-
margin-bottom: 1.5rem;
|
| 213 |
-
min-height: fit-content;
|
| 214 |
-
}}
|
| 215 |
-
.card-content {{
|
| 216 |
-
flex: 1;
|
| 217 |
-
display: flex;
|
| 218 |
-
flex-direction: column;
|
| 219 |
-
}}
|
| 220 |
-
.card-title {{
|
| 221 |
-
font-weight: bold;
|
| 222 |
-
margin-bottom: 0.75rem;
|
| 223 |
-
line-height: 1.4;
|
| 224 |
-
}}
|
| 225 |
-
.card-text {{
|
| 226 |
-
line-height: 1.6;
|
| 227 |
-
margin-bottom: 0.5rem;
|
| 228 |
-
}}
|
| 229 |
-
.info-item {{
|
| 230 |
-
margin-bottom: 0.75rem;
|
| 231 |
-
line-height: 1.5;
|
| 232 |
-
}}
|
| 233 |
-
li {{
|
| 234 |
-
margin-bottom: 0.5rem;
|
| 235 |
-
line-height: 1.5;
|
| 236 |
-
}}
|
| 237 |
-
p {{
|
| 238 |
-
margin-bottom: 0.75rem;
|
| 239 |
-
line-height: 1.5;
|
| 240 |
-
}}
|
| 241 |
-
```
|
| 242 |
-
|
| 243 |
-
## 自動テキスト調整機能
|
| 244 |
-
以下のJavaScriptを必ず追加して、テキスト量に応じたフォントサイズの自動調整を行う:
|
| 245 |
-
```html
|
| 246 |
-
<script>
|
| 247 |
-
document.addEventListener('DOMContentLoaded', function() {{
|
| 248 |
-
// カード内のテキスト量に基づいてフォントサイズを調整
|
| 249 |
-
const cards = document.querySelectorAll('.card, .section, .info-box');
|
| 250 |
-
cards.forEach(card => {{
|
| 251 |
-
const cardContent = card.querySelector('.card-content') || card;
|
| 252 |
-
const textLength = cardContent.textContent.length;
|
| 253 |
-
|
| 254 |
-
// テキスト量に応じてフォントサイズを調整
|
| 255 |
-
if (textLength > 200) {{
|
| 256 |
-
card.style.fontSize = '0.9em';
|
| 257 |
-
}}
|
| 258 |
-
if (textLength > 300) {{
|
| 259 |
-
card.style.fontSize = '0.85em';
|
| 260 |
-
}}
|
| 261 |
-
|
| 262 |
-
// カード内の要素間の余白を確保
|
| 263 |
-
const elements = card.querySelectorAll('p, h3, h4, ul, ol, .info-item');
|
| 264 |
-
elements.forEach(el => {{
|
| 265 |
-
el.style.marginBottom = '0.75rem';
|
| 266 |
-
el.style.lineHeight = '1.5';
|
| 267 |
-
}});
|
| 268 |
-
}});
|
| 269 |
-
}});
|
| 270 |
-
</script>
|
| 271 |
-
```
|
| 272 |
-
|
| 273 |
-
{layout_adjustments}
|
| 274 |
|
| 275 |
## グラフィックレコーディング表現技法
|
| 276 |
- テキストと視覚要素のバランスを重視(文字情報の50%以上をFont Awesomeアイコンで視覚的に補完)
|
|
@@ -311,7 +233,7 @@ document.addEventListener('DOMContentLoaded', function() {{
|
|
| 311 |
ーーー<ユーザーが入力(または添付)>ーーー"""
|
| 312 |
|
| 313 |
# モデルを初期化して処理
|
| 314 |
-
logger.info(f"Gemini APIにリクエストを送信: テキスト長さ = {len(text)}, 温度 = {temperature}
|
| 315 |
|
| 316 |
# モデル初期化とフォールバック処理
|
| 317 |
try:
|
|
@@ -351,8 +273,9 @@ document.addEventListener('DOMContentLoaded', function() {{
|
|
| 351 |
html_code = raw_response[html_start:html_end].strip()
|
| 352 |
logger.info(f"HTMLの生成に成功: 長さ = {len(html_code)}")
|
| 353 |
|
| 354 |
-
#
|
| 355 |
-
html_code =
|
|
|
|
| 356 |
|
| 357 |
return html_code
|
| 358 |
else:
|
|
@@ -364,237 +287,6 @@ document.addEventListener('DOMContentLoaded', function() {{
|
|
| 364 |
logger.error(f"HTML生成中にエラーが発生: {e}", exc_info=True)
|
| 365 |
raise Exception(f"Gemini APIでのHTML生成に失敗しました: {e}")
|
| 366 |
|
| 367 |
-
# HTMLを後処理してレイアウト崩れを防止する関数
|
| 368 |
-
def enhance_html_for_layout(html_code):
|
| 369 |
-
"""HTMLを後処理してレイアウト崩れを防止するための調整を行う(強化版)"""
|
| 370 |
-
try:
|
| 371 |
-
# 基本的なスタイルとスクリプトが含まれているか確認
|
| 372 |
-
base_styles_needed = True
|
| 373 |
-
base_scripts_needed = True
|
| 374 |
-
|
| 375 |
-
if "<style>" in html_code:
|
| 376 |
-
style_pos = html_code.find("</style>")
|
| 377 |
-
if style_pos != -1:
|
| 378 |
-
# カード要素のスタイルが含まれているか確認
|
| 379 |
-
if ".card" in html_code[:style_pos] and "flex-direction: column" in html_code[:style_pos]:
|
| 380 |
-
base_styles_needed = False
|
| 381 |
-
|
| 382 |
-
# レイアウト崩れ防止用の強化CSSを追加
|
| 383 |
-
enhanced_css = """
|
| 384 |
-
/* --- レイアウト崩れ防止強化スタイル --- */
|
| 385 |
-
.card, .section, .info-box {
|
| 386 |
-
position: relative !important;
|
| 387 |
-
display: flex !important;
|
| 388 |
-
flex-direction: column !important;
|
| 389 |
-
margin: 1.5rem 0 !important;
|
| 390 |
-
padding: 1.2rem !important;
|
| 391 |
-
height: auto !important;
|
| 392 |
-
min-height: fit-content !important;
|
| 393 |
-
overflow: visible !important;
|
| 394 |
-
box-sizing: border-box !important;
|
| 395 |
-
z-index: 1 !important;
|
| 396 |
-
clear: both !important;
|
| 397 |
-
}
|
| 398 |
-
|
| 399 |
-
/* フローティング要素のクリア */
|
| 400 |
-
.clearfix::after {
|
| 401 |
-
content: "" !important;
|
| 402 |
-
display: table !important;
|
| 403 |
-
clear: both !important;
|
| 404 |
-
}
|
| 405 |
-
|
| 406 |
-
/* コンテナ要素の高さ自動調整 */
|
| 407 |
-
.container, .row, .column {
|
| 408 |
-
height: auto !important;
|
| 409 |
-
overflow: hidden !important;
|
| 410 |
-
position: relative !important;
|
| 411 |
-
}
|
| 412 |
-
|
| 413 |
-
/* グリッドレイアウトの調整 */
|
| 414 |
-
.grid {
|
| 415 |
-
display: grid !important;
|
| 416 |
-
grid-template-columns: repeat(auto-fit, minmax(300px, 1fr)) !important;
|
| 417 |
-
grid-gap: 2rem !important;
|
| 418 |
-
grid-auto-rows: minmax(min-content, auto) !important;
|
| 419 |
-
}
|
| 420 |
-
|
| 421 |
-
/* マージンとパディングの強制 */
|
| 422 |
-
p, h1, h2, h3, h4, h5, h6, li {
|
| 423 |
-
margin-bottom: 1rem !important;
|
| 424 |
-
line-height: 1.6 !important;
|
| 425 |
-
}
|
| 426 |
-
|
| 427 |
-
/* 重なり解消のための特別なスタイル */
|
| 428 |
-
body {
|
| 429 |
-
overflow-x: hidden !important;
|
| 430 |
-
}
|
| 431 |
-
|
| 432 |
-
.card + .card, .section + .section, .info-box + .info-box {
|
| 433 |
-
margin-top: 2rem !important;
|
| 434 |
-
}
|
| 435 |
-
|
| 436 |
-
/* モバイル表示の改善 */
|
| 437 |
-
@media (max-width: 768px) {
|
| 438 |
-
.card, .section, .info-box {
|
| 439 |
-
width: 100% !important;
|
| 440 |
-
margin-left: 0 !important;
|
| 441 |
-
margin-right: 0 !important;
|
| 442 |
-
}
|
| 443 |
-
}
|
| 444 |
-
"""
|
| 445 |
-
# スタイルタグの閉じ直前に挿入
|
| 446 |
-
html_code = html_code[:style_pos] + enhanced_css + html_code[style_pos:]
|
| 447 |
-
|
| 448 |
-
# スタイルが存在しない場合は新たに追加
|
| 449 |
-
if base_styles_needed and "<style>" not in html_code:
|
| 450 |
-
head_end_pos = html_code.find("</head>")
|
| 451 |
-
if head_end_pos != -1:
|
| 452 |
-
base_styles = """
|
| 453 |
-
<style>
|
| 454 |
-
/* ベーススタイル - レイアウト崩れ防止 */
|
| 455 |
-
.card, .section, .info-box {
|
| 456 |
-
position: relative !important;
|
| 457 |
-
display: flex !important;
|
| 458 |
-
flex-direction: column !important;
|
| 459 |
-
margin: 1.5rem 0 !important;
|
| 460 |
-
padding: 1.2rem !important;
|
| 461 |
-
height: auto !important;
|
| 462 |
-
min-height: fit-content !important;
|
| 463 |
-
overflow: visible !important;
|
| 464 |
-
box-sizing: border-box !important;
|
| 465 |
-
z-index: 1 !important;
|
| 466 |
-
clear: both !important;
|
| 467 |
-
}
|
| 468 |
-
|
| 469 |
-
.card-content {
|
| 470 |
-
flex: 1 !important;
|
| 471 |
-
display: flex !important;
|
| 472 |
-
flex-direction: column !important;
|
| 473 |
-
}
|
| 474 |
-
|
| 475 |
-
.container, .row, .column {
|
| 476 |
-
height: auto !important;
|
| 477 |
-
overflow: hidden !important;
|
| 478 |
-
position: relative !important;
|
| 479 |
-
}
|
| 480 |
-
|
| 481 |
-
p, h1, h2, h3, h4, h5, h6, li {
|
| 482 |
-
margin-bottom: 1rem !important;
|
| 483 |
-
line-height: 1.6 !important;
|
| 484 |
-
}
|
| 485 |
-
|
| 486 |
-
/* 重なり解消のための特別なスタイル */
|
| 487 |
-
body {
|
| 488 |
-
overflow-x: hidden !important;
|
| 489 |
-
}
|
| 490 |
-
|
| 491 |
-
.card + .card, .section + .section, .info-box + .info-box {
|
| 492 |
-
margin-top: 2rem !important;
|
| 493 |
-
}
|
| 494 |
-
</style>
|
| 495 |
-
"""
|
| 496 |
-
html_code = html_code[:head_end_pos] + base_styles + html_code[head_end_pos:]
|
| 497 |
-
|
| 498 |
-
# 自動レイアウト修正用のスクリプトを強化
|
| 499 |
-
if "</body>" in html_code:
|
| 500 |
-
has_stabilize_script = "stabilizeLayout" in html_code
|
| 501 |
-
|
| 502 |
-
if not has_stabilize_script:
|
| 503 |
-
body_end_pos = html_code.find("</body>")
|
| 504 |
-
if body_end_pos != -1:
|
| 505 |
-
enhanced_script = """
|
| 506 |
-
<script>
|
| 507 |
-
// レイアウト安定化のための強化スクリプト
|
| 508 |
-
function stabilizeLayout() {
|
| 509 |
-
// カードの重なりを解消
|
| 510 |
-
document.querySelectorAll('.card, .section, .info-box').forEach(card => {
|
| 511 |
-
// 位置を相対指定に強制
|
| 512 |
-
card.style.position = 'relative';
|
| 513 |
-
|
| 514 |
-
// z-indexをカード間で競合しないよう設定
|
| 515 |
-
card.style.zIndex = '1';
|
| 516 |
-
|
| 517 |
-
// マージンを強制的に設定
|
| 518 |
-
card.style.marginBottom = '2rem';
|
| 519 |
-
card.style.marginTop = '1rem';
|
| 520 |
-
|
| 521 |
-
// 浮動要素のクリア
|
| 522 |
-
let clearDiv = document.createElement('div');
|
| 523 |
-
clearDiv.style.clear = 'both';
|
| 524 |
-
clearDiv.style.height = '1px';
|
| 525 |
-
card.parentNode.insertBefore(clearDiv, card.nextSibling);
|
| 526 |
-
|
| 527 |
-
// クリアフィックスクラスを追加
|
| 528 |
-
card.classList.add('clearfix');
|
| 529 |
-
});
|
| 530 |
-
|
| 531 |
-
// 親要素の高さを適切に設定
|
| 532 |
-
document.querySelectorAll('.row, .container, .column').forEach(container => {
|
| 533 |
-
container.style.overflow = 'hidden';
|
| 534 |
-
container.style.height = 'auto';
|
| 535 |
-
container.classList.add('clearfix');
|
| 536 |
-
|
| 537 |
-
// 子要素の合計高さを取得して設定
|
| 538 |
-
let totalHeight = 0;
|
| 539 |
-
Array.from(container.children).forEach(child => {
|
| 540 |
-
if (child.offsetHeight) {
|
| 541 |
-
totalHeight += child.offsetHeight +
|
| 542 |
-
parseInt(getComputedStyle(child).marginTop || 0) +
|
| 543 |
-
parseInt(getComputedStyle(child).marginBottom || 0);
|
| 544 |
-
}
|
| 545 |
-
});
|
| 546 |
-
|
| 547 |
-
if (totalHeight > 0) {
|
| 548 |
-
container.style.minHeight = (totalHeight + 50) + 'px';
|
| 549 |
-
}
|
| 550 |
-
});
|
| 551 |
-
|
| 552 |
-
// テキスト量に基づいてフォントサイズを調整
|
| 553 |
-
document.querySelectorAll('.card, .section, .info-box').forEach(card => {
|
| 554 |
-
const cardContent = card.querySelector('.card-content') || card;
|
| 555 |
-
const textLength = cardContent.textContent.length;
|
| 556 |
-
|
| 557 |
-
// テキスト量に応じてフォントサイズを調整
|
| 558 |
-
if (textLength > 200) {
|
| 559 |
-
card.style.fontSize = '0.9em';
|
| 560 |
-
}
|
| 561 |
-
if (textLength > 300) {
|
| 562 |
-
card.style.fontSize = '0.85em';
|
| 563 |
-
}
|
| 564 |
-
|
| 565 |
-
// カード内の要素間の余白を確保
|
| 566 |
-
const elements = card.querySelectorAll('p, h3, h4, ul, ol, .info-item');
|
| 567 |
-
elements.forEach(el => {
|
| 568 |
-
el.style.marginBottom = '0.75rem';
|
| 569 |
-
el.style.lineHeight = '1.5';
|
| 570 |
-
});
|
| 571 |
-
});
|
| 572 |
-
}
|
| 573 |
-
|
| 574 |
-
// DOMContentLoadedイベントで実行
|
| 575 |
-
document.addEventListener('DOMContentLoaded', stabilizeLayout);
|
| 576 |
-
|
| 577 |
-
// 安全のためにウィンドウロード時にも実行
|
| 578 |
-
window.addEventListener('load', stabilizeLayout);
|
| 579 |
-
|
| 580 |
-
// 1秒後に再度実行して安定化を確実にする
|
| 581 |
-
setTimeout(stabilizeLayout, 1000);
|
| 582 |
-
</script>
|
| 583 |
-
"""
|
| 584 |
-
html_code = html_code[:body_end_pos] + enhanced_script + html_code[body_end_pos:]
|
| 585 |
-
|
| 586 |
-
# カードコンテナのクラス追加
|
| 587 |
-
html_code = re.sub(r'<div class="([^"]*)"([^>]*)>', lambda m: f'<div class="{m.group(1)} card clearfix"{m.group(2)}>', html_code)
|
| 588 |
-
|
| 589 |
-
# ボディタグにクラス追加
|
| 590 |
-
if "<body" in html_code and "clearfix" not in html_code:
|
| 591 |
-
html_code = html_code.replace("<body", '<body class="clearfix"')
|
| 592 |
-
|
| 593 |
-
return html_code
|
| 594 |
-
except Exception as e:
|
| 595 |
-
logger.warning(f"HTMLの後処理中にエラーが発���しました: {e}")
|
| 596 |
-
return html_code # エラー時は元のHTMLを返す
|
| 597 |
-
|
| 598 |
# 画像から余分な空白領域をトリミングする関数
|
| 599 |
def trim_image_whitespace(image, threshold=250, padding=10):
|
| 600 |
"""
|
|
@@ -685,10 +377,6 @@ def render_fullpage_screenshot(html_code: str, extension_percentage: float = 6.0
|
|
| 685 |
# Font Awesomeが読み込まれない場合があるため、読み込み待機時間を長く設定
|
| 686 |
options.add_argument("--disable-features=NetworkService")
|
| 687 |
options.add_argument("--dns-prefetch-disable")
|
| 688 |
-
|
| 689 |
-
# 新規追加:CORSエラー防止のためのフラグ
|
| 690 |
-
options.add_argument("--disable-web-security")
|
| 691 |
-
options.add_argument("--allow-file-access-from-files")
|
| 692 |
|
| 693 |
try:
|
| 694 |
logger.info("Initializing WebDriver...")
|
|
@@ -710,10 +398,86 @@ def render_fullpage_screenshot(html_code: str, extension_percentage: float = 6.0
|
|
| 710 |
)
|
| 711 |
logger.info("Body element found. Waiting for potential resource loading...")
|
| 712 |
|
| 713 |
-
#
|
| 714 |
-
time.sleep(
|
| 715 |
|
| 716 |
-
# 5)
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 717 |
try:
|
| 718 |
driver.execute_script(
|
| 719 |
"document.documentElement.style.overflow = 'hidden';"
|
|
@@ -723,7 +487,7 @@ def render_fullpage_screenshot(html_code: str, extension_percentage: float = 6.0
|
|
| 723 |
except Exception as e:
|
| 724 |
logger.warning(f"Could not hide scrollbars via JS: {e}")
|
| 725 |
|
| 726 |
-
#
|
| 727 |
try:
|
| 728 |
# より正確なページ寸法を取得するためのJavaScriptコード
|
| 729 |
dimensions_script = """
|
|
@@ -777,21 +541,59 @@ def render_fullpage_screenshot(html_code: str, extension_percentage: float = 6.0
|
|
| 777 |
scroll_width = 1200
|
| 778 |
scroll_height = 1000
|
| 779 |
logger.warning(f"Falling back to dimensions: width={scroll_width}, height={scroll_height}")
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 780 |
|
| 781 |
-
#
|
| 782 |
adjusted_height = int(scroll_height * (1 + extension_percentage / 100.0))
|
| 783 |
# Ensure adjusted height is not excessively large or small
|
| 784 |
adjusted_height = max(adjusted_height, scroll_height, 100) # 最小高さを確保
|
| 785 |
logger.info(f"Adjusted height calculated: {adjusted_height} (extension: {extension_percentage}%)")
|
| 786 |
|
| 787 |
-
#
|
| 788 |
adjusted_width = scroll_width
|
| 789 |
logger.info(f"Resizing window to: width={adjusted_width}, height={adjusted_height}")
|
| 790 |
driver.set_window_size(adjusted_width, adjusted_height)
|
| 791 |
logger.info("Waiting for layout stabilization after resize...")
|
| 792 |
|
| 793 |
-
#
|
| 794 |
-
time.sleep(
|
| 795 |
|
| 796 |
# 外部リソースの読み込み状態を確認
|
| 797 |
try:
|
|
@@ -807,86 +609,10 @@ def render_fullpage_screenshot(html_code: str, extension_percentage: float = 6.0
|
|
| 807 |
# ドキュメントの読み込みが完了していない場合、追加で待機
|
| 808 |
if resource_state['readyState'] != 'complete':
|
| 809 |
logger.info("Document still loading, waiting additional time...")
|
| 810 |
-
time.sleep(
|
| 811 |
except Exception as e:
|
| 812 |
logger.warning(f"Error checking resource state: {e}")
|
| 813 |
|
| 814 |
-
# レイアウト崩れ修正のためのJavaScriptを実行
|
| 815 |
-
try:
|
| 816 |
-
# レイアウト安定化のための強化JavaScriptを実行
|
| 817 |
-
stabilize_script = """
|
| 818 |
-
// カードの重なりを解消するための修正
|
| 819 |
-
document.querySelectorAll('.card, .section, .info-box').forEach(card => {
|
| 820 |
-
// 位置を相対指定に強制
|
| 821 |
-
card.style.position = 'relative';
|
| 822 |
-
|
| 823 |
-
// z-indexをカード間で競合しないよう設定
|
| 824 |
-
card.style.zIndex = '1';
|
| 825 |
-
|
| 826 |
-
// マージンを強制的に設定
|
| 827 |
-
card.style.marginBottom = '2rem';
|
| 828 |
-
card.style.marginTop = '1rem';
|
| 829 |
-
|
| 830 |
-
// 浮動要素のクリア
|
| 831 |
-
let clearDiv = document.createElement('div');
|
| 832 |
-
clearDiv.style.clear = 'both';
|
| 833 |
-
clearDiv.style.height = '1px';
|
| 834 |
-
card.parentNode.insertBefore(clearDiv, card.nextSibling);
|
| 835 |
-
});
|
| 836 |
-
|
| 837 |
-
// 親要素の高さを適切に設定
|
| 838 |
-
document.querySelectorAll('.row, .container, .column').forEach(container => {
|
| 839 |
-
container.style.overflow = 'hidden';
|
| 840 |
-
container.style.height = 'auto';
|
| 841 |
-
|
| 842 |
-
// 子要素の合計高さを取得して設定
|
| 843 |
-
let totalHeight = 0;
|
| 844 |
-
Array.from(container.children).forEach(child => {
|
| 845 |
-
if (child.offsetHeight) {
|
| 846 |
-
totalHeight += child.offsetHeight +
|
| 847 |
-
parseInt(getComputedStyle(child).marginTop || 0) +
|
| 848 |
-
parseInt(getComputedStyle(child).marginBottom || 0);
|
| 849 |
-
}
|
| 850 |
-
});
|
| 851 |
-
|
| 852 |
-
if (totalHeight > 0) {
|
| 853 |
-
container.style.minHeight = (totalHeight + 50) + 'px';
|
| 854 |
-
}
|
| 855 |
-
});
|
| 856 |
-
|
| 857 |
-
// テキスト量に基づいてフォントサイズを調整
|
| 858 |
-
document.querySelectorAll('.card, .section, .info-box').forEach(card => {
|
| 859 |
-
const cardContent = card.querySelector('.card-content') || card;
|
| 860 |
-
const textLength = cardContent.textContent.length;
|
| 861 |
-
|
| 862 |
-
// テキスト量に応じてフォントサイズを調整
|
| 863 |
-
if (textLength > 200) {
|
| 864 |
-
card.style.fontSize = '0.9em';
|
| 865 |
-
}
|
| 866 |
-
if (textLength > 300) {
|
| 867 |
-
card.style.fontSize = '0.85em';
|
| 868 |
-
}
|
| 869 |
-
|
| 870 |
-
// カード内の要素間の余白を確保
|
| 871 |
-
const elements = card.querySelectorAll('p, h3, h4, ul, ol, .info-item');
|
| 872 |
-
elements.forEach(el => {
|
| 873 |
-
el.style.marginBottom = '0.75rem';
|
| 874 |
-
el.style.lineHeight = '1.5';
|
| 875 |
-
});
|
| 876 |
-
});
|
| 877 |
-
|
| 878 |
-
// 完了通知
|
| 879 |
-
return "Layout stabilization completed";
|
| 880 |
-
"""
|
| 881 |
-
|
| 882 |
-
stabilize_result = driver.execute_script(stabilize_script)
|
| 883 |
-
logger.info(f"Layout stabilization: {stabilize_result}")
|
| 884 |
-
|
| 885 |
-
# 安定化後の追加待機
|
| 886 |
-
time.sleep(2)
|
| 887 |
-
except Exception as e:
|
| 888 |
-
logger.warning(f"Failed to execute layout fix script: {e}")
|
| 889 |
-
|
| 890 |
# Scroll to top just in case
|
| 891 |
try:
|
| 892 |
driver.execute_script("window.scrollTo(0, 0)")
|
|
@@ -895,7 +621,7 @@ def render_fullpage_screenshot(html_code: str, extension_percentage: float = 6.0
|
|
| 895 |
except Exception as e:
|
| 896 |
logger.warning(f"Could not scroll to top: {e}")
|
| 897 |
|
| 898 |
-
#
|
| 899 |
logger.info("Taking screenshot...")
|
| 900 |
png = driver.get_screenshot_as_png()
|
| 901 |
logger.info("Screenshot taken successfully.")
|
|
@@ -933,12 +659,11 @@ def render_fullpage_screenshot(html_code: str, extension_percentage: float = 6.0
|
|
| 933 |
logger.error(f"Error removing temporary file {tmp_path}: {e}")
|
| 934 |
|
| 935 |
# --- Geminiを使った新しい関数 ---
|
| 936 |
-
def text_to_screenshot(text: str, extension_percentage: float, temperature: float = 1.0,
|
| 937 |
-
trim_whitespace: bool = True, layout_type: str = "standard") -> Image.Image:
|
| 938 |
"""テキストをGemini APIでHTMLに変換し、スクリーンショットを生成する統合関数"""
|
| 939 |
try:
|
| 940 |
-
# 1. テキストからHTML
|
| 941 |
-
html_code = generate_html_from_text(text, temperature
|
| 942 |
|
| 943 |
# 2. HTMLからスクリーンショットを生成
|
| 944 |
return render_fullpage_screenshot(html_code, extension_percentage, trim_whitespace)
|
|
@@ -1035,15 +760,14 @@ async def api_text_to_screenshot(request: GeminiRequest):
|
|
| 1035 |
テキストからHTMLインフォグラフィックを生成してスクリーンショットを返すAPIエンドポイント
|
| 1036 |
"""
|
| 1037 |
try:
|
| 1038 |
-
logger.info(f"テキスト→スクリーンショットAPIリクエスト受信。テキスト長さ: {len(request.text)}, 拡張率: {request.extension_percentage}%, 温度: {request.temperature}
|
| 1039 |
|
| 1040 |
-
# テキストからHTML
|
| 1041 |
pil_image = text_to_screenshot(
|
| 1042 |
request.text,
|
| 1043 |
request.extension_percentage,
|
| 1044 |
request.temperature,
|
| 1045 |
-
request.trim_whitespace
|
| 1046 |
-
request.layout_type
|
| 1047 |
)
|
| 1048 |
|
| 1049 |
if pil_image.size == (1, 1):
|
|
@@ -1064,14 +788,14 @@ async def api_text_to_screenshot(request: GeminiRequest):
|
|
| 1064 |
|
| 1065 |
# --- Gradio Interface Definition ---
|
| 1066 |
# 入力モードの選択用Radioコンポーネント
|
| 1067 |
-
def process_input(input_mode, input_text, extension_percentage, temperature, trim_whitespace
|
| 1068 |
"""入力モードに応じて適切な処理を行う"""
|
| 1069 |
if input_mode == "HTML入力":
|
| 1070 |
# HTMLモードの場合は既存の処理
|
| 1071 |
return render_fullpage_screenshot(input_text, extension_percentage, trim_whitespace)
|
| 1072 |
else:
|
| 1073 |
# テキスト入力モードの場合はGemini APIを使用
|
| 1074 |
-
return text_to_screenshot(input_text, extension_percentage, temperature, trim_whitespace
|
| 1075 |
|
| 1076 |
# Gradio UIの定義
|
| 1077 |
with gr.Blocks(title="Full Page Screenshot (テキスト変換対応)", theme=gr.themes.Base()) as iface:
|
|
@@ -1093,84 +817,61 @@ with gr.Blocks(title="Full Page Screenshot (テキスト変換対応)", theme=gr
|
|
| 1093 |
)
|
| 1094 |
|
| 1095 |
with gr.Row():
|
| 1096 |
-
|
| 1097 |
-
|
| 1098 |
-
|
| 1099 |
-
|
| 1100 |
-
|
| 1101 |
-
|
| 1102 |
-
|
| 1103 |
-
)
|
| 1104 |
-
|
| 1105 |
-
# 温度調整スライダー(テキストモード時のみ表示)
|
| 1106 |
-
temperature = gr.Slider(
|
| 1107 |
-
minimum=0.0,
|
| 1108 |
-
maximum=1.4,
|
| 1109 |
-
step=0.1,
|
| 1110 |
-
value=1.0, # デフォルト値1.0
|
| 1111 |
-
label="生成時の温度(創造性)",
|
| 1112 |
-
visible=False # 最初は非表示
|
| 1113 |
-
)
|
| 1114 |
-
|
| 1115 |
-
# 余白トリミングオプション
|
| 1116 |
-
trim_whitespace = gr.Checkbox(
|
| 1117 |
-
label="余白を自動トリミング",
|
| 1118 |
-
value=True,
|
| 1119 |
-
info="生成される画像から余分な空白領域を自動的に削除します"
|
| 1120 |
-
)
|
| 1121 |
|
| 1122 |
-
|
| 1123 |
-
|
| 1124 |
-
|
| 1125 |
-
|
| 1126 |
-
|
| 1127 |
-
|
| 1128 |
-
|
| 1129 |
-
|
| 1130 |
-
|
| 1131 |
|
| 1132 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1133 |
output_image = gr.Image(type="pil", label="ページ全体のスクリーンショット")
|
| 1134 |
|
| 1135 |
-
#
|
| 1136 |
-
def
|
| 1137 |
-
|
| 1138 |
-
|
| 1139 |
-
{"visible": mode == "テキスト入力", "__type__": "update"} # layout_type
|
| 1140 |
-
]
|
| 1141 |
|
| 1142 |
input_mode.change(
|
| 1143 |
-
fn=
|
| 1144 |
inputs=input_mode,
|
| 1145 |
-
outputs=
|
| 1146 |
)
|
| 1147 |
|
| 1148 |
# 生成ボタンクリック時のイベント処理
|
| 1149 |
submit_btn.click(
|
| 1150 |
fn=process_input,
|
| 1151 |
-
inputs=[input_mode, input_text, extension_percentage, temperature, trim_whitespace
|
| 1152 |
outputs=output_image
|
| 1153 |
)
|
| 1154 |
|
| 1155 |
-
#
|
| 1156 |
gemini_model = os.environ.get("GEMINI_MODEL", "gemini-1.5-pro")
|
| 1157 |
gr.Markdown(f"""
|
| 1158 |
-
## 更新情報
|
| 1159 |
-
- テキスト重なり自動修正機能を強化
|
| 1160 |
-
- レイアウトタイプ選択機能を追加(テキストモード時)
|
| 1161 |
-
- フォントサイズ自動調整機能を追加
|
| 1162 |
-
- レンダリング待機時間の最適化
|
| 1163 |
-
|
| 1164 |
## APIエンドポイント
|
| 1165 |
- `/api/screenshot` - HTMLコードからスクリーンショットを生成
|
| 1166 |
- `/api/text-to-screenshot` - テキストからインフォグラフィックスクリーンショットを生成
|
| 1167 |
|
| 1168 |
## 設定情報
|
| 1169 |
- 使用モデル: {gemini_model} (環境変数 GEMINI_MODEL で変更可能)
|
| 1170 |
-
- レイアウトタイプ:
|
| 1171 |
-
- standard: 標準レイアウト
|
| 1172 |
-
- spaced: 広々レイアウト(テキストが重なりやすい場合に推奨)
|
| 1173 |
-
- compact: コンパクトレイアウト(テキストが少ない場合に推奨)
|
| 1174 |
""")
|
| 1175 |
|
| 1176 |
# --- Mount Gradio App onto FastAPI ---
|
|
|
|
| 15 |
import time
|
| 16 |
import os
|
| 17 |
import logging
|
|
|
|
| 18 |
|
| 19 |
# 正しいGemini関連のインポート
|
| 20 |
import google.generativeai as genai
|
|
|
|
| 30 |
extension_percentage: float = 6.0 # デフォルト値6%
|
| 31 |
temperature: float = 1.0 # デフォルト値1.0の温度パラメータ
|
| 32 |
trim_whitespace: bool = True # 余白トリミングオプション(デフォルト有効)
|
|
|
|
| 33 |
|
| 34 |
class ScreenshotRequest(BaseModel):
|
| 35 |
"""スクリーンショットリクエストモデル"""
|
|
|
|
| 37 |
extension_percentage: float = 6.0 # デフォルト値6%
|
| 38 |
trim_whitespace: bool = True # 余白トリミングオプション(デフォルト有効)
|
| 39 |
|
| 40 |
+
# HTMLのFont Awesomeレイアウトを改善する関数
|
| 41 |
+
def enhance_font_awesome_layout(html_code):
|
| 42 |
+
"""Font Awesomeレイアウトを改善するCSSを追加"""
|
| 43 |
+
# CSSを追加
|
| 44 |
+
fa_fix_css = """
|
| 45 |
+
<style>
|
| 46 |
+
/* Font Awesomeアイコンのレイアウト修正 */
|
| 47 |
+
[class*="fa-"] {
|
| 48 |
+
display: inline-block !important;
|
| 49 |
+
margin-right: 8px !important;
|
| 50 |
+
vertical-align: middle !important;
|
| 51 |
+
}
|
| 52 |
+
|
| 53 |
+
/* テキスト内のアイコン位置調整 */
|
| 54 |
+
h1 [class*="fa-"], h2 [class*="fa-"], h3 [class*="fa-"],
|
| 55 |
+
h4 [class*="fa-"], h5 [class*="fa-"], h6 [class*="fa-"] {
|
| 56 |
+
vertical-align: middle !important;
|
| 57 |
+
margin-right: 10px !important;
|
| 58 |
+
}
|
| 59 |
+
|
| 60 |
+
/* 特定パターンの修正 */
|
| 61 |
+
.fa + span, .fas + span, .far + span, .fab + span,
|
| 62 |
+
span + .fa, span + .fas, span + .far, span + .fab {
|
| 63 |
+
display: inline-block !important;
|
| 64 |
+
margin-left: 5px !important;
|
| 65 |
+
}
|
| 66 |
+
|
| 67 |
+
/* カード内アイコン修正 */
|
| 68 |
+
.card [class*="fa-"], .card-body [class*="fa-"] {
|
| 69 |
+
float: none !important;
|
| 70 |
+
clear: none !important;
|
| 71 |
+
position: relative !important;
|
| 72 |
+
}
|
| 73 |
+
|
| 74 |
+
/* アイコンと文字が重なる場合の調整 */
|
| 75 |
+
li [class*="fa-"], p [class*="fa-"] {
|
| 76 |
+
margin-right: 10px !important;
|
| 77 |
+
}
|
| 78 |
+
|
| 79 |
+
/* インラインアイコンのスペーシング */
|
| 80 |
+
.inline-icon {
|
| 81 |
+
display: inline-flex !important;
|
| 82 |
+
align-items: center !important;
|
| 83 |
+
justify-content: flex-start !important;
|
| 84 |
+
}
|
| 85 |
+
|
| 86 |
+
/* アイコン後のテキスト */
|
| 87 |
+
[class*="fa-"] + span {
|
| 88 |
+
display: inline-block !important;
|
| 89 |
+
vertical-align: middle !important;
|
| 90 |
+
}
|
| 91 |
+
</style>
|
| 92 |
+
"""
|
| 93 |
+
|
| 94 |
+
# headタグがある場合はその中に追加
|
| 95 |
+
if '<head>' in html_code:
|
| 96 |
+
return html_code.replace('</head>', f'{fa_fix_css}</head>')
|
| 97 |
+
# HTMLタグがある場合はその後に追加
|
| 98 |
+
elif '<html' in html_code:
|
| 99 |
+
head_end = html_code.find('</head>')
|
| 100 |
+
if head_end > 0:
|
| 101 |
+
return html_code[:head_end] + fa_fix_css + html_code[head_end:]
|
| 102 |
+
else:
|
| 103 |
+
body_start = html_code.find('<body')
|
| 104 |
+
if body_start > 0:
|
| 105 |
+
return html_code[:body_start] + f'<head>{fa_fix_css}</head>' + html_code[body_start:]
|
| 106 |
+
|
| 107 |
+
# どちらもない場合は先頭に追加
|
| 108 |
+
return f'<html><head>{fa_fix_css}</head>' + html_code + '</html>'
|
| 109 |
+
|
| 110 |
+
def generate_html_from_text(text, temperature=1.0):
|
| 111 |
"""テキストからHTMLを生成する"""
|
| 112 |
try:
|
| 113 |
# APIキーの取得と設定
|
|
|
|
| 123 |
# Gemini APIの設定
|
| 124 |
genai.configure(api_key=api_key)
|
| 125 |
|
| 126 |
+
# システムプロンプト(リクエスト例と同じものを使用)
|
| 127 |
+
system_instruction = """# グラフィックレコーディング風インフォグラフィック変換プロンプト V2
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 128 |
## 目的
|
| 129 |
以下の内容を、超一流デザイナーが作成したような、日本語で完璧なグラフィックレコーディング風のHTMLインフォグラフィックに変換してください。情報設計とビジュアルデザインの両面で最高水準を目指します。
|
| 130 |
手書き風の図形やFont Awesomeアイコンを大きく活用して内容を視覚的かつ直感的に表現します。
|
|
|
|
| 171 |
- フォント指定:
|
| 172 |
```html
|
| 173 |
<style>
|
| 174 |
+
@ import url('https ://fonts.googleapis.com/css2?family=Kaisei+Decol&family=Yomogi&family=Zen+Kurenaido&display=swap');
|
| 175 |
+
@ import url('https ://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.4.0/css/all.min.css');
|
| 176 |
</style>
|
| 177 |
```
|
| 178 |
### 5. レイアウト
|
|
|
|
| 184 |
- 横幅は100%
|
| 185 |
- 重要な要素は中央寄り、補足情報は周辺部に配置
|
| 186 |
|
| 187 |
+
### 重要なレイアウト注意事項
|
| 188 |
+
- Font Awesomeアイコンと文字が重ならないよう適切なマージンを設定する
|
| 189 |
+
- アイコンには必ず`margin-right: 10px;`や`margin-left: 10px;`などの余白を設定する
|
| 190 |
+
- アイコンと文字列は必ず`display: inline-block;`または`display: inline-flex;`で配置し、`align-items: center;`を使用する
|
| 191 |
+
- 複数のアイコンを配置する場合は十分な余白を確保する
|
| 192 |
+
- レイアウト崩れを防ぐために、親要素には`overflow: hidden;`を適用する
|
| 193 |
+
- アイコンの配置はコンテンツフローを妨げないよう注意する
|
| 194 |
+
- カード内でのアイコン配置は、絶対位置指定ではなく相対位置で設定する
|
| 195 |
+
- モバイル表示も考慮し、レスポンシブ対応を徹底する
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 196 |
|
| 197 |
## グラフィックレコーディング表現技法
|
| 198 |
- テキストと視覚要素のバランスを重視(文字情報の50%以上をFont Awesomeアイコンで視覚的に補完)
|
|
|
|
| 233 |
ーーー<ユーザーが入力(または添付)>ーーー"""
|
| 234 |
|
| 235 |
# モデルを初期化して処理
|
| 236 |
+
logger.info(f"Gemini APIにリクエストを送信: テキスト長さ = {len(text)}, 温度 = {temperature}")
|
| 237 |
|
| 238 |
# モデル初期化とフォールバック処理
|
| 239 |
try:
|
|
|
|
| 273 |
html_code = raw_response[html_start:html_end].strip()
|
| 274 |
logger.info(f"HTMLの生成に成功: 長さ = {len(html_code)}")
|
| 275 |
|
| 276 |
+
# Font Awesomeのレイアウト改善
|
| 277 |
+
html_code = enhance_font_awesome_layout(html_code)
|
| 278 |
+
logger.info("Font Awesomeレイアウトの最適化を適用しました")
|
| 279 |
|
| 280 |
return html_code
|
| 281 |
else:
|
|
|
|
| 287 |
logger.error(f"HTML生成中にエラーが発生: {e}", exc_info=True)
|
| 288 |
raise Exception(f"Gemini APIでのHTML生成に失敗しました: {e}")
|
| 289 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 290 |
# 画像から余分な空白領域をトリミングする関数
|
| 291 |
def trim_image_whitespace(image, threshold=250, padding=10):
|
| 292 |
"""
|
|
|
|
| 377 |
# Font Awesomeが読み込まれない場合があるため、読み込み待機時間を長く設定
|
| 378 |
options.add_argument("--disable-features=NetworkService")
|
| 379 |
options.add_argument("--dns-prefetch-disable")
|
|
|
|
|
|
|
|
|
|
|
|
|
| 380 |
|
| 381 |
try:
|
| 382 |
logger.info("Initializing WebDriver...")
|
|
|
|
| 398 |
)
|
| 399 |
logger.info("Body element found. Waiting for potential resource loading...")
|
| 400 |
|
| 401 |
+
# リソース読み込みの待機時間
|
| 402 |
+
time.sleep(3) # 初期待機
|
| 403 |
|
| 404 |
+
# 5) Font Awesomeと外部リソースの読み込み完了を確認
|
| 405 |
+
try:
|
| 406 |
+
# Font Awesomeと外部リソースの読み込み完了を確認するスクリプト
|
| 407 |
+
resource_check_script = """
|
| 408 |
+
return new Promise((resolve) => {
|
| 409 |
+
// Font Awesomeの読み込み確認
|
| 410 |
+
const checkFontAwesome = () => {
|
| 411 |
+
const icons = document.querySelectorAll('.fa, .fas, .far, .fab, [class*="fa-"]');
|
| 412 |
+
if (icons.length > 0) {
|
| 413 |
+
console.log('Font Awesome icons found:', icons.length);
|
| 414 |
+
// すべてのフォントの読み込み完了を待つ
|
| 415 |
+
document.fonts.ready.then(() => {
|
| 416 |
+
console.log('All fonts loaded');
|
| 417 |
+
setTimeout(resolve, 1000); // 安定化のための追加待機
|
| 418 |
+
});
|
| 419 |
+
} else {
|
| 420 |
+
// アイコンがない、またはすでに読み込み完了
|
| 421 |
+
document.fonts.ready.then(() => setTimeout(resolve, 500));
|
| 422 |
+
}
|
| 423 |
+
};
|
| 424 |
+
|
| 425 |
+
// DOMContentLoadedまたはloadイベント後にチェック
|
| 426 |
+
if (document.readyState === 'complete') {
|
| 427 |
+
checkFontAwesome();
|
| 428 |
+
} else {
|
| 429 |
+
window.addEventListener('load', checkFontAwesome);
|
| 430 |
+
}
|
| 431 |
+
});
|
| 432 |
+
"""
|
| 433 |
+
|
| 434 |
+
logger.info("Waiting for Font Awesome and other resources to load...")
|
| 435 |
+
driver.set_script_timeout(15) # 15秒のタイムアウト
|
| 436 |
+
driver.execute_async_script(f"const callback = arguments[arguments.length - 1]; {resource_check_script}.then(callback);")
|
| 437 |
+
logger.info("Resources loaded successfully")
|
| 438 |
+
except Exception as e:
|
| 439 |
+
logger.warning(f"Resource loading check failed: {e}. Using fallback wait.")
|
| 440 |
+
time.sleep(8) # より長い待機時間を設定
|
| 441 |
+
|
| 442 |
+
# 6) スクロールを制御してコンテンツ全体が描画されるようにする
|
| 443 |
+
try:
|
| 444 |
+
scroll_script = """
|
| 445 |
+
return new Promise(resolve => {
|
| 446 |
+
const height = Math.max(
|
| 447 |
+
document.documentElement.scrollHeight,
|
| 448 |
+
document.body.scrollHeight
|
| 449 |
+
);
|
| 450 |
+
const viewportHeight = window.innerHeight;
|
| 451 |
+
|
| 452 |
+
// ページを少しずつスクロールして全体を描画させる
|
| 453 |
+
const scrollStep = Math.floor(viewportHeight * 0.8);
|
| 454 |
+
let currentPos = 0;
|
| 455 |
+
|
| 456 |
+
const scrollDown = () => {
|
| 457 |
+
if (currentPos < height) {
|
| 458 |
+
window.scrollTo(0, currentPos);
|
| 459 |
+
currentPos += scrollStep;
|
| 460 |
+
setTimeout(scrollDown, 100);
|
| 461 |
+
} else {
|
| 462 |
+
// 最後にトップに戻す
|
| 463 |
+
window.scrollTo(0, 0);
|
| 464 |
+
setTimeout(resolve, 300);
|
| 465 |
+
}
|
| 466 |
+
};
|
| 467 |
+
|
| 468 |
+
scrollDown();
|
| 469 |
+
});
|
| 470 |
+
"""
|
| 471 |
+
|
| 472 |
+
logger.info("Ensuring all content is rendered...")
|
| 473 |
+
driver.execute_async_script(f"const callback = arguments[arguments.length - 1]; {scroll_script}.then(callback);")
|
| 474 |
+
except Exception as e:
|
| 475 |
+
logger.warning(f"Content rendering check failed: {e}")
|
| 476 |
+
# スクロールを元の位置に戻す
|
| 477 |
+
driver.execute_script("window.scrollTo(0, 0);")
|
| 478 |
+
time.sleep(1)
|
| 479 |
+
|
| 480 |
+
# 7) Hide scrollbars via CSS
|
| 481 |
try:
|
| 482 |
driver.execute_script(
|
| 483 |
"document.documentElement.style.overflow = 'hidden';"
|
|
|
|
| 487 |
except Exception as e:
|
| 488 |
logger.warning(f"Could not hide scrollbars via JS: {e}")
|
| 489 |
|
| 490 |
+
# 8) Get full page dimensions accurately with improved script
|
| 491 |
try:
|
| 492 |
# より正確なページ寸法を取得するためのJavaScriptコード
|
| 493 |
dimensions_script = """
|
|
|
|
| 541 |
scroll_width = 1200
|
| 542 |
scroll_height = 1000
|
| 543 |
logger.warning(f"Falling back to dimensions: width={scroll_width}, height={scroll_height}")
|
| 544 |
+
|
| 545 |
+
# 9) レイアウト安定化の確認
|
| 546 |
+
try:
|
| 547 |
+
stability_script = """
|
| 548 |
+
return new Promise(resolve => {
|
| 549 |
+
let lastHeight = document.body.offsetHeight;
|
| 550 |
+
let lastWidth = document.body.offsetWidth;
|
| 551 |
+
let stableCount = 0;
|
| 552 |
+
|
| 553 |
+
const checkStability = () => {
|
| 554 |
+
const currentHeight = document.body.offsetHeight;
|
| 555 |
+
const currentWidth = document.body.offsetWidth;
|
| 556 |
+
|
| 557 |
+
if (currentHeight === lastHeight && currentWidth === lastWidth) {
|
| 558 |
+
stableCount++;
|
| 559 |
+
if (stableCount >= 3) { // 3回連続で同じなら安定と判断
|
| 560 |
+
resolve(true);
|
| 561 |
+
return;
|
| 562 |
+
}
|
| 563 |
+
} else {
|
| 564 |
+
stableCount = 0;
|
| 565 |
+
lastHeight = currentHeight;
|
| 566 |
+
lastWidth = currentWidth;
|
| 567 |
+
}
|
| 568 |
+
|
| 569 |
+
setTimeout(checkStability, 200); // 200ms間隔でチェック
|
| 570 |
+
};
|
| 571 |
+
|
| 572 |
+
checkStability();
|
| 573 |
+
});
|
| 574 |
+
"""
|
| 575 |
+
|
| 576 |
+
logger.info("Checking layout stability...")
|
| 577 |
+
driver.execute_async_script(f"const callback = arguments[arguments.length - 1]; {stability_script}.then(callback);")
|
| 578 |
+
logger.info("Layout is stable")
|
| 579 |
+
except Exception as e:
|
| 580 |
+
logger.warning(f"Layout stability check failed: {e}")
|
| 581 |
+
time.sleep(2) # 追加待機
|
| 582 |
|
| 583 |
+
# 10) Calculate adjusted height with user-specified margin
|
| 584 |
adjusted_height = int(scroll_height * (1 + extension_percentage / 100.0))
|
| 585 |
# Ensure adjusted height is not excessively large or small
|
| 586 |
adjusted_height = max(adjusted_height, scroll_height, 100) # 最小高さを確保
|
| 587 |
logger.info(f"Adjusted height calculated: {adjusted_height} (extension: {extension_percentage}%)")
|
| 588 |
|
| 589 |
+
# 11) Set window size to full page dimensions
|
| 590 |
adjusted_width = scroll_width
|
| 591 |
logger.info(f"Resizing window to: width={adjusted_width}, height={adjusted_height}")
|
| 592 |
driver.set_window_size(adjusted_width, adjusted_height)
|
| 593 |
logger.info("Waiting for layout stabilization after resize...")
|
| 594 |
|
| 595 |
+
# レイアウト安定化のための待機
|
| 596 |
+
time.sleep(4) # 統一した待機時間
|
| 597 |
|
| 598 |
# 外部リソースの読み込み状態を確認
|
| 599 |
try:
|
|
|
|
| 609 |
# ドキュメントの読み込みが完了していない場合、追加で待機
|
| 610 |
if resource_state['readyState'] != 'complete':
|
| 611 |
logger.info("Document still loading, waiting additional time...")
|
| 612 |
+
time.sleep(2)
|
| 613 |
except Exception as e:
|
| 614 |
logger.warning(f"Error checking resource state: {e}")
|
| 615 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 616 |
# Scroll to top just in case
|
| 617 |
try:
|
| 618 |
driver.execute_script("window.scrollTo(0, 0)")
|
|
|
|
| 621 |
except Exception as e:
|
| 622 |
logger.warning(f"Could not scroll to top: {e}")
|
| 623 |
|
| 624 |
+
# 12) Take screenshot
|
| 625 |
logger.info("Taking screenshot...")
|
| 626 |
png = driver.get_screenshot_as_png()
|
| 627 |
logger.info("Screenshot taken successfully.")
|
|
|
|
| 659 |
logger.error(f"Error removing temporary file {tmp_path}: {e}")
|
| 660 |
|
| 661 |
# --- Geminiを使った新しい関数 ---
|
| 662 |
+
def text_to_screenshot(text: str, extension_percentage: float, temperature: float = 1.0, trim_whitespace: bool = True) -> Image.Image:
|
|
|
|
| 663 |
"""テキストをGemini APIでHTMLに変換し、スクリーンショットを生成する統合関数"""
|
| 664 |
try:
|
| 665 |
+
# 1. テキストからHTMLを生成(温度パラメータも渡す)
|
| 666 |
+
html_code = generate_html_from_text(text, temperature)
|
| 667 |
|
| 668 |
# 2. HTMLからスクリーンショットを生成
|
| 669 |
return render_fullpage_screenshot(html_code, extension_percentage, trim_whitespace)
|
|
|
|
| 760 |
テキストからHTMLインフォグラフィックを生成してスクリーンショットを返すAPIエンドポイント
|
| 761 |
"""
|
| 762 |
try:
|
| 763 |
+
logger.info(f"テキスト→スクリーンショットAPIリクエスト受信。テキスト長さ: {len(request.text)}, 拡張率: {request.extension_percentage}%, 温度: {request.temperature}")
|
| 764 |
|
| 765 |
+
# テキストからHTMLを生成してスクリーンショットを作成(温度パラメータも渡す)
|
| 766 |
pil_image = text_to_screenshot(
|
| 767 |
request.text,
|
| 768 |
request.extension_percentage,
|
| 769 |
request.temperature,
|
| 770 |
+
request.trim_whitespace
|
|
|
|
| 771 |
)
|
| 772 |
|
| 773 |
if pil_image.size == (1, 1):
|
|
|
|
| 788 |
|
| 789 |
# --- Gradio Interface Definition ---
|
| 790 |
# 入力モードの選択用Radioコンポーネント
|
| 791 |
+
def process_input(input_mode, input_text, extension_percentage, temperature, trim_whitespace):
|
| 792 |
"""入力モードに応じて適切な処理を行う"""
|
| 793 |
if input_mode == "HTML入力":
|
| 794 |
# HTMLモードの場合は既存の処理
|
| 795 |
return render_fullpage_screenshot(input_text, extension_percentage, trim_whitespace)
|
| 796 |
else:
|
| 797 |
# テキスト入力モードの場合はGemini APIを使用
|
| 798 |
+
return text_to_screenshot(input_text, extension_percentage, temperature, trim_whitespace)
|
| 799 |
|
| 800 |
# Gradio UIの定義
|
| 801 |
with gr.Blocks(title="Full Page Screenshot (テキスト変換対応)", theme=gr.themes.Base()) as iface:
|
|
|
|
| 817 |
)
|
| 818 |
|
| 819 |
with gr.Row():
|
| 820 |
+
extension_percentage = gr.Slider(
|
| 821 |
+
minimum=0,
|
| 822 |
+
maximum=30,
|
| 823 |
+
step=1.0,
|
| 824 |
+
value=6, # デフォルト値6%
|
| 825 |
+
label="上下高さ拡張率(%)"
|
| 826 |
+
)
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 827 |
|
| 828 |
+
# 温度調整スライダー(テキストモード時のみ表示)
|
| 829 |
+
temperature = gr.Slider(
|
| 830 |
+
minimum=0.0,
|
| 831 |
+
maximum=1.4,
|
| 832 |
+
step=0.1,
|
| 833 |
+
value=1.0, # デフォルト値1.0
|
| 834 |
+
label="生成時の温度(創造性)",
|
| 835 |
+
visible=False # 最初は非表示
|
| 836 |
+
)
|
| 837 |
|
| 838 |
+
# 余白トリミングオプション
|
| 839 |
+
trim_whitespace = gr.Checkbox(
|
| 840 |
+
label="余白を自動トリミング",
|
| 841 |
+
value=True,
|
| 842 |
+
info="生成される画像から余分な空白領域を自動的に削除します"
|
| 843 |
+
)
|
| 844 |
+
|
| 845 |
+
submit_btn = gr.Button("生成")
|
| 846 |
output_image = gr.Image(type="pil", label="ページ全体のスクリーンショット")
|
| 847 |
|
| 848 |
+
# 入力モード変更時のイベント処理(テキストモード時のみ温度スライダーを表示)
|
| 849 |
+
def update_temperature_visibility(mode):
|
| 850 |
+
# Gradio 4.x用のアップデート方法
|
| 851 |
+
return {"visible": mode == "テキスト入力", "__type__": "update"}
|
|
|
|
|
|
|
| 852 |
|
| 853 |
input_mode.change(
|
| 854 |
+
fn=update_temperature_visibility,
|
| 855 |
inputs=input_mode,
|
| 856 |
+
outputs=temperature
|
| 857 |
)
|
| 858 |
|
| 859 |
# 生成ボタンクリック時のイベント処理
|
| 860 |
submit_btn.click(
|
| 861 |
fn=process_input,
|
| 862 |
+
inputs=[input_mode, input_text, extension_percentage, temperature, trim_whitespace],
|
| 863 |
outputs=output_image
|
| 864 |
)
|
| 865 |
|
| 866 |
+
# 環境変数情報を表示
|
| 867 |
gemini_model = os.environ.get("GEMINI_MODEL", "gemini-1.5-pro")
|
| 868 |
gr.Markdown(f"""
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 869 |
## APIエンドポイント
|
| 870 |
- `/api/screenshot` - HTMLコードからスクリーンショットを生成
|
| 871 |
- `/api/text-to-screenshot` - テキストからインフォグラフィックスクリーンショットを生成
|
| 872 |
|
| 873 |
## 設定情報
|
| 874 |
- 使用モデル: {gemini_model} (環境変数 GEMINI_MODEL で変更可能)
|
|
|
|
|
|
|
|
|
|
|
|
|
| 875 |
""")
|
| 876 |
|
| 877 |
# --- Mount Gradio App onto FastAPI ---
|