from fastapi import FastAPI import gradio as gr # Create FastAPI app app = FastAPI() # Shared data shared_message = {"text": "Hello from FastAPI + Gradio!"} # --- FastAPI Route --- @app.get("/api/message") def get_message(): """Fetch the current message.""" return {"message": shared_message["text"]} @app.post("/api/message") def update_message(new_message: str): """Update the current message.""" shared_message["text"] = new_message return {"success": True, "message": shared_message["text"]} # --- Gradio Interface --- def fetch_message(): return shared_message["text"] def set_message(new_message): shared_message["text"] = new_message return f"Updated message: {new_message}" with gr.Blocks() as demo: gr.Markdown("## Simple Gradio + FastAPI Integration") message_display = gr.Textbox(label="Current Message", value=fetch_message, interactive=False) new_message_input = gr.Textbox(label="Set New Message") submit_button = gr.Button("Update Message") submit_button.click(set_message, inputs=new_message_input, outputs=message_display) # Mount Gradio app at `/gradio` gradio_app = gr.mount_gradio_app(app, demo, path="/gradio") # --- Run --- if __name__ == "__main__": import uvicorn uvicorn.run(app, host="0.0.0.0", port=7860)