|
import gradio as gr |
|
from fastapi import FastAPI, Request |
|
import uvicorn |
|
|
|
|
|
app = FastAPI() |
|
gr_interface = None |
|
STORAGE_PATH = "storage.txt" |
|
|
|
|
|
def init_storage(): |
|
try: |
|
with open(STORAGE_PATH, "x") as f: |
|
f.write("") |
|
except FileExistsError: |
|
pass |
|
|
|
init_storage() |
|
|
|
|
|
def read_data(): |
|
with open(STORAGE_PATH, "r") as f: |
|
return f.read() |
|
|
|
|
|
def write_data(text): |
|
with open(STORAGE_PATH, "w") as f: |
|
f.write(text) |
|
|
|
|
|
def show_latest_data(): |
|
return read_data() |
|
|
|
|
|
with gr.Blocks() as gr_app: |
|
gr.Markdown("## Latest Sent Text") |
|
output = gr.Textbox(label="Stored Text", value=read_data(), interactive=False) |
|
refresh_btn = gr.Button("Refresh") |
|
|
|
refresh_btn.click(fn=show_latest_data, inputs=[], outputs=output) |
|
|
|
|
|
@app.get("/store") |
|
async def store_text(request: Request): |
|
text = request.query_params.get("text") |
|
if text: |
|
write_data(text) |
|
return {"status": "success", "stored": text} |
|
else: |
|
return {"status": "error", "message": "No text parameter provided."} |
|
|
|
@app.get("/") |
|
async def root(): |
|
return gr_app |
|
|
|
|
|
if __name__ == "__main__": |
|
gr_interface = gr.mount_gradio_app(app, gr_app, path="/") |
|
uvicorn.run(app, host="0.0.0.0", port=7860) |
|
|