Spaces:
Sleeping
Sleeping
File size: 2,743 Bytes
9f35f8e 9c3871b 9f35f8e |
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 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 |
from pathlib import Path
from fastapi import FastAPI
from fastapi.staticfiles import StaticFiles
from fastapi import File, UploadFile
import uvicorn
import gradio as gr
from datetime import datetime
import sys
# create a FastAPI app
app = FastAPI()
# create a static directory to store the static files
static_dir = Path('./static')
static_dir.mkdir(parents=True, exist_ok=True)
# mount FastAPI StaticFiles server
app.mount("/static", StaticFiles(directory=static_dir), name="static")
app.mount("/public", StaticFiles(directory=static_dir), name="static")
@app.post("/upload")
def upload(file: UploadFile = File(...)):
try:
file_name = f"{datetime.utcnow().strftime('%s')}.html"
file_path = static_dir / file_name
print(file_path)
with open(file_path, 'wb') as f:
while contents := file.file.read(1024 * 1024):
f.write(contents)
except Exception:
return {"message": "There was an error uploading the file"}
finally:
file.file.close()
return {"message": f"Successfully uploaded {file_path}", "url": f"https://fairedge-static-page.hf.space/{file_path}"}
def predict(text_input):
file_name = f"{datetime.utcnow().strftime('%s')}.html"
file_path = static_dir / file_name
print(file_path)
with open(file_path, "w") as f:
f.write(f"""
<script src="https://cdn.tailwindcss.com"></script>
<body class="bg-gray-200 dark:text-white dark:bg-gray-900">
<h1 class="text-3xl font-bold">
Hello <i>{text_input}</i> From Gradio Iframe
</h1>
<h3>Filename: {file_name}</h3>
""")
iframe = f"""<iframe src="/static/{file_name}" width="100%" height="500px"></iframe>"""
link = f'<a href="/static/{file_name}" target="_blank">{file_name}</a>'
return link, iframe
with gr.Blocks() as block:
gr.Markdown("""
## Gradio + FastAPI + Static Server
This is a demo of how to use Gradio with FastAPI and a static server.
The Gradio app generates dynamic HTML files and stores them in a static directory. FastAPI serves the static files.
""")
with gr.Row():
with gr.Column():
text_input = gr.Textbox(label="Name")
markdown = gr.Markdown(label="Output Box")
new_btn = gr.Button("New")
with gr.Column():
html = gr.HTML(label="HTML preview", show_label=True)
new_btn.click(fn=predict, inputs=[text_input], outputs=[markdown, html])
# mount Gradio app to FastAPI app
app = gr.mount_gradio_app(app, block, path="/")
# serve the app
if __name__ == "__main__":
uvicorn.run(app, host="0.0.0.0", port=7860)
# run the app with
# python app.py
# or
# uvicorn "app:app" --host "0.0.0.0" --port 7860 --reload
|