smajumdar commited on
Commit
e62ce2b
·
verified ·
1 Parent(s): 0d1898c

Upload folder using huggingface_hub

Browse files
.gitignore ADDED
@@ -0,0 +1,12 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ .eggs/
2
+ dist/
3
+ *.pyc
4
+ __pycache__/
5
+ *.py[cod]
6
+ *$py.class
7
+ __tmp/*
8
+ *.pyi
9
+ .mypycache
10
+ .ruff_cache
11
+ node_modules
12
+ backend/**/templates/
README.md CHANGED
@@ -1,12 +1,318 @@
1
  ---
2
- title: Gradio Json Markdown
3
- emoji: 📉
4
- colorFrom: gray
5
- colorTo: pink
 
6
  sdk: gradio
7
- sdk_version: 4.42.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
+ tags: [gradio-custom-component, JSON]
3
+ title: gradio_json_markdown
4
+ short_description: JSON module with markdown support
5
+ colorFrom: blue
6
+ colorTo: yellow
7
  sdk: gradio
 
 
8
  pinned: false
9
+ app_file: space.py
10
  ---
11
 
12
+ # `gradio_json_markdown`
13
+ <img alt="Static Badge" src="https://img.shields.io/badge/version%20-%200.0.1%20-%20orange">
14
+
15
+ JSON module with markdown support
16
+
17
+ ## Installation
18
+
19
+ ```bash
20
+ pip install gradio_json_markdown
21
+ ```
22
+
23
+ ## Usage
24
+
25
+ ```python
26
+
27
+ import gradio as gr
28
+ from gradio_json_markdown import JsonMarkdown
29
+
30
+ import json
31
+
32
+ data = """
33
+ {
34
+ "conversations": [
35
+ {
36
+ "value": "Modify the function to accept a list of integers and a positive integer `n` as input. The function should return the largest product that can be formed by selecting `n` integers from the list, where `n` is at least 2. For example, given the list `[-10,-20,5,6,7]` and `n=3`, the function should return `600` because the largest product is formed by selecting `-10`, `-20`, and `6` and multiplying them together. However, given `n=4`, the function should return `-1400` because the largest product is formed by selecting `-10`, `-20`, `5`, and `7`. Ensure the function handles cases where `n` is greater than the length of the input list by returning an appropriate message.",
37
+ "from": "User",
38
+ "canonical_form": ""
39
+ },
40
+ {
41
+ "value": "```python\\ndef largest_product_n(nums, n):\\n if n > len(nums):\\n return \\\"n must be less than or equal to the length of the input list\\\"\\n nums.sort() # sort the list\\n # return the product of the last 'n' elements (largest 'n' numbers) or\\n # the product of the first 'n' elements (smallest 'n' numbers), whichever is greater\\n return max(nums[-n] * nums[-1] *\\n reduce(lambda x, y: x * y, nums[-n:-1], 1),\\n nums[0] * nums[n-1] *\\n reduce(lambda x, y: x * y, nums[1:n], 1))\\n\\n# I used functool's reduce function, so import reduce from functools module\\nfrom functools import reduce\\n\\n# test cases\\nprint(largest_product_n([-10,-20,5,6,7], 3)) # returns 600\\nprint(largest_product_n([-10,-20,5,6,7], 4)) # returns -1400\\nprint(largest_product_n([1,2,3,4,5], 2)) # returns 20\\nprint(largest_product_n([1,2,3,4,5], 6)) # returns \\\"n must be less than or equal to the length of the input list\\\"\\n\\n```\\nPlease note, this code assumes that you always have at least `n` integers in the input list. If this is not the case, you should add a check for this in the function.\\n\\nThe function sorts the integers in the list and checks if the product of the largest `n` integers or the product of the smallest integers (with one exception, explained below) is larger.\\n\\nFor the smallest integers, the function multiplies the smallest integer (nums[0]) with the \\\"n-1\\\"th integer (since the smallest integer is already included), and with the product of all integers between the 1st and the \\\"n-1\\\"th index.\\n\\nFor the largest integers, the function multiplies the largest integer (nums[-1]) with the \\\"n\\\"th integer (with the sign taken into account, since if there are negative integers we want to include as many as possible), and with the product of all integers between the \\\"n\\\"th and the second last index. If all integers are positive, the product of the largest integers is always larger or equal than the product of the smallest integers. If there is one negative integer, the product of the largest integers is always larger, since -1*(-1)*any_positive_number > any_postive_number.\\n\\nThis case is different if there is more than one negative number. If there is more than one negative number, the product of the smallest integers could be larger than the product of the largest integers, since (-n1)*(-n2) > p1*p2, where n1, n2 are negative integers and p1, p2 are positive integers. Since we take the maximum product, this case is also covered.\\n\\nIn Python, indices start from 0 and go up to n-1, so nums[-n] denotes the n-th integer from the right (last 'n' integers), and nums[-1] denotes the last integer, corresponding to the largest integer. Likewise, nums[1:n] denotes the integers between index 1 and index n-1. The reduce function is used to multiply all integers in a range. For example, reduce(lambda x, y: x * y, [1,2,3,4,5]) is equivalent to 1*2*3*4*5, and returns `120`.\\n\\nThe input `n` is the number of integers we want to select to form our product. For this problem, we assume `n >= 2`. This condition should be checked before calling the function. We also assume that the input is a list of integers. The case where `n > len(nums)` is handled by returning an error message. If `n == 1`, the function would still work, but it would not make much sense, since it would always return the largest integer in the input list.",
42
+ "from": "Assistant",
43
+ "canonical_form": ""
44
+ }
45
+ ],
46
+ "system": "",
47
+ "mask": "User",
48
+ "type": null,
49
+ "task_id": 1450799
50
+ }
51
+ """
52
+ nested_block = json.loads(data)
53
+
54
+ example = JsonMarkdown().example_value()
55
+
56
+ with gr.Blocks() as demo:
57
+ with gr.Row():
58
+ JsonMarkdown(label="Blank"), # blank component
59
+ JsonMarkdown(value=example, label="Populated"), # populated component
60
+
61
+ JsonMarkdown(value=nested_block, label="Nested JSON")
62
+
63
+ if __name__ == "__main__":
64
+ demo.launch()
65
+
66
+ ```
67
+
68
+ ## `JsonMarkdown`
69
+
70
+ ### Initialization
71
+
72
+ <table>
73
+ <thead>
74
+ <tr>
75
+ <th align="left">name</th>
76
+ <th align="left" style="width: 25%;">type</th>
77
+ <th align="left">default</th>
78
+ <th align="left">description</th>
79
+ </tr>
80
+ </thead>
81
+ <tbody>
82
+ <tr>
83
+ <td align="left"><code>value</code></td>
84
+ <td align="left" style="width: 25%;">
85
+
86
+ ```python
87
+ str | dict | list | Callable | None
88
+ ```
89
+
90
+ </td>
91
+ <td align="left"><code>None</code></td>
92
+ <td align="left">Default value as a valid JsonMarkdown `str` -- or a `list` or `dict` that can be serialized to a JsonMarkdown string. If callable, the function will be called whenever the app loads to set the initial value of the component.</td>
93
+ </tr>
94
+
95
+ <tr>
96
+ <td align="left"><code>label</code></td>
97
+ <td align="left" style="width: 25%;">
98
+
99
+ ```python
100
+ str | None
101
+ ```
102
+
103
+ </td>
104
+ <td align="left"><code>None</code></td>
105
+ <td align="left">The label for this component. Appears above the component and is also 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>
106
+ </tr>
107
+
108
+ <tr>
109
+ <td align="left"><code>every</code></td>
110
+ <td align="left" style="width: 25%;">
111
+
112
+ ```python
113
+ Timer | float | None
114
+ ```
115
+
116
+ </td>
117
+ <td align="left"><code>None</code></td>
118
+ <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>
119
+ </tr>
120
+
121
+ <tr>
122
+ <td align="left"><code>inputs</code></td>
123
+ <td align="left" style="width: 25%;">
124
+
125
+ ```python
126
+ Component | Sequence[Component] | set[Component] | None
127
+ ```
128
+
129
+ </td>
130
+ <td align="left"><code>None</code></td>
131
+ <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>
132
+ </tr>
133
+
134
+ <tr>
135
+ <td align="left"><code>show_label</code></td>
136
+ <td align="left" style="width: 25%;">
137
+
138
+ ```python
139
+ bool | None
140
+ ```
141
+
142
+ </td>
143
+ <td align="left"><code>None</code></td>
144
+ <td align="left">if True, will display label.</td>
145
+ </tr>
146
+
147
+ <tr>
148
+ <td align="left"><code>container</code></td>
149
+ <td align="left" style="width: 25%;">
150
+
151
+ ```python
152
+ bool
153
+ ```
154
+
155
+ </td>
156
+ <td align="left"><code>True</code></td>
157
+ <td align="left">If True, will place the component in a container - providing some extra padding around the border.</td>
158
+ </tr>
159
+
160
+ <tr>
161
+ <td align="left"><code>scale</code></td>
162
+ <td align="left" style="width: 25%;">
163
+
164
+ ```python
165
+ int | None
166
+ ```
167
+
168
+ </td>
169
+ <td align="left"><code>None</code></td>
170
+ <td align="left">relative size compared to adjacent Components. For example if Components A and B are in a Row, and A has scale=2, and B has scale=1, A will be twice as wide as B. Should be an integer. scale applies in Rows, and to top-level Components in Blocks where fill_height=True.</td>
171
+ </tr>
172
+
173
+ <tr>
174
+ <td align="left"><code>min_width</code></td>
175
+ <td align="left" style="width: 25%;">
176
+
177
+ ```python
178
+ int
179
+ ```
180
+
181
+ </td>
182
+ <td align="left"><code>160</code></td>
183
+ <td align="left">minimum pixel width, will wrap if not sufficient screen space to satisfy this value. If a certain scale value results in this Component being narrower than min_width, the min_width parameter will be respected first.</td>
184
+ </tr>
185
+
186
+ <tr>
187
+ <td align="left"><code>visible</code></td>
188
+ <td align="left" style="width: 25%;">
189
+
190
+ ```python
191
+ bool
192
+ ```
193
+
194
+ </td>
195
+ <td align="left"><code>True</code></td>
196
+ <td align="left">If False, component will be hidden.</td>
197
+ </tr>
198
+
199
+ <tr>
200
+ <td align="left"><code>elem_id</code></td>
201
+ <td align="left" style="width: 25%;">
202
+
203
+ ```python
204
+ str | None
205
+ ```
206
+
207
+ </td>
208
+ <td align="left"><code>None</code></td>
209
+ <td align="left">An optional string that is assigned as the id of this component in the HTML DOM. Can be used for targeting CSS styles.</td>
210
+ </tr>
211
+
212
+ <tr>
213
+ <td align="left"><code>elem_classes</code></td>
214
+ <td align="left" style="width: 25%;">
215
+
216
+ ```python
217
+ list[str] | str | None
218
+ ```
219
+
220
+ </td>
221
+ <td align="left"><code>None</code></td>
222
+ <td align="left">An optional list of strings that are assigned as the classes of this component in the HTML DOM. Can be used for targeting CSS styles.</td>
223
+ </tr>
224
+
225
+ <tr>
226
+ <td align="left"><code>render</code></td>
227
+ <td align="left" style="width: 25%;">
228
+
229
+ ```python
230
+ bool
231
+ ```
232
+
233
+ </td>
234
+ <td align="left"><code>True</code></td>
235
+ <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>
236
+ </tr>
237
+
238
+ <tr>
239
+ <td align="left"><code>key</code></td>
240
+ <td align="left" style="width: 25%;">
241
+
242
+ ```python
243
+ int | str | None
244
+ ```
245
+
246
+ </td>
247
+ <td align="left"><code>None</code></td>
248
+ <td align="left">if assigned, will be used to assume identity across a re-render. Components that have the same key across a re-render will have their value preserved.</td>
249
+ </tr>
250
+
251
+ <tr>
252
+ <td align="left"><code>open</code></td>
253
+ <td align="left" style="width: 25%;">
254
+
255
+ ```python
256
+ bool
257
+ ```
258
+
259
+ </td>
260
+ <td align="left"><code>False</code></td>
261
+ <td align="left">If True, all JsonMarkdown nodes will be expanded when rendered. By default, node levels deeper than 3 are collapsed.</td>
262
+ </tr>
263
+
264
+ <tr>
265
+ <td align="left"><code>show_indices</code></td>
266
+ <td align="left" style="width: 25%;">
267
+
268
+ ```python
269
+ bool
270
+ ```
271
+
272
+ </td>
273
+ <td align="left"><code>False</code></td>
274
+ <td align="left">Whether to show numerical indices when displaying the elements of a list within the JsonMarkdown object.</td>
275
+ </tr>
276
+
277
+ <tr>
278
+ <td align="left"><code>height</code></td>
279
+ <td align="left" style="width: 25%;">
280
+
281
+ ```python
282
+ int | str | None
283
+ ```
284
+
285
+ </td>
286
+ <td align="left"><code>None</code></td>
287
+ <td align="left">Height of the JsonMarkdown component in pixels if a number is passed, or in CSS units if a string is passed. Overflow will be scrollable. If None, the height will be automatically adjusted to fit the content.</td>
288
+ </tr>
289
+ </tbody></table>
290
+
291
+
292
+ ### Events
293
+
294
+ | name | description |
295
+ |:-----|:------------|
296
+ | `change` | Triggered when the value of the JsonMarkdown 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. |
297
+
298
+
299
+
300
+ ### User function
301
+
302
+ 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).
303
+
304
+ - When used as an Input, the component only impacts the input signature of the user function.
305
+ - When used as an output, the component only impacts the return signature of the user function.
306
+
307
+ The code snippet below is accurate in cases where the component is used as both an input and an output.
308
+
309
+ - **As output:** Is passed, passes the JsonMarkdown value as a `dict` or `list` depending on the value.
310
+ - **As input:** Should return, expects a valid JsonMarkdown `str` -- or a `list` or `dict` that can be serialized to a JsonMarkdown string. The `list` or `dict` value can contain numpy arrays.
311
+
312
+ ```python
313
+ def predict(
314
+ value: dict | list | None
315
+ ) -> dict | list | str | None:
316
+ return value
317
+ ```
318
+
__init__.py ADDED
File without changes
app.py ADDED
@@ -0,0 +1,39 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+
2
+ import gradio as gr
3
+ from gradio_json_markdown import JsonMarkdown
4
+
5
+ import json
6
+
7
+ data = """
8
+ {
9
+ "conversations": [
10
+ {
11
+ "value": "Modify the function to accept a list of integers and a positive integer `n` as input. The function should return the largest product that can be formed by selecting `n` integers from the list, where `n` is at least 2. For example, given the list `[-10,-20,5,6,7]` and `n=3`, the function should return `600` because the largest product is formed by selecting `-10`, `-20`, and `6` and multiplying them together. However, given `n=4`, the function should return `-1400` because the largest product is formed by selecting `-10`, `-20`, `5`, and `7`. Ensure the function handles cases where `n` is greater than the length of the input list by returning an appropriate message.",
12
+ "from": "User",
13
+ "canonical_form": ""
14
+ },
15
+ {
16
+ "value": "```python\\ndef largest_product_n(nums, n):\\n if n > len(nums):\\n return \\\"n must be less than or equal to the length of the input list\\\"\\n nums.sort() # sort the list\\n # return the product of the last 'n' elements (largest 'n' numbers) or\\n # the product of the first 'n' elements (smallest 'n' numbers), whichever is greater\\n return max(nums[-n] * nums[-1] *\\n reduce(lambda x, y: x * y, nums[-n:-1], 1),\\n nums[0] * nums[n-1] *\\n reduce(lambda x, y: x * y, nums[1:n], 1))\\n\\n# I used functool's reduce function, so import reduce from functools module\\nfrom functools import reduce\\n\\n# test cases\\nprint(largest_product_n([-10,-20,5,6,7], 3)) # returns 600\\nprint(largest_product_n([-10,-20,5,6,7], 4)) # returns -1400\\nprint(largest_product_n([1,2,3,4,5], 2)) # returns 20\\nprint(largest_product_n([1,2,3,4,5], 6)) # returns \\\"n must be less than or equal to the length of the input list\\\"\\n\\n```\\nPlease note, this code assumes that you always have at least `n` integers in the input list. If this is not the case, you should add a check for this in the function.\\n\\nThe function sorts the integers in the list and checks if the product of the largest `n` integers or the product of the smallest integers (with one exception, explained below) is larger.\\n\\nFor the smallest integers, the function multiplies the smallest integer (nums[0]) with the \\\"n-1\\\"th integer (since the smallest integer is already included), and with the product of all integers between the 1st and the \\\"n-1\\\"th index.\\n\\nFor the largest integers, the function multiplies the largest integer (nums[-1]) with the \\\"n\\\"th integer (with the sign taken into account, since if there are negative integers we want to include as many as possible), and with the product of all integers between the \\\"n\\\"th and the second last index. If all integers are positive, the product of the largest integers is always larger or equal than the product of the smallest integers. If there is one negative integer, the product of the largest integers is always larger, since -1*(-1)*any_positive_number > any_postive_number.\\n\\nThis case is different if there is more than one negative number. If there is more than one negative number, the product of the smallest integers could be larger than the product of the largest integers, since (-n1)*(-n2) > p1*p2, where n1, n2 are negative integers and p1, p2 are positive integers. Since we take the maximum product, this case is also covered.\\n\\nIn Python, indices start from 0 and go up to n-1, so nums[-n] denotes the n-th integer from the right (last 'n' integers), and nums[-1] denotes the last integer, corresponding to the largest integer. Likewise, nums[1:n] denotes the integers between index 1 and index n-1. The reduce function is used to multiply all integers in a range. For example, reduce(lambda x, y: x * y, [1,2,3,4,5]) is equivalent to 1*2*3*4*5, and returns `120`.\\n\\nThe input `n` is the number of integers we want to select to form our product. For this problem, we assume `n >= 2`. This condition should be checked before calling the function. We also assume that the input is a list of integers. The case where `n > len(nums)` is handled by returning an error message. If `n == 1`, the function would still work, but it would not make much sense, since it would always return the largest integer in the input list.",
17
+ "from": "Assistant",
18
+ "canonical_form": ""
19
+ }
20
+ ],
21
+ "system": "",
22
+ "mask": "User",
23
+ "type": null,
24
+ "task_id": 1450799
25
+ }
26
+ """
27
+ nested_block = json.loads(data)
28
+
29
+ example = JsonMarkdown().example_value()
30
+
31
+ with gr.Blocks() as demo:
32
+ with gr.Row():
33
+ JsonMarkdown(label="Blank"), # blank component
34
+ JsonMarkdown(value=example, label="Populated"), # populated component
35
+
36
+ JsonMarkdown(value=nested_block, label="Nested JSON")
37
+
38
+ if __name__ == "__main__":
39
+ demo.launch()
css.css ADDED
@@ -0,0 +1,157 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ html {
2
+ font-family: Inter;
3
+ font-size: 16px;
4
+ font-weight: 400;
5
+ line-height: 1.5;
6
+ -webkit-text-size-adjust: 100%;
7
+ background: #fff;
8
+ color: #323232;
9
+ -webkit-font-smoothing: antialiased;
10
+ -moz-osx-font-smoothing: grayscale;
11
+ text-rendering: optimizeLegibility;
12
+ }
13
+
14
+ :root {
15
+ --space: 1;
16
+ --vspace: calc(var(--space) * 1rem);
17
+ --vspace-0: calc(3 * var(--space) * 1rem);
18
+ --vspace-1: calc(2 * var(--space) * 1rem);
19
+ --vspace-2: calc(1.5 * var(--space) * 1rem);
20
+ --vspace-3: calc(0.5 * var(--space) * 1rem);
21
+ }
22
+
23
+ .app {
24
+ max-width: 748px !important;
25
+ }
26
+
27
+ .prose p {
28
+ margin: var(--vspace) 0;
29
+ line-height: var(--vspace * 2);
30
+ font-size: 1rem;
31
+ }
32
+
33
+ code {
34
+ font-family: "Inconsolata", sans-serif;
35
+ font-size: 16px;
36
+ }
37
+
38
+ h1,
39
+ h1 code {
40
+ font-weight: 400;
41
+ line-height: calc(2.5 / var(--space) * var(--vspace));
42
+ }
43
+
44
+ h1 code {
45
+ background: none;
46
+ border: none;
47
+ letter-spacing: 0.05em;
48
+ padding-bottom: 5px;
49
+ position: relative;
50
+ padding: 0;
51
+ }
52
+
53
+ h2 {
54
+ margin: var(--vspace-1) 0 var(--vspace-2) 0;
55
+ line-height: 1em;
56
+ }
57
+
58
+ h3,
59
+ h3 code {
60
+ margin: var(--vspace-1) 0 var(--vspace-2) 0;
61
+ line-height: 1em;
62
+ }
63
+
64
+ h4,
65
+ h5,
66
+ h6 {
67
+ margin: var(--vspace-3) 0 var(--vspace-3) 0;
68
+ line-height: var(--vspace);
69
+ }
70
+
71
+ .bigtitle,
72
+ h1,
73
+ h1 code {
74
+ font-size: calc(8px * 4.5);
75
+ word-break: break-word;
76
+ }
77
+
78
+ .title,
79
+ h2,
80
+ h2 code {
81
+ font-size: calc(8px * 3.375);
82
+ font-weight: lighter;
83
+ word-break: break-word;
84
+ border: none;
85
+ background: none;
86
+ }
87
+
88
+ .subheading1,
89
+ h3,
90
+ h3 code {
91
+ font-size: calc(8px * 1.8);
92
+ font-weight: 600;
93
+ border: none;
94
+ background: none;
95
+ letter-spacing: 0.1em;
96
+ text-transform: uppercase;
97
+ }
98
+
99
+ h2 code {
100
+ padding: 0;
101
+ position: relative;
102
+ letter-spacing: 0.05em;
103
+ }
104
+
105
+ blockquote {
106
+ font-size: calc(8px * 1.1667);
107
+ font-style: italic;
108
+ line-height: calc(1.1667 * var(--vspace));
109
+ margin: var(--vspace-2) var(--vspace-2);
110
+ }
111
+
112
+ .subheading2,
113
+ h4 {
114
+ font-size: calc(8px * 1.4292);
115
+ text-transform: uppercase;
116
+ font-weight: 600;
117
+ }
118
+
119
+ .subheading3,
120
+ h5 {
121
+ font-size: calc(8px * 1.2917);
122
+ line-height: calc(1.2917 * var(--vspace));
123
+
124
+ font-weight: lighter;
125
+ text-transform: uppercase;
126
+ letter-spacing: 0.15em;
127
+ }
128
+
129
+ h6 {
130
+ font-size: calc(8px * 1.1667);
131
+ font-size: 1.1667em;
132
+ font-weight: normal;
133
+ font-style: italic;
134
+ font-family: "le-monde-livre-classic-byol", serif !important;
135
+ letter-spacing: 0px !important;
136
+ }
137
+
138
+ #start .md > *:first-child {
139
+ margin-top: 0;
140
+ }
141
+
142
+ h2 + h3 {
143
+ margin-top: 0;
144
+ }
145
+
146
+ .md hr {
147
+ border: none;
148
+ border-top: 1px solid var(--block-border-color);
149
+ margin: var(--vspace-2) 0 var(--vspace-2) 0;
150
+ }
151
+ .prose ul {
152
+ margin: var(--vspace-2) 0 var(--vspace-1) 0;
153
+ }
154
+
155
+ .gap {
156
+ gap: 0;
157
+ }
requirements.txt ADDED
@@ -0,0 +1 @@
 
 
1
+ gradio_json_markdown
space.py ADDED
@@ -0,0 +1,161 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+
2
+ import gradio as gr
3
+ from app import demo as app
4
+ import os
5
+
6
+ _docs = {'JsonMarkdown': {'description': 'Used to display arbitrary JsonMarkdown output prettily. As this component does not accept user input, it is rarely used as an input component.\n', 'members': {'__init__': {'value': {'type': 'str | dict | list | Callable | None', 'default': 'None', 'description': 'Default value as a valid JsonMarkdown `str` -- or a `list` or `dict` that can be serialized to a JsonMarkdown string. If callable, the function will be called whenever the app loads to set the initial value of the component.'}, 'label': {'type': 'str | None', 'default': 'None', 'description': 'The label for this component. Appears above the component and is also used as the header if there are a table of examples for this component. If None and used in a `gr.Interface`, the label will be the name of the parameter this component is assigned to.'}, 'every': {'type': 'Timer | float | None', 'default': 'None', 'description': 'Continously calls `value` to recalculate it if `value` is a function (has no effect otherwise). Can provide a Timer whose tick resets `value`, or a float that provides the regular interval for the reset Timer.'}, 'inputs': {'type': 'Component | Sequence[Component] | set[Component] | None', 'default': 'None', 'description': 'Components that are used as inputs to calculate `value` if `value` is a function (has no effect otherwise). `value` is recalculated any time the inputs change.'}, 'show_label': {'type': 'bool | None', 'default': 'None', 'description': 'if True, will display label.'}, 'container': {'type': 'bool', 'default': 'True', 'description': 'If True, will place the component in a container - providing some extra padding around the border.'}, 'scale': {'type': 'int | None', 'default': 'None', 'description': 'relative size compared to adjacent Components. For example if Components A and B are in a Row, and A has scale=2, and B has scale=1, A will be twice as wide as B. Should be an integer. scale applies in Rows, and to top-level Components in Blocks where fill_height=True.'}, 'min_width': {'type': 'int', 'default': '160', 'description': 'minimum pixel width, will wrap if not sufficient screen space to satisfy this value. If a certain scale value results in this Component being narrower than min_width, the min_width parameter will be respected first.'}, 'visible': {'type': 'bool', 'default': 'True', 'description': 'If False, component will be hidden.'}, 'elem_id': {'type': 'str | None', 'default': 'None', 'description': 'An optional string that is assigned as the id of this component in the HTML DOM. Can be used for targeting CSS styles.'}, 'elem_classes': {'type': 'list[str] | str | None', 'default': 'None', 'description': 'An optional list of strings that are assigned as the classes of this component in the HTML DOM. Can be used for targeting CSS styles.'}, 'render': {'type': 'bool', 'default': 'True', 'description': 'If False, component will not render be rendered in the Blocks context. Should be used if the intention is to assign event listeners now but render the component later.'}, 'key': {'type': 'int | str | None', 'default': 'None', 'description': 'if assigned, will be used to assume identity across a re-render. Components that have the same key across a re-render will have their value preserved.'}, 'open': {'type': 'bool', 'default': 'False', 'description': 'If True, all JsonMarkdown nodes will be expanded when rendered. By default, node levels deeper than 3 are collapsed.'}, 'show_indices': {'type': 'bool', 'default': 'False', 'description': 'Whether to show numerical indices when displaying the elements of a list within the JsonMarkdown object.'}, 'height': {'type': 'int | str | None', 'default': 'None', 'description': 'Height of the JsonMarkdown component in pixels if a number is passed, or in CSS units if a string is passed. Overflow will be scrollable. If None, the height will be automatically adjusted to fit the content.'}}, 'postprocess': {'value': {'type': 'dict | list | str | None', 'description': 'Expects a valid JsonMarkdown `str` -- or a `list` or `dict` that can be serialized to a JsonMarkdown string. The `list` or `dict` value can contain numpy arrays.'}}, 'preprocess': {'return': {'type': 'dict | list | None', 'description': 'Passes the JsonMarkdown value as a `dict` or `list` depending on the value.'}, 'value': None}}, 'events': {'change': {'type': None, 'default': None, 'description': 'Triggered when the value of the JsonMarkdown 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.'}}}, '__meta__': {'additional_interfaces': {}, 'user_fn_refs': {'JsonMarkdown': []}}}
7
+
8
+ abs_path = os.path.join(os.path.dirname(__file__), "css.css")
9
+
10
+ with gr.Blocks(
11
+ css=abs_path,
12
+ theme=gr.themes.Default(
13
+ font_mono=[
14
+ gr.themes.GoogleFont("Inconsolata"),
15
+ "monospace",
16
+ ],
17
+ ),
18
+ ) as demo:
19
+ gr.Markdown(
20
+ """
21
+ # `gradio_json_markdown`
22
+
23
+ <div style="display: flex; gap: 7px;">
24
+ <img alt="Static Badge" src="https://img.shields.io/badge/version%20-%200.0.1%20-%20orange">
25
+ </div>
26
+
27
+ JSON module with markdown support
28
+ """, elem_classes=["md-custom"], header_links=True)
29
+ app.render()
30
+ gr.Markdown(
31
+ """
32
+ ## Installation
33
+
34
+ ```bash
35
+ pip install gradio_json_markdown
36
+ ```
37
+
38
+ ## Usage
39
+
40
+ ```python
41
+
42
+ import gradio as gr
43
+ from gradio_json_markdown import JsonMarkdown
44
+
45
+ import json
46
+
47
+ data = \"\"\"
48
+ {
49
+ "conversations": [
50
+ {
51
+ "value": "Modify the function to accept a list of integers and a positive integer `n` as input. The function should return the largest product that can be formed by selecting `n` integers from the list, where `n` is at least 2. For example, given the list `[-10,-20,5,6,7]` and `n=3`, the function should return `600` because the largest product is formed by selecting `-10`, `-20`, and `6` and multiplying them together. However, given `n=4`, the function should return `-1400` because the largest product is formed by selecting `-10`, `-20`, `5`, and `7`. Ensure the function handles cases where `n` is greater than the length of the input list by returning an appropriate message.",
52
+ "from": "User",
53
+ "canonical_form": ""
54
+ },
55
+ {
56
+ "value": "```python\\ndef largest_product_n(nums, n):\\n if n > len(nums):\\n return \\\"n must be less than or equal to the length of the input list\\\"\\n nums.sort() # sort the list\\n # return the product of the last 'n' elements (largest 'n' numbers) or\\n # the product of the first 'n' elements (smallest 'n' numbers), whichever is greater\\n return max(nums[-n] * nums[-1] *\\n reduce(lambda x, y: x * y, nums[-n:-1], 1),\\n nums[0] * nums[n-1] *\\n reduce(lambda x, y: x * y, nums[1:n], 1))\\n\\n# I used functool's reduce function, so import reduce from functools module\\nfrom functools import reduce\\n\\n# test cases\\nprint(largest_product_n([-10,-20,5,6,7], 3)) # returns 600\\nprint(largest_product_n([-10,-20,5,6,7], 4)) # returns -1400\\nprint(largest_product_n([1,2,3,4,5], 2)) # returns 20\\nprint(largest_product_n([1,2,3,4,5], 6)) # returns \\\"n must be less than or equal to the length of the input list\\\"\\n\\n```\\nPlease note, this code assumes that you always have at least `n` integers in the input list. If this is not the case, you should add a check for this in the function.\\n\\nThe function sorts the integers in the list and checks if the product of the largest `n` integers or the product of the smallest integers (with one exception, explained below) is larger.\\n\\nFor the smallest integers, the function multiplies the smallest integer (nums[0]) with the \\\"n-1\\\"th integer (since the smallest integer is already included), and with the product of all integers between the 1st and the \\\"n-1\\\"th index.\\n\\nFor the largest integers, the function multiplies the largest integer (nums[-1]) with the \\\"n\\\"th integer (with the sign taken into account, since if there are negative integers we want to include as many as possible), and with the product of all integers between the \\\"n\\\"th and the second last index. If all integers are positive, the product of the largest integers is always larger or equal than the product of the smallest integers. If there is one negative integer, the product of the largest integers is always larger, since -1*(-1)*any_positive_number > any_postive_number.\\n\\nThis case is different if there is more than one negative number. If there is more than one negative number, the product of the smallest integers could be larger than the product of the largest integers, since (-n1)*(-n2) > p1*p2, where n1, n2 are negative integers and p1, p2 are positive integers. Since we take the maximum product, this case is also covered.\\n\\nIn Python, indices start from 0 and go up to n-1, so nums[-n] denotes the n-th integer from the right (last 'n' integers), and nums[-1] denotes the last integer, corresponding to the largest integer. Likewise, nums[1:n] denotes the integers between index 1 and index n-1. The reduce function is used to multiply all integers in a range. For example, reduce(lambda x, y: x * y, [1,2,3,4,5]) is equivalent to 1*2*3*4*5, and returns `120`.\\n\\nThe input `n` is the number of integers we want to select to form our product. For this problem, we assume `n >= 2`. This condition should be checked before calling the function. We also assume that the input is a list of integers. The case where `n > len(nums)` is handled by returning an error message. If `n == 1`, the function would still work, but it would not make much sense, since it would always return the largest integer in the input list.",
57
+ "from": "Assistant",
58
+ "canonical_form": ""
59
+ }
60
+ ],
61
+ "system": "",
62
+ "mask": "User",
63
+ "type": null,
64
+ "task_id": 1450799
65
+ }
66
+ \"\"\"
67
+ nested_block = json.loads(data)
68
+
69
+ example = JsonMarkdown().example_value()
70
+
71
+ with gr.Blocks() as demo:
72
+ with gr.Row():
73
+ JsonMarkdown(label="Blank"), # blank component
74
+ JsonMarkdown(value=example, label="Populated"), # populated component
75
+
76
+ JsonMarkdown(value=nested_block, label="Nested JSON")
77
+
78
+ if __name__ == "__main__":
79
+ demo.launch()
80
+
81
+ ```
82
+ """, elem_classes=["md-custom"], header_links=True)
83
+
84
+
85
+ gr.Markdown("""
86
+ ## `JsonMarkdown`
87
+
88
+ ### Initialization
89
+ """, elem_classes=["md-custom"], header_links=True)
90
+
91
+ gr.ParamViewer(value=_docs["JsonMarkdown"]["members"]["__init__"], linkify=[])
92
+
93
+
94
+ gr.Markdown("### Events")
95
+ gr.ParamViewer(value=_docs["JsonMarkdown"]["events"], linkify=['Event'])
96
+
97
+
98
+
99
+
100
+ gr.Markdown("""
101
+
102
+ ### User function
103
+
104
+ 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).
105
+
106
+ - When used as an Input, the component only impacts the input signature of the user function.
107
+ - When used as an output, the component only impacts the return signature of the user function.
108
+
109
+ The code snippet below is accurate in cases where the component is used as both an input and an output.
110
+
111
+ - **As input:** Is passed, passes the JsonMarkdown value as a `dict` or `list` depending on the value.
112
+ - **As output:** Should return, expects a valid JsonMarkdown `str` -- or a `list` or `dict` that can be serialized to a JsonMarkdown string. The `list` or `dict` value can contain numpy arrays.
113
+
114
+ ```python
115
+ def predict(
116
+ value: dict | list | None
117
+ ) -> dict | list | str | None:
118
+ return value
119
+ ```
120
+ """, elem_classes=["md-custom", "JsonMarkdown-user-fn"], header_links=True)
121
+
122
+
123
+
124
+
125
+ demo.load(None, js=r"""function() {
126
+ const refs = {};
127
+ const user_fn_refs = {
128
+ JsonMarkdown: [], };
129
+ requestAnimationFrame(() => {
130
+
131
+ Object.entries(user_fn_refs).forEach(([key, refs]) => {
132
+ if (refs.length > 0) {
133
+ const el = document.querySelector(`.${key}-user-fn`);
134
+ if (!el) return;
135
+ refs.forEach(ref => {
136
+ el.innerHTML = el.innerHTML.replace(
137
+ new RegExp("\\b"+ref+"\\b", "g"),
138
+ `<a href="#h-${ref.toLowerCase()}">${ref}</a>`
139
+ );
140
+ })
141
+ }
142
+ })
143
+
144
+ Object.entries(refs).forEach(([key, refs]) => {
145
+ if (refs.length > 0) {
146
+ const el = document.querySelector(`.${key}`);
147
+ if (!el) return;
148
+ refs.forEach(ref => {
149
+ el.innerHTML = el.innerHTML.replace(
150
+ new RegExp("\\b"+ref+"\\b", "g"),
151
+ `<a href="#h-${ref.toLowerCase()}">${ref}</a>`
152
+ );
153
+ })
154
+ }
155
+ })
156
+ })
157
+ }
158
+
159
+ """)
160
+
161
+ demo.launch()
src/.gitignore ADDED
@@ -0,0 +1,12 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ .eggs/
2
+ dist/
3
+ *.pyc
4
+ __pycache__/
5
+ *.py[cod]
6
+ *$py.class
7
+ __tmp/*
8
+ *.pyi
9
+ .mypycache
10
+ .ruff_cache
11
+ node_modules
12
+ backend/**/templates/
src/.idea/.gitignore ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ # Default ignored files
2
+ /shelf/
3
+ /workspace.xml
src/.idea/gradio-json-markdown.iml ADDED
@@ -0,0 +1,11 @@
 
 
 
 
 
 
 
 
 
 
 
 
1
+ <?xml version="1.0" encoding="UTF-8"?>
2
+ <module type="PYTHON_MODULE" version="4">
3
+ <component name="NewModuleRootManager">
4
+ <content url="file://$MODULE_DIR$">
5
+ <sourceFolder url="file://$MODULE_DIR$/backend" isTestSource="false" />
6
+ <sourceFolder url="file://$MODULE_DIR$/jsonmarkdown/backend" isTestSource="false" />
7
+ </content>
8
+ <orderEntry type="inheritedJdk" />
9
+ <orderEntry type="sourceFolder" forTests="false" />
10
+ </component>
11
+ </module>
src/.idea/inspectionProfiles/Project_Default.xml ADDED
@@ -0,0 +1,14 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ <component name="InspectionProjectProfileManager">
2
+ <profile version="1.0">
3
+ <option name="myName" value="Project Default" />
4
+ <inspection_tool class="PyPackageRequirementsInspection" enabled="true" level="WARNING" enabled_by_default="true">
5
+ <option name="ignoredPackages">
6
+ <value>
7
+ <list size="1">
8
+ <item index="0" class="java.lang.String" itemvalue="backoff" />
9
+ </list>
10
+ </value>
11
+ </option>
12
+ </inspection_tool>
13
+ </profile>
14
+ </component>
src/.idea/inspectionProfiles/profiles_settings.xml ADDED
@@ -0,0 +1,6 @@
 
 
 
 
 
 
 
1
+ <component name="InspectionProjectProfileManager">
2
+ <settings>
3
+ <option name="USE_PROJECT_PROFILE" value="false" />
4
+ <version value="1.0" />
5
+ </settings>
6
+ </component>
src/.idea/misc.xml ADDED
@@ -0,0 +1,7 @@
 
 
 
 
 
 
 
 
1
+ <?xml version="1.0" encoding="UTF-8"?>
2
+ <project version="4">
3
+ <component name="Black">
4
+ <option name="sdkName" value="NeMoVLLM" />
5
+ </component>
6
+ <component name="ProjectRootManager" version="2" project-jdk-name="NeMoVLLM" project-jdk-type="Python SDK" />
7
+ </project>
src/.idea/modules.xml ADDED
@@ -0,0 +1,8 @@
 
 
 
 
 
 
 
 
 
1
+ <?xml version="1.0" encoding="UTF-8"?>
2
+ <project version="4">
3
+ <component name="ProjectModuleManager">
4
+ <modules>
5
+ <module fileurl="file://$PROJECT_DIR$/.idea/gradio-json-markdown.iml" filepath="$PROJECT_DIR$/.idea/gradio-json-markdown.iml" />
6
+ </modules>
7
+ </component>
8
+ </project>
src/.idea/vcs.xml ADDED
@@ -0,0 +1,6 @@
 
 
 
 
 
 
 
1
+ <?xml version="1.0" encoding="UTF-8"?>
2
+ <project version="4">
3
+ <component name="VcsDirectoryMappings">
4
+ <mapping directory="$PROJECT_DIR$" vcs="Git" />
5
+ </component>
6
+ </project>
src/.idea/workspace.xml ADDED
@@ -0,0 +1,121 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ <?xml version="1.0" encoding="UTF-8"?>
2
+ <project version="4">
3
+ <component name="AutoImportSettings">
4
+ <option name="autoReloadType" value="SELECTIVE" />
5
+ </component>
6
+ <component name="ChangeListManager">
7
+ <list default="true" id="b53f7e4a-53f1-42ea-8826-4ef9a94fcbb4" name="Changes" comment="" />
8
+ <option name="SHOW_DIALOG" value="false" />
9
+ <option name="HIGHLIGHT_CONFLICTS" value="true" />
10
+ <option name="HIGHLIGHT_NON_ACTIVE_CHANGELIST" value="false" />
11
+ <option name="LAST_RESOLUTION" value="IGNORE" />
12
+ </component>
13
+ <component name="Git.Settings">
14
+ <option name="RECENT_GIT_ROOT_PATH" value="$PROJECT_DIR$" />
15
+ </component>
16
+ <component name="ProjectColorInfo"><![CDATA[{
17
+ "associatedIndex": 4
18
+ }]]></component>
19
+ <component name="ProjectId" id="2lGF9hSwZ5etpPURpEAwT5eDtlA" />
20
+ <component name="ProjectLevelVcsManager" settingsEditedManually="true" />
21
+ <component name="ProjectViewState">
22
+ <option name="hideEmptyMiddlePackages" value="true" />
23
+ <option name="showLibraryContents" value="true" />
24
+ <option name="showMembers" value="true" />
25
+ </component>
26
+ <component name="PropertiesComponent"><![CDATA[{
27
+ "keyToString": {
28
+ "Python.app (1).executor": "Run",
29
+ "Python.app.executor": "Run",
30
+ "RunOnceActivity.ShowReadmeOnStart": "true"
31
+ }
32
+ }]]></component>
33
+ <component name="RecentsManager">
34
+ <key name="MoveFile.RECENT_KEYS">
35
+ <recent name="$PROJECT_DIR$" />
36
+ </key>
37
+ </component>
38
+ <component name="RunManager" selected="Python.app (1)">
39
+ <configuration name="app (1)" type="PythonConfigurationType" factoryName="Python" temporary="true" nameIsGenerated="true">
40
+ <module name="gradio-json-markdown" />
41
+ <option name="ENV_FILES" value="" />
42
+ <option name="INTERPRETER_OPTIONS" value="" />
43
+ <option name="PARENT_ENVS" value="true" />
44
+ <envs>
45
+ <env name="PYTHONUNBUFFERED" value="1" />
46
+ </envs>
47
+ <option name="SDK_HOME" value="" />
48
+ <option name="WORKING_DIRECTORY" value="$PROJECT_DIR$/demo" />
49
+ <option name="IS_MODULE_SDK" value="true" />
50
+ <option name="ADD_CONTENT_ROOTS" value="true" />
51
+ <option name="ADD_SOURCE_ROOTS" value="true" />
52
+ <option name="SCRIPT_NAME" value="$PROJECT_DIR$/demo/app.py" />
53
+ <option name="PARAMETERS" value="" />
54
+ <option name="SHOW_COMMAND_LINE" value="false" />
55
+ <option name="EMULATE_TERMINAL" value="false" />
56
+ <option name="MODULE_MODE" value="false" />
57
+ <option name="REDIRECT_INPUT" value="false" />
58
+ <option name="INPUT_FILE" value="" />
59
+ <method v="2" />
60
+ </configuration>
61
+ <configuration name="app" type="PythonConfigurationType" factoryName="Python" temporary="true" nameIsGenerated="true">
62
+ <module name="gradio-json-markdown" />
63
+ <option name="ENV_FILES" value="" />
64
+ <option name="INTERPRETER_OPTIONS" value="" />
65
+ <option name="PARENT_ENVS" value="true" />
66
+ <envs>
67
+ <env name="PYTHONUNBUFFERED" value="1" />
68
+ </envs>
69
+ <option name="SDK_HOME" value="" />
70
+ <option name="WORKING_DIRECTORY" value="$PROJECT_DIR$/jsonmarkdown/demo" />
71
+ <option name="IS_MODULE_SDK" value="true" />
72
+ <option name="ADD_CONTENT_ROOTS" value="true" />
73
+ <option name="ADD_SOURCE_ROOTS" value="true" />
74
+ <option name="SCRIPT_NAME" value="$PROJECT_DIR$/jsonmarkdown/demo/app.py" />
75
+ <option name="PARAMETERS" value="" />
76
+ <option name="SHOW_COMMAND_LINE" value="false" />
77
+ <option name="EMULATE_TERMINAL" value="false" />
78
+ <option name="MODULE_MODE" value="false" />
79
+ <option name="REDIRECT_INPUT" value="false" />
80
+ <option name="INPUT_FILE" value="" />
81
+ <method v="2" />
82
+ </configuration>
83
+ <recent_temporary>
84
+ <list>
85
+ <item itemvalue="Python.app (1)" />
86
+ <item itemvalue="Python.app" />
87
+ </list>
88
+ </recent_temporary>
89
+ </component>
90
+ <component name="SharedIndexes">
91
+ <attachedChunks>
92
+ <set>
93
+ <option value="bundled-python-sdk-975db3bf15a3-31b6be0877a2-com.jetbrains.pycharm.community.sharedIndexes.bundled-PC-241.18034.82" />
94
+ </set>
95
+ </attachedChunks>
96
+ </component>
97
+ <component name="SpellCheckerSettings" RuntimeDictionaries="0" Folders="0" CustomDictionaries="0" DefaultDictionary="application-level" UseSingleDictionary="true" transferred="true" />
98
+ <component name="TaskManager">
99
+ <task active="true" id="Default" summary="Default task">
100
+ <changelist id="b53f7e4a-53f1-42ea-8826-4ef9a94fcbb4" name="Changes" comment="" />
101
+ <created>1724798356982</created>
102
+ <option name="number" value="Default" />
103
+ <option name="presentableId" value="Default" />
104
+ <updated>1724798356982</updated>
105
+ </task>
106
+ <task id="LOCAL-00001" summary="Initial commit">
107
+ <option name="closed" value="true" />
108
+ <created>1724807493649</created>
109
+ <option name="number" value="00001" />
110
+ <option name="presentableId" value="LOCAL-00001" />
111
+ <option name="project" value="LOCAL" />
112
+ <updated>1724807493650</updated>
113
+ </task>
114
+ <option name="localTasksCounter" value="2" />
115
+ <servers />
116
+ </component>
117
+ <component name="VcsManagerConfiguration">
118
+ <MESSAGE value="Initial commit" />
119
+ <option name="LAST_COMMIT_MESSAGE" value="Initial commit" />
120
+ </component>
121
+ </project>
src/README.md ADDED
@@ -0,0 +1,318 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ ---
2
+ tags: [gradio-custom-component, JSON]
3
+ title: gradio_json_markdown
4
+ short_description: JSON module with markdown support
5
+ colorFrom: blue
6
+ colorTo: yellow
7
+ sdk: gradio
8
+ pinned: false
9
+ app_file: space.py
10
+ ---
11
+
12
+ # `gradio_json_markdown`
13
+ <img alt="Static Badge" src="https://img.shields.io/badge/version%20-%200.0.1%20-%20orange">
14
+
15
+ JSON module with markdown support
16
+
17
+ ## Installation
18
+
19
+ ```bash
20
+ pip install gradio_json_markdown
21
+ ```
22
+
23
+ ## Usage
24
+
25
+ ```python
26
+
27
+ import gradio as gr
28
+ from gradio_json_markdown import JsonMarkdown
29
+
30
+ import json
31
+
32
+ data = """
33
+ {
34
+ "conversations": [
35
+ {
36
+ "value": "Modify the function to accept a list of integers and a positive integer `n` as input. The function should return the largest product that can be formed by selecting `n` integers from the list, where `n` is at least 2. For example, given the list `[-10,-20,5,6,7]` and `n=3`, the function should return `600` because the largest product is formed by selecting `-10`, `-20`, and `6` and multiplying them together. However, given `n=4`, the function should return `-1400` because the largest product is formed by selecting `-10`, `-20`, `5`, and `7`. Ensure the function handles cases where `n` is greater than the length of the input list by returning an appropriate message.",
37
+ "from": "User",
38
+ "canonical_form": ""
39
+ },
40
+ {
41
+ "value": "```python\\ndef largest_product_n(nums, n):\\n if n > len(nums):\\n return \\\"n must be less than or equal to the length of the input list\\\"\\n nums.sort() # sort the list\\n # return the product of the last 'n' elements (largest 'n' numbers) or\\n # the product of the first 'n' elements (smallest 'n' numbers), whichever is greater\\n return max(nums[-n] * nums[-1] *\\n reduce(lambda x, y: x * y, nums[-n:-1], 1),\\n nums[0] * nums[n-1] *\\n reduce(lambda x, y: x * y, nums[1:n], 1))\\n\\n# I used functool's reduce function, so import reduce from functools module\\nfrom functools import reduce\\n\\n# test cases\\nprint(largest_product_n([-10,-20,5,6,7], 3)) # returns 600\\nprint(largest_product_n([-10,-20,5,6,7], 4)) # returns -1400\\nprint(largest_product_n([1,2,3,4,5], 2)) # returns 20\\nprint(largest_product_n([1,2,3,4,5], 6)) # returns \\\"n must be less than or equal to the length of the input list\\\"\\n\\n```\\nPlease note, this code assumes that you always have at least `n` integers in the input list. If this is not the case, you should add a check for this in the function.\\n\\nThe function sorts the integers in the list and checks if the product of the largest `n` integers or the product of the smallest integers (with one exception, explained below) is larger.\\n\\nFor the smallest integers, the function multiplies the smallest integer (nums[0]) with the \\\"n-1\\\"th integer (since the smallest integer is already included), and with the product of all integers between the 1st and the \\\"n-1\\\"th index.\\n\\nFor the largest integers, the function multiplies the largest integer (nums[-1]) with the \\\"n\\\"th integer (with the sign taken into account, since if there are negative integers we want to include as many as possible), and with the product of all integers between the \\\"n\\\"th and the second last index. If all integers are positive, the product of the largest integers is always larger or equal than the product of the smallest integers. If there is one negative integer, the product of the largest integers is always larger, since -1*(-1)*any_positive_number > any_postive_number.\\n\\nThis case is different if there is more than one negative number. If there is more than one negative number, the product of the smallest integers could be larger than the product of the largest integers, since (-n1)*(-n2) > p1*p2, where n1, n2 are negative integers and p1, p2 are positive integers. Since we take the maximum product, this case is also covered.\\n\\nIn Python, indices start from 0 and go up to n-1, so nums[-n] denotes the n-th integer from the right (last 'n' integers), and nums[-1] denotes the last integer, corresponding to the largest integer. Likewise, nums[1:n] denotes the integers between index 1 and index n-1. The reduce function is used to multiply all integers in a range. For example, reduce(lambda x, y: x * y, [1,2,3,4,5]) is equivalent to 1*2*3*4*5, and returns `120`.\\n\\nThe input `n` is the number of integers we want to select to form our product. For this problem, we assume `n >= 2`. This condition should be checked before calling the function. We also assume that the input is a list of integers. The case where `n > len(nums)` is handled by returning an error message. If `n == 1`, the function would still work, but it would not make much sense, since it would always return the largest integer in the input list.",
42
+ "from": "Assistant",
43
+ "canonical_form": ""
44
+ }
45
+ ],
46
+ "system": "",
47
+ "mask": "User",
48
+ "type": null,
49
+ "task_id": 1450799
50
+ }
51
+ """
52
+ nested_block = json.loads(data)
53
+
54
+ example = JsonMarkdown().example_value()
55
+
56
+ with gr.Blocks() as demo:
57
+ with gr.Row():
58
+ JsonMarkdown(label="Blank"), # blank component
59
+ JsonMarkdown(value=example, label="Populated"), # populated component
60
+
61
+ JsonMarkdown(value=nested_block, label="Nested JSON")
62
+
63
+ if __name__ == "__main__":
64
+ demo.launch()
65
+
66
+ ```
67
+
68
+ ## `JsonMarkdown`
69
+
70
+ ### Initialization
71
+
72
+ <table>
73
+ <thead>
74
+ <tr>
75
+ <th align="left">name</th>
76
+ <th align="left" style="width: 25%;">type</th>
77
+ <th align="left">default</th>
78
+ <th align="left">description</th>
79
+ </tr>
80
+ </thead>
81
+ <tbody>
82
+ <tr>
83
+ <td align="left"><code>value</code></td>
84
+ <td align="left" style="width: 25%;">
85
+
86
+ ```python
87
+ str | dict | list | Callable | None
88
+ ```
89
+
90
+ </td>
91
+ <td align="left"><code>None</code></td>
92
+ <td align="left">Default value as a valid JsonMarkdown `str` -- or a `list` or `dict` that can be serialized to a JsonMarkdown string. If callable, the function will be called whenever the app loads to set the initial value of the component.</td>
93
+ </tr>
94
+
95
+ <tr>
96
+ <td align="left"><code>label</code></td>
97
+ <td align="left" style="width: 25%;">
98
+
99
+ ```python
100
+ str | None
101
+ ```
102
+
103
+ </td>
104
+ <td align="left"><code>None</code></td>
105
+ <td align="left">The label for this component. Appears above the component and is also 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>
106
+ </tr>
107
+
108
+ <tr>
109
+ <td align="left"><code>every</code></td>
110
+ <td align="left" style="width: 25%;">
111
+
112
+ ```python
113
+ Timer | float | None
114
+ ```
115
+
116
+ </td>
117
+ <td align="left"><code>None</code></td>
118
+ <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>
119
+ </tr>
120
+
121
+ <tr>
122
+ <td align="left"><code>inputs</code></td>
123
+ <td align="left" style="width: 25%;">
124
+
125
+ ```python
126
+ Component | Sequence[Component] | set[Component] | None
127
+ ```
128
+
129
+ </td>
130
+ <td align="left"><code>None</code></td>
131
+ <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>
132
+ </tr>
133
+
134
+ <tr>
135
+ <td align="left"><code>show_label</code></td>
136
+ <td align="left" style="width: 25%;">
137
+
138
+ ```python
139
+ bool | None
140
+ ```
141
+
142
+ </td>
143
+ <td align="left"><code>None</code></td>
144
+ <td align="left">if True, will display label.</td>
145
+ </tr>
146
+
147
+ <tr>
148
+ <td align="left"><code>container</code></td>
149
+ <td align="left" style="width: 25%;">
150
+
151
+ ```python
152
+ bool
153
+ ```
154
+
155
+ </td>
156
+ <td align="left"><code>True</code></td>
157
+ <td align="left">If True, will place the component in a container - providing some extra padding around the border.</td>
158
+ </tr>
159
+
160
+ <tr>
161
+ <td align="left"><code>scale</code></td>
162
+ <td align="left" style="width: 25%;">
163
+
164
+ ```python
165
+ int | None
166
+ ```
167
+
168
+ </td>
169
+ <td align="left"><code>None</code></td>
170
+ <td align="left">relative size compared to adjacent Components. For example if Components A and B are in a Row, and A has scale=2, and B has scale=1, A will be twice as wide as B. Should be an integer. scale applies in Rows, and to top-level Components in Blocks where fill_height=True.</td>
171
+ </tr>
172
+
173
+ <tr>
174
+ <td align="left"><code>min_width</code></td>
175
+ <td align="left" style="width: 25%;">
176
+
177
+ ```python
178
+ int
179
+ ```
180
+
181
+ </td>
182
+ <td align="left"><code>160</code></td>
183
+ <td align="left">minimum pixel width, will wrap if not sufficient screen space to satisfy this value. If a certain scale value results in this Component being narrower than min_width, the min_width parameter will be respected first.</td>
184
+ </tr>
185
+
186
+ <tr>
187
+ <td align="left"><code>visible</code></td>
188
+ <td align="left" style="width: 25%;">
189
+
190
+ ```python
191
+ bool
192
+ ```
193
+
194
+ </td>
195
+ <td align="left"><code>True</code></td>
196
+ <td align="left">If False, component will be hidden.</td>
197
+ </tr>
198
+
199
+ <tr>
200
+ <td align="left"><code>elem_id</code></td>
201
+ <td align="left" style="width: 25%;">
202
+
203
+ ```python
204
+ str | None
205
+ ```
206
+
207
+ </td>
208
+ <td align="left"><code>None</code></td>
209
+ <td align="left">An optional string that is assigned as the id of this component in the HTML DOM. Can be used for targeting CSS styles.</td>
210
+ </tr>
211
+
212
+ <tr>
213
+ <td align="left"><code>elem_classes</code></td>
214
+ <td align="left" style="width: 25%;">
215
+
216
+ ```python
217
+ list[str] | str | None
218
+ ```
219
+
220
+ </td>
221
+ <td align="left"><code>None</code></td>
222
+ <td align="left">An optional list of strings that are assigned as the classes of this component in the HTML DOM. Can be used for targeting CSS styles.</td>
223
+ </tr>
224
+
225
+ <tr>
226
+ <td align="left"><code>render</code></td>
227
+ <td align="left" style="width: 25%;">
228
+
229
+ ```python
230
+ bool
231
+ ```
232
+
233
+ </td>
234
+ <td align="left"><code>True</code></td>
235
+ <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>
236
+ </tr>
237
+
238
+ <tr>
239
+ <td align="left"><code>key</code></td>
240
+ <td align="left" style="width: 25%;">
241
+
242
+ ```python
243
+ int | str | None
244
+ ```
245
+
246
+ </td>
247
+ <td align="left"><code>None</code></td>
248
+ <td align="left">if assigned, will be used to assume identity across a re-render. Components that have the same key across a re-render will have their value preserved.</td>
249
+ </tr>
250
+
251
+ <tr>
252
+ <td align="left"><code>open</code></td>
253
+ <td align="left" style="width: 25%;">
254
+
255
+ ```python
256
+ bool
257
+ ```
258
+
259
+ </td>
260
+ <td align="left"><code>False</code></td>
261
+ <td align="left">If True, all JsonMarkdown nodes will be expanded when rendered. By default, node levels deeper than 3 are collapsed.</td>
262
+ </tr>
263
+
264
+ <tr>
265
+ <td align="left"><code>show_indices</code></td>
266
+ <td align="left" style="width: 25%;">
267
+
268
+ ```python
269
+ bool
270
+ ```
271
+
272
+ </td>
273
+ <td align="left"><code>False</code></td>
274
+ <td align="left">Whether to show numerical indices when displaying the elements of a list within the JsonMarkdown object.</td>
275
+ </tr>
276
+
277
+ <tr>
278
+ <td align="left"><code>height</code></td>
279
+ <td align="left" style="width: 25%;">
280
+
281
+ ```python
282
+ int | str | None
283
+ ```
284
+
285
+ </td>
286
+ <td align="left"><code>None</code></td>
287
+ <td align="left">Height of the JsonMarkdown component in pixels if a number is passed, or in CSS units if a string is passed. Overflow will be scrollable. If None, the height will be automatically adjusted to fit the content.</td>
288
+ </tr>
289
+ </tbody></table>
290
+
291
+
292
+ ### Events
293
+
294
+ | name | description |
295
+ |:-----|:------------|
296
+ | `change` | Triggered when the value of the JsonMarkdown 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. |
297
+
298
+
299
+
300
+ ### User function
301
+
302
+ 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).
303
+
304
+ - When used as an Input, the component only impacts the input signature of the user function.
305
+ - When used as an output, the component only impacts the return signature of the user function.
306
+
307
+ The code snippet below is accurate in cases where the component is used as both an input and an output.
308
+
309
+ - **As output:** Is passed, passes the JsonMarkdown value as a `dict` or `list` depending on the value.
310
+ - **As input:** Should return, expects a valid JsonMarkdown `str` -- or a `list` or `dict` that can be serialized to a JsonMarkdown string. The `list` or `dict` value can contain numpy arrays.
311
+
312
+ ```python
313
+ def predict(
314
+ value: dict | list | None
315
+ ) -> dict | list | str | None:
316
+ return value
317
+ ```
318
+
src/backend/gradio_json_markdown/__init__.py ADDED
@@ -0,0 +1,4 @@
 
 
 
 
 
1
+
2
+ from .jsonmarkdown import JsonMarkdown
3
+
4
+ __all__ = ['JsonMarkdown']
src/backend/gradio_json_markdown/jsonmarkdown.py ADDED
@@ -0,0 +1,145 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """gr.JSON() component."""
2
+
3
+ from __future__ import annotations
4
+
5
+ import json
6
+ from typing import (
7
+ TYPE_CHECKING,
8
+ Any,
9
+ Callable,
10
+ Sequence,
11
+ )
12
+
13
+ import orjson
14
+ from gradio_client.documentation import document
15
+
16
+ from gradio.components.base import Component
17
+ from gradio.data_classes import JsonData
18
+ from gradio.events import Events
19
+
20
+ import mistletoe
21
+
22
+ if TYPE_CHECKING:
23
+ from gradio.components import Timer
24
+
25
+
26
+ class JsonMarkdown(Component):
27
+ """
28
+ Used to display arbitrary JsonMarkdown output prettily. As this component does not accept user input, it is rarely used as an input component.
29
+
30
+ Demos: zip_to_json, blocks_xray
31
+ """
32
+
33
+ EVENTS = [Events.change]
34
+
35
+ def __init__(
36
+ self,
37
+ value: str | dict | list | Callable | None = None,
38
+ *,
39
+ label: str | None = None,
40
+ every: Timer | float | None = None,
41
+ inputs: Component | Sequence[Component] | set[Component] | None = None,
42
+ show_label: bool | None = None,
43
+ container: bool = True,
44
+ scale: int | None = None,
45
+ min_width: int = 160,
46
+ visible: bool = True,
47
+ elem_id: str | None = None,
48
+ elem_classes: list[str] | str | None = None,
49
+ render: bool = True,
50
+ key: int | str | None = None,
51
+ open: bool = False,
52
+ show_indices: bool = False,
53
+ height: int | str | None = None,
54
+ ):
55
+ """
56
+ Parameters:
57
+ value: Default value as a valid JsonMarkdown `str` -- or a `list` or `dict` that can be serialized to a JsonMarkdown string. If callable, the function will be called whenever the app loads to set the initial value of the component.
58
+ label: The label for this component. Appears above the component and is also 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.
59
+ every: 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.
60
+ inputs: 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.
61
+ show_label: if True, will display label.
62
+ container: If True, will place the component in a container - providing some extra padding around the border.
63
+ scale: relative size compared to adjacent Components. For example if Components A and B are in a Row, and A has scale=2, and B has scale=1, A will be twice as wide as B. Should be an integer. scale applies in Rows, and to top-level Components in Blocks where fill_height=True.
64
+ min_width: minimum pixel width, will wrap if not sufficient screen space to satisfy this value. If a certain scale value results in this Component being narrower than min_width, the min_width parameter will be respected first.
65
+ visible: If False, component will be hidden.
66
+ elem_id: An optional string that is assigned as the id of this component in the HTML DOM. Can be used for targeting CSS styles.
67
+ elem_classes: An optional list of strings that are assigned as the classes of this component in the HTML DOM. Can be used for targeting CSS styles.
68
+ render: 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.
69
+ key: if assigned, will be used to assume identity across a re-render. Components that have the same key across a re-render will have their value preserved.
70
+ open: If True, all JsonMarkdown nodes will be expanded when rendered. By default, node levels deeper than 3 are collapsed.
71
+ show_indices: Whether to show numerical indices when displaying the elements of a list within the JsonMarkdown object.
72
+ height: Height of the JsonMarkdown component in pixels if a number is passed, or in CSS units if a string is passed. Overflow will be scrollable. If None, the height will be automatically adjusted to fit the content.
73
+ """
74
+ super().__init__(
75
+ label=label,
76
+ every=every,
77
+ inputs=inputs,
78
+ show_label=show_label,
79
+ container=container,
80
+ scale=scale,
81
+ min_width=min_width,
82
+ visible=visible,
83
+ elem_id=elem_id,
84
+ elem_classes=elem_classes,
85
+ render=render,
86
+ key=key,
87
+ value=value,
88
+ )
89
+
90
+ self.show_indices = show_indices
91
+ self.open = open
92
+ self.height = height
93
+
94
+ def preprocess(self, payload: dict | list | None) -> dict | list | None:
95
+ """
96
+ Parameters:
97
+ payload: JsonMarkdown value as a `dict` or `list`
98
+ Returns:
99
+ Passes the JsonMarkdown value as a `dict` or `list` depending on the value.
100
+ """
101
+ return payload
102
+
103
+ def postprocess(self, value: dict | list | str | None) -> JsonData | None:
104
+ """
105
+ Parameters:
106
+ value: Expects a valid JsonMarkdown `str` -- or a `list` or `dict` that can be serialized to a JsonMarkdown string. The `list` or `dict` value can contain numpy arrays.
107
+ Returns:
108
+ Returns the JsonMarkdown as a `list` or `dict`.
109
+ """
110
+ if value is None:
111
+ return None
112
+ if isinstance(value, str):
113
+ return JsonData(orjson.loads(value))
114
+ else:
115
+ # Use orjson to convert NumPy arrays and datetime objects to JsonMarkdown.
116
+ # This ensures a backward compatibility with the previous behavior.
117
+ # See https://github.com/gradio-app/gradio/pull/8041
118
+ return JsonData(
119
+ orjson.loads(
120
+ orjson.dumps(
121
+ value,
122
+ option=orjson.OPT_SERIALIZE_NUMPY
123
+ | orjson.OPT_PASSTHROUGH_DATETIME,
124
+ default=str,
125
+ )
126
+ )
127
+ )
128
+
129
+ def example_payload(self) -> Any:
130
+ return {"foo": "bar"}
131
+
132
+ def example_value(self) -> Any:
133
+ return {"foo": """Here is the hello world code:
134
+
135
+ ```python
136
+ def hello_world():
137
+ print("Hello, World!")
138
+ ```
139
+ """}
140
+
141
+ def read_from_flag(self, payload: Any):
142
+ return json.loads(payload)
143
+
144
+ def api_info(self) -> dict[str, Any]:
145
+ return {"type": {}, "description": "any valid json"}
src/backend/gradio_json_markdown/templates/component/index.js ADDED
The diff for this file is too large to render. See raw diff
 
src/backend/gradio_json_markdown/templates/component/style.css ADDED
@@ -0,0 +1,10 @@
 
 
 
 
 
 
 
 
 
 
 
1
+ .dropdown-arrow.svelte-145leq6{fill:currentColor}.block.svelte-nl1om8{position:relative;margin:0;box-shadow:var(--block-shadow);border-width:var(--block-border-width);border-color:var(--block-border-color);border-radius:var(--block-radius);background:var(--block-background-fill);width:100%;line-height:var(--line-sm)}.block.border_focus.svelte-nl1om8{border-color:var(--color-accent)}.block.border_contrast.svelte-nl1om8{border-color:var(--body-text-color)}.padded.svelte-nl1om8{padding:var(--block-padding)}.hidden.svelte-nl1om8{display:none}.hide-container.svelte-nl1om8{margin:0;box-shadow:none;--block-border-width:0;background:transparent;padding:0;overflow:visible}div.svelte-1hnfib2{margin-bottom:var(--spacing-lg);color:var(--block-info-text-color);font-weight:var(--block-info-text-weight);font-size:var(--block-info-text-size);line-height:var(--line-sm)}span.has-info.svelte-22c38v{margin-bottom:var(--spacing-xs)}span.svelte-22c38v:not(.has-info){margin-bottom:var(--spacing-lg)}span.svelte-22c38v{display:inline-block;position:relative;z-index:var(--layer-4);border:solid var(--block-title-border-width) var(--block-title-border-color);border-radius:var(--block-title-radius);background:var(--block-title-background-fill);padding:var(--block-title-padding);color:var(--block-title-text-color);font-weight:var(--block-title-text-weight);font-size:var(--block-title-text-size);line-height:var(--line-sm)}.hide.svelte-22c38v{margin:0;height:0}label.svelte-9gxdi0{display:inline-flex;align-items:center;z-index:var(--layer-2);box-shadow:var(--block-label-shadow);border:var(--block-label-border-width) solid var(--border-color-primary);border-top:none;border-left:none;border-radius:var(--block-label-radius);background:var(--block-label-background-fill);padding:var(--block-label-padding);pointer-events:none;color:var(--block-label-text-color);font-weight:var(--block-label-text-weight);font-size:var(--block-label-text-size);line-height:var(--line-sm)}.gr-group label.svelte-9gxdi0{border-top-left-radius:0}label.float.svelte-9gxdi0{position:absolute;top:var(--block-label-margin);left:var(--block-label-margin)}label.svelte-9gxdi0:not(.float){position:static;margin-top:var(--block-label-margin);margin-left:var(--block-label-margin)}.hide.svelte-9gxdi0{height:0}span.svelte-9gxdi0{opacity:.8;margin-right:var(--size-2);width:calc(var(--block-label-text-size) - 1px);height:calc(var(--block-label-text-size) - 1px)}.hide-label.svelte-9gxdi0{box-shadow:none;border-width:0;background:transparent;overflow:visible}button.svelte-1lrphxw{display:flex;justify-content:center;align-items:center;gap:1px;z-index:var(--layer-2);border-radius:var(--radius-sm);color:var(--block-label-text-color);border:1px solid transparent}button[disabled].svelte-1lrphxw{opacity:.5;box-shadow:none}button[disabled].svelte-1lrphxw:hover{cursor:not-allowed}.padded.svelte-1lrphxw{padding:2px;background:var(--bg-color);box-shadow:var(--shadow-drop);border:1px solid var(--button-secondary-border-color)}button.svelte-1lrphxw:hover,button.highlight.svelte-1lrphxw{cursor:pointer;color:var(--color-accent)}.padded.svelte-1lrphxw:hover{border:2px solid var(--button-secondary-border-color-hover);padding:1px;color:var(--block-label-text-color)}span.svelte-1lrphxw{padding:0 1px;font-size:10px}div.svelte-1lrphxw{padding:2px;display:flex;align-items:flex-end}.small.svelte-1lrphxw{width:14px;height:14px}.medium.svelte-1lrphxw{width:20px;height:20px}.large.svelte-1lrphxw{width:22px;height:22px}.pending.svelte-1lrphxw{animation:svelte-1lrphxw-flash .5s infinite}@keyframes svelte-1lrphxw-flash{0%{opacity:.5}50%{opacity:1}to{opacity:.5}}.transparent.svelte-1lrphxw{background:transparent;border:none;box-shadow:none}.empty.svelte-3w3rth{display:flex;justify-content:center;align-items:center;margin-top:calc(0px - var(--size-6));height:var(--size-full)}.icon.svelte-3w3rth{opacity:.5;height:var(--size-5);color:var(--body-text-color)}.small.svelte-3w3rth{min-height:calc(var(--size-32) - 20px)}.large.svelte-3w3rth{min-height:calc(var(--size-64) - 20px)}.unpadded_box.svelte-3w3rth{margin-top:0}.small_parent.svelte-3w3rth{min-height:100%!important}h2.svelte-1xg7h5n{font-size:var(--text-xl)!important}p.svelte-1xg7h5n,h2.svelte-1xg7h5n{white-space:pre-line}.wrap.svelte-1xg7h5n{display:flex;flex-direction:column;justify-content:center;align-items:center;min-height:var(--size-60);color:var(--block-label-text-color);line-height:var(--line-md);height:100%;padding-top:var(--size-3);text-align:center;margin:auto var(--spacing-lg)}.or.svelte-1xg7h5n{color:var(--body-text-color-subdued);display:flex}.icon-wrap.svelte-1xg7h5n{width:30px;margin-bottom:var(--spacing-lg)}@media (--screen-md){.wrap.svelte-1xg7h5n{font-size:var(--text-lg)}}.hovered.svelte-1xg7h5n{color:var(--color-accent)}div.svelte-q32hvf{border-top:1px solid transparent;display:flex;max-height:100%;justify-content:center;align-items:center;gap:var(--spacing-sm);height:auto;align-items:flex-end;color:var(--block-label-text-color);flex-shrink:0}.show_border.svelte-q32hvf{border-top:1px solid var(--block-border-color);margin-top:var(--spacing-xxl);box-shadow:var(--shadow-drop)}.source-selection.svelte-15ls1gu{display:flex;align-items:center;justify-content:center;border-top:1px solid var(--border-color-primary);width:100%;margin-left:auto;margin-right:auto;height:var(--size-10)}.icon.svelte-15ls1gu{width:22px;height:22px;margin:var(--spacing-lg) var(--spacing-xs);padding:var(--spacing-xs);color:var(--neutral-400);border-radius:var(--radius-md)}.selected.svelte-15ls1gu{color:var(--color-accent)}.icon.svelte-15ls1gu:hover,.icon.svelte-15ls1gu:focus{color:var(--color-accent)}pre code.hljs{display:block;overflow-x:auto;padding:1em}code.hljs{padding:3px 5px}/*!
2
+ Theme: GitHub
3
+ Description: Light theme as seen on github.com
4
+ Author: github.com
5
+ Maintainer: @Hirse
6
+ Updated: 2021-05-15
7
+
8
+ Outdated base version: https://github.com/primer/github-syntax-light
9
+ Current colors taken from GitHub's CSS
10
+ */.hljs{color:#24292e;background:#fff}.hljs-doctag,.hljs-keyword,.hljs-meta .hljs-keyword,.hljs-template-tag,.hljs-template-variable,.hljs-type,.hljs-variable.language_{color:#d73a49}.hljs-title,.hljs-title.class_,.hljs-title.class_.inherited__,.hljs-title.function_{color:#6f42c1}.hljs-attr,.hljs-attribute,.hljs-literal,.hljs-meta,.hljs-number,.hljs-operator,.hljs-variable,.hljs-selector-attr,.hljs-selector-class,.hljs-selector-id{color:#005cc5}.hljs-regexp,.hljs-string,.hljs-meta .hljs-string{color:#032f62}.hljs-built_in,.hljs-symbol{color:#e36209}.hljs-comment,.hljs-code,.hljs-formula{color:#6a737d}.hljs-name,.hljs-quote,.hljs-selector-tag,.hljs-selector-pseudo{color:#22863a}.hljs-subst{color:#24292e}.hljs-section{color:#005cc5;font-weight:700}.hljs-bullet{color:#735c0f}.hljs-emphasis{color:#24292e;font-style:italic}.hljs-strong{color:#24292e;font-weight:700}.hljs-addition{color:#22863a;background-color:#f0fff4}.hljs-deletion{color:#b31d28;background-color:#ffeef0}.json-node.svelte-1340jar{font-family:var(--font-mono);--text-color:#d18770;--key-color:var(--text-color);--string-color:#ce9178;--number-color:#719fad;--bracket-color:#5d8585;--square-bracket-color:#be6069;--punctuation-color:#8fbcbb;--line-number-color:#6a737d;--separator-color:var(--line-number-color)}.json-node.dark-mode.svelte-1340jar{--bracket-color:#7eb4b3;--number-color:#638d9a}.json-node.root.svelte-1340jar{position:relative;padding-left:var(--size-14)}.json-node.root.svelte-1340jar:before{content:"";position:absolute;top:0;bottom:0;left:var(--size-11);width:1px;background-color:var(--separator-color)}.line.svelte-1340jar{display:flex;align-items:flex-start;padding:0;margin:0;line-height:var(--line-md)}.line-number.svelte-1340jar{position:absolute;left:0;width:calc(var(--size-7));text-align:right;color:var(--line-number-color);-webkit-user-select:none;user-select:none;text-overflow:ellipsis;direction:rtl;overflow:hidden}.content.svelte-1340jar{flex:1;display:flex;align-items:center;padding-left:calc(var(--depth) * var(--size-2));flex-wrap:wrap}.children.svelte-1340jar{padding-left:var(--size-4)}.children.hidden.svelte-1340jar{display:none}.key.svelte-1340jar{color:var(--key-color)}.number.svelte-1340jar{color:var(--number-color)}.bool.svelte-1340jar,.null.svelte-1340jar{color:var(--text-color)}.value.svelte-1340jar{margin-left:var(--spacing-md)}.punctuation.svelte-1340jar{color:var(--punctuation-color)}.bracket.svelte-1340jar{margin-left:var(--spacing-sm);color:var(--bracket-color)}.square-bracket.svelte-1340jar{margin-left:var(--spacing-sm);color:var(--square-bracket-color)}.toggle.svelte-1340jar,.preview.svelte-1340jar{background:none;border:none;color:inherit;cursor:pointer;padding:0;margin:0}.toggle.svelte-1340jar{-webkit-user-select:none;user-select:none;margin-right:var(--spacing-md)}.preview.svelte-1340jar{margin:0 var(--spacing-sm) 0 var(--spacing-lg)}.preview.svelte-1340jar:hover{text-decoration:underline}[data-pseudo-content]:before{content:attr(data-pseudo-content)}.copied svg{animation:svelte-8hojd6-fade ease .3s;animation-fill-mode:forwards}@keyframes svelte-8hojd6-fade{0%{opacity:0}to{opacity:1}}.json-holder.svelte-8hojd6{padding:var(--size-2);overflow-y:scroll}.empty-wrapper.svelte-8hojd6{min-height:calc(var(--size-32) - 20px);height:100%}button.svelte-8hojd6{display:flex;position:absolute;top:var(--block-label-margin);right:var(--block-label-margin);align-items:center;box-shadow:var(--shadow-drop);border:1px solid var(--border-color-primary);border-top:none;border-right:none;border-radius:var(--block-label-right-radius);background:var(--block-label-background-fill);padding:5px;width:22px;height:22px;overflow:hidden;color:var(--block-label-text-color);font:var(--font);font-size:var(--button-small-text-size)}svg.svelte-43sxxs.svelte-43sxxs{width:var(--size-20);height:var(--size-20)}svg.svelte-43sxxs path.svelte-43sxxs{fill:var(--loader-color)}div.svelte-43sxxs.svelte-43sxxs{z-index:var(--layer-2)}.margin.svelte-43sxxs.svelte-43sxxs{margin:var(--size-4)}.wrap.svelte-v0wucf.svelte-v0wucf{display:flex;flex-direction:column;justify-content:center;align-items:center;z-index:var(--layer-2);transition:opacity .1s ease-in-out;border-radius:var(--block-radius);background:var(--block-background-fill);padding:0 var(--size-6);max-height:var(--size-screen-h);overflow:hidden}.wrap.center.svelte-v0wucf.svelte-v0wucf{top:0;right:0;left:0}.wrap.default.svelte-v0wucf.svelte-v0wucf{top:0;right:0;bottom:0;left:0}.hide.svelte-v0wucf.svelte-v0wucf{opacity:0;pointer-events:none}.generating.svelte-v0wucf.svelte-v0wucf{animation:svelte-v0wucf-pulseStart 1s cubic-bezier(.4,0,.6,1),svelte-v0wucf-pulse 2s cubic-bezier(.4,0,.6,1) 1s infinite;border:2px solid var(--color-accent);background:transparent;z-index:var(--layer-1);pointer-events:none}.translucent.svelte-v0wucf.svelte-v0wucf{background:none}@keyframes svelte-v0wucf-pulseStart{0%{opacity:0}to{opacity:1}}@keyframes svelte-v0wucf-pulse{0%,to{opacity:1}50%{opacity:.5}}.loading.svelte-v0wucf.svelte-v0wucf{z-index:var(--layer-2);color:var(--body-text-color)}.eta-bar.svelte-v0wucf.svelte-v0wucf{position:absolute;top:0;right:0;bottom:0;left:0;transform-origin:left;opacity:.8;z-index:var(--layer-1);transition:10ms;background:var(--background-fill-secondary)}.progress-bar-wrap.svelte-v0wucf.svelte-v0wucf{border:1px solid var(--border-color-primary);background:var(--background-fill-primary);width:55.5%;height:var(--size-4)}.progress-bar.svelte-v0wucf.svelte-v0wucf{transform-origin:left;background-color:var(--loader-color);width:var(--size-full);height:var(--size-full)}.progress-level.svelte-v0wucf.svelte-v0wucf{display:flex;flex-direction:column;align-items:center;gap:1;z-index:var(--layer-2);width:var(--size-full)}.progress-level-inner.svelte-v0wucf.svelte-v0wucf{margin:var(--size-2) auto;color:var(--body-text-color);font-size:var(--text-sm);font-family:var(--font-mono)}.meta-text.svelte-v0wucf.svelte-v0wucf{position:absolute;top:0;right:0;z-index:var(--layer-2);padding:var(--size-1) var(--size-2);font-size:var(--text-sm);font-family:var(--font-mono)}.meta-text-center.svelte-v0wucf.svelte-v0wucf{display:flex;position:absolute;top:0;right:0;justify-content:center;align-items:center;transform:translateY(var(--size-6));z-index:var(--layer-2);padding:var(--size-1) var(--size-2);font-size:var(--text-sm);font-family:var(--font-mono);text-align:center}.error.svelte-v0wucf.svelte-v0wucf{box-shadow:var(--shadow-drop);border:solid 1px var(--error-border-color);border-radius:var(--radius-full);background:var(--error-background-fill);padding-right:var(--size-4);padding-left:var(--size-4);color:var(--error-text-color);font-weight:var(--weight-semibold);font-size:var(--text-lg);line-height:var(--line-lg);font-family:var(--font)}.minimal.svelte-v0wucf.svelte-v0wucf{pointer-events:none}.minimal.svelte-v0wucf .progress-text.svelte-v0wucf{background:var(--block-background-fill)}.border.svelte-v0wucf.svelte-v0wucf{border:1px solid var(--border-color-primary)}.clear-status.svelte-v0wucf.svelte-v0wucf{position:absolute;display:flex;top:var(--size-2);right:var(--size-2);justify-content:flex-end;gap:var(--spacing-sm);z-index:var(--layer-1)}.toast-body.svelte-1swlrmr{display:flex;position:relative;right:0;left:0;align-items:center;margin:var(--size-6) var(--size-4);margin:auto;border-radius:var(--container-radius);overflow:hidden;pointer-events:auto}.toast-body.error.svelte-1swlrmr{border:1px solid var(--color-red-700);background:var(--color-red-50)}.dark .toast-body.error.svelte-1swlrmr{border:1px solid var(--color-red-500);background-color:var(--color-grey-950)}.toast-body.warning.svelte-1swlrmr{border:1px solid var(--color-yellow-700);background:var(--color-yellow-50)}.dark .toast-body.warning.svelte-1swlrmr{border:1px solid var(--color-yellow-500);background-color:var(--color-grey-950)}.toast-body.info.svelte-1swlrmr{border:1px solid var(--color-grey-700);background:var(--color-grey-50)}.dark .toast-body.info.svelte-1swlrmr{border:1px solid var(--color-grey-500);background-color:var(--color-grey-950)}.toast-title.svelte-1swlrmr{display:flex;align-items:center;font-weight:var(--weight-bold);font-size:var(--text-lg);line-height:var(--line-sm);text-transform:capitalize}.toast-title.error.svelte-1swlrmr{color:var(--color-red-700)}.dark .toast-title.error.svelte-1swlrmr{color:var(--color-red-50)}.toast-title.warning.svelte-1swlrmr{color:var(--color-yellow-700)}.dark .toast-title.warning.svelte-1swlrmr{color:var(--color-yellow-50)}.toast-title.info.svelte-1swlrmr{color:var(--color-grey-700)}.dark .toast-title.info.svelte-1swlrmr{color:var(--color-grey-50)}.toast-close.svelte-1swlrmr{margin:0 var(--size-3);border-radius:var(--size-3);padding:0px var(--size-1-5);font-size:var(--size-5);line-height:var(--size-5)}.toast-close.error.svelte-1swlrmr{color:var(--color-red-700)}.dark .toast-close.error.svelte-1swlrmr{color:var(--color-red-500)}.toast-close.warning.svelte-1swlrmr{color:var(--color-yellow-700)}.dark .toast-close.warning.svelte-1swlrmr{color:var(--color-yellow-500)}.toast-close.info.svelte-1swlrmr{color:var(--color-grey-700)}.dark .toast-close.info.svelte-1swlrmr{color:var(--color-grey-500)}.toast-text.svelte-1swlrmr{font-size:var(--text-lg)}.toast-text.error.svelte-1swlrmr{color:var(--color-red-700)}.dark .toast-text.error.svelte-1swlrmr{color:var(--color-red-50)}.toast-text.warning.svelte-1swlrmr{color:var(--color-yellow-700)}.dark .toast-text.warning.svelte-1swlrmr{color:var(--color-yellow-50)}.toast-text.info.svelte-1swlrmr{color:var(--color-grey-700)}.dark .toast-text.info.svelte-1swlrmr{color:var(--color-grey-50)}.toast-details.svelte-1swlrmr{margin:var(--size-3) var(--size-3) var(--size-3) 0;width:100%}.toast-icon.svelte-1swlrmr{display:flex;position:absolute;position:relative;flex-shrink:0;justify-content:center;align-items:center;margin:var(--size-2);border-radius:var(--radius-full);padding:var(--size-1);padding-left:calc(var(--size-1) - 1px);width:35px;height:35px}.toast-icon.error.svelte-1swlrmr{color:var(--color-red-700)}.dark .toast-icon.error.svelte-1swlrmr{color:var(--color-red-500)}.toast-icon.warning.svelte-1swlrmr{color:var(--color-yellow-700)}.dark .toast-icon.warning.svelte-1swlrmr{color:var(--color-yellow-500)}.toast-icon.info.svelte-1swlrmr{color:var(--color-grey-700)}.dark .toast-icon.info.svelte-1swlrmr{color:var(--color-grey-500)}@keyframes svelte-1swlrmr-countdown{0%{transform:scaleX(1)}to{transform:scaleX(0)}}.timer.svelte-1swlrmr{position:absolute;bottom:0;left:0;transform-origin:0 0;animation:svelte-1swlrmr-countdown 10s linear forwards;width:100%;height:var(--size-1)}.timer.error.svelte-1swlrmr{background:var(--color-red-700)}.dark .timer.error.svelte-1swlrmr{background:var(--color-red-500)}.timer.warning.svelte-1swlrmr{background:var(--color-yellow-700)}.dark .timer.warning.svelte-1swlrmr{background:var(--color-yellow-500)}.timer.info.svelte-1swlrmr{background:var(--color-grey-700)}.dark .timer.info.svelte-1swlrmr{background:var(--color-grey-500)}.hidden.svelte-1swlrmr{display:none}.toast-text.svelte-1swlrmr a{text-decoration:underline}.toast-wrap.svelte-gatr8h{display:flex;position:fixed;top:var(--size-4);right:var(--size-4);flex-direction:column;align-items:end;gap:var(--size-2);z-index:var(--layer-top);width:calc(100% - var(--size-8))}@media (--screen-sm){.toast-wrap.svelte-gatr8h{width:calc(var(--size-96) + var(--size-10))}}.block{overflow-y:scroll!important}
src/demo/__init__.py ADDED
File without changes
src/demo/app.py ADDED
@@ -0,0 +1,39 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+
2
+ import gradio as gr
3
+ from gradio_json_markdown import JsonMarkdown
4
+
5
+ import json
6
+
7
+ data = """
8
+ {
9
+ "conversations": [
10
+ {
11
+ "value": "Modify the function to accept a list of integers and a positive integer `n` as input. The function should return the largest product that can be formed by selecting `n` integers from the list, where `n` is at least 2. For example, given the list `[-10,-20,5,6,7]` and `n=3`, the function should return `600` because the largest product is formed by selecting `-10`, `-20`, and `6` and multiplying them together. However, given `n=4`, the function should return `-1400` because the largest product is formed by selecting `-10`, `-20`, `5`, and `7`. Ensure the function handles cases where `n` is greater than the length of the input list by returning an appropriate message.",
12
+ "from": "User",
13
+ "canonical_form": ""
14
+ },
15
+ {
16
+ "value": "```python\\ndef largest_product_n(nums, n):\\n if n > len(nums):\\n return \\\"n must be less than or equal to the length of the input list\\\"\\n nums.sort() # sort the list\\n # return the product of the last 'n' elements (largest 'n' numbers) or\\n # the product of the first 'n' elements (smallest 'n' numbers), whichever is greater\\n return max(nums[-n] * nums[-1] *\\n reduce(lambda x, y: x * y, nums[-n:-1], 1),\\n nums[0] * nums[n-1] *\\n reduce(lambda x, y: x * y, nums[1:n], 1))\\n\\n# I used functool's reduce function, so import reduce from functools module\\nfrom functools import reduce\\n\\n# test cases\\nprint(largest_product_n([-10,-20,5,6,7], 3)) # returns 600\\nprint(largest_product_n([-10,-20,5,6,7], 4)) # returns -1400\\nprint(largest_product_n([1,2,3,4,5], 2)) # returns 20\\nprint(largest_product_n([1,2,3,4,5], 6)) # returns \\\"n must be less than or equal to the length of the input list\\\"\\n\\n```\\nPlease note, this code assumes that you always have at least `n` integers in the input list. If this is not the case, you should add a check for this in the function.\\n\\nThe function sorts the integers in the list and checks if the product of the largest `n` integers or the product of the smallest integers (with one exception, explained below) is larger.\\n\\nFor the smallest integers, the function multiplies the smallest integer (nums[0]) with the \\\"n-1\\\"th integer (since the smallest integer is already included), and with the product of all integers between the 1st and the \\\"n-1\\\"th index.\\n\\nFor the largest integers, the function multiplies the largest integer (nums[-1]) with the \\\"n\\\"th integer (with the sign taken into account, since if there are negative integers we want to include as many as possible), and with the product of all integers between the \\\"n\\\"th and the second last index. If all integers are positive, the product of the largest integers is always larger or equal than the product of the smallest integers. If there is one negative integer, the product of the largest integers is always larger, since -1*(-1)*any_positive_number > any_postive_number.\\n\\nThis case is different if there is more than one negative number. If there is more than one negative number, the product of the smallest integers could be larger than the product of the largest integers, since (-n1)*(-n2) > p1*p2, where n1, n2 are negative integers and p1, p2 are positive integers. Since we take the maximum product, this case is also covered.\\n\\nIn Python, indices start from 0 and go up to n-1, so nums[-n] denotes the n-th integer from the right (last 'n' integers), and nums[-1] denotes the last integer, corresponding to the largest integer. Likewise, nums[1:n] denotes the integers between index 1 and index n-1. The reduce function is used to multiply all integers in a range. For example, reduce(lambda x, y: x * y, [1,2,3,4,5]) is equivalent to 1*2*3*4*5, and returns `120`.\\n\\nThe input `n` is the number of integers we want to select to form our product. For this problem, we assume `n >= 2`. This condition should be checked before calling the function. We also assume that the input is a list of integers. The case where `n > len(nums)` is handled by returning an error message. If `n == 1`, the function would still work, but it would not make much sense, since it would always return the largest integer in the input list.",
17
+ "from": "Assistant",
18
+ "canonical_form": ""
19
+ }
20
+ ],
21
+ "system": "",
22
+ "mask": "User",
23
+ "type": null,
24
+ "task_id": 1450799
25
+ }
26
+ """
27
+ nested_block = json.loads(data)
28
+
29
+ example = JsonMarkdown().example_value()
30
+
31
+ with gr.Blocks() as demo:
32
+ with gr.Row():
33
+ JsonMarkdown(label="Blank"), # blank component
34
+ JsonMarkdown(value=example, label="Populated"), # populated component
35
+
36
+ JsonMarkdown(value=nested_block, label="Nested JSON")
37
+
38
+ if __name__ == "__main__":
39
+ demo.launch()
src/demo/css.css ADDED
@@ -0,0 +1,157 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ html {
2
+ font-family: Inter;
3
+ font-size: 16px;
4
+ font-weight: 400;
5
+ line-height: 1.5;
6
+ -webkit-text-size-adjust: 100%;
7
+ background: #fff;
8
+ color: #323232;
9
+ -webkit-font-smoothing: antialiased;
10
+ -moz-osx-font-smoothing: grayscale;
11
+ text-rendering: optimizeLegibility;
12
+ }
13
+
14
+ :root {
15
+ --space: 1;
16
+ --vspace: calc(var(--space) * 1rem);
17
+ --vspace-0: calc(3 * var(--space) * 1rem);
18
+ --vspace-1: calc(2 * var(--space) * 1rem);
19
+ --vspace-2: calc(1.5 * var(--space) * 1rem);
20
+ --vspace-3: calc(0.5 * var(--space) * 1rem);
21
+ }
22
+
23
+ .app {
24
+ max-width: 748px !important;
25
+ }
26
+
27
+ .prose p {
28
+ margin: var(--vspace) 0;
29
+ line-height: var(--vspace * 2);
30
+ font-size: 1rem;
31
+ }
32
+
33
+ code {
34
+ font-family: "Inconsolata", sans-serif;
35
+ font-size: 16px;
36
+ }
37
+
38
+ h1,
39
+ h1 code {
40
+ font-weight: 400;
41
+ line-height: calc(2.5 / var(--space) * var(--vspace));
42
+ }
43
+
44
+ h1 code {
45
+ background: none;
46
+ border: none;
47
+ letter-spacing: 0.05em;
48
+ padding-bottom: 5px;
49
+ position: relative;
50
+ padding: 0;
51
+ }
52
+
53
+ h2 {
54
+ margin: var(--vspace-1) 0 var(--vspace-2) 0;
55
+ line-height: 1em;
56
+ }
57
+
58
+ h3,
59
+ h3 code {
60
+ margin: var(--vspace-1) 0 var(--vspace-2) 0;
61
+ line-height: 1em;
62
+ }
63
+
64
+ h4,
65
+ h5,
66
+ h6 {
67
+ margin: var(--vspace-3) 0 var(--vspace-3) 0;
68
+ line-height: var(--vspace);
69
+ }
70
+
71
+ .bigtitle,
72
+ h1,
73
+ h1 code {
74
+ font-size: calc(8px * 4.5);
75
+ word-break: break-word;
76
+ }
77
+
78
+ .title,
79
+ h2,
80
+ h2 code {
81
+ font-size: calc(8px * 3.375);
82
+ font-weight: lighter;
83
+ word-break: break-word;
84
+ border: none;
85
+ background: none;
86
+ }
87
+
88
+ .subheading1,
89
+ h3,
90
+ h3 code {
91
+ font-size: calc(8px * 1.8);
92
+ font-weight: 600;
93
+ border: none;
94
+ background: none;
95
+ letter-spacing: 0.1em;
96
+ text-transform: uppercase;
97
+ }
98
+
99
+ h2 code {
100
+ padding: 0;
101
+ position: relative;
102
+ letter-spacing: 0.05em;
103
+ }
104
+
105
+ blockquote {
106
+ font-size: calc(8px * 1.1667);
107
+ font-style: italic;
108
+ line-height: calc(1.1667 * var(--vspace));
109
+ margin: var(--vspace-2) var(--vspace-2);
110
+ }
111
+
112
+ .subheading2,
113
+ h4 {
114
+ font-size: calc(8px * 1.4292);
115
+ text-transform: uppercase;
116
+ font-weight: 600;
117
+ }
118
+
119
+ .subheading3,
120
+ h5 {
121
+ font-size: calc(8px * 1.2917);
122
+ line-height: calc(1.2917 * var(--vspace));
123
+
124
+ font-weight: lighter;
125
+ text-transform: uppercase;
126
+ letter-spacing: 0.15em;
127
+ }
128
+
129
+ h6 {
130
+ font-size: calc(8px * 1.1667);
131
+ font-size: 1.1667em;
132
+ font-weight: normal;
133
+ font-style: italic;
134
+ font-family: "le-monde-livre-classic-byol", serif !important;
135
+ letter-spacing: 0px !important;
136
+ }
137
+
138
+ #start .md > *:first-child {
139
+ margin-top: 0;
140
+ }
141
+
142
+ h2 + h3 {
143
+ margin-top: 0;
144
+ }
145
+
146
+ .md hr {
147
+ border: none;
148
+ border-top: 1px solid var(--block-border-color);
149
+ margin: var(--vspace-2) 0 var(--vspace-2) 0;
150
+ }
151
+ .prose ul {
152
+ margin: var(--vspace-2) 0 var(--vspace-1) 0;
153
+ }
154
+
155
+ .gap {
156
+ gap: 0;
157
+ }
src/demo/requirements.txt ADDED
@@ -0,0 +1 @@
 
 
1
+ gradio_json_markdown
src/demo/space.py ADDED
@@ -0,0 +1,161 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+
2
+ import gradio as gr
3
+ from app import demo as app
4
+ import os
5
+
6
+ _docs = {'JsonMarkdown': {'description': 'Used to display arbitrary JsonMarkdown output prettily. As this component does not accept user input, it is rarely used as an input component.\n', 'members': {'__init__': {'value': {'type': 'str | dict | list | Callable | None', 'default': 'None', 'description': 'Default value as a valid JsonMarkdown `str` -- or a `list` or `dict` that can be serialized to a JsonMarkdown string. If callable, the function will be called whenever the app loads to set the initial value of the component.'}, 'label': {'type': 'str | None', 'default': 'None', 'description': 'The label for this component. Appears above the component and is also used as the header if there are a table of examples for this component. If None and used in a `gr.Interface`, the label will be the name of the parameter this component is assigned to.'}, 'every': {'type': 'Timer | float | None', 'default': 'None', 'description': 'Continously calls `value` to recalculate it if `value` is a function (has no effect otherwise). Can provide a Timer whose tick resets `value`, or a float that provides the regular interval for the reset Timer.'}, 'inputs': {'type': 'Component | Sequence[Component] | set[Component] | None', 'default': 'None', 'description': 'Components that are used as inputs to calculate `value` if `value` is a function (has no effect otherwise). `value` is recalculated any time the inputs change.'}, 'show_label': {'type': 'bool | None', 'default': 'None', 'description': 'if True, will display label.'}, 'container': {'type': 'bool', 'default': 'True', 'description': 'If True, will place the component in a container - providing some extra padding around the border.'}, 'scale': {'type': 'int | None', 'default': 'None', 'description': 'relative size compared to adjacent Components. For example if Components A and B are in a Row, and A has scale=2, and B has scale=1, A will be twice as wide as B. Should be an integer. scale applies in Rows, and to top-level Components in Blocks where fill_height=True.'}, 'min_width': {'type': 'int', 'default': '160', 'description': 'minimum pixel width, will wrap if not sufficient screen space to satisfy this value. If a certain scale value results in this Component being narrower than min_width, the min_width parameter will be respected first.'}, 'visible': {'type': 'bool', 'default': 'True', 'description': 'If False, component will be hidden.'}, 'elem_id': {'type': 'str | None', 'default': 'None', 'description': 'An optional string that is assigned as the id of this component in the HTML DOM. Can be used for targeting CSS styles.'}, 'elem_classes': {'type': 'list[str] | str | None', 'default': 'None', 'description': 'An optional list of strings that are assigned as the classes of this component in the HTML DOM. Can be used for targeting CSS styles.'}, 'render': {'type': 'bool', 'default': 'True', 'description': 'If False, component will not render be rendered in the Blocks context. Should be used if the intention is to assign event listeners now but render the component later.'}, 'key': {'type': 'int | str | None', 'default': 'None', 'description': 'if assigned, will be used to assume identity across a re-render. Components that have the same key across a re-render will have their value preserved.'}, 'open': {'type': 'bool', 'default': 'False', 'description': 'If True, all JsonMarkdown nodes will be expanded when rendered. By default, node levels deeper than 3 are collapsed.'}, 'show_indices': {'type': 'bool', 'default': 'False', 'description': 'Whether to show numerical indices when displaying the elements of a list within the JsonMarkdown object.'}, 'height': {'type': 'int | str | None', 'default': 'None', 'description': 'Height of the JsonMarkdown component in pixels if a number is passed, or in CSS units if a string is passed. Overflow will be scrollable. If None, the height will be automatically adjusted to fit the content.'}}, 'postprocess': {'value': {'type': 'dict | list | str | None', 'description': 'Expects a valid JsonMarkdown `str` -- or a `list` or `dict` that can be serialized to a JsonMarkdown string. The `list` or `dict` value can contain numpy arrays.'}}, 'preprocess': {'return': {'type': 'dict | list | None', 'description': 'Passes the JsonMarkdown value as a `dict` or `list` depending on the value.'}, 'value': None}}, 'events': {'change': {'type': None, 'default': None, 'description': 'Triggered when the value of the JsonMarkdown 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.'}}}, '__meta__': {'additional_interfaces': {}, 'user_fn_refs': {'JsonMarkdown': []}}}
7
+
8
+ abs_path = os.path.join(os.path.dirname(__file__), "css.css")
9
+
10
+ with gr.Blocks(
11
+ css=abs_path,
12
+ theme=gr.themes.Default(
13
+ font_mono=[
14
+ gr.themes.GoogleFont("Inconsolata"),
15
+ "monospace",
16
+ ],
17
+ ),
18
+ ) as demo:
19
+ gr.Markdown(
20
+ """
21
+ # `gradio_json_markdown`
22
+
23
+ <div style="display: flex; gap: 7px;">
24
+ <img alt="Static Badge" src="https://img.shields.io/badge/version%20-%200.0.1%20-%20orange">
25
+ </div>
26
+
27
+ JSON module with markdown support
28
+ """, elem_classes=["md-custom"], header_links=True)
29
+ app.render()
30
+ gr.Markdown(
31
+ """
32
+ ## Installation
33
+
34
+ ```bash
35
+ pip install gradio_json_markdown
36
+ ```
37
+
38
+ ## Usage
39
+
40
+ ```python
41
+
42
+ import gradio as gr
43
+ from gradio_json_markdown import JsonMarkdown
44
+
45
+ import json
46
+
47
+ data = \"\"\"
48
+ {
49
+ "conversations": [
50
+ {
51
+ "value": "Modify the function to accept a list of integers and a positive integer `n` as input. The function should return the largest product that can be formed by selecting `n` integers from the list, where `n` is at least 2. For example, given the list `[-10,-20,5,6,7]` and `n=3`, the function should return `600` because the largest product is formed by selecting `-10`, `-20`, and `6` and multiplying them together. However, given `n=4`, the function should return `-1400` because the largest product is formed by selecting `-10`, `-20`, `5`, and `7`. Ensure the function handles cases where `n` is greater than the length of the input list by returning an appropriate message.",
52
+ "from": "User",
53
+ "canonical_form": ""
54
+ },
55
+ {
56
+ "value": "```python\\ndef largest_product_n(nums, n):\\n if n > len(nums):\\n return \\\"n must be less than or equal to the length of the input list\\\"\\n nums.sort() # sort the list\\n # return the product of the last 'n' elements (largest 'n' numbers) or\\n # the product of the first 'n' elements (smallest 'n' numbers), whichever is greater\\n return max(nums[-n] * nums[-1] *\\n reduce(lambda x, y: x * y, nums[-n:-1], 1),\\n nums[0] * nums[n-1] *\\n reduce(lambda x, y: x * y, nums[1:n], 1))\\n\\n# I used functool's reduce function, so import reduce from functools module\\nfrom functools import reduce\\n\\n# test cases\\nprint(largest_product_n([-10,-20,5,6,7], 3)) # returns 600\\nprint(largest_product_n([-10,-20,5,6,7], 4)) # returns -1400\\nprint(largest_product_n([1,2,3,4,5], 2)) # returns 20\\nprint(largest_product_n([1,2,3,4,5], 6)) # returns \\\"n must be less than or equal to the length of the input list\\\"\\n\\n```\\nPlease note, this code assumes that you always have at least `n` integers in the input list. If this is not the case, you should add a check for this in the function.\\n\\nThe function sorts the integers in the list and checks if the product of the largest `n` integers or the product of the smallest integers (with one exception, explained below) is larger.\\n\\nFor the smallest integers, the function multiplies the smallest integer (nums[0]) with the \\\"n-1\\\"th integer (since the smallest integer is already included), and with the product of all integers between the 1st and the \\\"n-1\\\"th index.\\n\\nFor the largest integers, the function multiplies the largest integer (nums[-1]) with the \\\"n\\\"th integer (with the sign taken into account, since if there are negative integers we want to include as many as possible), and with the product of all integers between the \\\"n\\\"th and the second last index. If all integers are positive, the product of the largest integers is always larger or equal than the product of the smallest integers. If there is one negative integer, the product of the largest integers is always larger, since -1*(-1)*any_positive_number > any_postive_number.\\n\\nThis case is different if there is more than one negative number. If there is more than one negative number, the product of the smallest integers could be larger than the product of the largest integers, since (-n1)*(-n2) > p1*p2, where n1, n2 are negative integers and p1, p2 are positive integers. Since we take the maximum product, this case is also covered.\\n\\nIn Python, indices start from 0 and go up to n-1, so nums[-n] denotes the n-th integer from the right (last 'n' integers), and nums[-1] denotes the last integer, corresponding to the largest integer. Likewise, nums[1:n] denotes the integers between index 1 and index n-1. The reduce function is used to multiply all integers in a range. For example, reduce(lambda x, y: x * y, [1,2,3,4,5]) is equivalent to 1*2*3*4*5, and returns `120`.\\n\\nThe input `n` is the number of integers we want to select to form our product. For this problem, we assume `n >= 2`. This condition should be checked before calling the function. We also assume that the input is a list of integers. The case where `n > len(nums)` is handled by returning an error message. If `n == 1`, the function would still work, but it would not make much sense, since it would always return the largest integer in the input list.",
57
+ "from": "Assistant",
58
+ "canonical_form": ""
59
+ }
60
+ ],
61
+ "system": "",
62
+ "mask": "User",
63
+ "type": null,
64
+ "task_id": 1450799
65
+ }
66
+ \"\"\"
67
+ nested_block = json.loads(data)
68
+
69
+ example = JsonMarkdown().example_value()
70
+
71
+ with gr.Blocks() as demo:
72
+ with gr.Row():
73
+ JsonMarkdown(label="Blank"), # blank component
74
+ JsonMarkdown(value=example, label="Populated"), # populated component
75
+
76
+ JsonMarkdown(value=nested_block, label="Nested JSON")
77
+
78
+ if __name__ == "__main__":
79
+ demo.launch()
80
+
81
+ ```
82
+ """, elem_classes=["md-custom"], header_links=True)
83
+
84
+
85
+ gr.Markdown("""
86
+ ## `JsonMarkdown`
87
+
88
+ ### Initialization
89
+ """, elem_classes=["md-custom"], header_links=True)
90
+
91
+ gr.ParamViewer(value=_docs["JsonMarkdown"]["members"]["__init__"], linkify=[])
92
+
93
+
94
+ gr.Markdown("### Events")
95
+ gr.ParamViewer(value=_docs["JsonMarkdown"]["events"], linkify=['Event'])
96
+
97
+
98
+
99
+
100
+ gr.Markdown("""
101
+
102
+ ### User function
103
+
104
+ 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).
105
+
106
+ - When used as an Input, the component only impacts the input signature of the user function.
107
+ - When used as an output, the component only impacts the return signature of the user function.
108
+
109
+ The code snippet below is accurate in cases where the component is used as both an input and an output.
110
+
111
+ - **As input:** Is passed, passes the JsonMarkdown value as a `dict` or `list` depending on the value.
112
+ - **As output:** Should return, expects a valid JsonMarkdown `str` -- or a `list` or `dict` that can be serialized to a JsonMarkdown string. The `list` or `dict` value can contain numpy arrays.
113
+
114
+ ```python
115
+ def predict(
116
+ value: dict | list | None
117
+ ) -> dict | list | str | None:
118
+ return value
119
+ ```
120
+ """, elem_classes=["md-custom", "JsonMarkdown-user-fn"], header_links=True)
121
+
122
+
123
+
124
+
125
+ demo.load(None, js=r"""function() {
126
+ const refs = {};
127
+ const user_fn_refs = {
128
+ JsonMarkdown: [], };
129
+ requestAnimationFrame(() => {
130
+
131
+ Object.entries(user_fn_refs).forEach(([key, refs]) => {
132
+ if (refs.length > 0) {
133
+ const el = document.querySelector(`.${key}-user-fn`);
134
+ if (!el) return;
135
+ refs.forEach(ref => {
136
+ el.innerHTML = el.innerHTML.replace(
137
+ new RegExp("\\b"+ref+"\\b", "g"),
138
+ `<a href="#h-${ref.toLowerCase()}">${ref}</a>`
139
+ );
140
+ })
141
+ }
142
+ })
143
+
144
+ Object.entries(refs).forEach(([key, refs]) => {
145
+ if (refs.length > 0) {
146
+ const el = document.querySelector(`.${key}`);
147
+ if (!el) return;
148
+ refs.forEach(ref => {
149
+ el.innerHTML = el.innerHTML.replace(
150
+ new RegExp("\\b"+ref+"\\b", "g"),
151
+ `<a href="#h-${ref.toLowerCase()}">${ref}</a>`
152
+ );
153
+ })
154
+ }
155
+ })
156
+ })
157
+ }
158
+
159
+ """)
160
+
161
+ demo.launch()
src/frontend/Index.svelte ADDED
@@ -0,0 +1,78 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ <script lang="ts" context="module">
2
+ export { default as BaseJSON } from "./shared/JSON.svelte";
3
+ </script>
4
+
5
+ <script lang="ts">
6
+ import type { Gradio } from "@gradio/utils";
7
+ import JSON from "./shared/JSON.svelte";
8
+ import { Block, BlockLabel } from "@gradio/atoms";
9
+ import { JSON as JSONIcon } from "@gradio/icons";
10
+
11
+ import { StatusTracker } from "@gradio/statustracker";
12
+ import type { LoadingStatus } from "@gradio/statustracker";
13
+
14
+ export let elem_id = "";
15
+ export let elem_classes: string[] = [];
16
+ export let visible = true;
17
+ export let value: any;
18
+ let old_value: any;
19
+ export let loading_status: LoadingStatus;
20
+ export let label: string;
21
+ export let show_label: boolean;
22
+ export let container = true;
23
+ export let scale: number | null = null;
24
+ export let min_width: number | undefined = undefined;
25
+ export let gradio: Gradio<{
26
+ change: never;
27
+ clear_status: LoadingStatus;
28
+ }>;
29
+ export let open = false;
30
+ export let theme_mode: "system" | "light" | "dark";
31
+ export let show_indices: boolean;
32
+ export let height: string | number | undefined;
33
+
34
+ $: {
35
+ if (value !== old_value) {
36
+ old_value = value;
37
+ gradio.dispatch("change");
38
+ }
39
+ }
40
+ </script>
41
+
42
+ <Block
43
+ {visible}
44
+ test_id="json"
45
+ {elem_id}
46
+ {elem_classes}
47
+ {container}
48
+ {scale}
49
+ {min_width}
50
+ padding={false}
51
+ allow_overflow={false}
52
+ {height}
53
+ >
54
+ {#if label}
55
+ <BlockLabel
56
+ Icon={JSONIcon}
57
+ {show_label}
58
+ {label}
59
+ float={false}
60
+ disable={container === false}
61
+ />
62
+ {/if}
63
+
64
+ <StatusTracker
65
+ autoscroll={gradio.autoscroll}
66
+ i18n={gradio.i18n}
67
+ {...loading_status}
68
+ on:clear_status={() => gradio.dispatch("clear_status", loading_status)}
69
+ />
70
+
71
+ <JSON {value} {open} {theme_mode} {show_indices} />
72
+ </Block>
73
+
74
+ <style>
75
+ :global(.block) {
76
+ overflow-y: scroll !important;
77
+ }
78
+ </style>
src/frontend/gradio.config.js ADDED
@@ -0,0 +1,9 @@
 
 
 
 
 
 
 
 
 
 
1
+ export default {
2
+ plugins: [],
3
+ svelte: {
4
+ preprocess: [],
5
+ },
6
+ build: {
7
+ target: "modules",
8
+ },
9
+ };
src/frontend/package-lock.json ADDED
The diff for this file is too large to render. See raw diff
 
src/frontend/package.json ADDED
@@ -0,0 +1,29 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "name": "gradio_json_markdown",
3
+ "version": "0.4.0",
4
+ "description": "Gradio UI packages",
5
+ "type": "module",
6
+ "author": "",
7
+ "license": "ISC",
8
+ "private": false,
9
+ "dependencies": {
10
+ "@gradio/atoms": "0.8.0",
11
+ "@gradio/icons": "0.7.1",
12
+ "@gradio/statustracker": "0.7.5",
13
+ "@gradio/utils": "0.6.0"
14
+ },
15
+ "devDependencies": {
16
+ "@gradio/preview": "0.11.0"
17
+ },
18
+ "main": "./Index.svelte",
19
+ "main_changeset": true,
20
+ "exports": {
21
+ ".": "./Index.svelte",
22
+ "./package.json": "./package.json"
23
+ },
24
+ "repository": {
25
+ "type": "git",
26
+ "url": "git+https://github.com/gradio-app/gradio.git",
27
+ "directory": "js/json"
28
+ }
29
+ }
src/frontend/shared/JSON.svelte ADDED
@@ -0,0 +1,121 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ <script lang="ts">
2
+ import { onDestroy } from "svelte";
3
+ import { JSON as JSONIcon } from "@gradio/icons";
4
+ import { Empty } from "@gradio/atoms";
5
+ import JSONNode from "./JSONNode.svelte";
6
+ import { Copy, Check } from "@gradio/icons";
7
+
8
+ export let value: any = {};
9
+ export let open = false;
10
+ export let theme_mode: "system" | "light" | "dark" = "system";
11
+ export let show_indices = false;
12
+
13
+ let copied = false;
14
+ let timer: NodeJS.Timeout;
15
+
16
+ function copy_feedback(): void {
17
+ copied = true;
18
+ if (timer) clearTimeout(timer);
19
+ timer = setTimeout(() => {
20
+ copied = false;
21
+ }, 1000);
22
+ }
23
+
24
+ async function handle_copy(): Promise<void> {
25
+ if ("clipboard" in navigator) {
26
+ await navigator.clipboard.writeText(JSON.stringify(value, null, 2));
27
+ copy_feedback();
28
+ }
29
+ }
30
+
31
+ function is_empty(obj: object): boolean {
32
+ return (
33
+ obj &&
34
+ Object.keys(obj).length === 0 &&
35
+ Object.getPrototypeOf(obj) === Object.prototype &&
36
+ JSON.stringify(obj) === JSON.stringify({})
37
+ );
38
+ }
39
+
40
+ onDestroy(() => {
41
+ if (timer) clearTimeout(timer);
42
+ });
43
+ </script>
44
+
45
+ {#if value && value !== '""' && !is_empty(value)}
46
+ <button
47
+ on:click={handle_copy}
48
+ title="copy"
49
+ class={copied ? "copied" : "copy-text"}
50
+ aria-roledescription={copied ? "Copied value" : "Copy value"}
51
+ aria-label={copied ? "Copied" : "Copy"}
52
+ >
53
+ {#if copied}
54
+ <Check />
55
+ {:else}
56
+ <Copy />
57
+ {/if}
58
+ </button>
59
+ <div class="json-holder">
60
+ <JSONNode
61
+ {value}
62
+ depth={0}
63
+ is_root={true}
64
+ {open}
65
+ {theme_mode}
66
+ {show_indices}
67
+ />
68
+ </div>
69
+ {:else}
70
+ <div class="empty-wrapper">
71
+ <Empty>
72
+ <JSONIcon />
73
+ </Empty>
74
+ </div>
75
+ {/if}
76
+
77
+ <style>
78
+ :global(.copied svg) {
79
+ animation: fade ease 300ms;
80
+ animation-fill-mode: forwards;
81
+ }
82
+
83
+ @keyframes fade {
84
+ 0% {
85
+ opacity: 0;
86
+ }
87
+ 100% {
88
+ opacity: 1;
89
+ }
90
+ }
91
+
92
+ .json-holder {
93
+ padding: var(--size-2);
94
+ overflow-y: scroll;
95
+ }
96
+
97
+ .empty-wrapper {
98
+ min-height: calc(var(--size-32) - 20px);
99
+ height: 100%;
100
+ }
101
+ button {
102
+ display: flex;
103
+ position: absolute;
104
+ top: var(--block-label-margin);
105
+ right: var(--block-label-margin);
106
+ align-items: center;
107
+ box-shadow: var(--shadow-drop);
108
+ border: 1px solid var(--border-color-primary);
109
+ border-top: none;
110
+ border-right: none;
111
+ border-radius: var(--block-label-right-radius);
112
+ background: var(--block-label-background-fill);
113
+ padding: 5px;
114
+ width: 22px;
115
+ height: 22px;
116
+ overflow: hidden;
117
+ color: var(--block-label-text-color);
118
+ font: var(--font);
119
+ font-size: var(--button-small-text-size);
120
+ }
121
+ </style>
src/frontend/shared/JSONNode.svelte ADDED
@@ -0,0 +1,299 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ <script lang="ts">
2
+ import { onMount, createEventDispatcher, tick, afterUpdate } from "svelte";
3
+ import { Marked } from "marked";
4
+ import { markedHighlight } from "marked-highlight";
5
+ import hljs from 'highlight.js';
6
+ import "highlight.js/styles/github.css"; // You can choose a different style
7
+
8
+ export let value: any;
9
+ export let depth = 0;
10
+ export let is_root = false;
11
+ export let is_last_item = true;
12
+ export let key: string | number | null = null;
13
+ export let open = false;
14
+ export let theme_mode: "system" | "light" | "dark" = "system";
15
+ export let show_indices = false;
16
+
17
+ const dispatch = createEventDispatcher();
18
+ let root_element: HTMLElement;
19
+ let collapsed = open ? false : depth >= 3;
20
+ let child_nodes: any[] = [];
21
+
22
+ function is_collapsible(val: any): boolean {
23
+ return val !== null && (typeof val === "object" || Array.isArray(val));
24
+ }
25
+
26
+ async function toggle_collapse(): Promise<void> {
27
+ collapsed = !collapsed;
28
+ await tick();
29
+ dispatch("toggle", { collapsed, depth });
30
+ }
31
+
32
+ function get_collapsed_preview(val: any): string {
33
+ if (Array.isArray(val)) return `Array(${val.length})`;
34
+ if (typeof val === "object" && val !== null)
35
+ return `Object(${Object.keys(val).length})`;
36
+ return String(val);
37
+ }
38
+
39
+ const marked = new Marked(
40
+ markedHighlight({
41
+ langPrefix: 'hljs language-',
42
+ highlight(code, lang, info) {
43
+ const language = hljs.getLanguage(lang) ? lang : 'plaintext';
44
+ return hljs.highlight(code, { language }).value;
45
+ }
46
+ })
47
+ );
48
+
49
+ function toMarkdown(value: string): string {
50
+ console.log("Render:" + value);
51
+ const parsed = marked.parse(value);
52
+ const parser = new DOMParser();
53
+ const doc = parser.parseFromString(parsed, 'text/html');
54
+ doc.querySelectorAll('code').forEach((codeElement) => {
55
+ codeElement.setAttribute('style', 'border: 1px solid #d3d3d3; background-color: rgba(150,150,150,0.05);');
56
+ });
57
+ return doc.body.innerHTML;
58
+ }
59
+
60
+ $: if (is_collapsible(value)) {
61
+ child_nodes = Object.entries(value);
62
+ } else {
63
+ child_nodes = [];
64
+ }
65
+ $: if (is_root && root_element) {
66
+ updateLineNumbers();
67
+ }
68
+
69
+ function updateLineNumbers(): void {
70
+ const lines = root_element.querySelectorAll(".line");
71
+ lines.forEach((line, index) => {
72
+ const line_number = line.querySelector(".line-number");
73
+ if (line_number) {
74
+ line_number.setAttribute("data-pseudo-content", (index + 1).toString());
75
+ line_number?.setAttribute(
76
+ "aria-roledescription",
77
+ `Line number ${index + 1}`
78
+ );
79
+ line_number?.setAttribute("title", `Line number ${index + 1}`);
80
+ }
81
+ });
82
+ }
83
+
84
+ onMount(() => {
85
+ if (is_root) {
86
+ updateLineNumbers();
87
+ }
88
+ });
89
+
90
+ afterUpdate(() => {
91
+ if (is_root) {
92
+ updateLineNumbers();
93
+ }
94
+ });
95
+ </script>
96
+
97
+ <div
98
+ class="json-node"
99
+ class:root={is_root}
100
+ class:dark-mode={theme_mode === "dark"}
101
+ bind:this={root_element}
102
+ on:toggle
103
+ style="--depth: {depth};"
104
+ >
105
+ <div class="line" class:collapsed>
106
+ <span class="line-number"></span>
107
+ <span class="content">
108
+ {#if is_collapsible(value)}
109
+ <button
110
+ data-pseudo-content={collapsed ? "▶" : "▼"}
111
+ aria-label={collapsed ? "Expand" : "Collapse"}
112
+ class="toggle"
113
+ on:click={toggle_collapse}
114
+ />
115
+ {/if}
116
+
117
+ {#if key !== null}
118
+ <span class="key">"{key}"</span><span class="punctuation colon"
119
+ >:
120
+ </span>
121
+ {/if}
122
+ {#if is_collapsible(value)}
123
+ <span
124
+ class="punctuation bracket"
125
+ class:square-bracket={Array.isArray(value)}
126
+ >{Array.isArray(value) ? "[" : "{"}</span
127
+ >
128
+ {#if collapsed}
129
+ <button on:click={toggle_collapse} class="preview">
130
+ {get_collapsed_preview(value)}
131
+ </button>
132
+ <span
133
+ class="punctuation bracket"
134
+ class:square-bracket={Array.isArray(value)}
135
+ >{Array.isArray(value) ? "]" : "}"}</span
136
+ >
137
+ {/if}
138
+ {:else if typeof value === "string"}
139
+ <span class="value">{@html toMarkdown(value)}</span>
140
+ {:else if typeof value === "number"}
141
+ <span class="value number">{value}</span>
142
+ {:else if typeof value === "boolean"}
143
+ <span class="value bool">{value.toString()}</span>
144
+ {:else if value === null}
145
+ <span class="value null">null</span>
146
+ {:else}
147
+ <span>{value}</span>
148
+ {/if}
149
+ {#if !is_last_item && (!is_collapsible(value) || collapsed)}
150
+ <span class="punctuation">,</span>
151
+ {/if}
152
+ </span>
153
+ </div>
154
+
155
+ {#if is_collapsible(value)}
156
+ <div class="children" class:hidden={collapsed}>
157
+ {#each child_nodes as [subKey, subVal], i}
158
+ <svelte:self
159
+ value={subVal}
160
+ depth={depth + 1}
161
+ is_last_item={i === child_nodes.length - 1}
162
+ key={subKey}
163
+ {open}
164
+ {theme_mode}
165
+ {show_indices}
166
+ on:toggle
167
+ />
168
+ {/each}
169
+ <div class="line">
170
+ <span class="line-number"></span>
171
+ <span class="content">
172
+ <span
173
+ class="punctuation bracket"
174
+ class:square-bracket={Array.isArray(value)}
175
+ >{Array.isArray(value) ? "]" : "}"}</span
176
+ >
177
+ {#if !is_last_item}<span class="punctuation">,</span>{/if}
178
+ </span>
179
+ </div>
180
+ </div>
181
+ {/if}
182
+ </div>
183
+
184
+ <style>
185
+ .json-node {
186
+ font-family: var(--font-mono);
187
+ --text-color: #d18770;
188
+ --key-color: var(--text-color);
189
+ --string-color: #ce9178;
190
+ --number-color: #719fad;
191
+
192
+ --bracket-color: #5d8585;
193
+ --square-bracket-color: #be6069;
194
+ --punctuation-color: #8fbcbb;
195
+ --line-number-color: #6a737d;
196
+ --separator-color: var(--line-number-color);
197
+ }
198
+ .json-node.dark-mode {
199
+ --bracket-color: #7eb4b3;
200
+ --number-color: #638d9a;
201
+ }
202
+ .json-node.root {
203
+ position: relative;
204
+ padding-left: var(--size-14);
205
+ }
206
+ .json-node.root::before {
207
+ content: "";
208
+ position: absolute;
209
+ top: 0;
210
+ bottom: 0;
211
+ left: var(--size-11);
212
+ width: 1px;
213
+ background-color: var(--separator-color);
214
+ }
215
+ .line {
216
+ display: flex;
217
+ align-items: flex-start;
218
+ padding: 0;
219
+ margin: 0;
220
+ line-height: var(--line-md);
221
+ }
222
+ .line-number {
223
+ position: absolute;
224
+ left: 0;
225
+ width: calc(var(--size-7));
226
+ text-align: right;
227
+ color: var(--line-number-color);
228
+ user-select: none;
229
+ text-overflow: ellipsis;
230
+ text-overflow: ellipsis;
231
+ direction: rtl;
232
+ overflow: hidden;
233
+ }
234
+ .content {
235
+ flex: 1;
236
+ display: flex;
237
+ align-items: center;
238
+ padding-left: calc(var(--depth) * var(--size-2));
239
+ flex-wrap: wrap;
240
+ }
241
+ .children {
242
+ padding-left: var(--size-4);
243
+ }
244
+ .children.hidden {
245
+ display: none;
246
+ }
247
+ .key {
248
+ color: var(--key-color);
249
+ }
250
+ .string {
251
+ color: var(--string-color);
252
+ }
253
+ .number {
254
+ color: var(--number-color);
255
+ }
256
+ .bool {
257
+ color: var(--text-color);
258
+ }
259
+ .null {
260
+ color: var(--text-color);
261
+ }
262
+ .value {
263
+ margin-left: var(--spacing-md);
264
+ }
265
+ .punctuation {
266
+ color: var(--punctuation-color);
267
+ }
268
+ .bracket {
269
+ margin-left: var(--spacing-sm);
270
+ color: var(--bracket-color);
271
+ }
272
+ .square-bracket {
273
+ margin-left: var(--spacing-sm);
274
+ color: var(--square-bracket-color);
275
+ }
276
+ .toggle,
277
+ .preview {
278
+ background: none;
279
+ border: none;
280
+ color: inherit;
281
+ cursor: pointer;
282
+ padding: 0;
283
+ margin: 0;
284
+ }
285
+ .toggle {
286
+ user-select: none;
287
+ margin-right: var(--spacing-md);
288
+ }
289
+ .preview {
290
+ margin: 0 var(--spacing-sm) 0 var(--spacing-lg);
291
+ }
292
+ .preview:hover {
293
+ text-decoration: underline;
294
+ }
295
+
296
+ :global([data-pseudo-content])::before {
297
+ content: attr(data-pseudo-content);
298
+ }
299
+ </style>
src/package-lock.json ADDED
@@ -0,0 +1,44 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "name": "gradio-json-markdown",
3
+ "lockfileVersion": 3,
4
+ "requires": true,
5
+ "packages": {
6
+ "": {
7
+ "dependencies": {
8
+ "highlight.js": "^11.10.0",
9
+ "marked": "^14.1.0",
10
+ "marked-highlight": "^2.1.4"
11
+ }
12
+ },
13
+ "node_modules/highlight.js": {
14
+ "version": "11.10.0",
15
+ "resolved": "https://registry.npmjs.org/highlight.js/-/highlight.js-11.10.0.tgz",
16
+ "integrity": "sha512-SYVnVFswQER+zu1laSya563s+F8VDGt7o35d4utbamowvUNLLMovFqwCLSocpZTz3MgaSRA1IbqRWZv97dtErQ==",
17
+ "license": "BSD-3-Clause",
18
+ "engines": {
19
+ "node": ">=12.0.0"
20
+ }
21
+ },
22
+ "node_modules/marked": {
23
+ "version": "14.1.0",
24
+ "resolved": "https://registry.npmjs.org/marked/-/marked-14.1.0.tgz",
25
+ "integrity": "sha512-P93GikH/Pde0hM5TAXEd8I4JAYi8IB03n8qzW8Bh1BIEFpEyBoYxi/XWZA53LSpTeLBiMQOoSMj0u5E/tiVYTA==",
26
+ "license": "MIT",
27
+ "bin": {
28
+ "marked": "bin/marked.js"
29
+ },
30
+ "engines": {
31
+ "node": ">= 18"
32
+ }
33
+ },
34
+ "node_modules/marked-highlight": {
35
+ "version": "2.1.4",
36
+ "resolved": "https://registry.npmjs.org/marked-highlight/-/marked-highlight-2.1.4.tgz",
37
+ "integrity": "sha512-D1GOkcdzP+1dzjoColL7umojefFrASDuLeyaHS0Zr/Uo9jkr1V6vpLRCzfi1djmEaWyK0SYMFtHnpkZ+cwFT1w==",
38
+ "license": "MIT",
39
+ "peerDependencies": {
40
+ "marked": ">=4 <15"
41
+ }
42
+ }
43
+ }
44
+ }
src/package.json ADDED
@@ -0,0 +1,7 @@
 
 
 
 
 
 
 
 
1
+ {
2
+ "dependencies": {
3
+ "highlight.js": "^11.10.0",
4
+ "marked": "^14.1.0",
5
+ "marked-highlight": "^2.1.4"
6
+ }
7
+ }
src/pyproject.toml ADDED
@@ -0,0 +1,54 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ [build-system]
2
+ requires = [
3
+ "hatchling",
4
+ "hatch-requirements-txt",
5
+ "hatch-fancy-pypi-readme>=22.5.0",
6
+ ]
7
+ build-backend = "hatchling.build"
8
+
9
+ [project]
10
+ name = "gradio_json_markdown"
11
+ version = "0.0.1"
12
+ description = "JSON module with markdown support"
13
+ readme = "README.md"
14
+ license = "apache-2.0"
15
+ requires-python = ">=3.8"
16
+ authors = [{ name = "YOUR NAME", email = "[email protected]" }]
17
+ keywords = ["gradio-custom-component", "gradio-template-JSON"]
18
+ # Add dependencies here
19
+ dependencies = [
20
+ "gradio>=4.0,<5.0",
21
+ "mistletoe>=1.4.0",
22
+ ]
23
+ classifiers = [
24
+ 'Development Status :: 3 - Alpha',
25
+ 'Operating System :: OS Independent',
26
+ 'Programming Language :: Python :: 3',
27
+ 'Programming Language :: Python :: 3 :: Only',
28
+ 'Programming Language :: Python :: 3.8',
29
+ 'Programming Language :: Python :: 3.9',
30
+ 'Programming Language :: Python :: 3.10',
31
+ 'Programming Language :: Python :: 3.11',
32
+ 'Topic :: Scientific/Engineering',
33
+ 'Topic :: Scientific/Engineering :: Artificial Intelligence',
34
+ 'Topic :: Scientific/Engineering :: Visualization',
35
+ ]
36
+
37
+ # The repository and space URLs are optional, but recommended.
38
+ # Adding a repository URL will create a badge in the auto-generated README that links to the repository.
39
+ # Adding a space URL will create a badge in the auto-generated README that links to the space.
40
+ # This will make it easy for people to find your deployed demo or source code when they
41
+ # encounter your project in the wild.
42
+
43
+ # [project.urls]
44
+ # repository = "your github repository"
45
+ # space = "your space url"
46
+
47
+ [project.optional-dependencies]
48
+ dev = ["build", "twine"]
49
+
50
+ [tool.hatch.build]
51
+ artifacts = ["/backend/gradio_json_markdown/templates", "*.pyi"]
52
+
53
+ [tool.hatch.build.targets.wheel]
54
+ packages = ["/backend/gradio_json_markdown"]