tomo2chin2 commited on
Commit
03a6dcc
·
verified ·
1 Parent(s): b06f6d3

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +198 -713
app.py CHANGED
@@ -1,5 +1,5 @@
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
@@ -15,776 +15,261 @@ 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 {
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タグ部分だけを抽出(```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=["*"],
566
- allow_credentials=True,
567
- allow_methods=["*"],
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,
657
- request.temperature,
658
- request.trim_whitespace,
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
  import gradio as gr
2
+ from fastapi import FastAPI, HTTPException
3
  from fastapi.responses import StreamingResponse
4
  from fastapi.staticfiles import StaticFiles
5
  from fastapi.middleware.cors import CORSMiddleware
 
15
  import time
16
  import os
17
  import logging
18
+ from huggingface_hub import hf_hub_download
19
 
20
+ # --- Gemini SDK (v1.x) ---------------------------------
21
+ from google import genai
22
+ from google.genai import types
23
+ # -------------------------------------------------------
24
 
25
  # ロギング設定
26
  logging.basicConfig(level=logging.INFO)
27
  logger = logging.getLogger(__name__)
28
 
29
+ # ---------- データモデル ----------
30
  class GeminiRequest(BaseModel):
 
31
  text: str
32
+ extension_percentage: float = 10.0
33
+ temperature: float = 0.5
34
+ trim_whitespace: bool = True
35
+ style: str = "standard"
36
 
37
  class ScreenshotRequest(BaseModel):
 
38
  html_code: str
39
+ extension_percentage: float = 10.0
40
+ trim_whitespace: bool = True
41
+ style: str = "standard"
42
 
43
+ # ---------- ユーティリティ ----------
44
  def enhance_font_awesome_layout(html_code):
 
 
45
  fa_fix_css = """
46
  <style>
47
+ [class*="fa-"]{display:inline-block!important;margin-right:8px!important;vertical-align:middle!important;}
48
+ h1 [class*="fa-"],h2 [class*="fa-"],h3 [class*="fa-"],h4 [class*="fa-"],h5 [class*="fa-"],h6 [class*="fa-"]{
49
+ vertical-align:middle!important;margin-right:10px!important;}
50
+ .fa+span,.fas+span,.far+span,.fab+span,span+.fa,span+.fas,span+.far,span+.fab{
51
+ display:inline-block!important;margin-left:5px!important;}
52
+ .card [class*="fa-"],.card-body [class*="fa-"]{float:none!important;clear:none!important;position:relative!important;}
53
+ li [class*="fa-"],p [class*="fa-"]{margin-right:10px!important;}
54
+ .inline-icon{display:inline-flex!important;align-items:center!important;justify-content:flex-start!important;}
55
+ [class*="fa-"]+span{display:inline-block!important;vertical-align:middle!important;}
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
56
  </style>
57
  """
 
 
58
  if '<head>' in html_code:
59
  return html_code.replace('</head>', f'{fa_fix_css}</head>')
 
60
  elif '<html' in html_code:
61
  head_end = html_code.find('</head>')
62
  if head_end > 0:
63
  return html_code[:head_end] + fa_fix_css + html_code[head_end:]
64
+ body_start = html_code.find('<body')
65
+ if body_start > 0:
66
+ return html_code[:body_start] + f'<head>{fa_fix_css}</head>' + html_code[body_start:]
 
 
 
67
  return f'<html><head>{fa_fix_css}</head>' + html_code + '</html>'
68
 
69
  def load_system_instruction(style="standard"):
70
+ valid_styles = ["standard", "cute", "resort", "cool", "dental"]
71
+ if style not in valid_styles:
72
+ logger.warning(f"無効なスタイル '{style}'。'standard' を使用")
73
+ style = "standard"
74
+ local_path = os.path.join(os.path.dirname(__file__), style, "prompt.txt")
75
+ if os.path.exists(local_path):
76
+ with open(local_path, encoding="utf-8") as f:
77
+ return f.read()
 
78
  try:
79
+ file_path = hf_hub_download(
80
+ repo_id="tomo2chin2/GURAREKOstlyle",
81
+ filename=f"{style}/prompt.txt",
82
+ repo_type="dataset"
83
+ )
84
+ with open(file_path, encoding="utf-8") as f:
85
+ return f.read()
86
+ except Exception:
87
+ file_path = hf_hub_download(
88
+ repo_id="tomo2chin2/GURAREKOstlyle",
89
+ filename="prompt.txt",
90
+ repo_type="dataset"
91
+ )
92
+ with open(file_path, encoding="utf-8") as f:
93
+ return f.read()
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
94
 
95
+ # ---------- Gemini HTML 生成 ----------
96
  def generate_html_from_text(text, temperature=0.3, style="standard"):
97
+ """Gemini で HTML を生成。2.5 Flash Preview の場合は thinking_off"""
98
+ api_key = os.environ.get("GEMINI_API_KEY")
99
+ if not api_key:
100
+ raise ValueError("GEMINI_API_KEY が未設定")
101
+ model_name = os.environ.get("GEMINI_MODEL", "gemini-1.5-pro")
102
+
103
+ client = genai.Client(api_key=api_key)
104
+ system_instruction = load_system_instruction(style)
105
+ prompt = f"{system_instruction}\n\n{text}"
106
+
107
+ safety_settings = [
108
+ {"category": "HARM_CATEGORY_HARASSMENT", "threshold": "BLOCK_MEDIUM_AND_ABOVE"},
109
+ {"category": "HARM_CATEGORY_HATE_SPEECH", "threshold": "BLOCK_MEDIUM_AND_ABOVE"},
110
+ {"category": "HARM_CATEGORY_SEXUALLY_EXPLICIT", "threshold": "BLOCK_MEDIUM_AND_ABOVE"},
111
+ {"category": "HARM_CATEGORY_DANGEROUS_CONTENT", "threshold": "BLOCK_MEDIUM_AND_ABOVE"},
112
+ ]
113
+
114
+ # ---- モデル分岐 ----
115
+ if model_name == "gemini-2.5-flash-preview-04-17":
116
+ generation_cfg = types.GenerateContentConfig(
117
+ temperature=temperature,
118
+ top_p=0.7,
119
+ top_k=20,
120
+ max_output_tokens=8192,
121
+ candidate_count=1,
122
+ thinking_config=types.ThinkingConfig(thinking_budget=0) # thinking OFF
123
+ )
124
+ else:
125
+ generation_cfg = types.GenerateContentConfig(
126
+ temperature=temperature,
127
+ top_p=0.7,
128
+ top_k=20,
129
+ max_output_tokens=8192,
130
+ candidate_count=1,
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
131
  )
132
 
133
+ response = client.models.generate_content(
134
+ model=model_name,
135
+ contents=prompt,
136
+ config=generation_cfg,
137
+ safety_settings=safety_settings
138
+ )
139
+ raw = response.text
140
+
141
+ # ```html ... ``` 抽出
142
+ start = raw.find("```html")
143
+ end = raw.rfind("```")
144
+ if start != -1 and end != -1 and start < end:
145
+ html_code = raw[start + 7:end].strip()
146
+ return enhance_font_awesome_layout(html_code)
147
+ logger.warning("```html``` ブロックが見つからず全文返却")
148
+ return raw
149
+
150
+ # ---------- 画像トリミング ----------
 
 
 
 
 
 
 
 
 
151
  def trim_image_whitespace(image, threshold=250, padding=10):
152
+ gray = image.convert("L")
153
+ data = list(gray.getdata())
154
+ w, h = gray.size
155
+ pixels = [data[i * w:(i + 1) * w] for i in range(h)]
156
+ min_x, min_y, max_x, max_y = w, h, 0, 0
157
+ for y in range(h):
158
+ for x in range(w):
159
+ if pixels[y][x] < threshold:
160
+ min_x, min_y = min(min_x, x), min(min_y, y)
161
+ max_x, max_y = max(max_x, x), max(max_y, y)
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
162
  if min_x > max_x or min_y > max_y:
 
163
  return image
 
 
164
  min_x = max(0, min_x - padding)
165
  min_y = max(0, min_y - padding)
166
+ max_x = min(w - 1, max_x + padding)
167
+ max_y = min(h - 1, max_y + padding)
168
+ return image.crop((min_x, min_y, max_x + 1, max_y + 1))
 
 
 
 
 
 
 
169
 
170
+ # ---------- HTML スクリーンショット(Selenium) ----------
171
+ def render_fullpage_screenshot(html_code, extension_percentage=6.0, trim_whitespace=True):
172
+ tmp_path, driver = None, None
 
 
 
 
 
 
 
 
 
 
 
 
 
 
173
  try:
174
+ with tempfile.NamedTemporaryFile(suffix=".html", delete=False, mode="w", encoding="utf-8") as f:
175
+ tmp_path = f.name
176
+ f.write(html_code)
177
+ options = Options()
178
+ options.add_argument("--headless")
179
+ options.add_argument("--no-sandbox")
180
+ options.add_argument("--disable-dev-shm-usage")
181
+ driver = webdriver.Chrome(options=options)
182
+ driver.set_window_size(1200, 1000)
183
+ driver.get("file://" + tmp_path)
184
+ WebDriverWait(driver, 15).until(EC.presence_of_element_located((By.TAG_NAME, "body")))
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
185
  time.sleep(3)
186
 
187
+ total_height = driver.execute_script("return Math.max(document.body.scrollHeight, document.documentElement.scrollHeight)")
188
+ viewport = driver.execute_script("return window.innerHeight")
189
+ for i in range(max(1, total_height // viewport) + 1):
190
+ driver.execute_script(f"window.scrollTo(0, {i * (viewport - 200)})")
191
+ time.sleep(0.2)
192
+ driver.execute_script("window.scrollTo(0, 0)")
193
+ driver.execute_script("document.documentElement.style.overflow='hidden';document.body.style.overflow='hidden'")
194
+ dims = driver.execute_script("return {w:document.documentElement.scrollWidth,h:document.documentElement.scrollHeight}")
195
+ driver.set_window_size(dims["w"], int(dims["h"] * (1 + extension_percentage / 100)))
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
196
  time.sleep(1)
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
197
  png = driver.get_screenshot_as_png()
 
 
 
198
  img = Image.open(BytesIO(png))
199
+ return trim_image_whitespace(img, 248, 20) if trim_whitespace else img
 
 
 
 
 
 
 
 
200
  except Exception as e:
201
+ logger.error(f"Selenium error: {e}", exc_info=True)
202
+ return Image.new("RGB", (1, 1))
 
203
  finally:
 
204
  if driver:
205
+ driver.quit()
 
 
 
 
206
  if tmp_path and os.path.exists(tmp_path):
207
+ os.remove(tmp_path)
 
 
 
 
208
 
209
+ # ---------- 統合 ----------
210
+ def text_to_screenshot(text, ext, temp=0.3, trim=True, style="standard"):
211
+ html = generate_html_from_text(text, temp, style)
212
+ return render_fullpage_screenshot(html, ext, trim)
 
 
 
 
 
 
 
 
 
213
 
214
+ # ---------- FastAPI ----------
215
  app = FastAPI()
 
 
216
  app.add_middleware(
217
  CORSMiddleware,
218
+ allow_origins=["*"], allow_credentials=True,
219
+ allow_methods=["*"], allow_headers=["*"],
 
 
220
  )
221
 
222
+ # Gradio 静的ファイル
 
223
  gradio_dir = os.path.dirname(gr.__file__)
224
+ app.mount("/static", StaticFiles(directory=os.path.join(gradio_dir, "templates/frontend/static")), name="static")
225
+
226
+ # ---------- API ----------
227
+ @app.post("/api/screenshot", response_class=StreamingResponse)
228
+ async def api_render(req: ScreenshotRequest):
229
+ img = render_fullpage_screenshot(req.html_code, req.extension_percentage, req.trim_whitespace)
230
+ buf = BytesIO()
231
+ img.save(buf, format="PNG")
232
+ buf.seek(0)
233
+ return StreamingResponse(buf, media_type="image/png")
234
+
235
+ @app.post("/api/text-to-screenshot", response_class=StreamingResponse)
236
+ async def api_text_screenshot(req: GeminiRequest):
237
+ img = text_to_screenshot(req.text, req.extension_percentage, req.temperature, req.trim_whitespace, req.style)
238
+ buf = BytesIO()
239
+ img.save(buf, format="PNG")
240
+ buf.seek(0)
241
+ return StreamingResponse(buf, media_type="image/png")
242
+
243
+ # ---------- Gradio ----------
244
+ def process_input(mode, txt, ext, temp, trim, style):
245
+ if mode == "HTML入力":
246
+ return render_fullpage_screenshot(txt, ext, trim)
247
+ return text_to_screenshot(txt, ext, temp, trim, style)
248
+
249
+ with gr.Blocks(title="HTML Viewer & Gemini 2.5 Flash Demo", theme=gr.themes.Base()) as iface:
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
250
  gr.Markdown("# HTMLビューア & テキスト→インフォグラフィック変換")
251
+ input_mode = gr.Radio(["HTML入力", "テキスト入力"], value="HTML入力", label="入力モード")
252
+ input_text = gr.Textbox(lines=15, label="入力")
253
+ style_dd = gr.Dropdown(["standard", "cute", "resort", "cool", "dental"], value="standard", label="デザインスタイル", visible=False)
254
+ ext_slider = gr.Slider(0, 30, value=10, step=1, label="上下高さ拡張率(%)")
255
+ temp_slider = gr.Slider(0.0, 1.0, value=0.5, step=0.1, label="生成時の温度", visible=False)
256
+ trim_cb = gr.Checkbox(value=True, label="余白を自動トリミング")
257
+ out_img = gr.Image(type="pil", label="スクリーンショット")
258
+ gen_btn = gr.Button("生成")
259
+
260
+ def toggle(mode):
261
+ show = mode == "テキスト入力"
262
+ return [{"visible": show, "__type__": "update"}, {"visible": show, "__type__": "update"}]
263
+ input_mode.change(toggle, input_mode, [temp_slider, style_dd])
264
+ gen_btn.click(process_input, [input_mode, input_text, ext_slider, temp_slider, trim_cb, style_dd], out_img)
265
+
266
+ iface.markdown(f"""
267
+ **使用モデル**: `{os.environ.get("GEMINI_MODEL", "gemini-1.5-pro")}`
268
+ **API**: `/api/screenshot`, `/api/text-to-screenshot`
269
+ """)
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
270
 
 
271
  app = gr.mount_gradio_app(app, iface, path="/")
272
 
 
273
  if __name__ == "__main__":
274
  import uvicorn
275
+ uvicorn.run(app, host="0.0.0.0", port=7860)