import gradio as gr from fastapi import FastAPI, Request import uvicorn # Initialize FastAPI and Gradio app = FastAPI() gr_interface = None STORAGE_PATH = "storage.txt" # Initialize storage def init_storage(): try: with open(STORAGE_PATH, "x") as f: f.write("") except FileExistsError: pass init_storage() # Function to read stored data def read_data(): with open(STORAGE_PATH, "r") as f: return f.read() # Function to write data def write_data(text): with open(STORAGE_PATH, "w") as f: f.write(text) # Gradio UI function def show_latest_data(): return read_data() # Set up the Gradio Blocks interface 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) # Mount Gradio to FastAPI @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 # Launch Gradio when run as __main__ if __name__ == "__main__": gr_interface = gr.mount_gradio_app(app, gr_app, path="/") uvicorn.run(app, host="0.0.0.0", port=7860)