Update app.py
Browse files27 unmodified lines28293031323334353637383940414265 unmodified lines1081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371389 unmodified lines148149150151152153154155156157158327 unmodified lines48648748848949049149249349449549690 unmodified lines58758858959059159259359459559659759859960014 unmodified lines61561661761861962062162262362462562662762815 unmodified lines6446456466476486496506516526536546556566576586596606616626636646656665 unmodified lines6726736746756766776786796806816826836846856866876886896906916926 unmodified lines69970070170270370427 unmodified linesclass GeminiRequest(BaseModel):"""Geminiへのリクエストデータモデル"""text: strextension_percentage: float = 10.0 # デフォルト値8%temperature: float = 0.5 # デフォルト値を0.3に下げて創造性を抑制trim_whitespace: bool = True # 余白トリミングオプション(デフォルト有効)class ScreenshotRequest(BaseModel):"""スクリーンショットリクエストモデル"""html_code: strextension_percentage: float = 10.0 # デフォルト値8%trim_whitespace: bool = True # 余白トリミングオプション(デフォルト有効)# HTMLのFont Awesomeレイアウトを改善する関数def enhance_font_awesome_layout(html_code):65 unmodified lines# どちらもない場合は先頭に追加return f'<html><head>{fa_fix_css}</head>' + html_code + '</html>'def load_system_instruction():"""HuggingFaceリポジトリからprompt.txtを直接ダウンロードして読み込む"""try:# ファイルを直接ダウンロードlogger.info("HuggingFaceリポジトリからprompt.txtをダウンロード中...")file_path = hf_hub_download(repo_id="tomo2chin2/GURAREKOstlyle",filename="prompt.txt",repo_type="dataset")# ファイルを読み込むwith open(file_path, 'r', encoding='utf-8') as file:instruction = file.read()logger.info(f"システムインストラクションを正常に読み込みました: {len(instruction)}バイト")return instructionexcept Exception as e:# エラーが発生した場合error_msg = f"システムインストラクションの読み込みに失敗: {str(e)}"logger.error(error_msg)raise ValueError(error_msg)def generate_html_from_text(text, temperature=0.3):"""テキストからHTMLを生成する"""try:# APIキーの取得と設定9 unmodified lines# Gemini APIの設定genai.configure(api_key=api_key)# HuggingFaceデータセットからシステムインストラクションを読み込むsystem_instruction = load_system_instruction()# モデル初期化logger.info(f"Gemini APIにリクエストを送信: テキスト長さ = {len(text)}, 温度 = {temperature}")# モデル初期化model = genai.GenerativeModel(model_name)327 unmodified lineslogger.error(f"Error removing temporary file {tmp_path}: {e}")# --- Geminiを使った新しい関数 ---def text_to_screenshot(text: str, extension_percentage: float, temperature: float = 0.3, trim_whitespace: bool = True) -> Image.Image:"""テキストをGemini APIでHTMLに変換し、スクリーンショットを生成する統合関数"""try:# 1. テキストからHTMLを生成(温度パラメータも渡す)html_code = generate_html_from_text(text, temperature)# 2. HTMLからスクリーンショットを生成return render_fullpage_screenshot(html_code, extension_percentage, trim_whitespace)90 unmodified linesテキストからHTMLインフォグラフィックを生成してスクリーンショットを返すAPIエンドポイント"""try:logger.info(f"テキスト→スクリーンショットAPIリクエスト受信。テキスト長さ: {len(request.text)}, 拡張率: {request.extension_percentage}%, 温度: {request.temperature}")# テキストからHTMLを生成してスクリーンショットを作成(温度パラメータも渡す)pil_image = text_to_screenshot(request.text,request.extension_percentage,request.temperature,request.trim_whitespace)if pil_image.size == (1, 1):14 unmodified lines# --- Gradio Interface Definition ---# 入力モードの選択用Radioコンポーネントdef process_input(input_mode, input_text, extension_percentage, temperature, trim_whitespace):"""入力モードに応じて適切な処理を行う"""if input_mode == "HTML入力":# HTMLモードの場合は既存の処理return render_fullpage_screenshot(input_text, extension_percentage, trim_whitespace)else:# テキスト入力モードの場合はGemini APIを使用return text_to_screenshot(input_text, extension_percentage, temperature, trim_whitespace)# Gradio UIの定義with gr.Blocks(title="Full Page Screenshot (テキスト変換対応)", theme=gr.themes.Base()) as iface:15 unmodified lines)with gr.Row():extension_percentage = gr.Slider(minimum=0,maximum=30,step=1.0,value=10, # デフォルト値10%label="上下高さ拡張率(%)")# 温度調整スライダー(テキストモード時のみ表示)temperature = gr.Slider(minimum=0.0,maximum=1.0,step=0.1,value=0.5, # デフォルト値を0.5に下げて創造性を抑制label="生成時の温度(低い=一貫性高、高い=創造性高)",visible=False # 最初は非表示)# 余白トリミングオプションtrim_whitespace = gr.Checkbox(5 unmodified linessubmit_btn = gr.Button("生成")output_image = gr.Image(type="pil", label="ページ全体のスクリーンショット")# 入力モード変更時のイベント処理(テキストモード時のみ温度スライダーを表示)def update_temperature_visibility(mode):# Gradio 4.x用のアップデート方法return {"visible": mode == "テキスト入力", "__type__": "update"}input_mode.change(fn=update_temperature_visibility,inputs=input_mode,outputs=temperature)# 生成ボタンクリック時のイベント処理submit_btn.click(fn=process_input,inputs=[input_mode, input_text, extension_percentage, temperature, trim_whitespace],outputs=output_image)6 unmodified lines## 設定情報- 使用モデル: {gemini_model} (環境変数 GEMINI_MODEL で変更可能)""")# --- Mount Gradio App onto FastAPI ---27 unmodified lines282930313233343536373839404142434465 unmodified lines1101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821839 unmodified lines193194195196197198199200201202203327 unmodified lines53153253353453553653753853954054154290 unmodified lines63363463563663763863964064164264364464564664764864914 unmodified lines66466566666766866967067167267367467567667715 unmodified lines6936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257265 unmodified lines7327337347357367377387397407417427437447457467477487497507517527537547557566 unmodified lines76376476576676776876927 unmodified linesclass GeminiRequest(BaseModel):"""Geminiへのリクエストデータモデル"""text: strextension_percentage: float = 10.0 # デフォルト値10%temperature: float = 0.5 # デフォルト値を0.5に設定trim_whitespace: bool = True # 余白トリミングオプション(デフォルト有効)style: str = "standard" # デフォルトはstandardclass ScreenshotRequest(BaseModel):"""スクリーンショットリクエストモデル"""html_code: strextension_percentage: float = 10.0 # デフォルト値10%trim_whitespace: bool = True # 余白トリミングオプション(デフォルト有効)style: str = "standard" # デフォルトはstandard# HTMLのFont Awesomeレイアウトを改善する関数def enhance_font_awesome_layout(html_code):65 unmodified lines# どちらもない場合は先頭に追加return f'<html><head>{fa_fix_css}</head>' + html_code + '</html>'def load_system_instruction(style="standard"):"""指定されたスタイルのシステムインストラクションを読み込むArgs:style: 使用するスタイル名 (standard, cute, resort, cool, dental)Returns:読み込まれたシステムインストラクション"""try:# 有効なスタイル一覧valid_styles = ["standard", "cute", "resort", "cool", "dental"]# スタイルの検証if style not in valid_styles:logger.warning(f"無効なスタイル '{style}' が指定されました。デフォルトの 'standard' を使用します。")style = "standard"logger.info(f"スタイル '{style}' のシステムインストラクションを読み込みます")# まず、ローカルのスタイルディレクトリ内のprompt.txtを確認local_path = os.path.join(os.path.dirname(__file__), style, "prompt.txt")# ローカルファイルが存在する場合はそれを使用if os.path.exists(local_path):logger.info(f"ローカルファイルを使用: {local_path}")with open(local_path, 'r', encoding='utf-8') as file:instruction = file.read()return instruction# HuggingFaceリポジトリからのファイル読み込みを試行try:# スタイル固有のファイルパスを指定file_path = hf_hub_download(repo_id="tomo2chin2/GURAREKOstlyle",filename=f"{style}/prompt.txt",repo_type="dataset")logger.info(f"スタイル '{style}' のプロンプトをHuggingFaceから読み込みました: {file_path}")with open(file_path, 'r', encoding='utf-8') as file:instruction = file.read()return instructionexcept Exception as style_error:# スタイル固有ファイルの読み込みに失敗した場合、デフォルトのprompt.txtを使用logger.warning(f"スタイル '{style}' のプロンプト読み込みに失敗: {str(style_error)}")logger.info("デフォルトのprompt.txtを読み込みます")file_path = hf_hub_download(repo_id="tomo2chin2/GURAREKOstlyle",filename="prompt.txt",repo_type="dataset")with open(file_path, 'r', encoding='utf-8') as file:instruction = file.read()logger.info("デフォルトのシステムインストラクションを読み込みました")return instructionexcept Exception as e:error_msg = f"システムインストラクションの読み込みに失敗: {str(e)}"logger.error(error_msg)raise ValueError(error_msg)def generate_html_from_text(text, temperature=0.3, style="standard"):"""テキストからHTMLを生成する"""try:# APIキーの取得と設定9 unmodified lines# Gemini APIの設定genai.configure(api_key=api_key)# 指定されたスタイルのシステムインストラクションを読み込むsystem_instruction = load_system_instruction(style)# モデル初期化logger.info(f"Gemini APIにリクエストを送信: テキスト長さ = {len(text)}, 温度 = {temperature}, スタイル = {style}")# モデル初期化model = genai.GenerativeModel(model_name)327 unmodified lineslogger.error(f"Error removing temporary file {tmp_path}: {e}")# --- Geminiを使った新しい関数 ---def text_to_screenshot(text: str, extension_percentage: float, temperature: float = 0.3,trim_whitespace: bool = True, style: str = "standard") -> Image.Image:"""テキストをGemini APIでHTMLに変換し、スクリーンショットを生成する統合関数"""try:# 1. テキストからHTMLを生成(温度パラメータとスタイルも渡す)html_code = generate_html_from_text(text, temperature, style)# 2. HTMLからスクリーンショットを生成return render_fullpage_screenshot(html_code, extension_percentage, trim_whitespace)90 unmodified linesテキストからHTMLインフォグラフィックを生成してスクリーンショットを返すAPIエンドポイント"""try:logger.info(f"テキスト→スクリーンショットAPIリクエスト受信。テキスト長さ: {len(request.text)}, "f"拡張率: {request.extension_percentage}%, 温度: {request.temperature}, "f"スタイル: {request.style}")# テキストからHTMLを生成してスクリーンショットを作成(温度パラメータとスタイルも渡す)pil_image = text_to_screenshot(request.text,request.extension_percentage,request.temperature,request.trim_whitespace,request.style)if pil_image.size == (1, 1):14 unmodified lines# --- Gradio Interface Definition ---# 入力モードの選択用Radioコンポーネントdef process_input(input_mode, input_text, extension_percentage, temperature, trim_whitespace, style):"""入力モードに応じて適切な処理を行う"""if input_mode == "HTML入力":# HTMLモードの場合は既存の処理(スタイルは使わない)return render_fullpage_screenshot(input_text, extension_percentage, trim_whitespace)else:# テキスト入力モードの場合はGemini APIを使用return text_to_screenshot(input_text, extension_percentage, temperature, trim_whitespace, style)# Gradio UIの定義with gr.Blocks(title="Full Page Screenshot (テキスト変換対応)", theme=gr.themes.Base()) as iface:15 unmodified lines)with gr.Row():with gr.Column(scale=1):# スタイル選択ドロップダウンstyle_dropdown = gr.Dropdown(choices=["standard", "cute", "resort", "cool", "dental"],value="standard",label="デザインスタイル",info="テキスト→HTML変換時のデザインテーマを選択します",visible=False # テキスト入力モードの時だけ表示)with gr.Column(scale=2):extension_percentage = gr.Slider(minimum=0,maximum=30,step=1.0,value=10, # デフォルト値10%label="上下高さ拡張率(%)")# 温度調整スライダー(テキストモード時のみ表示)temperature = gr.Slider(minimum=0.0,maximum=1.0,step=0.1,value=0.5, # デフォルト値を0.5に設定label="生成時の温度(低い=一貫性高、高い=創造性高)",visible=False # 最初は非表示)# 余白トリミングオプションtrim_whitespace = gr.Checkbox(5 unmodified linessubmit_btn = gr.Button("生成")output_image = gr.Image(type="pil", label="ページ全体のスクリーンショット")# 入力モード変更時のイベント処理(テキストモード時のみ温度スライダーとスタイルドロップダウンを表示)def update_controls_visibility(mode):# Gradio 4.x用のアップデート方法is_text_mode = mode == "テキスト入力"return [{"visible": is_text_mode, "__type__": "update"}, # temperature{"visible": is_text_mode, "__type__": "update"}, # style_dropdown]input_mode.change(fn=update_controls_visibility,inputs=input_mode,outputs=[temperature, style_dropdown])# 生成ボタンクリック時のイベント処理submit_btn.click(fn=process_input,inputs=[input_mode, input_text, extension_percentage, temperature, trim_whitespace, style_dropdown],outputs=output_image)6 unmodified lines## 設定情報- 使用モデル: {gemini_model} (環境変数 GEMINI_MODEL で変更可能)- 対応スタイル: standard, cute, resort, cool, dental""")# --- Mount Gradio App onto FastAPI ---
app.py+120-55