dynamic-hfspaces / space_loader_tab.py
LPX55
Refactor app.py to utilize shared functions for greeting, calculation, and image processing, enhancing modularity and code reuse. Introduce space loading tabs for dynamic integration of popular Hugging Face Spaces.
4cc700d
raw
history blame
2.35 kB
import gradio as gr
POPULAR_SPACES = [
"gradio/calculator",
"gradio/image-classification",
"huggingface-projects/llama-2-7b-chat",
"gradio/englishtranslator",
"gradio/blocks-gallery"
]
def gr_load_tab():
gr.Markdown("## Load a Popular Hugging Face Space (gr.load)")
space_dropdown = gr.Dropdown(POPULAR_SPACES, label="Popular Spaces", interactive=True)
load_btn = gr.Button("Load Space")
error_box = gr.Markdown(visible=False)
with gr.Column():
gr.Markdown("### gr.load() Interface")
loaded_interface = gr.Blocks()
def load_space(space):
if not space or "/" not in space:
return gr.update(visible=True, value="**Error:** Please select a valid space name."), None
try:
interface = gr.load(space, src="spaces")
except Exception as e:
return gr.update(visible=True, value=f"**Error loading space:** {e}"), None
return gr.update(visible=False), interface
load_btn.click(
fn=load_space,
inputs=space_dropdown,
outputs=[error_box, loaded_interface]
)
def iframe_loader_tab():
gr.Markdown("## Load Any Hugging Face Space (iframe)")
with gr.Row():
space_name = gr.Textbox(label="Space Name", placeholder="e.g. gradio/calculator")
space_dropdown = gr.Dropdown(POPULAR_SPACES, label="Popular Spaces", interactive=True)
load_btn = gr.Button("Load Space")
error_box = gr.Markdown(visible=False)
with gr.Column():
gr.Markdown("### Space IFrame")
iframe_html = gr.HTML("")
def get_space_name(text, dropdown):
return text if text else dropdown
def load_space(space):
if not space or "/" not in space:
return gr.update(visible=True, value="**Error:** Please enter a valid space name (e.g. gradio/calculator)."), ""
space_id = space.replace("/", "-")
iframe_url = f"https://{space_id}.hf.space?__theme=dark"
iframe = f'<iframe src="{iframe_url}" width="100%" height="600" style="border:none;"></iframe>'
return gr.update(visible=False), iframe
load_btn.click(
fn=get_space_name,
inputs=[space_name, space_dropdown],
outputs=space_name
).then(
fn=load_space,
inputs=space_name,
outputs=[error_box, iframe_html]
)