m7n's picture
Changed to self contained example
755230a verified
raw
history blame
1.39 kB
import os
from pathlib import Path
import gradio as gr
from fastapi import FastAPI
from fastapi.staticfiles import StaticFiles
import uvicorn
# Create FastAPI app
app = FastAPI()
# Create and configure static directory
static_dir = Path("./static")
static_dir.mkdir(parents=True, exist_ok=True)
# Mount static directory to FastAPI
app.mount("/static", StaticFiles(directory="static"), name="static")
# Tell Gradio which paths are allowed to be served
os.environ["GRADIO_ALLOWED_PATHS"] = str(static_dir.resolve())
def process_and_save(text):
"""Simple function that saves text to a file and returns file path"""
# Save text to a file in static directory
file_path = static_dir / "output.txt"
with open(file_path, "w") as f:
f.write(text)
# Return file path for download
return gr.File(value=file_path)
# Mark function as not requiring GPU
process_and_save.zerogpu = True
# Create Gradio interface
with gr.Blocks() as demo:
text_input = gr.Textbox(label="Enter some text")
submit_btn = gr.Button("Save and Download")
output = gr.File(label="Download File")
submit_btn.click(
fn=process_and_save,
inputs=text_input,
outputs=output
)
# Mount Gradio app to FastAPI
app = gr.mount_gradio_app(app, demo, path="/")
# Run server
if __name__ == "__main__":
uvicorn.run(app, host="0.0.0.0", port=7860)