Spaces:
Paused
Paused
Update app.py
Browse files
app.py
CHANGED
|
@@ -1,4 +1,3 @@
|
|
| 1 |
-
# -*- coding: utf-8 -*-
|
| 2 |
import gradio as gr
|
| 3 |
from fastapi import FastAPI, HTTPException, Body
|
| 4 |
from fastapi.responses import StreamingResponse
|
|
@@ -10,45 +9,92 @@ 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 |
-
from selenium.common.exceptions import TimeoutException, JavascriptException
|
| 14 |
from PIL import Image
|
| 15 |
from io import BytesIO
|
| 16 |
import tempfile
|
| 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 =
|
| 29 |
-
temperature: float = 0.3
|
| 30 |
-
trim_whitespace: bool = True
|
| 31 |
|
| 32 |
class ScreenshotRequest(BaseModel):
|
|
|
|
| 33 |
html_code: str
|
| 34 |
-
extension_percentage: float =
|
| 35 |
-
trim_whitespace: bool = True
|
| 36 |
|
| 37 |
-
#
|
| 38 |
def enhance_font_awesome_layout(html_code):
|
|
|
|
|
|
|
| 39 |
fa_fix_css = """
|
| 40 |
<style>
|
| 41 |
-
|
| 42 |
-
|
| 43 |
-
|
| 44 |
-
|
| 45 |
-
|
| 46 |
-
|
| 47 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 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,366 +103,539 @@ def enhance_font_awesome_layout(html_code):
|
|
| 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 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 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 |
-
|
| 80 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 81 |
prompt = f"{system_instruction}\n\n{text}"
|
| 82 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 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()
|
| 89 |
logger.info(f"HTMLの生成に成功: 長さ = {len(html_code)}")
|
|
|
|
|
|
|
| 90 |
html_code = enhance_font_awesome_layout(html_code)
|
| 91 |
logger.info("Font Awesomeレイアウトの最適化を適用しました")
|
|
|
|
| 92 |
return html_code
|
| 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
|
|
|
|
|
|
|
| 105 |
min_x, min_y = width, height
|
| 106 |
max_x = max_y = 0
|
|
|
|
|
|
|
| 107 |
pixels = list(data)
|
| 108 |
pixels = [pixels[i * width:(i + 1) * width] for i in range(height)]
|
|
|
|
|
|
|
| 109 |
for y in range(height):
|
| 110 |
for x in range(width):
|
| 111 |
-
if pixels[y][x] < threshold:
|
| 112 |
min_x = min(min_x, x)
|
| 113 |
min_y = min(min_y, y)
|
| 114 |
max_x = max(max_x, x)
|
| 115 |
max_y = max(max_y, y)
|
|
|
|
|
|
|
| 116 |
if min_x > max_x or min_y > max_y:
|
| 117 |
logger.warning("トリミング領域が見つかりません。元の画像を返します。")
|
| 118 |
return image
|
|
|
|
|
|
|
| 119 |
min_x = max(0, min_x - padding)
|
| 120 |
min_y = max(0, min_y - padding)
|
| 121 |
max_x = min(width - 1, max_x + padding)
|
| 122 |
max_y = min(height - 1, max_y + padding)
|
|
|
|
|
|
|
| 123 |
trimmed = image.crop((min_x, min_y, max_x + 1, max_y + 1))
|
|
|
|
| 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 |
-
|
| 131 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 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 |
-
|
| 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)
|
| 153 |
-
initial_width = 1200
|
| 154 |
initial_height = 1000
|
| 155 |
driver.set_window_size(initial_width, initial_height)
|
| 156 |
file_url = "file://" + tmp_path
|
| 157 |
logger.info(f"Navigating to {file_url}")
|
| 158 |
driver.get(file_url)
|
| 159 |
|
| 160 |
-
# 4) Wait for
|
| 161 |
logger.info("Waiting for body element...")
|
| 162 |
-
WebDriverWait(driver, 15).until(
|
|
|
|
|
|
|
| 163 |
logger.info("Body element found. Waiting for potential resource loading...")
|
| 164 |
-
|
| 165 |
-
|
| 166 |
-
#
|
|
|
|
|
|
|
| 167 |
try:
|
| 168 |
-
#
|
| 169 |
resource_check_script = """
|
| 170 |
-
|
| 171 |
-
|
| 172 |
-
|
| 173 |
-
|
| 174 |
-
|
| 175 |
-
|
| 176 |
-
|
| 177 |
-
|
| 178 |
-
|
| 179 |
-
|
| 180 |
-
}
|
| 181 |
-
};
|
| 182 |
-
if (document.readyState === 'complete') {
|
| 183 |
-
checkFontAwesome();
|
| 184 |
} else {
|
| 185 |
-
//
|
| 186 |
-
|
| 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 |
-
}
|
| 197 |
-
|
| 198 |
-
|
| 199 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 200 |
"""
|
|
|
|
| 201 |
logger.info("Waiting for Font Awesome and other resources to load...")
|
| 202 |
-
driver.set_script_timeout(
|
| 203 |
-
|
| 204 |
-
|
| 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 |
-
|
| 211 |
-
|
| 212 |
-
|
| 213 |
-
# 6)
|
| 214 |
try:
|
| 215 |
scroll_script = """
|
| 216 |
-
|
| 217 |
-
|
| 218 |
-
|
| 219 |
-
|
| 220 |
-
|
| 221 |
-
|
| 222 |
-
|
| 223 |
-
|
| 224 |
-
|
| 225 |
-
|
| 226 |
-
|
| 227 |
-
|
| 228 |
-
|
| 229 |
-
|
| 230 |
-
|
| 231 |
-
|
| 232 |
-
|
| 233 |
-
|
| 234 |
-
|
| 235 |
-
|
| 236 |
-
|
| 237 |
-
|
| 238 |
-
|
| 239 |
-
|
| 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 |
-
|
| 268 |
-
|
| 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 |
-
|
| 280 |
-
|
|
|
|
|
|
|
| 281 |
|
| 282 |
-
# 7) Hide scrollbars
|
| 283 |
try:
|
| 284 |
-
driver.execute_script(
|
|
|
|
|
|
|
|
|
|
| 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 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 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 |
-
|
| 297 |
-
|
| 298 |
-
|
| 299 |
-
|
| 300 |
-
|
| 301 |
-
|
| 302 |
-
|
| 303 |
-
|
| 304 |
-
|
| 305 |
-
|
| 306 |
-
|
| 307 |
-
|
| 308 |
-
|
| 309 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 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)
|
| 317 |
try:
|
| 318 |
stability_script = """
|
| 319 |
-
|
| 320 |
-
|
| 321 |
-
|
| 322 |
-
|
| 323 |
-
|
| 324 |
-
|
| 325 |
-
|
| 326 |
-
|
| 327 |
-
|
| 328 |
-
|
| 329 |
-
|
| 330 |
-
|
| 331 |
-
resolve(
|
| 332 |
return;
|
| 333 |
}
|
| 334 |
-
|
| 335 |
-
|
| 336 |
-
|
| 337 |
-
|
| 338 |
-
|
| 339 |
-
|
| 340 |
-
|
| 341 |
-
|
| 342 |
-
|
| 343 |
-
|
| 344 |
-
|
| 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.
|
| 378 |
-
|
| 379 |
-
stable = driver.execute_async_script(stability_script)
|
| 380 |
-
|
| 381 |
-
if stable:
|
| 382 |
-
logger.info("Layout is stable")
|
| 383 |
-
else:
|
| 384 |
-
logger.warning("Layout did not stabilize within the expected time. Proceeding anyway.")
|
| 385 |
-
time.sleep(2)
|
| 386 |
-
|
| 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.
|
| 395 |
-
time.sleep(2)
|
| 396 |
|
| 397 |
-
# 10) Calculate height
|
| 398 |
adjusted_height = int(scroll_height * (1 + extension_percentage / 100.0))
|
| 399 |
-
|
|
|
|
| 400 |
logger.info(f"Adjusted height calculated: {adjusted_height} (extension: {extension_percentage}%)")
|
| 401 |
|
| 402 |
-
# 11)
|
| 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 |
-
|
|
|
|
|
|
|
| 408 |
|
| 409 |
-
#
|
| 410 |
try:
|
| 411 |
-
resource_state = driver.execute_script("
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 412 |
logger.info(f"Resource state: {resource_state}")
|
|
|
|
|
|
|
| 413 |
if resource_state['readyState'] != 'complete':
|
| 414 |
logger.info("Document still loading, waiting additional time...")
|
| 415 |
time.sleep(2)
|
| 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)
|
|
@@ -424,20 +643,28 @@ def render_fullpage_screenshot(html_code: str, extension_percentage: float = 6.0
|
|
| 424 |
except Exception as e:
|
| 425 |
logger.warning(f"Could not scroll to top: {e}")
|
| 426 |
|
| 427 |
-
# 12) Take screenshot
|
| 428 |
logger.info("Taking screenshot...")
|
| 429 |
png = driver.get_screenshot_as_png()
|
| 430 |
logger.info("Screenshot taken successfully.")
|
|
|
|
|
|
|
| 431 |
img = Image.open(BytesIO(png))
|
|
|
|
|
|
|
| 432 |
logger.info(f"Screenshot dimensions: {img.width}x{img.height}")
|
|
|
|
|
|
|
| 433 |
if trim_whitespace:
|
|
|
|
| 434 |
img = trim_image_whitespace(img, threshold=248, padding=20)
|
| 435 |
logger.info(f"Trimmed dimensions: {img.width}x{img.height}")
|
|
|
|
| 436 |
return img
|
| 437 |
|
| 438 |
except Exception as e:
|
| 439 |
logger.error(f"An error occurred during screenshot generation: {e}", exc_info=True)
|
| 440 |
-
return Image.new('RGB', (1, 1), color=(0, 0, 0))
|
| 441 |
finally:
|
| 442 |
logger.info("Cleaning up...")
|
| 443 |
if driver:
|
|
@@ -453,98 +680,226 @@ def render_fullpage_screenshot(html_code: str, extension_percentage: float = 6.0
|
|
| 453 |
except Exception as e:
|
| 454 |
logger.error(f"Error removing temporary file {tmp_path}: {e}")
|
| 455 |
|
| 456 |
-
# ---
|
| 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)
|
|
|
|
|
|
|
| 460 |
return render_fullpage_screenshot(html_code, extension_percentage, trim_whitespace)
|
| 461 |
except Exception as e:
|
| 462 |
logger.error(f"テキストからスクリーンショット生成中にエラーが発生: {e}", exc_info=True)
|
| 463 |
-
return Image.new('RGB', (1, 1), color=(0, 0, 0))
|
| 464 |
|
| 465 |
-
# --- FastAPI Setup
|
| 466 |
app = FastAPI()
|
| 467 |
-
|
| 468 |
-
#
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 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 |
-
|
|
|
|
| 473 |
static_dir = os.path.join(gradio_dir, "templates", "frontend", "static")
|
| 474 |
-
if os.path.exists(static_dir):
|
|
|
|
|
|
|
|
|
|
|
|
|
| 475 |
app_dir = os.path.join(gradio_dir, "templates", "frontend", "_app")
|
| 476 |
-
if os.path.exists(app_dir):
|
| 477 |
-
|
| 478 |
-
|
| 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 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 484 |
async def api_render_screenshot(request: ScreenshotRequest):
|
|
|
|
|
|
|
|
|
|
| 485 |
try:
|
| 486 |
logger.info(f"API request received. Extension: {request.extension_percentage}%")
|
| 487 |
-
|
| 488 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 489 |
img_byte_arr = BytesIO()
|
| 490 |
pil_image.save(img_byte_arr, format='PNG')
|
| 491 |
-
img_byte_arr.seek(0)
|
|
|
|
| 492 |
logger.info("Returning screenshot as PNG stream.")
|
| 493 |
return StreamingResponse(img_byte_arr, media_type="image/png")
|
|
|
|
| 494 |
except Exception as e:
|
| 495 |
logger.error(f"API Error: {e}", exc_info=True)
|
| 496 |
raise HTTPException(status_code=500, detail=f"Internal Server Error: {e}")
|
| 497 |
|
| 498 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 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 |
-
|
| 503 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 504 |
img_byte_arr = BytesIO()
|
| 505 |
pil_image.save(img_byte_arr, format='PNG')
|
| 506 |
-
img_byte_arr.seek(0)
|
|
|
|
| 507 |
logger.info("スクリーンショットをPNGストリームとして返します。")
|
| 508 |
return StreamingResponse(img_byte_arr, media_type="image/png")
|
|
|
|
| 509 |
except Exception as e:
|
| 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)
|
| 517 |
else:
|
|
|
|
| 518 |
return text_to_screenshot(input_text, extension_percentage, temperature, trim_whitespace)
|
| 519 |
|
|
|
|
| 520 |
with gr.Blocks(title="Full Page Screenshot (��キスト変換対応)", theme=gr.themes.Base()) as iface:
|
| 521 |
gr.Markdown("# HTMLビューア & テキスト→インフォグラフィック変換")
|
| 522 |
gr.Markdown("HTMLコードをレンダリングするか、テキストをGemini APIでインフォグラフィックに変換して画像として取得します。")
|
|
|
|
| 523 |
with gr.Row():
|
| 524 |
-
input_mode = gr.Radio(
|
| 525 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 526 |
with gr.Row():
|
| 527 |
-
extension_percentage = gr.Slider(
|
| 528 |
-
|
| 529 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 530 |
submit_btn = gr.Button("生成")
|
| 531 |
output_image = gr.Image(type="pil", label="ページ全体のスクリーンショット")
|
|
|
|
|
|
|
| 532 |
def update_temperature_visibility(mode):
|
|
|
|
| 533 |
return {"visible": mode == "テキスト入力", "__type__": "update"}
|
| 534 |
-
|
| 535 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 536 |
gemini_model = os.environ.get("GEMINI_MODEL", "gemini-1.5-pro")
|
| 537 |
gr.Markdown(f"""
|
| 538 |
## APIエンドポイント
|
| 539 |
-
- `/api/screenshot` - HTMLコードからスクリーンショットを生成
|
| 540 |
- `/api/text-to-screenshot` - テキストからインフォグラフィックスクリーンショットを生成
|
| 541 |
-
|
| 542 |
## 設定情報
|
| 543 |
- 使用モデル: {gemini_model} (環境変数 GEMINI_MODEL で変更可能)
|
| 544 |
""")
|
| 545 |
|
| 546 |
-
# --- Mount Gradio App
|
| 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...")
|
|
|
|
|
|
|
| 1 |
import gradio as gr
|
| 2 |
from fastapi import FastAPI, HTTPException, Body
|
| 3 |
from fastapi.responses import StreamingResponse
|
|
|
|
| 9 |
from selenium.webdriver.common.by import By
|
| 10 |
from selenium.webdriver.support.ui import WebDriverWait
|
| 11 |
from selenium.webdriver.support import expected_conditions as EC
|
|
|
|
| 12 |
from PIL import Image
|
| 13 |
from io import BytesIO
|
| 14 |
import tempfile
|
| 15 |
import time
|
| 16 |
import os
|
| 17 |
import logging
|
| 18 |
+
|
| 19 |
+
# 正しいGemini関連のインポート
|
| 20 |
import google.generativeai as genai
|
| 21 |
|
| 22 |
+
# ロギング設定
|
| 23 |
logging.basicConfig(level=logging.INFO)
|
| 24 |
logger = logging.getLogger(__name__)
|
| 25 |
|
| 26 |
+
# --- Gemini統合 ---
|
| 27 |
class GeminiRequest(BaseModel):
|
| 28 |
+
"""Geminiへのリクエストデータモデル"""
|
| 29 |
text: str
|
| 30 |
+
extension_percentage: float = 8.0 # デフォルト値8%
|
| 31 |
+
temperature: float = 0.3 # デフォルト値を0.3に下げて創造性を抑制
|
| 32 |
+
trim_whitespace: bool = True # 余白トリミングオプション(デフォルト有効)
|
| 33 |
|
| 34 |
class ScreenshotRequest(BaseModel):
|
| 35 |
+
"""スクリーンショットリクエストモデル"""
|
| 36 |
html_code: str
|
| 37 |
+
extension_percentage: float = 8.0 # デフォルト値8%
|
| 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:
|
|
|
|
| 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=0.3):
|
| 111 |
+
"""テキストからHTMLを生成する"""
|
| 112 |
try:
|
| 113 |
+
# APIキーの取得と設定
|
| 114 |
api_key = os.environ.get("GEMINI_API_KEY")
|
| 115 |
if not api_key:
|
| 116 |
logger.error("GEMINI_API_KEY 環境変数が設定されていません")
|
| 117 |
raise ValueError("GEMINI_API_KEY 環境変数が設定されていません")
|
| 118 |
+
|
| 119 |
+
# モデル名の取得(環境変数から、なければデフォルト値)
|
| 120 |
model_name = os.environ.get("GEMINI_MODEL", "gemini-1.5-pro")
|
| 121 |
logger.info(f"使用するGeminiモデル: {model_name}")
|
| 122 |
+
|
| 123 |
+
# Gemini APIの設定
|
| 124 |
genai.configure(api_key=api_key)
|
| 125 |
+
|
| 126 |
+
# システムプロンプト(リクエスト例と同じものを使用)
|
| 127 |
+
system_instruction = """# グラフィックレコーディング風インフォグラフィック変換プロンプト V2
|
| 128 |
+
## 目的
|
| 129 |
+
以下の内容を、超一流デザイナーが作成したような、日本語で完璧なグラフィックレコーディング風のHTMLインフォグラフィックに変換してください。情報設計とビジュアルデザインの両面で最高水準を目指します。
|
| 130 |
+
手書き風の図形やFont Awesomeアイコンを大きく活用して内容を視覚的かつ直感的に表現します。
|
| 131 |
+
|
| 132 |
+
## デザイン仕様
|
| 133 |
+
### 1. カラースキーム
|
| 134 |
+
```
|
| 135 |
+
<palette>
|
| 136 |
+
<color name='MysticLibrary-1' rgb='2E578C' r='46' g='87' b='140' />
|
| 137 |
+
<color name='MysticLibrary-2' rgb='182D40' r='24' g='45' b='64' />
|
| 138 |
+
<color name='MysticLibrary-3' rgb='BF807A' r='191' g='128' b='122' />
|
| 139 |
+
<color name='MysticLibrary-4' rgb='592A2A' r='89' g='42' b='42' />
|
| 140 |
+
<color name='MysticLibrary-5' rgb='F2F2F2' r='242' g='242' b='242' />
|
| 141 |
+
</palette>
|
| 142 |
+
```
|
| 143 |
+
### 2. グラフィックレコーディング要素
|
| 144 |
+
- 左上から右へ、上から下へと情報を順次配置
|
| 145 |
+
- 日本語の手書き風フォントの使用(Yomogi, Zen Kurenaido, Kaisei Decol)
|
| 146 |
+
- 手描き風の囲み線、矢印、バナー、吹き出し
|
| 147 |
+
- テキストと視覚要素(Font Awesomeアイコン、シンプルな図形)の組み合わせ
|
| 148 |
+
- Font Awesomeアイコンは各セクションの内容を表現するものを大きく(2x〜3x)表示
|
| 149 |
+
- キーワードごとに関連するFont Awesomeアイコンを隣接配置
|
| 150 |
+
- キーワードの強調(色付き下線、マーカー効果、Font Awesomeによる装飾)
|
| 151 |
+
- 関連する概念を線や矢印で接続し、接続部にもFont Awesomeアイコン(fa-arrow-right, fa-connection等)を挿入
|
| 152 |
+
- Font Awesomeアニメーション効果(fa-beat, fa-bounce, fa-fade, fa-flip, fa-shake, fa-spin)を適切に活用
|
| 153 |
+
- 重要なポイントには「fa-circle-exclamation」や「fa-lightbulb」などのアイコンを目立つ大きさで配置
|
| 154 |
+
- 数値やデータには「fa-chart-line」や「fa-percent」などの関連アイコンを添える
|
| 155 |
+
- 感情や状態を表すには表情アイコン(fa-face-smile, fa-face-frown等)を活用
|
| 156 |
+
- アイコンにホバー効果(色変化、サイズ変化)を付与
|
| 157 |
+
- 背景にはFont Awesomeの薄いパターンを配置(fa-shapes等を透過度を下げて配置)
|
| 158 |
+
### 3. アニメーション効果
|
| 159 |
+
- Font Awesomeアイコンに連動するアニメーション(fa-beat, fa-bounce, fa-fade等)
|
| 160 |
+
- 重要キーワード出現時のハイライト効果(グラデーション変化)
|
| 161 |
+
- 接続線や矢印の流れるようなアニメーション
|
| 162 |
+
- アイコンの回転・拡大縮小アニメーション(特に注目させたい箇所)
|
| 163 |
+
- 背景グラデーションの緩やかな変化
|
| 164 |
+
- スクロールに連動した要素の出現効果
|
| 165 |
+
- クリック/タップでアイコンが反応する効果
|
| 166 |
+
### 4. タイポグラフィ
|
| 167 |
+
- タイトル:32px、グラデーション効果、太字、Font Awesomeアイコンを左右に配置
|
| 168 |
+
- サブタイトル:16px、#475569、関連するFont Awesomeアイコンを添える
|
| 169 |
+
- セクション見出し:18px、# 1e40af、左側にFont Awesomeアイコンを必ず配置し、アイコンにはアニメーション効果
|
| 170 |
+
- 本文:14px、#334155、行間1.4、重要キーワードには関連する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. レイアウト
|
| 179 |
+
- ヘッダー:左揃えタイトル(大きなFont Awesomeアイコンを添える)+右揃え日付/出典
|
| 180 |
+
- 2カラム構成:左側50%, 右側50%
|
| 181 |
+
- カード型コンポーネント:白背景、角丸12px、微細シャドウ、右上にFont Awesomeアイコンを配置
|
| 182 |
+
- セクション間の適切な余白と階層構造(階層を示すFont Awesomeアイコンを活用)
|
| 183 |
+
- 適切にグラスモーフィズムを活用(背後にぼ��したFont Awesomeアイコンを配置)
|
| 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アイコンで視覚的に補完)
|
| 199 |
+
- キーワードを囲み線や色で強調し、関連するFont Awesomeアイコンを必ず添える
|
| 200 |
+
- 概念ごとに最適なFont Awesomeアイコンを選定(抽象的な概念には複数の関連アイコンを組み合わせて表現)
|
| 201 |
+
- 数値データは簡潔なグラフや図表で表現し、データ種類に応じたFont Awesomeアイコン(fa-chart-pie, fa-chart-column等)を配置
|
| 202 |
+
- 接続線や矢印で情報間の関係性を明示し、関係性の種類に応じたアイコン(fa-link, fa-code-branch等)を添える
|
| 203 |
+
- 余白を効果的に活用して視認性を確保(余白にも薄いFont Awesomeパターンを配置可)
|
| 204 |
+
- コントラストと色の使い分けでメリハリを付け、カラースキームに沿ったアイコン色を活用
|
| 205 |
+
## Font Awesomeアイコン活用ガイドライン
|
| 206 |
+
- 概念カテゴリー別の推奨アイコン:
|
| 207 |
+
- 時間・順序:fa-clock, fa-hourglass, fa-calendar, fa-timeline
|
| 208 |
+
- 場所・位置:fa-location-dot, fa-map, fa-compass, fa-globe
|
| 209 |
+
- 人物・組織:fa-user, fa-users, fa-building, fa-sitemap
|
| 210 |
+
- 行動・活動:fa-person-running, fa-gears, fa-hammer, fa-rocket
|
| 211 |
+
- 思考・アイデア:fa-brain, fa-lightbulb, fa-thought-bubble, fa-comments
|
| 212 |
+
- 感情・状態:fa-face-smile, fa-face-sad-tear, fa-heart, fa-temperature-half
|
| 213 |
+
- 成長・変化:fa-seedling, fa-arrow-trend-up, fa-chart-line, fa-diagram-project
|
| 214 |
+
- 問題・課題:fa-triangle-exclamation, fa-circle-question, fa-bug, fa-ban
|
| 215 |
+
- 解決・成功:fa-check, fa-trophy, fa-handshake, fa-key
|
| 216 |
+
- アイコンサイズの使い分け:
|
| 217 |
+
- 主要概念:3x(fa-3x)
|
| 218 |
+
- 重要キーワード:2x(fa-2x)
|
| 219 |
+
- 補足情報:1x(標準サイズ)
|
| 220 |
+
- 装飾的要素:lg(fa-lg)
|
| 221 |
+
- アニメーション効果の適切な使い分け:
|
| 222 |
+
- 注目喚起:fa-beat, fa-shake
|
| 223 |
+
- 継続的プロセス:fa-spin, fa-pulse
|
| 224 |
+
- 状態変化:fa-flip, fa-fade
|
| 225 |
+
- 新規情報:fa-bounce
|
| 226 |
+
## 全体的な指針
|
| 227 |
+
- 読み手が自然に視線を移動できる配置(Font Awesomeアイコンで視線誘導)
|
| 228 |
+
- 情報の階層と関連性を視覚的に明確化(階層ごとにアイコンのサイズや色を変える)
|
| 229 |
+
- 手書き風の要素とFont Awesomeアイコンを組み合わせて親しみやすさとプロフェッショナル感を両立
|
| 230 |
+
- 大きなFont Awesomeアイコンを活用した視覚的な記憶に残るデザイン(各セクションに象徴的なアイコンを配置)
|
| 231 |
+
- フッターに出典情報と関連するFont Awesomeアイコン(fa-book, fa-citation等)を明記
|
| 232 |
+
## 変換する文章/記事
|
| 233 |
+
ーーー<ユーザーが入力(または添付)>ーーー"""
|
| 234 |
+
|
| 235 |
+
# モデルを初期化して処理
|
| 236 |
logger.info(f"Gemini APIにリクエストを送信: テキスト長さ = {len(text)}, 温度 = {temperature}")
|
| 237 |
+
|
| 238 |
+
# モデル初期化とフォールバック処理
|
| 239 |
try:
|
| 240 |
model = genai.GenerativeModel(model_name)
|
| 241 |
except Exception as e:
|
| 242 |
+
# 指定されたモデルが使用できない場合はフォールバック
|
| 243 |
fallback_model = "gemini-pro"
|
| 244 |
logger.warning(f"{model_name}が利用できません: {e}, フォールバックモデル{fallback_model}を使用します")
|
| 245 |
model = genai.GenerativeModel(fallback_model)
|
| 246 |
+
|
| 247 |
+
# 生成設定 - ばらつきを減らすために設定を調���
|
| 248 |
+
generation_config = {
|
| 249 |
+
"temperature": temperature, # より低い温度を設定
|
| 250 |
+
"top_p": 0.7, # 0.95から0.7に下げて出力の多様性を制限
|
| 251 |
+
"top_k": 20, # 64から20に下げて候補を絞る
|
| 252 |
+
"max_output_tokens": 8192,
|
| 253 |
+
"candidate_count": 1 # 候補は1つだけ生成
|
| 254 |
+
}
|
| 255 |
+
|
| 256 |
+
# 安全設定 - デフォルトの安全設定を使用
|
| 257 |
+
safety_settings = [
|
| 258 |
+
{
|
| 259 |
+
"category": "HARM_CATEGORY_HARASSMENT",
|
| 260 |
+
"threshold": "BLOCK_MEDIUM_AND_ABOVE"
|
| 261 |
+
},
|
| 262 |
+
{
|
| 263 |
+
"category": "HARM_CATEGORY_HATE_SPEECH",
|
| 264 |
+
"threshold": "BLOCK_MEDIUM_AND_ABOVE"
|
| 265 |
+
},
|
| 266 |
+
{
|
| 267 |
+
"category": "HARM_CATEGORY_SEXUALLY_EXPLICIT",
|
| 268 |
+
"threshold": "BLOCK_MEDIUM_AND_ABOVE"
|
| 269 |
+
},
|
| 270 |
+
{
|
| 271 |
+
"category": "HARM_CATEGORY_DANGEROUS_CONTENT",
|
| 272 |
+
"threshold": "BLOCK_MEDIUM_AND_ABOVE"
|
| 273 |
+
}
|
| 274 |
+
]
|
| 275 |
+
|
| 276 |
+
# プロンプト構築
|
| 277 |
prompt = f"{system_instruction}\n\n{text}"
|
| 278 |
+
|
| 279 |
+
# コンテンツ生成
|
| 280 |
+
response = model.generate_content(
|
| 281 |
+
prompt,
|
| 282 |
+
generation_config=generation_config,
|
| 283 |
+
safety_settings=safety_settings
|
| 284 |
+
)
|
| 285 |
+
|
| 286 |
+
# レスポンスからHTMLを抽出
|
| 287 |
raw_response = response.text
|
| 288 |
+
|
| 289 |
+
# HTMLタグ部分だけを抽出(```html と ``` の間)
|
| 290 |
html_start = raw_response.find("```html")
|
| 291 |
html_end = raw_response.rfind("```")
|
| 292 |
+
|
| 293 |
if html_start != -1 and html_end != -1 and html_start < html_end:
|
| 294 |
+
html_start += 7 # "```html" の長さ分進める
|
| 295 |
html_code = raw_response[html_start:html_end].strip()
|
| 296 |
logger.info(f"HTMLの生成に成功: 長さ = {len(html_code)}")
|
| 297 |
+
|
| 298 |
+
# Font Awesomeのレイアウト改善
|
| 299 |
html_code = enhance_font_awesome_layout(html_code)
|
| 300 |
logger.info("Font Awesomeレイアウトの最適化を適用しました")
|
| 301 |
+
|
| 302 |
return html_code
|
| 303 |
else:
|
| 304 |
+
# HTMLタグが見つからない場合、レスポンス全体を返す
|
| 305 |
logger.warning("レスポンスから```html```タグが見つかりませんでした。全テキストを返します。")
|
| 306 |
return raw_response
|
| 307 |
+
|
| 308 |
except Exception as e:
|
| 309 |
logger.error(f"HTML生成中にエラーが発生: {e}", exc_info=True)
|
| 310 |
raise Exception(f"Gemini APIでのHTML生成に失敗しました: {e}")
|
| 311 |
|
| 312 |
+
# 画像から余分な空白領域をトリミングする関数
|
| 313 |
def trim_image_whitespace(image, threshold=250, padding=10):
|
| 314 |
+
"""
|
| 315 |
+
画像から余分な白い空白をトリミングする
|
| 316 |
+
|
| 317 |
+
Args:
|
| 318 |
+
image: PIL.Image - 入力画像
|
| 319 |
+
threshold: int - どの明るさ以上を空白と判断するか (0-255)
|
| 320 |
+
padding: int - トリミング後に残す余白のピクセル数
|
| 321 |
+
|
| 322 |
+
Returns:
|
| 323 |
+
トリミングされたPIL.Image
|
| 324 |
+
"""
|
| 325 |
+
# グレースケールに変換
|
| 326 |
gray = image.convert('L')
|
| 327 |
+
|
| 328 |
+
# ピクセルデータを配列として取得
|
| 329 |
data = gray.getdata()
|
| 330 |
width, height = gray.size
|
| 331 |
+
|
| 332 |
+
# 有効範囲を見つける
|
| 333 |
min_x, min_y = width, height
|
| 334 |
max_x = max_y = 0
|
| 335 |
+
|
| 336 |
+
# ピクセルデータを2次元配列に変換して処理
|
| 337 |
pixels = list(data)
|
| 338 |
pixels = [pixels[i * width:(i + 1) * width] for i in range(height)]
|
| 339 |
+
|
| 340 |
+
# 各行をスキャンして非空白ピクセルを見つける
|
| 341 |
for y in range(height):
|
| 342 |
for x in range(width):
|
| 343 |
+
if pixels[y][x] < threshold: # 非空白ピクセル
|
| 344 |
min_x = min(min_x, x)
|
| 345 |
min_y = min(min_y, y)
|
| 346 |
max_x = max(max_x, x)
|
| 347 |
max_y = max(max_y, y)
|
| 348 |
+
|
| 349 |
+
# 境界外のトリミングの場合はエラー
|
| 350 |
if min_x > max_x or min_y > max_y:
|
| 351 |
logger.warning("トリミング領域が見つかりません。元の画像を返します。")
|
| 352 |
return image
|
| 353 |
+
|
| 354 |
+
# パディングを追加
|
| 355 |
min_x = max(0, min_x - padding)
|
| 356 |
min_y = max(0, min_y - padding)
|
| 357 |
max_x = min(width - 1, max_x + padding)
|
| 358 |
max_y = min(height - 1, max_y + padding)
|
| 359 |
+
|
| 360 |
+
# 画像をトリミング
|
| 361 |
trimmed = image.crop((min_x, min_y, max_x + 1, max_y + 1))
|
| 362 |
+
|
| 363 |
logger.info(f"画像をトリミングしました: 元サイズ {width}x{height} → トリミング後 {trimmed.width}x{trimmed.height}")
|
| 364 |
return trimmed
|
| 365 |
|
| 366 |
+
# --- Core Screenshot Logic ---
|
| 367 |
+
def render_fullpage_screenshot(html_code: str, extension_percentage: float = 6.0,
|
| 368 |
trim_whitespace: bool = True) -> Image.Image:
|
| 369 |
+
"""
|
| 370 |
+
Renders HTML code to a full-page screenshot using Selenium.
|
| 371 |
+
|
| 372 |
+
Args:
|
| 373 |
+
html_code: The HTML source code string.
|
| 374 |
+
extension_percentage: Percentage of extra space to add vertically (e.g., 4 means 4% total).
|
| 375 |
+
trim_whitespace: Whether to trim excess whitespace from the image.
|
| 376 |
+
|
| 377 |
+
Returns:
|
| 378 |
+
A PIL Image object of the screenshot. Returns a 1x1 black image on error.
|
| 379 |
+
"""
|
| 380 |
+
tmp_path = None # 初期化
|
| 381 |
+
driver = None # 初期化
|
| 382 |
+
|
| 383 |
+
# 1) Save HTML code to a temporary file
|
| 384 |
try:
|
|
|
|
| 385 |
with tempfile.NamedTemporaryFile(suffix=".html", delete=False, mode='w', encoding='utf-8') as tmp_file:
|
| 386 |
tmp_path = tmp_file.name
|
| 387 |
tmp_file.write(html_code)
|
| 388 |
logger.info(f"HTML saved to temporary file: {tmp_path}")
|
| 389 |
+
except Exception as e:
|
| 390 |
+
logger.error(f"Error writing temporary HTML file: {e}")
|
| 391 |
+
return Image.new('RGB', (1, 1), color=(0, 0, 0)) # エラー時は黒画像
|
| 392 |
+
|
| 393 |
+
# 2) Headless Chrome(Chromium) options
|
| 394 |
+
options = Options()
|
| 395 |
+
options.add_argument("--headless")
|
| 396 |
+
options.add_argument("--no-sandbox")
|
| 397 |
+
options.add_argument("--disable-dev-shm-usage")
|
| 398 |
+
options.add_argument("--force-device-scale-factor=1")
|
| 399 |
+
# Font Awesomeが読み込まれない場合があるため、読み込み待機時間を長く設定
|
| 400 |
+
options.add_argument("--disable-features=NetworkService")
|
| 401 |
+
options.add_argument("--dns-prefetch-disable")
|
| 402 |
|
| 403 |
+
try:
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 404 |
logger.info("Initializing WebDriver...")
|
| 405 |
driver = webdriver.Chrome(options=options)
|
| 406 |
logger.info("WebDriver initialized.")
|
| 407 |
|
| 408 |
+
# 3) 初期ウィンドウサイズを設定(コンテンツの種類に関わらず同じサイズ)
|
| 409 |
+
initial_width = 1200
|
| 410 |
initial_height = 1000
|
| 411 |
driver.set_window_size(initial_width, initial_height)
|
| 412 |
file_url = "file://" + tmp_path
|
| 413 |
logger.info(f"Navigating to {file_url}")
|
| 414 |
driver.get(file_url)
|
| 415 |
|
| 416 |
+
# 4) Wait for page load with extended timeout
|
| 417 |
logger.info("Waiting for body element...")
|
| 418 |
+
WebDriverWait(driver, 15).until(
|
| 419 |
+
EC.presence_of_element_located((By.TAG_NAME, "body"))
|
| 420 |
+
)
|
| 421 |
logger.info("Body element found. Waiting for potential resource loading...")
|
| 422 |
+
|
| 423 |
+
# リソース読み込みの待機時間
|
| 424 |
+
time.sleep(3) # 初期待機
|
| 425 |
+
|
| 426 |
+
# 5) Font Awesomeと外部リソースの読み込み完了を確認
|
| 427 |
try:
|
| 428 |
+
# Font Awesomeと外部リソースの読み込み完了を確認するスクリプト
|
| 429 |
resource_check_script = """
|
| 430 |
+
return new Promise((resolve) => {
|
| 431 |
+
// Font Awesomeの読み込み確認
|
| 432 |
+
const checkFontAwesome = () => {
|
| 433 |
+
const icons = document.querySelectorAll('.fa, .fas, .far, .fab, [class*="fa-"]');
|
| 434 |
+
if (icons.length > 0) {
|
| 435 |
+
console.log('Font Awesome icons found:', icons.length);
|
| 436 |
+
// すべてのフォントの読み込み完了を待つ
|
| 437 |
+
document.fonts.ready.then(() => {
|
| 438 |
+
console.log('All fonts loaded');
|
| 439 |
+
setTimeout(resolve, 1000); // 安定化のための追加待機
|
| 440 |
+
});
|
|
|
|
|
|
|
|
|
|
| 441 |
} else {
|
| 442 |
+
// アイコンがない、またはすでに読み込み完了
|
| 443 |
+
document.fonts.ready.then(() => setTimeout(resolve, 500));
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 444 |
}
|
| 445 |
+
};
|
| 446 |
+
|
| 447 |
+
// DOMContentLoadedまたはloadイベント後にチェック
|
| 448 |
+
if (document.readyState === 'complete') {
|
| 449 |
+
checkFontAwesome();
|
| 450 |
+
} else {
|
| 451 |
+
window.addEventListener('load', checkFontAwesome);
|
| 452 |
+
}
|
| 453 |
+
});
|
| 454 |
"""
|
| 455 |
+
|
| 456 |
logger.info("Waiting for Font Awesome and other resources to load...")
|
| 457 |
+
driver.set_script_timeout(15) # 15秒のタイムアウト
|
| 458 |
+
driver.execute_async_script(f"const callback = arguments[arguments.length - 1]; {resource_check_script}.then(callback);")
|
| 459 |
+
logger.info("Resources loaded successfully")
|
|
|
|
|
|
|
|
|
|
|
|
|
| 460 |
except Exception as e:
|
| 461 |
+
logger.warning(f"Resource loading check failed: {e}. Using fallback wait.")
|
| 462 |
+
time.sleep(8) # より長い待機時間を設定
|
| 463 |
+
|
| 464 |
+
# 6) スクロールを制御してコンテンツ全体が描画されるようにする
|
| 465 |
try:
|
| 466 |
scroll_script = """
|
| 467 |
+
return new Promise(resolve => {
|
| 468 |
+
const height = Math.max(
|
| 469 |
+
document.documentElement.scrollHeight,
|
| 470 |
+
document.body.scrollHeight
|
| 471 |
+
);
|
| 472 |
+
const viewportHeight = window.innerHeight;
|
| 473 |
+
|
| 474 |
+
// ページを少しずつスクロールして全体を描画させる
|
| 475 |
+
const scrollStep = Math.floor(viewportHeight * 0.8);
|
| 476 |
+
let currentPos = 0;
|
| 477 |
+
|
| 478 |
+
const scrollDown = () => {
|
| 479 |
+
if (currentPos < height) {
|
| 480 |
+
window.scrollTo(0, currentPos);
|
| 481 |
+
currentPos += scrollStep;
|
| 482 |
+
setTimeout(scrollDown, 100);
|
| 483 |
+
} else {
|
| 484 |
+
// 最後にトップに戻す
|
| 485 |
+
window.scrollTo(0, 0);
|
| 486 |
+
setTimeout(resolve, 300);
|
| 487 |
+
}
|
| 488 |
+
};
|
| 489 |
+
|
| 490 |
+
scrollDown();
|
| 491 |
+
});
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 492 |
"""
|
| 493 |
+
|
| 494 |
+
logger.info("Ensuring all content is rendered...")
|
| 495 |
+
driver.execute_async_script(f"const callback = arguments[arguments.length - 1]; {scroll_script}.then(callback);")
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 496 |
except Exception as e:
|
| 497 |
+
logger.warning(f"Content rendering check failed: {e}")
|
| 498 |
+
# スクロールを元の位置に戻す
|
| 499 |
+
driver.execute_script("window.scrollTo(0, 0);")
|
| 500 |
+
time.sleep(1)
|
| 501 |
|
| 502 |
+
# 7) Hide scrollbars via CSS
|
| 503 |
try:
|
| 504 |
+
driver.execute_script(
|
| 505 |
+
"document.documentElement.style.overflow = 'hidden';"
|
| 506 |
+
"document.body.style.overflow = 'hidden';"
|
| 507 |
+
)
|
| 508 |
logger.info("Scrollbars hidden via JS.")
|
| 509 |
except Exception as e:
|
| 510 |
logger.warning(f"Could not hide scrollbars via JS: {e}")
|
| 511 |
|
| 512 |
+
# 8) Get full page dimensions accurately with improved script
|
| 513 |
try:
|
| 514 |
+
# より正確なページ寸法を取得するためのJavaScriptコード
|
| 515 |
+
dimensions_script = """
|
| 516 |
+
return {
|
| 517 |
+
width: Math.max(
|
| 518 |
+
document.documentElement.scrollWidth,
|
| 519 |
+
document.documentElement.offsetWidth,
|
| 520 |
+
document.documentElement.clientWidth,
|
| 521 |
+
document.body ? document.body.scrollWidth : 0,
|
| 522 |
+
document.body ? document.body.offsetWidth : 0,
|
| 523 |
+
document.body ? document.body.clientWidth : 0
|
| 524 |
+
),
|
| 525 |
+
height: Math.max(
|
| 526 |
+
document.documentElement.scrollHeight,
|
| 527 |
+
document.documentElement.offsetHeight,
|
| 528 |
+
document.documentElement.clientHeight,
|
| 529 |
+
document.body ? document.body.scrollHeight : 0,
|
| 530 |
+
document.body ? document.body.offsetHeight : 0,
|
| 531 |
+
document.body ? document.body.clientHeight : 0
|
| 532 |
+
)
|
| 533 |
+
};
|
| 534 |
+
"""
|
| 535 |
dimensions = driver.execute_script(dimensions_script)
|
| 536 |
scroll_width = dimensions['width']
|
| 537 |
scroll_height = dimensions['height']
|
| 538 |
+
|
| 539 |
logger.info(f"Detected dimensions: width={scroll_width}, height={scroll_height}")
|
| 540 |
+
|
| 541 |
+
# スクロールして確認する追加の検証
|
| 542 |
+
driver.execute_script("window.scrollTo(0, document.body.scrollHeight);")
|
| 543 |
+
time.sleep(1) # スクロール完了を待つ
|
| 544 |
+
driver.execute_script("window.scrollTo(0, 0);")
|
| 545 |
+
time.sleep(1) # 元の位置に戻す
|
| 546 |
+
|
| 547 |
+
# 再検証
|
| 548 |
+
dimensions_after_scroll = driver.execute_script(dimensions_script)
|
| 549 |
+
scroll_height = max(scroll_height, dimensions_after_scroll['height'])
|
| 550 |
+
|
| 551 |
+
logger.info(f"After scroll check, height={scroll_height}")
|
| 552 |
+
|
| 553 |
+
# 最小値と最大値の設定
|
| 554 |
+
scroll_width = max(scroll_width, 100) # 最小幅
|
| 555 |
+
scroll_height = max(scroll_height, 100) # 最小高さ
|
| 556 |
+
|
| 557 |
+
scroll_width = min(scroll_width, 2000) # 最大幅
|
| 558 |
+
scroll_height = min(scroll_height, 6000) # 最大高さ
|
| 559 |
+
|
| 560 |
except Exception as e:
|
| 561 |
logger.error(f"Error getting page dimensions: {e}")
|
| 562 |
+
# フォールバックとしてデフォルト値を設定
|
| 563 |
scroll_width = 1200
|
| 564 |
scroll_height = 1000
|
| 565 |
logger.warning(f"Falling back to dimensions: width={scroll_width}, height={scroll_height}")
|
| 566 |
+
|
| 567 |
+
# 9) レイアウト安定化の確認
|
| 568 |
try:
|
| 569 |
stability_script = """
|
| 570 |
+
return new Promise(resolve => {
|
| 571 |
+
let lastHeight = document.body.offsetHeight;
|
| 572 |
+
let lastWidth = document.body.offsetWidth;
|
| 573 |
+
let stableCount = 0;
|
| 574 |
+
|
| 575 |
+
const checkStability = () => {
|
| 576 |
+
const currentHeight = document.body.offsetHeight;
|
| 577 |
+
const currentWidth = document.body.offsetWidth;
|
| 578 |
+
|
| 579 |
+
if (currentHeight === lastHeight && currentWidth === lastWidth) {
|
| 580 |
+
stableCount++;
|
| 581 |
+
if (stableCount >= 3) { // 3回連続で同じなら安定と判断
|
| 582 |
+
resolve(true);
|
| 583 |
return;
|
| 584 |
}
|
| 585 |
+
} else {
|
| 586 |
+
stableCount = 0;
|
| 587 |
+
lastHeight = currentHeight;
|
| 588 |
+
lastWidth = currentWidth;
|
| 589 |
+
}
|
| 590 |
+
|
| 591 |
+
setTimeout(checkStability, 200); // 200ms間隔でチェック
|
| 592 |
+
};
|
| 593 |
+
|
| 594 |
+
checkStability();
|
| 595 |
+
});
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 596 |
"""
|
| 597 |
+
|
| 598 |
logger.info("Checking layout stability...")
|
| 599 |
+
driver.execute_async_script(f"const callback = arguments[arguments.length - 1]; {stability_script}.then(callback);")
|
| 600 |
+
logger.info("Layout is stable")
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 601 |
except Exception as e:
|
| 602 |
+
logger.warning(f"Layout stability check failed: {e}")
|
| 603 |
+
time.sleep(2) # 追加待機
|
| 604 |
|
| 605 |
+
# 10) Calculate adjusted height with user-specified margin
|
| 606 |
adjusted_height = int(scroll_height * (1 + extension_percentage / 100.0))
|
| 607 |
+
# Ensure adjusted height is not excessively large or small
|
| 608 |
+
adjusted_height = max(adjusted_height, scroll_height, 100) # 最小高さを確保
|
| 609 |
logger.info(f"Adjusted height calculated: {adjusted_height} (extension: {extension_percentage}%)")
|
| 610 |
|
| 611 |
+
# 11) Set window size to full page dimensions
|
| 612 |
adjusted_width = scroll_width
|
| 613 |
logger.info(f"Resizing window to: width={adjusted_width}, height={adjusted_height}")
|
| 614 |
driver.set_window_size(adjusted_width, adjusted_height)
|
| 615 |
logger.info("Waiting for layout stabilization after resize...")
|
| 616 |
+
|
| 617 |
+
# レイアウト安定化のための待機
|
| 618 |
+
time.sleep(4) # 統一した待機時間
|
| 619 |
|
| 620 |
+
# 外部リソースの読み込み状態を確認
|
| 621 |
try:
|
| 622 |
+
resource_state = driver.execute_script("""
|
| 623 |
+
return {
|
| 624 |
+
readyState: document.readyState,
|
| 625 |
+
resourcesComplete: !document.querySelector('img:not([complete])') &&
|
| 626 |
+
!document.querySelector('link[rel="stylesheet"]:not([loaded])')
|
| 627 |
+
};
|
| 628 |
+
""")
|
| 629 |
logger.info(f"Resource state: {resource_state}")
|
| 630 |
+
|
| 631 |
+
# ドキュメントの読み込みが完了していない場合、追加で待機
|
| 632 |
if resource_state['readyState'] != 'complete':
|
| 633 |
logger.info("Document still loading, waiting additional time...")
|
| 634 |
time.sleep(2)
|
| 635 |
except Exception as e:
|
| 636 |
logger.warning(f"Error checking resource state: {e}")
|
| 637 |
|
| 638 |
+
# Scroll to top just in case
|
| 639 |
try:
|
| 640 |
driver.execute_script("window.scrollTo(0, 0)")
|
| 641 |
time.sleep(1)
|
|
|
|
| 643 |
except Exception as e:
|
| 644 |
logger.warning(f"Could not scroll to top: {e}")
|
| 645 |
|
| 646 |
+
# 12) Take screenshot
|
| 647 |
logger.info("Taking screenshot...")
|
| 648 |
png = driver.get_screenshot_as_png()
|
| 649 |
logger.info("Screenshot taken successfully.")
|
| 650 |
+
|
| 651 |
+
# Convert to PIL Image
|
| 652 |
img = Image.open(BytesIO(png))
|
| 653 |
+
|
| 654 |
+
# 画像サイズの確認とログ
|
| 655 |
logger.info(f"Screenshot dimensions: {img.width}x{img.height}")
|
| 656 |
+
|
| 657 |
+
# 余白トリミングが有効な場合
|
| 658 |
if trim_whitespace:
|
| 659 |
+
# 余分な空白をトリミング
|
| 660 |
img = trim_image_whitespace(img, threshold=248, padding=20)
|
| 661 |
logger.info(f"Trimmed dimensions: {img.width}x{img.height}")
|
| 662 |
+
|
| 663 |
return img
|
| 664 |
|
| 665 |
except Exception as e:
|
| 666 |
logger.error(f"An error occurred during screenshot generation: {e}", exc_info=True)
|
| 667 |
+
return Image.new('RGB', (1, 1), color=(0, 0, 0)) # Return black 1x1 image on error
|
| 668 |
finally:
|
| 669 |
logger.info("Cleaning up...")
|
| 670 |
if driver:
|
|
|
|
| 680 |
except Exception as e:
|
| 681 |
logger.error(f"Error removing temporary file {tmp_path}: {e}")
|
| 682 |
|
| 683 |
+
# --- Geminiを使った新しい関数 ---
|
| 684 |
def text_to_screenshot(text: str, extension_percentage: float, temperature: float = 0.3, trim_whitespace: bool = True) -> Image.Image:
|
| 685 |
+
"""テキストをGemini APIでHTMLに変換し、スクリーンショットを生成する統合関数"""
|
| 686 |
try:
|
| 687 |
+
# 1. テキストからHTMLを生成(温度パラメータも渡す)
|
| 688 |
html_code = generate_html_from_text(text, temperature)
|
| 689 |
+
|
| 690 |
+
# 2. HTMLからスクリーンショットを生成
|
| 691 |
return render_fullpage_screenshot(html_code, extension_percentage, trim_whitespace)
|
| 692 |
except Exception as e:
|
| 693 |
logger.error(f"テキストからスクリーンショット生成中にエラーが発生: {e}", exc_info=True)
|
| 694 |
+
return Image.new('RGB', (1, 1), color=(0, 0, 0)) # エラー時は黒画像
|
| 695 |
|
| 696 |
+
# --- FastAPI Setup ---
|
| 697 |
app = FastAPI()
|
| 698 |
+
|
| 699 |
+
# CORS設定を追加
|
| 700 |
+
app.add_middleware(
|
| 701 |
+
CORSMiddleware,
|
| 702 |
+
allow_origins=["*"],
|
| 703 |
+
allow_credentials=True,
|
| 704 |
+
allow_methods=["*"],
|
| 705 |
+
allow_headers=["*"],
|
| 706 |
+
)
|
| 707 |
+
|
| 708 |
+
# 静的ファイルのサービング設定
|
| 709 |
+
# Gradioのディレクトリを探索してアセットを見つける
|
| 710 |
gradio_dir = os.path.dirname(gr.__file__)
|
| 711 |
logger.info(f"Gradio version: {gr.__version__}")
|
| 712 |
logger.info(f"Gradio directory: {gradio_dir}")
|
| 713 |
+
|
| 714 |
+
# 基本的な静的ファイルディレクトリをマウント
|
| 715 |
static_dir = os.path.join(gradio_dir, "templates", "frontend", "static")
|
| 716 |
+
if os.path.exists(static_dir):
|
| 717 |
+
logger.info(f"Mounting static directory: {static_dir}")
|
| 718 |
+
app.mount("/static", StaticFiles(directory=static_dir), name="static")
|
| 719 |
+
|
| 720 |
+
# _appディレクトリを探す(新しいSvelteKitベースのフロントエンド用)
|
| 721 |
app_dir = os.path.join(gradio_dir, "templates", "frontend", "_app")
|
| 722 |
+
if os.path.exists(app_dir):
|
| 723 |
+
logger.info(f"Mounting _app directory: {app_dir}")
|
| 724 |
+
app.mount("/_app", StaticFiles(directory=app_dir), name="_app")
|
|
|
|
|
|
|
| 725 |
|
| 726 |
+
# assetsディレクトリを探す
|
| 727 |
+
assets_dir = os.path.join(gradio_dir, "templates", "frontend", "assets")
|
| 728 |
+
if os.path.exists(assets_dir):
|
| 729 |
+
logger.info(f"Mounting assets directory: {assets_dir}")
|
| 730 |
+
app.mount("/assets", StaticFiles(directory=assets_dir), name="assets")
|
| 731 |
|
| 732 |
+
# cdnディレクトリがあれば追加
|
| 733 |
+
cdn_dir = os.path.join(gradio_dir, "templates", "cdn")
|
| 734 |
+
if os.path.exists(cdn_dir):
|
| 735 |
+
logger.info(f"Mounting cdn directory: {cdn_dir}")
|
| 736 |
+
app.mount("/cdn", StaticFiles(directory=cdn_dir), name="cdn")
|
| 737 |
+
|
| 738 |
+
# API Endpoint for screenshot generation
|
| 739 |
+
@app.post("/api/screenshot",
|
| 740 |
+
response_class=StreamingResponse,
|
| 741 |
+
tags=["Screenshot"],
|
| 742 |
+
summary="Render HTML to Full Page Screenshot",
|
| 743 |
+
description="Takes HTML code and an optional vertical extension percentage, renders it using a headless browser, and returns the full-page screenshot as a PNG image.")
|
| 744 |
async def api_render_screenshot(request: ScreenshotRequest):
|
| 745 |
+
"""
|
| 746 |
+
API endpoint to render HTML and return a screenshot.
|
| 747 |
+
"""
|
| 748 |
try:
|
| 749 |
logger.info(f"API request received. Extension: {request.extension_percentage}%")
|
| 750 |
+
# Run the blocking Selenium code in a separate thread (FastAPI handles this)
|
| 751 |
+
pil_image = render_fullpage_screenshot(
|
| 752 |
+
request.html_code,
|
| 753 |
+
request.extension_percentage,
|
| 754 |
+
request.trim_whitespace
|
| 755 |
+
)
|
| 756 |
+
|
| 757 |
+
if pil_image.size == (1, 1):
|
| 758 |
+
logger.error("Screenshot generation failed, returning 1x1 image.")
|
| 759 |
+
# Optionally return a proper error response instead of 1x1 image
|
| 760 |
+
# raise HTTPException(status_code=500, detail="Failed to generate screenshot")
|
| 761 |
+
|
| 762 |
+
# Convert PIL Image to PNG bytes
|
| 763 |
img_byte_arr = BytesIO()
|
| 764 |
pil_image.save(img_byte_arr, format='PNG')
|
| 765 |
+
img_byte_arr.seek(0) # Go to the start of the BytesIO buffer
|
| 766 |
+
|
| 767 |
logger.info("Returning screenshot as PNG stream.")
|
| 768 |
return StreamingResponse(img_byte_arr, media_type="image/png")
|
| 769 |
+
|
| 770 |
except Exception as e:
|
| 771 |
logger.error(f"API Error: {e}", exc_info=True)
|
| 772 |
raise HTTPException(status_code=500, detail=f"Internal Server Error: {e}")
|
| 773 |
|
| 774 |
+
# --- 新しいGemini API連携エンドポイント ---
|
| 775 |
+
@app.post("/api/text-to-screenshot",
|
| 776 |
+
response_class=StreamingResponse,
|
| 777 |
+
tags=["Screenshot", "Gemini"],
|
| 778 |
+
summary="テキストからインフォグラフィックを生成",
|
| 779 |
+
description="テキストをGemini APIを使ってHTMLインフォグラフィックに変換し、スクリーンショットとして返します。")
|
| 780 |
async def api_text_to_screenshot(request: GeminiRequest):
|
| 781 |
+
"""
|
| 782 |
+
テキストからHTMLインフォグラフィックを生成してスクリーンショットを返すAPIエンドポイント
|
| 783 |
+
"""
|
| 784 |
try:
|
| 785 |
logger.info(f"テキスト→スクリーンショットAPIリクエスト受信。テキスト長さ: {len(request.text)}, 拡張率: {request.extension_percentage}%, 温度: {request.temperature}")
|
| 786 |
+
|
| 787 |
+
# テキストからHTMLを生成してスクリーンショットを作成(温度パラメータも渡す)
|
| 788 |
+
pil_image = text_to_screenshot(
|
| 789 |
+
request.text,
|
| 790 |
+
request.extension_percentage,
|
| 791 |
+
request.temperature,
|
| 792 |
+
request.trim_whitespace
|
| 793 |
+
)
|
| 794 |
+
|
| 795 |
+
if pil_image.size == (1, 1):
|
| 796 |
+
logger.error("スクリーンショット生成に失敗しました。1x1画像を返します。")
|
| 797 |
+
# raise HTTPException(status_code=500, detail="スクリーンショット生成に失敗しました")
|
| 798 |
+
|
| 799 |
+
# PIL画像をPNGバイトに変換
|
| 800 |
img_byte_arr = BytesIO()
|
| 801 |
pil_image.save(img_byte_arr, format='PNG')
|
| 802 |
+
img_byte_arr.seek(0) # BytesIOバッファの先頭に戻る
|
| 803 |
+
|
| 804 |
logger.info("スクリーンショットをPNGストリームとして返します。")
|
| 805 |
return StreamingResponse(img_byte_arr, media_type="image/png")
|
| 806 |
+
|
| 807 |
except Exception as e:
|
| 808 |
logger.error(f"API Error: {e}", exc_info=True)
|
| 809 |
raise HTTPException(status_code=500, detail=f"Internal Server Error: {e}")
|
| 810 |
|
| 811 |
+
# --- Gradio Interface Definition ---
|
| 812 |
+
# 入力モードの選択用Radioコンポーネント
|
| 813 |
def process_input(input_mode, input_text, extension_percentage, temperature, trim_whitespace):
|
| 814 |
+
"""入力モードに応じて適切な処理を行う"""
|
| 815 |
if input_mode == "HTML入力":
|
| 816 |
+
# HTMLモードの場合は既存の処理
|
| 817 |
return render_fullpage_screenshot(input_text, extension_percentage, trim_whitespace)
|
| 818 |
else:
|
| 819 |
+
# テキスト入力モードの場合はGemini APIを使用
|
| 820 |
return text_to_screenshot(input_text, extension_percentage, temperature, trim_whitespace)
|
| 821 |
|
| 822 |
+
# Gradio UIの定義
|
| 823 |
with gr.Blocks(title="Full Page Screenshot (��キスト変換対応)", theme=gr.themes.Base()) as iface:
|
| 824 |
gr.Markdown("# HTMLビューア & テキスト→インフォグラフィック変換")
|
| 825 |
gr.Markdown("HTMLコードをレンダリングするか、テキストをGemini APIでインフォグラフィックに変換して画像として取得します。")
|
| 826 |
+
|
| 827 |
with gr.Row():
|
| 828 |
+
input_mode = gr.Radio(
|
| 829 |
+
["HTML入力", "テキスト入力"],
|
| 830 |
+
label="入力モード",
|
| 831 |
+
value="HTML入力"
|
| 832 |
+
)
|
| 833 |
+
|
| 834 |
+
# 共用のテキストボックス
|
| 835 |
+
input_text = gr.Textbox(
|
| 836 |
+
lines=15,
|
| 837 |
+
label="入力",
|
| 838 |
+
placeholder="HTMLコードまたはテキストを入力してください。入力モードに応じて処理されます。"
|
| 839 |
+
)
|
| 840 |
+
|
| 841 |
with gr.Row():
|
| 842 |
+
extension_percentage = gr.Slider(
|
| 843 |
+
minimum=0,
|
| 844 |
+
maximum=30,
|
| 845 |
+
step=1.0,
|
| 846 |
+
value=8, # デフォルト値8%
|
| 847 |
+
label="上下高さ拡張率(%)"
|
| 848 |
+
)
|
| 849 |
+
|
| 850 |
+
# 温度調整スライダー(テキストモード時のみ表示)
|
| 851 |
+
temperature = gr.Slider(
|
| 852 |
+
minimum=0.0,
|
| 853 |
+
maximum=1.0,
|
| 854 |
+
step=0.1,
|
| 855 |
+
value=0.3, # デフォルト値を0.3に下げて創造性を抑制
|
| 856 |
+
label="生成時の温度(低い=一貫性高、高い=創造性高)",
|
| 857 |
+
visible=False # 最初は非表示
|
| 858 |
+
)
|
| 859 |
+
|
| 860 |
+
# 余白トリミングオプション
|
| 861 |
+
trim_whitespace = gr.Checkbox(
|
| 862 |
+
label="余白を自動トリミング",
|
| 863 |
+
value=True,
|
| 864 |
+
info="生成される画像から余分な空白領域を自動的に削除します"
|
| 865 |
+
)
|
| 866 |
+
|
| 867 |
submit_btn = gr.Button("生成")
|
| 868 |
output_image = gr.Image(type="pil", label="ページ全体のスクリーンショット")
|
| 869 |
+
|
| 870 |
+
# 入力モード変更時のイベント処理(テキストモード時のみ温度スライダーを表示)
|
| 871 |
def update_temperature_visibility(mode):
|
| 872 |
+
# Gradio 4.x用のアップデート方法
|
| 873 |
return {"visible": mode == "テキスト入力", "__type__": "update"}
|
| 874 |
+
|
| 875 |
+
input_mode.change(
|
| 876 |
+
fn=update_temperature_visibility,
|
| 877 |
+
inputs=input_mode,
|
| 878 |
+
outputs=temperature
|
| 879 |
+
)
|
| 880 |
+
|
| 881 |
+
# 生成ボタンクリック時のイベント処理
|
| 882 |
+
submit_btn.click(
|
| 883 |
+
fn=process_input,
|
| 884 |
+
inputs=[input_mode, input_text, extension_percentage, temperature, trim_whitespace],
|
| 885 |
+
outputs=output_image
|
| 886 |
+
)
|
| 887 |
+
|
| 888 |
+
# 環境変数情報を表示
|
| 889 |
gemini_model = os.environ.get("GEMINI_MODEL", "gemini-1.5-pro")
|
| 890 |
gr.Markdown(f"""
|
| 891 |
## APIエンドポイント
|
| 892 |
+
- `/api/screenshot` - HTMLコードからスクリーンショットを生成
|
| 893 |
- `/api/text-to-screenshot` - テキストからインフォグラフィックスクリーンショットを生成
|
| 894 |
+
|
| 895 |
## 設定情報
|
| 896 |
- 使用モデル: {gemini_model} (環境変数 GEMINI_MODEL で変更可能)
|
| 897 |
""")
|
| 898 |
|
| 899 |
+
# --- Mount Gradio App onto FastAPI ---
|
| 900 |
app = gr.mount_gradio_app(app, iface, path="/")
|
| 901 |
+
|
| 902 |
+
# --- Run with Uvicorn (for local testing) ---
|
| 903 |
if __name__ == "__main__":
|
| 904 |
import uvicorn
|
| 905 |
logger.info("Starting Uvicorn server for local development...")
|