import gradio as gr
from fastapi import FastAPI, HTTPException, Body
from fastapi.responses import StreamingResponse
from fastapi.staticfiles import StaticFiles
from fastapi.middleware.cors import CORSMiddleware
from pydantic import BaseModel
from selenium import webdriver
from selenium.webdriver.chrome.options import Options
from selenium.webdriver.common.by import By
from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.support import expected_conditions as EC
from PIL import Image
from io import BytesIO
import tempfile
import time
import os
import logging
import re
# 正しいGemini関連のインポート
import google.generativeai as genai
# ロギング設定
logging.basicConfig(level=logging.INFO)
logger = logging.getLogger(__name__)
# --- Gemini統合 ---
class GeminiRequest(BaseModel):
"""Geminiへのリクエストデータモデル"""
text: str
extension_percentage: float = 6.0 # デフォルト値6%
temperature: float = 1.0 # デフォルト値1.0の温度パラメータ
trim_whitespace: bool = True # 余白トリミングオプション(デフォルト有効)
layout_type: str = "standard" # レイアウトタイプ(standard, spaced, compact)
class ScreenshotRequest(BaseModel):
"""スクリーンショットリクエストモデル"""
html_code: str
extension_percentage: float = 6.0 # デフォルト値6%
trim_whitespace: bool = True # 余白トリミングオプション(デフォルト有効)
def generate_html_from_text(text, temperature=1.0, layout_type="standard"):
"""テキストからHTMLを生成する"""
try:
# APIキーの取得と設定
api_key = os.environ.get("GEMINI_API_KEY")
if not api_key:
logger.error("GEMINI_API_KEY 環境変数が設定されていません")
raise ValueError("GEMINI_API_KEY 環境変数が設定されていません")
# モデル名の取得(環境変数から、なければデフォルト値)
model_name = os.environ.get("GEMINI_MODEL", "gemini-1.5-pro")
logger.info(f"使用するGeminiモデル: {model_name}")
# Gemini APIの設定
genai.configure(api_key=api_key)
# レイアウトタイプに応じた追加設定
layout_adjustments = ""
if layout_type == "spaced":
layout_adjustments = """
## 特別なスタイル設定
- 全てのテキスト要素には最低2rem以上の行間と要素間マージンを設定する
- 各カードのパディングを1.5倍に増やす
- 箇条書きリストのアイテム間は1.5emの間隔を確保する
- すべての文字サイズを15%大きくする
- 内容量に応じて自動的にグリッドやフレックスレイアウトを調整する
- テキストが重ならないように要素間に十分なスペースを強制的に設ける
"""
elif layout_type == "compact":
layout_adjustments = """
## 特別なスタイル設定
- レイアウトをよりコンパクトに配置
- 小さめのアイコンサイズを使用(標準の75%)
- フォントサイズを10%小さく設定
- テキスト量が多い場合は自動的に複数列に分割表示
"""
# レイアウト崩れ防止のための追加指示
layout_improvements = """
## 重要なレイアウト指示(必ず守ってください)
- カード要素は必ずdisplay: gridまたはflexboxで配置してください
- カードの配置は絶対位置(position: absolute)を使わず、フロー配置を使ってください
- 各カードには以下のスタイルを必ず適用してください:
```css
.card {
position: relative;
clear: both;
display: flex;
flex-direction: column;
margin: 1.5rem 0;
padding: 1.2rem;
height: auto;
overflow: visible;
box-sizing: border-box;
}
```
- 兄弟要素間のマージンは必ず以下のように設定してください:
```css
.card + .card,
.section + .section,
.info-box + .info-box,
.row + .row {
margin-top: 2rem;
}
```
- コンテナの高さは自動的に調整されるようにしてください:
```css
.container, .row, .column {
height: auto;
overflow: hidden;
display: flex;
flex-direction: column;
}
```
- グリッドレイアウトを使用する場合は明示的な行の高さを設定してください:
```css
.grid {
display: grid;
grid-template-columns: repeat(auto-fit, minmax(300px, 1fr));
grid-gap: 2rem;
grid-auto-rows: minmax(min-content, auto);
}
```
- すべてのテキスト要素に余白を設定してください:
```css
p, h1, h2, h3, h4, h5, h6, li {
margin-bottom: 1rem;
line-height: 1.6;
}
```
"""
# システムプロンプト(強化版)
system_instruction = f"""# グラフィックレコーディング風インフォグラフィック変換プロンプト V3
## 目的
以下の内容を、超一流デザイナーが作成したような、日本語で完璧なグラフィックレコーディング風のHTMLインフォグラフィックに変換してください。情報設計とビジュアルデザインの両面で最高水準を目指します。
手書き風の図形やFont Awesomeアイコンを大きく活用して内容を視覚的かつ直感的に表現します。
## デザイン仕様
### 1. カラースキーム
```
```
### 2. グラフィックレコーディング要素
- 左上から右へ、上から下へと情報を順次配置
- 日本語の手書き風フォントの使用(Yomogi, Zen Kurenaido, Kaisei Decol)
- 手描き風の囲み線、矢印、バナー、吹き出し
- テキストと視覚要素(Font Awesomeアイコン、シンプルな図形)の組み合わせ
- Font Awesomeアイコンは各セクションの内容を表現するものを大きく(2x〜3x)表示
- キーワードごとに関連するFont Awesomeアイコンを隣接配置
- キーワードの強調(色付き下線、マーカー効果、Font Awesomeによる装飾)
- 関連する概念を線や矢印で接続し、接続部にもFont Awesomeアイコン(fa-arrow-right, fa-connection等)を挿入
- Font Awesomeアニメーション効果(fa-beat, fa-bounce, fa-fade, fa-flip, fa-shake, fa-spin)を適切に活用
- 重要なポイントには「fa-circle-exclamation」や「fa-lightbulb」などのアイコンを目立つ大きさで配置
- 数値やデータには「fa-chart-line」や「fa-percent」などの関連アイコンを添える
- 感情や状態を表すには表情アイコン(fa-face-smile, fa-face-frown等)を活用
- アイコンにホバー効果(色変化、サイズ変化)を付与
- 背景にはFont Awesomeの薄いパターンを配置(fa-shapes等を透過度を下げて配置)
### 3. アニメーション効果
- Font Awesomeアイコンに連動するアニメーション(fa-beat, fa-bounce, fa-fade等)
- 重要キーワード出現時のハイライト効果(グラデーション変化)
- 接続線や矢印の流れるようなアニメーション
- アイコンの回転・拡大縮小アニメーション(特に注目させたい箇所)
- 背景グラデーションの緩やかな変化
- スクロールに連動した要素の出現効果
- クリック/タップでアイコンが反応する効果
### 4. タイポグラフィ
- タイトル:32px、グラデーション効果、太字、Font Awesomeアイコンを左右に配置
- サブタイトル:16px、#475569、関連するFont Awesomeアイコンを添える
- セクション見出し:18px、# 1e40af、左側にFont Awesomeアイコンを必ず配置し、アイコンにはアニメーション効果
- 本文:14px、#334155、行間1.4、重要キーワードには関連するFont Awesomeアイコンを小さく添える
- フォント指定:
```html
```
### 5. レイアウト
- ヘッダー:左揃えタイトル(大きなFont Awesomeアイコンを添える)+右揃え日付/出典
- 3カラム構成:左側33%、中央33%、右側33%
- カード型コンポーネント:白背景、角丸12px、微細シャドウ、右上にFont Awesomeアイコンを配置
- セクション間の適切な余白と階層構造(階層を示すFont Awesomeアイコンを活用)
- 適切にグラスモーフィズムを活用(背後にぼかしたFont Awesomeアイコンを配置)
- 横幅は100%
- 重要な要素は中央寄り、補足情報は周辺部に配置
{layout_improvements}
## レイアウト崩れ防止のための追加設定
- テキストが重ならないようにカードやセクション間に十分なマージンを設定(最低25px)
- テキスト量に応じて自動的に要素の高さが伸びるフレックスレイアウトを採用
- テキストが多い場合は自動的にフォントサイズを調整する機能を実装
- スマートスペーシング:内容量に応じて自動的に間隔を調整
- 以下のCSSを必ず追加して、テキストの重なりを防止する:
```css
.card, .section, .info-box {{
overflow: hidden;
display: flex;
flex-direction: column;
margin-bottom: 1.5rem;
min-height: fit-content;
}}
.card-content {{
flex: 1;
display: flex;
flex-direction: column;
}}
.card-title {{
font-weight: bold;
margin-bottom: 0.75rem;
line-height: 1.4;
}}
.card-text {{
line-height: 1.6;
margin-bottom: 0.5rem;
}}
.info-item {{
margin-bottom: 0.75rem;
line-height: 1.5;
}}
li {{
margin-bottom: 0.5rem;
line-height: 1.5;
}}
p {{
margin-bottom: 0.75rem;
line-height: 1.5;
}}
```
## 自動テキスト調整機能
以下のJavaScriptを必ず追加して、テキスト量に応じたフォントサイズの自動調整を行う:
```html
```
{layout_adjustments}
## グラフィックレコーディング表現技法
- テキストと視覚要素のバランスを重視(文字情報の50%以上をFont Awesomeアイコンで視覚的に補完)
- キーワードを囲み線や色で強調し、関連するFont Awesomeアイコンを必ず添える
- 概念ごとに最適なFont Awesomeアイコンを選定(抽象的な概念には複数の関連アイコンを組み合わせて表現)
- 数値データは簡潔なグラフや図表で表現し、データ種類に応じたFont Awesomeアイコン(fa-chart-pie, fa-chart-column等)を配置
- 接続線や矢印で情報間の関係性を明示し、関係性の種類に応じたアイコン(fa-link, fa-code-branch等)を添える
- 余白を効果的に活用して視認性を確保(余白にも薄いFont Awesomeパターンを配置可)
- コントラストと色の使い分けでメリハリを付け、カラースキームに沿ったアイコン色を活用
## Font Awesomeアイコン活用ガイドライン
- 概念カテゴリー別の推奨アイコン:
- 時間・順序:fa-clock, fa-hourglass, fa-calendar, fa-timeline
- 場所・位置:fa-location-dot, fa-map, fa-compass, fa-globe
- 人物・組織:fa-user, fa-users, fa-building, fa-sitemap
- 行動・活動:fa-person-running, fa-gears, fa-hammer, fa-rocket
- 思考・アイデア:fa-brain, fa-lightbulb, fa-thought-bubble, fa-comments
- 感情・状態:fa-face-smile, fa-face-sad-tear, fa-heart, fa-temperature-half
- 成長・変化:fa-seedling, fa-arrow-trend-up, fa-chart-line, fa-diagram-project
- 問題・課題:fa-triangle-exclamation, fa-circle-question, fa-bug, fa-ban
- 解決・成功:fa-check, fa-trophy, fa-handshake, fa-key
- アイコンサイズの使い分け:
- 主要概念:3x(fa-3x)
- 重要キーワード:2x(fa-2x)
- 補足情報:1x(標準サイズ)
- 装飾的要素:lg(fa-lg)
- アニメーション効果の適切な使い分け:
- 注目喚起:fa-beat, fa-shake
- 継続的プロセス:fa-spin, fa-pulse
- 状態変化:fa-flip, fa-fade
- 新規情報:fa-bounce
## 全体的な指針
- 読み手が自然に視線を移動できる配置(Font Awesomeアイコンで視線誘導)
- 情報の階層と関連性を視覚的に明確化(階層ごとにアイコンのサイズや色を変える)
- 手書き風の要素とFont Awesomeアイコンを組み合わせて親しみやすさとプロフェッショナル感を両立
- 大きなFont Awesomeアイコンを活用した視覚的な記憶に残るデザイン(各セクションに象徴的なアイコンを配置)
- フッターに出典情報と関連するFont Awesomeアイコン(fa-book, fa-citation等)を明記
## 変換する文章/記事
ーーー<ユーザーが入力(または添付)>ーーー"""
# モデルを初期化して処理
logger.info(f"Gemini APIにリクエストを送信: テキスト長さ = {len(text)}, 温度 = {temperature}, レイアウトタイプ = {layout_type}")
# モデル初期化とフォールバック処理
try:
model = genai.GenerativeModel(model_name)
except Exception as e:
# 指定されたモデルが使用できない場合はフォールバック
fallback_model = "gemini-pro"
logger.warning(f"{model_name}が利用できません: {e}, フォールバックモデル{fallback_model}を使用します")
model = genai.GenerativeModel(fallback_model)
# 生成設定
generation_config = {
"temperature": temperature, # パラメータとして受け取った温度を設定
"top_p": 0.95,
"top_k": 64,
"max_output_tokens": 8192,
}
# プロンプト構築
prompt = f"{system_instruction}\n\n{text}"
# コンテンツ生成
response = model.generate_content(
prompt,
generation_config=generation_config
)
# レスポンスからHTMLを抽出
raw_response = response.text
# HTMLタグ部分だけを抽出(```html と ``` の間)
html_start = raw_response.find("```html")
html_end = raw_response.rfind("```")
if html_start != -1 and html_end != -1 and html_start < html_end:
html_start += 7 # "```html" の長さ分進める
html_code = raw_response[html_start:html_end].strip()
logger.info(f"HTMLの生成に成功: 長さ = {len(html_code)}")
# HTML後処理:テキスト重なり防止のためのクラス・スタイル追加
html_code = enhance_html_for_layout(html_code)
return html_code
else:
# HTMLタグが見つからない場合、レスポンス全体を返す
logger.warning("レスポンスから```html```タグが見つかりませんでした。全テキストを返します。")
return raw_response
except Exception as e:
logger.error(f"HTML生成中にエラーが発生: {e}", exc_info=True)
raise Exception(f"Gemini APIでのHTML生成に失敗しました: {e}")
# HTMLを後処理してレイアウト崩れを防止する関数
def enhance_html_for_layout(html_code):
"""HTMLを後処理してレイアウト崩れを防止するための調整を行う(強化版)"""
try:
# 基本的なスタイルとスクリプトが含まれているか確認
base_styles_needed = True
base_scripts_needed = True
if "")
if style_pos != -1:
# カード要素のスタイルが含まれているか確認
if ".card" in html_code[:style_pos] and "flex-direction: column" in html_code[:style_pos]:
base_styles_needed = False
# レイアウト崩れ防止用の強化CSSを追加
enhanced_css = """
/* --- レイアウト崩れ防止強化スタイル --- */
.card, .section, .info-box {
position: relative !important;
display: flex !important;
flex-direction: column !important;
margin: 1.5rem 0 !important;
padding: 1.2rem !important;
height: auto !important;
min-height: fit-content !important;
overflow: visible !important;
box-sizing: border-box !important;
z-index: 1 !important;
clear: both !important;
}
/* フローティング要素のクリア */
.clearfix::after {
content: "" !important;
display: table !important;
clear: both !important;
}
/* コンテナ要素の高さ自動調整 */
.container, .row, .column {
height: auto !important;
overflow: hidden !important;
position: relative !important;
}
/* グリッドレイアウトの調整 */
.grid {
display: grid !important;
grid-template-columns: repeat(auto-fit, minmax(300px, 1fr)) !important;
grid-gap: 2rem !important;
grid-auto-rows: minmax(min-content, auto) !important;
}
/* マージンとパディングの強制 */
p, h1, h2, h3, h4, h5, h6, li {
margin-bottom: 1rem !important;
line-height: 1.6 !important;
}
/* 重なり解消のための特別なスタイル */
body {
overflow-x: hidden !important;
}
.card + .card, .section + .section, .info-box + .info-box {
margin-top: 2rem !important;
}
/* モバイル表示の改善 */
@media (max-width: 768px) {
.card, .section, .info-box {
width: 100% !important;
margin-left: 0 !important;
margin-right: 0 !important;
}
}
"""
# スタイルタグの閉じ直前に挿入
html_code = html_code[:style_pos] + enhanced_css + html_code[style_pos:]
# スタイルが存在しない場合は新たに追加
if base_styles_needed and "
"""
html_code = html_code[:head_end_pos] + base_styles + html_code[head_end_pos:]
# 自動レイアウト修正用のスクリプトを強化
if "