shubhamofbce commited on
Commit
19db356
1 Parent(s): 64fcd8a

Upload folder using huggingface_hub

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