Skip to main content

tags: [gradio-custom-component, HTML] title: gradio_htmlplus short_description: Gradio HTML Advanced Component colorFrom: blue colorTo: yellow sdk: gradio pinned: false app_file: space.py

gradio_htmlplus

Static Badge

Gradio HTML Advanced Component

Installation

pip install gradio_htmlplus

Usage

import gradio as gr
import pandas as pd
import numpy as np
import uuid

# Import the custom component and the HTML generator
from gradio_htmlplus import HTMLPlus
from leaderboard import generate_leaderboard_html

# Generate Mock Data
def create_mock_leaderboard_data(num_rows=15):
    """
    Creates a pandas DataFrame with random data for the leaderboard demo.

    Args:
        num_rows (int): The number of rows to generate.

    Returns:
        pd.DataFrame: A DataFrame containing mock leaderboard data.
    """
    data = {
        'run_id': [str(uuid.uuid4()) for _ in range(num_rows)],
        'model': [f'model-v{i}-{np.random.choice(["alpha", "beta", "gamma"])}' for i in range(num_rows)],
        'agent_type': np.random.choice(['tool', 'code', 'both'], num_rows),
        'provider': np.random.choice(['litellm', 'transformers'], num_rows),
        'success_rate': np.random.uniform(40, 99.9, num_rows),
        'total_tests': np.random.randint(50, 100, num_rows),
        'avg_steps': np.random.uniform(3, 8, num_rows),
        'avg_duration_ms': np.random.uniform(1500, 5000, num_rows),
        'total_tokens': np.random.randint(10000, 50000, num_rows),
        'total_cost_usd': np.random.uniform(0.01, 0.2, num_rows),
        'co2_emissions_g': np.random.uniform(0.5, 5, num_rows),
        'gpu_utilization_avg': [np.random.uniform(60, 95) if i % 2 == 0 else None for i in range(num_rows)],
        'timestamp': pd.to_datetime(pd.Timestamp.now() - pd.to_timedelta(np.random.rand(num_rows), unit='D')),
        'submitted_by': [f'user_{np.random.randint(1, 5)}' for _ in range(num_rows)],
    }
    df = pd.DataFrame(data)
    df['successful_tests'] = (df['total_tests'] * (df['success_rate'] / 100)).astype(int)
    df['failed_tests'] = df['total_tests'] - df['successful_tests']
    return df


with gr.Blocks(css=".gradio-container { max-width: 95% !important; }") as demo:
    gr.Markdown("# 🏆 Interactive Leaderboard with Action Buttons")
    gr.Markdown("Click on any row in the table to view its complete data, or click a button for a specific action.")

    # Create and display the initial table
    leaderboard_df = create_mock_leaderboard_data(15)
    leaderboard_html = generate_leaderboard_html(leaderboard_df)

    html_table = HTMLPlus(
        value=leaderboard_html,
        # Define both the action button and the table row as selectable elements.
        # The more specific selector should come first to ensure it's matched first.
        selectable_elements=[".tm-action-button", "tr"]
    )

    clicked_data_output = gr.JSON(label="Selected Row Data")
    action_log_output = gr.Textbox(label="Action Log", interactive=False)
    
    def on_element_selected(evt: gr.SelectData):
        """
        Handles select events from the HTMLPlus component. It differentiates actions
        based on which CSS selector was matched (evt.index).

        Args:
            evt (gr.SelectData): The event data object, containing the matched
                                 selector (`.index`) and the element's data
                                 attributes (`.value`).

        Returns:
            tuple: A tuple of values to update the output components.
                   Uses gr.skip() to avoid updating a component.
        """
        if evt.index == ".tm-action-button":
            # This block handles clicks on the 'Delete' button.
            action = evt.value.get('action')
            run_id = evt.value.get('run-id') or "Unknown" 
            
            log_message = f"ACTION: Button '{action}' clicked for Run ID: {run_id[:8]}..."
            
            # Update the log, but skip updating the JSON output.
            return gr.skip(), log_message

        elif evt.index == "tr":
            # This block handles clicks on the table row itself.
            data = evt.value
            run_id = data.get('run-id') or "Unknown"
            
            log_message = f"INFO: Row selected for Run ID: {run_id[:8]}..."
            
            # The frontend sends all data attributes as strings.
            # Convert numeric strings back to numbers for cleaner display.
            numeric_keys = [
                'success-rate', 'total-tests', 'avg-steps', 'avg-duration-ms', 
                'total-tokens', 'total-cost-usd', 'co2-emissions-g', 
                'gpu-utilization-avg', 'successful-tests', 'failed-tests'
            ]
            
            for key in numeric_keys:
                if key in data and data[key] not in ['None', None, '']:
                    try:
                        num_val = float(data[key])
                        if num_val.is_integer():
                            data[key] = int(num_val)
                        else:
                            data[key] = round(num_val, 4)
                    except (ValueError, TypeError):
                        pass  # Leave as a string if conversion fails

            # Update both the JSON output and the log.
            return data, log_message
        
        # A fallback for any unexpected event.
        return gr.skip(), "Unknown action occurred."

    # Connect the 'select' event to the callback function, mapping its
    # return values to the two output components.
    html_table.select(
        fn=on_element_selected,
        inputs=None,
        outputs=[clicked_data_output, action_log_output]
    )

if __name__ == "__main__":
    demo.launch()

HTMLPlus

Initialization

name type default description
value
str | Callable | None
None The HTMLPlus content to display. Only static HTMLPlus is rendered (e.g. no JavaScript. To render JavaScript, use the `js` or `head` parameters in the `Blocks` constructor). If a function is provided, the function will be called each time the app loads to set the initial value of this component.
label
str | I18nData | None
None The label for this component. Is used as the header if there are a table of examples for this component. If None and used in a `gr.Interface`, the label will be the name of the parameter this component is assigned to.
every
Timer | float | None
None Continously calls `value` to recalculate it if `value` is a function (has no effect otherwise). Can provide a Timer whose tick resets `value`, or a float that provides the regular interval for the reset Timer.
inputs
Component | Sequence[Component] | set[Component] | None
None Components that are used as inputs to calculate `value` if `value` is a function (has no effect otherwise). `value` is recalculated any time the inputs change.
show_label
bool
False If True, the label will be displayed. If False, the label will be hidden.
visible
bool | Literal["hidden"]
True If False, component will be hidden. If "hidden", component will be visually hidden and not take up space in the layout but still exist in the DOM
elem_id
str | None
None An optional string that is assigned as the id of this component in the HTMLPlus DOM. Can be used for targeting CSS styles.
elem_classes
list[str] | str | None
None An optional list of strings that are assigned as the classes of this component in the HTMLPlus DOM. Can be used for targeting CSS styles.
render
bool
True If False, component will not render be rendered in the Blocks context. Should be used if the intention is to assign event listeners now but render the component later.
key
int | str | tuple[int | str, ...] | None
None in a gr.render, Components with the same key across re-renders are treated as the same component, not a new component. Properties set in 'preserved_by_key' are not reset across a re-render.
preserved_by_key
list[str] | str | None
"value" A list of parameters from this component's constructor. Inside a gr.render() function, if a component is re-rendered with the same key, these (and only these) parameters will be preserved in the UI (if they have been changed by the user or an event listener) instead of re-rendered based on the values provided during constructor.
min_height
int | None
None The minimum height of the component, specified in pixels if a number is passed, or in CSS units if a string is passed. If HTMLPlus content exceeds the height, the component will expand to fit the content.
max_height
int | None
None The maximum height of the component, specified in pixels if a number is passed, or in CSS units if a string is passed. If content exceeds the height, the component will scroll.
container
bool
False If True, the HTMLPlus component will be displayed in a container. Default is False.
padding
bool
True If True, the HTMLPlus component will have a certain padding (set by the `--block-padding` CSS variable) in all directions. Default is True.
autoscroll
bool
False If True, will automatically scroll to the bottom of the component when the content changes, unless the user has scrolled up. If False, will not scroll to the bottom when the content changes.
selectable_elements
List[str] | None
None A list of CSS selectors (e.g., ['tr', '.my-button']) for elements within the HTML that are selectable. When an element matching a selector is clicked, the `select` event is triggered. The event data will contain the selector that was matched and the data from the element.

Events

name description
change Triggered when the value of the HTMLPlus changes either because of user input (e.g. a user types in a textbox) OR because of a function update (e.g. an image receives a value from the output of an event trigger). See .input() for a listener that is only triggered by user input.
click Triggered when the HTMLPlus is clicked.
select Event listener for when the user selects or deselects the HTMLPlus. Uses event data gradio.SelectData to carry value referring to the label of the HTMLPlus, and selected to refer to state of the HTMLPlus. See EventData documentation on how to use this event data

User function

The impact on the users predict function varies depending on whether the component is used as an input or output for an event (or both).

  • When used as an Input, the component only impacts the input signature of the user function.
  • When used as an output, the component only impacts the return signature of the user function.

The code snippet below is accurate in cases where the component is used as both an input and an output.

  • As output: Is passed, (Rarely used) passes the HTMLPlus as a str.
  • As input: Should return, expects a str consisting of valid HTMLPlus.
def predict(
    value: str | None
) -> str | None:
    return value

Metadata

Release files for gradio-htmlplus 0.0.1

For a detailed explanation of source distributions (sdists) and built distributions (wheels), please see the package formats documentation.

Source distribution (sdist)

Source distribution for gradio-htmlplus 0.0.1
File Size Uploaded Provenance Actions
gradio_htmlplus-0.0.1.tar.gz 153.9 kB Without provenance Details for gradio_htmlplus-0.0.1.tar.gz

Built distribution (wheel)

Table of built distributions (wheels) for gradio-htmlplus 0.0.1
File Interpreter ABI Platform Actions
gradio_htmlplus-0.0.1-py3-none-any.whl Python 3 none any Details for gradio_htmlplus-0.0.1-py3-none-any.whl

Total release size: 245.1 kB

Release files / gradio_htmlplus-0.0.1.tar.gz

Download URL gradio_htmlplus-0.0.1.tar.gz
Size 153.9 kB
Tags Source
SHA-256 checksum
How to use checksums
d67edbd074fb50f14776b5628c8012144bf4efd5b1b138fc65a22d6afbd390ef
BLAKE2b-256 checksum
How to use checksums
ef6df13e62a4f968a846bd2bbb44fbfb63d77a0bf960f3b7d13e5df5ef58b1c6
Upload date
Uploaded using Trusted Publishing?
What is trusted publishing?
No
Uploaded via twine/6.1.0 CPython/3.10.11

Release files / gradio_htmlplus-0.0.1-py3-none-any.whl

Download URL gradio_htmlplus-0.0.1-py3-none-any.whl
Size 91.1 kB
Tags Python 3
SHA-256 checksum
How to use checksums
efa614248032666e27081da514feb1138928075c2b089f55dc94e0ea64b4a087
BLAKE2b-256 checksum
How to use checksums
cb4e7d30c6332d1bb5b7c230f71ebddc8ca719200f4f126f5efd55b9f4d50fa8
Upload date
Uploaded using Trusted Publishing?
What is trusted publishing?
No
Uploaded via twine/6.1.0 CPython/3.10.11

Security for gradio-htmlplus 0.0.1

Provenance

Provenance describes where a file came from. On PyPI, provenance is shared via attestations, which provide a verifiable record of the build or publishing details. View details, limitations and caveats.

No provenance found

None of the files in this release were uploaded with provenance metadata.

A note on package security

PyPI is a repository for distributing packages, not a service for auditing them. While third-party security researchers and our staff do their best to detect and remove malicious packages, PyPI cannot guarantee the quality, security or suitability of any given package.

To learn more about protecting yourself from malicious actors, visit our package security documentation.

Release history Release notifications | RSS feed

This release

0.0.1 This release

2 release files No provenance

Anthropic, PBC Visionary sponsor Bloomberg Visionary sponsor Hudson River Trading Visionary sponsor Meta Visionary sponsor NVIDIA Visionary sponsor Microsoft Sustainability sponsor Depot Continuous Integration AWS Cloud computing and Security Sponsor Datadog Monitoring Fastly CDN Google Download Analytics Sentry Error logging StatusPage Status page