tomo2chin2 commited on
Commit
10d0aca
·
verified ·
1 Parent(s): ac872fa

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +43 -765
app.py CHANGED
@@ -1,783 +1,61 @@
1
- import gradio as gr
2
- from fastapi import FastAPI, HTTPException, Body
3
- from fastapi.responses import StreamingResponse
4
- from fastapi.staticfiles import StaticFiles
5
- from fastapi.middleware.cors import CORSMiddleware
6
- from pydantic import BaseModel
7
- from selenium import webdriver
8
- from selenium.webdriver.chrome.options import Options
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
- from huggingface_hub import hf_hub_download # 追加: HuggingFace Hubからファイルを直接ダウンロード
19
-
20
- # 正しいGemini関連のインポート
21
- import google.generativeai as genai
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 = 10.0 # デフォルト値10%
32
- temperature: float = 0.5 # デフォルト値を0.5に設定
33
- trim_whitespace: bool = True # 余白トリミングオプション(デフォルト有効)
34
- style: str = "standard" # デフォルトはstandard
35
-
36
- class ScreenshotRequest(BaseModel):
37
- """スクリーンショットリクエストモデル"""
38
- html_code: str
39
- extension_percentage: float = 10.0 # デフォルト値10%
40
- trim_whitespace: bool = True # 余白トリミングオプション(デフォルト有効)
41
- style: str = "standard" # デフォルトはstandard
42
-
43
- # HTMLのFont Awesomeレイアウトを改善する関数
44
- def enhance_font_awesome_layout(html_code):
45
- """Font Awesomeレイアウトを改善するCSSを追加"""
46
- # CSSを追加
47
- fa_fix_css = """
48
- <style>
49
- /* Font Awesomeアイコンのレイアウト修正 */
50
- [class*="fa-"] {
51
- display: inline-block !important;
52
- margin-right: 8px !important;
53
- vertical-align: middle !important;
54
- }
55
-
56
- /* テキスト内のアイコン位置調整 */
57
- h1 [class*="fa-"], h2 [class*="fa-"], h3 [class*="fa-"],
58
- h4 [class*="fa-"], h5 [class*="fa-"], h6 [class*="fa-"] {
59
- vertical-align: middle !important;
60
- margin-right: 10px !important;
61
- }
62
-
63
- /* 特定パターンの修正 */
64
- .fa + span, .fas + span, .far + span, .fab + span,
65
- span + .fa, span + .fas, span + .far, span + .fab {
66
- display: inline-block !important;
67
- margin-left: 5px !important;
68
- }
69
-
70
- /* カード内アイコン修正 */
71
- .card [class*="fa-"], .card-body [class*="fa-"] {
72
- float: none !important;
73
- clear: none !important;
74
- position: relative !important;
75
- }
76
-
77
- /* アイコンと文字が重なる場合の調整 */
78
- li [class*="fa-"], p [class*="fa-"] {
79
- margin-right: 10px !important;
80
- }
81
-
82
- /* インラインアイコンのスペーシング */
83
- .inline-icon {
84
- display: inline-flex !important;
85
- align-items: center !important;
86
- justify-content: flex-start !important;
87
- }
88
-
89
- /* アイコン後のテキスト */
90
- [class*="fa-"] + span {
91
- display: inline-block !important;
92
- vertical-align: middle !important;
93
- }
94
- </style>
95
- """
96
-
97
- # headタグがある場合はその中に追加
98
- if '<head>' in html_code:
99
- return html_code.replace('</head>', f'{fa_fix_css}</head>')
100
- # HTMLタグがある場合はその後に追加
101
- elif '<html' in html_code:
102
- head_end = html_code.find('</head>')
103
- if head_end > 0:
104
- return html_code[:head_end] + fa_fix_css + html_code[head_end:]
105
- else:
106
- body_start = html_code.find('<body')
107
- if body_start > 0:
108
- return html_code[:body_start] + f'<head>{fa_fix_css}</head>' + html_code[body_start:]
109
-
110
- # どちらもない場合は先頭に追加
111
- return f'<html><head>{fa_fix_css}</head>' + html_code + '</html>'
112
-
113
- def load_system_instruction(style="standard"):
114
- """
115
- 指定されたスタイルのシステムインストラクションを読み込む
116
-
117
- Args:
118
- style: 使用するスタイル名 (standard, cute, resort, cool, dental)
119
-
120
- Returns:
121
- 読み込まれたシステムインストラクション
122
- """
123
- try:
124
- # 有効なスタイル一覧
125
- valid_styles = ["standard", "cute", "resort", "cool", "dental"]
126
-
127
- # スタイルの検証
128
- if style not in valid_styles:
129
- logger.warning(f"無効なスタイル '{style}' が指定されました。デフォルトの 'standard' を使用します。")
130
- style = "standard"
131
-
132
- logger.info(f"スタイル '{style}' のシステムインストラクションを読み込みます")
133
-
134
- # まず、ローカルのスタイルディレクトリ内のprompt.txtを確認
135
- local_path = os.path.join(os.path.dirname(__file__), style, "prompt.txt")
136
-
137
- # ローカルファイルが存在する場合はそれを使用
138
- if os.path.exists(local_path):
139
- logger.info(f"ローカルファイルを使用: {local_path}")
140
- with open(local_path, 'r', encoding='utf-8') as file:
141
- instruction = file.read()
142
- return instruction
143
-
144
- # HuggingFaceリポジトリからのファイル読み込みを試行
145
- try:
146
- # スタイル固有のファイルパスを指定
147
- file_path = hf_hub_download(
148
- repo_id="tomo2chin2/GURAREKOstlyle",
149
- filename=f"{style}/prompt.txt",
150
- repo_type="dataset"
151
- )
152
-
153
- logger.info(f"スタイル '{style}' のプロンプトをHuggingFaceから読み込みました: {file_path}")
154
- with open(file_path, 'r', encoding='utf-8') as file:
155
- instruction = file.read()
156
- return instruction
157
-
158
- except Exception as style_error:
159
- # スタイル固有ファイルの読み込みに失敗した場合、デフォルトのprompt.txtを使用
160
- logger.warning(f"スタイル '{style}' のプロンプト読み込みに失敗: {str(style_error)}")
161
- logger.info("デフォルトのprompt.txtを読み込みます")
162
-
163
- file_path = hf_hub_download(
164
- repo_id="tomo2chin2/GURAREKOstlyle",
165
- filename="prompt.txt",
166
- repo_type="dataset"
167
- )
168
-
169
- with open(file_path, 'r', encoding='utf-8') as file:
170
- instruction = file.read()
171
-
172
- logger.info("デフォルトのシステムインストラクションを読み込みました")
173
- return instruction
174
-
175
- except Exception as e:
176
- error_msg = f"システムインストラクションの読み込みに失敗: {str(e)}"
177
- logger.error(error_msg)
178
- raise ValueError(error_msg)
179
-
180
  def generate_html_from_text(text, temperature=0.3, style="standard"):
181
- """テキストからHTMLを生成する"""
182
  try:
183
- # APIキーの取得と設定
184
  api_key = os.environ.get("GEMINI_API_KEY")
185
  if not api_key:
186
- logger.error("GEMINI_API_KEY 環境変数が設定されていません")
187
  raise ValueError("GEMINI_API_KEY 環境変数が設定されていません")
188
-
189
- # モデル名の取得(環境変数から、なければデフォルト値)
190
  model_name = os.environ.get("GEMINI_MODEL", "gemini-1.5-pro")
191
  logger.info(f"使用するGeminiモデル: {model_name}")
192
-
193
- # Gemini APIの設定
194
  genai.configure(api_key=api_key)
195
-
196
- # 指定されたスタイルのシステムインストラクションを読み込む
197
  system_instruction = load_system_instruction(style)
198
-
199
- # モデル初期化
200
- logger.info(f"Gemini APIにリクエストを送信: テキスト長さ = {len(text)}, 温度 = {temperature}, スタイル = {style}")
201
-
202
- # モデル初期化
203
- model = genai.GenerativeModel(model_name)
204
-
205
- # 生成設定 - ばらつきを減らすために設定を調整
206
- generation_config = {
207
- "temperature": temperature, # より低い温度を設定
208
- "top_p": 0.7, # 0.95から0.7に下げて出力の多様性を制限
209
- "top_k": 20, # 64から20に下げて候補を絞る
210
  "max_output_tokens": 8192,
211
- "candidate_count": 1 # 候補は1つだけ生成
212
  }
213
-
214
- # 安全設定 - デフォルトの安全設定を使用
215
- safety_settings = [
216
- {
217
- "category": "HARM_CATEGORY_HARASSMENT",
218
- "threshold": "BLOCK_MEDIUM_AND_ABOVE"
219
- },
220
- {
221
- "category": "HARM_CATEGORY_HATE_SPEECH",
222
- "threshold": "BLOCK_MEDIUM_AND_ABOVE"
223
- },
224
- {
225
- "category": "HARM_CATEGORY_SEXUALLY_EXPLICIT",
226
- "threshold": "BLOCK_MEDIUM_AND_ABOVE"
227
- },
228
- {
229
- "category": "HARM_CATEGORY_DANGEROUS_CONTENT",
230
- "threshold": "BLOCK_MEDIUM_AND_ABOVE"
231
- }
232
- ]
233
-
234
- # プロンプト構築
235
- prompt = f"{system_instruction}\n\n{text}"
236
-
237
- # コンテンツ生成
238
- response = model.generate_content(
239
- prompt,
240
- generation_config=generation_config,
241
- safety_settings=safety_settings
242
- )
243
-
244
- # レスポンスからHTMLを抽出
245
- raw_response = response.text
246
-
247
- # HTMLタグ部分だけを抽出(
248
- html と
249
- の間)
250
- html_start = raw_response.find("
251
- html")
252
- html_end = raw_response.rfind("
253
- ")
254
-
255
- if html_start != -1 and html_end != -1 and html_start < html_end:
256
- html_start += 7 # "
257
- html" の長さ分進める
258
- html_code = raw_response[html_start:html_end].strip()
259
- logger.info(f"HTMLの生成に成功: 長さ = {len(html_code)}")
260
-
261
- # Font Awesomeのレイアウト改善
262
- html_code = enhance_font_awesome_layout(html_code)
263
- logger.info("Font Awesomeレイアウトの最適化を適用しました")
264
-
265
- return html_code
266
- else:
267
- # HTMLタグが見つからない場合、レスポンス全体を返す
268
- logger.warning("レスポンスから
269
- html
270
- タグが見つかりませんでした。全テキストを返します。")
271
- return raw_response
272
-
273
- except Exception as e:
274
- logger.error(f"HTML生成中にエラーが発生: {e}", exc_info=True)
275
- raise Exception(f"Gemini APIでのHTML生成に失敗しました: {e}")
276
-
277
- # 画像から余分な空白領域をトリミングする関数
278
- def trim_image_whitespace(image, threshold=250, padding=10):
279
- """
280
- 画像から余分な白い空白をトリミングする
281
-
282
- Args:
283
- image: PIL.Image - 入力画像
284
- threshold: int - どの明るさ以上を空白と判断するか (0-255)
285
- padding: int - トリミング後に残す余白のピクセル数
286
-
287
- Returns:
288
- トリミングされたPIL.Image
289
- """
290
- # グレースケールに変換
291
- gray = image.convert('L')
292
-
293
- # ピクセルデータを配列として取得
294
- data = gray.getdata()
295
- width, height = gray.size
296
-
297
- # 有効範囲を見つける
298
- min_x, min_y = width, height
299
- max_x = max_y = 0
300
-
301
- # ピクセルデータを2次元配列に変換して処理
302
- pixels = list(data)
303
- pixels = [pixels[i * width:(i + 1) * width] for i in range(height)]
304
-
305
- # 各行をスキャンして非空白ピクセルを見つける
306
- for y in range(height):
307
- for x in range(width):
308
- if pixels[y][x] < threshold: # 非空白ピクセル
309
- min_x = min(min_x, x)
310
- min_y = min(min_y, y)
311
- max_x = max(max_x, x)
312
- max_y = max(max_y, y)
313
-
314
- # 境界外のトリミングの場合はエラー
315
- if min_x > max_x or min_y > max_y:
316
- logger.warning("トリミング領域が見つかりません。元の画像を返します。")
317
- return image
318
-
319
- # パディングを追加
320
- min_x = max(0, min_x - padding)
321
- min_y = max(0, min_y - padding)
322
- max_x = min(width - 1, max_x + padding)
323
- max_y = min(height - 1, max_y + padding)
324
-
325
- # 画像をトリミング
326
- trimmed = image.crop((min_x, min_y, max_x + 1, max_y + 1))
327
-
328
- logger.info(f"画像をトリミングしました: 元サイズ {width}x{height} → トリミング後 {trimmed.width}x{trimmed.height}")
329
- return trimmed
330
-
331
- # 非同期スクリプトを使わず、同期的なスクリプトのみ使用する改善版
332
-
333
- def render_fullpage_screenshot(html_code: str, extension_percentage: float = 6.0,
334
- trim_whitespace: bool = True) -> Image.Image:
335
- """
336
- Renders HTML code to a full-page screenshot using Selenium.
337
-
338
- Args:
339
- html_code: The HTML source code string.
340
- extension_percentage: Percentage of extra space to add vertically.
341
- trim_whitespace: Whether to trim excess whitespace from the image.
342
-
343
- Returns:
344
- A PIL Image object of the screenshot.
345
- """
346
- tmp_path = None
347
- driver = None
348
-
349
- # 1) Save HTML code to a temporary file
350
- try:
351
- with tempfile.NamedTemporaryFile(suffix=".html", delete=False, mode='w', encoding='utf-8') as tmp_file:
352
- tmp_path = tmp_file.name
353
- tmp_file.write(html_code)
354
- logger.info(f"HTML saved to temporary file: {tmp_path}")
355
- except Exception as e:
356
- logger.error(f"Error writing temporary HTML file: {e}")
357
- return Image.new('RGB', (1, 1), color=(0, 0, 0))
358
-
359
- # 2) Headless Chrome(Chromium) options
360
- options = Options()
361
- options.add_argument("--headless")
362
- options.add_argument("--no-sandbox")
363
- options.add_argument("--disable-dev-shm-usage")
364
- options.add_argument("--force-device-scale-factor=1")
365
- options.add_argument("--disable-features=NetworkService")
366
- options.add_argument("--dns-prefetch-disable")
367
-
368
- try:
369
- logger.info("Initializing WebDriver...")
370
- driver = webdriver.Chrome(options=options)
371
- logger.info("WebDriver initialized.")
372
-
373
- # 3) 初期ウィンドウサイズを設定
374
- initial_width = 1200
375
- initial_height = 1000
376
- driver.set_window_size(initial_width, initial_height)
377
- file_url = "file://" + tmp_path
378
- logger.info(f"Navigating to {file_url}")
379
- driver.get(file_url)
380
-
381
- # 4) ページ読み込み待機
382
- logger.info("Waiting for body element...")
383
- WebDriverWait(driver, 15).until(
384
- EC.presence_of_element_located((By.TAG_NAME, "body"))
385
- )
386
- logger.info("Body element found. Waiting for resource loading...")
387
-
388
- # 5) 基本的なリソース読み込み待機 - タイムアウト回避
389
- time.sleep(3)
390
-
391
- # Font Awesome読み込み確認 - 非同期を使わない
392
- logger.info("Checking for Font Awesome resources...")
393
- fa_count = driver.execute_script("""
394
- var icons = document.querySelectorAll('.fa, .fas, .far, .fab, [class*="fa-"]');
395
- return icons.length;
396
- """)
397
- logger.info(f"Found {fa_count} Font Awesome elements")
398
-
399
- # リソース読み込み状態を確認
400
- doc_ready = driver.execute_script("return document.readyState;")
401
- logger.info(f"Document ready state: {doc_ready}")
402
-
403
- # Font Awesomeが多い場合は追加待機
404
- if fa_count > 50:
405
- logger.info("Many Font Awesome icons detected, waiting additional time")
406
- time.sleep(2)
407
-
408
- # 6) コンテンツレンダリングのためのスクロール処理 - 同期的に実行
409
- logger.info("Performing content rendering scroll...")
410
- total_height = driver.execute_script("return Math.max(document.body.scrollHeight, document.documentElement.scrollHeight);")
411
- viewport_height = driver.execute_script("return window.innerHeight;")
412
- scrolls_needed = max(1, total_height // viewport_height)
413
-
414
- for i in range(scrolls_needed + 1):
415
- scroll_pos = i * (viewport_height - 200) # オーバーラップさせる
416
- driver.execute_script(f"window.scrollTo(0, {scroll_pos});")
417
- time.sleep(0.2) # 短い待機
418
-
419
- # トップに戻る
420
- driver.execute_script("window.scrollTo(0, 0);")
421
- time.sleep(0.5)
422
- logger.info("Scroll rendering completed")
423
-
424
- # 7) スクロールバーを非表示に
425
- driver.execute_script("""
426
- document.documentElement.style.overflow = 'hidden';
427
- document.body.style.overflow = 'hidden';
428
- """)
429
- logger.info("Scrollbars hidden")
430
-
431
- # 8) ページの寸法を取得
432
- dimensions = driver.execute_script("""
433
- return {
434
- width: Math.max(
435
- document.documentElement.scrollWidth,
436
- document.documentElement.offsetWidth,
437
- document.documentElement.clientWidth,
438
- document.body ? document.body.scrollWidth : 0,
439
- document.body ? document.body.offsetWidth : 0,
440
- document.body ? document.body.clientWidth : 0
441
- ),
442
- height: Math.max(
443
- document.documentElement.scrollHeight,
444
- document.documentElement.offsetHeight,
445
- document.documentElement.clientHeight,
446
- document.body ? document.body.scrollHeight : 0,
447
- document.body ? document.body.offsetHeight : 0,
448
- document.body ? document.body.clientHeight : 0
449
- )
450
- };
451
- """)
452
- scroll_width = dimensions['width']
453
- scroll_height = dimensions['height']
454
- logger.info(f"Detected dimensions: width={scroll_width}, height={scroll_height}")
455
-
456
- # 再検証 - 短いスクロールで再確認
457
- driver.execute_script("window.scrollTo(0, document.body.scrollHeight);")
458
- time.sleep(0.5)
459
- driver.execute_script("window.scrollTo(0, 0);")
460
- time.sleep(0.5)
461
-
462
- dimensions_after = driver.execute_script("return {height: Math.max(document.documentElement.scrollHeight, document.body.scrollHeight)};")
463
- scroll_height = max(scroll_height, dimensions_after['height'])
464
- logger.info(f"After scroll check, height={scroll_height}")
465
-
466
- # 最小/最大値の設定
467
- scroll_width = max(scroll_width, 100)
468
- scroll_height = max(scroll_height, 100)
469
- scroll_width = min(scroll_width, 2000)
470
- scroll_height = min(scroll_height, 4000)
471
-
472
- # 9) レイアウト安定化のための単純な待機 - タイムアウト回避
473
- logger.info("Waiting for layout stabilization...")
474
- time.sleep(2)
475
-
476
- # 10) 高さに余白を追加
477
- adjusted_height = int(scroll_height * (1 + extension_percentage / 100.0))
478
- adjusted_height = max(adjusted_height, scroll_height, 100)
479
- logger.info(f"Adjusted height calculated: {adjusted_height} (extension: {extension_percentage}%)")
480
 
481
- # 11) ウィンドウサイズを調整
482
- adjusted_width = scroll_width
483
- logger.info(f"Resizing window to: width={adjusted_width}, height={adjusted_height}")
484
- driver.set_window_size(adjusted_width, adjusted_height)
485
- time.sleep(1)
486
-
487
- # リソース状態を確認 - 同期的スクリプト
488
- resource_state = driver.execute_script("""
489
- return {
490
- readyState: document.readyState,
491
- resourcesComplete: !document.querySelector('img:not([complete])') &&
492
- !document.querySelector('link[rel="stylesheet"]:not([loaded])')
493
- };
494
- """)
495
- logger.info(f"Resource state: {resource_state}")
496
-
497
- if resource_state['readyState'] != 'complete':
498
- logger.info("Document still loading, waiting additional time...")
499
- time.sleep(1)
500
-
501
- # トップにスクロール
502
- driver.execute_script("window.scrollTo(0, 0);")
503
- time.sleep(0.5)
504
- logger.info("Scrolled to top.")
505
-
506
- # 12) スクリーンショット取得
507
- logger.info("Taking screenshot...")
508
- png = driver.get_screenshot_as_png()
509
- logger.info("Screenshot taken successfully.")
510
-
511
- # PIL画像に変換
512
- img = Image.open(BytesIO(png))
513
- logger.info(f"Screenshot dimensions: {img.width}x{img.height}")
514
-
515
- # 余白トリミング
516
- if trim_whitespace:
517
- img = trim_image_whitespace(img, threshold=248, padding=20)
518
- logger.info(f"Trimmed dimensions: {img.width}x{img.height}")
519
-
520
- return img
521
-
522
- except Exception as e:
523
- logger.error(f"Error during screenshot generation: {e}")
524
- return Image.new('RGB', (1, 1), color=(0, 0, 0))
525
- finally:
526
- logger.info("Cleaning up...")
527
- if driver:
528
- try:
529
- driver.quit()
530
- logger.info("WebDriver quit successfully.")
531
- except Exception as e:
532
- logger.error(f"Error quitting WebDriver: {e}")
533
- if tmp_path and os.path.exists(tmp_path):
534
- try:
535
- os.remove(tmp_path)
536
- logger.info(f"Temporary file {tmp_path} removed.")
537
- except Exception as e:
538
- logger.error(f"Error removing temporary file {tmp_path}: {e}")
539
-
540
- # --- Geminiを使った新しい関数 ---
541
- def text_to_screenshot(text: str, extension_percentage: float, temperature: float = 0.3,
542
- trim_whitespace: bool = True, style: str = "standard") -> Image.Image:
543
- """テキストをGemini APIでHTMLに変換し、スクリーンショットを生成する統合関数"""
544
- try:
545
- # 1. テキストからHTMLを生成(温度パラメータとスタイルも渡す)
546
- html_code = generate_html_from_text(text, temperature, style)
547
-
548
- # 2. HTMLからスクリーンショットを生成
549
- return render_fullpage_screenshot(html_code, extension_percentage, trim_whitespace)
550
- except Exception as e:
551
- logger.error(f"テキストからスクリーンショット生成中にエラーが発生: {e}", exc_info=True)
552
- return Image.new('RGB', (1, 1), color=(0, 0, 0)) # エラー時は黒画像
553
-
554
- # --- FastAPI Setup ---
555
- app = FastAPI()
556
-
557
- # CORS設定を追加
558
- app.add_middleware(
559
- CORSMiddleware,
560
- allow_origins=["*"],
561
- allow_credentials=True,
562
- allow_methods=["*"],
563
- allow_headers=["*"],
564
- )
565
-
566
- # 静的ファイルのサービング設定
567
- # Gradioのディレクトリを探索してアセットを見つける
568
- gradio_dir = os.path.dirname(gr.__file__)
569
- logger.info(f"Gradio version: {gr.__version__}")
570
- logger.info(f"Gradio directory: {gradio_dir}")
571
-
572
- # 基本的な静的ファイルディレクトリをマウント
573
- static_dir = os.path.join(gradio_dir, "templates", "frontend", "static")
574
- if os.path.exists(static_dir):
575
- logger.info(f"Mounting static directory: {static_dir}")
576
- app.mount("/static", StaticFiles(directory=static_dir), name="static")
577
-
578
- # _appディレクトリを探す(新しいSvelteKitベースのフロントエンド用)
579
- app_dir = os.path.join(gradio_dir, "templates", "frontend", "_app")
580
- if os.path.exists(app_dir):
581
- logger.info(f"Mounting _app directory: {app_dir}")
582
- app.mount("/_app", StaticFiles(directory=app_dir), name="_app")
583
-
584
- # assetsディレクトリを探す
585
- assets_dir = os.path.join(gradio_dir, "templates", "frontend", "assets")
586
- if os.path.exists(assets_dir):
587
- logger.info(f"Mounting assets directory: {assets_dir}")
588
- app.mount("/assets", StaticFiles(directory=assets_dir), name="assets")
589
-
590
- # cdnディレクトリがあれば追加
591
- cdn_dir = os.path.join(gradio_dir, "templates", "cdn")
592
- if os.path.exists(cdn_dir):
593
- logger.info(f"Mounting cdn directory: {cdn_dir}")
594
- app.mount("/cdn", StaticFiles(directory=cdn_dir), name="cdn")
595
-
596
- # API Endpoint for screenshot generation
597
- @app.post("/api/screenshot",
598
- response_class=StreamingResponse,
599
- tags=["Screenshot"],
600
- summary="Render HTML to Full Page Screenshot",
601
- 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.")
602
- async def api_render_screenshot(request: ScreenshotRequest):
603
- """
604
- API endpoint to render HTML and return a screenshot.
605
- """
606
- try:
607
- logger.info(f"API request received. Extension: {request.extension_percentage}%")
608
- # Run the blocking Selenium code in a separate thread (FastAPI handles this)
609
- pil_image = render_fullpage_screenshot(
610
- request.html_code,
611
- request.extension_percentage,
612
- request.trim_whitespace
613
- )
614
-
615
- if pil_image.size == (1, 1):
616
- logger.error("Screenshot generation failed, returning 1x1 image.")
617
- # Optionally return a proper error response instead of 1x1 image
618
- # raise HTTPException(status_code=500, detail="Failed to generate screenshot")
619
-
620
- # Convert PIL Image to PNG bytes
621
- img_byte_arr = BytesIO()
622
- pil_image.save(img_byte_arr, format='PNG')
623
- img_byte_arr.seek(0) # Go to the start of the BytesIO buffer
624
-
625
- logger.info("Returning screenshot as PNG stream.")
626
- return StreamingResponse(img_byte_arr, media_type="image/png")
627
 
628
- except Exception as e:
629
- logger.error(f"API Error: {e}", exc_info=True)
630
- raise HTTPException(status_code=500, detail=f"Internal Server Error: {e}")
631
 
632
- # --- 新しいGemini API連携エンドポイント ---
633
- @app.post("/api/text-to-screenshot",
634
- response_class=StreamingResponse,
635
- tags=["Screenshot", "Gemini"],
636
- summary="テキストからインフォグラフィックを生成",
637
- description="テキストをGemini APIを使ってHTMLインフォグラフィックに変換し、スクリーンショットとして返します。")
638
- async def api_text_to_screenshot(request: GeminiRequest):
639
- """
640
- テキストからHTMLインフォグラフィックを生成してスクリーンショットを返すAPIエンドポイント
641
- """
642
- try:
643
- logger.info(f"テキスト→スクリーンショットAPIリクエスト受信。テキスト長さ: {len(request.text)}, "
644
- f"拡張率: {request.extension_percentage}%, 温度: {request.temperature}, "
645
- f"スタイル: {request.style}")
646
-
647
- # テキストからHTMLを生成してスクリーンショットを作成(温度パラメータとスタイルも渡す)
648
- pil_image = text_to_screenshot(
649
- request.text,
650
- request.extension_percentage,
651
- request.temperature,
652
- request.trim_whitespace,
653
- request.style
654
  )
655
 
656
- if pil_image.size == (1, 1):
657
- logger.error("スクリーンショット生成に失敗しました。1x1画像を返します。")
658
- # raise HTTPException(status_code=500, detail="スクリーンショット生成に失敗しました")
659
-
660
- # PIL画像をPNGバイトに変換
661
- img_byte_arr = BytesIO()
662
- pil_image.save(img_byte_arr, format='PNG')
663
- img_byte_arr.seek(0) # BytesIOバッファの先頭に戻る
664
-
665
- logger.info("スクリーンショットをPNGストリームとして返します。")
666
- return StreamingResponse(img_byte_arr, media_type="image/png")
667
 
668
  except Exception as e:
669
- logger.error(f"API Error: {e}", exc_info=True)
670
- raise HTTPException(status_code=500, detail=f"Internal Server Error: {e}")
671
-
672
- # --- Gradio Interface Definition ---
673
- # 入力モードの選択用Radioコンポーネント
674
- def process_input(input_mode, input_text, extension_percentage, temperature, trim_whitespace, style):
675
- """入力モードに応じて適切な処理を行う"""
676
- if input_mode == "HTML入力":
677
- # HTMLモードの場合は既存の処理(スタイルは使わない)
678
- return render_fullpage_screenshot(input_text, extension_percentage, trim_whitespace)
679
- else:
680
- # テキスト入力モードの場合はGemini APIを使用
681
- return text_to_screenshot(input_text, extension_percentage, temperature, trim_whitespace, style)
682
-
683
- # Gradio UIの定義
684
- with gr.Blocks(title="Full Page Screenshot (テキスト変換対応)", theme=gr.themes.Base()) as iface:
685
- gr.Markdown("# HTMLビューア & テキスト→インフォグラフィック変換")
686
- gr.Markdown("HTMLコードをレンダリングするか、テキストをGemini APIでインフォグラフィックに変換して画像として取得します。")
687
-
688
- with gr.Row():
689
- input_mode = gr.Radio(
690
- ["HTML入力", "テキスト入力"],
691
- label="入力モード",
692
- value="HTML入力"
693
- )
694
-
695
- # 共用のテキストボックス
696
- input_text = gr.Textbox(
697
- lines=15,
698
- label="入力",
699
- placeholder="HTMLコードまたはテキストを入力してください。入力モードに応じて処理されます。"
700
- )
701
-
702
- with gr.Row():
703
- with gr.Column(scale=1):
704
- # スタイル選択ドロップダウン
705
- style_dropdown = gr.Dropdown(
706
- choices=["standard", "cute", "resort", "cool", "dental"],
707
- value="standard",
708
- label="デザインスタイル",
709
- info="テキスト→HTML変換時のデザインテーマを選択します",
710
- visible=False # テキスト入力モードの時だけ表示
711
- )
712
-
713
- with gr.Column(scale=2):
714
- extension_percentage = gr.Slider(
715
- minimum=0,
716
- maximum=30,
717
- step=1.0,
718
- value=10, # デフォルト値10%
719
- label="上下高さ拡張率(%)"
720
- )
721
-
722
- # 温度調整スライダー(テキストモード時のみ表示)
723
- temperature = gr.Slider(
724
- minimum=0.0,
725
- maximum=1.0,
726
- step=0.1,
727
- value=0.5, # デフォルト値を0.5に設定
728
- label="生成時の温度(低い=一貫性高、高い=創造性高)",
729
- visible=False # 最初は非表示
730
- )
731
-
732
- # 余白トリミングオプション
733
- trim_whitespace = gr.Checkbox(
734
- label="余白を自動トリミング",
735
- value=True,
736
- info="生成される画像から余分な空白領域を自動的に削除します"
737
- )
738
-
739
- submit_btn = gr.Button("生成")
740
- output_image = gr.Image(type="pil", label="ページ全体のスクリーンショット")
741
-
742
- # 入力モード変更時のイベント処理(テキストモード時のみ温度スライダーとスタイルドロップダウンを表示)
743
- def update_controls_visibility(mode):
744
- # Gradio 4.x用のアップデート方法
745
- is_text_mode = mode == "テキスト入力"
746
- return [
747
- {"visible": is_text_mode, "__type__": "update"}, # temperature
748
- {"visible": is_text_mode, "__type__": "update"}, # style_dropdown
749
- ]
750
-
751
- input_mode.change(
752
- fn=update_controls_visibility,
753
- inputs=input_mode,
754
- outputs=[temperature, style_dropdown]
755
- )
756
-
757
- # 生成ボタンクリック時のイベント処理
758
- submit_btn.click(
759
- fn=process_input,
760
- inputs=[input_mode, input_text, extension_percentage, temperature, trim_whitespace, style_dropdown],
761
- outputs=output_image
762
- )
763
-
764
- # 環境変数情報を表示
765
- gemini_model = os.environ.get("GEMINI_MODEL", "gemini-1.5-pro")
766
- gr.Markdown(f"""
767
- ## APIエンドポイント
768
- - `/api/screenshot` - HTMLコードからスクリーンショットを生成
769
- - `/api/text-to-screenshot` - テキストからインフォグラフィックスクリーンショットを生成
770
-
771
- ## 設定情報
772
- - 使用モデル: {gemini_model} (環境変数 GEMINI_MODEL で変更可能)
773
- - 対応スタイル: standard, cute, resort, cool, dental
774
- """)
775
-
776
- # --- Mount Gradio App onto FastAPI ---
777
- app = gr.mount_gradio_app(app, iface, path="/")
778
-
779
- # --- Run with Uvicorn (for local testing) ---
780
- if __name__ == "__main__":
781
- import uvicorn
782
- logger.info("Starting Uvicorn server for local development...")
783
- uvicorn.run(app, host="0.0.0.0", port=7860)
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
  def generate_html_from_text(text, temperature=0.3, style="standard"):
2
+ """テキストからHTMLを生成して返す"""
3
  try:
 
4
  api_key = os.environ.get("GEMINI_API_KEY")
5
  if not api_key:
 
6
  raise ValueError("GEMINI_API_KEY 環境変数が設定されていません")
7
+
 
8
  model_name = os.environ.get("GEMINI_MODEL", "gemini-1.5-pro")
9
  logger.info(f"使用するGeminiモデル: {model_name}")
 
 
10
  genai.configure(api_key=api_key)
11
+
 
12
  system_instruction = load_system_instruction(style)
13
+
14
+ # --- 共通の生成パラメータ ---
15
+ base_cfg = {
16
+ "temperature": temperature,
17
+ "top_p": 0.7,
18
+ "top_k": 20,
 
 
 
 
 
 
19
  "max_output_tokens": 8192,
20
+ "candidate_count": 1,
21
  }
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
22
 
23
+ # --- 2.5 Flash だけ thinking_budget=0 を追加 ---
24
+ if model_name == "gemini-2.5-flash-preview-04-17":
25
+ logger.info("thinking_budget=0 を設定します")
26
+ cfg = genai.types.GenerateContentConfig(
27
+ **base_cfg,
28
+ thinking_config=genai.types.ThinkingConfig(thinking_budget=0)
29
+ )
30
+ else:
31
+ cfg = genai.types.GenerateContentConfig(**base_cfg)
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
32
 
33
+ model = genai.GenerativeModel(model_name)
34
+ prompt = f"{system_instruction}\n\n{text}"
 
35
 
36
+ response = model.generate_content(
37
+ prompt,
38
+ config=cfg,
39
+ safety_settings=[
40
+ {"category": "HARM_CATEGORY_HARASSMENT", "threshold": "BLOCK_MEDIUM_AND_ABOVE"},
41
+ {"category": "HARM_CATEGORY_HATE_SPEECH", "threshold": "BLOCK_MEDIUM_AND_ABOVE"},
42
+ {"category": "HARM_CATEGORY_SEXUALLY_EXPLICIT", "threshold": "BLOCK_MEDIUM_AND_ABOVE"},
43
+ {"category": "HARM_CATEGORY_DANGEROUS_CONTENT", "threshold": "BLOCK_MEDIUM_AND_ABOVE"},
44
+ ],
 
 
 
 
 
 
 
 
 
 
 
 
 
45
  )
46
 
47
+ # --- レスポンス処理は元コードと同じ ---
48
+ raw = response.text
49
+ start = raw.find("```html")
50
+ end = raw.rfind("```")
51
+ if start != -1 and end != -1 and start < end:
52
+ html = raw[start + 7:end].strip()
53
+ html = enhance_font_awesome_layout(html)
54
+ return html
55
+ else:
56
+ logger.warning("```html``` タグが見つからず。全文を返します")
57
+ return raw
58
 
59
  except Exception as e:
60
+ logger.error(f"HTML生成中にエラー: {e}", exc_info=True)
61
+ raise Exception(f"Gemini APIでのHTML生成に失敗しました: {e}")