tomo2chin2 commited on
Commit
88184d3
·
verified ·
1 Parent(s): 3e5bb1c

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +273 -12
app.py CHANGED
@@ -16,10 +16,176 @@ import time
16
  import os
17
  import logging
18
 
 
 
 
 
19
  # ロギング設定
20
  logging.basicConfig(level=logging.INFO)
21
  logger = logging.getLogger(__name__)
22
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
23
  # --- Core Screenshot Logic ---
24
  def render_fullpage_screenshot(html_code: str, extension_percentage: float) -> Image.Image:
25
  """
@@ -151,6 +317,19 @@ def render_fullpage_screenshot(html_code: str, extension_percentage: float) -> I
151
  except Exception as e:
152
  logger.error(f"Error removing temporary file {tmp_path}: {e}")
153
 
 
 
 
 
 
 
 
 
 
 
 
 
 
154
  # --- FastAPI Setup ---
155
  app = FastAPI()
156
 
@@ -233,19 +412,101 @@ async def api_render_screenshot(request: ScreenshotRequest):
233
  logger.error(f"API Error: {e}", exc_info=True)
234
  raise HTTPException(status_code=500, detail=f"Internal Server Error: {e}")
235
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
236
  # --- Gradio Interface Definition ---
237
- iface = gr.Interface(
238
- fn=render_fullpage_screenshot,
239
- inputs=[
240
- gr.Textbox(lines=15, label="HTMLコード入力"),
241
- gr.Slider(minimum=0, maximum=20, step=1.0, value=8, label="上下高さ拡張率(%)")
242
- ],
243
- outputs=gr.Image(type="pil", label="ページ全体のスクリーンショット"),
244
- title="Full Page Screenshot (高さ拡張調整可能)",
245
- description="HTMLをヘッドレスブラウザでレンダリングし、ページ全体を1枚の画像として取得します。上下のみユーザー指定の余裕(%)を追加します。APIエンドポイントは /api/screenshot で利用可能です。",
246
- allow_flagging="never",
247
- theme=gr.themes.Base() # 明示的にテーマを指定
248
- )
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
249
 
250
  # --- Mount Gradio App onto FastAPI ---
251
  app = gr.mount_gradio_app(app, iface, path="/")
 
16
  import os
17
  import logging
18
 
19
+ # 新しいGemini関連のインポート
20
+ from google import genai
21
+ from google.genai import types
22
+
23
  # ロギング設定
24
  logging.basicConfig(level=logging.INFO)
25
  logger = logging.getLogger(__name__)
26
 
27
+ # --- Gemini統合 ---
28
+ class GeminiRequest(BaseModel):
29
+ """Geminiへのリクエストデータモデル"""
30
+ text: str
31
+ extension_percentage: float = 8.0 # Default value same as Gradio slider
32
+
33
+ def init_gemini_client():
34
+ """Gemini APIクライアントを初期化する"""
35
+ api_key = os.environ.get("GEMINI_API_KEY")
36
+ if not api_key:
37
+ logger.error("GEMINI_API_KEY 環境変数が設定されていません")
38
+ raise ValueError("GEMINI_API_KEY 環境変数が設定されていません")
39
+
40
+ return genai.Client(api_key=api_key)
41
+
42
+ def generate_html_from_text(text):
43
+ """テキストからHTMLを生成する"""
44
+ try:
45
+ client = init_gemini_client()
46
+ model = "gemini-2.5-pro-exp-03-25" # リクエスト例と同じモデルを使用
47
+
48
+ # システムプロンプト(リクエスト例と同じものを使用)
49
+ system_instruction = """# グラフィックレコーディング風インフォグラフィック変換プロンプト V2
50
+ ## 目的
51
+ 以下の内容を、超一流デザイナーが作成したような、日本語で完璧なグラフィックレコーディング風のHTMLインフォグラフィックに変換してください。情報設計とビジュアルデザインの両面で最高水準を目指します。
52
+ 手書き風の図形やFont Awesomeアイコンを大きく活用して内容を視覚的かつ直感的に表現します。
53
+
54
+ ## デザイン仕様
55
+ ### 1. カラースキーム
56
+ ```
57
+ <palette>
58
+ <color name='MysticLibrary-1' rgb='2E578C' r='46' g='87' b='140' />
59
+ <color name='MysticLibrary-2' rgb='182D40' r='24' g='45' b='64' />
60
+ <color name='MysticLibrary-3' rgb='BF807A' r='191' g='128' b='122' />
61
+ <color name='MysticLibrary-4' rgb='592A2A' r='89' g='42' b='42' />
62
+ <color name='MysticLibrary-5' rgb='F2F2F2' r='242' g='242' b='242' />
63
+ </palette>
64
+ ```
65
+ ### 2. グラフィックレコーディング要素
66
+ - 左上から右へ、上から下へと情報を順次配置
67
+ - 日本語の手書き風フォントの使用(Yomogi, Zen Kurenaido, Kaisei Decol)
68
+ - 手描き風の囲み線、矢印、バナー、吹き出し
69
+ - テキストと視覚要素(Font Awesomeアイコン、シンプルな図形)の組み合わせ
70
+ - Font Awesomeアイコンは各セクションの内容を表現するものを大きく(2x〜3x)表示
71
+ - キーワードごとに関連するFont Awesomeアイコンを隣接配置
72
+ - キーワードの強調(色付き下線、マーカー効果、Font Awesomeによる装飾)
73
+ - 関連する概念を線や矢印で接続し、接続部にもFont Awesomeアイコン(fa-arrow-right, fa-connection等)を挿入
74
+ - Font Awesomeアニメーション効果(fa-beat, fa-bounce, fa-fade, fa-flip, fa-shake, fa-spin)を適切に活用
75
+ - 重要なポイントには「fa-circle-exclamation」や「fa-lightbulb」などのアイコンを目立つ大きさで配置
76
+ - 数値やデータには「fa-chart-line」や「fa-percent」などの関連アイコンを添える
77
+ - 感情や状態を表すには表情アイコン(fa-face-smile, fa-face-frown等)を活用
78
+ - アイコンにホバー効果(色変化、サイズ変化)を付与
79
+ - 背景にはFont Awesomeの薄いパターンを配置(fa-shapes等を透過度を下げて配置)
80
+ ### 3. アニメーション効果
81
+ - Font Awesomeアイコンに連動するアニメーション(fa-beat, fa-bounce, fa-fade等)
82
+ - 重要キーワード出現時のハイライト効果(グラデーション変化)
83
+ - 接続線や矢印の流れるようなアニメーション
84
+ - アイコンの回転・拡大縮小アニメーション(特に注目させたい箇所)
85
+ - 背景グラデーションの緩やかな変化
86
+ - スクロールに連動した要素の出現効果
87
+ - クリック/タップでアイコンが反応する効果
88
+ ### 4. タイポグラフィ
89
+ - タイトル:32px、グラデーション効果、太字、Font Awesomeアイコンを左右に配置
90
+ - サブタイトル:16px、#475569、関連するFont Awesomeアイコンを添える
91
+ - セクション見出し:18px、# 1e40af、左側にFont Awesomeアイコンを必ず配置し、アイコンにはアニメーション効果
92
+ - 本文:14px、#334155、行間1.4、重要キーワードには関連するFont Awesomeアイコンを小さく添える
93
+ - フォント指定:
94
+ ```html
95
+ <style>
96
+ @ import url('https ://fonts.googleapis.com/css2?family=Kaisei+Decol&family=Yomogi&family=Zen+Kurenaido&display=swap');
97
+ @ import url('https ://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.4.0/css/all.min.css');
98
+ </style>
99
+ ```
100
+ ### 5. レイアウト
101
+ - ヘッダー:左揃えタイトル(大きなFont Awesomeアイコンを添える)+右揃え日付/出典
102
+ - 3カラム構成:左側33%、中��33%、右側33%
103
+ - カード型コンポーネント:白背景、角丸12px、微細シャドウ、右上にFont Awesomeアイコンを配置
104
+ - セクション間の適切な余白と階層構造(階層を示すFont Awesomeアイコンを活用)
105
+ - 適切にグラスモーフィズムを活用(背後にぼかしたFont Awesomeアイコンを配置)
106
+ - 横幅は100%
107
+ - 重要な要素は中央寄り、補足情報は周辺部に配置
108
+ ## グラフィックレコーディング表現技法
109
+ - テキストと視覚要素のバランスを重視(文字情報の50%以上をFont Awesomeアイコンで視覚的に補完)
110
+ - キーワードを囲み線や色で強調し、関連するFont Awesomeアイコンを必ず添える
111
+ - 概念ごとに最適なFont Awesomeアイコンを選定(抽象的な概念には複数の関連アイコンを組み合わせて表現)
112
+ - 数値データは簡潔なグラフや図表で表現し、データ種類に応じたFont Awesomeアイコン(fa-chart-pie, fa-chart-column等)を配置
113
+ - 接続線や矢印で情報間の関係性を明示し、関係性の種類に応じたアイコン(fa-link, fa-code-branch等)を添える
114
+ - 余白を効果的に活用して視認性を確保(余白にも薄いFont Awesomeパターンを配置可)
115
+ - コントラストと色の使い分けでメリハリを付け、カラースキームに沿ったアイコン色を活用
116
+ ## Font Awesomeアイコン活用ガイドライン
117
+ - 概念カテゴリー別の推奨アイコン:
118
+ - 時間・順序:fa-clock, fa-hourglass, fa-calendar, fa-timeline
119
+ - 場所・位置:fa-location-dot, fa-map, fa-compass, fa-globe
120
+ - 人物・組織:fa-user, fa-users, fa-building, fa-sitemap
121
+ - 行動・活動:fa-person-running, fa-gears, fa-hammer, fa-rocket
122
+ - 思考・アイデア:fa-brain, fa-lightbulb, fa-thought-bubble, fa-comments
123
+ - 感情・状態:fa-face-smile, fa-face-sad-tear, fa-heart, fa-temperature-half
124
+ - 成長・変化:fa-seedling, fa-arrow-trend-up, fa-chart-line, fa-diagram-project
125
+ - 問題・課題:fa-triangle-exclamation, fa-circle-question, fa-bug, fa-ban
126
+ - 解決・成功:fa-check, fa-trophy, fa-handshake, fa-key
127
+ - アイコンサイズの使い分け:
128
+ - 主要概念:3x(fa-3x)
129
+ - 重要キーワード:2x(fa-2x)
130
+ - 補足情報:1x(標準サイズ)
131
+ - 装飾的要素:lg(fa-lg)
132
+ - アニメーション効果の適切な使い分け:
133
+ - 注目喚起:fa-beat, fa-shake
134
+ - 継続的プロセス:fa-spin, fa-pulse
135
+ - 状態変化:fa-flip, fa-fade
136
+ - 新規情報:fa-bounce
137
+ ## 全体的な指針
138
+ - 読み手が自然に視線を移動できる配置(Font Awesomeアイコンで視線誘導)
139
+ - 情報の階層と関連性を視覚的に明確化(階層ごとにアイコンのサイズや色を変える)
140
+ - 手書き風の要素とFont Awesomeアイコンを組み合わせて親しみやすさとプロフェッショナル感を両立
141
+ - 大きなFont Awesomeアイコンを活用した視覚的な記憶に残るデザイン(各セクションに象徴的なアイコンを配置)
142
+ - フッターに出典情報と関連するFont Awesomeアイコン(fa-book, fa-citation等)を明記
143
+ ## 変換する文章/記事
144
+ ーーー<ユーザーが入力(または添付)>ーーー"""
145
+
146
+ # 実際のユーザー入力を指定
147
+ contents = [
148
+ types.Content(
149
+ role="user",
150
+ parts=[types.Part.from_text(text=text)]
151
+ )
152
+ ]
153
+
154
+ # 生成設定
155
+ generate_content_config = types.GenerateContentConfig(
156
+ response_mime_type="text/plain",
157
+ system_instruction=[types.Part.from_text(text=system_instruction)],
158
+ )
159
+
160
+ # HTMLを生成
161
+ logger.info(f"Gemini APIにリクエストを送信: テキスト長さ = {len(text)}")
162
+ response = client.models.generate_content(
163
+ model=model,
164
+ contents=contents,
165
+ config=generate_content_config,
166
+ )
167
+
168
+ # レスポンスからHTMLを抽出
169
+ raw_response = response.text
170
+
171
+ # HTMLタグ部分だけを抽出(```html と ``` の間)
172
+ html_start = raw_response.find("```html")
173
+ html_end = raw_response.rfind("```")
174
+
175
+ if html_start != -1 and html_end != -1 and html_start < html_end:
176
+ html_start += 7 # "```html" の長さ分進める
177
+ html_code = raw_response[html_start:html_end].strip()
178
+ logger.info(f"HTMLの生成に成功: 長さ = {len(html_code)}")
179
+ return html_code
180
+ else:
181
+ # HTMLタグが見つからない場合、レスポンス全体を返す
182
+ logger.warning("レスポンスから```html```タグが見つかりませんでした。全テキストを返します。")
183
+ return raw_response
184
+
185
+ except Exception as e:
186
+ logger.error(f"HTML生成中にエラーが発生: {e}", exc_info=True)
187
+ raise Exception(f"Gemini APIでのHTML生成に失敗しました: {e}")
188
+
189
  # --- Core Screenshot Logic ---
190
  def render_fullpage_screenshot(html_code: str, extension_percentage: float) -> Image.Image:
191
  """
 
317
  except Exception as e:
318
  logger.error(f"Error removing temporary file {tmp_path}: {e}")
319
 
320
+ # --- Geminiを使った新しい関数 ---
321
+ def text_to_screenshot(text: str, extension_percentage: float) -> Image.Image:
322
+ """テキストをGemini APIでHTMLに変換し、スクリーンショットを生成する統合関数"""
323
+ try:
324
+ # 1. テキストからHTMLを生成
325
+ html_code = generate_html_from_text(text)
326
+
327
+ # 2. HTMLからスクリーンショットを生成
328
+ return render_fullpage_screenshot(html_code, extension_percentage)
329
+ except Exception as e:
330
+ logger.error(f"テキストからスクリーンショット生成中にエラーが発生: {e}", exc_info=True)
331
+ return Image.new('RGB', (1, 1), color=(0, 0, 0)) # エラー時は黒画像
332
+
333
  # --- FastAPI Setup ---
334
  app = FastAPI()
335
 
 
412
  logger.error(f"API Error: {e}", exc_info=True)
413
  raise HTTPException(status_code=500, detail=f"Internal Server Error: {e}")
414
 
415
+ # --- 新しいGemini API連携エンドポイント ---
416
+ @app.post("/api/text-to-screenshot",
417
+ response_class=StreamingResponse,
418
+ tags=["Screenshot", "Gemini"],
419
+ summary="テキストからインフォグラフィックを生成",
420
+ description="テキストをGemini APIを使ってHTMLインフォグラフィックに変換し、スクリーンショットとして返します。")
421
+ async def api_text_to_screenshot(request: GeminiRequest):
422
+ """
423
+ テキストからHTMLインフォグラフィックを生成してスクリーンショットを返すAPIエンドポイント
424
+ """
425
+ try:
426
+ logger.info(f"テキスト→スクリーンショットAPIリクエスト受信。テキスト長さ: {len(request.text)}, 拡張率: {request.extension_percentage}%")
427
+
428
+ # テキストからHTMLを生成してスクリーンショットを作成
429
+ pil_image = text_to_screenshot(
430
+ request.text,
431
+ request.extension_percentage
432
+ )
433
+
434
+ if pil_image.size == (1, 1):
435
+ logger.error("スクリーンショット生成に失敗しました。1x1画像を返します。")
436
+ # raise HTTPException(status_code=500, detail="スクリーンショット生成に失敗しました")
437
+
438
+ # PIL画像をPNGバイトに変換
439
+ img_byte_arr = BytesIO()
440
+ pil_image.save(img_byte_arr, format='PNG')
441
+ img_byte_arr.seek(0) # BytesIOバッファの先頭に戻る
442
+
443
+ logger.info("スクリーンショットをPNGストリームとして返します。")
444
+ return StreamingResponse(img_byte_arr, media_type="image/png")
445
+
446
+ except Exception as e:
447
+ logger.error(f"API Error: {e}", exc_info=True)
448
+ raise HTTPException(status_code=500, detail=f"Internal Server Error: {e}")
449
+
450
  # --- Gradio Interface Definition ---
451
+ # 入力モードの選択用Radioコンポーネント
452
+ def process_input(input_mode, html_input, text_input, extension_percentage):
453
+ """入力モードに応じて適切な処理を行う"""
454
+ if input_mode == "HTML入力":
455
+ # HTMLモードの場合は既存の処理
456
+ return render_fullpage_screenshot(html_input, extension_percentage)
457
+ else:
458
+ # テキスト入力モードの場合はGemini APIを使用
459
+ return text_to_screenshot(text_input, extension_percentage)
460
+
461
+ # Gradio UIの定義
462
+ with gr.Blocks(title="Full Page Screenshot (テキスト変換対応)", theme=gr.themes.Base()) as iface:
463
+ gr.Markdown("# HTMLビューア & テキスト→インフォグラフィック変換")
464
+ gr.Markdown("HTMLをヘッドレスブラウザでレンダリングするか、テキストをGemini APIでインフォグラフィックに変換して画像として取得します。")
465
+
466
+ with gr.Row():
467
+ input_mode = gr.Radio(
468
+ ["HTML入力", "テキスト入力"],
469
+ label="��力モード",
470
+ value="HTML入力"
471
+ )
472
+
473
+ with gr.Tabs():
474
+ with gr.TabItem("HTML入力"):
475
+ html_input = gr.Textbox(
476
+ lines=15,
477
+ label="HTMLコード入力",
478
+ placeholder="<!DOCTYPE html>\n<html>\n<head>\n <title>Example</title>\n</head>\n<body>\n <h1>Hello World</h1>\n</body>\n</html>"
479
+ )
480
+
481
+ with gr.TabItem("テキスト入力"):
482
+ text_input = gr.Textbox(
483
+ lines=15,
484
+ label="テキスト入力 (Geminiで変換)",
485
+ placeholder="ここにテキストを入力すると、Gemini APIによってグラフィカルなHTMLに変換されます。"
486
+ )
487
+
488
+ extension_percentage = gr.Slider(
489
+ minimum=0,
490
+ maximum=20,
491
+ step=1.0,
492
+ value=8,
493
+ label="上下高さ拡張率(%)"
494
+ )
495
+
496
+ submit_btn = gr.Button("生成")
497
+ output_image = gr.Image(type="pil", label="ページ全体のスクリーンショット")
498
+
499
+ submit_btn.click(
500
+ fn=process_input,
501
+ inputs=[input_mode, html_input, text_input, extension_percentage],
502
+ outputs=output_image
503
+ )
504
+
505
+ gr.Markdown("""
506
+ ## APIエンドポイント
507
+ - `/api/screenshot` - HTMLコードからスクリーンショットを生成
508
+ - `/api/text-to-screenshot` - テキストからインフォグラフィックスクリーンショットを生成
509
+ """)
510
 
511
  # --- Mount Gradio App onto FastAPI ---
512
  app = gr.mount_gradio_app(app, iface, path="/")