import gradio as gr from fastapi import FastAPI from fastapi.responses import JSONResponse # 建立 FastAPI app app = FastAPI() # 定義一個簡單的推論函式 def predict(text: str): return {"result": text[::-1]} # 這裡只是示範,把字串反轉 # 提供 API 端點 @app.post("/predict") async def predict_api(payload: dict): input_text = payload.get("text", "") return JSONResponse(content=predict(input_text)) # 如果要同時提供 Gradio UI with gr.Blocks() as demo: inp = gr.Textbox(label="Input") out = gr.Textbox(label="Output") btn = gr.Button("Run") btn.click(fn=lambda x: x[::-1], inputs=inp, outputs=out) # 把 Gradio 挂到 FastAPI #app = gr.mount_gradio_app(app, demo, path="/gradio")