tomo2chin2 commited on
Commit
b26e489
·
verified ·
1 Parent(s): 6b75d21

Create app.py

Browse files
Files changed (1) hide show
  1. app.py +47 -0
app.py ADDED
@@ -0,0 +1,47 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import gradio as gr
2
+ from selenium import webdriver
3
+ from selenium.common.exceptions import WebDriverException
4
+ from PIL import Image
5
+ from io import BytesIO
6
+ import tempfile, os
7
+
8
+ def render_html_to_image(html_code):
9
+ # 入力HTMLを一時ファイルに保存
10
+ tmp_file = tempfile.NamedTemporaryFile(suffix=".html", delete=False)
11
+ tmp_path = tmp_file.name
12
+ tmp_file.write(html_code.encode('utf-8'))
13
+ tmp_file.close()
14
+
15
+ # Chrome(Chromium)をヘッドレスモードで起動
16
+ options = webdriver.ChromeOptions()
17
+ options.add_argument('--headless') # ヘッドレス(画面非表示)モード
18
+ options.add_argument('--no-sandbox') # コンテナ環境でのサンドボックス無効化
19
+ options.add_argument('--disable-dev-shm-usage') # /dev/shm の共有メモリ領域を不使用
20
+ try:
21
+ driver = webdriver.Chrome(options=options)
22
+ driver.set_window_size(1200, 800) # ウィンドウサイズを適宜指定
23
+ # ローカルHTMLファイルを開く(file:// スキームを使用)
24
+ driver.get("file://" + tmp_path)
25
+ driver.implicitly_wait(3) # レンダリング待ち (最大3秒)
26
+ png = driver.get_screenshot_as_png()
27
+ except WebDriverException as e:
28
+ # 失敗時は1x1の透明画像を返すなどの処理
29
+ return Image.new('RGB', (1, 1), color=(0,0,0))
30
+ finally:
31
+ driver.quit()
32
+ if os.path.exists(tmp_path):
33
+ os.remove(tmp_path)
34
+ # PillowでPNGバイナリからImageオブジェクトを生成
35
+ return Image.open(BytesIO(png))
36
+
37
+ # Gradioインタフェースの定義
38
+ iface = gr.Interface(
39
+ fn=render_html_to_image,
40
+ inputs=gr.Textbox(lines=15, label="HTMLコード入力"),
41
+ outputs=gr.Image(type="pil", label="レンダリング結果のスクリーンショット"),
42
+ title="HTMLレンダリング Screenshot アプリ",
43
+ description="入力したHTMLをヘッドレスブラウザでレンダリングしてスクリーンショットを表示します。"
44
+ )
45
+
46
+ if __name__ == "__main__":
47
+ iface.launch()