tomo2chin2 commited on
Commit
b2e8a66
·
verified ·
1 Parent(s): 45b1af9

Upload 3 files

Browse files
Files changed (3) hide show
  1. README.md +1 -1
  2. app.py +749 -185
  3. requirements.txt +8 -7
README.md CHANGED
@@ -4,7 +4,7 @@ emoji: 🏢
4
  colorFrom: purple
5
  colorTo: yellow
6
  sdk: gradio
7
- sdk_version: 5.25.2
8
  app_file: app.py
9
  pinned: true
10
  ---
 
4
  colorFrom: purple
5
  colorTo: yellow
6
  sdk: gradio
7
+ sdk_version: 4.19.2
8
  app_file: app.py
9
  pinned: true
10
  ---
app.py CHANGED
@@ -1,5 +1,5 @@
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
@@ -11,216 +11,780 @@ from selenium.webdriver.support.ui import WebDriverWait
11
  from selenium.webdriver.support import expected_conditions as EC
12
  from PIL import Image
13
  from io import BytesIO
14
- import tempfile, time, os, logging
15
- from huggingface_hub import hf_hub_download
 
 
 
16
 
17
- # ---------- Gemini SDK (v1.x) ----------
18
- from google import genai # :contentReference[oaicite:4]{index=4}
19
- from google.genai import types
20
- # ---------------------------------------
21
 
 
22
  logging.basicConfig(level=logging.INFO)
23
  logger = logging.getLogger(__name__)
24
 
25
- # ---------- Pydantic モデル ----------
26
  class GeminiRequest(BaseModel):
 
27
  text: str
28
- extension_percentage: float = 10.0
29
- temperature: float = 0.5
30
- trim_whitespace: bool = True
31
- style: str = "standard"
32
 
33
  class ScreenshotRequest(BaseModel):
 
34
  html_code: str
35
- extension_percentage: float = 10.0
36
- trim_whitespace: bool = True
37
- # --------------------------------------
38
-
39
- # ---------- ユーティリティ ----------
40
- def enhance_font_awesome_layout(html_code: str) -> str:
41
- fix_css = """
42
- <style>[class*="fa-"]{display:inline-block!important;margin-right:8px!important;vertical-align:middle!important;}
43
- h1 [class*="fa-"],h2 [class*="fa-"],h3 [class*="fa-"],h4 [class*="fa-"],h5 [class*="fa-"],h6 [class*="fa-"]{
44
- vertical-align:middle!important;margin-right:10px!important;}
45
- .fa+span,.fas+span,.far+span,.fab+span,span+.fa,span+.fas,span+.far,span+.fab{
46
- display:inline-block!important;margin-left:5px!important;}
47
- li [class*="fa-"],p [class*="fa-"]{margin-right:10px!important;}</style>"""
48
- if "<head>" in html_code:
49
- return html_code.replace("</head>", f"{fix_css}</head>")
50
- return f"<html><head>{fix_css}</head>{html_code}</html>"
51
-
52
- def load_system_instruction(style="standard") -> str:
53
- styles = ["standard", "cute", "resort", "cool", "dental"]
54
- if style not in styles:
55
- style = "standard"
56
- local = os.path.join(os.path.dirname(__file__), style, "prompt.txt")
57
- if os.path.exists(local):
58
- with open(local, encoding="utf-8") as f:
59
- return f.read()
60
- # HF fallback
61
- file_path = hf_hub_download(
62
- repo_id="tomo2chin2/GURAREKOstlyle",
63
- filename=f"{style}/prompt.txt" if style != "standard" else "prompt.txt",
64
- repo_type="dataset"
65
- )
66
- with open(file_path, encoding="utf-8") as f:
67
- return f.read()
68
- # --------------------------------------
69
-
70
- # ---------- Gemini → HTML ----------
71
- def generate_html_from_text(text, temperature=0.3, style="standard") -> str:
72
- api_key = os.getenv("GEMINI_API_KEY")
73
- if not api_key:
74
- raise ValueError("GEMINI_API_KEY 未設定")
75
- model_name = os.getenv("GEMINI_MODEL", "gemini-1.5-pro")
76
-
77
- client = genai.Client(api_key=api_key)
78
- prompt = f"{load_system_instruction(style)}\n\n{text}"
79
-
80
- if model_name == "gemini-2.5-flash-preview-04-17": # thinking OFF :contentReference[oaicite:5]{index=5}
81
- cfg = types.GenerateContentConfig(
82
- temperature=temperature, top_p=0.7, top_k=20,
83
- max_output_tokens=8192, candidate_count=1,
84
- thinking_config=types.ThinkingConfig(thinking_budget=0)
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
85
  )
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
86
  else:
87
- cfg = types.GenerateContentConfig(
88
- temperature=temperature, top_p=0.7, top_k=20,
89
- max_output_tokens=8192, candidate_count=1
90
- )
91
 
92
- raw = client.models.generate_content(
93
- model=model_name,
94
- contents=prompt,
95
- config=cfg
96
- ).text
97
-
98
- s, e = raw.find("```html"), raw.rfind("```")
99
- if s != -1 and e != -1 and s < e:
100
- html = raw[s + 7:e].strip()
101
- return enhance_font_awesome_layout(html)
102
- return raw
103
- # --------------------------------------
104
-
105
- # ---------- 画像トリミング ----------
106
- def trim_image_whitespace(img: Image.Image, threshold=248, padding=20):
107
- g = img.convert("L")
108
- w, h = g.size
109
- pix = list(g.getdata())
110
- pix = [pix[i*w:(i+1)*w] for i in range(h)]
111
- xs, ys = [w], [h]
112
- xe = ye = -1
113
- for y in range(h):
114
- for x in range(w):
115
- if pix[y][x] < threshold:
116
- xs.append(x); ys.append(y); xe = max(xe, x); ye = max(ye, y)
117
- if xe == -1:
118
- return img
119
- x0, y0 = max(0, min(xs)-padding), max(0, min(ys)-padding)
120
- x1, y1 = min(w, xe+padding+1), min(h, ye+padding+1)
121
- return img.crop((x0, y0, x1, y1))
122
- # --------------------------------------
123
-
124
- # ---------- Selenium スクショ ----------
125
- def render_fullpage_screenshot(html, ext=6.0, trim=True) -> Image.Image:
126
- tmp, driver = None, None
127
  try:
128
- with tempfile.NamedTemporaryFile(delete=False, suffix=".html", mode="w", encoding="utf-8") as f:
129
- f.write(html); tmp = f.name
130
- opts = Options()
131
- opts.add_argument("--headless=new") # 新 headless フラグ :contentReference[oaicite:6]{index=6}
132
- opts.add_argument("--no-sandbox"); opts.add_argument("--disable-dev-shm-usage")
133
- driver = webdriver.Chrome(options=opts)
134
- driver.set_window_size(1200, 1000)
135
- driver.get("file://" + tmp)
136
- WebDriverWait(driver, 15).until(EC.presence_of_element_located((By.TAG_NAME, "body")))
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
137
  time.sleep(1)
138
- total = driver.execute_script("return Math.max(document.body.scrollHeight,document.documentElement.scrollHeight)")
139
- vp = driver.execute_script("return window.innerHeight")
140
- for y in range(0, total, vp-200):
141
- driver.execute_script(f"window.scrollTo(0,{y})"); time.sleep(0.1)
142
- driver.execute_script("window.scrollTo(0,0)")
143
- driver.execute_script("document.documentElement.style.overflow='hidden'")
144
- w = driver.execute_script("return document.documentElement.scrollWidth")
145
- h = driver.execute_script("return document.documentElement.scrollHeight")
146
- driver.set_window_size(w, int(h*(1+ext/100)))
 
 
 
 
 
 
 
 
147
  time.sleep(0.5)
148
- img = Image.open(BytesIO(driver.get_screenshot_as_png()))
149
- return trim_image_whitespace(img) if trim else img
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
150
  except Exception as e:
151
- logger.error(e, exc_info=True)
152
- return Image.new("RGB", (1,1))
 
153
  finally:
154
- if driver: driver.quit()
155
- if tmp and os.path.exists(tmp): os.remove(tmp)
156
- # --------------------------------------
 
 
 
 
 
 
 
 
 
 
157
 
158
- def text_to_screenshot(text, ext, temp, trim, style):
159
- html = generate_html_from_text(text, temp, style)
160
- return render_fullpage_screenshot(html, ext, trim)
 
 
 
 
161
 
162
- # ---------- FastAPI ----------
 
 
 
 
 
 
163
  app = FastAPI()
 
 
164
  app.add_middleware(
165
- CORSMiddleware, allow_origins=["*"], allow_methods=["*"],
166
- allow_headers=["*"], allow_credentials=True
 
 
 
167
  )
168
 
169
- @app.post("/api/screenshot", response_class=StreamingResponse)
170
- async def api_screen(req: ScreenshotRequest):
171
- img = render_fullpage_screenshot(req.html_code, req.extension_percentage, req.trim_whitespace)
172
- buf = BytesIO(); img.save(buf, format="PNG"); buf.seek(0)
173
- return StreamingResponse(buf, media_type="image/png")
174
-
175
- @app.post("/api/text-to-screenshot", response_class=StreamingResponse)
176
- async def api_text(req: GeminiRequest):
177
- img = text_to_screenshot(req.text, req.extension_percentage,
178
- req.temperature, req.trim_whitespace, req.style)
179
- buf = BytesIO(); img.save(buf, format="PNG"); buf.seek(0)
180
- return StreamingResponse(buf, media_type="image/png")
181
- # --------------------------------------
182
-
183
- # ---------- Gradio UI ----------
184
- def process(mode, txt, ext, temp, trim, style):
185
- if mode == "HTML入力":
186
- return render_fullpage_screenshot(txt, ext, trim)
187
- return text_to_screenshot(txt, ext, temp, trim, style)
188
-
189
- with gr.Blocks(theme=gr.themes.Base(), title="HTML Viewer & Text→Infographic") as demo:
190
- gr.Markdown("## HTMLビューア & テキスト→インフォグラフィック変換") # central heading :contentReference[oaicite:7]{index=7}
191
-
192
- with gr.Row(): # 横一列配置 :contentReference[oaicite:8]{index=8}
193
- mode = gr.Radio(["HTML入力", "テキスト入力"], value="HTML入力", label="入力モード")
194
-
195
- with gr.Row(): # 入力パネル & 出力画像
196
- with gr.Column(scale=5):
197
- txt = gr.Textbox(lines=15, label="入力")
198
- with gr.Row():
199
- style_dd = gr.Dropdown(["standard","cute","resort","cool","dental"],
200
- value="standard", label="デザインスタイル", visible=False)
201
- temp_sl = gr.Slider(0,1,step=0.1,value=0.5,label="生成温度",visible=False)
202
- ext_sl = gr.Slider(0,30,step=1,value=10,label="高さ拡張率(%)")
203
- trim_cb = gr.Checkbox(value=True,label="余白トリミング")
204
- gen_btn = gr.Button("生成", variant="primary")
205
- with gr.Column(scale=7):
206
- out_img = gr.Image(type="pil", label="プレビュー", height=540)
207
-
208
- # モード切替で可視/不可視を更新
209
- def _toggle(m): vis = m=="テキスト入力"; return [gr.update(visible=vis), gr.update(visible=vis)]
210
- mode.change(_toggle, mode, [temp_sl, style_dd])
211
-
212
- gen_btn.click(process, [mode, txt, ext_sl, temp_sl, trim_cb, style_dd], out_img)
213
-
214
- gr.Markdown(
215
- f"""
216
- **使用モデル** : `{os.getenv('GEMINI_MODEL','gemini-1.5-pro')}`
217
- `/api/screenshot` ・ `/api/text-to-screenshot`
218
- """
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
219
  )
220
 
221
- # ---------- マウント ----------
222
- demo_app = gr.mount_gradio_app(app, demo, path="/")
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
223
 
 
224
  if __name__ == "__main__":
225
  import uvicorn
226
- uvicorn.run(demo_app, host="0.0.0.0", port=7860)
 
 
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
 
11
  from selenium.webdriver.support import expected_conditions as EC
12
  from PIL import Image
13
  from io import BytesIO
14
+ import tempfile
15
+ import time
16
+ import os
17
+ import logging
18
+ from huggingface_hub import hf_hub_download # 追加: HuggingFace Hubからファイルを直接ダウンロード
19
 
20
+ # 正しいGemini関連のインポート
21
+ import google.generativeai as genai
 
 
22
 
23
+ # ロギング設定
24
  logging.basicConfig(level=logging.INFO)
25
  logger = logging.getLogger(__name__)
26
 
27
+ # --- Gemini統合 ---
28
  class GeminiRequest(BaseModel):
29
+ """Geminiへのリクエストデータモデル"""
30
  text: str
31
+ extension_percentage: float = 10.0 # デフォルト値10%
32
+ temperature: float = 0.5 # デフォルト値を0.5に設定
33
+ trim_whitespace: bool = True # 余白トリミングオプション(デフォルト有効)
34
+ style: str = "standard" # デフォルトはstandard
35
 
36
  class ScreenshotRequest(BaseModel):
37
+ """スクリーンショットリクエストモデル"""
38
  html_code: str
39
+ extension_percentage: float = 10.0 # デフォルト値10%
40
+ trim_whitespace: bool = True # 余白トリミングオプション(デフォルト有効)
41
+ style: str = "standard" # デフォルトはstandard
42
+
43
+ # HTMLのFont Awesomeレイアウトを改善する関数
44
+ def enhance_font_awesome_layout(html_code):
45
+ """Font Awesomeレイアウトを改善するCSSを追加"""
46
+ # CSSを追加
47
+ fa_fix_css = """
48
+ <style>
49
+ /* Font Awesomeアイコンのレイアウト修正 */
50
+ [class*="fa-"] {
51
+ display: inline-block !important;
52
+ margin-right: 8px !important;
53
+ vertical-align: middle !important;
54
+ }
55
+
56
+ /* テキスト内のアイコン位置調整 */
57
+ h1 [class*="fa-"], h2 [class*="fa-"], h3 [class*="fa-"],
58
+ h4 [class*="fa-"], h5 [class*="fa-"], h6 [class*="fa-"] {
59
+ vertical-align: middle !important;
60
+ margin-right: 10px !important;
61
+ }
62
+
63
+ /* 特定パターンの修正 */
64
+ .fa + span, .fas + span, .far + span, .fab + span,
65
+ span + .fa, span + .fas, span + .far + span {
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)
requirements.txt CHANGED
@@ -1,10 +1,11 @@
1
- # --- START requirements.txt ---
 
2
  selenium
3
- gradio==5.25.2 # Gradio 5 系は websockets ≥13 を許容 :contentReference[oaicite:1]{index=1}
4
- fastapi
5
- uvicorn # extras を外し websockets を固定
6
  Pillow
 
 
 
7
  huggingface_hub
8
- google-genai==1.11.* # ThinkingConfig 対応版 :contentReference[oaicite:2]{index=2}
9
- websockets>=13,<15.1 # gradio-client google‑genai 両方を満たす :contentReference[oaicite:3]{index=3}
10
- # --- END requirements.txt ---
 
1
+ # --- START OF FILE requirements.txt ---
2
+
3
  selenium
4
+ gradio==4.19.2
 
 
5
  Pillow
6
+ fastapi
7
+ uvicorn[standard]
8
+ google-generativeai
9
  huggingface_hub
10
+
11
+ # --- END OF FILE requirements.txt ---