import os os.system("pip uninstall -y gradio") os.system("pip install --upgrade gradio") from pathlib import Path from fastapi import FastAPI from fastapi.staticfiles import StaticFiles import uvicorn import gradio as gr from datetime import datetime import sys gr.set_static_paths(paths=["static/"]) # 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") # Gradio stuff import datamapplot import numpy as np import requests import io def predict(text_input): file_name = f"{datetime.utcnow().strftime('%s')}.html" file_path = static_dir / file_name print(file_path) base_url = "https://github.com/TutteInstitute/datamapplot" data_map_file = requests.get( f"{base_url}/raw/main/examples/arxiv_ml_data_map.npy" ) arxivml_data_map = np.load(io.BytesIO(data_map_file.content)) arxivml_label_layers = [] for layer_num in range(5): label_file = requests.get( f"{base_url}/raw/interactive/examples/arxiv_ml_layer{layer_num}_cluster_labels.npy" ) arxivml_label_layers.append(np.load(io.BytesIO(label_file.content), allow_pickle=True)) hover_data_file = requests.get( f"{base_url}/raw/interactive/examples/arxiv_ml_hover_data.npy" ) arxiv_hover_data = np.load(io.BytesIO(hover_data_file.content), allow_pickle=True) plot = datamapplot.create_interactive_plot( arxivml_data_map, arxivml_label_layers[0], arxivml_label_layers[2], arxivml_label_layers[4], hover_text = arxiv_hover_data, font_family="Roboto Condensed", ) plot.save(file_path) iframe = f"""""" link = f'{file_name}' 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