tomo2chin2 commited on
Commit
7215bb7
·
verified ·
1 Parent(s): 36e642f

Update app.py

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