Spaces:
Paused
Paused
Update app.py
Browse files
app.py
CHANGED
|
@@ -1,132 +1,71 @@
|
|
| 1 |
import gradio as gr
|
| 2 |
import base64
|
| 3 |
-
import
|
| 4 |
-
import io
|
| 5 |
-
from fastapi import FastAPI, File, UploadFile, HTTPException
|
| 6 |
from fastapi.responses import JSONResponse
|
| 7 |
-
import uvicorn #
|
| 8 |
|
| 9 |
-
# ---
|
| 10 |
-
|
| 11 |
-
"""
|
| 12 |
-
バイト列を受け取り、Base64エンコードされた文字列を返す。
|
| 13 |
-
エラーが発生した場合は例外を送出する。
|
| 14 |
-
"""
|
| 15 |
-
try:
|
| 16 |
-
base64_bytes = base64.b64encode(file_bytes)
|
| 17 |
-
base64_string = base64_bytes.decode('utf-8')
|
| 18 |
-
return base64_string
|
| 19 |
-
except Exception as e:
|
| 20 |
-
print(f"Base64エンコードエラー: {e}")
|
| 21 |
-
# エラーを呼び出し元に伝えるために再度raiseする
|
| 22 |
-
raise ValueError(f"Base64エンコード中にエラーが発生しました: {e}")
|
| 23 |
|
| 24 |
-
# ---
|
| 25 |
-
def
|
| 26 |
"""
|
| 27 |
-
|
|
|
|
| 28 |
"""
|
| 29 |
if file_obj is None:
|
| 30 |
return "ファイルをアップロードしてください。"
|
| 31 |
|
| 32 |
try:
|
| 33 |
-
|
| 34 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
| 35 |
|
| 36 |
-
|
| 37 |
-
|
| 38 |
-
|
| 39 |
-
# 共通のエンコード関数を呼び出す
|
| 40 |
-
base64_string = encode_bytes_to_base64(file_bytes)
|
| 41 |
return base64_string
|
| 42 |
|
| 43 |
except Exception as e:
|
| 44 |
-
print(f"
|
| 45 |
-
# Gradioではエラーメッセージを文字列として返す
|
| 46 |
return f"ファイルの処理中にエラーが発生しました: {e}"
|
| 47 |
|
| 48 |
-
# --- FastAPI
|
| 49 |
-
app
|
| 50 |
-
|
| 51 |
-
description="ファイルを受け取りBase64にエンコードするAPIとGradio UIを提供します。"
|
| 52 |
-
)
|
| 53 |
-
|
| 54 |
-
# --- FastAPI エンドポイントの定義 ---
|
| 55 |
-
@app.post(
|
| 56 |
-
"/encode/",
|
| 57 |
-
summary="ファイルをBase64エンコード",
|
| 58 |
-
description="アップロードされたファイルを読み込み、Base64エンコードされた文字列をJSON形式で返します。",
|
| 59 |
-
response_description="ファイル名とBase64エンコードされた文字列を含むJSONオブジェクト"
|
| 60 |
-
)
|
| 61 |
-
async def api_encode_file(file: UploadFile = File(..., description="Base64エンコードする画像またはPDFファイル")):
|
| 62 |
"""
|
| 63 |
-
|
| 64 |
-
POSTリクエストでファイルを受け取り、Base64エンコードしてJSONで返す。
|
| 65 |
"""
|
| 66 |
-
|
| 67 |
-
|
| 68 |
-
|
| 69 |
-
|
| 70 |
-
|
| 71 |
-
# ファイルが空でないかチェック
|
| 72 |
-
if not contents:
|
| 73 |
-
raise HTTPException(status_code=400, detail="空のファイルは処理できません。")
|
| 74 |
-
|
| 75 |
-
try:
|
| 76 |
-
# 共通のエンコード関数を呼び出す
|
| 77 |
-
base64_string = encode_bytes_to_base64(contents)
|
| 78 |
-
# 成功したらJSONレスポンスを返す
|
| 79 |
-
return JSONResponse(
|
| 80 |
-
content={
|
| 81 |
-
"filename": file.filename,
|
| 82 |
-
"content_type": file.content_type,
|
| 83 |
-
"base64_string": base64_string
|
| 84 |
-
}
|
| 85 |
-
)
|
| 86 |
-
except ValueError as e: # Base64エンコード中のエラーを捕捉
|
| 87 |
-
print(f"APIエンコード処理エラー: {e}")
|
| 88 |
-
raise HTTPException(status_code=500, detail=str(e))
|
| 89 |
-
except Exception as e: # その他の予期せぬエラー
|
| 90 |
-
print(f"API予期せぬエラー: {e}")
|
| 91 |
-
raise HTTPException(status_code=500, detail=f"ファイルの処理中に予期せぬエラーが発生しまし���: {e}")
|
| 92 |
-
finally:
|
| 93 |
-
# アップロードされたファイルを閉じる (重要)
|
| 94 |
-
await file.close()
|
| 95 |
|
| 96 |
-
# --- Gradio
|
| 97 |
-
|
| 98 |
label="画像またはPDFファイルを入力",
|
| 99 |
-
file_types=['image', '.pdf']
|
| 100 |
)
|
| 101 |
-
|
| 102 |
-
label="Base64エンコード結果",
|
| 103 |
lines=10,
|
| 104 |
-
interactive=True
|
| 105 |
)
|
| 106 |
|
| 107 |
-
# Gradioインターフェースを作成
|
| 108 |
iface = gr.Interface(
|
| 109 |
-
fn=
|
| 110 |
-
inputs=
|
| 111 |
-
outputs=
|
| 112 |
-
title="ファイル ⇨ Base64 エンコーダー (Gradio
|
| 113 |
-
description="
|
| 114 |
-
|
| 115 |
-
flagging_mode="never" # Flagging機能を無効にする(推奨される書き方)
|
| 116 |
)
|
| 117 |
|
| 118 |
-
# ---
|
| 119 |
-
# Gradio
|
| 120 |
-
app = gr.mount_gradio_app(app, iface, path="/")
|
| 121 |
|
| 122 |
-
|
| 123 |
-
|
| 124 |
-
# Hugging Face Spaces環境では、Spacesがuvicornを起動してくれるため、この部分は実行されません。
|
| 125 |
-
#if __name__ == "__main__":
|
| 126 |
-
# print("ローカルサーバーを起動します (http://127.0.0.1:8000)")
|
| 127 |
-
# print("Gradio UI: http://127.0.0.1:8000/")
|
| 128 |
-
# print("FastAPI エンドポイント (POST): http://127.0.0.1:8000/encode/")
|
| 129 |
-
# print("API ドキュメント (Swagger UI): http://127.0.0.1:8000/docs")
|
| 130 |
-
# print("API ドキュメント (ReDoc): http://127.0.0.1:8000/redoc")
|
| 131 |
-
# # host="0.0.0.0" でローカルネットワーク内の他のデバイスからもアクセス可能に
|
| 132 |
-
# uvicorn.run(app, host="0.0.0.0", port=8000)
|
|
|
|
| 1 |
import gradio as gr
|
| 2 |
import base64
|
| 3 |
+
from fastapi import FastAPI, File, UploadFile
|
|
|
|
|
|
|
| 4 |
from fastapi.responses import JSONResponse
|
| 5 |
+
import uvicorn # FastAPIアプリを起動するために必要
|
| 6 |
|
| 7 |
+
# --- FastAPI アプリケーションの作成 ---
|
| 8 |
+
app = FastAPI()
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 9 |
|
| 10 |
+
# --- (既存の) Base64 エンコード関数 ---
|
| 11 |
+
def encode_to_base64(file_obj):
|
| 12 |
"""
|
| 13 |
+
gr.FileまたはUploadFileから受け取ったファイルオブジェクトを処理し、
|
| 14 |
+
Base64エンコードされた文字列を返す関数。
|
| 15 |
"""
|
| 16 |
if file_obj is None:
|
| 17 |
return "ファイルをアップロードしてください。"
|
| 18 |
|
| 19 |
try:
|
| 20 |
+
if isinstance(file_obj, UploadFile): # FastAPIのUploadFileの場合
|
| 21 |
+
file_bytes = await file_obj.read() # await を使用
|
| 22 |
+
else: # GradioのFileの場合 (file_obj.name はファイルパス)
|
| 23 |
+
file_path = file_obj.name
|
| 24 |
+
with open(file_path, 'rb') as f:
|
| 25 |
+
file_bytes = f.read()
|
| 26 |
|
| 27 |
+
base64_bytes = base64.b64encode(file_bytes)
|
| 28 |
+
base64_string = base64_bytes.decode('utf-8')
|
|
|
|
|
|
|
|
|
|
| 29 |
return base64_string
|
| 30 |
|
| 31 |
except Exception as e:
|
| 32 |
+
print(f"エラー発生: {e}")
|
|
|
|
| 33 |
return f"ファイルの処理中にエラーが発生しました: {e}"
|
| 34 |
|
| 35 |
+
# --- FastAPI エンドポイント ---
|
| 36 |
+
@app.post("/api/encode_base64")
|
| 37 |
+
async def api_encode_base64(file: UploadFile = File(...)):
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 38 |
"""
|
| 39 |
+
APIエンドポイント: ファイルを受け取りBase64エンコードしてJSONで返す
|
|
|
|
| 40 |
"""
|
| 41 |
+
base64_string = await encode_to_base64(file) # await を使用
|
| 42 |
+
if "エラー" in base64_string: # エラーメッセージの場合
|
| 43 |
+
return JSONResponse(content={"error": base64_string}, status_code=400) # エラーレスポンス
|
| 44 |
+
return {"base64_string": base64_string} # 成功レスポンス
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 45 |
|
| 46 |
+
# --- Gradio インターフェース (変更なし) ---
|
| 47 |
+
input_file = gr.File(
|
| 48 |
label="画像またはPDFファイルを入力",
|
| 49 |
+
file_types=['image', '.pdf']
|
| 50 |
)
|
| 51 |
+
output_text = gr.Textbox(
|
| 52 |
+
label="Base64エンコード結果 (Gradio)",
|
| 53 |
lines=10,
|
| 54 |
+
interactive=True
|
| 55 |
)
|
| 56 |
|
|
|
|
| 57 |
iface = gr.Interface(
|
| 58 |
+
fn=encode_to_base64,
|
| 59 |
+
inputs=input_file,
|
| 60 |
+
outputs=output_text,
|
| 61 |
+
title="ファイル ⇨ Base64 エンコーダー (Gradio & API)",
|
| 62 |
+
description="画像またはPDFファイルをアップロードしてBase64エンコード。\nAPIエンドポイント: `/api/encode_base64` (POST)",
|
| 63 |
+
allow_flagging='never'
|
|
|
|
| 64 |
)
|
| 65 |
|
| 66 |
+
# --- アプリケーションの起動 ---
|
| 67 |
+
# GradioアプリとFastAPIアプリを両方起動 (uvicorn経由でFastAPIを起動)
|
| 68 |
+
app = gr.mount_gradio_app(app, iface, path="/gradio") # GradioアプリをFastAPIにマウント
|
| 69 |
|
| 70 |
+
if __name__ == "__main__":
|
| 71 |
+
uvicorn.run(app, host="0.0.0.0", port=8000) # FastAPIアプリをuvicornで起動
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|