jsscclr commited on
Commit
b2e4b35
·
verified ·
1 Parent(s): 04e6590

Update run.py

Browse files
Files changed (1) hide show
  1. run.py +1001 -1
run.py CHANGED
@@ -1,4 +1,1004 @@
1
- from gradio.themes.builder_app import demo
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
2
 
3
  if __name__ == "__main__":
4
  demo.launch()
 
 
1
+ import inspect
2
+ import time
3
+ from collections.abc import Iterable
4
+
5
+ from gradio_client.documentation import document_fn
6
+
7
+ import gradio as gr
8
+
9
+ themes = [
10
+ gr.themes.Base,
11
+ gr.themes.Default,
12
+ gr.themes.Soft,
13
+ gr.themes.Monochrome,
14
+ gr.themes.Glass,
15
+ gr.themes.Origin,
16
+ gr.themes.Citrus,
17
+ gr.themes.Ocean,
18
+ ]
19
+ colors = gr.themes.Color.all
20
+ sizes = gr.themes.Size.all
21
+
22
+ palette_range = [50, 100, 200, 300, 400, 500, 600, 700, 800, 900, 950]
23
+ size_range = ["xxs", "xs", "sm", "md", "lg", "xl", "xxl"]
24
+ docs_theme_core = document_fn(gr.themes.Base.__init__, gr.themes.Base)[1]
25
+ docs_theme_vars = document_fn(gr.themes.Base.set, gr.themes.Base)[1]
26
+
27
+
28
+ def get_docstr(var):
29
+ for parameters in docs_theme_core + docs_theme_vars:
30
+ if parameters["name"] == var:
31
+ return parameters["doc"]
32
+ raise ValueError(f"Variable {var} not found in theme documentation.")
33
+
34
+
35
+ def get_doc_theme_var_groups():
36
+ source = inspect.getsource(gr.themes.Base.set)
37
+ groups = []
38
+ group, desc, variables, flat_variables = None, None, [], []
39
+ for line in source.splitlines():
40
+ line = line.strip()
41
+ if line.startswith(")"):
42
+ break
43
+ elif line.startswith("# "):
44
+ if group is not None:
45
+ groups.append((group, desc, variables))
46
+ group, desc = line[2:].split(": ")
47
+ variables = []
48
+ elif "=" in line:
49
+ var = line.split("=")[0]
50
+ variables.append(var)
51
+ flat_variables.append(var)
52
+ groups.append((group, desc, variables))
53
+ return groups, flat_variables
54
+
55
+
56
+ variable_groups, flat_variables = get_doc_theme_var_groups()
57
+
58
+ css = """
59
+ .gradio-container {
60
+ overflow: visible !important;
61
+ max-width: none !important;
62
+ }
63
+ #controls {
64
+ max-height: 100vh;
65
+ flex-wrap: unset;
66
+ overflow-y: scroll;
67
+ position: sticky;
68
+ top: 0;
69
+ }
70
+ #controls::-webkit-scrollbar {
71
+ -webkit-appearance: none;
72
+ width: 7px;
73
+ }
74
+
75
+ #controls::-webkit-scrollbar-thumb {
76
+ border-radius: 4px;
77
+ background-color: rgba(0, 0, 0, .5);
78
+ box-shadow: 0 0 1px rgba(255, 255, 255, .5);
79
+ }
80
+ """
81
+
82
+ with gr.Blocks( # noqa: SIM117
83
+ theme=gr.themes.Base(),
84
+ css=css,
85
+ title="Gradio Theme Builder",
86
+ head="<style id='theme_css'></style>",
87
+ ) as demo:
88
+ with gr.Row():
89
+ with gr.Column(scale=1, elem_id="controls", min_width=400):
90
+ with gr.Row():
91
+ undo_btn = gr.Button("Undo", size="sm")
92
+ dark_mode_btn = gr.Button("Dark Mode", variant="primary", size="sm")
93
+ with gr.Tabs():
94
+ with gr.TabItem("Source Theme"):
95
+ gr.Markdown(
96
+ """
97
+ Select a base theme below you would like to build off of. Note: when you click 'Load Theme', all variable values in other tabs will be overwritten!
98
+ """
99
+ )
100
+ base_theme_dropdown = gr.Dropdown(
101
+ [theme.__name__ for theme in themes],
102
+ value="Base",
103
+ show_label=False,
104
+ label="Theme",
105
+ )
106
+ load_theme_btn = gr.Button("Load Theme", elem_id="load_theme")
107
+ with gr.TabItem("Core Colors"):
108
+ gr.Markdown(
109
+ """Set the three hues of the theme: `primary_hue`, `secondary_hue`, and `neutral_hue`.
110
+ Each of these is a palette ranging from 50 to 950 in brightness. Pick a preset palette - optionally, open the accordion to overwrite specific values.
111
+ Note that these variables do not affect elements directly, but are referenced by other variables with asterisks, such as `*primary_200` or `*neutral_950`."""
112
+ )
113
+ primary_hue = gr.Dropdown(
114
+ [color.name for color in colors], label="Primary Hue"
115
+ )
116
+ with gr.Accordion(label="Primary Hue Palette", open=False):
117
+ primary_hues = []
118
+ for i in palette_range:
119
+ primary_hues.append(
120
+ gr.ColorPicker(
121
+ label=f"primary_{i}",
122
+ )
123
+ )
124
+
125
+ secondary_hue = gr.Dropdown(
126
+ [color.name for color in colors], label="Secondary Hue"
127
+ )
128
+ with gr.Accordion(label="Secondary Hue Palette", open=False):
129
+ secondary_hues = []
130
+ for i in palette_range:
131
+ secondary_hues.append(
132
+ gr.ColorPicker(
133
+ label=f"secondary_{i}",
134
+ )
135
+ )
136
+
137
+ neutral_hue = gr.Dropdown(
138
+ [color.name for color in colors], label="Neutral hue"
139
+ )
140
+ with gr.Accordion(label="Neutral Hue Palette", open=False):
141
+ neutral_hues = []
142
+ for i in palette_range:
143
+ neutral_hues.append(
144
+ gr.ColorPicker(
145
+ label=f"neutral_{i}",
146
+ )
147
+ )
148
+
149
+ with gr.TabItem("Core Sizing"):
150
+ gr.Markdown(
151
+ """Set the sizing of the theme via: `text_size`, `spacing_size`, and `radius_size`.
152
+ Each of these is set to a collection of sizes ranging from `xxs` to `xxl`. Pick a preset size collection - optionally, open the accordion to overwrite specific values.
153
+ Note that these variables do not affect elements directly, but are referenced by other variables with asterisks, such as `*spacing_xl` or `*text_sm`.
154
+ """
155
+ )
156
+ text_size = gr.Dropdown(
157
+ [size.name for size in sizes if size.name.startswith("text_")],
158
+ label="Text Size",
159
+ )
160
+ with gr.Accordion(label="Text Size Range", open=False):
161
+ text_sizes = []
162
+ for i in size_range:
163
+ text_sizes.append(
164
+ gr.Textbox(
165
+ label=f"text_{i}",
166
+ )
167
+ )
168
+
169
+ spacing_size = gr.Dropdown(
170
+ [
171
+ size.name
172
+ for size in sizes
173
+ if size.name.startswith("spacing_")
174
+ ],
175
+ label="Spacing Size",
176
+ )
177
+ with gr.Accordion(label="Spacing Size Range", open=False):
178
+ spacing_sizes = []
179
+ for i in size_range:
180
+ spacing_sizes.append(
181
+ gr.Textbox(
182
+ label=f"spacing_{i}",
183
+ )
184
+ )
185
+
186
+ radius_size = gr.Dropdown(
187
+ [
188
+ size.name
189
+ for size in sizes
190
+ if size.name.startswith("radius_")
191
+ ],
192
+ label="Radius Size",
193
+ )
194
+ with gr.Accordion(label="Radius Size Range", open=False):
195
+ radius_sizes = []
196
+ for i in size_range:
197
+ radius_sizes.append(
198
+ gr.Textbox(
199
+ label=f"radius_{i}",
200
+ )
201
+ )
202
+
203
+ with gr.TabItem("Core Fonts"):
204
+ gr.Markdown(
205
+ """Set the main `font` and the monospace `font_mono` here.
206
+ Set up to 4 values for each (fallbacks in case a font is not available).
207
+ Check "Google Font" if font should be loaded from Google Fonts.
208
+ """
209
+ )
210
+ gr.Markdown("### Main Font")
211
+ main_fonts, main_is_google = [], []
212
+ for i in range(4):
213
+ with gr.Row():
214
+ font = gr.Textbox(label=f"Font {i + 1}")
215
+ font_is_google = gr.Checkbox(label="Google Font")
216
+ main_fonts.append(font)
217
+ main_is_google.append(font_is_google)
218
+
219
+ mono_fonts, mono_is_google = [], []
220
+ gr.Markdown("### Monospace Font")
221
+ for i in range(4):
222
+ with gr.Row():
223
+ font = gr.Textbox(label=f"Font {i + 1}")
224
+ font_is_google = gr.Checkbox(label="Google Font")
225
+ mono_fonts.append(font)
226
+ mono_is_google.append(font_is_google)
227
+
228
+ theme_var_input = []
229
+
230
+ core_color_suggestions = (
231
+ [f"*primary_{i}" for i in palette_range]
232
+ + [f"*secondary_{i}" for i in palette_range]
233
+ + [f"*neutral_{i}" for i in palette_range]
234
+ )
235
+
236
+ variable_suggestions = {
237
+ "fill": core_color_suggestions[:],
238
+ "color": core_color_suggestions[:],
239
+ "text_size": [f"*text_{i}" for i in size_range],
240
+ "radius": [f"*radius_{i}" for i in size_range],
241
+ "padding": [f"*spacing_{i}" for i in size_range],
242
+ "gap": [f"*spacing_{i}" for i in size_range],
243
+ "weight": [
244
+ "100",
245
+ "200",
246
+ "300",
247
+ "400",
248
+ "500",
249
+ "600",
250
+ "700",
251
+ "800",
252
+ ],
253
+ "shadow": ["none"],
254
+ "border_width": [],
255
+ }
256
+ for variable in flat_variables:
257
+ if variable.endswith("_dark"):
258
+ continue
259
+ for style_type in variable_suggestions:
260
+ if style_type in variable:
261
+ variable_suggestions[style_type].append("*" + variable)
262
+ break
263
+
264
+ variable_suggestions["fill"], variable_suggestions["color"] = (
265
+ variable_suggestions["fill"]
266
+ + variable_suggestions["color"][len(core_color_suggestions) :],
267
+ variable_suggestions["color"]
268
+ + variable_suggestions["fill"][len(core_color_suggestions) :],
269
+ )
270
+
271
+ for group, desc, variables in variable_groups:
272
+ with gr.TabItem(group):
273
+ gr.Markdown(
274
+ desc
275
+ + "\nYou can set these to one of the dropdown values, or clear the dropdown to set a custom value."
276
+ )
277
+ for variable in variables:
278
+ suggestions = []
279
+ for style_type in variable_suggestions:
280
+ if style_type in variable:
281
+ suggestions = variable_suggestions[style_type][:]
282
+ if "*" + variable in suggestions:
283
+ suggestions.remove("*" + variable)
284
+ break
285
+ dropdown = gr.Dropdown(
286
+ label=variable,
287
+ info=get_docstr(variable),
288
+ choices=suggestions,
289
+ allow_custom_value=True,
290
+ )
291
+ theme_var_input.append(dropdown)
292
+
293
+ # App
294
+
295
+ with gr.Column(scale=6, elem_id="app"):
296
+ with gr.Column(variant="panel"):
297
+ gr.Markdown(
298
+ """
299
+ # Theme Builder
300
+ Welcome to the theme builder. The left panel is where you create the theme. The different aspects of the theme are broken down into different tabs. Here's how to navigate them:
301
+ 1. First, set the "Source Theme". This will set the default values that you can override.
302
+ 2. Set the "Core Colors", "Core Sizing" and "Core Fonts". These are the core variables that are used to build the rest of the theme.
303
+ 3. The rest of the tabs set specific CSS theme variables. These control finer aspects of the UI. Within these theme variables, you can reference the core variables and other theme variables using the variable name preceded by an asterisk, e.g. `*primary_50` or `*body_text_color`. Clear the dropdown to set a custom value.
304
+ 4. Once you have finished your theme, click on "View Code" below to see how you can integrate the theme into your app. You can also click on "Upload to Hub" to upload your theme to the Hugging Face Hub, where others can download and use your theme.
305
+ """
306
+ )
307
+ with gr.Accordion("View Code", open=False):
308
+ output_code = gr.Code(language="python")
309
+ with gr.Accordion("Upload to Hub", open=False):
310
+ gr.Markdown(
311
+ "You can save your theme on the Hugging Face Hub. HF API write token can be found [here](https://huggingface.co/settings/tokens)."
312
+ )
313
+ with gr.Row():
314
+ theme_name = gr.Textbox(label="Theme Name")
315
+ theme_hf_token = gr.Textbox(label="Hugging Face Write Token")
316
+ theme_version = gr.Textbox(
317
+ label="Version",
318
+ placeholder="Leave blank to automatically update version.",
319
+ )
320
+ upload_to_hub_btn = gr.Button("Upload to Hub")
321
+ theme_upload_status = gr.Markdown(visible=False)
322
+
323
+ gr.Markdown("Below this panel is a dummy app to demo your theme.")
324
+
325
+ name = gr.Textbox(
326
+ label="Name",
327
+ info="Full name, including middle name. No special characters.",
328
+ placeholder="John Doe",
329
+ value="John Doe",
330
+ interactive=True,
331
+ )
332
+
333
+ gr.Interface(lambda x: x, "number", "textbox")
334
+
335
+ with gr.Row():
336
+ slider1 = gr.Slider(label="Slider 1")
337
+ slider2 = gr.Slider(label="Slider 2")
338
+ gr.CheckboxGroup(["A", "B", "C"], label="Checkbox Group")
339
+
340
+ with gr.Row():
341
+ with gr.Column(variant="panel", scale=1):
342
+ gr.Markdown("## Panel 1")
343
+ radio = gr.Radio(
344
+ ["A", "B", "C"],
345
+ label="Radio",
346
+ info="Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat.",
347
+ )
348
+ drop = gr.Dropdown(
349
+ ["Option 1", "Option 2", "Option 3"], show_label=False
350
+ )
351
+ drop_2 = gr.Dropdown(
352
+ ["Option A", "Option B", "Option C"],
353
+ multiselect=True,
354
+ value=["Option A"],
355
+ label="Dropdown",
356
+ interactive=True,
357
+ )
358
+ check = gr.Checkbox(label="Go")
359
+ with gr.Column(variant="panel", scale=2):
360
+ img = gr.Image(
361
+ "https://gradio-static-files.s3.us-west-2.amazonaws.com/header-image.jpg",
362
+ label="Image",
363
+ height=320,
364
+ )
365
+ with gr.Row():
366
+ go_btn = gr.Button("Go", variant="primary")
367
+ clear_btn = gr.Button("Clear", variant="secondary")
368
+
369
+ def go(*_args):
370
+ time.sleep(3)
371
+ return "https://gradio-static-files.s3.us-west-2.amazonaws.com/header-image.jpg"
372
+
373
+ go_btn.click(
374
+ go,
375
+ [radio, drop, drop_2, check, name],
376
+ img,
377
+ show_api=False,
378
+ )
379
+
380
+ def clear():
381
+ time.sleep(0.2)
382
+
383
+ clear_btn.click(clear, None, img)
384
+
385
+ with gr.Row():
386
+ btn1 = gr.Button("Button 1", size="sm")
387
+ btn2 = gr.UploadButton(size="sm")
388
+ stop_btn = gr.Button("Stop", variant="stop", size="sm")
389
+
390
+ gr.Examples(
391
+ examples=[
392
+ [
393
+ "A",
394
+ "Option 1",
395
+ ["Option B"],
396
+ True,
397
+ ],
398
+ [
399
+ "B",
400
+ "Option 2",
401
+ ["Option B", "Option C"],
402
+ False,
403
+ ],
404
+ ],
405
+ inputs=[radio, drop, drop_2, check],
406
+ label="Examples",
407
+ )
408
+
409
+ with gr.Row():
410
+ gr.Dataframe(value=[[1, 2, 3], [4, 5, 6], [7, 8, 9]], label="Dataframe")
411
+ gr.JSON(
412
+ value={"a": 1, "b": 2, "c": {"test": "a", "test2": [1, 2, 3]}},
413
+ label="JSON",
414
+ )
415
+ gr.Label(value={"cat": 0.7, "dog": 0.2, "fish": 0.1})
416
+ gr.File()
417
+ with gr.Row():
418
+ gr.ColorPicker()
419
+ gr.Video(
420
+ "https://gradio-static-files.s3.us-west-2.amazonaws.com/world.mp4"
421
+ )
422
+ gr.Gallery(
423
+ [
424
+ (
425
+ "https://gradio-static-files.s3.us-west-2.amazonaws.com/lion.jpg",
426
+ "lion",
427
+ ),
428
+ (
429
+ "https://gradio-static-files.s3.us-west-2.amazonaws.com/logo.png",
430
+ "logo",
431
+ ),
432
+ (
433
+ "https://gradio-static-files.s3.us-west-2.amazonaws.com/tower.jpg",
434
+ "tower",
435
+ ),
436
+ ],
437
+ height="200px",
438
+ columns=2,
439
+ )
440
+
441
+ with gr.Row():
442
+ with gr.Column(scale=2):
443
+ chatbot = gr.Chatbot([("Hello", "Hi")], label="Chatbot")
444
+ multimodal = gr.MultimodalTextbox(
445
+ interactive=True, show_label=False
446
+ )
447
+ chat_btn = gr.Button("Add messages")
448
+
449
+ chat_btn.click(
450
+ lambda history: history
451
+ + [["How are you?", "I am good."]]
452
+ + (time.sleep(2) or []),
453
+ chatbot,
454
+ chatbot,
455
+ show_api=False,
456
+ )
457
+ with gr.Column(scale=1):
458
+ with gr.Accordion("Advanced Settings"):
459
+ gr.Markdown("Hello")
460
+ gr.Number(label="Chatbot control 1")
461
+ gr.Number(label="Chatbot control 2")
462
+ gr.Number(label="Chatbot control 3")
463
+
464
+ # Event Listeners
465
+
466
+ secret_css = gr.Textbox(visible=False)
467
+ secret_font = gr.JSON(visible=False)
468
+
469
+ demo.load( # doing this via python was not working for some reason, so using this hacky method for now
470
+ None,
471
+ None,
472
+ None,
473
+ js="""() => {
474
+ let evt_listener = window.setTimeout(
475
+ () => {
476
+ load_theme_btn = document.querySelector('#load_theme');
477
+ if (load_theme_btn) {
478
+ load_theme_btn.click();
479
+ window.clearTimeout(evt_listener);
480
+ }
481
+ },
482
+ 100
483
+ );
484
+ }""",
485
+ show_api=False,
486
+ )
487
+
488
+ theme_inputs = (
489
+ [primary_hue, secondary_hue, neutral_hue]
490
+ + primary_hues
491
+ + secondary_hues
492
+ + neutral_hues
493
+ + [text_size, spacing_size, radius_size]
494
+ + text_sizes
495
+ + spacing_sizes
496
+ + radius_sizes
497
+ + main_fonts
498
+ + main_is_google
499
+ + mono_fonts
500
+ + mono_is_google
501
+ + theme_var_input
502
+ )
503
+
504
+ def load_theme(theme_name):
505
+ theme = [theme for theme in themes if theme.__name__ == theme_name][0]
506
+
507
+ parameters = inspect.signature(theme.__init__).parameters
508
+ primary_hue = parameters["primary_hue"].default
509
+ secondary_hue = parameters["secondary_hue"].default
510
+ neutral_hue = parameters["neutral_hue"].default
511
+ text_size = parameters["text_size"].default
512
+ spacing_size = parameters["spacing_size"].default
513
+ radius_size = parameters["radius_size"].default
514
+
515
+ theme = theme()
516
+
517
+ font = theme._font[:4]
518
+ font_mono = theme._font_mono[:4]
519
+ font_is_google = [isinstance(f, gr.themes.GoogleFont) for f in font]
520
+ font_mono_is_google = [
521
+ isinstance(f, gr.themes.GoogleFont) for f in font_mono
522
+ ]
523
+
524
+ def pad_to_4(x):
525
+ return x + [None] * (4 - len(x))
526
+
527
+ var_output = []
528
+ for variable in flat_variables:
529
+ theme_val = getattr(theme, variable)
530
+ if theme_val is None and variable.endswith("_dark"):
531
+ theme_val = getattr(theme, variable[:-5])
532
+ var_output.append(theme_val)
533
+
534
+ return (
535
+ [primary_hue.name, secondary_hue.name, neutral_hue.name]
536
+ + primary_hue.expand()
537
+ + secondary_hue.expand()
538
+ + neutral_hue.expand()
539
+ + [text_size.name, spacing_size.name, radius_size.name]
540
+ + text_size.expand()
541
+ + spacing_size.expand()
542
+ + radius_size.expand()
543
+ + pad_to_4([f.name for f in font])
544
+ + pad_to_4(font_is_google)
545
+ + pad_to_4([f.name for f in font_mono])
546
+ + pad_to_4(font_mono_is_google)
547
+ + var_output
548
+ )
549
+
550
+ def generate_theme_code(
551
+ base_theme, final_theme, core_variables, final_main_fonts, final_mono_fonts
552
+ ):
553
+ base_theme_name = base_theme
554
+ base_theme = [theme for theme in themes if theme.__name__ == base_theme][
555
+ 0
556
+ ]()
557
+
558
+ parameters = inspect.signature(base_theme.__init__).parameters
559
+ primary_hue = parameters["primary_hue"].default
560
+ secondary_hue = parameters["secondary_hue"].default
561
+ neutral_hue = parameters["neutral_hue"].default
562
+ text_size = parameters["text_size"].default
563
+ spacing_size = parameters["spacing_size"].default
564
+ radius_size = parameters["radius_size"].default
565
+ font = parameters["font"].default
566
+ font = [font] if not isinstance(font, Iterable) else font
567
+ font = [
568
+ gr.themes.Font(f) if not isinstance(f, gr.themes.Font) else f
569
+ for f in font
570
+ ]
571
+ font_mono = parameters["font_mono"].default
572
+ font_mono = (
573
+ [font_mono] if not isinstance(font_mono, Iterable) else font_mono
574
+ )
575
+ font_mono = [
576
+ gr.themes.Font(f) if not isinstance(f, gr.themes.Font) else f
577
+ for f in font_mono
578
+ ]
579
+
580
+ core_diffs = {}
581
+ specific_core_diffs = {}
582
+ core_var_names = [
583
+ "primary_hue",
584
+ "secondary_hue",
585
+ "neutral_hue",
586
+ "text_size",
587
+ "spacing_size",
588
+ "radius_size",
589
+ ]
590
+ for value_name, base_value, source_class, final_value in zip(
591
+ core_var_names,
592
+ [
593
+ primary_hue,
594
+ secondary_hue,
595
+ neutral_hue,
596
+ text_size,
597
+ spacing_size,
598
+ radius_size,
599
+ ],
600
+ [
601
+ gr.themes.Color,
602
+ gr.themes.Color,
603
+ gr.themes.Color,
604
+ gr.themes.Size,
605
+ gr.themes.Size,
606
+ gr.themes.Size,
607
+ ],
608
+ core_variables,
609
+ strict=False,
610
+ ):
611
+ if base_value.name != final_value:
612
+ core_diffs[value_name] = final_value
613
+ source_obj = [
614
+ obj for obj in source_class.all if obj.name == final_value
615
+ ][0]
616
+ final_attr_values = {}
617
+ diff = False
618
+ for attr in dir(source_obj):
619
+ if attr in ["all", "name", "expand"] or attr.startswith("_"):
620
+ continue
621
+ final_theme_attr = (
622
+ value_name.split("_")[0]
623
+ + "_"
624
+ + (attr[1:] if source_class == gr.themes.Color else attr)
625
+ )
626
+ final_attr_values[final_theme_attr] = getattr(
627
+ final_theme, final_theme_attr
628
+ )
629
+ if getattr(source_obj, attr) != final_attr_values[final_theme_attr]:
630
+ diff = True
631
+ if diff:
632
+ new_final_attr_values = {}
633
+ # We need to update the theme keys to match the color and size attribute names
634
+ for key, val in final_attr_values.items():
635
+ if key.startswith(("primary_", "secondary_", "neutral_")):
636
+ color_key = "c" + key.split("_")[-1]
637
+ new_final_attr_values[color_key] = val
638
+ elif key.startswith(("text_", "spacing_", "radius_")):
639
+ size_key = key.split("_")[-1]
640
+ new_final_attr_values[size_key] = val
641
+ else:
642
+ new_final_attr_values[key] = val
643
+ specific_core_diffs[value_name] = (
644
+ source_class,
645
+ new_final_attr_values,
646
+ )
647
+
648
+ font_diffs = {}
649
+
650
+ final_main_fonts = [font for font in final_main_fonts if font[0]]
651
+ final_mono_fonts = [font for font in final_mono_fonts if font[0]]
652
+ font = font[:4]
653
+ font_mono = font_mono[:4]
654
+ for base_font_set, theme_font_set, font_set_name in [
655
+ (font, final_main_fonts, "font"),
656
+ (font_mono, final_mono_fonts, "font_mono"),
657
+ ]:
658
+ if len(base_font_set) != len(theme_font_set) or any(
659
+ base_font.name != theme_font[0]
660
+ or isinstance(base_font, gr.themes.GoogleFont) != theme_font[1]
661
+ for base_font, theme_font in zip(
662
+ base_font_set, theme_font_set, strict=False
663
+ )
664
+ ):
665
+ font_diffs[font_set_name] = [
666
+ f"gr.themes.GoogleFont('{font_name}')"
667
+ if is_google_font
668
+ else f"'{font_name}'"
669
+ for font_name, is_google_font in theme_font_set
670
+ ]
671
+
672
+ newline = "\n"
673
+
674
+ core_diffs_code = ""
675
+ if len(core_diffs) + len(specific_core_diffs) > 0:
676
+ for var_name in core_var_names:
677
+ if var_name in specific_core_diffs:
678
+ cls, vals = specific_core_diffs[var_name]
679
+ core_diffs_code += f""" {var_name}=gr.themes.{cls.__name__}({', '.join(f'''{k}="{v}"''' for k, v in vals.items())}),\n"""
680
+ elif var_name in core_diffs:
681
+ var_val = core_diffs[var_name]
682
+ if var_name.endswith("_size"):
683
+ var_val = var_val.split("_")[-1]
684
+ core_diffs_code += f""" {var_name}="{var_val}",\n"""
685
+
686
+ font_diffs_code = ""
687
+
688
+ if len(font_diffs) > 0:
689
+ font_diffs_code = "".join(
690
+ [
691
+ f""" {font_set_name}=[{", ".join(fonts)}],\n"""
692
+ for font_set_name, fonts in font_diffs.items()
693
+ ]
694
+ )
695
+ var_diffs = {}
696
+ for variable in flat_variables:
697
+ base_theme_val = getattr(base_theme, variable)
698
+ final_theme_val = getattr(final_theme, variable)
699
+ if base_theme_val is None and variable.endswith("_dark"):
700
+ base_theme_val = getattr(base_theme, variable[:-5])
701
+ if base_theme_val != final_theme_val:
702
+ var_diffs[variable] = getattr(final_theme, variable)
703
+
704
+ newline = "\n"
705
+
706
+ vars_diff_code = ""
707
+ if len(var_diffs) > 0:
708
+ vars_diff_code = f""".set(
709
+ {(',' + newline + " ").join([f"{k}='{v}'" for k, v in var_diffs.items()])}
710
+ )"""
711
+
712
+ output = f"""
713
+ import gradio as gr
714
+
715
+ theme = gr.themes.{base_theme_name}({newline if core_diffs_code or font_diffs_code else ""}{core_diffs_code}{font_diffs_code}){vars_diff_code}
716
+
717
+ with gr.Blocks(theme=theme) as demo:
718
+ ..."""
719
+ return output
720
+
721
+ history = gr.State([])
722
+ current_theme = gr.State(None)
723
+
724
+ def render_variables(history, base_theme, *args):
725
+ primary_hue, secondary_hue, neutral_hue = args[0:3]
726
+ primary_hues = args[3 : 3 + len(palette_range)]
727
+ secondary_hues = args[3 + len(palette_range) : 3 + 2 * len(palette_range)]
728
+ neutral_hues = args[3 + 2 * len(palette_range) : 3 + 3 * len(palette_range)]
729
+ text_size, spacing_size, radius_size = args[
730
+ 3 + 3 * len(palette_range) : 6 + 3 * len(palette_range)
731
+ ]
732
+ text_sizes = args[
733
+ 6 + 3 * len(palette_range) : 6
734
+ + 3 * len(palette_range)
735
+ + len(size_range)
736
+ ]
737
+ spacing_sizes = args[
738
+ 6 + 3 * len(palette_range) + len(size_range) : 6
739
+ + 3 * len(palette_range)
740
+ + 2 * len(size_range)
741
+ ]
742
+ radius_sizes = args[
743
+ 6 + 3 * len(palette_range) + 2 * len(size_range) : 6
744
+ + 3 * len(palette_range)
745
+ + 3 * len(size_range)
746
+ ]
747
+ main_fonts = args[
748
+ 6 + 3 * len(palette_range) + 3 * len(size_range) : 6
749
+ + 3 * len(palette_range)
750
+ + 3 * len(size_range)
751
+ + 4
752
+ ]
753
+ main_is_google = args[
754
+ 6 + 3 * len(palette_range) + 3 * len(size_range) + 4 : 6
755
+ + 3 * len(palette_range)
756
+ + 3 * len(size_range)
757
+ + 8
758
+ ]
759
+ mono_fonts = args[
760
+ 6 + 3 * len(palette_range) + 3 * len(size_range) + 8 : 6
761
+ + 3 * len(palette_range)
762
+ + 3 * len(size_range)
763
+ + 12
764
+ ]
765
+ mono_is_google = args[
766
+ 6 + 3 * len(palette_range) + 3 * len(size_range) + 12 : 6
767
+ + 3 * len(palette_range)
768
+ + 3 * len(size_range)
769
+ + 16
770
+ ]
771
+ remaining_args = args[
772
+ 6 + 3 * len(palette_range) + 3 * len(size_range) + 16 :
773
+ ]
774
+
775
+ final_primary_color = gr.themes.Color(*primary_hues)
776
+ final_secondary_color = gr.themes.Color(*secondary_hues)
777
+ final_neutral_color = gr.themes.Color(*neutral_hues)
778
+ final_text_size = gr.themes.Size(*text_sizes)
779
+ final_spacing_size = gr.themes.Size(*spacing_sizes)
780
+ final_radius_size = gr.themes.Size(*radius_sizes)
781
+
782
+ final_main_fonts = []
783
+ font_weights = set()
784
+ for attr, val in zip(flat_variables, remaining_args, strict=False):
785
+ if "weight" in attr:
786
+ font_weights.add(val)
787
+ font_weights = sorted(font_weights)
788
+
789
+ for main_font, is_google in zip(main_fonts, main_is_google, strict=False):
790
+ if not main_font:
791
+ continue
792
+ if is_google:
793
+ main_font = gr.themes.GoogleFont(main_font, weights=font_weights)
794
+ final_main_fonts.append(main_font)
795
+ final_mono_fonts = []
796
+ for mono_font, is_google in zip(mono_fonts, mono_is_google, strict=False):
797
+ if not mono_font:
798
+ continue
799
+ if is_google:
800
+ mono_font = gr.themes.GoogleFont(mono_font, weights=font_weights)
801
+ final_mono_fonts.append(mono_font)
802
+
803
+ theme = gr.themes.Base(
804
+ primary_hue=final_primary_color,
805
+ secondary_hue=final_secondary_color,
806
+ neutral_hue=final_neutral_color,
807
+ text_size=final_text_size,
808
+ spacing_size=final_spacing_size,
809
+ radius_size=final_radius_size,
810
+ font=final_main_fonts,
811
+ font_mono=final_mono_fonts,
812
+ )
813
+
814
+ theme.set(**dict(zip(flat_variables, remaining_args, strict=False)))
815
+ new_step = (base_theme, args)
816
+ if len(history) == 0 or str(history[-1]) != str(new_step):
817
+ history.append(new_step)
818
+
819
+ return (
820
+ history,
821
+ theme._get_theme_css(),
822
+ theme._stylesheets,
823
+ generate_theme_code(
824
+ base_theme,
825
+ theme,
826
+ (
827
+ primary_hue,
828
+ secondary_hue,
829
+ neutral_hue,
830
+ text_size,
831
+ spacing_size,
832
+ radius_size,
833
+ ),
834
+ list(zip(main_fonts, main_is_google, strict=False)),
835
+ list(zip(mono_fonts, mono_is_google, strict=False)),
836
+ ),
837
+ theme,
838
+ )
839
+
840
+ def attach_rerender(evt_listener):
841
+ return evt_listener(
842
+ render_variables,
843
+ [history, base_theme_dropdown] + theme_inputs,
844
+ [history, secret_css, secret_font, output_code, current_theme],
845
+ show_api=False,
846
+ ).then(
847
+ None,
848
+ [secret_css, secret_font],
849
+ None,
850
+ js="""(css, fonts) => {
851
+ document.getElementById('theme_css').innerHTML = css;
852
+ let existing_font_links = document.querySelectorAll('link[rel="stylesheet"][href^="https://fonts.googleapis.com/css"]');
853
+ existing_font_links.forEach(link => {
854
+ if (fonts.includes(link.href)) {
855
+ fonts = fonts.filter(font => font != link.href);
856
+ } else {
857
+ link.remove();
858
+ }
859
+ });
860
+ fonts.forEach(font => {
861
+ let link = document.createElement('link');
862
+ link.rel = 'stylesheet';
863
+ link.href = font;
864
+ document.head.appendChild(link);
865
+ });
866
+ }""",
867
+ show_api=False,
868
+ )
869
+
870
+ def load_color(color_name):
871
+ color = [color for color in colors if color.name == color_name][0]
872
+ return [getattr(color, f"c{i}") for i in palette_range]
873
+
874
+ attach_rerender(
875
+ primary_hue.select(
876
+ load_color, primary_hue, primary_hues, show_api=False
877
+ ).then
878
+ )
879
+ attach_rerender(
880
+ secondary_hue.select(
881
+ load_color, secondary_hue, secondary_hues, show_api=False
882
+ ).then
883
+ )
884
+ attach_rerender(
885
+ neutral_hue.select(
886
+ load_color, neutral_hue, neutral_hues, show_api=False
887
+ ).then
888
+ )
889
+ for hue_set in (primary_hues, secondary_hues, neutral_hues):
890
+ for hue in hue_set:
891
+ attach_rerender(hue.blur)
892
+
893
+ def load_size(size_name):
894
+ size = [size for size in sizes if size.name == size_name][0]
895
+ return [getattr(size, i) for i in size_range]
896
+
897
+ attach_rerender(
898
+ text_size.change(load_size, text_size, text_sizes, show_api=False).then
899
+ )
900
+ attach_rerender(
901
+ spacing_size.change(
902
+ load_size, spacing_size, spacing_sizes, show_api=False
903
+ ).then
904
+ )
905
+ attach_rerender(
906
+ radius_size.change(
907
+ load_size, radius_size, radius_sizes, show_api=False
908
+ ).then
909
+ )
910
+
911
+ attach_rerender(
912
+ load_theme_btn.click(
913
+ load_theme, base_theme_dropdown, theme_inputs, show_api=False
914
+ ).then
915
+ )
916
+
917
+ for theme_box in (
918
+ text_sizes + spacing_sizes + radius_sizes + main_fonts + mono_fonts
919
+ ):
920
+ attach_rerender(theme_box.blur)
921
+ attach_rerender(theme_box.submit)
922
+ for theme_box in theme_var_input:
923
+ attach_rerender(theme_box.blur)
924
+ attach_rerender(theme_box.select)
925
+ for checkbox in main_is_google + mono_is_google:
926
+ attach_rerender(checkbox.select)
927
+
928
+ dark_mode_btn.click(
929
+ None,
930
+ None,
931
+ None,
932
+ js="""() => {
933
+ if (document.querySelectorAll('.dark').length) {
934
+ document.querySelectorAll('.dark').forEach(el => el.classList.remove('dark'));
935
+ } else {
936
+ document.querySelector('body').classList.add('dark');
937
+ }
938
+ }""",
939
+ show_api=False,
940
+ )
941
+
942
+ def undo(history_var):
943
+ if len(history_var) <= 1:
944
+ return {history: gr.skip()}
945
+ else:
946
+ history_var.pop()
947
+ old = history_var.pop()
948
+ return [history_var, old[0]] + list(old[1])
949
+
950
+ attach_rerender(
951
+ undo_btn.click(
952
+ undo,
953
+ [history],
954
+ [history, base_theme_dropdown] + theme_inputs,
955
+ show_api=False,
956
+ ).then
957
+ )
958
+
959
+ def upload_to_hub(data):
960
+ try:
961
+ theme_url = data[current_theme].push_to_hub(
962
+ repo_name=data[theme_name],
963
+ version=data[theme_version] or None,
964
+ hf_token=data[theme_hf_token],
965
+ theme_name=data[theme_name],
966
+ )
967
+ space_name = "/".join(theme_url.split("/")[-2:])
968
+ return (
969
+ gr.Markdown(
970
+ value=f"Theme uploaded [here!]({theme_url})! Load it as `gr.Blocks(theme='{space_name}')`",
971
+ visible=True,
972
+ ),
973
+ "Upload to Hub",
974
+ )
975
+ except Exception as e:
976
+ return (
977
+ gr.Markdown(
978
+ value=f"Error: {e}",
979
+ visible=True,
980
+ ),
981
+ "Upload to Hub",
982
+ )
983
+
984
+ upload_to_hub_btn.click(
985
+ lambda: "Uploading...",
986
+ None,
987
+ upload_to_hub_btn,
988
+ show_api=False,
989
+ ).then(
990
+ upload_to_hub,
991
+ {
992
+ current_theme,
993
+ theme_name,
994
+ theme_hf_token,
995
+ theme_version,
996
+ },
997
+ [theme_upload_status, upload_to_hub_btn],
998
+ show_api=False,
999
+ )
1000
+
1001
 
1002
  if __name__ == "__main__":
1003
  demo.launch()
1004
+