dynamic-hfspaces / space_loader_tab.py
LPX55
Refactor space loading functionality in space_loader_tab.py to streamline the selection and display of popular Hugging Face Spaces. Replace dropdown and button with a dynamic interface that shows the selected space directly, enhancing user experience and code clarity.
56e596b
import gradio as gr
POPULAR_SPACES = [
"gradio/calculator",
"huggingface-projects/llama-2-7b-chat",
]
def gr_load_tab():
gr.Markdown("## Load a Popular Hugging Face Space (gr.load)")
dropdown = gr.Dropdown(POPULAR_SPACES, label="Popular Spaces", value=POPULAR_SPACES[0])
space_blocks = []
for space in POPULAR_SPACES:
with gr.Column(visible=(space == POPULAR_SPACES[0])) as col:
gr.load(space, src="spaces")
space_blocks.append(col)
def show_space(selected):
return [gr.Column(visible=(selected == space)) for space in POPULAR_SPACES]
dropdown.change(fn=show_space, inputs=dropdown, outputs=space_blocks)
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]
)