-
Notifications
You must be signed in to change notification settings - Fork 3.3k
Expand file tree
/
Copy pathrun.py
More file actions
433 lines (395 loc) · 14.9 KB
/
run.py
File metadata and controls
433 lines (395 loc) · 14.9 KB
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
422
423
424
425
426
427
428
429
430
431
432
433
import os
import gradio as gr
with gr.Blocks() as demo:
gr.Markdown("""
# Simple HTML usecase
This is the classic `gr.HTML` usecase where we just want to render some static HTML.
""")
simple_html = gr.HTML("<h1 style='color:purple;' id='simple'>Hello, World!</h1>")
gr.Markdown("""
# Templated HTML usecase
'value' can now be anything, and it can be used inside the `html_template` using `${value}` syntax.
Note that when used as output or input, `value` is just this specific value rather than the entire HTML.
""")
with gr.Row():
name1 = gr.Textbox(label="Name")
templated_html = gr.HTML(
"",
html_template="<h1>Hello, {{value}}! ${value.length} letters</h1>",
elem_id="templated",
)
name1.change(lambda x: x, inputs=name1, outputs=templated_html)
gr.Markdown("""
# Additional Props
You are not limited to using `${value}` in the templates, you can add any number of custom tags to the template, and pass them to the component as keyword arguments. These props can be updated via python event listeners as well.
""")
with gr.Row():
templated_html_props = gr.HTML(
"John",
html_template="""
<h1 style="font-size: ${fontSize}px;">Hello, ${value}!</h1>
""",
fontSize=30,
elem_id="props",
)
slider = gr.Slider(10, 100, value=30, label="Font Size")
slider.change(
lambda x: gr.HTML(fontSize=x), inputs=slider, outputs=templated_html_props
)
gr.Markdown("""
# CSS Templating
We can also template CSS, which is automatically scoped to the component.
""")
with gr.Row():
name2 = gr.Textbox(label="Person")
color = gr.ColorPicker(label="Text Color", value="#00ff00")
bold = gr.Checkbox(label="Bold Text", value=True)
templated_html_css = gr.HTML(
["J", "o", "h", "n"],
html_template="""
<h1>Hello, ${value.join('')}!</h1>
<ul>
{{#each value}}
<li>{{this}}</li>
{{/each}}
</ul>
""",
css_template="""
h1, li {
color: ${color};
font-weight: ${bold ? 'bold' : 'normal'};
}
""",
color="green",
bold=True,
elem_id="css",
)
with gr.Row():
btn = gr.Button("Update HTML")
btn_blue = gr.Button("Make HTML Blue")
def update_templated_html_css(name, color, bold):
return gr.HTML(value=list(name), color=color, bold=bold)
btn.click(
update_templated_html_css,
inputs=[name2, color, bold],
outputs=templated_html_css,
)
btn_blue.click(lambda: gr.HTML(color="blue"), outputs=templated_html_css)
gr.Markdown("""
# JS Prop Updates
We can now trigger events from gr.HTML using event listeners in `js_on_load`. This script has access to `element` which refers to the parent element, and `trigger(event_name)` or `trigger(event_name, event_data)`, which can be used to dispatch events.
""")
button_set = gr.HTML(
html_template="""
<button id='A'>A</button>
<button id='B'>B</button>
<button id='C'>C</button>
""",
css_template="""
button {
padding: 10px;
background-color: red;
}
""",
js_on_load="""
const buttons = element.querySelectorAll('button');
buttons.forEach(button => {
button.addEventListener('click', () => {
trigger('click', {clicked: button.innerText});
});
});
""",
elem_id="button_set",
)
clicked_box = gr.Textbox(label="Clicked")
def on_button_click(evt: gr.EventData):
return evt.clicked
button_set.click(on_button_click, outputs=clicked_box)
gr.Markdown("""
# JS Prop Changes
You can also update `value` or any other prop of the component from JS using `props`, e.g., `props.value = "new value"` will update the `value` prop and re-render the HTML template.
""")
form = gr.HTML(
html_template="""
<input type="text" value="${value}" id="text-input" />
<p>${value.length} letters</p>
<button class="submit" style="display: ${valid ? 'block' : 'none'};">submit</button>
<button class="clear">clear</button>
""",
js_on_load="""
const input = element.querySelector('input');
const submit_button = element.querySelector('button.submit');
const clear_button = element.querySelector('button.clear');
input.addEventListener('input', () => {
props.valid = input.value.length > 5;
props.value = input.value;
});
submit_button.addEventListener('click', () => {
trigger('submit');
});
clear_button.addEventListener('click', () => {
props.value = "";
props.valid = false;
trigger('clear');
});
""",
valid=False,
elem_id="form",
)
output_box = gr.Textbox(label="Output Box")
form.submit(lambda x: x, form, outputs=output_box)
output_box.submit(lambda x: x, output_box, outputs=form)
gr.Markdown("""
# Watch API
Use `watch` inside `js_on_load` to run a callback after the template re-renders whenever specific props change. The callback takes no arguments — read current values from `props` directly.
""")
watch_html = gr.HTML(
value=0,
html_template="""
<div>
<div>Will 'submit' at 10, currently ${value}</div>
<button class="inc">+1</button>
<button class="reset">Reset</button>
</div>
""",
js_on_load="""
element.querySelector('.inc').addEventListener('click', () => {
props.value++;
});
element.querySelector('.reset').addEventListener('click', () => {
props.value = 0;
});
watch('value', () => {
if (props.value === 10) {
trigger('submit');
}
});
""",
elem_id="watch_demo",
)
watch_output = gr.Textbox(label="Watch Output")
watch_html.submit(lambda x: x, watch_html, outputs=watch_output)
gr.Markdown("""
# Extending gr.HTML for new Components
You can create your own Components by extending the gr.HTML class.
""")
class ListComponent(gr.HTML):
def __init__(self, container=True, label="List", ordered=False, **kwargs):
self.ordered = ordered
super().__init__(
html_template="""
<h2>${label}</h2>
${ordered ? `<ol>` : `<ul>`}
${value.map(item => `<li>${item}</li>`).join('')}
${ordered ? `</ol>` : `</ul>`}
""",
container=container,
label=label,
ordered=ordered,
**kwargs,
)
l1 = ListComponent(
label="Fruits", value=["Apple", "Banana", "Cherry"], elem_id="fruits"
)
l2 = ListComponent(
label="Vegetables",
value=["Carrot", "Broccoli", "Spinach"],
elem_id="vegetables",
)
make_ordered_btn = gr.Button("Make Ordered")
make_unordered_btn = gr.Button("Make Unordered")
make_ordered_btn.click(
lambda: [ListComponent(ordered=True), ListComponent(ordered=True)],
outputs=[l1, l2],
)
make_unordered_btn.click(
lambda: [ListComponent(ordered=False), ListComponent(ordered=False)],
outputs=[l1, l2],
)
failed_template = gr.HTML(
value=None,
html_template="""
${Zalue}
""",
)
gr.Markdown("""
# File Upload via gr.HTML
The `upload` async function is available in `js_on_load`. It takes a JavaScript `File` object,
uploads it to the Gradio server, and returns the server-side file path as a string.
""")
upload_html = gr.HTML(
html_template="""
<div>
<input type="file" id="html-file-input" />
<button id="html-upload-btn" style="margin-left: 8px; padding: 4px 8px;">Upload</button>
<p id="html-upload-status">No file uploaded yet.</p>
</div>
""",
js_on_load="""
const input = element.querySelector('#html-file-input');
const btn = element.querySelector('#html-upload-btn');
const status = element.querySelector('#html-upload-status');
btn.addEventListener('click', async () => {
const file = input.files[0];
if (!file) {
status.textContent = 'Please select a file first.';
return;
}
status.textContent = 'Uploading...';
try {
const { path, url } = await upload(file);
status.textContent = 'Uploaded: ' + path;
trigger('upload', { path: path, url: url, name: file.name });
} catch (e) {
status.textContent = 'Upload failed: ' + e.message;
}
});
""",
elem_id="upload_html"
)
upload_result = gr.Textbox(label="Upload Result", elem_id="upload_result")
def on_html_upload(evt: gr.EventData):
return evt.path
upload_html.upload(on_html_upload, outputs=upload_result)
class TodoList(gr.HTML):
def __init__(
self,
value: list[str] | None = None,
completed: list[int] | None = None,
**kwargs,
):
self.completed = completed or []
super().__init__(
html_template="""
<h2>Todo List</h2>
<ul>
${value.map((item, index) => `
<li style="text-decoration: ${completed.includes(index) ? 'line-through' : 'none'};">
<input type="checkbox" ${completed.includes(index) ? 'checked' : ''} data-index="${index}" />
${item}
</li>
`).join('')}
</ul>
""",
js_on_load="""
const checkboxes = element.querySelectorAll('input[type="checkbox"]');
checkboxes.forEach(checkbox => {
checkbox.addEventListener('change', () => {
const index = parseInt(checkbox.getAttribute('data-index'));
let completed = props.completed || [];
if (checkbox.checked) {
if (!completed.includes(index)) {
completed.push(index);
}
} else {
completed = completed.filter(i => i !== index);
}
props.completed = [...completed];
console.log(JSON.stringify(props.completed))
});
});
""",
completed=self.completed,
value=value,
**kwargs,
)
todo_list = TodoList(
value=["Buy groceries", "Walk the dog", "Read a book"],
completed=[1],
elem_id="todo",
)
gr.Markdown("""
# HTML Children
Use `@children` in `html_template` to render child components inside the HTML wrapper.
""")
with gr.HTML(
html_template="""
<h2>${title}</h2>
@children
<button class="send">Send</button>
""",
css_template="""
border: 2px solid gray;
border-radius: 8px;
padding: 16px;
""",
js_on_load="""
element.querySelector('.send').addEventListener('click', () => {
trigger('submit');
});
""",
title="Contact Form",
elem_id="children_form",
) as children_form:
children_name = gr.Textbox(label="Your Name")
children_email = gr.Textbox(label="Your Email")
children_output = gr.Textbox(label="Children Output")
children_form.submit(
lambda name, email: f"Name: {name}, Email: {email}",
inputs=[children_name, children_email],
outputs=children_output,
)
gr.Markdown("""
# Server Functions
You can call Python functions from `js_on_load` using the `server` object. Pass a list of functions via `server_functions` and they become available as async methods on the `server` object in your JavaScript code.
""")
def list_directory(path):
try:
items = sorted(os.listdir(path))
return [
{"name": item, "is_dir": os.path.isdir(os.path.join(path, item))}
for item in items[:20]
]
except (FileNotFoundError, PermissionError):
return []
server_fn_html = gr.HTML(
value=os.path.dirname(__file__),
html_template="""
<div>
<p>Directory: <strong>${value}</strong></p>
<div id='server-fn-tree'></div>
<button id='server-fn-load'>Load Files</button>
</div>
""",
js_on_load="""
const loadBtn = element.querySelector('#server-fn-load');
const tree = element.querySelector('#server-fn-tree');
loadBtn.addEventListener('click', async () => {
tree.innerHTML = '<em>Loading...</em>';
const items = await server.list_directory(props.value);
tree.innerHTML = '';
items.forEach(item => {
const el = document.createElement('div');
el.textContent = (item.is_dir ? '📁 ' : '📄 ') + item.name;
el.className = 'server-fn-item';
tree.appendChild(el);
});
});
""",
css_template="""
#server-fn-tree { padding: 8px; min-height: 20px; }
.server-fn-item { padding: 2px 8px; }
#server-fn-load { padding: 6px 12px; margin-top: 8px; }
""",
server_functions=[list_directory],
elem_id="server_fns",
)
gr.Markdown("""
# Custom Events
You can trigger custom events (not in the standard event list) from `js_on_load` using `trigger('custom_event_name', data)`. As long as the event name appears in quotes in `js_on_load`, you can attach a Python listener using `component.custom_event_name(fn, ...)`.
""")
keyboard = gr.HTML(
html_template="<p>Press any key...</p>",
js_on_load="""
document.addEventListener('keydown', (e) => {
trigger('keypress', {key: e.key});
});
""",
elem_id="custom_event",
)
key_output = gr.Textbox(label="Key Pressed", elem_id="key_output")
def get_key(evt_data: gr.EventData):
return evt_data.key
keyboard.keypress(get_key, None, key_output)
if __name__ == "__main__":
demo.launch()