Spaces:
Running
Running
File size: 14,629 Bytes
70c137d | 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 | ---
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`
<img alt="Static Badge" src="https://img.shields.io/badge/version%20-%200.0.1%20-%20blue"> <a href="https://huggingface.co/spaces/elismasilva/gradio_htmlplus"><img src="https://img.shields.io/badge/%F0%9F%A4%97%20Hugging%20Face-Demo-blue"></a><p><span>💻 <a href='https://github.com/DEVAIEXP/gradio_component_htmlplus'>Component GitHub Code</a></span></p>
Gradio HTML Advanced Component
## Installation
```bash
pip install gradio_htmlplus
```
## Usage
```python
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
<table>
<thead>
<tr>
<th align="left">name</th>
<th align="left" style="width: 25%;">type</th>
<th align="left">default</th>
<th align="left">description</th>
</tr>
</thead>
<tbody>
<tr>
<td align="left"><code>value</code></td>
<td align="left" style="width: 25%;">
```python
str | Callable | None
```
</td>
<td align="left"><code>None</code></td>
<td align="left">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.</td>
</tr>
<tr>
<td align="left"><code>label</code></td>
<td align="left" style="width: 25%;">
```python
str | I18nData | None
```
</td>
<td align="left"><code>None</code></td>
<td align="left">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.</td>
</tr>
<tr>
<td align="left"><code>every</code></td>
<td align="left" style="width: 25%;">
```python
Timer | float | None
```
</td>
<td align="left"><code>None</code></td>
<td align="left">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.</td>
</tr>
<tr>
<td align="left"><code>inputs</code></td>
<td align="left" style="width: 25%;">
```python
Component | Sequence[Component] | set[Component] | None
```
</td>
<td align="left"><code>None</code></td>
<td align="left">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.</td>
</tr>
<tr>
<td align="left"><code>show_label</code></td>
<td align="left" style="width: 25%;">
```python
bool
```
</td>
<td align="left"><code>False</code></td>
<td align="left">If True, the label will be displayed. If False, the label will be hidden.</td>
</tr>
<tr>
<td align="left"><code>visible</code></td>
<td align="left" style="width: 25%;">
```python
bool | Literal["hidden"]
```
</td>
<td align="left"><code>True</code></td>
<td align="left">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</td>
</tr>
<tr>
<td align="left"><code>elem_id</code></td>
<td align="left" style="width: 25%;">
```python
str | None
```
</td>
<td align="left"><code>None</code></td>
<td align="left">An optional string that is assigned as the id of this component in the HTMLPlus DOM. Can be used for targeting CSS styles.</td>
</tr>
<tr>
<td align="left"><code>elem_classes</code></td>
<td align="left" style="width: 25%;">
```python
list[str] | str | None
```
</td>
<td align="left"><code>None</code></td>
<td align="left">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.</td>
</tr>
<tr>
<td align="left"><code>render</code></td>
<td align="left" style="width: 25%;">
```python
bool
```
</td>
<td align="left"><code>True</code></td>
<td align="left">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.</td>
</tr>
<tr>
<td align="left"><code>key</code></td>
<td align="left" style="width: 25%;">
```python
int | str | tuple[int | str, ...] | None
```
</td>
<td align="left"><code>None</code></td>
<td align="left">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.</td>
</tr>
<tr>
<td align="left"><code>preserved_by_key</code></td>
<td align="left" style="width: 25%;">
```python
list[str] | str | None
```
</td>
<td align="left"><code>"value"</code></td>
<td align="left">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.</td>
</tr>
<tr>
<td align="left"><code>min_height</code></td>
<td align="left" style="width: 25%;">
```python
int | None
```
</td>
<td align="left"><code>None</code></td>
<td align="left">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.</td>
</tr>
<tr>
<td align="left"><code>max_height</code></td>
<td align="left" style="width: 25%;">
```python
int | None
```
</td>
<td align="left"><code>None</code></td>
<td align="left">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.</td>
</tr>
<tr>
<td align="left"><code>container</code></td>
<td align="left" style="width: 25%;">
```python
bool
```
</td>
<td align="left"><code>False</code></td>
<td align="left">If True, the HTMLPlus component will be displayed in a container. Default is False.</td>
</tr>
<tr>
<td align="left"><code>padding</code></td>
<td align="left" style="width: 25%;">
```python
bool
```
</td>
<td align="left"><code>True</code></td>
<td align="left">If True, the HTMLPlus component will have a certain padding (set by the `--block-padding` CSS variable) in all directions. Default is True.</td>
</tr>
<tr>
<td align="left"><code>autoscroll</code></td>
<td align="left" style="width: 25%;">
```python
bool
```
</td>
<td align="left"><code>False</code></td>
<td align="left">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.</td>
</tr>
<tr>
<td align="left"><code>selectable_elements</code></td>
<td align="left" style="width: 25%;">
```python
List[str] | None
```
</td>
<td align="left"><code>None</code></td>
<td align="left">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.</td>
</tr>
</tbody></table>
### 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.
```python
def predict(
value: str | None
) -> str | None:
return value
```
|