File size: 1,306 Bytes
73b4d62
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
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)