Basic Example ============= This example demonstrates a simple Gradio application running on nanoHUB. Jupyter Notebook Approach ------------------------- Create a new Jupyter notebook on nanoHUB and add the following cells: **Cell 1: Load the extension and configure environment** .. code-block:: python %load_ext nanohubgradio %set_gradio_env **Cell 2: Create and run the Gradio app** .. code-block:: python import os import gradio as gr import plotly.express as px import pandas as pd # Simple sample data df = pd.DataFrame({ "x": list(range(1, 11)), "y": [1, 4, 2, 8, 5, 7, 6, 9, 10, 3], "group": ["A"] * 5 + ["B"] * 5 }) def update_plot(group): """Update plot based on selected group""" dff = df if group == "ALL" else df[df["group"] == group] fig = px.line(dff, x="x", y="y", markers=True, title=f"y vs x ({group})") stats = f"Rows: {len(dff)} | y min: {dff['y'].min()} | y max: {dff['y'].max()}" return fig, stats # Create Gradio interface with gr.Blocks(title="Basic Gradio App") as app: gr.Markdown("# Basic Gradio App") gr.Markdown("Pick a group to filter the chart:") with gr.Row(): group = gr.Dropdown( choices=["A", "B", "ALL"], value="ALL", label="Select Group", interactive=True ) with gr.Row(): plot = gr.Plot(label="Plot") with gr.Row(): stats = gr.Markdown() # Set up the callback group.change( fn=update_plot, inputs=[group], outputs=[plot, stats] ) # Load initial plot app.load(fn=update_plot, inputs=[group], outputs=[plot, stats]) if __name__ == "__main__": # Use environment variables set by %set_gradio_env or start_gradio host = os.getenv("GRADIO_HOST", "0.0.0.0") port = int(os.getenv("GRADIO_PORT", "8001")) root_path = os.getenv("GRADIO_ROOT_PATH", "") app.launch( server_name=host, server_port=port, root_path=root_path if root_path else None, share=False, quiet=True, inline=False ) Understanding the Code ---------------------- 1. **Loading the extension**: ``%load_ext nanohubgradio`` registers the magic command 2. **Setting the environment**: ``%set_gradio_env`` configures all necessary environment variables 3. **Creating the app**: Standard Gradio Blocks application code 4. **Running the server**: ``app.launch()`` starts the development server The magic command automatically detects your nanoHUB session and configures: - The correct root path for the weber proxy - The host and port settings - Access URLs for external connection Standalone Python File Approach ------------------------------- You can also create a standalone Python file and use the ``start_gradio`` command. **basic.py** .. code-block:: python import os import gradio as gr import plotly.express as px import pandas as pd # Simple sample data df = pd.DataFrame({ "x": list(range(1, 11)), "y": [1, 4, 2, 8, 5, 7, 6, 9, 10, 3], "group": ["A"] * 5 + ["B"] * 5 }) def update_plot(group): """Update plot based on selected group""" dff = df if group == "ALL" else df[df["group"] == group] fig = px.line(dff, x="x", y="y", markers=True, title=f"y vs x ({group})") stats = f"Rows: {len(dff)} | y min: {dff['y'].min()} | y max: {dff['y'].max()}" return fig, stats # Create Gradio interface with gr.Blocks(title="Basic Gradio App") as app: gr.Markdown("# Basic Gradio App") gr.Markdown("Pick a group to filter the chart:") with gr.Row(): group = gr.Dropdown( choices=["A", "B", "ALL"], value="ALL", label="Select Group", interactive=True ) with gr.Row(): plot = gr.Plot(label="Plot") with gr.Row(): stats = gr.Markdown() # Set up the callback group.change( fn=update_plot, inputs=[group], outputs=[plot, stats] ) # Load initial plot app.load(fn=update_plot, inputs=[group], outputs=[plot, stats]) if __name__ == "__main__": # Use environment variables set by %set_gradio_env or start_gradio host = os.getenv("GRADIO_HOST", "0.0.0.0") port = int(os.getenv("GRADIO_PORT", "8001")) root_path = os.getenv("GRADIO_ROOT_PATH", "") app.launch( server_name=host, server_port=port, root_path=root_path if root_path else None, share=False, quiet=True, inline=False ) **Running the App** Save this as ``basic.py`` and run it using: .. code-block:: bash start_gradio basic.py This command will: 1. Start your Gradio application on port 8001 2. Configure the weber proxy on port 8000 for external access 3. Automatically inject a nanoHUB header bar with support and terminate buttons 4. Display the access URL in your terminal **Key Features** - **Automatic Header Injection**: The ``start_gradio`` tool automatically adds a header bar with nanoHUB branding - **Responsive Layout**: Uses Gradio's Row/Column components for responsive design - **Interactive Callbacks**: Uses ``group.change()`` to update the plot when the dropdown changes - **Initial Load**: Uses ``app.load()`` to display the plot when the app first loads routes_pathname_prefix=os.getenv("DASH_ROUTES_PATHNAME_PREFIX"), requests_pathname_prefix=os.getenv("DASH_REQUESTS_PATHNAME_PREFIX") ) # Create a bar chart fig = px.bar(df, x="Fruit", y="Amount", color="City", barmode="group") app.layout = html.Div([ html.H1("Fruit Sales Dashboard", style={'textAlign': 'center'}), html.Hr(), dcc.Graph( id='fruit-chart', figure=fig ) ]) if __name__ == "__main__": app.run( jupyter_server_url=os.environ.get("DASH_BASE_PROXY"), host=os.environ.get("DASH_HOST", "0.0.0.0"), port=os.environ.get("DASH_PORT", "8001"), ) Then run from the terminal: .. code-block:: bash start_dash --app app.py This approach: - Automatically configures the environment - Launches the wrwroxy reverse proxy - Injects a header bar with nanoHUB branding - Provides a "Submit a ticket" link for support - Includes a "Terminate Session" button