Asukaa02 commited on
Commit
3653172
·
verified ·
1 Parent(s): 5cfb4fb

Upload folder using huggingface_hub

Browse files
This view is limited to 50 files because it contains too many changes.   See raw diff
Files changed (50) hide show
  1. .gitignore +78 -0
  2. LICENSE +201 -0
  3. PKG-INFO +374 -0
  4. README.md +323 -0
  5. gradio/.dockerignore +2 -0
  6. gradio/CHANGELOG.md +0 -0
  7. gradio/__init__.py +107 -0
  8. gradio/analytics.py +188 -0
  9. gradio/blocks.py +2178 -0
  10. gradio/chat_interface.py +470 -0
  11. gradio/cli.py +21 -0
  12. gradio/cli_env_info.py +29 -0
  13. gradio/components/__init__.py +116 -0
  14. gradio/components/annotated_image.py +243 -0
  15. gradio/components/audio.py +350 -0
  16. gradio/components/bar_plot.py +376 -0
  17. gradio/components/base.py +407 -0
  18. gradio/components/button.py +121 -0
  19. gradio/components/carousel.py +22 -0
  20. gradio/components/chatbot.py +247 -0
  21. gradio/components/checkbox.py +134 -0
  22. gradio/components/checkboxgroup.py +213 -0
  23. gradio/components/clear_button.py +70 -0
  24. gradio/components/code.py +157 -0
  25. gradio/components/color_picker.py +143 -0
  26. gradio/components/dataframe.py +304 -0
  27. gradio/components/dataset.py +137 -0
  28. gradio/components/dropdown.py +243 -0
  29. gradio/components/duplicate_button.py +61 -0
  30. gradio/components/file.py +281 -0
  31. gradio/components/gallery.py +238 -0
  32. gradio/components/highlighted_text.py +205 -0
  33. gradio/components/html.py +81 -0
  34. gradio/components/image.py +442 -0
  35. gradio/components/interpretation.py +61 -0
  36. gradio/components/json_component.py +122 -0
  37. gradio/components/label.py +182 -0
  38. gradio/components/line_plot.py +430 -0
  39. gradio/components/markdown.py +95 -0
  40. gradio/components/model3d.py +155 -0
  41. gradio/components/number.py +238 -0
  42. gradio/components/plot.py +159 -0
  43. gradio/components/radio.py +193 -0
  44. gradio/components/scatter_plot.py +472 -0
  45. gradio/components/slider.py +210 -0
  46. gradio/components/state.py +50 -0
  47. gradio/components/status_tracker.py +13 -0
  48. gradio/components/textbox.py +284 -0
  49. gradio/components/timeseries.py +157 -0
  50. gradio/components/upload_button.py +211 -0
.gitignore ADDED
@@ -0,0 +1,78 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Python build
2
+ .eggs/
3
+ gradio.egg-info
4
+ dist/
5
+ *.pyc
6
+ __pycache__/
7
+ *.py[cod]
8
+ *$py.class
9
+ build/
10
+ __tmp/*
11
+
12
+ # JS build
13
+ gradio/templates/cdn
14
+ gradio/templates/frontend
15
+
16
+ # Secrets
17
+ .env
18
+
19
+ # Gradio run artifacts
20
+ *.db
21
+ *.sqlite3
22
+ gradio/launches.json
23
+ flagged/
24
+ gradio_cached_examples/
25
+ tmp.zip
26
+
27
+ # Tests
28
+ .coverage
29
+ coverage.xml
30
+ test.txt
31
+ **/snapshots/**/*.png
32
+ playwright-report/
33
+
34
+ # Demos
35
+ demo/tmp.zip
36
+ demo/files/*.avi
37
+ demo/files/*.mp4
38
+ demo/all_demos/demos/*
39
+ demo/all_demos/requirements.txt
40
+ demo/*/config.json
41
+ demo/annotatedimage_component/*.png
42
+
43
+ # Etc
44
+ .idea/*
45
+ .DS_Store
46
+ *.bak
47
+ workspace.code-workspace
48
+ *.h5
49
+
50
+ # dev containers
51
+ .pnpm-store/
52
+
53
+ # log files
54
+ .pnpm-debug.log
55
+
56
+ # Local virtualenv for devs
57
+ .venv*
58
+
59
+ # FRP
60
+ gradio/frpc_*
61
+ .vercel
62
+
63
+ # js
64
+ node_modules
65
+ public/build/
66
+ test-results
67
+ client/js/test.js
68
+ .config/test.py
69
+
70
+ # storybook
71
+ storybook-static
72
+ build-storybook.log
73
+ js/storybook/theme.css
74
+
75
+ # playwright
76
+ .config/playwright
77
+ !.config/playwright/index.html
78
+ !.config/playwright/index.ts
LICENSE ADDED
@@ -0,0 +1,201 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ Apache License
2
+ Version 2.0, January 2004
3
+ http://www.apache.org/licenses/
4
+
5
+ TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
6
+
7
+ 1. Definitions.
8
+
9
+ "License" shall mean the terms and conditions for use, reproduction,
10
+ and distribution as defined by Sections 1 through 9 of this document.
11
+
12
+ "Licensor" shall mean the copyright owner or entity authorized by
13
+ the copyright owner that is granting the License.
14
+
15
+ "Legal Entity" shall mean the union of the acting entity and all
16
+ other entities that control, are controlled by, or are under common
17
+ control with that entity. For the purposes of this definition,
18
+ "control" means (i) the power, direct or indirect, to cause the
19
+ direction or management of such entity, whether by contract or
20
+ otherwise, or (ii) ownership of fifty percent (50%) or more of the
21
+ outstanding shares, or (iii) beneficial ownership of such entity.
22
+
23
+ "You" (or "Your") shall mean an individual or Legal Entity
24
+ exercising permissions granted by this License.
25
+
26
+ "Source" form shall mean the preferred form for making modifications,
27
+ including but not limited to software source code, documentation
28
+ source, and configuration files.
29
+
30
+ "Object" form shall mean any form resulting from mechanical
31
+ transformation or translation of a Source form, including but
32
+ not limited to compiled object code, generated documentation,
33
+ and conversions to other media types.
34
+
35
+ "Work" shall mean the work of authorship, whether in Source or
36
+ Object form, made available under the License, as indicated by a
37
+ copyright notice that is included in or attached to the work
38
+ (an example is provided in the Appendix below).
39
+
40
+ "Derivative Works" shall mean any work, whether in Source or Object
41
+ form, that is based on (or derived from) the Work and for which the
42
+ editorial revisions, annotations, elaborations, or other modifications
43
+ represent, as a whole, an original work of authorship. For the purposes
44
+ of this License, Derivative Works shall not include works that remain
45
+ separable from, or merely link (or bind by name) to the interfaces of,
46
+ the Work and Derivative Works thereof.
47
+
48
+ "Contribution" shall mean any work of authorship, including
49
+ the original version of the Work and any modifications or additions
50
+ to that Work or Derivative Works thereof, that is intentionally
51
+ submitted to Licensor for inclusion in the Work by the copyright owner
52
+ or by an individual or Legal Entity authorized to submit on behalf of
53
+ the copyright owner. For the purposes of this definition, "submitted"
54
+ means any form of electronic, verbal, or written communication sent
55
+ to the Licensor or its representatives, including but not limited to
56
+ communication on electronic mailing lists, source code control systems,
57
+ and issue tracking systems that are managed by, or on behalf of, the
58
+ Licensor for the purpose of discussing and improving the Work, but
59
+ excluding communication that is conspicuously marked or otherwise
60
+ designated in writing by the copyright owner as "Not a Contribution."
61
+
62
+ "Contributor" shall mean Licensor and any individual or Legal Entity
63
+ on behalf of whom a Contribution has been received by Licensor and
64
+ subsequently incorporated within the Work.
65
+
66
+ 2. Grant of Copyright License. Subject to the terms and conditions of
67
+ this License, each Contributor hereby grants to You a perpetual,
68
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
69
+ copyright license to reproduce, prepare Derivative Works of,
70
+ publicly display, publicly perform, sublicense, and distribute the
71
+ Work and such Derivative Works in Source or Object form.
72
+
73
+ 3. Grant of Patent License. Subject to the terms and conditions of
74
+ this License, each Contributor hereby grants to You a perpetual,
75
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
76
+ (except as stated in this section) patent license to make, have made,
77
+ use, offer to sell, sell, import, and otherwise transfer the Work,
78
+ where such license applies only to those patent claims licensable
79
+ by such Contributor that are necessarily infringed by their
80
+ Contribution(s) alone or by combination of their Contribution(s)
81
+ with the Work to which such Contribution(s) was submitted. If You
82
+ institute patent litigation against any entity (including a
83
+ cross-claim or counterclaim in a lawsuit) alleging that the Work
84
+ or a Contribution incorporated within the Work constitutes direct
85
+ or contributory patent infringement, then any patent licenses
86
+ granted to You under this License for that Work shall terminate
87
+ as of the date such litigation is filed.
88
+
89
+ 4. Redistribution. You may reproduce and distribute copies of the
90
+ Work or Derivative Works thereof in any medium, with or without
91
+ modifications, and in Source or Object form, provided that You
92
+ meet the following conditions:
93
+
94
+ (a) You must give any other recipients of the Work or
95
+ Derivative Works a copy of this License; and
96
+
97
+ (b) You must cause any modified files to carry prominent notices
98
+ stating that You changed the files; and
99
+
100
+ (c) You must retain, in the Source form of any Derivative Works
101
+ that You distribute, all copyright, patent, trademark, and
102
+ attribution notices from the Source form of the Work,
103
+ excluding those notices that do not pertain to any part of
104
+ the Derivative Works; and
105
+
106
+ (d) If the Work includes a "NOTICE" text file as part of its
107
+ distribution, then any Derivative Works that You distribute must
108
+ include a readable copy of the attribution notices contained
109
+ within such NOTICE file, excluding those notices that do not
110
+ pertain to any part of the Derivative Works, in at least one
111
+ of the following places: within a NOTICE text file distributed
112
+ as part of the Derivative Works; within the Source form or
113
+ documentation, if provided along with the Derivative Works; or,
114
+ within a display generated by the Derivative Works, if and
115
+ wherever such third-party notices normally appear. The contents
116
+ of the NOTICE file are for informational purposes only and
117
+ do not modify the License. You may add Your own attribution
118
+ notices within Derivative Works that You distribute, alongside
119
+ or as an addendum to the NOTICE text from the Work, provided
120
+ that such additional attribution notices cannot be construed
121
+ as modifying the License.
122
+
123
+ You may add Your own copyright statement to Your modifications and
124
+ may provide additional or different license terms and conditions
125
+ for use, reproduction, or distribution of Your modifications, or
126
+ for any such Derivative Works as a whole, provided Your use,
127
+ reproduction, and distribution of the Work otherwise complies with
128
+ the conditions stated in this License.
129
+
130
+ 5. Submission of Contributions. Unless You explicitly state otherwise,
131
+ any Contribution intentionally submitted for inclusion in the Work
132
+ by You to the Licensor shall be under the terms and conditions of
133
+ this License, without any additional terms or conditions.
134
+ Notwithstanding the above, nothing herein shall supersede or modify
135
+ the terms of any separate license agreement you may have executed
136
+ with Licensor regarding such Contributions.
137
+
138
+ 6. Trademarks. This License does not grant permission to use the trade
139
+ names, trademarks, service marks, or product names of the Licensor,
140
+ except as required for reasonable and customary use in describing the
141
+ origin of the Work and reproducing the content of the NOTICE file.
142
+
143
+ 7. Disclaimer of Warranty. Unless required by applicable law or
144
+ agreed to in writing, Licensor provides the Work (and each
145
+ Contributor provides its Contributions) on an "AS IS" BASIS,
146
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
147
+ implied, including, without limitation, any warranties or conditions
148
+ of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
149
+ PARTICULAR PURPOSE. You are solely responsible for determining the
150
+ appropriateness of using or redistributing the Work and assume any
151
+ risks associated with Your exercise of permissions under this License.
152
+
153
+ 8. Limitation of Liability. In no event and under no legal theory,
154
+ whether in tort (including negligence), contract, or otherwise,
155
+ unless required by applicable law (such as deliberate and grossly
156
+ negligent acts) or agreed to in writing, shall any Contributor be
157
+ liable to You for damages, including any direct, indirect, special,
158
+ incidental, or consequential damages of any character arising as a
159
+ result of this License or out of the use or inability to use the
160
+ Work (including but not limited to damages for loss of goodwill,
161
+ work stoppage, computer failure or malfunction, or any and all
162
+ other commercial damages or losses), even if such Contributor
163
+ has been advised of the possibility of such damages.
164
+
165
+ 9. Accepting Warranty or Additional Liability. While redistributing
166
+ the Work or Derivative Works thereof, You may choose to offer,
167
+ and charge a fee for, acceptance of support, warranty, indemnity,
168
+ or other liability obligations and/or rights consistent with this
169
+ License. However, in accepting such obligations, You may act only
170
+ on Your own behalf and on Your sole responsibility, not on behalf
171
+ of any other Contributor, and only if You agree to indemnify,
172
+ defend, and hold each Contributor harmless for any liability
173
+ incurred by, or claims asserted against, such Contributor by reason
174
+ of your accepting any such warranty or additional liability.
175
+
176
+ END OF TERMS AND CONDITIONS
177
+
178
+ APPENDIX: How to apply the Apache License to your work.
179
+
180
+ To apply the Apache License to your work, attach the following
181
+ boilerplate notice, with the fields enclosed by brackets "[]"
182
+ replaced with your own identifying information. (Don't include
183
+ the brackets!) The text should be enclosed in the appropriate
184
+ comment syntax for the file format. We also recommend that a
185
+ file or class name and description of purpose be included on the
186
+ same "printed page" as the copyright notice for easier
187
+ identification within third-party archives.
188
+
189
+ Copyright [yyyy] [name of copyright owner]
190
+
191
+ Licensed under the Apache License, Version 2.0 (the "License");
192
+ you may not use this file except in compliance with the License.
193
+ You may obtain a copy of the License at
194
+
195
+ http://www.apache.org/licenses/LICENSE-2.0
196
+
197
+ Unless required by applicable law or agreed to in writing, software
198
+ distributed under the License is distributed on an "AS IS" BASIS,
199
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
200
+ See the License for the specific language governing permissions and
201
+ limitations under the License.
PKG-INFO ADDED
@@ -0,0 +1,374 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ Metadata-Version: 2.1
2
+ Name: gradio
3
+ Version: 3.39.0
4
+ Summary: Python library for easily interacting with trained machine learning models
5
+ Project-URL: Homepage, https://github.com/gradio-app/gradio
6
+ Author-email: Abubakar Abid <team@gradio.app>, Ali Abid <team@gradio.app>, Ali Abdalla <team@gradio.app>, Dawood Khan <team@gradio.app>, Ahsen Khaliq <team@gradio.app>, Pete Allen <team@gradio.app>, Ömer Faruk Özdemir <team@gradio.app>
7
+ License-Expression: Apache-2.0
8
+ License-File: LICENSE
9
+ Keywords: machine learning,reproducibility,visualization
10
+ Classifier: Development Status :: 5 - Production/Stable
11
+ Classifier: License :: OSI Approved :: Apache Software License
12
+ Classifier: Operating System :: OS Independent
13
+ Classifier: Programming Language :: Python :: 3
14
+ Classifier: Programming Language :: Python :: 3 :: Only
15
+ Classifier: Programming Language :: Python :: 3.8
16
+ Classifier: Programming Language :: Python :: 3.9
17
+ Classifier: Programming Language :: Python :: 3.10
18
+ Classifier: Programming Language :: Python :: 3.11
19
+ Classifier: Topic :: Scientific/Engineering
20
+ Classifier: Topic :: Scientific/Engineering :: Artificial Intelligence
21
+ Classifier: Topic :: Scientific/Engineering :: Visualization
22
+ Requires-Python: >=3.8
23
+ Requires-Dist: aiofiles<24.0,>=22.0
24
+ Requires-Dist: aiohttp~=3.0
25
+ Requires-Dist: altair<6.0,>=4.2.0
26
+ Requires-Dist: fastapi
27
+ Requires-Dist: ffmpy
28
+ Requires-Dist: gradio-client>=0.3.0
29
+ Requires-Dist: httpx
30
+ Requires-Dist: huggingface-hub>=0.14.0
31
+ Requires-Dist: jinja2<4.0
32
+ Requires-Dist: markdown-it-py[linkify]>=2.0.0
33
+ Requires-Dist: markupsafe~=2.0
34
+ Requires-Dist: matplotlib~=3.0
35
+ Requires-Dist: mdit-py-plugins<=0.3.3
36
+ Requires-Dist: numpy~=1.0
37
+ Requires-Dist: orjson~=3.0
38
+ Requires-Dist: packaging
39
+ Requires-Dist: pandas<3.0,>=1.0
40
+ Requires-Dist: pillow<11.0,>=8.0
41
+ Requires-Dist: pydantic!=1.8,!=1.8.1,!=2.0.0,!=2.0.1,<3.0.0,>=1.7.4
42
+ Requires-Dist: pydub
43
+ Requires-Dist: python-multipart
44
+ Requires-Dist: pyyaml<7.0,>=5.0
45
+ Requires-Dist: requests~=2.0
46
+ Requires-Dist: semantic-version~=2.0
47
+ Requires-Dist: typing-extensions~=4.0
48
+ Requires-Dist: uvicorn>=0.14.0
49
+ Requires-Dist: websockets<12.0,>=10.0
50
+ Description-Content-Type: text/markdown
51
+
52
+ <!-- DO NOT EDIT THIS FILE DIRECTLY. INSTEAD EDIT THE `readme_template.md` OR `guides/1)getting_started/1)quickstart.md` TEMPLATES AND THEN RUN `render_readme.py` SCRIPT. -->
53
+
54
+ <div align="center">
55
+
56
+ [<img src="https://raw.githubusercontent.com/gradio-app/gradio/main/readme_files/gradio.svg" alt="gradio" width=300>](https://gradio.app)<br>
57
+ <em>Build & share delightful machine learning apps easily</em>
58
+
59
+ [![gradio-backend](https://github.com/gradio-app/gradio/actions/workflows/backend.yml/badge.svg)](https://github.com/gradio-app/gradio/actions/workflows/backend.yml)
60
+ [![gradio-ui](https://github.com/gradio-app/gradio/actions/workflows/ui.yml/badge.svg)](https://github.com/gradio-app/gradio/actions/workflows/ui.yml)
61
+ [![PyPI](https://img.shields.io/pypi/v/gradio)](https://pypi.org/project/gradio/)
62
+ [![PyPI downloads](https://img.shields.io/pypi/dm/gradio)](https://pypi.org/project/gradio/)
63
+ ![Python version](https://img.shields.io/badge/python-3.8+-important)
64
+ [![Twitter follow](https://img.shields.io/twitter/follow/gradio?style=social&label=follow)](https://twitter.com/gradio)
65
+
66
+ [Website](https://gradio.app)
67
+ | [Documentation](https://gradio.app/docs/)
68
+ | [Guides](https://gradio.app/guides/)
69
+ | [Getting Started](https://gradio.app/getting_started/)
70
+ | [Examples](demo/)
71
+ | [中文](https://raw.githubusercontent.com/gradio-app/gradio/main/readme_files/zh-cn#readme)
72
+ </div>
73
+
74
+ # Gradio: Build Machine Learning Web Apps — in Python
75
+
76
+ Gradio is an open-source Python library that is used to build machine learning and data science demos and web applications.
77
+
78
+ With Gradio, you can quickly create a beautiful user interface around your machine learning models or data science workflow and let people "try it out" by dragging-and-dropping in their own images,
79
+ pasting text, recording their own voice, and interacting with your demo, all through the browser.
80
+
81
+ ![Interface montage](https://raw.githubusercontent.com/gradio-app/gradio/main/readme_files/header-image.jpg)
82
+
83
+ Gradio is useful for:
84
+
85
+ - **Demoing** your machine learning models for clients/collaborators/users/students.
86
+
87
+ - **Deploying** your models quickly with automatic shareable links and getting feedback on model performance.
88
+
89
+ - **Debugging** your model interactively during development using built-in manipulation and interpretation tools.
90
+
91
+ ## Quickstart
92
+
93
+ **Prerequisite**: Gradio requires Python 3.8 or higher, that's all!
94
+
95
+ ### What Does Gradio Do?
96
+
97
+ One of the *best ways to share* your machine learning model, API, or data science workflow with others is to create an **interactive app** that allows your users or colleagues to try out the demo in their browsers.
98
+
99
+ Gradio allows you to **build demos and share them, all in Python.** And usually in just a few lines of code! So let's get started.
100
+
101
+ ### Hello, World
102
+
103
+ To get Gradio running with a simple "Hello, World" example, follow these three steps:
104
+
105
+ 1\. Install Gradio using pip:
106
+
107
+ ```bash
108
+ pip install gradio
109
+ ```
110
+
111
+ 2\. Run the code below as a Python script or in a Jupyter Notebook (or [Google Colab](https://colab.research.google.com/drive/18ODkJvyxHutTN0P5APWyGFO_xwNcgHDZ?usp=sharing)):
112
+
113
+ ```python
114
+ import gradio as gr
115
+
116
+ def greet(name):
117
+ return "Hello " + name + "!"
118
+
119
+ demo = gr.Interface(fn=greet, inputs="text", outputs="text")
120
+
121
+ demo.launch()
122
+ ```
123
+
124
+
125
+ We shorten the imported name to `gr` for better readability of code using Gradio. This is a widely adopted convention that you should follow so that anyone working with your code can easily understand it.
126
+
127
+ 3\. The demo below will appear automatically within the Jupyter Notebook, or pop in a browser on [http://localhost:7860](http://localhost:7860) if running from a script:
128
+
129
+ ![`hello_world` demo](https://raw.githubusercontent.com/gradio-app/gradio/main/demo/hello_world/screenshot.gif)
130
+
131
+ When developing locally, if you want to run the code as a Python script, you can use the Gradio CLI to launch the application **in reload mode**, which will provide seamless and fast development. Learn more about reloading in the [Auto-Reloading Guide](https://gradio.app/developing-faster-with-reload-mode/).
132
+
133
+ ```bash
134
+ gradio app.py
135
+ ```
136
+
137
+ Note: you can also do `python app.py`, but it won't provide the automatic reload mechanism.
138
+
139
+ ### The `Interface` Class
140
+
141
+ You'll notice that in order to make the demo, we created a `gr.Interface`. This `Interface` class can wrap any Python function with a user interface. In the example above, we saw a simple text-based function, but the function could be anything from music generator to a tax calculator to the prediction function of a pretrained machine learning model.
142
+
143
+ The core `Interface` class is initialized with three required parameters:
144
+
145
+ - `fn`: the function to wrap a UI around
146
+ - `inputs`: which component(s) to use for the input (e.g. `"text"`, `"image"` or `"audio"`)
147
+ - `outputs`: which component(s) to use for the output (e.g. `"text"`, `"image"` or `"label"`)
148
+
149
+ Let's take a closer look at these components used to provide input and output.
150
+
151
+ ### Components Attributes
152
+
153
+ We saw some simple `Textbox` components in the previous examples, but what if you want to change how the UI components look or behave?
154
+
155
+ Let's say you want to customize the input text field — for example, you wanted it to be larger and have a text placeholder. If we use the actual class for `Textbox` instead of using the string shortcut, you have access to much more customizability through component attributes.
156
+
157
+ ```python
158
+ import gradio as gr
159
+
160
+ def greet(name):
161
+ return "Hello " + name + "!"
162
+
163
+ demo = gr.Interface(
164
+ fn=greet,
165
+ inputs=gr.Textbox(lines=2, placeholder="Name Here..."),
166
+ outputs="text",
167
+ )
168
+ demo.launch()
169
+ ```
170
+
171
+ ![`hello_world_2` demo](https://raw.githubusercontent.com/gradio-app/gradio/main/demo/hello_world_2/screenshot.gif)
172
+
173
+ ### Multiple Input and Output Components
174
+
175
+ Suppose you had a more complex function, with multiple inputs and outputs. In the example below, we define a function that takes a string, boolean, and number, and returns a string and number. Take a look how you pass a list of input and output components.
176
+
177
+ ```python
178
+ import gradio as gr
179
+
180
+ def greet(name, is_morning, temperature):
181
+ salutation = "Good morning" if is_morning else "Good evening"
182
+ greeting = f"{salutation} {name}. It is {temperature} degrees today"
183
+ celsius = (temperature - 32) * 5 / 9
184
+ return greeting, round(celsius, 2)
185
+
186
+ demo = gr.Interface(
187
+ fn=greet,
188
+ inputs=["text", "checkbox", gr.Slider(0, 100)],
189
+ outputs=["text", "number"],
190
+ )
191
+ demo.launch()
192
+ ```
193
+
194
+ ![`hello_world_3` demo](https://raw.githubusercontent.com/gradio-app/gradio/main/demo/hello_world_3/screenshot.gif)
195
+
196
+ You simply wrap the components in a list. Each component in the `inputs` list corresponds to one of the parameters of the function, in order. Each component in the `outputs` list corresponds to one of the values returned by the function, again in order.
197
+
198
+ ### An Image Example
199
+
200
+ Gradio supports many types of components, such as `Image`, `DataFrame`, `Video`, or `Label`. Let's try an image-to-image function to get a feel for these!
201
+
202
+ ```python
203
+ import numpy as np
204
+ import gradio as gr
205
+
206
+ def sepia(input_img):
207
+ sepia_filter = np.array([
208
+ [0.393, 0.769, 0.189],
209
+ [0.349, 0.686, 0.168],
210
+ [0.272, 0.534, 0.131]
211
+ ])
212
+ sepia_img = input_img.dot(sepia_filter.T)
213
+ sepia_img /= sepia_img.max()
214
+ return sepia_img
215
+
216
+ demo = gr.Interface(sepia, gr.Image(shape=(200, 200)), "image")
217
+ demo.launch()
218
+ ```
219
+
220
+ ![`sepia_filter` demo](https://raw.githubusercontent.com/gradio-app/gradio/main/demo/sepia_filter/screenshot.gif)
221
+
222
+ When using the `Image` component as input, your function will receive a NumPy array with the shape `(height, width, 3)`, where the last dimension represents the RGB values. We'll return an image as well in the form of a NumPy array.
223
+
224
+ You can also set the datatype used by the component with the `type=` keyword argument. For example, if you wanted your function to take a file path to an image instead of a NumPy array, the input `Image` component could be written as:
225
+
226
+ ```python
227
+ gr.Image(type="filepath", shape=...)
228
+ ```
229
+
230
+ Also note that our input `Image` component comes with an edit button 🖉, which allows for cropping and zooming into images. Manipulating images in this way can help reveal biases or hidden flaws in a machine learning model!
231
+
232
+ You can read more about the many components and how to use them in the [Gradio docs](https://gradio.app/docs).
233
+
234
+ ### Chatbots
235
+
236
+ Gradio includes a high-level class, `gr.ChatInterface`, which is similar to `gr.Interface`, but is specifically designed for chatbot UIs. The `gr.ChatInterface` class also wraps a function but this function must have a specific signature. The function should take two arguments: `message` and then `history` (the arguments can be named anything, but must be in this order)
237
+
238
+ * `message`: a `str` representing the user's input
239
+ * `history`: a `list` of `list` representing the conversations up until that point. Each inner list consists of two `str` representing a pair: `[user input, bot response]`.
240
+
241
+ Your function should return a single string response, which is the bot's response to the particular user input `message`.
242
+
243
+ Other than that, `gr.ChatInterface` has no required parameters (though several are available for customization of the UI).
244
+
245
+ Here's a toy example:
246
+
247
+ ```python
248
+ import random
249
+ import gradio as gr
250
+
251
+ def random_response(message, history):
252
+ return random.choice(["Yes", "No"])
253
+
254
+ demo = gr.ChatInterface(random_response)
255
+
256
+ demo.launch()
257
+ ```
258
+
259
+ ![`chatinterface_random_response` demo](https://raw.githubusercontent.com/gradio-app/gradio/main/demo/chatinterface_random_response/screenshot.gif)
260
+
261
+ You can [read more about `gr.ChatInterface` here](https://gradio.app/guides/creating-a-chatbot-fast).
262
+
263
+ ### Blocks: More Flexibility and Control
264
+
265
+ Gradio offers two approaches to build apps:
266
+
267
+ 1\. **Interface** and **ChatInterface**, which provide a high-level abstraction for creating demos that we've been discussing so far.
268
+
269
+ 2\. **Blocks**, a low-level API for designing web apps with more flexible layouts and data flows. Blocks allows you to do things like feature multiple data flows and demos, control where components appear on the page, handle complex data flows (e.g. outputs can serve as inputs to other functions), and update properties/visibility of components based on user interaction — still all in Python. If this customizability is what you need, try `Blocks` instead!
270
+
271
+ ### Hello, Blocks
272
+
273
+ Let's take a look at a simple example. Note how the API here differs from `Interface`.
274
+
275
+ ```python
276
+ import gradio as gr
277
+
278
+ def greet(name):
279
+ return "Hello " + name + "!"
280
+
281
+ with gr.Blocks() as demo:
282
+ name = gr.Textbox(label="Name")
283
+ output = gr.Textbox(label="Output Box")
284
+ greet_btn = gr.Button("Greet")
285
+ greet_btn.click(fn=greet, inputs=name, outputs=output, api_name="greet")
286
+
287
+
288
+ demo.launch()
289
+ ```
290
+
291
+ ![`hello_blocks` demo](https://raw.githubusercontent.com/gradio-app/gradio/main/demo/hello_blocks/screenshot.gif)
292
+
293
+ Things to note:
294
+
295
+ - `Blocks` are made with a `with` clause, and any component created inside this clause is automatically added to the app.
296
+ - Components appear vertically in the app in the order they are created. (Later we will cover customizing layouts!)
297
+ - A `Button` was created, and then a `click` event-listener was added to this button. The API for this should look familiar! Like an `Interface`, the `click` method takes a Python function, input components, and output components.
298
+
299
+ ### More Complexity
300
+
301
+ Here's an app to give you a taste of what's possible with `Blocks`:
302
+
303
+ ```python
304
+ import numpy as np
305
+ import gradio as gr
306
+
307
+
308
+ def flip_text(x):
309
+ return x[::-1]
310
+
311
+
312
+ def flip_image(x):
313
+ return np.fliplr(x)
314
+
315
+
316
+ with gr.Blocks() as demo:
317
+ gr.Markdown("Flip text or image files using this demo.")
318
+ with gr.Tab("Flip Text"):
319
+ text_input = gr.Textbox()
320
+ text_output = gr.Textbox()
321
+ text_button = gr.Button("Flip")
322
+ with gr.Tab("Flip Image"):
323
+ with gr.Row():
324
+ image_input = gr.Image()
325
+ image_output = gr.Image()
326
+ image_button = gr.Button("Flip")
327
+
328
+ with gr.Accordion("Open for More!"):
329
+ gr.Markdown("Look at me...")
330
+
331
+ text_button.click(flip_text, inputs=text_input, outputs=text_output)
332
+ image_button.click(flip_image, inputs=image_input, outputs=image_output)
333
+
334
+ demo.launch()
335
+ ```
336
+
337
+ ![`blocks_flipper` demo](https://raw.githubusercontent.com/gradio-app/gradio/main/demo/blocks_flipper/screenshot.gif)
338
+
339
+ A lot more going on here! We'll cover how to create complex `Blocks` apps like this in the [building with blocks](https://gradio.app/building_with_blocks) section for you.
340
+
341
+ Congrats, you're now familiar with the basics of Gradio! 🥳 Go to our [next guide](https://gradio.app/key_features) to learn more about the key features of Gradio.
342
+
343
+
344
+ ## Open Source Stack
345
+
346
+ Gradio is built with many wonderful open-source libraries, please support them as well!
347
+
348
+ [<img src="https://raw.githubusercontent.com/gradio-app/gradio/main/readme_files/huggingface_mini.svg" alt="huggingface" height=40>](https://huggingface.co)
349
+ [<img src="https://raw.githubusercontent.com/gradio-app/gradio/main/readme_files/python.svg" alt="python" height=40>](https://www.python.org)
350
+ [<img src="https://raw.githubusercontent.com/gradio-app/gradio/main/readme_files/fastapi.svg" alt="fastapi" height=40>](https://fastapi.tiangolo.com)
351
+ [<img src="https://raw.githubusercontent.com/gradio-app/gradio/main/readme_files/encode.svg" alt="encode" height=40>](https://www.encode.io)
352
+ [<img src="https://raw.githubusercontent.com/gradio-app/gradio/main/readme_files/svelte.svg" alt="svelte" height=40>](https://svelte.dev)
353
+ [<img src="https://raw.githubusercontent.com/gradio-app/gradio/main/readme_files/vite.svg" alt="vite" height=40>](https://vitejs.dev)
354
+ [<img src="https://raw.githubusercontent.com/gradio-app/gradio/main/readme_files/pnpm.svg" alt="pnpm" height=40>](https://pnpm.io)
355
+ [<img src="https://raw.githubusercontent.com/gradio-app/gradio/main/readme_files/tailwind.svg" alt="tailwind" height=40>](https://tailwindcss.com)
356
+ [<img src="https://raw.githubusercontent.com/gradio-app/gradio/main/readme_files/storybook.svg" alt="storybook" height=40>](https://storybook.js.org/)
357
+ [<img src="https://raw.githubusercontent.com/gradio-app/gradio/main/readme_files/chromatic.svg" alt="chromatic" height=40>](https://www.chromatic.com/)
358
+
359
+ ## License
360
+
361
+ Gradio is licensed under the Apache License 2.0 found in the [LICENSE](LICENSE) file in the root directory of this repository.
362
+
363
+ ## Citation
364
+
365
+ Also check out the paper *[Gradio: Hassle-Free Sharing and Testing of ML Models in the Wild](https://arxiv.org/abs/1906.02569), ICML HILL 2019*, and please cite it if you use Gradio in your work.
366
+
367
+ ```
368
+ @article{abid2019gradio,
369
+ title = {Gradio: Hassle-Free Sharing and Testing of ML Models in the Wild},
370
+ author = {Abid, Abubakar and Abdalla, Ali and Abid, Ali and Khan, Dawood and Alfozan, Abdulrahman and Zou, James},
371
+ journal = {arXiv preprint arXiv:1906.02569},
372
+ year = {2019},
373
+ }
374
+ ```
README.md ADDED
@@ -0,0 +1,323 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ <!-- DO NOT EDIT THIS FILE DIRECTLY. INSTEAD EDIT THE `readme_template.md` OR `guides/1)getting_started/1)quickstart.md` TEMPLATES AND THEN RUN `render_readme.py` SCRIPT. -->
2
+
3
+ <div align="center">
4
+
5
+ [<img src="readme_files/gradio.svg" alt="gradio" width=300>](https://gradio.app)<br>
6
+ <em>Build & share delightful machine learning apps easily</em>
7
+
8
+ [![gradio-backend](https://github.com/gradio-app/gradio/actions/workflows/backend.yml/badge.svg)](https://github.com/gradio-app/gradio/actions/workflows/backend.yml)
9
+ [![gradio-ui](https://github.com/gradio-app/gradio/actions/workflows/ui.yml/badge.svg)](https://github.com/gradio-app/gradio/actions/workflows/ui.yml)
10
+ [![PyPI](https://img.shields.io/pypi/v/gradio)](https://pypi.org/project/gradio/)
11
+ [![PyPI downloads](https://img.shields.io/pypi/dm/gradio)](https://pypi.org/project/gradio/)
12
+ ![Python version](https://img.shields.io/badge/python-3.8+-important)
13
+ [![Twitter follow](https://img.shields.io/twitter/follow/gradio?style=social&label=follow)](https://twitter.com/gradio)
14
+
15
+ [Website](https://gradio.app)
16
+ | [Documentation](https://gradio.app/docs/)
17
+ | [Guides](https://gradio.app/guides/)
18
+ | [Getting Started](https://gradio.app/getting_started/)
19
+ | [Examples](demo/)
20
+ | [中文](readme_files/zh-cn#readme)
21
+ </div>
22
+
23
+ # Gradio: Build Machine Learning Web Apps — in Python
24
+
25
+ Gradio is an open-source Python library that is used to build machine learning and data science demos and web applications.
26
+
27
+ With Gradio, you can quickly create a beautiful user interface around your machine learning models or data science workflow and let people "try it out" by dragging-and-dropping in their own images,
28
+ pasting text, recording their own voice, and interacting with your demo, all through the browser.
29
+
30
+ ![Interface montage](readme_files/header-image.jpg)
31
+
32
+ Gradio is useful for:
33
+
34
+ - **Demoing** your machine learning models for clients/collaborators/users/students.
35
+
36
+ - **Deploying** your models quickly with automatic shareable links and getting feedback on model performance.
37
+
38
+ - **Debugging** your model interactively during development using built-in manipulation and interpretation tools.
39
+
40
+ ## Quickstart
41
+
42
+ **Prerequisite**: Gradio requires Python 3.8 or higher, that's all!
43
+
44
+ ### What Does Gradio Do?
45
+
46
+ One of the *best ways to share* your machine learning model, API, or data science workflow with others is to create an **interactive app** that allows your users or colleagues to try out the demo in their browsers.
47
+
48
+ Gradio allows you to **build demos and share them, all in Python.** And usually in just a few lines of code! So let's get started.
49
+
50
+ ### Hello, World
51
+
52
+ To get Gradio running with a simple "Hello, World" example, follow these three steps:
53
+
54
+ 1\. Install Gradio using pip:
55
+
56
+ ```bash
57
+ pip install gradio
58
+ ```
59
+
60
+ 2\. Run the code below as a Python script or in a Jupyter Notebook (or [Google Colab](https://colab.research.google.com/drive/18ODkJvyxHutTN0P5APWyGFO_xwNcgHDZ?usp=sharing)):
61
+
62
+ ```python
63
+ import gradio as gr
64
+
65
+ def greet(name):
66
+ return "Hello " + name + "!"
67
+
68
+ demo = gr.Interface(fn=greet, inputs="text", outputs="text")
69
+
70
+ demo.launch()
71
+ ```
72
+
73
+
74
+ We shorten the imported name to `gr` for better readability of code using Gradio. This is a widely adopted convention that you should follow so that anyone working with your code can easily understand it.
75
+
76
+ 3\. The demo below will appear automatically within the Jupyter Notebook, or pop in a browser on [http://localhost:7860](http://localhost:7860) if running from a script:
77
+
78
+ ![`hello_world` demo](demo/hello_world/screenshot.gif)
79
+
80
+ When developing locally, if you want to run the code as a Python script, you can use the Gradio CLI to launch the application **in reload mode**, which will provide seamless and fast development. Learn more about reloading in the [Auto-Reloading Guide](https://gradio.app/developing-faster-with-reload-mode/).
81
+
82
+ ```bash
83
+ gradio app.py
84
+ ```
85
+
86
+ Note: you can also do `python app.py`, but it won't provide the automatic reload mechanism.
87
+
88
+ ### The `Interface` Class
89
+
90
+ You'll notice that in order to make the demo, we created a `gr.Interface`. This `Interface` class can wrap any Python function with a user interface. In the example above, we saw a simple text-based function, but the function could be anything from music generator to a tax calculator to the prediction function of a pretrained machine learning model.
91
+
92
+ The core `Interface` class is initialized with three required parameters:
93
+
94
+ - `fn`: the function to wrap a UI around
95
+ - `inputs`: which component(s) to use for the input (e.g. `"text"`, `"image"` or `"audio"`)
96
+ - `outputs`: which component(s) to use for the output (e.g. `"text"`, `"image"` or `"label"`)
97
+
98
+ Let's take a closer look at these components used to provide input and output.
99
+
100
+ ### Components Attributes
101
+
102
+ We saw some simple `Textbox` components in the previous examples, but what if you want to change how the UI components look or behave?
103
+
104
+ Let's say you want to customize the input text field — for example, you wanted it to be larger and have a text placeholder. If we use the actual class for `Textbox` instead of using the string shortcut, you have access to much more customizability through component attributes.
105
+
106
+ ```python
107
+ import gradio as gr
108
+
109
+ def greet(name):
110
+ return "Hello " + name + "!"
111
+
112
+ demo = gr.Interface(
113
+ fn=greet,
114
+ inputs=gr.Textbox(lines=2, placeholder="Name Here..."),
115
+ outputs="text",
116
+ )
117
+ demo.launch()
118
+ ```
119
+
120
+ ![`hello_world_2` demo](demo/hello_world_2/screenshot.gif)
121
+
122
+ ### Multiple Input and Output Components
123
+
124
+ Suppose you had a more complex function, with multiple inputs and outputs. In the example below, we define a function that takes a string, boolean, and number, and returns a string and number. Take a look how you pass a list of input and output components.
125
+
126
+ ```python
127
+ import gradio as gr
128
+
129
+ def greet(name, is_morning, temperature):
130
+ salutation = "Good morning" if is_morning else "Good evening"
131
+ greeting = f"{salutation} {name}. It is {temperature} degrees today"
132
+ celsius = (temperature - 32) * 5 / 9
133
+ return greeting, round(celsius, 2)
134
+
135
+ demo = gr.Interface(
136
+ fn=greet,
137
+ inputs=["text", "checkbox", gr.Slider(0, 100)],
138
+ outputs=["text", "number"],
139
+ )
140
+ demo.launch()
141
+ ```
142
+
143
+ ![`hello_world_3` demo](demo/hello_world_3/screenshot.gif)
144
+
145
+ You simply wrap the components in a list. Each component in the `inputs` list corresponds to one of the parameters of the function, in order. Each component in the `outputs` list corresponds to one of the values returned by the function, again in order.
146
+
147
+ ### An Image Example
148
+
149
+ Gradio supports many types of components, such as `Image`, `DataFrame`, `Video`, or `Label`. Let's try an image-to-image function to get a feel for these!
150
+
151
+ ```python
152
+ import numpy as np
153
+ import gradio as gr
154
+
155
+ def sepia(input_img):
156
+ sepia_filter = np.array([
157
+ [0.393, 0.769, 0.189],
158
+ [0.349, 0.686, 0.168],
159
+ [0.272, 0.534, 0.131]
160
+ ])
161
+ sepia_img = input_img.dot(sepia_filter.T)
162
+ sepia_img /= sepia_img.max()
163
+ return sepia_img
164
+
165
+ demo = gr.Interface(sepia, gr.Image(shape=(200, 200)), "image")
166
+ demo.launch()
167
+ ```
168
+
169
+ ![`sepia_filter` demo](demo/sepia_filter/screenshot.gif)
170
+
171
+ When using the `Image` component as input, your function will receive a NumPy array with the shape `(height, width, 3)`, where the last dimension represents the RGB values. We'll return an image as well in the form of a NumPy array.
172
+
173
+ You can also set the datatype used by the component with the `type=` keyword argument. For example, if you wanted your function to take a file path to an image instead of a NumPy array, the input `Image` component could be written as:
174
+
175
+ ```python
176
+ gr.Image(type="filepath", shape=...)
177
+ ```
178
+
179
+ Also note that our input `Image` component comes with an edit button 🖉, which allows for cropping and zooming into images. Manipulating images in this way can help reveal biases or hidden flaws in a machine learning model!
180
+
181
+ You can read more about the many components and how to use them in the [Gradio docs](https://gradio.app/docs).
182
+
183
+ ### Chatbots
184
+
185
+ Gradio includes a high-level class, `gr.ChatInterface`, which is similar to `gr.Interface`, but is specifically designed for chatbot UIs. The `gr.ChatInterface` class also wraps a function but this function must have a specific signature. The function should take two arguments: `message` and then `history` (the arguments can be named anything, but must be in this order)
186
+
187
+ * `message`: a `str` representing the user's input
188
+ * `history`: a `list` of `list` representing the conversations up until that point. Each inner list consists of two `str` representing a pair: `[user input, bot response]`.
189
+
190
+ Your function should return a single string response, which is the bot's response to the particular user input `message`.
191
+
192
+ Other than that, `gr.ChatInterface` has no required parameters (though several are available for customization of the UI).
193
+
194
+ Here's a toy example:
195
+
196
+ ```python
197
+ import random
198
+ import gradio as gr
199
+
200
+ def random_response(message, history):
201
+ return random.choice(["Yes", "No"])
202
+
203
+ demo = gr.ChatInterface(random_response)
204
+
205
+ demo.launch()
206
+ ```
207
+
208
+ ![`chatinterface_random_response` demo](demo/chatinterface_random_response/screenshot.gif)
209
+
210
+ You can [read more about `gr.ChatInterface` here](https://gradio.app/guides/creating-a-chatbot-fast).
211
+
212
+ ### Blocks: More Flexibility and Control
213
+
214
+ Gradio offers two approaches to build apps:
215
+
216
+ 1\. **Interface** and **ChatInterface**, which provide a high-level abstraction for creating demos that we've been discussing so far.
217
+
218
+ 2\. **Blocks**, a low-level API for designing web apps with more flexible layouts and data flows. Blocks allows you to do things like feature multiple data flows and demos, control where components appear on the page, handle complex data flows (e.g. outputs can serve as inputs to other functions), and update properties/visibility of components based on user interaction — still all in Python. If this customizability is what you need, try `Blocks` instead!
219
+
220
+ ### Hello, Blocks
221
+
222
+ Let's take a look at a simple example. Note how the API here differs from `Interface`.
223
+
224
+ ```python
225
+ import gradio as gr
226
+
227
+ def greet(name):
228
+ return "Hello " + name + "!"
229
+
230
+ with gr.Blocks() as demo:
231
+ name = gr.Textbox(label="Name")
232
+ output = gr.Textbox(label="Output Box")
233
+ greet_btn = gr.Button("Greet")
234
+ greet_btn.click(fn=greet, inputs=name, outputs=output, api_name="greet")
235
+
236
+
237
+ demo.launch()
238
+ ```
239
+
240
+ ![`hello_blocks` demo](demo/hello_blocks/screenshot.gif)
241
+
242
+ Things to note:
243
+
244
+ - `Blocks` are made with a `with` clause, and any component created inside this clause is automatically added to the app.
245
+ - Components appear vertically in the app in the order they are created. (Later we will cover customizing layouts!)
246
+ - A `Button` was created, and then a `click` event-listener was added to this button. The API for this should look familiar! Like an `Interface`, the `click` method takes a Python function, input components, and output components.
247
+
248
+ ### More Complexity
249
+
250
+ Here's an app to give you a taste of what's possible with `Blocks`:
251
+
252
+ ```python
253
+ import numpy as np
254
+ import gradio as gr
255
+
256
+
257
+ def flip_text(x):
258
+ return x[::-1]
259
+
260
+
261
+ def flip_image(x):
262
+ return np.fliplr(x)
263
+
264
+
265
+ with gr.Blocks() as demo:
266
+ gr.Markdown("Flip text or image files using this demo.")
267
+ with gr.Tab("Flip Text"):
268
+ text_input = gr.Textbox()
269
+ text_output = gr.Textbox()
270
+ text_button = gr.Button("Flip")
271
+ with gr.Tab("Flip Image"):
272
+ with gr.Row():
273
+ image_input = gr.Image()
274
+ image_output = gr.Image()
275
+ image_button = gr.Button("Flip")
276
+
277
+ with gr.Accordion("Open for More!"):
278
+ gr.Markdown("Look at me...")
279
+
280
+ text_button.click(flip_text, inputs=text_input, outputs=text_output)
281
+ image_button.click(flip_image, inputs=image_input, outputs=image_output)
282
+
283
+ demo.launch()
284
+ ```
285
+
286
+ ![`blocks_flipper` demo](demo/blocks_flipper/screenshot.gif)
287
+
288
+ A lot more going on here! We'll cover how to create complex `Blocks` apps like this in the [building with blocks](https://gradio.app/building_with_blocks) section for you.
289
+
290
+ Congrats, you're now familiar with the basics of Gradio! 🥳 Go to our [next guide](https://gradio.app/key_features) to learn more about the key features of Gradio.
291
+
292
+
293
+ ## Open Source Stack
294
+
295
+ Gradio is built with many wonderful open-source libraries, please support them as well!
296
+
297
+ [<img src="readme_files/huggingface_mini.svg" alt="huggingface" height=40>](https://huggingface.co)
298
+ [<img src="readme_files/python.svg" alt="python" height=40>](https://www.python.org)
299
+ [<img src="readme_files/fastapi.svg" alt="fastapi" height=40>](https://fastapi.tiangolo.com)
300
+ [<img src="readme_files/encode.svg" alt="encode" height=40>](https://www.encode.io)
301
+ [<img src="readme_files/svelte.svg" alt="svelte" height=40>](https://svelte.dev)
302
+ [<img src="readme_files/vite.svg" alt="vite" height=40>](https://vitejs.dev)
303
+ [<img src="readme_files/pnpm.svg" alt="pnpm" height=40>](https://pnpm.io)
304
+ [<img src="readme_files/tailwind.svg" alt="tailwind" height=40>](https://tailwindcss.com)
305
+ [<img src="readme_files/storybook.svg" alt="storybook" height=40>](https://storybook.js.org/)
306
+ [<img src="readme_files/chromatic.svg" alt="chromatic" height=40>](https://www.chromatic.com/)
307
+
308
+ ## License
309
+
310
+ Gradio is licensed under the Apache License 2.0 found in the [LICENSE](LICENSE) file in the root directory of this repository.
311
+
312
+ ## Citation
313
+
314
+ Also check out the paper *[Gradio: Hassle-Free Sharing and Testing of ML Models in the Wild](https://arxiv.org/abs/1906.02569), ICML HILL 2019*, and please cite it if you use Gradio in your work.
315
+
316
+ ```
317
+ @article{abid2019gradio,
318
+ title = {Gradio: Hassle-Free Sharing and Testing of ML Models in the Wild},
319
+ author = {Abid, Abubakar and Abdalla, Ali and Abid, Ali and Khan, Dawood and Alfozan, Abdulrahman and Zou, James},
320
+ journal = {arXiv preprint arXiv:1906.02569},
321
+ year = {2019},
322
+ }
323
+ ```
gradio/.dockerignore ADDED
@@ -0,0 +1,2 @@
 
 
 
1
+ templates/frontend
2
+ templates/frontend/**/*
gradio/CHANGELOG.md ADDED
The diff for this file is too large to render. See raw diff
 
gradio/__init__.py ADDED
@@ -0,0 +1,107 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import pkgutil
2
+
3
+ import gradio.components as components
4
+ import gradio.inputs as inputs
5
+ import gradio.outputs as outputs
6
+ import gradio.processing_utils
7
+ import gradio.templates
8
+ import gradio.themes as themes
9
+ from gradio.blocks import Blocks
10
+ from gradio.chat_interface import ChatInterface
11
+ from gradio.components import (
12
+ HTML,
13
+ JSON,
14
+ AnnotatedImage,
15
+ Annotatedimage,
16
+ Audio,
17
+ BarPlot,
18
+ Button,
19
+ Carousel,
20
+ Chatbot,
21
+ Checkbox,
22
+ CheckboxGroup,
23
+ Checkboxgroup,
24
+ ClearButton,
25
+ Code,
26
+ ColorPicker,
27
+ DataFrame,
28
+ Dataframe,
29
+ Dataset,
30
+ Dropdown,
31
+ DuplicateButton,
32
+ File,
33
+ Gallery,
34
+ Highlight,
35
+ HighlightedText,
36
+ Highlightedtext,
37
+ Image,
38
+ Interpretation,
39
+ Json,
40
+ Label,
41
+ LinePlot,
42
+ Markdown,
43
+ Model3D,
44
+ Number,
45
+ Plot,
46
+ Radio,
47
+ ScatterPlot,
48
+ Slider,
49
+ State,
50
+ StatusTracker,
51
+ Text,
52
+ Textbox,
53
+ TimeSeries,
54
+ Timeseries,
55
+ UploadButton,
56
+ Variable,
57
+ Video,
58
+ component,
59
+ )
60
+ from gradio.deploy_space import deploy
61
+ from gradio.events import SelectData
62
+ from gradio.exceptions import Error
63
+ from gradio.external import load
64
+ from gradio.flagging import (
65
+ CSVLogger,
66
+ FlaggingCallback,
67
+ HuggingFaceDatasetJSONSaver,
68
+ HuggingFaceDatasetSaver,
69
+ SimpleCSVLogger,
70
+ )
71
+ from gradio.helpers import (
72
+ EventData,
73
+ Info,
74
+ Progress,
75
+ Warning,
76
+ make_waveform,
77
+ skip,
78
+ update,
79
+ )
80
+ from gradio.helpers import create_examples as Examples # noqa: N812
81
+ from gradio.interface import Interface, TabbedInterface, close_all
82
+ from gradio.ipython_ext import load_ipython_extension
83
+ from gradio.layouts import Accordion, Box, Column, Group, Row, Tab, TabItem, Tabs
84
+ from gradio.mix import Parallel, Series
85
+ from gradio.routes import Request, mount_gradio_app
86
+ from gradio.templates import (
87
+ Files,
88
+ ImageMask,
89
+ ImagePaint,
90
+ List,
91
+ Matrix,
92
+ Mic,
93
+ Microphone,
94
+ Numpy,
95
+ Paint,
96
+ Pil,
97
+ PlayableVideo,
98
+ Sketchpad,
99
+ TextArea,
100
+ Webcam,
101
+ )
102
+ from gradio.themes import Base as Theme
103
+
104
+ current_pkg_version = (
105
+ (pkgutil.get_data(__name__, "version.txt") or b"").decode("ascii").strip()
106
+ )
107
+ __version__ = current_pkg_version
gradio/analytics.py ADDED
@@ -0,0 +1,188 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """ Functions related to analytics and telemetry. """
2
+ from __future__ import annotations
3
+
4
+ import json
5
+ import os
6
+ import pkgutil
7
+ import threading
8
+ import warnings
9
+ from distutils.version import StrictVersion
10
+ from typing import Any
11
+
12
+ import requests
13
+
14
+ import gradio
15
+ from gradio.context import Context
16
+ from gradio.utils import GRADIO_VERSION
17
+
18
+ ANALYTICS_URL = "https://api.gradio.app/"
19
+ PKG_VERSION_URL = "https://api.gradio.app/pkg-version"
20
+
21
+
22
+ def analytics_enabled() -> bool:
23
+ """
24
+ Returns: True if analytics are enabled, False otherwise.
25
+ """
26
+ return os.getenv("GRADIO_ANALYTICS_ENABLED", "True") == "True"
27
+
28
+
29
+ def _do_analytics_request(url: str, data: dict[str, Any]) -> None:
30
+ data["ip_address"] = get_local_ip_address()
31
+ try:
32
+ requests.post(url, data=data, timeout=5)
33
+ except (requests.ConnectionError, requests.exceptions.ReadTimeout):
34
+ pass # do not push analytics if no network
35
+
36
+
37
+ def version_check():
38
+ try:
39
+ version_data = pkgutil.get_data(__name__, "version.txt")
40
+ if not version_data:
41
+ raise FileNotFoundError
42
+ current_pkg_version = version_data.decode("ascii").strip()
43
+ latest_pkg_version = requests.get(url=PKG_VERSION_URL, timeout=3).json()[
44
+ "version"
45
+ ]
46
+ if StrictVersion(latest_pkg_version) > StrictVersion(current_pkg_version):
47
+ print(
48
+ f"IMPORTANT: You are using gradio version {current_pkg_version}, "
49
+ f"however version {latest_pkg_version} is available, please upgrade."
50
+ )
51
+ print("--------")
52
+ except json.decoder.JSONDecodeError:
53
+ warnings.warn("unable to parse version details from package URL.")
54
+ except KeyError:
55
+ warnings.warn("package URL does not contain version info.")
56
+ except Exception:
57
+ pass
58
+
59
+
60
+ def get_local_ip_address() -> str:
61
+ """
62
+ Gets the public IP address or returns the string "No internet connection" if unable
63
+ to obtain it or the string "Analytics disabled" if a user has disabled analytics.
64
+ Does not make a new request if the IP address has already been obtained in the
65
+ same Python session.
66
+ """
67
+ if not analytics_enabled():
68
+ return "Analytics disabled"
69
+
70
+ if Context.ip_address is None:
71
+ try:
72
+ ip_address = requests.get(
73
+ "https://checkip.amazonaws.com/", timeout=3
74
+ ).text.strip()
75
+ except (requests.ConnectionError, requests.exceptions.ReadTimeout):
76
+ ip_address = "No internet connection"
77
+ Context.ip_address = ip_address
78
+ else:
79
+ ip_address = Context.ip_address
80
+ return ip_address
81
+
82
+
83
+ def initiated_analytics(data: dict[str, Any]) -> None:
84
+ if not analytics_enabled():
85
+ return
86
+
87
+ threading.Thread(
88
+ target=_do_analytics_request,
89
+ kwargs={
90
+ "url": f"{ANALYTICS_URL}gradio-initiated-analytics/",
91
+ "data": data,
92
+ },
93
+ ).start()
94
+
95
+
96
+ def launched_analytics(blocks: gradio.Blocks, data: dict[str, Any]) -> None:
97
+ if not analytics_enabled():
98
+ return
99
+
100
+ blocks_telemetry, inputs_telemetry, outputs_telemetry, targets_telemetry = (
101
+ [],
102
+ [],
103
+ [],
104
+ [],
105
+ )
106
+
107
+ from gradio.blocks import BlockContext
108
+
109
+ for x in list(blocks.blocks.values()):
110
+ blocks_telemetry.append(x.get_block_name()) if isinstance(
111
+ x, BlockContext
112
+ ) else blocks_telemetry.append(str(x))
113
+
114
+ for x in blocks.dependencies:
115
+ targets_telemetry = targets_telemetry + [
116
+ # Sometimes the target can be the Blocks object itself, so we need to check if its in blocks.blocks
117
+ str(blocks.blocks[y])
118
+ for y in x["targets"]
119
+ if y in blocks.blocks
120
+ ]
121
+ inputs_telemetry = inputs_telemetry + [
122
+ str(blocks.blocks[y]) for y in x["inputs"] if y in blocks.blocks
123
+ ]
124
+ outputs_telemetry = outputs_telemetry + [
125
+ str(blocks.blocks[y]) for y in x["outputs"] if y in blocks.blocks
126
+ ]
127
+ additional_data = {
128
+ "version": GRADIO_VERSION,
129
+ "is_kaggle": blocks.is_kaggle,
130
+ "is_sagemaker": blocks.is_sagemaker,
131
+ "using_auth": blocks.auth is not None,
132
+ "dev_mode": blocks.dev_mode,
133
+ "show_api": blocks.show_api,
134
+ "show_error": blocks.show_error,
135
+ "title": blocks.title,
136
+ "inputs": blocks.input_components
137
+ if blocks.mode == "interface"
138
+ else inputs_telemetry,
139
+ "outputs": blocks.output_components
140
+ if blocks.mode == "interface"
141
+ else outputs_telemetry,
142
+ "targets": targets_telemetry,
143
+ "blocks": blocks_telemetry,
144
+ "events": [str(x["trigger"]) for x in blocks.dependencies],
145
+ }
146
+
147
+ data.update(additional_data)
148
+
149
+ threading.Thread(
150
+ target=_do_analytics_request,
151
+ kwargs={
152
+ "url": f"{ANALYTICS_URL}gradio-launched-telemetry/",
153
+ "data": data,
154
+ },
155
+ ).start()
156
+
157
+
158
+ def integration_analytics(data: dict[str, Any]) -> None:
159
+ if not analytics_enabled():
160
+ return
161
+
162
+ threading.Thread(
163
+ target=_do_analytics_request,
164
+ kwargs={
165
+ "url": f"{ANALYTICS_URL}gradio-integration-analytics/",
166
+ "data": data,
167
+ },
168
+ ).start()
169
+
170
+
171
+ def error_analytics(message: str) -> None:
172
+ """
173
+ Send error analytics if there is network
174
+ Parameters:
175
+ message: Details about error
176
+ """
177
+ if not analytics_enabled():
178
+ return
179
+
180
+ data = {"error": message}
181
+
182
+ threading.Thread(
183
+ target=_do_analytics_request,
184
+ kwargs={
185
+ "url": f"{ANALYTICS_URL}gradio-error-analytics/",
186
+ "data": data,
187
+ },
188
+ ).start()
gradio/blocks.py ADDED
@@ -0,0 +1,2178 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from __future__ import annotations
2
+
3
+ import copy
4
+ import inspect
5
+ import json
6
+ import os
7
+ import random
8
+ import secrets
9
+ import sys
10
+ import threading
11
+ import time
12
+ import warnings
13
+ import webbrowser
14
+ from abc import abstractmethod
15
+ from pathlib import Path
16
+ from types import ModuleType
17
+ from typing import TYPE_CHECKING, Any, AsyncIterator, Callable, Literal, cast
18
+
19
+ import anyio
20
+ import requests
21
+ from anyio import CapacityLimiter
22
+ from gradio_client import serializing
23
+ from gradio_client import utils as client_utils
24
+ from gradio_client.documentation import document, set_documentation_group
25
+ from packaging import version
26
+
27
+ from gradio import (
28
+ analytics,
29
+ components,
30
+ external,
31
+ networking,
32
+ queueing,
33
+ routes,
34
+ strings,
35
+ themes,
36
+ utils,
37
+ wasm_utils,
38
+ )
39
+ from gradio.context import Context
40
+ from gradio.deprecation import check_deprecated_parameters, warn_deprecation
41
+ from gradio.exceptions import (
42
+ DuplicateBlockError,
43
+ InvalidApiNameError,
44
+ InvalidBlockError,
45
+ )
46
+ from gradio.helpers import EventData, create_tracker, skip, special_args
47
+ from gradio.themes import Default as DefaultTheme
48
+ from gradio.themes import ThemeClass as Theme
49
+ from gradio.tunneling import (
50
+ BINARY_FILENAME,
51
+ BINARY_FOLDER,
52
+ BINARY_PATH,
53
+ BINARY_URL,
54
+ CURRENT_TUNNELS,
55
+ )
56
+ from gradio.utils import (
57
+ GRADIO_VERSION,
58
+ TupleNoPrint,
59
+ check_function_inputs_match,
60
+ component_or_layout_class,
61
+ delete_none,
62
+ get_cancel_function,
63
+ get_continuous_fn,
64
+ )
65
+
66
+ try:
67
+ import spaces # type: ignore
68
+ except Exception:
69
+ spaces = None
70
+
71
+ set_documentation_group("blocks")
72
+
73
+ if TYPE_CHECKING: # Only import for type checking (is False at runtime).
74
+ from fastapi.applications import FastAPI
75
+
76
+ from gradio.components import Component
77
+
78
+ BUILT_IN_THEMES: dict[str, Theme] = {
79
+ t.name: t
80
+ for t in [
81
+ themes.Base(),
82
+ themes.Default(),
83
+ themes.Monochrome(),
84
+ themes.Soft(),
85
+ themes.Glass(),
86
+ ]
87
+ }
88
+
89
+
90
+ class Block:
91
+ def __init__(
92
+ self,
93
+ *,
94
+ render: bool = True,
95
+ elem_id: str | None = None,
96
+ elem_classes: list[str] | str | None = None,
97
+ visible: bool = True,
98
+ root_url: str | None = None, # URL that is prepended to all file paths
99
+ _skip_init_processing: bool = False, # Used for loading from Spaces
100
+ **kwargs,
101
+ ):
102
+ self._id = Context.id
103
+ Context.id += 1
104
+ self.visible = visible
105
+ self.elem_id = elem_id
106
+ self.elem_classes = (
107
+ [elem_classes] if isinstance(elem_classes, str) else elem_classes
108
+ )
109
+ self.root_url = root_url
110
+ self.share_token = secrets.token_urlsafe(32)
111
+ self._skip_init_processing = _skip_init_processing
112
+ self.parent: BlockContext | None = None
113
+ self.is_rendered: bool = False
114
+
115
+ if render:
116
+ self.render()
117
+ check_deprecated_parameters(self.__class__.__name__, kwargs=kwargs)
118
+
119
+ def render(self):
120
+ """
121
+ Adds self into appropriate BlockContext
122
+ """
123
+ if Context.root_block is not None and self._id in Context.root_block.blocks:
124
+ raise DuplicateBlockError(
125
+ f"A block with id: {self._id} has already been rendered in the current Blocks."
126
+ )
127
+ if Context.block is not None:
128
+ Context.block.add(self)
129
+ if Context.root_block is not None:
130
+ Context.root_block.blocks[self._id] = self
131
+ self.is_rendered = True
132
+ if isinstance(self, components.IOComponent):
133
+ Context.root_block.temp_file_sets.append(self.temp_files)
134
+ return self
135
+
136
+ def unrender(self):
137
+ """
138
+ Removes self from BlockContext if it has been rendered (otherwise does nothing).
139
+ Removes self from the layout and collection of blocks, but does not delete any event triggers.
140
+ """
141
+ if Context.block is not None:
142
+ try:
143
+ Context.block.children.remove(self)
144
+ except ValueError:
145
+ pass
146
+ if Context.root_block is not None:
147
+ try:
148
+ del Context.root_block.blocks[self._id]
149
+ self.is_rendered = False
150
+ except KeyError:
151
+ pass
152
+ return self
153
+
154
+ def get_block_name(self) -> str:
155
+ """
156
+ Gets block's class name.
157
+
158
+ If it is template component it gets the parent's class name.
159
+
160
+ @return: class name
161
+ """
162
+ return (
163
+ self.__class__.__base__.__name__.lower()
164
+ if hasattr(self, "is_template")
165
+ else self.__class__.__name__.lower()
166
+ )
167
+
168
+ def get_expected_parent(self) -> type[BlockContext] | None:
169
+ return None
170
+
171
+ def set_event_trigger(
172
+ self,
173
+ event_name: str,
174
+ fn: Callable | None,
175
+ inputs: Component | list[Component] | set[Component] | None,
176
+ outputs: Component | list[Component] | None,
177
+ preprocess: bool = True,
178
+ postprocess: bool = True,
179
+ scroll_to_output: bool = False,
180
+ show_progress: str = "full",
181
+ api_name: str | None | Literal[False] = None,
182
+ js: str | None = None,
183
+ no_target: bool = False,
184
+ queue: bool | None = None,
185
+ batch: bool = False,
186
+ max_batch_size: int = 4,
187
+ cancels: list[int] | None = None,
188
+ every: float | None = None,
189
+ collects_event_data: bool | None = None,
190
+ trigger_after: int | None = None,
191
+ trigger_only_on_success: bool = False,
192
+ ) -> tuple[dict[str, Any], int]:
193
+ """
194
+ Adds an event to the component's dependencies.
195
+ Parameters:
196
+ event_name: event name
197
+ fn: Callable function
198
+ inputs: input list
199
+ outputs: output list
200
+ preprocess: whether to run the preprocess methods of components
201
+ postprocess: whether to run the postprocess methods of components
202
+ scroll_to_output: whether to scroll to output of dependency on trigger
203
+ show_progress: whether to show progress animation while running.
204
+ api_name: defines how the endpoint appears in the API docs. Can be a string, None, or False. If False, the endpoint will not be exposed in the api docs. If set to None, the endpoint will be exposed in the api docs as an unnamed endpoint, although this behavior will be changed in Gradio 4.0. If set to a string, the endpoint will be exposed in the api docs with the given name.
205
+ js: Experimental parameter (API may change): Optional frontend js method to run before running 'fn'. Input arguments for js method are values of 'inputs' and 'outputs', return should be a list of values for output components
206
+ no_target: if True, sets "targets" to [], used for Blocks "load" event
207
+ queue: If True, will place the request on the queue, if the queue has been enabled. If False, will not put this event on the queue, even if the queue has been enabled. If None, will use the queue setting of the gradio app.
208
+ batch: whether this function takes in a batch of inputs
209
+ max_batch_size: the maximum batch size to send to the function
210
+ cancels: a list of other events to cancel when this event is triggered. For example, setting cancels=[click_event] will cancel the click_event, where click_event is the return value of another components .click method.
211
+ every: Run this event 'every' number of seconds while the client connection is open. Interpreted in seconds. Queue must be enabled.
212
+ collects_event_data: whether to collect event data for this event
213
+ trigger_after: if set, this event will be triggered after 'trigger_after' function index
214
+ trigger_only_on_success: if True, this event will only be triggered if the previous event was successful (only applies if `trigger_after` is set)
215
+ Returns: dependency information, dependency index
216
+ """
217
+ # Support for singular parameter
218
+ if isinstance(inputs, set):
219
+ inputs_as_dict = True
220
+ inputs = sorted(inputs, key=lambda x: x._id)
221
+ else:
222
+ inputs_as_dict = False
223
+ if inputs is None:
224
+ inputs = []
225
+ elif not isinstance(inputs, list):
226
+ inputs = [inputs]
227
+
228
+ if isinstance(outputs, set):
229
+ outputs = sorted(outputs, key=lambda x: x._id)
230
+ else:
231
+ if outputs is None:
232
+ outputs = []
233
+ elif not isinstance(outputs, list):
234
+ outputs = [outputs]
235
+
236
+ if fn is not None and not cancels:
237
+ check_function_inputs_match(fn, inputs, inputs_as_dict)
238
+
239
+ if Context.root_block is None:
240
+ raise AttributeError(
241
+ f"{event_name}() and other events can only be called within a Blocks context."
242
+ )
243
+ if every is not None and every <= 0:
244
+ raise ValueError("Parameter every must be positive or None")
245
+ if every and batch:
246
+ raise ValueError(
247
+ f"Cannot run {event_name} event in a batch and every {every} seconds. "
248
+ "Either batch is True or every is non-zero but not both."
249
+ )
250
+
251
+ if every and fn:
252
+ fn = get_continuous_fn(fn, every)
253
+ elif every:
254
+ raise ValueError("Cannot set a value for `every` without a `fn`.")
255
+
256
+ _, progress_index, event_data_index = (
257
+ special_args(fn) if fn else (None, None, None)
258
+ )
259
+ Context.root_block.fns.append(
260
+ BlockFunction(
261
+ fn,
262
+ inputs,
263
+ outputs,
264
+ preprocess,
265
+ postprocess,
266
+ inputs_as_dict,
267
+ progress_index is not None,
268
+ )
269
+ )
270
+ if api_name is not None and api_name is not False:
271
+ api_name_ = utils.append_unique_suffix(
272
+ api_name, [dep["api_name"] for dep in Context.root_block.dependencies]
273
+ )
274
+ if api_name != api_name_:
275
+ warnings.warn(f"api_name {api_name} already exists, using {api_name_}")
276
+ api_name = api_name_
277
+
278
+ if collects_event_data is None:
279
+ collects_event_data = event_data_index is not None
280
+
281
+ dependency = {
282
+ "targets": [self._id] if not no_target else [],
283
+ "trigger": event_name,
284
+ "inputs": [block._id for block in inputs],
285
+ "outputs": [block._id for block in outputs],
286
+ "backend_fn": fn is not None,
287
+ "js": js,
288
+ "queue": False if fn is None else queue,
289
+ "api_name": api_name,
290
+ "scroll_to_output": False if utils.get_space() else scroll_to_output,
291
+ "show_progress": show_progress,
292
+ "every": every,
293
+ "batch": batch,
294
+ "max_batch_size": max_batch_size,
295
+ "cancels": cancels or [],
296
+ "types": {
297
+ "continuous": bool(every),
298
+ "generator": inspect.isgeneratorfunction(fn) or bool(every),
299
+ },
300
+ "collects_event_data": collects_event_data,
301
+ "trigger_after": trigger_after,
302
+ "trigger_only_on_success": trigger_only_on_success,
303
+ }
304
+ Context.root_block.dependencies.append(dependency)
305
+ return dependency, len(Context.root_block.dependencies) - 1
306
+
307
+ def get_config(self):
308
+ return {
309
+ "visible": self.visible,
310
+ "elem_id": self.elem_id,
311
+ "elem_classes": self.elem_classes,
312
+ "root_url": self.root_url,
313
+ }
314
+
315
+ @staticmethod
316
+ @abstractmethod
317
+ def update(**kwargs) -> dict:
318
+ return {}
319
+
320
+ @classmethod
321
+ def get_specific_update(cls, generic_update: dict[str, Any]) -> dict:
322
+ generic_update = generic_update.copy()
323
+ del generic_update["__type__"]
324
+ specific_update = cls.update(**generic_update)
325
+ return specific_update
326
+
327
+
328
+ class BlockContext(Block):
329
+ def __init__(
330
+ self,
331
+ visible: bool = True,
332
+ render: bool = True,
333
+ **kwargs,
334
+ ):
335
+ """
336
+ Parameters:
337
+ visible: If False, this will be hidden but included in the Blocks config file (its visibility can later be updated).
338
+ render: If False, this will not be included in the Blocks config file at all.
339
+ """
340
+ self.children: list[Block] = []
341
+ Block.__init__(self, visible=visible, render=render, **kwargs)
342
+
343
+ def add_child(self, child: Block):
344
+ self.children.append(child)
345
+
346
+ def __enter__(self):
347
+ self.parent = Context.block
348
+ Context.block = self
349
+ return self
350
+
351
+ def add(self, child: Block):
352
+ child.parent = self
353
+ self.children.append(child)
354
+
355
+ def fill_expected_parents(self):
356
+ children = []
357
+ pseudo_parent = None
358
+ for child in self.children:
359
+ expected_parent = child.get_expected_parent()
360
+ if not expected_parent or isinstance(self, expected_parent):
361
+ pseudo_parent = None
362
+ children.append(child)
363
+ else:
364
+ if pseudo_parent is not None and isinstance(
365
+ pseudo_parent, expected_parent
366
+ ):
367
+ pseudo_parent.add_child(child)
368
+ else:
369
+ pseudo_parent = expected_parent(render=False)
370
+ pseudo_parent.parent = self
371
+ children.append(pseudo_parent)
372
+ pseudo_parent.add_child(child)
373
+ if Context.root_block:
374
+ Context.root_block.blocks[pseudo_parent._id] = pseudo_parent
375
+ child.parent = pseudo_parent
376
+ self.children = children
377
+
378
+ def __exit__(self, *args):
379
+ if getattr(self, "allow_expected_parents", True):
380
+ self.fill_expected_parents()
381
+ Context.block = self.parent
382
+
383
+ def postprocess(self, y):
384
+ """
385
+ Any postprocessing needed to be performed on a block context.
386
+ """
387
+ return y
388
+
389
+
390
+ class BlockFunction:
391
+ def __init__(
392
+ self,
393
+ fn: Callable | None,
394
+ inputs: list[Component],
395
+ outputs: list[Component],
396
+ preprocess: bool,
397
+ postprocess: bool,
398
+ inputs_as_dict: bool,
399
+ tracks_progress: bool = False,
400
+ ):
401
+ self.fn = fn
402
+ self.inputs = inputs
403
+ self.outputs = outputs
404
+ self.preprocess = preprocess
405
+ self.postprocess = postprocess
406
+ self.tracks_progress = tracks_progress
407
+ self.total_runtime = 0
408
+ self.total_runs = 0
409
+ self.inputs_as_dict = inputs_as_dict
410
+ self.name = getattr(fn, "__name__", "fn") if fn is not None else None
411
+ self.spaces_auto_wrap()
412
+
413
+ def spaces_auto_wrap(self):
414
+ if spaces is None:
415
+ return
416
+ if utils.get_space() is None:
417
+ return
418
+ self.fn = spaces.gradio_auto_wrap(self.fn)
419
+
420
+ def __str__(self):
421
+ return str(
422
+ {
423
+ "fn": self.name,
424
+ "preprocess": self.preprocess,
425
+ "postprocess": self.postprocess,
426
+ }
427
+ )
428
+
429
+ def __repr__(self):
430
+ return str(self)
431
+
432
+
433
+ class class_or_instancemethod(classmethod): # noqa: N801
434
+ def __get__(self, instance, type_):
435
+ descr_get = super().__get__ if instance is None else self.__func__.__get__
436
+ return descr_get(instance, type_)
437
+
438
+
439
+ def postprocess_update_dict(block: Block, update_dict: dict, postprocess: bool = True):
440
+ """
441
+ Converts a dictionary of updates into a format that can be sent to the frontend.
442
+ E.g. {"__type__": "generic_update", "value": "2", "interactive": False}
443
+ Into -> {"__type__": "update", "value": 2.0, "mode": "static"}
444
+
445
+ Parameters:
446
+ block: The Block that is being updated with this update dictionary.
447
+ update_dict: The original update dictionary
448
+ postprocess: Whether to postprocess the "value" key of the update dictionary.
449
+ """
450
+ if update_dict.get("__type__", "") == "generic_update":
451
+ update_dict = block.get_specific_update(update_dict)
452
+ if update_dict.get("value") is components._Keywords.NO_VALUE:
453
+ update_dict.pop("value")
454
+ interactive = update_dict.pop("interactive", None)
455
+ if interactive is not None:
456
+ update_dict["mode"] = "dynamic" if interactive else "static"
457
+ prediction_value = delete_none(update_dict, skip_value=True)
458
+ if "value" in prediction_value and postprocess:
459
+ assert isinstance(
460
+ block, components.IOComponent
461
+ ), f"Component {block.__class__} does not support value"
462
+ prediction_value["value"] = block.postprocess(prediction_value["value"])
463
+ return prediction_value
464
+
465
+
466
+ def convert_component_dict_to_list(
467
+ outputs_ids: list[int], predictions: dict
468
+ ) -> list | dict:
469
+ """
470
+ Converts a dictionary of component updates into a list of updates in the order of
471
+ the outputs_ids and including every output component. Leaves other types of dictionaries unchanged.
472
+ E.g. {"textbox": "hello", "number": {"__type__": "generic_update", "value": "2"}}
473
+ Into -> ["hello", {"__type__": "generic_update"}, {"__type__": "generic_update", "value": "2"}]
474
+ """
475
+ keys_are_blocks = [isinstance(key, Block) for key in predictions]
476
+ if all(keys_are_blocks):
477
+ reordered_predictions = [skip() for _ in outputs_ids]
478
+ for component, value in predictions.items():
479
+ if component._id not in outputs_ids:
480
+ raise ValueError(
481
+ f"Returned component {component} not specified as output of function."
482
+ )
483
+ output_index = outputs_ids.index(component._id)
484
+ reordered_predictions[output_index] = value
485
+ predictions = utils.resolve_singleton(reordered_predictions)
486
+ elif any(keys_are_blocks):
487
+ raise ValueError(
488
+ "Returned dictionary included some keys as Components. Either all keys must be Components to assign Component values, or return a List of values to assign output values in order."
489
+ )
490
+ return predictions
491
+
492
+
493
+ def get_api_info(config: dict, serialize: bool = True):
494
+ """
495
+ Gets the information needed to generate the API docs from a Blocks config.
496
+ Parameters:
497
+ config: a Blocks config dictionary
498
+ serialize: If True, returns the serialized version of the typed information. If False, returns the raw version.
499
+ """
500
+ api_info = {"named_endpoints": {}, "unnamed_endpoints": {}}
501
+ mode = config.get("mode", None)
502
+ after_new_format = version.parse(config.get("version", "2.0")) > version.Version(
503
+ "3.28.3"
504
+ )
505
+
506
+ for d, dependency in enumerate(config["dependencies"]):
507
+ dependency_info = {"parameters": [], "returns": []}
508
+ skip_endpoint = False
509
+
510
+ inputs = dependency["inputs"]
511
+ for i in inputs:
512
+ for component in config["components"]:
513
+ if component["id"] == i:
514
+ break
515
+ else:
516
+ skip_endpoint = True # if component not found, skip endpoint
517
+ break
518
+ type = component["type"]
519
+ if type in client_utils.SKIP_COMPONENTS:
520
+ continue
521
+ if (
522
+ not component.get("serializer")
523
+ and type not in serializing.COMPONENT_MAPPING
524
+ ):
525
+ skip_endpoint = True # if component not serializable, skip endpoint
526
+ break
527
+ if type in client_utils.SKIP_COMPONENTS:
528
+ continue
529
+ label = component["props"].get("label", f"parameter_{i}")
530
+ # The config has the most specific API info (taking into account the parameters
531
+ # of the component), so we use that if it exists. Otherwise, we fallback to the
532
+ # Serializer's API info.
533
+ serializer = serializing.COMPONENT_MAPPING[type]()
534
+ if component.get("api_info") and after_new_format:
535
+ info = component["api_info"]
536
+ example = component["example_inputs"]["serialized"]
537
+ else:
538
+ assert isinstance(serializer, serializing.Serializable)
539
+ info = serializer.api_info()
540
+ example = serializer.example_inputs()["raw"]
541
+ python_info = info["info"]
542
+ if serialize and info["serialized_info"]:
543
+ python_info = serializer.serialized_info()
544
+ if (
545
+ isinstance(serializer, serializing.FileSerializable)
546
+ and component["props"].get("file_count", "single") != "single"
547
+ ):
548
+ python_info = serializer._multiple_file_serialized_info()
549
+
550
+ python_type = client_utils.json_schema_to_python_type(python_info)
551
+ serializer_name = serializing.COMPONENT_MAPPING[type].__name__
552
+ dependency_info["parameters"].append(
553
+ {
554
+ "label": label,
555
+ "type": info["info"],
556
+ "python_type": {
557
+ "type": python_type,
558
+ "description": python_info.get("description", ""),
559
+ },
560
+ "component": type.capitalize(),
561
+ "example_input": example,
562
+ "serializer": serializer_name,
563
+ }
564
+ )
565
+
566
+ outputs = dependency["outputs"]
567
+ for o in outputs:
568
+ for component in config["components"]:
569
+ if component["id"] == o:
570
+ break
571
+ else:
572
+ skip_endpoint = True # if component not found, skip endpoint
573
+ break
574
+ type = component["type"]
575
+ if type in client_utils.SKIP_COMPONENTS:
576
+ continue
577
+ if (
578
+ not component.get("serializer")
579
+ and type not in serializing.COMPONENT_MAPPING
580
+ ):
581
+ skip_endpoint = True # if component not serializable, skip endpoint
582
+ break
583
+ label = component["props"].get("label", f"value_{o}")
584
+ serializer = serializing.COMPONENT_MAPPING[type]()
585
+ if component.get("api_info") and after_new_format:
586
+ info = component["api_info"]
587
+ example = component["example_inputs"]["serialized"]
588
+ else:
589
+ assert isinstance(serializer, serializing.Serializable)
590
+ info = serializer.api_info()
591
+ example = serializer.example_inputs()["raw"]
592
+ python_info = info["info"]
593
+ if serialize and info["serialized_info"]:
594
+ python_info = serializer.serialized_info()
595
+ if (
596
+ isinstance(serializer, serializing.FileSerializable)
597
+ and component["props"].get("file_count", "single") != "single"
598
+ ):
599
+ python_info = serializer._multiple_file_serialized_info()
600
+ python_type = client_utils.json_schema_to_python_type(python_info)
601
+ serializer_name = serializing.COMPONENT_MAPPING[type].__name__
602
+ dependency_info["returns"].append(
603
+ {
604
+ "label": label,
605
+ "type": info["info"],
606
+ "python_type": {
607
+ "type": python_type,
608
+ "description": python_info.get("description", ""),
609
+ },
610
+ "component": type.capitalize(),
611
+ "serializer": serializer_name,
612
+ }
613
+ )
614
+
615
+ if not dependency["backend_fn"]:
616
+ skip_endpoint = True
617
+
618
+ if skip_endpoint:
619
+ continue
620
+ if dependency["api_name"] is not None and dependency["api_name"] is not False:
621
+ api_info["named_endpoints"][f"/{dependency['api_name']}"] = dependency_info
622
+ elif (
623
+ dependency["api_name"] is False
624
+ or mode == "interface"
625
+ or mode == "tabbed_interface"
626
+ ):
627
+ pass # Skip unnamed endpoints in interface mode
628
+ else:
629
+ api_info["unnamed_endpoints"][str(d)] = dependency_info
630
+
631
+ return api_info
632
+
633
+
634
+ @document("launch", "queue", "integrate", "load")
635
+ class Blocks(BlockContext):
636
+ """
637
+ Blocks is Gradio's low-level API that allows you to create more custom web
638
+ applications and demos than Interfaces (yet still entirely in Python).
639
+
640
+
641
+ Compared to the Interface class, Blocks offers more flexibility and control over:
642
+ (1) the layout of components (2) the events that
643
+ trigger the execution of functions (3) data flows (e.g. inputs can trigger outputs,
644
+ which can trigger the next level of outputs). Blocks also offers ways to group
645
+ together related demos such as with tabs.
646
+
647
+
648
+ The basic usage of Blocks is as follows: create a Blocks object, then use it as a
649
+ context (with the "with" statement), and then define layouts, components, or events
650
+ within the Blocks context. Finally, call the launch() method to launch the demo.
651
+
652
+ Example:
653
+ import gradio as gr
654
+ def update(name):
655
+ return f"Welcome to Gradio, {name}!"
656
+
657
+ with gr.Blocks() as demo:
658
+ gr.Markdown("Start typing below and then click **Run** to see the output.")
659
+ with gr.Row():
660
+ inp = gr.Textbox(placeholder="What is your name?")
661
+ out = gr.Textbox()
662
+ btn = gr.Button("Run")
663
+ btn.click(fn=update, inputs=inp, outputs=out)
664
+
665
+ demo.launch()
666
+ Demos: blocks_hello, blocks_flipper, blocks_speech_text_sentiment, generate_english_german, sound_alert
667
+ Guides: blocks-and-event-listeners, controlling-layout, state-in-blocks, custom-CSS-and-JS, custom-interpretations-with-blocks, using-blocks-like-functions
668
+ """
669
+
670
+ def __init__(
671
+ self,
672
+ theme: Theme | str | None = None,
673
+ analytics_enabled: bool | None = None,
674
+ mode: str = "blocks",
675
+ title: str = "Gradio",
676
+ css: str | None = None,
677
+ **kwargs,
678
+ ):
679
+ """
680
+ Parameters:
681
+ theme: a Theme object or a string representing a theme. If a string, will look for a built-in theme with that name (e.g. "soft" or "default"), or will attempt to load a theme from the HF Hub (e.g. "gradio/monochrome"). If None, will use the Default theme.
682
+ analytics_enabled: whether to allow basic telemetry. If None, will use GRADIO_ANALYTICS_ENABLED environment variable or default to True.
683
+ mode: a human-friendly name for the kind of Blocks or Interface being created.
684
+ title: The tab title to display when this is opened in a browser window.
685
+ css: custom css or path to custom css file to apply to entire Blocks
686
+ """
687
+ self.limiter = None
688
+ if theme is None:
689
+ theme = DefaultTheme()
690
+ elif isinstance(theme, str):
691
+ if theme.lower() in BUILT_IN_THEMES:
692
+ theme = BUILT_IN_THEMES[theme.lower()]
693
+ else:
694
+ try:
695
+ theme = Theme.from_hub(theme)
696
+ except Exception as e:
697
+ warnings.warn(f"Cannot load {theme}. Caught Exception: {str(e)}")
698
+ theme = DefaultTheme()
699
+ if not isinstance(theme, Theme):
700
+ warnings.warn("Theme should be a class loaded from gradio.themes")
701
+ theme = DefaultTheme()
702
+ self.theme: Theme = theme
703
+ self.theme_css = theme._get_theme_css()
704
+ self.stylesheets = theme._stylesheets
705
+ self.encrypt = False
706
+ self.share = False
707
+ self.enable_queue = None
708
+ self.max_threads = 40
709
+ self.show_error = True
710
+ if css is not None and os.path.exists(css):
711
+ with open(css) as css_file:
712
+ self.css = css_file.read()
713
+ else:
714
+ self.css = css
715
+
716
+ # For analytics_enabled and allow_flagging: (1) first check for
717
+ # parameter, (2) check for env variable, (3) default to True/"manual"
718
+ self.analytics_enabled = (
719
+ analytics_enabled
720
+ if analytics_enabled is not None
721
+ else analytics.analytics_enabled()
722
+ )
723
+ if self.analytics_enabled:
724
+ t = threading.Thread(target=analytics.version_check)
725
+ t.start()
726
+ else:
727
+ os.environ["HF_HUB_DISABLE_TELEMETRY"] = "True"
728
+ super().__init__(render=False, **kwargs)
729
+ self.blocks: dict[int, Block] = {}
730
+ self.fns: list[BlockFunction] = []
731
+ self.dependencies = []
732
+ self.mode = mode
733
+
734
+ self.is_running = False
735
+ self.local_url = None
736
+ self.share_url = None
737
+ self.width = None
738
+ self.height = None
739
+ self.api_open = True
740
+
741
+ self.space_id = utils.get_space()
742
+ self.favicon_path = None
743
+ self.auth = None
744
+ self.dev_mode = True
745
+ self.app_id = random.getrandbits(64)
746
+ self.temp_file_sets = []
747
+ self.title = title
748
+ self.show_api = True
749
+
750
+ # Only used when an Interface is loaded from a config
751
+ self.predict = None
752
+ self.input_components = None
753
+ self.output_components = None
754
+ self.__name__ = None
755
+ self.api_mode = None
756
+ self.progress_tracking = None
757
+ self.ssl_verify = True
758
+
759
+ self.allowed_paths = []
760
+ self.blocked_paths = []
761
+ self.root_path = ""
762
+ self.root_urls = set()
763
+
764
+ if not wasm_utils.IS_WASM and self.analytics_enabled:
765
+ is_custom_theme = not any(
766
+ self.theme.to_dict() == built_in_theme.to_dict()
767
+ for built_in_theme in BUILT_IN_THEMES.values()
768
+ )
769
+ data = {
770
+ "mode": self.mode,
771
+ "custom_css": self.css is not None,
772
+ "theme": self.theme.name,
773
+ "is_custom_theme": is_custom_theme,
774
+ "version": GRADIO_VERSION,
775
+ }
776
+ analytics.initiated_analytics(data)
777
+
778
+ @classmethod
779
+ def from_config(
780
+ cls,
781
+ config: dict,
782
+ fns: list[Callable],
783
+ root_url: str,
784
+ ) -> Blocks:
785
+ """
786
+ Factory method that creates a Blocks from a config and list of functions. Used
787
+ internally by the gradio.external.load() method.
788
+
789
+ Parameters:
790
+ config: a dictionary containing the configuration of the Blocks.
791
+ fns: a list of functions that are used in the Blocks. Must be in the same order as the dependencies in the config.
792
+ root_url: an external url to use as a root URL when serving files for components in the Blocks.
793
+ """
794
+ config = copy.deepcopy(config)
795
+ components_config = config["components"]
796
+ for component_config in components_config:
797
+ # for backwards compatibility, extract style into props
798
+ if "style" in component_config["props"]:
799
+ component_config["props"].update(component_config["props"]["style"])
800
+ del component_config["props"]["style"]
801
+ theme = config.get("theme", "default")
802
+ original_mapping: dict[int, Block] = {}
803
+ root_urls = {root_url}
804
+
805
+ def get_block_instance(id: int) -> Block:
806
+ for block_config in components_config:
807
+ if block_config["id"] == id:
808
+ break
809
+ else:
810
+ raise ValueError(f"Cannot find block with id {id}")
811
+ cls = component_or_layout_class(block_config["type"])
812
+ block_config["props"].pop("type", None)
813
+ block_config["props"].pop("name", None)
814
+ # If a Gradio app B is loaded into a Gradio app A, and B itself loads a
815
+ # Gradio app C, then the root_urls of the components in A need to be the
816
+ # URL of C, not B. The else clause below handles this case.
817
+ if block_config["props"].get("root_url") is None:
818
+ block_config["props"]["root_url"] = f"{root_url}/"
819
+ else:
820
+ root_urls.add(block_config["props"]["root_url"])
821
+ # Any component has already processed its initial value, so we skip that step here
822
+ block = cls(**block_config["props"], _skip_init_processing=True)
823
+ return block
824
+
825
+ def iterate_over_children(children_list):
826
+ for child_config in children_list:
827
+ id = child_config["id"]
828
+ block = get_block_instance(id)
829
+
830
+ original_mapping[id] = block
831
+
832
+ children = child_config.get("children")
833
+ if children is not None:
834
+ assert isinstance(
835
+ block, BlockContext
836
+ ), f"Invalid config, Block with id {id} has children but is not a BlockContext."
837
+ with block:
838
+ iterate_over_children(children)
839
+
840
+ derived_fields = ["types"]
841
+
842
+ with Blocks(theme=theme) as blocks:
843
+ # ID 0 should be the root Blocks component
844
+ original_mapping[0] = Context.root_block or blocks
845
+
846
+ iterate_over_children(config["layout"]["children"])
847
+
848
+ first_dependency = None
849
+
850
+ # add the event triggers
851
+ for dependency, fn in zip(config["dependencies"], fns):
852
+ # We used to add a "fake_event" to the config to cache examples
853
+ # without removing it. This was causing bugs in calling gr.load
854
+ # We fixed the issue by removing "fake_event" from the config in examples.py
855
+ # but we still need to skip these events when loading the config to support
856
+ # older demos
857
+ if dependency["trigger"] == "fake_event":
858
+ continue
859
+ for field in derived_fields:
860
+ dependency.pop(field, None)
861
+ targets = dependency.pop("targets")
862
+ trigger = dependency.pop("trigger")
863
+ dependency.pop("backend_fn")
864
+ dependency.pop("documentation", None)
865
+ dependency["inputs"] = [
866
+ original_mapping[i] for i in dependency["inputs"]
867
+ ]
868
+ dependency["outputs"] = [
869
+ original_mapping[o] for o in dependency["outputs"]
870
+ ]
871
+ dependency.pop("status_tracker", None)
872
+ dependency["preprocess"] = False
873
+ dependency["postprocess"] = False
874
+
875
+ for target in targets:
876
+ dependency = original_mapping[target].set_event_trigger(
877
+ event_name=trigger, fn=fn, **dependency
878
+ )[0]
879
+ if first_dependency is None:
880
+ first_dependency = dependency
881
+
882
+ # Allows some use of Interface-specific methods with loaded Spaces
883
+ if first_dependency and Context.root_block:
884
+ blocks.predict = [fns[0]]
885
+ blocks.input_components = [
886
+ Context.root_block.blocks[i] for i in first_dependency["inputs"]
887
+ ]
888
+ blocks.output_components = [
889
+ Context.root_block.blocks[o] for o in first_dependency["outputs"]
890
+ ]
891
+ blocks.__name__ = "Interface"
892
+ blocks.api_mode = True
893
+
894
+ blocks.root_urls = root_urls
895
+ return blocks
896
+
897
+ def __str__(self):
898
+ return self.__repr__()
899
+
900
+ def __repr__(self):
901
+ num_backend_fns = len([d for d in self.dependencies if d["backend_fn"]])
902
+ repr = f"Gradio Blocks instance: {num_backend_fns} backend functions"
903
+ repr += f"\n{'-' * len(repr)}"
904
+ for d, dependency in enumerate(self.dependencies):
905
+ if dependency["backend_fn"]:
906
+ repr += f"\nfn_index={d}"
907
+ repr += "\n inputs:"
908
+ for input_id in dependency["inputs"]:
909
+ block = self.blocks[input_id]
910
+ repr += f"\n |-{block}"
911
+ repr += "\n outputs:"
912
+ for output_id in dependency["outputs"]:
913
+ block = self.blocks[output_id]
914
+ repr += f"\n |-{block}"
915
+ return repr
916
+
917
+ def render(self):
918
+ if Context.root_block is not None:
919
+ if self._id in Context.root_block.blocks:
920
+ raise DuplicateBlockError(
921
+ f"A block with id: {self._id} has already been rendered in the current Blocks."
922
+ )
923
+ overlapping_ids = set(Context.root_block.blocks).intersection(self.blocks)
924
+ for id in overlapping_ids:
925
+ # State components are allowed to be reused between Blocks
926
+ if not isinstance(self.blocks[id], components.State):
927
+ raise DuplicateBlockError(
928
+ "At least one block in this Blocks has already been rendered."
929
+ )
930
+
931
+ Context.root_block.blocks.update(self.blocks)
932
+ Context.root_block.fns.extend(self.fns)
933
+ dependency_offset = len(Context.root_block.dependencies)
934
+ for i, dependency in enumerate(self.dependencies):
935
+ api_name = dependency["api_name"]
936
+ if api_name is not None and api_name is not False:
937
+ api_name_ = utils.append_unique_suffix(
938
+ api_name,
939
+ [dep["api_name"] for dep in Context.root_block.dependencies],
940
+ )
941
+ if api_name != api_name_:
942
+ warnings.warn(
943
+ f"api_name {api_name} already exists, using {api_name_}"
944
+ )
945
+ dependency["api_name"] = api_name_
946
+ dependency["cancels"] = [
947
+ c + dependency_offset for c in dependency["cancels"]
948
+ ]
949
+ if dependency.get("trigger_after") is not None:
950
+ dependency["trigger_after"] += dependency_offset
951
+ # Recreate the cancel function so that it has the latest
952
+ # dependency fn indices. This is necessary to properly cancel
953
+ # events in the backend
954
+ if dependency["cancels"]:
955
+ updated_cancels = [
956
+ Context.root_block.dependencies[i]
957
+ for i in dependency["cancels"]
958
+ ]
959
+ new_fn = BlockFunction(
960
+ get_cancel_function(updated_cancels)[0],
961
+ [],
962
+ [],
963
+ False,
964
+ True,
965
+ False,
966
+ )
967
+ Context.root_block.fns[dependency_offset + i] = new_fn
968
+ Context.root_block.dependencies.append(dependency)
969
+ Context.root_block.temp_file_sets.extend(self.temp_file_sets)
970
+ Context.root_block.root_urls.update(self.root_urls)
971
+
972
+ if Context.block is not None:
973
+ Context.block.children.extend(self.children)
974
+ return self
975
+
976
+ def is_callable(self, fn_index: int = 0) -> bool:
977
+ """Checks if a particular Blocks function is callable (i.e. not stateful or a generator)."""
978
+ block_fn = self.fns[fn_index]
979
+ dependency = self.dependencies[fn_index]
980
+
981
+ if inspect.isasyncgenfunction(block_fn.fn):
982
+ return False
983
+ if inspect.isgeneratorfunction(block_fn.fn):
984
+ return False
985
+ for input_id in dependency["inputs"]:
986
+ block = self.blocks[input_id]
987
+ if getattr(block, "stateful", False):
988
+ return False
989
+ for output_id in dependency["outputs"]:
990
+ block = self.blocks[output_id]
991
+ if getattr(block, "stateful", False):
992
+ return False
993
+
994
+ return True
995
+
996
+ def __call__(self, *inputs, fn_index: int = 0, api_name: str | None = None):
997
+ """
998
+ Allows Blocks objects to be called as functions. Supply the parameters to the
999
+ function as positional arguments. To choose which function to call, use the
1000
+ fn_index parameter, which must be a keyword argument.
1001
+
1002
+ Parameters:
1003
+ *inputs: the parameters to pass to the function
1004
+ fn_index: the index of the function to call (defaults to 0, which for Interfaces, is the default prediction function)
1005
+ api_name: The api_name of the dependency to call. Will take precedence over fn_index.
1006
+ """
1007
+ if api_name is not None:
1008
+ inferred_fn_index = next(
1009
+ (
1010
+ i
1011
+ for i, d in enumerate(self.dependencies)
1012
+ if d.get("api_name") == api_name
1013
+ ),
1014
+ None,
1015
+ )
1016
+ if inferred_fn_index is None:
1017
+ raise InvalidApiNameError(
1018
+ f"Cannot find a function with api_name {api_name}"
1019
+ )
1020
+ fn_index = inferred_fn_index
1021
+ if not (self.is_callable(fn_index)):
1022
+ raise ValueError(
1023
+ "This function is not callable because it is either stateful or is a generator. Please use the .launch() method instead to create an interactive user interface."
1024
+ )
1025
+
1026
+ inputs = list(inputs)
1027
+ processed_inputs = self.serialize_data(fn_index, inputs)
1028
+ batch = self.dependencies[fn_index]["batch"]
1029
+ if batch:
1030
+ processed_inputs = [[inp] for inp in processed_inputs]
1031
+
1032
+ outputs = client_utils.synchronize_async(
1033
+ self.process_api,
1034
+ fn_index=fn_index,
1035
+ inputs=processed_inputs,
1036
+ request=None,
1037
+ state={},
1038
+ )
1039
+ outputs = outputs["data"]
1040
+
1041
+ if batch:
1042
+ outputs = [out[0] for out in outputs]
1043
+
1044
+ processed_outputs = self.deserialize_data(fn_index, outputs)
1045
+ processed_outputs = utils.resolve_singleton(processed_outputs)
1046
+
1047
+ return processed_outputs
1048
+
1049
+ async def call_function(
1050
+ self,
1051
+ fn_index: int,
1052
+ processed_input: list[Any],
1053
+ iterator: AsyncIterator[Any] | None = None,
1054
+ requests: routes.Request | list[routes.Request] | None = None,
1055
+ event_id: str | None = None,
1056
+ event_data: EventData | None = None,
1057
+ ):
1058
+ """
1059
+ Calls function with given index and preprocessed input, and measures process time.
1060
+ Parameters:
1061
+ fn_index: index of function to call
1062
+ processed_input: preprocessed input to pass to function
1063
+ iterator: iterator to use if function is a generator
1064
+ requests: requests to pass to function
1065
+ event_id: id of event in queue
1066
+ event_data: data associated with event trigger
1067
+ """
1068
+ block_fn = self.fns[fn_index]
1069
+ assert block_fn.fn, f"function with index {fn_index} not defined."
1070
+ is_generating = False
1071
+
1072
+ if block_fn.inputs_as_dict:
1073
+ processed_input = [dict(zip(block_fn.inputs, processed_input))]
1074
+
1075
+ request = requests[0] if isinstance(requests, list) else requests
1076
+ processed_input, progress_index, _ = special_args(
1077
+ block_fn.fn, processed_input, request, event_data
1078
+ )
1079
+ progress_tracker = (
1080
+ processed_input[progress_index] if progress_index is not None else None
1081
+ )
1082
+
1083
+ start = time.time()
1084
+
1085
+ fn = utils.get_function_with_locals(block_fn.fn, self, event_id)
1086
+
1087
+ if iterator is None: # If not a generator function that has already run
1088
+ if progress_tracker is not None and progress_index is not None:
1089
+ progress_tracker, fn = create_tracker(
1090
+ self, event_id, fn, progress_tracker.track_tqdm
1091
+ )
1092
+ processed_input[progress_index] = progress_tracker
1093
+
1094
+ if inspect.iscoroutinefunction(fn):
1095
+ prediction = await fn(*processed_input)
1096
+ else:
1097
+ prediction = await anyio.to_thread.run_sync(
1098
+ fn, *processed_input, limiter=self.limiter
1099
+ )
1100
+ else:
1101
+ prediction = None
1102
+
1103
+ if inspect.isgeneratorfunction(fn) or inspect.isasyncgenfunction(fn):
1104
+ if not self.enable_queue:
1105
+ raise ValueError("Need to enable queue to use generators.")
1106
+ try:
1107
+ if iterator is None:
1108
+ iterator = cast(AsyncIterator[Any], prediction)
1109
+ if inspect.isgenerator(iterator):
1110
+ iterator = utils.SyncToAsyncIterator(iterator, self.limiter)
1111
+ prediction = await utils.async_iteration(iterator)
1112
+ is_generating = True
1113
+ except StopAsyncIteration:
1114
+ n_outputs = len(self.dependencies[fn_index].get("outputs"))
1115
+ prediction = (
1116
+ components._Keywords.FINISHED_ITERATING
1117
+ if n_outputs == 1
1118
+ else (components._Keywords.FINISHED_ITERATING,) * n_outputs
1119
+ )
1120
+ iterator = None
1121
+
1122
+ duration = time.time() - start
1123
+
1124
+ return {
1125
+ "prediction": prediction,
1126
+ "duration": duration,
1127
+ "is_generating": is_generating,
1128
+ "iterator": iterator,
1129
+ }
1130
+
1131
+ def serialize_data(self, fn_index: int, inputs: list[Any]) -> list[Any]:
1132
+ dependency = self.dependencies[fn_index]
1133
+ processed_input = []
1134
+
1135
+ for i, input_id in enumerate(dependency["inputs"]):
1136
+ try:
1137
+ block = self.blocks[input_id]
1138
+ except KeyError as e:
1139
+ raise InvalidBlockError(
1140
+ f"Input component with id {input_id} used in {dependency['trigger']}() event is not defined in this gr.Blocks context. You are allowed to nest gr.Blocks contexts, but there must be a gr.Blocks context that contains all components and events."
1141
+ ) from e
1142
+ assert isinstance(
1143
+ block, components.IOComponent
1144
+ ), f"{block.__class__} Component with id {input_id} not a valid input component."
1145
+ serialized_input = block.serialize(inputs[i])
1146
+ processed_input.append(serialized_input)
1147
+
1148
+ return processed_input
1149
+
1150
+ def deserialize_data(self, fn_index: int, outputs: list[Any]) -> list[Any]:
1151
+ dependency = self.dependencies[fn_index]
1152
+ predictions = []
1153
+
1154
+ for o, output_id in enumerate(dependency["outputs"]):
1155
+ try:
1156
+ block = self.blocks[output_id]
1157
+ except KeyError as e:
1158
+ raise InvalidBlockError(
1159
+ f"Output component with id {output_id} used in {dependency['trigger']}() event not found in this gr.Blocks context. You are allowed to nest gr.Blocks contexts, but there must be a gr.Blocks context that contains all components and events."
1160
+ ) from e
1161
+ assert isinstance(
1162
+ block, components.IOComponent
1163
+ ), f"{block.__class__} Component with id {output_id} not a valid output component."
1164
+ deserialized = block.deserialize(
1165
+ outputs[o],
1166
+ save_dir=block.DEFAULT_TEMP_DIR,
1167
+ root_url=block.root_url,
1168
+ hf_token=Context.hf_token,
1169
+ )
1170
+ predictions.append(deserialized)
1171
+
1172
+ return predictions
1173
+
1174
+ def validate_inputs(self, fn_index: int, inputs: list[Any]):
1175
+ block_fn = self.fns[fn_index]
1176
+ dependency = self.dependencies[fn_index]
1177
+
1178
+ dep_inputs = dependency["inputs"]
1179
+
1180
+ # This handles incorrect inputs when args are changed by a JS function
1181
+ # Only check not enough args case, ignore extra arguments (for now)
1182
+ # TODO: make this stricter?
1183
+ if len(inputs) < len(dep_inputs):
1184
+ name = (
1185
+ f" ({block_fn.name})"
1186
+ if block_fn.name and block_fn.name != "<lambda>"
1187
+ else ""
1188
+ )
1189
+
1190
+ wanted_args = []
1191
+ received_args = []
1192
+ for input_id in dep_inputs:
1193
+ block = self.blocks[input_id]
1194
+ wanted_args.append(str(block))
1195
+ for inp in inputs:
1196
+ v = f'"{inp}"' if isinstance(inp, str) else str(inp)
1197
+ received_args.append(v)
1198
+
1199
+ wanted = ", ".join(wanted_args)
1200
+ received = ", ".join(received_args)
1201
+
1202
+ # JS func didn't pass enough arguments
1203
+ raise ValueError(
1204
+ f"""An event handler{name} didn't receive enough input values (needed: {len(dep_inputs)}, got: {len(inputs)}).
1205
+ Check if the event handler calls a Javascript function, and make sure its return value is correct.
1206
+ Wanted inputs:
1207
+ [{wanted}]
1208
+ Received inputs:
1209
+ [{received}]"""
1210
+ )
1211
+
1212
+ def preprocess_data(self, fn_index: int, inputs: list[Any], state: dict[int, Any]):
1213
+ block_fn = self.fns[fn_index]
1214
+ dependency = self.dependencies[fn_index]
1215
+
1216
+ self.validate_inputs(fn_index, inputs)
1217
+
1218
+ if block_fn.preprocess:
1219
+ processed_input = []
1220
+ for i, input_id in enumerate(dependency["inputs"]):
1221
+ try:
1222
+ block = self.blocks[input_id]
1223
+ except KeyError as e:
1224
+ raise InvalidBlockError(
1225
+ f"Input component with id {input_id} used in {dependency['trigger']}() event not found in this gr.Blocks context. You are allowed to nest gr.Blocks contexts, but there must be a gr.Blocks context that contains all components and events."
1226
+ ) from e
1227
+ assert isinstance(
1228
+ block, components.Component
1229
+ ), f"{block.__class__} Component with id {input_id} not a valid input component."
1230
+ if getattr(block, "stateful", False):
1231
+ processed_input.append(state.get(input_id))
1232
+ else:
1233
+ processed_input.append(block.preprocess(inputs[i]))
1234
+ else:
1235
+ processed_input = inputs
1236
+ return processed_input
1237
+
1238
+ def validate_outputs(self, fn_index: int, predictions: Any | list[Any]):
1239
+ block_fn = self.fns[fn_index]
1240
+ dependency = self.dependencies[fn_index]
1241
+
1242
+ dep_outputs = dependency["outputs"]
1243
+
1244
+ if type(predictions) is not list and type(predictions) is not tuple:
1245
+ predictions = [predictions]
1246
+
1247
+ if len(predictions) < len(dep_outputs):
1248
+ name = (
1249
+ f" ({block_fn.name})"
1250
+ if block_fn.name and block_fn.name != "<lambda>"
1251
+ else ""
1252
+ )
1253
+
1254
+ wanted_args = []
1255
+ received_args = []
1256
+ for output_id in dep_outputs:
1257
+ block = self.blocks[output_id]
1258
+ wanted_args.append(str(block))
1259
+ for pred in predictions:
1260
+ v = f'"{pred}"' if isinstance(pred, str) else str(pred)
1261
+ received_args.append(v)
1262
+
1263
+ wanted = ", ".join(wanted_args)
1264
+ received = ", ".join(received_args)
1265
+
1266
+ raise ValueError(
1267
+ f"""An event handler{name} didn't receive enough output values (needed: {len(dep_outputs)}, received: {len(predictions)}).
1268
+ Wanted outputs:
1269
+ [{wanted}]
1270
+ Received outputs:
1271
+ [{received}]"""
1272
+ )
1273
+
1274
+ def postprocess_data(
1275
+ self, fn_index: int, predictions: list | dict, state: dict[int, Any]
1276
+ ):
1277
+ block_fn = self.fns[fn_index]
1278
+ dependency = self.dependencies[fn_index]
1279
+ batch = dependency["batch"]
1280
+
1281
+ if type(predictions) is dict and len(predictions) > 0:
1282
+ predictions = convert_component_dict_to_list(
1283
+ dependency["outputs"], predictions
1284
+ )
1285
+
1286
+ if len(dependency["outputs"]) == 1 and not (batch):
1287
+ predictions = [
1288
+ predictions,
1289
+ ]
1290
+
1291
+ self.validate_outputs(fn_index, predictions) # type: ignore
1292
+
1293
+ output = []
1294
+ for i, output_id in enumerate(dependency["outputs"]):
1295
+ try:
1296
+ if predictions[i] is components._Keywords.FINISHED_ITERATING:
1297
+ output.append(None)
1298
+ continue
1299
+ except (IndexError, KeyError) as err:
1300
+ raise ValueError(
1301
+ "Number of output components does not match number "
1302
+ f"of values returned from from function {block_fn.name}"
1303
+ ) from err
1304
+
1305
+ try:
1306
+ block = self.blocks[output_id]
1307
+ except KeyError as e:
1308
+ raise InvalidBlockError(
1309
+ f"Output component with id {output_id} used in {dependency['trigger']}() event not found in this gr.Blocks context. You are allowed to nest gr.Blocks contexts, but there must be a gr.Blocks context that contains all components and events."
1310
+ ) from e
1311
+
1312
+ if getattr(block, "stateful", False):
1313
+ if not utils.is_update(predictions[i]):
1314
+ state[output_id] = predictions[i]
1315
+ output.append(None)
1316
+ else:
1317
+ prediction_value = predictions[i]
1318
+ if utils.is_update(prediction_value):
1319
+ assert isinstance(prediction_value, dict)
1320
+ prediction_value = postprocess_update_dict(
1321
+ block=block,
1322
+ update_dict=prediction_value,
1323
+ postprocess=block_fn.postprocess,
1324
+ )
1325
+ elif block_fn.postprocess:
1326
+ assert isinstance(
1327
+ block, components.Component
1328
+ ), f"{block.__class__} Component with id {output_id} not a valid output component."
1329
+ prediction_value = block.postprocess(prediction_value)
1330
+ output.append(prediction_value)
1331
+
1332
+ return output
1333
+
1334
+ async def process_api(
1335
+ self,
1336
+ fn_index: int,
1337
+ inputs: list[Any],
1338
+ state: dict[int, Any],
1339
+ request: routes.Request | list[routes.Request] | None = None,
1340
+ iterators: dict[int, Any] | None = None,
1341
+ event_id: str | None = None,
1342
+ event_data: EventData | None = None,
1343
+ ) -> dict[str, Any]:
1344
+ """
1345
+ Processes API calls from the frontend. First preprocesses the data,
1346
+ then runs the relevant function, then postprocesses the output.
1347
+ Parameters:
1348
+ fn_index: Index of function to run.
1349
+ inputs: input data received from the frontend
1350
+ state: data stored from stateful components for session (key is input block id)
1351
+ request: the gr.Request object containing information about the network request (e.g. IP address, headers, query parameters, username)
1352
+ iterators: the in-progress iterators for each generator function (key is function index)
1353
+ event_id: id of event that triggered this API call
1354
+ event_data: data associated with the event trigger itself
1355
+ Returns: None
1356
+ """
1357
+ block_fn = self.fns[fn_index]
1358
+ batch = self.dependencies[fn_index]["batch"]
1359
+
1360
+ if batch:
1361
+ max_batch_size = self.dependencies[fn_index]["max_batch_size"]
1362
+ batch_sizes = [len(inp) for inp in inputs]
1363
+ batch_size = batch_sizes[0]
1364
+ if inspect.isasyncgenfunction(block_fn.fn) or inspect.isgeneratorfunction(
1365
+ block_fn.fn
1366
+ ):
1367
+ raise ValueError("Gradio does not support generators in batch mode.")
1368
+ if not all(x == batch_size for x in batch_sizes):
1369
+ raise ValueError(
1370
+ f"All inputs to a batch function must have the same length but instead have sizes: {batch_sizes}."
1371
+ )
1372
+ if batch_size > max_batch_size:
1373
+ raise ValueError(
1374
+ f"Batch size ({batch_size}) exceeds the max_batch_size for this function ({max_batch_size})"
1375
+ )
1376
+
1377
+ inputs = [
1378
+ self.preprocess_data(fn_index, list(i), state) for i in zip(*inputs)
1379
+ ]
1380
+ result = await self.call_function(
1381
+ fn_index, list(zip(*inputs)), None, request, event_id, event_data
1382
+ )
1383
+ preds = result["prediction"]
1384
+ data = [
1385
+ self.postprocess_data(fn_index, list(o), state) for o in zip(*preds)
1386
+ ]
1387
+ data = list(zip(*data))
1388
+ is_generating, iterator = None, None
1389
+ else:
1390
+ inputs = self.preprocess_data(fn_index, inputs, state)
1391
+ iterator = iterators.get(fn_index, None) if iterators else None
1392
+ result = await self.call_function(
1393
+ fn_index, inputs, iterator, request, event_id, event_data
1394
+ )
1395
+ data = self.postprocess_data(fn_index, result["prediction"], state)
1396
+ is_generating, iterator = result["is_generating"], result["iterator"]
1397
+
1398
+ block_fn.total_runtime += result["duration"]
1399
+ block_fn.total_runs += 1
1400
+ return {
1401
+ "data": data,
1402
+ "is_generating": is_generating,
1403
+ "iterator": iterator,
1404
+ "duration": result["duration"],
1405
+ "average_duration": block_fn.total_runtime / block_fn.total_runs,
1406
+ }
1407
+
1408
+ async def create_limiter(self):
1409
+ self.limiter = (
1410
+ None
1411
+ if self.max_threads == 40
1412
+ else CapacityLimiter(total_tokens=self.max_threads)
1413
+ )
1414
+
1415
+ def get_config(self):
1416
+ return {"type": "column"}
1417
+
1418
+ def get_config_file(self):
1419
+ config = {
1420
+ "version": routes.VERSION,
1421
+ "mode": self.mode,
1422
+ "dev_mode": self.dev_mode,
1423
+ "analytics_enabled": self.analytics_enabled,
1424
+ "components": [],
1425
+ "css": self.css,
1426
+ "title": self.title or "Gradio",
1427
+ "space_id": self.space_id,
1428
+ "enable_queue": getattr(self, "enable_queue", False), # launch attributes
1429
+ "show_error": getattr(self, "show_error", False),
1430
+ "show_api": self.show_api,
1431
+ "is_colab": utils.colab_check(),
1432
+ "stylesheets": self.stylesheets,
1433
+ "theme": self.theme.name,
1434
+ }
1435
+
1436
+ def get_layout(block):
1437
+ if not isinstance(block, BlockContext):
1438
+ return {"id": block._id}
1439
+ children_layout = []
1440
+ for child in block.children:
1441
+ children_layout.append(get_layout(child))
1442
+ return {"id": block._id, "children": children_layout}
1443
+
1444
+ config["layout"] = get_layout(self)
1445
+
1446
+ for _id, block in self.blocks.items():
1447
+ props = block.get_config() if hasattr(block, "get_config") else {}
1448
+ block_config = {
1449
+ "id": _id,
1450
+ "type": block.get_block_name(),
1451
+ "props": utils.delete_none(props),
1452
+ }
1453
+ serializer = utils.get_serializer_name(block)
1454
+ if serializer:
1455
+ assert isinstance(block, serializing.Serializable)
1456
+ block_config["serializer"] = serializer
1457
+ block_config["api_info"] = block.api_info() # type: ignore
1458
+ block_config["example_inputs"] = block.example_inputs() # type: ignore
1459
+ config["components"].append(block_config)
1460
+ config["dependencies"] = self.dependencies
1461
+ return config
1462
+
1463
+ def __enter__(self):
1464
+ if Context.block is None:
1465
+ Context.root_block = self
1466
+ self.parent = Context.block
1467
+ Context.block = self
1468
+ self.exited = False
1469
+ return self
1470
+
1471
+ def __exit__(self, *args):
1472
+ super().fill_expected_parents()
1473
+ Context.block = self.parent
1474
+ # Configure the load events before root_block is reset
1475
+ self.attach_load_events()
1476
+ if self.parent is None:
1477
+ Context.root_block = None
1478
+ else:
1479
+ self.parent.children.extend(self.children)
1480
+ self.config = self.get_config_file()
1481
+ self.app = routes.App.create_app(self)
1482
+ self.progress_tracking = any(block_fn.tracks_progress for block_fn in self.fns)
1483
+ self.exited = True
1484
+
1485
+ @class_or_instancemethod
1486
+ def load(
1487
+ self_or_cls, # noqa: N805
1488
+ fn: Callable | None = None,
1489
+ inputs: list[Component] | None = None,
1490
+ outputs: list[Component] | None = None,
1491
+ api_name: str | None | Literal[False] = None,
1492
+ scroll_to_output: bool = False,
1493
+ show_progress: str = "full",
1494
+ queue=None,
1495
+ batch: bool = False,
1496
+ max_batch_size: int = 4,
1497
+ preprocess: bool = True,
1498
+ postprocess: bool = True,
1499
+ every: float | None = None,
1500
+ _js: str | None = None,
1501
+ *,
1502
+ name: str | None = None,
1503
+ src: str | None = None,
1504
+ api_key: str | None = None,
1505
+ alias: str | None = None,
1506
+ **kwargs,
1507
+ ) -> Blocks | dict[str, Any] | None:
1508
+ """
1509
+ For reverse compatibility reasons, this is both a class method and an instance
1510
+ method, the two of which, confusingly, do two completely different things.
1511
+
1512
+
1513
+ Class method: loads a demo from a Hugging Face Spaces repo and creates it locally and returns a block instance. Warning: this method will be deprecated. Use the equivalent `gradio.load()` instead.
1514
+
1515
+
1516
+ Instance method: adds event that runs as soon as the demo loads in the browser. Example usage below.
1517
+ Parameters:
1518
+ name: Class Method - the name of the model (e.g. "gpt2" or "facebook/bart-base") or space (e.g. "flax-community/spanish-gpt2"), can include the `src` as prefix (e.g. "models/facebook/bart-base")
1519
+ src: Class Method - the source of the model: `models` or `spaces` (or leave empty if source is provided as a prefix in `name`)
1520
+ api_key: Class Method - optional access token for loading private Hugging Face Hub models or spaces. Find your token here: https://huggingface.co/settings/tokens. Warning: only provide this if you are loading a trusted private Space as it can be read by the Space you are loading.
1521
+ alias: Class Method - optional string used as the name of the loaded model instead of the default name (only applies if loading a Space running Gradio 2.x)
1522
+ fn: Instance Method - the function to wrap an interface around. Often a machine learning model's prediction function. Each parameter of the function corresponds to one input component, and the function should return a single value or a tuple of values, with each element in the tuple corresponding to one output component.
1523
+ inputs: Instance Method - List of gradio.components to use as inputs. If the function takes no inputs, this should be an empty list.
1524
+ outputs: Instance Method - List of gradio.components to use as inputs. If the function returns no outputs, this should be an empty list.
1525
+ api_name: Instance Method - Defines how the endpoint appears in the API docs. Can be a string, None, or False. If False, the endpoint will not be exposed in the api docs. If set to None, the endpoint will be exposed in the api docs as an unnamed endpoint, although this behavior will be changed in Gradio 4.0. If set to a string, the endpoint will be exposed in the api docs with the given name.
1526
+ scroll_to_output: Instance Method - If True, will scroll to output component on completion
1527
+ show_progress: Instance Method - If True, will show progress animation while pending
1528
+ queue: Instance Method - If True, will place the request on the queue, if the queue exists
1529
+ batch: Instance Method - If True, then the function should process a batch of inputs, meaning that it should accept a list of input values for each parameter. The lists should be of equal length (and be up to length `max_batch_size`). The function is then *required* to return a tuple of lists (even if there is only 1 output component), with each list in the tuple corresponding to one output component.
1530
+ max_batch_size: Instance Method - Maximum number of inputs to batch together if this is called from the queue (only relevant if batch=True)
1531
+ preprocess: Instance Method - If False, will not run preprocessing of component data before running 'fn' (e.g. leaving it as a base64 string if this method is called with the `Image` component).
1532
+ postprocess: Instance Method - If False, will not run postprocessing of component data before returning 'fn' output to the browser.
1533
+ every: Instance Method - Run this event 'every' number of seconds. Interpreted in seconds. Queue must be enabled.
1534
+ Example:
1535
+ import gradio as gr
1536
+ import datetime
1537
+ with gr.Blocks() as demo:
1538
+ def get_time():
1539
+ return datetime.datetime.now().time()
1540
+ dt = gr.Textbox(label="Current time")
1541
+ demo.load(get_time, inputs=None, outputs=dt)
1542
+ demo.launch()
1543
+ """
1544
+ if isinstance(self_or_cls, type):
1545
+ warn_deprecation(
1546
+ "gr.Blocks.load() will be deprecated. Use gr.load() instead."
1547
+ )
1548
+ if name is None:
1549
+ raise ValueError(
1550
+ "Blocks.load() requires passing parameters as keyword arguments"
1551
+ )
1552
+ return external.load(
1553
+ name=name, src=src, hf_token=api_key, alias=alias, **kwargs
1554
+ )
1555
+ else:
1556
+ from gradio.events import Dependency
1557
+
1558
+ dep, dep_index = self_or_cls.set_event_trigger(
1559
+ event_name="load",
1560
+ fn=fn,
1561
+ inputs=inputs,
1562
+ outputs=outputs,
1563
+ api_name=api_name,
1564
+ preprocess=preprocess,
1565
+ postprocess=postprocess,
1566
+ scroll_to_output=scroll_to_output,
1567
+ show_progress=show_progress,
1568
+ js=_js,
1569
+ queue=queue,
1570
+ batch=batch,
1571
+ max_batch_size=max_batch_size,
1572
+ every=every,
1573
+ no_target=True,
1574
+ )
1575
+ return Dependency(self_or_cls, dep, dep_index)
1576
+
1577
+ def clear(self):
1578
+ """Resets the layout of the Blocks object."""
1579
+ self.blocks = {}
1580
+ self.fns = []
1581
+ self.dependencies = []
1582
+ self.children = []
1583
+ return self
1584
+
1585
+ @document()
1586
+ def queue(
1587
+ self,
1588
+ concurrency_count: int = 1,
1589
+ status_update_rate: float | Literal["auto"] = "auto",
1590
+ client_position_to_load_data: int | None = None,
1591
+ default_enabled: bool | None = None,
1592
+ api_open: bool = True,
1593
+ max_size: int | None = None,
1594
+ ):
1595
+ """
1596
+ You can control the rate of processed requests by creating a queue. This will allow you to set the number of requests to be processed at one time, and will let users know their position in the queue.
1597
+ Parameters:
1598
+ concurrency_count: Number of worker threads that will be processing requests from the queue concurrently. Increasing this number will increase the rate at which requests are processed, but will also increase the memory usage of the queue.
1599
+ status_update_rate: If "auto", Queue will send status estimations to all clients whenever a job is finished. Otherwise Queue will send status at regular intervals set by this parameter as the number of seconds.
1600
+ client_position_to_load_data: DEPRECATED. This parameter is deprecated and has no effect.
1601
+ default_enabled: Deprecated and has no effect.
1602
+ api_open: If True, the REST routes of the backend will be open, allowing requests made directly to those endpoints to skip the queue.
1603
+ max_size: The maximum number of events the queue will store at any given moment. If the queue is full, new events will not be added and a user will receive a message saying that the queue is full. If None, the queue size will be unlimited.
1604
+ Example: (Blocks)
1605
+ with gr.Blocks() as demo:
1606
+ button = gr.Button(label="Generate Image")
1607
+ button.click(fn=image_generator, inputs=gr.Textbox(), outputs=gr.Image())
1608
+ demo.queue(concurrency_count=3)
1609
+ demo.launch()
1610
+ Example: (Interface)
1611
+ demo = gr.Interface(image_generator, gr.Textbox(), gr.Image())
1612
+ demo.queue(concurrency_count=3)
1613
+ demo.launch()
1614
+ """
1615
+ if default_enabled is not None:
1616
+ warn_deprecation(
1617
+ "The default_enabled parameter of queue has no effect and will be removed "
1618
+ "in a future version of gradio."
1619
+ )
1620
+ self.enable_queue = True
1621
+ self.api_open = api_open
1622
+ if client_position_to_load_data is not None:
1623
+ warn_deprecation(
1624
+ "The client_position_to_load_data parameter is deprecated."
1625
+ )
1626
+ max_size_default = self.max_threads if utils.is_zero_gpu_space() else None
1627
+ self._queue = queueing.Queue(
1628
+ live_updates=status_update_rate == "auto",
1629
+ concurrency_count=concurrency_count,
1630
+ update_intervals=status_update_rate if status_update_rate != "auto" else 1,
1631
+ max_size=max_size_default if max_size is None else max_size,
1632
+ blocks_dependencies=self.dependencies,
1633
+ )
1634
+ self.config = self.get_config_file()
1635
+ self.app = routes.App.create_app(self)
1636
+ return self
1637
+
1638
+ def validate_queue_settings(self):
1639
+ if not self.enable_queue and self.progress_tracking:
1640
+ raise ValueError("Progress tracking requires queuing to be enabled.")
1641
+
1642
+ for fn_index, dep in enumerate(self.dependencies):
1643
+ if not self.enable_queue and self.queue_enabled_for_fn(fn_index):
1644
+ raise ValueError(
1645
+ f"The queue is enabled for event {dep['api_name'] if dep['api_name'] else fn_index} "
1646
+ "but the queue has not been enabled for the app. Please call .queue() "
1647
+ "on your app. Consult https://gradio.app/docs/#blocks-queue for information on how "
1648
+ "to configure the queue."
1649
+ )
1650
+ for i in dep["cancels"]:
1651
+ if not self.queue_enabled_for_fn(i):
1652
+ raise ValueError(
1653
+ "Queue needs to be enabled! "
1654
+ "You may get this error by either 1) passing a function that uses the yield keyword "
1655
+ "into an interface without enabling the queue or 2) defining an event that cancels "
1656
+ "another event without enabling the queue. Both can be solved by calling .queue() "
1657
+ "before .launch()"
1658
+ )
1659
+ if dep["batch"] and (
1660
+ dep["queue"] is False
1661
+ or (dep["queue"] is None and not self.enable_queue)
1662
+ ):
1663
+ raise ValueError("In order to use batching, the queue must be enabled.")
1664
+
1665
+ def launch(
1666
+ self,
1667
+ inline: bool | None = None,
1668
+ inbrowser: bool = False,
1669
+ share: bool | None = None,
1670
+ debug: bool = False,
1671
+ enable_queue: bool | None = None,
1672
+ max_threads: int = 40,
1673
+ auth: Callable | tuple[str, str] | list[tuple[str, str]] | None = None,
1674
+ auth_message: str | None = None,
1675
+ prevent_thread_lock: bool = False,
1676
+ show_error: bool = False,
1677
+ server_name: str | None = None,
1678
+ server_port: int | None = None,
1679
+ show_tips: bool = False,
1680
+ height: int = 500,
1681
+ width: int | str = "100%",
1682
+ encrypt: bool | None = None,
1683
+ favicon_path: str | None = None,
1684
+ ssl_keyfile: str | None = None,
1685
+ ssl_certfile: str | None = None,
1686
+ ssl_keyfile_password: str | None = None,
1687
+ ssl_verify: bool = True,
1688
+ quiet: bool = False,
1689
+ show_api: bool = True,
1690
+ file_directories: list[str] | None = None,
1691
+ allowed_paths: list[str] | None = None,
1692
+ blocked_paths: list[str] | None = None,
1693
+ root_path: str = "",
1694
+ _frontend: bool = True,
1695
+ app_kwargs: dict[str, Any] | None = None,
1696
+ ) -> tuple[FastAPI, str, str]:
1697
+ """
1698
+ Launches a simple web server that serves the demo. Can also be used to create a
1699
+ public link used by anyone to access the demo from their browser by setting share=True.
1700
+
1701
+ Parameters:
1702
+ inline: whether to display in the interface inline in an iframe. Defaults to True in python notebooks; False otherwise.
1703
+ inbrowser: whether to automatically launch the interface in a new tab on the default browser.
1704
+ share: whether to create a publicly shareable link for the interface. Creates an SSH tunnel to make your UI accessible from anywhere. If not provided, it is set to False by default every time, except when running in Google Colab. When localhost is not accessible (e.g. Google Colab), setting share=False is not supported.
1705
+ debug: if True, blocks the main thread from running. If running in Google Colab, this is needed to print the errors in the cell output.
1706
+ auth: If provided, username and password (or list of username-password tuples) required to access interface. Can also provide function that takes username and password and returns True if valid login.
1707
+ auth_message: If provided, HTML message provided on login page.
1708
+ prevent_thread_lock: If True, the interface will block the main thread while the server is running.
1709
+ show_error: If True, any errors in the interface will be displayed in an alert modal and printed in the browser console log
1710
+ server_port: will start gradio app on this port (if available). Can be set by environment variable GRADIO_SERVER_PORT. If None, will search for an available port starting at 7860.
1711
+ server_name: to make app accessible on local network, set this to "0.0.0.0". Can be set by environment variable GRADIO_SERVER_NAME. If None, will use "127.0.0.1".
1712
+ show_tips: if True, will occasionally show tips about new Gradio features
1713
+ enable_queue: DEPRECATED (use .queue() method instead.) if True, inference requests will be served through a queue instead of with parallel threads. Required for longer inference times (> 1min) to prevent timeout. The default option in HuggingFace Spaces is True. The default option elsewhere is False.
1714
+ max_threads: the maximum number of total threads that the Gradio app can generate in parallel. The default is inherited from the starlette library (currently 40). Applies whether the queue is enabled or not. But if queuing is enabled, this parameter is increaseed to be at least the concurrency_count of the queue.
1715
+ width: The width in pixels of the iframe element containing the interface (used if inline=True)
1716
+ height: The height in pixels of the iframe element containing the interface (used if inline=True)
1717
+ encrypt: DEPRECATED. Has no effect.
1718
+ favicon_path: If a path to a file (.png, .gif, or .ico) is provided, it will be used as the favicon for the web page.
1719
+ ssl_keyfile: If a path to a file is provided, will use this as the private key file to create a local server running on https.
1720
+ ssl_certfile: If a path to a file is provided, will use this as the signed certificate for https. Needs to be provided if ssl_keyfile is provided.
1721
+ ssl_keyfile_password: If a password is provided, will use this with the ssl certificate for https.
1722
+ ssl_verify: If False, skips certificate validation which allows self-signed certificates to be used.
1723
+ quiet: If True, suppresses most print statements.
1724
+ show_api: If True, shows the api docs in the footer of the app. Default True. If the queue is enabled, then api_open parameter of .queue() will determine if the api docs are shown, independent of the value of show_api.
1725
+ file_directories: This parameter has been renamed to `allowed_paths`. It will be removed in a future version.
1726
+ allowed_paths: List of complete filepaths or parent directories that gradio is allowed to serve (in addition to the directory containing the gradio python file). Must be absolute paths. Warning: if you provide directories, any files in these directories or their subdirectories are accessible to all users of your app.
1727
+ blocked_paths: List of complete filepaths or parent directories that gradio is not allowed to serve (i.e. users of your app are not allowed to access). Must be absolute paths. Warning: takes precedence over `allowed_paths` and all other directories exposed by Gradio by default.
1728
+ root_path: The root path (or "mount point") of the application, if it's not served from the root ("/") of the domain. Often used when the application is behind a reverse proxy that forwards requests to the application. For example, if the application is served at "https://example.com/myapp", the `root_path` should be set to "/myapp".
1729
+ app_kwargs: Additional keyword arguments to pass to the underlying FastAPI app as a dictionary of parameter keys and argument values. For example, `{"docs_url": "/docs"}`
1730
+ Returns:
1731
+ app: FastAPI app object that is running the demo
1732
+ local_url: Locally accessible link to the demo
1733
+ share_url: Publicly accessible link to the demo (if share=True, otherwise None)
1734
+ Example: (Blocks)
1735
+ import gradio as gr
1736
+ def reverse(text):
1737
+ return text[::-1]
1738
+ with gr.Blocks() as demo:
1739
+ button = gr.Button(value="Reverse")
1740
+ button.click(reverse, gr.Textbox(), gr.Textbox())
1741
+ demo.launch(share=True, auth=("username", "password"))
1742
+ Example: (Interface)
1743
+ import gradio as gr
1744
+ def reverse(text):
1745
+ return text[::-1]
1746
+ demo = gr.Interface(reverse, "text", "text")
1747
+ demo.launch(share=True, auth=("username", "password"))
1748
+ """
1749
+ if not self.exited:
1750
+ self.__exit__()
1751
+
1752
+ self.dev_mode = False
1753
+ if (
1754
+ auth
1755
+ and not callable(auth)
1756
+ and not isinstance(auth[0], tuple)
1757
+ and not isinstance(auth[0], list)
1758
+ ):
1759
+ self.auth = [auth]
1760
+ else:
1761
+ self.auth = auth
1762
+ self.auth_message = auth_message
1763
+ self.show_tips = show_tips
1764
+ self.show_error = show_error
1765
+ self.height = height
1766
+ self.width = width
1767
+ self.favicon_path = favicon_path
1768
+ self.ssl_verify = ssl_verify
1769
+ self.root_path = root_path
1770
+
1771
+ if enable_queue is not None:
1772
+ self.enable_queue = enable_queue
1773
+ warn_deprecation(
1774
+ "The `enable_queue` parameter has been deprecated. "
1775
+ "Please use the `.queue()` method instead.",
1776
+ )
1777
+ if encrypt is not None:
1778
+ warn_deprecation(
1779
+ "The `encrypt` parameter has been deprecated and has no effect.",
1780
+ )
1781
+
1782
+ if self.space_id:
1783
+ self.enable_queue = self.enable_queue is not False
1784
+ else:
1785
+ self.enable_queue = self.enable_queue is True
1786
+ if self.enable_queue and not hasattr(self, "_queue"):
1787
+ self.queue()
1788
+ self.show_api = self.api_open if self.enable_queue else show_api
1789
+
1790
+ if file_directories is not None:
1791
+ warn_deprecation(
1792
+ "The `file_directories` parameter has been renamed to `allowed_paths`. "
1793
+ "Please use that instead.",
1794
+ )
1795
+ if allowed_paths is None:
1796
+ allowed_paths = file_directories
1797
+ self.allowed_paths = allowed_paths or []
1798
+ self.blocked_paths = blocked_paths or []
1799
+
1800
+ if not isinstance(self.allowed_paths, list):
1801
+ raise ValueError("`allowed_paths` must be a list of directories.")
1802
+ if not isinstance(self.blocked_paths, list):
1803
+ raise ValueError("`blocked_paths` must be a list of directories.")
1804
+
1805
+ self.validate_queue_settings()
1806
+
1807
+ self.config = self.get_config_file()
1808
+ self.max_threads = max(
1809
+ self._queue.max_thread_count if self.enable_queue else 0, max_threads
1810
+ )
1811
+
1812
+ if self.is_running:
1813
+ assert isinstance(
1814
+ self.local_url, str
1815
+ ), f"Invalid local_url: {self.local_url}"
1816
+ if not (quiet):
1817
+ print(
1818
+ "Rerunning server... use `close()` to stop if you need to change `launch()` parameters.\n----"
1819
+ )
1820
+ else:
1821
+ if wasm_utils.IS_WASM:
1822
+ server_name = "xxx"
1823
+ server_port = 99999
1824
+ local_url = ""
1825
+ server = None
1826
+
1827
+ # In the Wasm environment, we only need the app object
1828
+ # which the frontend app will directly communicate with through the Worker API,
1829
+ # and we don't need to start a server.
1830
+ # So we just create the app object and register it here,
1831
+ # and avoid using `networking.start_server` that would start a server that don't work in the Wasm env.
1832
+ from gradio.routes import App
1833
+
1834
+ app = App.create_app(self, app_kwargs=app_kwargs)
1835
+ wasm_utils.register_app(app)
1836
+ else:
1837
+ (
1838
+ server_name,
1839
+ server_port,
1840
+ local_url,
1841
+ app,
1842
+ server,
1843
+ ) = networking.start_server(
1844
+ self,
1845
+ server_name,
1846
+ server_port,
1847
+ ssl_keyfile,
1848
+ ssl_certfile,
1849
+ ssl_keyfile_password,
1850
+ app_kwargs=app_kwargs,
1851
+ )
1852
+ self.server_name = server_name
1853
+ self.local_url = local_url
1854
+ self.server_port = server_port
1855
+ self.server_app = app
1856
+ self.server = server
1857
+ self.is_running = True
1858
+ self.is_colab = utils.colab_check()
1859
+ self.is_kaggle = utils.kaggle_check()
1860
+
1861
+ self.protocol = (
1862
+ "https"
1863
+ if self.local_url.startswith("https") or self.is_colab
1864
+ else "http"
1865
+ )
1866
+ if not self.is_colab:
1867
+ print(
1868
+ strings.en["RUNNING_LOCALLY_SEPARATED"].format(
1869
+ self.protocol, self.server_name, self.server_port
1870
+ )
1871
+ )
1872
+
1873
+ if self.enable_queue:
1874
+ self._queue.set_url(self.local_url)
1875
+
1876
+ # Cannot run async functions in background other than app's scope.
1877
+ # Workaround by triggering the app endpoint
1878
+ if not wasm_utils.IS_WASM:
1879
+ requests.get(f"{self.local_url}startup-events", verify=ssl_verify)
1880
+
1881
+ if wasm_utils.IS_WASM:
1882
+ return TupleNoPrint((self.server_app, self.local_url, self.share_url))
1883
+
1884
+ utils.launch_counter()
1885
+ self.is_sagemaker = utils.sagemaker_check()
1886
+ if share is None:
1887
+ if self.is_colab and self.enable_queue:
1888
+ if not quiet:
1889
+ print(
1890
+ "Setting queue=True in a Colab notebook requires sharing enabled. Setting `share=True` (you can turn this off by setting `share=False` in `launch()` explicitly).\n"
1891
+ )
1892
+ self.share = True
1893
+ elif self.is_kaggle:
1894
+ if not quiet:
1895
+ print(
1896
+ "Kaggle notebooks require sharing enabled. Setting `share=True` (you can turn this off by setting `share=False` in `launch()` explicitly).\n"
1897
+ )
1898
+ self.share = True
1899
+ elif self.is_sagemaker:
1900
+ if not quiet:
1901
+ print(
1902
+ "Sagemaker notebooks may require sharing enabled. Setting `share=True` (you can turn this off by setting `share=False` in `launch()` explicitly).\n"
1903
+ )
1904
+ self.share = True
1905
+ else:
1906
+ self.share = False
1907
+ else:
1908
+ self.share = share
1909
+
1910
+ # If running in a colab or not able to access localhost,
1911
+ # a shareable link must be created.
1912
+ if _frontend and (not networking.url_ok(self.local_url)) and (not self.share):
1913
+ raise ValueError(
1914
+ "When localhost is not accessible, a shareable link must be created. Please set share=True or check your proxy settings to allow access to localhost."
1915
+ )
1916
+
1917
+ if self.is_colab:
1918
+ if not quiet:
1919
+ if debug:
1920
+ print(strings.en["COLAB_DEBUG_TRUE"])
1921
+ else:
1922
+ print(strings.en["COLAB_DEBUG_FALSE"])
1923
+ if not self.share:
1924
+ print(strings.en["COLAB_WARNING"].format(self.server_port))
1925
+ if self.enable_queue and not self.share:
1926
+ raise ValueError(
1927
+ "When using queueing in Colab, a shareable link must be created. Please set share=True."
1928
+ )
1929
+
1930
+ if self.share:
1931
+ if self.space_id:
1932
+ raise RuntimeError("Share is not supported when you are in Spaces")
1933
+ try:
1934
+ if self.share_url is None:
1935
+ self.share_url = networking.setup_tunnel(
1936
+ self.server_name, self.server_port, self.share_token
1937
+ )
1938
+ print(strings.en["SHARE_LINK_DISPLAY"].format(self.share_url))
1939
+ if not (quiet):
1940
+ print(strings.en["SHARE_LINK_MESSAGE"])
1941
+ except (RuntimeError, requests.exceptions.ConnectionError):
1942
+ if self.analytics_enabled:
1943
+ analytics.error_analytics("Not able to set up tunnel")
1944
+ self.share_url = None
1945
+ self.share = False
1946
+ if Path(BINARY_PATH).exists():
1947
+ print(strings.en["COULD_NOT_GET_SHARE_LINK"])
1948
+ else:
1949
+ print(
1950
+ strings.en["COULD_NOT_GET_SHARE_LINK_MISSING_FILE"].format(
1951
+ BINARY_PATH,
1952
+ BINARY_URL,
1953
+ BINARY_FILENAME,
1954
+ BINARY_FOLDER,
1955
+ )
1956
+ )
1957
+ else:
1958
+ if not (quiet):
1959
+ print(strings.en["PUBLIC_SHARE_TRUE"])
1960
+ self.share_url = None
1961
+
1962
+ if inbrowser:
1963
+ link = self.share_url if self.share and self.share_url else self.local_url
1964
+ webbrowser.open(link)
1965
+
1966
+ # Check if running in a Python notebook in which case, display inline
1967
+ if inline is None:
1968
+ inline = utils.ipython_check()
1969
+ if inline:
1970
+ try:
1971
+ from IPython.display import HTML, Javascript, display # type: ignore
1972
+
1973
+ if self.share and self.share_url:
1974
+ while not networking.url_ok(self.share_url):
1975
+ time.sleep(0.25)
1976
+ display(
1977
+ HTML(
1978
+ f'<div><iframe src="{self.share_url}" width="{self.width}" height="{self.height}" allow="autoplay; camera; microphone; clipboard-read; clipboard-write;" frameborder="0" allowfullscreen></iframe></div>'
1979
+ )
1980
+ )
1981
+ elif self.is_colab:
1982
+ # modified from /usr/local/lib/python3.7/dist-packages/google/colab/output/_util.py within Colab environment
1983
+ code = """(async (port, path, width, height, cache, element) => {
1984
+ if (!google.colab.kernel.accessAllowed && !cache) {
1985
+ return;
1986
+ }
1987
+ element.appendChild(document.createTextNode(''));
1988
+ const url = await google.colab.kernel.proxyPort(port, {cache});
1989
+
1990
+ const external_link = document.createElement('div');
1991
+ external_link.innerHTML = `
1992
+ <div style="font-family: monospace; margin-bottom: 0.5rem">
1993
+ Running on <a href=${new URL(path, url).toString()} target="_blank">
1994
+ https://localhost:${port}${path}
1995
+ </a>
1996
+ </div>
1997
+ `;
1998
+ element.appendChild(external_link);
1999
+
2000
+ const iframe = document.createElement('iframe');
2001
+ iframe.src = new URL(path, url).toString();
2002
+ iframe.height = height;
2003
+ iframe.allow = "autoplay; camera; microphone; clipboard-read; clipboard-write;"
2004
+ iframe.width = width;
2005
+ iframe.style.border = 0;
2006
+ element.appendChild(iframe);
2007
+ })""" + "({port}, {path}, {width}, {height}, {cache}, window.element)".format(
2008
+ port=json.dumps(self.server_port),
2009
+ path=json.dumps("/"),
2010
+ width=json.dumps(self.width),
2011
+ height=json.dumps(self.height),
2012
+ cache=json.dumps(False),
2013
+ )
2014
+
2015
+ display(Javascript(code))
2016
+ else:
2017
+ display(
2018
+ HTML(
2019
+ f'<div><iframe src="{self.local_url}" width="{self.width}" height="{self.height}" allow="autoplay; camera; microphone; clipboard-read; clipboard-write;" frameborder="0" allowfullscreen></iframe></div>'
2020
+ )
2021
+ )
2022
+ except ImportError:
2023
+ pass
2024
+
2025
+ if getattr(self, "analytics_enabled", False):
2026
+ data = {
2027
+ "launch_method": "browser" if inbrowser else "inline",
2028
+ "is_google_colab": self.is_colab,
2029
+ "is_sharing_on": self.share,
2030
+ "share_url": self.share_url,
2031
+ "enable_queue": self.enable_queue,
2032
+ "show_tips": self.show_tips,
2033
+ "server_name": server_name,
2034
+ "server_port": server_port,
2035
+ "is_space": self.space_id is not None,
2036
+ "mode": self.mode,
2037
+ }
2038
+ analytics.launched_analytics(self, data)
2039
+
2040
+ utils.show_tip(self)
2041
+
2042
+ # Block main thread if debug==True
2043
+ if debug or int(os.getenv("GRADIO_DEBUG", 0)) == 1:
2044
+ self.block_thread()
2045
+ # Block main thread if running in a script to stop script from exiting
2046
+ is_in_interactive_mode = bool(getattr(sys, "ps1", sys.flags.interactive))
2047
+
2048
+ if not prevent_thread_lock and not is_in_interactive_mode:
2049
+ self.block_thread()
2050
+
2051
+ return TupleNoPrint((self.server_app, self.local_url, self.share_url))
2052
+
2053
+ def integrate(
2054
+ self,
2055
+ comet_ml=None,
2056
+ wandb: ModuleType | None = None,
2057
+ mlflow: ModuleType | None = None,
2058
+ ) -> None:
2059
+ """
2060
+ A catch-all method for integrating with other libraries. This method should be run after launch()
2061
+ Parameters:
2062
+ comet_ml: If a comet_ml Experiment object is provided, will integrate with the experiment and appear on Comet dashboard
2063
+ wandb: If the wandb module is provided, will integrate with it and appear on WandB dashboard
2064
+ mlflow: If the mlflow module is provided, will integrate with the experiment and appear on ML Flow dashboard
2065
+ """
2066
+ analytics_integration = ""
2067
+ if comet_ml is not None:
2068
+ analytics_integration = "CometML"
2069
+ comet_ml.log_other("Created from", "Gradio")
2070
+ if self.share_url is not None:
2071
+ comet_ml.log_text(f"gradio: {self.share_url}")
2072
+ comet_ml.end()
2073
+ elif self.local_url:
2074
+ comet_ml.log_text(f"gradio: {self.local_url}")
2075
+ comet_ml.end()
2076
+ else:
2077
+ raise ValueError("Please run `launch()` first.")
2078
+ if wandb is not None:
2079
+ analytics_integration = "WandB"
2080
+ if self.share_url is not None:
2081
+ wandb.log(
2082
+ {
2083
+ "Gradio panel": wandb.Html(
2084
+ '<iframe src="'
2085
+ + self.share_url
2086
+ + '" width="'
2087
+ + str(self.width)
2088
+ + '" height="'
2089
+ + str(self.height)
2090
+ + '" frameBorder="0"></iframe>'
2091
+ )
2092
+ }
2093
+ )
2094
+ else:
2095
+ print(
2096
+ "The WandB integration requires you to "
2097
+ "`launch(share=True)` first."
2098
+ )
2099
+ if mlflow is not None:
2100
+ analytics_integration = "MLFlow"
2101
+ if self.share_url is not None:
2102
+ mlflow.log_param("Gradio Interface Share Link", self.share_url)
2103
+ else:
2104
+ mlflow.log_param("Gradio Interface Local Link", self.local_url)
2105
+ if self.analytics_enabled and analytics_integration:
2106
+ data = {"integration": analytics_integration}
2107
+ analytics.integration_analytics(data)
2108
+
2109
+ def close(self, verbose: bool = True) -> None:
2110
+ """
2111
+ Closes the Interface that was launched and frees the port.
2112
+ """
2113
+ try:
2114
+ if self.enable_queue:
2115
+ self._queue.close()
2116
+ if self.server:
2117
+ self.server.close()
2118
+ self.is_running = False
2119
+ # So that the startup events (starting the queue)
2120
+ # happen the next time the app is launched
2121
+ self.app.startup_events_triggered = False
2122
+ if verbose:
2123
+ print(f"Closing server running on port: {self.server_port}")
2124
+ except (AttributeError, OSError): # can't close if not running
2125
+ pass
2126
+
2127
+ def block_thread(
2128
+ self,
2129
+ ) -> None:
2130
+ """Block main thread until interrupted by user."""
2131
+ try:
2132
+ while True:
2133
+ time.sleep(0.1)
2134
+ except (KeyboardInterrupt, OSError):
2135
+ print("Keyboard interruption in main thread... closing server.")
2136
+ if self.server:
2137
+ self.server.close()
2138
+ for tunnel in CURRENT_TUNNELS:
2139
+ tunnel.kill()
2140
+
2141
+ def attach_load_events(self):
2142
+ """Add a load event for every component whose initial value should be randomized."""
2143
+ if Context.root_block:
2144
+ for component in Context.root_block.blocks.values():
2145
+ if (
2146
+ isinstance(component, components.IOComponent)
2147
+ and component.load_event_to_attach
2148
+ ):
2149
+ load_fn, every = component.load_event_to_attach
2150
+ # Use set_event_trigger to avoid ambiguity between load class/instance method
2151
+ dep = self.set_event_trigger(
2152
+ "load",
2153
+ load_fn,
2154
+ None,
2155
+ component,
2156
+ no_target=True,
2157
+ # If every is None, for sure skip the queue
2158
+ # else, let the enable_queue parameter take precedence
2159
+ # this will raise a nice error message is every is used
2160
+ # without queue
2161
+ queue=False if every is None else None,
2162
+ every=every,
2163
+ )[0]
2164
+ component.load_event = dep
2165
+
2166
+ def startup_events(self):
2167
+ """Events that should be run when the app containing this block starts up."""
2168
+
2169
+ if self.enable_queue:
2170
+ utils.run_coro_in_background(self._queue.start, self.ssl_verify)
2171
+ # So that processing can resume in case the queue was stopped
2172
+ self._queue.stopped = False
2173
+ utils.run_coro_in_background(self.create_limiter)
2174
+
2175
+ def queue_enabled_for_fn(self, fn_index: int):
2176
+ if self.dependencies[fn_index]["queue"] is None:
2177
+ return self.enable_queue
2178
+ return self.dependencies[fn_index]["queue"]
gradio/chat_interface.py ADDED
@@ -0,0 +1,470 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """
2
+ This file defines a useful high-level abstraction to build Gradio chatbots: ChatInterface.
3
+ """
4
+
5
+
6
+ from __future__ import annotations
7
+
8
+ import inspect
9
+ from typing import Callable, Generator
10
+
11
+ from gradio_client import utils as client_utils
12
+ from gradio_client.documentation import document, set_documentation_group
13
+
14
+ from gradio.blocks import Blocks
15
+ from gradio.components import (
16
+ Button,
17
+ Chatbot,
18
+ IOComponent,
19
+ Markdown,
20
+ State,
21
+ Textbox,
22
+ get_component_instance,
23
+ )
24
+ from gradio.events import Dependency, EventListenerMethod
25
+ from gradio.helpers import create_examples as Examples # noqa: N812
26
+ from gradio.layouts import Accordion, Column, Group, Row
27
+ from gradio.themes import ThemeClass as Theme
28
+
29
+ set_documentation_group("chatinterface")
30
+
31
+
32
+ @document()
33
+ class ChatInterface(Blocks):
34
+ """
35
+ ChatInterface is Gradio's high-level abstraction for creating chatbot UIs, and allows you to create
36
+ a web-based demo around a chatbot model in a few lines of code. Only one parameter is required: fn, which
37
+ takes a function that governs the response of the chatbot based on the user input and chat history. Additional
38
+ parameters can be used to control the appearance and behavior of the demo.
39
+
40
+ Example:
41
+ import gradio as gr
42
+
43
+ def echo(message, history):
44
+ return message
45
+
46
+ demo = gr.ChatInterface(fn=echo, examples=["hello", "hola", "merhaba"], title="Echo Bot")
47
+ demo.launch()
48
+ Demos: chatinterface_random_response, chatinterface_streaming_echo
49
+ Guides: creating-a-chatbot-fast, sharing-your-app
50
+ """
51
+
52
+ def __init__(
53
+ self,
54
+ fn: Callable,
55
+ *,
56
+ chatbot: Chatbot | None = None,
57
+ textbox: Textbox | None = None,
58
+ additional_inputs: str | IOComponent | list[str | IOComponent] | None = None,
59
+ additional_inputs_accordion_name: str = "Additional Inputs",
60
+ examples: list[str] | None = None,
61
+ cache_examples: bool | None = None,
62
+ title: str | None = None,
63
+ description: str | None = None,
64
+ theme: Theme | str | None = None,
65
+ css: str | None = None,
66
+ analytics_enabled: bool | None = None,
67
+ submit_btn: str | None | Button = "Submit",
68
+ stop_btn: str | None | Button = "Stop",
69
+ retry_btn: str | None | Button = "🔄 Retry",
70
+ undo_btn: str | None | Button = "↩️ Undo",
71
+ clear_btn: str | None | Button = "🗑️ Clear",
72
+ autofocus: bool = True,
73
+ ):
74
+ """
75
+ Parameters:
76
+ fn: the function to wrap the chat interface around. Should accept two parameters: a string input message and list of two-element lists of the form [[user_message, bot_message], ...] representing the chat history, and return a string response. See the Chatbot documentation for more information on the chat history format.
77
+ chatbot: an instance of the gr.Chatbot component to use for the chat interface, if you would like to customize the chatbot properties. If not provided, a default gr.Chatbot component will be created.
78
+ textbox: an instance of the gr.Textbox component to use for the chat interface, if you would like to customize the textbox properties. If not provided, a default gr.Textbox component will be created.
79
+ additional_inputs: an instance or list of instances of gradio components (or their string shortcuts) to use as additional inputs to the chatbot. If components are not already rendered in a surrounding Blocks, then the components will be displayed under the chatbot, in an accordion.
80
+ additional_inputs_accordion_name: the label of the accordion to use for additional inputs, only used if additional_inputs is provided.
81
+ examples: sample inputs for the function; if provided, appear below the chatbot and can be clicked to populate the chatbot input.
82
+ cache_examples: If True, caches examples in the server for fast runtime in examples. The default option in HuggingFace Spaces is True. The default option elsewhere is False.
83
+ title: a title for the interface; if provided, appears above chatbot in large font. Also used as the tab title when opened in a browser window.
84
+ description: a description for the interface; if provided, appears above the chatbot and beneath the title in regular font. Accepts Markdown and HTML content.
85
+ theme: Theme to use, loaded from gradio.themes.
86
+ css: custom css or path to custom css file to use with interface.
87
+ analytics_enabled: Whether to allow basic telemetry. If None, will use GRADIO_ANALYTICS_ENABLED environment variable if defined, or default to True.
88
+ submit_btn: Text to display on the submit button. If None, no button will be displayed. If a Button object, that button will be used.
89
+ stop_btn: Text to display on the stop button, which replaces the submit_btn when the submit_btn or retry_btn is clicked and response is streaming. Clicking on the stop_btn will halt the chatbot response. If set to None, stop button functionality does not appear in the chatbot. If a Button object, that button will be used as the stop button.
90
+ retry_btn: Text to display on the retry button. If None, no button will be displayed. If a Button object, that button will be used.
91
+ undo_btn: Text to display on the delete last button. If None, no button will be displayed. If a Button object, that button will be used.
92
+ clear_btn: Text to display on the clear button. If None, no button will be displayed. If a Button object, that button will be used.
93
+ autofocus: If True, autofocuses to the textbox when the page loads.
94
+ """
95
+ super().__init__(
96
+ analytics_enabled=analytics_enabled,
97
+ mode="chat_interface",
98
+ css=css,
99
+ title=title or "Gradio",
100
+ theme=theme,
101
+ )
102
+ self.fn = fn
103
+ self.is_generator = inspect.isgeneratorfunction(self.fn)
104
+ self.examples = examples
105
+ if self.space_id and cache_examples is None:
106
+ self.cache_examples = True
107
+ else:
108
+ self.cache_examples = cache_examples or False
109
+ self.buttons: list[Button] = []
110
+
111
+ if additional_inputs:
112
+ if not isinstance(additional_inputs, list):
113
+ additional_inputs = [additional_inputs]
114
+ self.additional_inputs = [
115
+ get_component_instance(i, render=False) for i in additional_inputs # type: ignore
116
+ ]
117
+ else:
118
+ self.additional_inputs = []
119
+ self.additional_inputs_accordion_name = additional_inputs_accordion_name
120
+
121
+ with self:
122
+ if title:
123
+ Markdown(
124
+ f"<h1 style='text-align: center; margin-bottom: 1rem'>{self.title}</h1>"
125
+ )
126
+ if description:
127
+ Markdown(description)
128
+
129
+ with Column(variant="panel"):
130
+ if chatbot:
131
+ self.chatbot = chatbot.render()
132
+ else:
133
+ self.chatbot = Chatbot(label="Chatbot")
134
+
135
+ with Group():
136
+ with Row():
137
+ if textbox:
138
+ textbox.container = False
139
+ textbox.show_label = False
140
+ self.textbox = textbox.render()
141
+ else:
142
+ self.textbox = Textbox(
143
+ container=False,
144
+ show_label=False,
145
+ label="Message",
146
+ placeholder="Type a message...",
147
+ scale=7,
148
+ autofocus=autofocus,
149
+ )
150
+ if submit_btn:
151
+ if isinstance(submit_btn, Button):
152
+ submit_btn.render()
153
+ elif isinstance(submit_btn, str):
154
+ submit_btn = Button(
155
+ submit_btn,
156
+ variant="primary",
157
+ scale=1,
158
+ min_width=150,
159
+ )
160
+ else:
161
+ raise ValueError(
162
+ f"The submit_btn parameter must be a gr.Button, string, or None, not {type(submit_btn)}"
163
+ )
164
+ if stop_btn:
165
+ if isinstance(stop_btn, Button):
166
+ stop_btn.visible = False
167
+ stop_btn.render()
168
+ elif isinstance(stop_btn, str):
169
+ stop_btn = Button(
170
+ stop_btn,
171
+ variant="stop",
172
+ visible=False,
173
+ scale=1,
174
+ min_width=150,
175
+ )
176
+ else:
177
+ raise ValueError(
178
+ f"The stop_btn parameter must be a gr.Button, string, or None, not {type(stop_btn)}"
179
+ )
180
+ self.buttons.extend([submit_btn, stop_btn])
181
+
182
+ with Row():
183
+ for btn in [retry_btn, undo_btn, clear_btn]:
184
+ if btn:
185
+ if isinstance(btn, Button):
186
+ btn.render()
187
+ elif isinstance(btn, str):
188
+ btn = Button(btn, variant="secondary")
189
+ else:
190
+ raise ValueError(
191
+ f"All the _btn parameters must be a gr.Button, string, or None, not {type(btn)}"
192
+ )
193
+ self.buttons.append(btn)
194
+
195
+ self.fake_api_btn = Button("Fake API", visible=False)
196
+ self.fake_response_textbox = Textbox(
197
+ label="Response", visible=False
198
+ )
199
+ (
200
+ self.submit_btn,
201
+ self.stop_btn,
202
+ self.retry_btn,
203
+ self.undo_btn,
204
+ self.clear_btn,
205
+ ) = self.buttons
206
+
207
+ if examples:
208
+ if self.is_generator:
209
+ examples_fn = self._examples_stream_fn
210
+ else:
211
+ examples_fn = self._examples_fn
212
+
213
+ self.examples_handler = Examples(
214
+ examples=examples,
215
+ inputs=[self.textbox] + self.additional_inputs,
216
+ outputs=self.chatbot,
217
+ fn=examples_fn,
218
+ )
219
+
220
+ any_unrendered_inputs = any(
221
+ not inp.is_rendered for inp in self.additional_inputs
222
+ )
223
+ if self.additional_inputs and any_unrendered_inputs:
224
+ with Accordion(self.additional_inputs_accordion_name, open=False):
225
+ for input_component in self.additional_inputs:
226
+ if not input_component.is_rendered:
227
+ input_component.render()
228
+
229
+ # The example caching must happen after the input components have rendered
230
+ if cache_examples:
231
+ client_utils.synchronize_async(self.examples_handler.cache)
232
+
233
+ self.saved_input = State()
234
+ self.chatbot_state = State([])
235
+
236
+ self._setup_events()
237
+ self._setup_api()
238
+
239
+ def _setup_events(self) -> None:
240
+ submit_fn = self._stream_fn if self.is_generator else self._submit_fn
241
+ submit_event = (
242
+ self.textbox.submit(
243
+ self._clear_and_save_textbox,
244
+ [self.textbox],
245
+ [self.textbox, self.saved_input],
246
+ api_name=False,
247
+ queue=False,
248
+ )
249
+ .then(
250
+ self._display_input,
251
+ [self.saved_input, self.chatbot_state],
252
+ [self.chatbot, self.chatbot_state],
253
+ api_name=False,
254
+ queue=False,
255
+ )
256
+ .then(
257
+ submit_fn,
258
+ [self.saved_input, self.chatbot_state] + self.additional_inputs,
259
+ [self.chatbot, self.chatbot_state],
260
+ api_name=False,
261
+ )
262
+ )
263
+ self._setup_stop_events(self.textbox.submit, submit_event)
264
+
265
+ if self.submit_btn:
266
+ click_event = (
267
+ self.submit_btn.click(
268
+ self._clear_and_save_textbox,
269
+ [self.textbox],
270
+ [self.textbox, self.saved_input],
271
+ api_name=False,
272
+ queue=False,
273
+ )
274
+ .then(
275
+ self._display_input,
276
+ [self.saved_input, self.chatbot_state],
277
+ [self.chatbot, self.chatbot_state],
278
+ api_name=False,
279
+ queue=False,
280
+ )
281
+ .then(
282
+ submit_fn,
283
+ [self.saved_input, self.chatbot_state] + self.additional_inputs,
284
+ [self.chatbot, self.chatbot_state],
285
+ api_name=False,
286
+ )
287
+ )
288
+ self._setup_stop_events(self.submit_btn.click, click_event)
289
+
290
+ if self.retry_btn:
291
+ retry_event = (
292
+ self.retry_btn.click(
293
+ self._delete_prev_fn,
294
+ [self.chatbot_state],
295
+ [self.chatbot, self.saved_input, self.chatbot_state],
296
+ api_name=False,
297
+ queue=False,
298
+ )
299
+ .then(
300
+ self._display_input,
301
+ [self.saved_input, self.chatbot_state],
302
+ [self.chatbot, self.chatbot_state],
303
+ api_name=False,
304
+ queue=False,
305
+ )
306
+ .then(
307
+ submit_fn,
308
+ [self.saved_input, self.chatbot_state] + self.additional_inputs,
309
+ [self.chatbot, self.chatbot_state],
310
+ api_name=False,
311
+ )
312
+ )
313
+ self._setup_stop_events(self.retry_btn.click, retry_event)
314
+
315
+ if self.undo_btn:
316
+ self.undo_btn.click(
317
+ self._delete_prev_fn,
318
+ [self.chatbot_state],
319
+ [self.chatbot, self.saved_input, self.chatbot_state],
320
+ api_name=False,
321
+ queue=False,
322
+ ).then(
323
+ lambda x: x,
324
+ [self.saved_input],
325
+ [self.textbox],
326
+ api_name=False,
327
+ queue=False,
328
+ )
329
+
330
+ if self.clear_btn:
331
+ self.clear_btn.click(
332
+ lambda: ([], [], None),
333
+ None,
334
+ [self.chatbot, self.chatbot_state, self.saved_input],
335
+ queue=False,
336
+ api_name=False,
337
+ )
338
+
339
+ def _setup_stop_events(
340
+ self, event_trigger: EventListenerMethod, event_to_cancel: Dependency
341
+ ) -> None:
342
+ if self.stop_btn and self.is_generator:
343
+ if self.submit_btn:
344
+ event_trigger(
345
+ lambda: (Button.update(visible=False), Button.update(visible=True)),
346
+ None,
347
+ [self.submit_btn, self.stop_btn],
348
+ api_name=False,
349
+ queue=False,
350
+ )
351
+ event_to_cancel.then(
352
+ lambda: (Button.update(visible=True), Button.update(visible=False)),
353
+ None,
354
+ [self.submit_btn, self.stop_btn],
355
+ api_name=False,
356
+ queue=False,
357
+ )
358
+ else:
359
+ event_trigger(
360
+ lambda: Button.update(visible=True),
361
+ None,
362
+ [self.stop_btn],
363
+ api_name=False,
364
+ queue=False,
365
+ )
366
+ event_to_cancel.then(
367
+ lambda: Button.update(visible=False),
368
+ None,
369
+ [self.stop_btn],
370
+ api_name=False,
371
+ queue=False,
372
+ )
373
+ self.stop_btn.click(
374
+ None,
375
+ None,
376
+ None,
377
+ cancels=event_to_cancel,
378
+ api_name=False,
379
+ )
380
+
381
+ def _setup_api(self) -> None:
382
+ api_fn = self._api_stream_fn if self.is_generator else self._api_submit_fn
383
+
384
+ self.fake_api_btn.click(
385
+ api_fn,
386
+ [self.textbox, self.chatbot_state] + self.additional_inputs,
387
+ [self.textbox, self.chatbot_state],
388
+ api_name="chat",
389
+ )
390
+
391
+ def _clear_and_save_textbox(self, message: str) -> tuple[str, str]:
392
+ return "", message
393
+
394
+ def _display_input(
395
+ self, message: str, history: list[list[str | None]]
396
+ ) -> tuple[list[list[str | None]], list[list[str | None]]]:
397
+ history.append([message, None])
398
+ return history, history
399
+
400
+ def _submit_fn(
401
+ self,
402
+ message: str,
403
+ history_with_input: list[list[str | None]],
404
+ *args,
405
+ **kwargs,
406
+ ) -> tuple[list[list[str | None]], list[list[str | None]]]:
407
+ history = history_with_input[:-1]
408
+ response = self.fn(message, history, *args, **kwargs)
409
+ history.append([message, response])
410
+ return history, history
411
+
412
+ def _stream_fn(
413
+ self,
414
+ message: str,
415
+ history_with_input: list[list[str | None]],
416
+ *args,
417
+ **kwargs,
418
+ ) -> Generator[tuple[list[list[str | None]], list[list[str | None]]], None, None]:
419
+ history = history_with_input[:-1]
420
+ generator = self.fn(message, history, *args, **kwargs)
421
+ try:
422
+ first_response = next(generator)
423
+ update = history + [[message, first_response]]
424
+ yield update, update
425
+ except StopIteration:
426
+ update = history + [[message, None]]
427
+ yield update, update
428
+ for response in generator:
429
+ update = history + [[message, response]]
430
+ yield update, update
431
+
432
+ def _api_submit_fn(
433
+ self, message: str, history: list[list[str | None]], *args, **kwargs
434
+ ) -> tuple[str, list[list[str | None]]]:
435
+ response = self.fn(message, history)
436
+ history.append([message, response])
437
+ return response, history
438
+
439
+ def _api_stream_fn(
440
+ self, message: str, history: list[list[str | None]], *args, **kwargs
441
+ ) -> Generator[tuple[str | None, list[list[str | None]]], None, None]:
442
+ generator = self.fn(message, history, *args, **kwargs)
443
+ try:
444
+ first_response = next(generator)
445
+ yield first_response, history + [[message, first_response]]
446
+ except StopIteration:
447
+ yield None, history + [[message, None]]
448
+ for response in generator:
449
+ yield response, history + [[message, response]]
450
+
451
+ def _examples_fn(self, message: str, *args, **kwargs) -> list[list[str | None]]:
452
+ return [[message, self.fn(message, [], *args, **kwargs)]]
453
+
454
+ def _examples_stream_fn(
455
+ self,
456
+ message: str,
457
+ *args,
458
+ **kwargs,
459
+ ) -> Generator[list[list[str | None]], None, None]:
460
+ for response in self.fn(message, [], *args, **kwargs):
461
+ yield [[message, response]]
462
+
463
+ def _delete_prev_fn(
464
+ self, history: list[list[str | None]]
465
+ ) -> tuple[list[list[str | None]], str, list[list[str | None]]]:
466
+ try:
467
+ message, _ = history.pop()
468
+ except IndexError:
469
+ message = ""
470
+ return history, message or "", history
gradio/cli.py ADDED
@@ -0,0 +1,21 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import sys
2
+
3
+ from gradio_client.cli import deploy_discord # type: ignore
4
+
5
+ import gradio.cli_env_info
6
+ import gradio.deploy_space
7
+ import gradio.reload
8
+
9
+
10
+ def cli():
11
+ args = sys.argv[1:]
12
+ if len(args) == 0:
13
+ raise ValueError("No file specified.")
14
+ elif args[0] == "deploy":
15
+ gradio.deploy_space.deploy()
16
+ elif args[0] == "environment":
17
+ gradio.cli_env_info.print_environment_info()
18
+ elif args[0] == "deploy-discord":
19
+ deploy_discord.main()
20
+ else:
21
+ gradio.reload.main()
gradio/cli_env_info.py ADDED
@@ -0,0 +1,29 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """ This file is the part of 'gradio/cli.py' for printing the environment info
2
+ for the cli command 'gradio environment'
3
+ """
4
+ import platform
5
+
6
+ import pkg_resources
7
+
8
+
9
+ def print_environment_info():
10
+ print("Gradio Environment Information:")
11
+
12
+ print("Operating System: ", platform.system())
13
+ print("\n")
14
+
15
+ for package_name in ["gradio", "gradio_client"]:
16
+ try:
17
+ package_dist = pkg_resources.get_distribution(package_name)
18
+ package_version = package_dist.version
19
+ print(f"{package_name} version: ", package_version)
20
+
21
+ print(f"\n{package_name} Dependencies:")
22
+ for req in package_dist.requires():
23
+ print(
24
+ f" {req.project_name}: {pkg_resources.get_distribution(req.project_name).version}"
25
+ )
26
+
27
+ print("\n")
28
+ except pkg_resources.DistributionNotFound:
29
+ print(f"{package_name} package is not installed.")
gradio/components/__init__.py ADDED
@@ -0,0 +1,116 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from gradio.components.annotated_image import AnnotatedImage
2
+ from gradio.components.audio import Audio
3
+ from gradio.components.bar_plot import BarPlot
4
+ from gradio.components.base import (
5
+ Column,
6
+ Component,
7
+ Form,
8
+ FormComponent,
9
+ IOComponent,
10
+ Row,
11
+ _Keywords,
12
+ component,
13
+ get_component_instance,
14
+ )
15
+ from gradio.components.button import Button
16
+ from gradio.components.carousel import Carousel
17
+ from gradio.components.chatbot import Chatbot
18
+ from gradio.components.checkbox import Checkbox
19
+ from gradio.components.checkboxgroup import CheckboxGroup
20
+ from gradio.components.clear_button import ClearButton
21
+ from gradio.components.code import Code
22
+ from gradio.components.color_picker import ColorPicker
23
+ from gradio.components.dataframe import Dataframe
24
+ from gradio.components.dataset import Dataset
25
+ from gradio.components.dropdown import Dropdown
26
+ from gradio.components.duplicate_button import DuplicateButton
27
+ from gradio.components.file import File
28
+ from gradio.components.gallery import Gallery
29
+ from gradio.components.highlighted_text import HighlightedText
30
+ from gradio.components.html import HTML
31
+ from gradio.components.image import Image
32
+ from gradio.components.interpretation import Interpretation
33
+ from gradio.components.json_component import JSON
34
+ from gradio.components.label import Label
35
+ from gradio.components.line_plot import LinePlot
36
+ from gradio.components.markdown import Markdown
37
+ from gradio.components.model3d import Model3D
38
+ from gradio.components.number import Number
39
+ from gradio.components.plot import Plot
40
+ from gradio.components.radio import Radio
41
+ from gradio.components.scatter_plot import ScatterPlot
42
+ from gradio.components.slider import Slider
43
+ from gradio.components.state import State, Variable
44
+ from gradio.components.status_tracker import StatusTracker
45
+ from gradio.components.textbox import Textbox
46
+ from gradio.components.timeseries import Timeseries
47
+ from gradio.components.upload_button import UploadButton
48
+ from gradio.components.video import Video
49
+
50
+ Text = Textbox
51
+ DataFrame = Dataframe
52
+ Highlightedtext = HighlightedText
53
+ Annotatedimage = AnnotatedImage
54
+ Highlight = HighlightedText
55
+ Checkboxgroup = CheckboxGroup
56
+ TimeSeries = Timeseries
57
+ Json = JSON
58
+
59
+ __all__ = [
60
+ "Audio",
61
+ "BarPlot",
62
+ "Button",
63
+ "Carousel",
64
+ "Chatbot",
65
+ "ClearButton",
66
+ "Component",
67
+ "component",
68
+ "get_component_instance",
69
+ "_Keywords",
70
+ "Checkbox",
71
+ "CheckboxGroup",
72
+ "Code",
73
+ "ColorPicker",
74
+ "Column",
75
+ "Dataframe",
76
+ "DataFrame",
77
+ "Dataset",
78
+ "DuplicateButton",
79
+ "Form",
80
+ "FormComponent",
81
+ "Gallery",
82
+ "HTML",
83
+ "Image",
84
+ "IOComponent",
85
+ "Interpretation",
86
+ "JSON",
87
+ "Json",
88
+ "Label",
89
+ "LinePlot",
90
+ "Markdown",
91
+ "Textbox",
92
+ "Dropdown",
93
+ "Model3D",
94
+ "File",
95
+ "HighlightedText",
96
+ "AnnotatedImage",
97
+ "CheckboxGroup",
98
+ "Timeseries",
99
+ "Text",
100
+ "Highlightedtext",
101
+ "Annotatedimage",
102
+ "Highlight",
103
+ "Checkboxgroup",
104
+ "TimeSeries",
105
+ "Number",
106
+ "Plot",
107
+ "Radio",
108
+ "Row",
109
+ "ScatterPlot",
110
+ "Slider",
111
+ "State",
112
+ "Variable",
113
+ "StatusTracker",
114
+ "UploadButton",
115
+ "Video",
116
+ ]
gradio/components/annotated_image.py ADDED
@@ -0,0 +1,243 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """gr.AnnotatedImage() component."""
2
+
3
+ from __future__ import annotations
4
+
5
+ from typing import Literal
6
+
7
+ import numpy as np
8
+ from gradio_client.documentation import document, set_documentation_group
9
+ from gradio_client.serializing import JSONSerializable
10
+ from PIL import Image as _Image # using _ to minimize namespace pollution
11
+
12
+ from gradio import utils
13
+ from gradio.components.base import IOComponent, _Keywords
14
+ from gradio.deprecation import warn_style_method_deprecation
15
+ from gradio.events import (
16
+ EventListenerMethod,
17
+ Selectable,
18
+ )
19
+
20
+ set_documentation_group("component")
21
+
22
+ _Image.init() # fixes https://github.com/gradio-app/gradio/issues/2843
23
+
24
+
25
+ @document()
26
+ class AnnotatedImage(Selectable, IOComponent, JSONSerializable):
27
+ """
28
+ Displays a base image and colored subsections on top of that image. Subsections can take the from of rectangles (e.g. object detection) or masks (e.g. image segmentation).
29
+ Preprocessing: this component does *not* accept input.
30
+ Postprocessing: expects a {Tuple[numpy.ndarray | PIL.Image | str, List[Tuple[numpy.ndarray | Tuple[int, int, int, int], str]]]} consisting of a base image and a list of subsections, that are either (x1, y1, x2, y2) tuples identifying object boundaries, or 0-1 confidence masks of the same shape as the image. A label is provided for each subsection.
31
+
32
+ Demos: image_segmentation
33
+ """
34
+
35
+ def __init__(
36
+ self,
37
+ value: tuple[
38
+ np.ndarray | _Image.Image | str,
39
+ list[tuple[np.ndarray | tuple[int, int, int, int], str]],
40
+ ]
41
+ | None = None,
42
+ *,
43
+ show_legend: bool = True,
44
+ height: int | None = None,
45
+ width: int | None = None,
46
+ color_map: dict[str, str] | None = None,
47
+ label: str | None = None,
48
+ every: float | None = None,
49
+ show_label: bool | None = None,
50
+ container: bool = True,
51
+ scale: int | None = None,
52
+ min_width: int = 160,
53
+ visible: bool = True,
54
+ elem_id: str | None = None,
55
+ elem_classes: list[str] | str | None = None,
56
+ **kwargs,
57
+ ):
58
+ """
59
+ Parameters:
60
+ value: Tuple of base image and list of (subsection, label) pairs.
61
+ show_legend: If True, will show a legend of the subsections.
62
+ height: Height of the displayed image.
63
+ width: Width of the displayed image.
64
+ color_map: A dictionary mapping labels to colors. The colors must be specified as hex codes.
65
+ label: component name in interface.
66
+ every: If `value` is a callable, run the function 'every' number of seconds while the client connection is open. Has no effect otherwise. Queue must be enabled. The event can be accessed (e.g. to cancel it) via this component's .load_event attribute.
67
+ show_label: if True, will display label.
68
+ container: If True, will place the component in a container - providing some extra padding around the border.
69
+ scale: relative width compared to adjacent Components in a Row. For example, if Component A has scale=2, and Component B has scale=1, A will be twice as wide as B. Should be an integer.
70
+ 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.
71
+ visible: If False, component will be hidden.
72
+ 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.
73
+ 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.
74
+ """
75
+ self.show_legend = show_legend
76
+ self.height = height
77
+ self.width = width
78
+ self.color_map = color_map
79
+ self.select: EventListenerMethod
80
+ """
81
+ Event listener for when the user selects Image subsection.
82
+ Uses event data gradio.SelectData to carry `value` referring to selected subsection label, and `index` to refer to subsection index.
83
+ See EventData documentation on how to use this event data.
84
+ """
85
+ IOComponent.__init__(
86
+ self,
87
+ label=label,
88
+ every=every,
89
+ show_label=show_label,
90
+ container=container,
91
+ scale=scale,
92
+ min_width=min_width,
93
+ visible=visible,
94
+ elem_id=elem_id,
95
+ elem_classes=elem_classes,
96
+ value=value,
97
+ **kwargs,
98
+ )
99
+
100
+ def get_config(self):
101
+ return {
102
+ "show_legend": self.show_legend,
103
+ "value": self.value,
104
+ "height": self.height,
105
+ "width": self.width,
106
+ "color_map": self.color_map,
107
+ "selectable": self.selectable,
108
+ **IOComponent.get_config(self),
109
+ }
110
+
111
+ @staticmethod
112
+ def update(
113
+ value: tuple[
114
+ np.ndarray | _Image.Image | str,
115
+ list[tuple[np.ndarray | tuple[int, int, int, int], str]],
116
+ ]
117
+ | Literal[_Keywords.NO_VALUE] = _Keywords.NO_VALUE,
118
+ show_legend: bool | None = None,
119
+ height: int | None = None,
120
+ width: int | None = None,
121
+ color_map: dict[str, str] | None = None,
122
+ label: str | None = None,
123
+ show_label: bool | None = None,
124
+ container: bool | None = None,
125
+ scale: int | None = None,
126
+ min_width: int | None = None,
127
+ visible: bool | None = None,
128
+ ):
129
+ updated_config = {
130
+ "show_legend": show_legend,
131
+ "height": height,
132
+ "width": width,
133
+ "color_map": color_map,
134
+ "label": label,
135
+ "show_label": show_label,
136
+ "container": container,
137
+ "scale": scale,
138
+ "min_width": min_width,
139
+ "visible": visible,
140
+ "value": value,
141
+ "__type__": "update",
142
+ }
143
+ return updated_config
144
+
145
+ def postprocess(
146
+ self,
147
+ y: tuple[
148
+ np.ndarray | _Image.Image | str,
149
+ list[tuple[np.ndarray | tuple[int, int, int, int], str]],
150
+ ],
151
+ ) -> tuple[dict, list[tuple[dict, str]]] | None:
152
+ """
153
+ Parameters:
154
+ y: Tuple of base image and list of subsections, with each subsection a two-part tuple where the first element is a 4 element bounding box or a 0-1 confidence mask, and the second element is the label.
155
+ Returns:
156
+ Tuple of base image file and list of subsections, with each subsection a two-part tuple where the first element image path of the mask, and the second element is the label.
157
+ """
158
+ if y is None:
159
+ return None
160
+ base_img = y[0]
161
+ if isinstance(base_img, str):
162
+ base_img_path = base_img
163
+ base_img = np.array(_Image.open(base_img))
164
+ elif isinstance(base_img, np.ndarray):
165
+ base_file = self.img_array_to_temp_file(base_img, dir=self.DEFAULT_TEMP_DIR)
166
+ base_img_path = str(utils.abspath(base_file))
167
+ elif isinstance(base_img, _Image.Image):
168
+ base_file = self.pil_to_temp_file(base_img, dir=self.DEFAULT_TEMP_DIR)
169
+ base_img_path = str(utils.abspath(base_file))
170
+ base_img = np.array(base_img)
171
+ else:
172
+ raise ValueError(
173
+ "AnnotatedImage only accepts filepaths, PIL images or numpy arrays for the base image."
174
+ )
175
+ self.temp_files.add(base_img_path)
176
+
177
+ sections = []
178
+ color_map = self.color_map or {}
179
+
180
+ def hex_to_rgb(value):
181
+ value = value.lstrip("#")
182
+ lv = len(value)
183
+ return [int(value[i : i + lv // 3], 16) for i in range(0, lv, lv // 3)]
184
+
185
+ for mask, label in y[1]:
186
+ mask_array = np.zeros((base_img.shape[0], base_img.shape[1]))
187
+ if isinstance(mask, np.ndarray):
188
+ mask_array = mask
189
+ else:
190
+ x1, y1, x2, y2 = mask
191
+ border_width = 3
192
+ mask_array[y1:y2, x1:x2] = 0.5
193
+ mask_array[y1:y2, x1 : x1 + border_width] = 1
194
+ mask_array[y1:y2, x2 - border_width : x2] = 1
195
+ mask_array[y1 : y1 + border_width, x1:x2] = 1
196
+ mask_array[y2 - border_width : y2, x1:x2] = 1
197
+
198
+ if label in color_map:
199
+ rgb_color = hex_to_rgb(color_map[label])
200
+ else:
201
+ rgb_color = [255, 0, 0]
202
+ colored_mask = np.zeros((base_img.shape[0], base_img.shape[1], 4))
203
+ solid_mask = np.copy(mask_array)
204
+ solid_mask[solid_mask > 0] = 1
205
+
206
+ colored_mask[:, :, 0] = rgb_color[0] * solid_mask
207
+ colored_mask[:, :, 1] = rgb_color[1] * solid_mask
208
+ colored_mask[:, :, 2] = rgb_color[2] * solid_mask
209
+ colored_mask[:, :, 3] = mask_array * 255
210
+
211
+ colored_mask_img = _Image.fromarray((colored_mask).astype(np.uint8))
212
+
213
+ mask_file = self.pil_to_temp_file(
214
+ colored_mask_img, dir=self.DEFAULT_TEMP_DIR
215
+ )
216
+ mask_file_path = str(utils.abspath(mask_file))
217
+ self.temp_files.add(mask_file_path)
218
+
219
+ sections.append(
220
+ ({"name": mask_file_path, "data": None, "is_file": True}, label)
221
+ )
222
+
223
+ return {"name": base_img_path, "data": None, "is_file": True}, sections
224
+
225
+ def style(
226
+ self,
227
+ *,
228
+ height: int | None = None,
229
+ width: int | None = None,
230
+ color_map: dict[str, str] | None = None,
231
+ **kwargs,
232
+ ):
233
+ """
234
+ This method is deprecated. Please set these arguments in the constructor instead.
235
+ """
236
+ warn_style_method_deprecation()
237
+ if height is not None:
238
+ self.height = height
239
+ if width is not None:
240
+ self.width = width
241
+ if color_map is not None:
242
+ self.color_map = color_map
243
+ return self
gradio/components/audio.py ADDED
@@ -0,0 +1,350 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """gr.Audio() component."""
2
+
3
+ from __future__ import annotations
4
+
5
+ import tempfile
6
+ from pathlib import Path
7
+ from typing import Any, Callable, Literal
8
+
9
+ import numpy as np
10
+ from gradio_client import media_data
11
+ from gradio_client import utils as client_utils
12
+ from gradio_client.documentation import document, set_documentation_group
13
+ from gradio_client.serializing import FileSerializable
14
+
15
+ from gradio import processing_utils, utils
16
+ from gradio.components.base import IOComponent, _Keywords
17
+ from gradio.events import (
18
+ Changeable,
19
+ Clearable,
20
+ Playable,
21
+ Recordable,
22
+ Streamable,
23
+ Uploadable,
24
+ )
25
+ from gradio.interpretation import TokenInterpretable
26
+
27
+ set_documentation_group("component")
28
+
29
+
30
+ @document()
31
+ class Audio(
32
+ Changeable,
33
+ Clearable,
34
+ Playable,
35
+ Recordable,
36
+ Streamable,
37
+ Uploadable,
38
+ IOComponent,
39
+ FileSerializable,
40
+ TokenInterpretable,
41
+ ):
42
+ """
43
+ Creates an audio component that can be used to upload/record audio (as an input) or display audio (as an output).
44
+ Preprocessing: passes the uploaded audio as a {Tuple(int, numpy.array)} corresponding to (sample rate in Hz, audio data as a 16-bit int array whose values range from -32768 to 32767), or as a {str} filepath, depending on `type`.
45
+ Postprocessing: expects a {Tuple(int, numpy.array)} corresponding to (sample rate in Hz, audio data as a float or int numpy array) or as a {str} or {pathlib.Path} filepath or URL to an audio file, which gets displayed
46
+ Examples-format: a {str} filepath to a local file that contains audio.
47
+ Demos: main_note, generate_tone, reverse_audio
48
+ Guides: real-time-speech-recognition
49
+ """
50
+
51
+ def __init__(
52
+ self,
53
+ value: str | Path | tuple[int, np.ndarray] | Callable | None = None,
54
+ *,
55
+ source: Literal["upload", "microphone"] = "upload",
56
+ type: Literal["numpy", "filepath"] = "numpy",
57
+ label: str | None = None,
58
+ every: float | None = None,
59
+ show_label: bool | None = None,
60
+ container: bool = True,
61
+ scale: int | None = None,
62
+ min_width: int = 160,
63
+ interactive: bool | None = None,
64
+ visible: bool = True,
65
+ streaming: bool = False,
66
+ elem_id: str | None = None,
67
+ elem_classes: list[str] | str | None = None,
68
+ format: Literal["wav", "mp3"] = "wav",
69
+ autoplay: bool = False,
70
+ show_download_button=True,
71
+ show_share_button: bool | None = None,
72
+ **kwargs,
73
+ ):
74
+ """
75
+ Parameters:
76
+ value: A path, URL, or [sample_rate, numpy array] tuple (sample rate in Hz, audio data as a float or int numpy array) for the default value that Audio component is going to take. If callable, the function will be called whenever the app loads to set the initial value of the component.
77
+ source: Source of audio. "upload" creates a box where user can drop an audio file, "microphone" creates a microphone input.
78
+ type: The format the audio file is converted to before being passed into the prediction function. "numpy" converts the audio to a tuple consisting of: (int sample rate, numpy.array for the data), "filepath" passes a str path to a temporary file containing the audio.
79
+ label: component name in interface.
80
+ every: If `value` is a callable, run the function 'every' number of seconds while the client connection is open. Has no effect otherwise. Queue must be enabled. The event can be accessed (e.g. to cancel it) via this component's .load_event attribute.
81
+ show_label: if True, will display label.
82
+ container: If True, will place the component in a container - providing some extra padding around the border.
83
+ scale: relative width compared to adjacent Components in a Row. For example, if Component A has scale=2, and Component B has scale=1, A will be twice as wide as B. Should be an integer.
84
+ 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.
85
+ interactive: if True, will allow users to upload and edit a audio file; if False, can only be used to play audio. If not provided, this is inferred based on whether the component is used as an input or output.
86
+ visible: If False, component will be hidden.
87
+ streaming: If set to True when used in a `live` interface, will automatically stream webcam feed. Only valid is source is 'microphone'.
88
+ 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.
89
+ 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.
90
+ format: The file format to save audio files. Either 'wav' or 'mp3'. wav files are lossless but will tend to be larger files. mp3 files tend to be smaller. Default is wav. Applies both when this component is used as an input (when `type` is "format") and when this component is used as an output.
91
+ autoplay: Whether to automatically play the audio when the component is used as an output. Note: browsers will not autoplay audio files if the user has not interacted with the page yet.
92
+ show_download_button: If True, will show a download button in the corner of the component for saving audio. If False, icon does not appear.
93
+ show_share_button: If True, will show a share icon in the corner of the component that allows user to share outputs to Hugging Face Spaces Discussions. If False, icon does not appear. If set to None (default behavior), then the icon appears if this Gradio app is launched on Spaces, but not otherwise.
94
+ """
95
+ valid_sources = ["upload", "microphone"]
96
+ if source not in valid_sources:
97
+ raise ValueError(
98
+ f"Invalid value for parameter `source`: {source}. Please choose from one of: {valid_sources}"
99
+ )
100
+ self.source = source
101
+ valid_types = ["numpy", "filepath"]
102
+ if type not in valid_types:
103
+ raise ValueError(
104
+ f"Invalid value for parameter `type`: {type}. Please choose from one of: {valid_types}"
105
+ )
106
+ self.type = type
107
+ self.streaming = streaming
108
+ if streaming and source != "microphone":
109
+ raise ValueError(
110
+ "Audio streaming only available if source is 'microphone'."
111
+ )
112
+ self.format = format
113
+ self.autoplay = autoplay
114
+ self.show_download_button = show_download_button
115
+ self.show_share_button = (
116
+ (utils.get_space() is not None)
117
+ if show_share_button is None
118
+ else show_share_button
119
+ )
120
+ IOComponent.__init__(
121
+ self,
122
+ label=label,
123
+ every=every,
124
+ show_label=show_label,
125
+ container=container,
126
+ scale=scale,
127
+ min_width=min_width,
128
+ interactive=interactive,
129
+ visible=visible,
130
+ elem_id=elem_id,
131
+ elem_classes=elem_classes,
132
+ value=value,
133
+ **kwargs,
134
+ )
135
+ TokenInterpretable.__init__(self)
136
+
137
+ def get_config(self):
138
+ return {
139
+ "source": self.source,
140
+ "value": self.value,
141
+ "streaming": self.streaming,
142
+ "autoplay": self.autoplay,
143
+ "show_download_button": self.show_download_button,
144
+ "show_share_button": self.show_share_button,
145
+ **IOComponent.get_config(self),
146
+ }
147
+
148
+ def example_inputs(self) -> dict[str, Any]:
149
+ return {
150
+ "raw": {"is_file": False, "data": media_data.BASE64_AUDIO},
151
+ "serialized": "https://github.com/gradio-app/gradio/raw/main/test/test_files/audio_sample.wav",
152
+ }
153
+
154
+ @staticmethod
155
+ def update(
156
+ value: Any | Literal[_Keywords.NO_VALUE] | None = _Keywords.NO_VALUE,
157
+ source: Literal["upload", "microphone"] | None = None,
158
+ label: str | None = None,
159
+ show_label: bool | None = None,
160
+ container: bool | None = None,
161
+ scale: int | None = None,
162
+ min_width: int | None = None,
163
+ interactive: bool | None = None,
164
+ visible: bool | None = None,
165
+ autoplay: bool | None = None,
166
+ show_download_button: bool | None = None,
167
+ show_share_button: bool | None = None,
168
+ ):
169
+ return {
170
+ "source": source,
171
+ "label": label,
172
+ "show_label": show_label,
173
+ "container": container,
174
+ "scale": scale,
175
+ "min_width": min_width,
176
+ "interactive": interactive,
177
+ "visible": visible,
178
+ "value": value,
179
+ "autoplay": autoplay,
180
+ "show_download_button": show_download_button,
181
+ "show_share_button": show_share_button,
182
+ "__type__": "update",
183
+ }
184
+
185
+ def preprocess(
186
+ self, x: dict[str, Any] | None
187
+ ) -> tuple[int, np.ndarray] | str | None:
188
+ """
189
+ Parameters:
190
+ x: dictionary with keys "name", "data", "is_file", "crop_min", "crop_max".
191
+ Returns:
192
+ audio in requested format
193
+ """
194
+ if x is None:
195
+ return x
196
+ file_name, file_data, is_file = (
197
+ x["name"],
198
+ x["data"],
199
+ x.get("is_file", False),
200
+ )
201
+ crop_min, crop_max = x.get("crop_min", 0), x.get("crop_max", 100)
202
+ if is_file:
203
+ if client_utils.is_http_url_like(file_name):
204
+ temp_file_path = self.download_temp_copy_if_needed(file_name)
205
+ else:
206
+ temp_file_path = self.make_temp_copy_if_needed(file_name)
207
+ else:
208
+ temp_file_path = self.base64_to_temp_file_if_needed(file_data, file_name)
209
+
210
+ sample_rate, data = processing_utils.audio_from_file(
211
+ temp_file_path, crop_min=crop_min, crop_max=crop_max
212
+ )
213
+
214
+ # Need a unique name for the file to avoid re-using the same audio file if
215
+ # a user submits the same audio file twice, but with different crop min/max.
216
+ temp_file_path = Path(temp_file_path)
217
+ output_file_name = str(
218
+ temp_file_path.with_name(
219
+ f"{temp_file_path.stem}-{crop_min}-{crop_max}{temp_file_path.suffix}"
220
+ )
221
+ )
222
+
223
+ if self.type == "numpy":
224
+ return sample_rate, data
225
+ elif self.type == "filepath":
226
+ output_file = str(Path(output_file_name).with_suffix(f".{self.format}"))
227
+ processing_utils.audio_to_file(
228
+ sample_rate, data, output_file, format=self.format
229
+ )
230
+ return output_file
231
+ else:
232
+ raise ValueError(
233
+ "Unknown type: "
234
+ + str(self.type)
235
+ + ". Please choose from: 'numpy', 'filepath'."
236
+ )
237
+
238
+ def set_interpret_parameters(self, segments: int = 8):
239
+ """
240
+ Calculates interpretation score of audio subsections by splitting the audio into subsections, then using a "leave one out" method to calculate the score of each subsection by removing the subsection and measuring the delta of the output value.
241
+ Parameters:
242
+ segments: Number of interpretation segments to split audio into.
243
+ """
244
+ self.interpretation_segments = segments
245
+ return self
246
+
247
+ def tokenize(self, x):
248
+ if x.get("is_file"):
249
+ sample_rate, data = processing_utils.audio_from_file(x["name"])
250
+ else:
251
+ file_name = self.base64_to_temp_file_if_needed(x["data"])
252
+ sample_rate, data = processing_utils.audio_from_file(file_name)
253
+ leave_one_out_sets = []
254
+ tokens = []
255
+ masks = []
256
+ duration = data.shape[0]
257
+ boundaries = np.linspace(0, duration, self.interpretation_segments + 1).tolist()
258
+ boundaries = [round(boundary) for boundary in boundaries]
259
+ for index in range(len(boundaries) - 1):
260
+ start, stop = boundaries[index], boundaries[index + 1]
261
+ masks.append((start, stop))
262
+
263
+ # Handle the leave one outs
264
+ leave_one_out_data = np.copy(data)
265
+ leave_one_out_data[start:stop] = 0
266
+ file = tempfile.NamedTemporaryFile(
267
+ delete=False, suffix=".wav", dir=self.DEFAULT_TEMP_DIR
268
+ )
269
+ processing_utils.audio_to_file(sample_rate, leave_one_out_data, file.name)
270
+ out_data = client_utils.encode_file_to_base64(file.name)
271
+ leave_one_out_sets.append(out_data)
272
+ file.close()
273
+ Path(file.name).unlink()
274
+
275
+ # Handle the tokens
276
+ token = np.copy(data)
277
+ token[0:start] = 0
278
+ token[stop:] = 0
279
+ file = tempfile.NamedTemporaryFile(
280
+ delete=False, suffix=".wav", dir=self.DEFAULT_TEMP_DIR
281
+ )
282
+ processing_utils.audio_to_file(sample_rate, token, file.name)
283
+ token_data = client_utils.encode_file_to_base64(file.name)
284
+ file.close()
285
+ Path(file.name).unlink()
286
+
287
+ tokens.append(token_data)
288
+ tokens = [{"name": "token.wav", "data": token} for token in tokens]
289
+ leave_one_out_sets = [
290
+ {"name": "loo.wav", "data": loo_set} for loo_set in leave_one_out_sets
291
+ ]
292
+ return tokens, leave_one_out_sets, masks
293
+
294
+ def get_masked_inputs(self, tokens, binary_mask_matrix):
295
+ # create a "zero input" vector and get sample rate
296
+ x = tokens[0]["data"]
297
+ file_name = self.base64_to_temp_file_if_needed(x)
298
+ sample_rate, data = processing_utils.audio_from_file(file_name)
299
+ zero_input = np.zeros_like(data, dtype="int16")
300
+ # decode all of the tokens
301
+ token_data = []
302
+ for token in tokens:
303
+ file_name = self.base64_to_temp_file_if_needed(token["data"])
304
+ _, data = processing_utils.audio_from_file(file_name)
305
+ token_data.append(data)
306
+ # construct the masked version
307
+ masked_inputs = []
308
+ for binary_mask_vector in binary_mask_matrix:
309
+ masked_input = np.copy(zero_input)
310
+ for t, b in zip(token_data, binary_mask_vector):
311
+ masked_input = masked_input + t * int(b)
312
+ file = tempfile.NamedTemporaryFile(delete=False, dir=self.DEFAULT_TEMP_DIR)
313
+ processing_utils.audio_to_file(sample_rate, masked_input, file.name)
314
+ masked_data = client_utils.encode_file_to_base64(file.name)
315
+ file.close()
316
+ Path(file.name).unlink()
317
+ masked_inputs.append(masked_data)
318
+ return masked_inputs
319
+
320
+ def postprocess(
321
+ self, y: tuple[int, np.ndarray] | str | Path | None
322
+ ) -> str | dict | None:
323
+ """
324
+ Parameters:
325
+ y: audio data in either of the following formats: a tuple of (sample_rate, data), or a string filepath or URL to an audio file, or None.
326
+ Returns:
327
+ base64 url data
328
+ """
329
+ if y is None:
330
+ return None
331
+ if isinstance(y, str) and client_utils.is_http_url_like(y):
332
+ return {"name": y, "data": None, "is_file": True}
333
+ if isinstance(y, tuple):
334
+ sample_rate, data = y
335
+ file_path = self.audio_to_temp_file(
336
+ data, sample_rate, dir=self.DEFAULT_TEMP_DIR, format=self.format
337
+ )
338
+ self.temp_files.add(file_path)
339
+ else:
340
+ file_path = self.make_temp_copy_if_needed(y)
341
+ return {"name": file_path, "data": None, "is_file": True}
342
+
343
+ def check_streamable(self):
344
+ if self.source != "microphone":
345
+ raise ValueError(
346
+ "Audio streaming only available if source is 'microphone'."
347
+ )
348
+
349
+ def as_example(self, input_data: str | None) -> str:
350
+ return Path(input_data).name if input_data else ""
gradio/components/bar_plot.py ADDED
@@ -0,0 +1,376 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """gr.BarPlot() component."""
2
+
3
+ from __future__ import annotations
4
+
5
+ from typing import Callable, Literal
6
+
7
+ import altair as alt
8
+ import pandas as pd
9
+ from gradio_client.documentation import document, set_documentation_group
10
+
11
+ from gradio.components.base import _Keywords
12
+ from gradio.components.plot import AltairPlot, Plot
13
+
14
+ set_documentation_group("component")
15
+
16
+
17
+ @document()
18
+ class BarPlot(Plot):
19
+ """
20
+ Create a bar plot.
21
+
22
+ Preprocessing: this component does *not* accept input.
23
+ Postprocessing: expects a pandas dataframe with the data to plot.
24
+
25
+ Demos: bar_plot, chicago-bikeshare-dashboard
26
+ """
27
+
28
+ def __init__(
29
+ self,
30
+ value: pd.DataFrame | Callable | None = None,
31
+ x: str | None = None,
32
+ y: str | None = None,
33
+ *,
34
+ color: str | None = None,
35
+ vertical: bool = True,
36
+ group: str | None = None,
37
+ title: str | None = None,
38
+ tooltip: list[str] | str | None = None,
39
+ x_title: str | None = None,
40
+ y_title: str | None = None,
41
+ color_legend_title: str | None = None,
42
+ group_title: str | None = None,
43
+ color_legend_position: Literal[
44
+ "left",
45
+ "right",
46
+ "top",
47
+ "bottom",
48
+ "top-left",
49
+ "top-right",
50
+ "bottom-left",
51
+ "bottom-right",
52
+ "none",
53
+ ]
54
+ | None = None,
55
+ height: int | None = None,
56
+ width: int | None = None,
57
+ y_lim: list[int] | None = None,
58
+ caption: str | None = None,
59
+ interactive: bool | None = True,
60
+ label: str | None = None,
61
+ show_label: bool | None = None,
62
+ container: bool = True,
63
+ scale: int | None = None,
64
+ min_width: int = 160,
65
+ every: float | None = None,
66
+ visible: bool = True,
67
+ elem_id: str | None = None,
68
+ elem_classes: list[str] | str | None = None,
69
+ ):
70
+ """
71
+ Parameters:
72
+ value: The pandas dataframe containing the data to display in a scatter plot.
73
+ x: Column corresponding to the x axis.
74
+ y: Column corresponding to the y axis.
75
+ color: The column to determine the bar color. Must be categorical (discrete values).
76
+ vertical: If True, the bars will be displayed vertically. If False, the x and y axis will be switched, displaying the bars horizontally. Default is True.
77
+ group: The column with which to split the overall plot into smaller subplots.
78
+ title: The title to display on top of the chart.
79
+ tooltip: The column (or list of columns) to display on the tooltip when a user hovers over a bar.
80
+ x_title: The title given to the x axis. By default, uses the value of the x parameter.
81
+ y_title: The title given to the y axis. By default, uses the value of the y parameter.
82
+ color_legend_title: The title given to the color legend. By default, uses the value of color parameter.
83
+ group_title: The label displayed on top of the subplot columns (or rows if vertical=True). Use an empty string to omit.
84
+ color_legend_position: The position of the color legend. If the string value 'none' is passed, this legend is omitted. For other valid position values see: https://vega.github.io/vega/docs/legends/#orientation.
85
+ height: The height of the plot in pixels.
86
+ width: The width of the plot in pixels.
87
+ y_lim: A tuple of list containing the limits for the y-axis, specified as [y_min, y_max].
88
+ caption: The (optional) caption to display below the plot.
89
+ interactive: Whether users should be able to interact with the plot by panning or zooming with their mouse or trackpad.
90
+ label: The (optional) label to display on the top left corner of the plot.
91
+ show_label: Whether the label should be displayed.
92
+ every: If `value` is a callable, run the function 'every' number of seconds while the client connection is open. Has no effect otherwise. Queue must be enabled. The event can be accessed (e.g. to cancel it) via this component's .load_event attribute.
93
+ visible: Whether the plot should be visible.
94
+ 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.
95
+ 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.
96
+ """
97
+ self.x = x
98
+ self.y = y
99
+ self.color = color
100
+ self.vertical = vertical
101
+ self.group = group
102
+ self.group_title = group_title
103
+ self.tooltip = tooltip
104
+ self.title = title
105
+ self.x_title = x_title
106
+ self.y_title = y_title
107
+ self.color_legend_title = color_legend_title
108
+ self.group_title = group_title
109
+ self.color_legend_position = color_legend_position
110
+ self.y_lim = y_lim
111
+ self.caption = caption
112
+ self.interactive_chart = interactive
113
+ self.width = width
114
+ self.height = height
115
+ super().__init__(
116
+ value=value,
117
+ label=label,
118
+ show_label=show_label,
119
+ container=container,
120
+ scale=scale,
121
+ min_width=min_width,
122
+ visible=visible,
123
+ elem_id=elem_id,
124
+ elem_classes=elem_classes,
125
+ every=every,
126
+ )
127
+
128
+ def get_config(self):
129
+ config = super().get_config()
130
+ config["caption"] = self.caption
131
+ return config
132
+
133
+ def get_block_name(self) -> str:
134
+ return "plot"
135
+
136
+ @staticmethod
137
+ def update(
138
+ value: pd.DataFrame | dict | Literal[_Keywords.NO_VALUE] = _Keywords.NO_VALUE,
139
+ x: str | None = None,
140
+ y: str | None = None,
141
+ color: str | None = None,
142
+ vertical: bool = True,
143
+ group: str | None = None,
144
+ title: str | None = None,
145
+ tooltip: list[str] | str | None = None,
146
+ x_title: str | None = None,
147
+ y_title: str | None = None,
148
+ color_legend_title: str | None = None,
149
+ group_title: str | None = None,
150
+ color_legend_position: Literal[
151
+ "left",
152
+ "right",
153
+ "top",
154
+ "bottom",
155
+ "top-left",
156
+ "top-right",
157
+ "bottom-left",
158
+ "bottom-right",
159
+ "none",
160
+ ]
161
+ | None = None,
162
+ height: int | None = None,
163
+ width: int | None = None,
164
+ y_lim: list[int] | None = None,
165
+ caption: str | None = None,
166
+ interactive: bool | None = None,
167
+ label: str | None = None,
168
+ show_label: bool | None = None,
169
+ container: bool | None = None,
170
+ scale: int | None = None,
171
+ min_width: int | None = None,
172
+ visible: bool | None = None,
173
+ ):
174
+ """Update an existing BarPlot component.
175
+
176
+ If updating any of the plot properties (color, size, etc) the value, x, and y parameters must be specified.
177
+
178
+ Parameters:
179
+ value: The pandas dataframe containing the data to display in a scatter plot.
180
+ x: Column corresponding to the x axis.
181
+ y: Column corresponding to the y axis.
182
+ color: The column to determine the bar color. Must be categorical (discrete values).
183
+ vertical: If True, the bars will be displayed vertically. If False, the x and y axis will be switched, displaying the bars horizontally. Default is True.
184
+ group: The column with which to split the overall plot into smaller subplots.
185
+ title: The title to display on top of the chart.
186
+ tooltip: The column (or list of columns) to display on the tooltip when a user hovers over a bar.
187
+ x_title: The title given to the x axis. By default, uses the value of the x parameter.
188
+ y_title: The title given to the y axis. By default, uses the value of the y parameter.
189
+ color_legend_title: The title given to the color legend. By default, uses the value of color parameter.
190
+ group_title: The label displayed on top of the subplot columns (or rows if vertical=True). Use an empty string to omit.
191
+ color_legend_position: The position of the color legend. If the string value 'none' is passed, this legend is omitted. For other valid position values see: https://vega.github.io/vega/docs/legends/#orientation.
192
+ height: The height of the plot in pixels.
193
+ width: The width of the plot in pixels.
194
+ y_lim: A tuple of list containing the limits for the y-axis, specified as [y_min, y_max].
195
+ caption: The (optional) caption to display below the plot.
196
+ interactive: Whether users should be able to interact with the plot by panning or zooming with their mouse or trackpad.
197
+ label: The (optional) label to display on the top left corner of the plot.
198
+ show_label: Whether the label should be displayed.
199
+ visible: Whether the plot should be visible.
200
+ """
201
+ properties = [
202
+ x,
203
+ y,
204
+ color,
205
+ vertical,
206
+ group,
207
+ title,
208
+ tooltip,
209
+ x_title,
210
+ y_title,
211
+ color_legend_title,
212
+ group_title,
213
+ color_legend_position,
214
+ height,
215
+ width,
216
+ y_lim,
217
+ interactive,
218
+ ]
219
+ if any(properties):
220
+ if not isinstance(value, pd.DataFrame):
221
+ raise ValueError(
222
+ "In order to update plot properties the value parameter "
223
+ "must be provided, and it must be a Dataframe. Please pass a value "
224
+ "parameter to gr.BarPlot.update."
225
+ )
226
+ if x is None or y is None:
227
+ raise ValueError(
228
+ "In order to update plot properties, the x and y axis data "
229
+ "must be specified. Please pass valid values for x an y to "
230
+ "gr.BarPlot.update."
231
+ )
232
+ chart = BarPlot.create_plot(value, *properties)
233
+ value = {"type": "altair", "plot": chart.to_json(), "chart": "bar"}
234
+
235
+ updated_config = {
236
+ "label": label,
237
+ "show_label": show_label,
238
+ "container": container,
239
+ "scale": scale,
240
+ "min_width": min_width,
241
+ "visible": visible,
242
+ "value": value,
243
+ "caption": caption,
244
+ "__type__": "update",
245
+ }
246
+ return updated_config
247
+
248
+ @staticmethod
249
+ def create_plot(
250
+ value: pd.DataFrame,
251
+ x: str,
252
+ y: str,
253
+ color: str | None = None,
254
+ vertical: bool = True,
255
+ group: str | None = None,
256
+ title: str | None = None,
257
+ tooltip: list[str] | str | None = None,
258
+ x_title: str | None = None,
259
+ y_title: str | None = None,
260
+ color_legend_title: str | None = None,
261
+ group_title: str | None = None,
262
+ color_legend_position: Literal[
263
+ "left",
264
+ "right",
265
+ "top",
266
+ "bottom",
267
+ "top-left",
268
+ "top-right",
269
+ "bottom-left",
270
+ "bottom-right",
271
+ "none",
272
+ ]
273
+ | None = None,
274
+ height: int | None = None,
275
+ width: int | None = None,
276
+ y_lim: list[int] | None = None,
277
+ interactive: bool | None = True,
278
+ ):
279
+ """Helper for creating the bar plot."""
280
+ interactive = True if interactive is None else interactive
281
+ orientation = (
282
+ {"field": group, "title": group_title if group_title is not None else group}
283
+ if group
284
+ else {}
285
+ )
286
+
287
+ x_title = x_title or x
288
+ y_title = y_title or y
289
+
290
+ # If horizontal, switch x and y
291
+ if not vertical:
292
+ y, x = x, y
293
+ x = f"sum({x}):Q"
294
+ y_title, x_title = x_title, y_title
295
+ orientation = {"row": alt.Row(**orientation)} if orientation else {} # type: ignore
296
+ x_lim = y_lim
297
+ y_lim = None
298
+ else:
299
+ y = f"sum({y}):Q"
300
+ x_lim = None
301
+ orientation = {"column": alt.Column(**orientation)} if orientation else {} # type: ignore
302
+
303
+ encodings = dict(
304
+ x=alt.X(
305
+ x, # type: ignore
306
+ title=x_title, # type: ignore
307
+ scale=AltairPlot.create_scale(x_lim), # type: ignore
308
+ ),
309
+ y=alt.Y(
310
+ y, # type: ignore
311
+ title=y_title, # type: ignore
312
+ scale=AltairPlot.create_scale(y_lim), # type: ignore
313
+ ),
314
+ **orientation,
315
+ )
316
+ properties = {}
317
+ if title:
318
+ properties["title"] = title
319
+ if height:
320
+ properties["height"] = height
321
+ if width:
322
+ properties["width"] = width
323
+
324
+ if color:
325
+ domain = value[color].unique().tolist()
326
+ range_ = list(range(len(domain)))
327
+ encodings["color"] = {
328
+ "field": color,
329
+ "type": "nominal",
330
+ "scale": {"domain": domain, "range": range_},
331
+ "legend": AltairPlot.create_legend(
332
+ position=color_legend_position, title=color_legend_title or color
333
+ ),
334
+ }
335
+
336
+ if tooltip:
337
+ encodings["tooltip"] = tooltip
338
+
339
+ chart = (
340
+ alt.Chart(value) # type: ignore
341
+ .mark_bar() # type: ignore
342
+ .encode(**encodings)
343
+ .properties(background="transparent", **properties)
344
+ )
345
+ if interactive:
346
+ chart = chart.interactive()
347
+
348
+ return chart
349
+
350
+ def postprocess(self, y: pd.DataFrame | dict | None) -> dict[str, str] | None:
351
+ # if None or update
352
+ if y is None or isinstance(y, dict):
353
+ return y
354
+ if self.x is None or self.y is None:
355
+ raise ValueError("No value provided for required parameters `x` and `y`.")
356
+ chart = self.create_plot(
357
+ value=y,
358
+ x=self.x,
359
+ y=self.y,
360
+ color=self.color,
361
+ vertical=self.vertical,
362
+ group=self.group,
363
+ title=self.title,
364
+ tooltip=self.tooltip,
365
+ x_title=self.x_title,
366
+ y_title=self.y_title,
367
+ color_legend_title=self.color_legend_title,
368
+ color_legend_position=self.color_legend_position, # type: ignore
369
+ group_title=self.group_title,
370
+ y_lim=self.y_lim,
371
+ interactive=self.interactive_chart,
372
+ height=self.height,
373
+ width=self.width,
374
+ )
375
+
376
+ return {"type": "altair", "plot": chart.to_json(), "chart": "bar"}
gradio/components/base.py ADDED
@@ -0,0 +1,407 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Contains all of the components that can be used with Gradio Interface / Blocks.
2
+ Along with the docs for each component, you can find the names of example demos that use
3
+ each component. These demos are located in the `demo` directory."""
4
+
5
+ from __future__ import annotations
6
+
7
+ import hashlib
8
+ import os
9
+ import secrets
10
+ import shutil
11
+ import tempfile
12
+ import urllib.request
13
+ from enum import Enum
14
+ from pathlib import Path
15
+ from typing import TYPE_CHECKING, Any, Callable
16
+
17
+ import aiofiles
18
+ import numpy as np
19
+ import requests
20
+ from fastapi import UploadFile
21
+ from gradio_client import utils as client_utils
22
+ from gradio_client.documentation import set_documentation_group
23
+ from gradio_client.serializing import (
24
+ Serializable,
25
+ )
26
+ from PIL import Image as _Image # using _ to minimize namespace pollution
27
+
28
+ from gradio import processing_utils, utils
29
+ from gradio.blocks import Block, BlockContext
30
+ from gradio.deprecation import warn_deprecation, warn_style_method_deprecation
31
+ from gradio.events import (
32
+ EventListener,
33
+ )
34
+ from gradio.layouts import Column, Form, Row
35
+
36
+ if TYPE_CHECKING:
37
+ from typing import TypedDict
38
+
39
+ class DataframeData(TypedDict):
40
+ headers: list[str]
41
+ data: list[list[str | int | bool]]
42
+
43
+
44
+ set_documentation_group("component")
45
+ _Image.init() # fixes https://github.com/gradio-app/gradio/issues/2843
46
+
47
+
48
+ class _Keywords(Enum):
49
+ NO_VALUE = "NO_VALUE" # Used as a sentinel to determine if nothing is provided as a argument for `value` in `Component.update()`
50
+ FINISHED_ITERATING = "FINISHED_ITERATING" # Used to skip processing of a component's value (needed for generators + state)
51
+
52
+
53
+ class Component(Block, Serializable):
54
+ """
55
+ A base class for defining the methods that all gradio components should have.
56
+ """
57
+
58
+ def __init__(self, *args, **kwargs):
59
+ Block.__init__(self, *args, **kwargs)
60
+ EventListener.__init__(self)
61
+
62
+ def __str__(self):
63
+ return self.__repr__()
64
+
65
+ def __repr__(self):
66
+ return f"{self.get_block_name()}"
67
+
68
+ def get_config(self):
69
+ """
70
+ :return: a dictionary with context variables for the javascript file associated with the context
71
+ """
72
+ return {
73
+ "name": self.get_block_name(),
74
+ **super().get_config(),
75
+ }
76
+
77
+ def preprocess(self, x: Any) -> Any:
78
+ """
79
+ Any preprocessing needed to be performed on function input.
80
+ """
81
+ return x
82
+
83
+ def postprocess(self, y):
84
+ """
85
+ Any postprocessing needed to be performed on function output.
86
+ """
87
+ return y
88
+
89
+ def style(self, *args, **kwargs):
90
+ """
91
+ This method is deprecated. Please set these arguments in the Components constructor instead.
92
+ """
93
+ warn_style_method_deprecation()
94
+ put_deprecated_params_in_box = False
95
+ if "rounded" in kwargs:
96
+ warn_deprecation(
97
+ "'rounded' styling is no longer supported. To round adjacent components together, place them in a Column(variant='box')."
98
+ )
99
+ if isinstance(kwargs["rounded"], (list, tuple)):
100
+ put_deprecated_params_in_box = True
101
+ kwargs.pop("rounded")
102
+ if "margin" in kwargs:
103
+ warn_deprecation(
104
+ "'margin' styling is no longer supported. To place adjacent components together without margin, place them in a Column(variant='box')."
105
+ )
106
+ if isinstance(kwargs["margin"], (list, tuple)):
107
+ put_deprecated_params_in_box = True
108
+ kwargs.pop("margin")
109
+ if "border" in kwargs:
110
+ warn_deprecation(
111
+ "'border' styling is no longer supported. To place adjacent components in a shared border, place them in a Column(variant='box')."
112
+ )
113
+ kwargs.pop("border")
114
+ for key in kwargs:
115
+ warn_deprecation(f"Unknown style parameter: {key}")
116
+ if (
117
+ put_deprecated_params_in_box
118
+ and isinstance(self.parent, (Row, Column))
119
+ and self.parent.variant == "default"
120
+ ):
121
+ self.parent.variant = "compact"
122
+ return self
123
+
124
+
125
+ class IOComponent(Component):
126
+ """
127
+ A base class for defining methods that all input/output components should have.
128
+ """
129
+
130
+ def __init__(
131
+ self,
132
+ *,
133
+ value: Any = None,
134
+ label: str | None = None,
135
+ info: str | None = None,
136
+ show_label: bool | None = None,
137
+ container: bool = True,
138
+ scale: int | None = None,
139
+ min_width: int | None = None,
140
+ interactive: bool | None = None,
141
+ visible: bool = True,
142
+ elem_id: str | None = None,
143
+ elem_classes: list[str] | str | None = None,
144
+ load_fn: Callable | None = None,
145
+ every: float | None = None,
146
+ **kwargs,
147
+ ):
148
+ self.temp_files: set[str] = set()
149
+ self.DEFAULT_TEMP_DIR = os.environ.get("GRADIO_TEMP_DIR") or str(
150
+ Path(tempfile.gettempdir()) / "gradio"
151
+ )
152
+
153
+ Component.__init__(
154
+ self, elem_id=elem_id, elem_classes=elem_classes, visible=visible, **kwargs
155
+ )
156
+
157
+ self.label = label
158
+ self.info = info
159
+ if not container:
160
+ if show_label:
161
+ warn_deprecation("show_label has no effect when container is False.")
162
+ show_label = False
163
+ if show_label is None:
164
+ show_label = True
165
+ self.show_label = show_label
166
+ self.container = container
167
+ if scale is not None and scale != round(scale):
168
+ warn_deprecation(
169
+ f"'scale' value should be an integer. Using {scale} will cause issues."
170
+ )
171
+ self.scale = scale
172
+ self.min_width = min_width
173
+ self.interactive = interactive
174
+
175
+ # load_event is set in the Blocks.attach_load_events method
176
+ self.load_event: None | dict[str, Any] = None
177
+ self.load_event_to_attach = None
178
+ load_fn, initial_value = self.get_load_fn_and_initial_value(value)
179
+ self.value = (
180
+ initial_value
181
+ if self._skip_init_processing
182
+ else self.postprocess(initial_value)
183
+ )
184
+ if callable(load_fn):
185
+ self.attach_load_event(load_fn, every)
186
+
187
+ @staticmethod
188
+ def hash_file(file_path: str | Path, chunk_num_blocks: int = 128) -> str:
189
+ sha1 = hashlib.sha1()
190
+ with open(file_path, "rb") as f:
191
+ for chunk in iter(lambda: f.read(chunk_num_blocks * sha1.block_size), b""):
192
+ sha1.update(chunk)
193
+ return sha1.hexdigest()
194
+
195
+ @staticmethod
196
+ def hash_url(url: str, chunk_num_blocks: int = 128) -> str:
197
+ sha1 = hashlib.sha1()
198
+ remote = urllib.request.urlopen(url)
199
+ max_file_size = 100 * 1024 * 1024 # 100MB
200
+ total_read = 0
201
+ while True:
202
+ data = remote.read(chunk_num_blocks * sha1.block_size)
203
+ total_read += chunk_num_blocks * sha1.block_size
204
+ if not data or total_read > max_file_size:
205
+ break
206
+ sha1.update(data)
207
+ return sha1.hexdigest()
208
+
209
+ @staticmethod
210
+ def hash_bytes(bytes: bytes):
211
+ sha1 = hashlib.sha1()
212
+ sha1.update(bytes)
213
+ return sha1.hexdigest()
214
+
215
+ @staticmethod
216
+ def hash_base64(base64_encoding: str, chunk_num_blocks: int = 128) -> str:
217
+ sha1 = hashlib.sha1()
218
+ for i in range(0, len(base64_encoding), chunk_num_blocks * sha1.block_size):
219
+ data = base64_encoding[i : i + chunk_num_blocks * sha1.block_size]
220
+ sha1.update(data.encode("utf-8"))
221
+ return sha1.hexdigest()
222
+
223
+ def make_temp_copy_if_needed(self, file_path: str | Path) -> str:
224
+ """Returns a temporary file path for a copy of the given file path if it does
225
+ not already exist. Otherwise returns the path to the existing temp file."""
226
+ temp_dir = self.hash_file(file_path)
227
+ temp_dir = Path(self.DEFAULT_TEMP_DIR) / temp_dir
228
+ temp_dir.mkdir(exist_ok=True, parents=True)
229
+
230
+ name = client_utils.strip_invalid_filename_characters(Path(file_path).name)
231
+ full_temp_file_path = str(utils.abspath(temp_dir / name))
232
+
233
+ if not Path(full_temp_file_path).exists():
234
+ shutil.copy2(file_path, full_temp_file_path)
235
+
236
+ self.temp_files.add(full_temp_file_path)
237
+ return full_temp_file_path
238
+
239
+ async def save_uploaded_file(self, file: UploadFile, upload_dir: str) -> str:
240
+ temp_dir = secrets.token_hex(
241
+ 20
242
+ ) # Since the full file is being uploaded anyways, there is no benefit to hashing the file.
243
+ temp_dir = Path(upload_dir) / temp_dir
244
+ temp_dir.mkdir(exist_ok=True, parents=True)
245
+
246
+ if file.filename:
247
+ file_name = Path(file.filename).name
248
+ name = client_utils.strip_invalid_filename_characters(file_name)
249
+ else:
250
+ name = f"tmp{secrets.token_hex(5)}"
251
+
252
+ full_temp_file_path = str(utils.abspath(temp_dir / name))
253
+
254
+ async with aiofiles.open(full_temp_file_path, "wb") as output_file:
255
+ while True:
256
+ content = await file.read(100 * 1024 * 1024)
257
+ if not content:
258
+ break
259
+ await output_file.write(content)
260
+
261
+ return full_temp_file_path
262
+
263
+ def download_temp_copy_if_needed(self, url: str) -> str:
264
+ """Downloads a file and makes a temporary file path for a copy if does not already
265
+ exist. Otherwise returns the path to the existing temp file."""
266
+ temp_dir = self.hash_url(url)
267
+ temp_dir = Path(self.DEFAULT_TEMP_DIR) / temp_dir
268
+ temp_dir.mkdir(exist_ok=True, parents=True)
269
+
270
+ name = client_utils.strip_invalid_filename_characters(Path(url).name)
271
+ full_temp_file_path = str(utils.abspath(temp_dir / name))
272
+
273
+ if not Path(full_temp_file_path).exists():
274
+ with requests.get(url, stream=True) as r, open(
275
+ full_temp_file_path, "wb"
276
+ ) as f:
277
+ shutil.copyfileobj(r.raw, f)
278
+
279
+ self.temp_files.add(full_temp_file_path)
280
+ return full_temp_file_path
281
+
282
+ def base64_to_temp_file_if_needed(
283
+ self, base64_encoding: str, file_name: str | None = None
284
+ ) -> str:
285
+ """Converts a base64 encoding to a file and returns the path to the file if
286
+ the file doesn't already exist. Otherwise returns the path to the existing file.
287
+ """
288
+ temp_dir = self.hash_base64(base64_encoding)
289
+ temp_dir = Path(self.DEFAULT_TEMP_DIR) / temp_dir
290
+ temp_dir.mkdir(exist_ok=True, parents=True)
291
+
292
+ guess_extension = client_utils.get_extension(base64_encoding)
293
+ if file_name:
294
+ file_name = client_utils.strip_invalid_filename_characters(file_name)
295
+ elif guess_extension:
296
+ file_name = f"file.{guess_extension}"
297
+ else:
298
+ file_name = "file"
299
+
300
+ full_temp_file_path = str(utils.abspath(temp_dir / file_name)) # type: ignore
301
+
302
+ if not Path(full_temp_file_path).exists():
303
+ data, _ = client_utils.decode_base64_to_binary(base64_encoding)
304
+ with open(full_temp_file_path, "wb") as fb:
305
+ fb.write(data)
306
+
307
+ self.temp_files.add(full_temp_file_path)
308
+ return full_temp_file_path
309
+
310
+ def pil_to_temp_file(self, img: _Image.Image, dir: str, format="png") -> str:
311
+ bytes_data = processing_utils.encode_pil_to_bytes(img, format)
312
+ temp_dir = Path(dir) / self.hash_bytes(bytes_data)
313
+ temp_dir.mkdir(exist_ok=True, parents=True)
314
+ filename = str(temp_dir / f"image.{format}")
315
+ img.save(filename, pnginfo=processing_utils.get_pil_metadata(img))
316
+ return filename
317
+
318
+ def img_array_to_temp_file(self, arr: np.ndarray, dir: str) -> str:
319
+ pil_image = _Image.fromarray(
320
+ processing_utils._convert(arr, np.uint8, force_copy=False)
321
+ )
322
+ return self.pil_to_temp_file(pil_image, dir, format="png")
323
+
324
+ def audio_to_temp_file(
325
+ self, data: np.ndarray, sample_rate: int, dir: str, format: str
326
+ ):
327
+ temp_dir = Path(dir) / self.hash_bytes(data.tobytes())
328
+ temp_dir.mkdir(exist_ok=True, parents=True)
329
+ filename = str(temp_dir / f"audio.{format}")
330
+ processing_utils.audio_to_file(sample_rate, data, filename, format=format)
331
+ return filename
332
+
333
+ def file_bytes_to_file(self, data: bytes, dir: str, file_name: str):
334
+ path = Path(dir) / self.hash_bytes(data)
335
+ path.mkdir(exist_ok=True, parents=True)
336
+ path = path / Path(file_name).name
337
+ path.write_bytes(data)
338
+ return path
339
+
340
+ def get_config(self):
341
+ config = {
342
+ "label": self.label,
343
+ "show_label": self.show_label,
344
+ "container": self.container,
345
+ "scale": self.scale,
346
+ "min_width": self.min_width,
347
+ "interactive": self.interactive,
348
+ **super().get_config(),
349
+ }
350
+ if self.info:
351
+ config["info"] = self.info
352
+ return config
353
+
354
+ @staticmethod
355
+ def get_load_fn_and_initial_value(value):
356
+ if callable(value):
357
+ initial_value = value()
358
+ load_fn = value
359
+ else:
360
+ initial_value = value
361
+ load_fn = None
362
+ return load_fn, initial_value
363
+
364
+ def attach_load_event(self, callable: Callable, every: float | None):
365
+ """Add a load event that runs `callable`, optionally every `every` seconds."""
366
+ self.load_event_to_attach = (callable, every)
367
+
368
+ def as_example(self, input_data):
369
+ """Return the input data in a way that can be displayed by the examples dataset component in the front-end."""
370
+ return input_data
371
+
372
+
373
+ class FormComponent:
374
+ def get_expected_parent(self) -> type[Form] | None:
375
+ if getattr(self, "container", None) is False:
376
+ return None
377
+ return Form
378
+
379
+
380
+ def component(cls_name: str) -> Component:
381
+ obj = utils.component_or_layout_class(cls_name)()
382
+ if isinstance(obj, BlockContext):
383
+ raise ValueError(f"Invalid component: {obj.__class__}")
384
+ return obj
385
+
386
+
387
+ def get_component_instance(comp: str | dict | Component, render=True) -> Component:
388
+ if isinstance(comp, str):
389
+ component_obj = component(comp)
390
+ if not (render):
391
+ component_obj.unrender()
392
+ return component_obj
393
+ elif isinstance(comp, dict):
394
+ name = comp.pop("name")
395
+ component_cls = utils.component_or_layout_class(name)
396
+ component_obj = component_cls(**comp)
397
+ if isinstance(component_obj, BlockContext):
398
+ raise ValueError(f"Invalid component: {name}")
399
+ if not (render):
400
+ component_obj.unrender()
401
+ return component_obj
402
+ elif isinstance(comp, Component):
403
+ return comp
404
+ else:
405
+ raise ValueError(
406
+ f"Component must provided as a `str` or `dict` or `Component` but is {comp}"
407
+ )
gradio/components/button.py ADDED
@@ -0,0 +1,121 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """gr.Button() component."""
2
+
3
+ from __future__ import annotations
4
+
5
+ from typing import Callable, Literal
6
+
7
+ from gradio_client.documentation import document, set_documentation_group
8
+ from gradio_client.serializing import StringSerializable
9
+
10
+ from gradio.components.base import Component, IOComponent, _Keywords
11
+ from gradio.deprecation import warn_deprecation, warn_style_method_deprecation
12
+ from gradio.events import Clickable
13
+
14
+ set_documentation_group("component")
15
+
16
+
17
+ @document()
18
+ class Button(Clickable, IOComponent, StringSerializable):
19
+ """
20
+ Used to create a button, that can be assigned arbitrary click() events. The label (value) of the button can be used as an input or set via the output of a function.
21
+
22
+ Preprocessing: passes the button value as a {str} into the function
23
+ Postprocessing: expects a {str} to be returned from a function, which is set as the label of the button
24
+ Demos: blocks_inputs, blocks_kinematics
25
+ """
26
+
27
+ def __init__(
28
+ self,
29
+ value: str | Callable = "Run",
30
+ *,
31
+ variant: Literal["primary", "secondary", "stop"] = "secondary",
32
+ size: Literal["sm", "lg"] | None = None,
33
+ visible: bool = True,
34
+ interactive: bool = True,
35
+ elem_id: str | None = None,
36
+ elem_classes: list[str] | str | None = None,
37
+ scale: int | None = None,
38
+ min_width: int | None = None,
39
+ **kwargs,
40
+ ):
41
+ """
42
+ Parameters:
43
+ value: Default text for the button to display. If callable, the function will be called whenever the app loads to set the initial value of the component.
44
+ variant: 'primary' for main call-to-action, 'secondary' for a more subdued style, 'stop' for a stop button.
45
+ size: Size of the button. Can be "sm" or "lg".
46
+ visible: If False, component will be hidden.
47
+ interactive: If False, the Button will be in a disabled state.
48
+ 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.
49
+ 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.
50
+ scale: relative width compared to adjacent Components in a Row. For example, if Component A has scale=2, and Component B has scale=1, A will be twice as wide as B. Should be an integer.
51
+ 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.
52
+ """
53
+ IOComponent.__init__(
54
+ self,
55
+ visible=visible,
56
+ elem_id=elem_id,
57
+ elem_classes=elem_classes,
58
+ value=value,
59
+ interactive=interactive,
60
+ scale=scale,
61
+ min_width=min_width,
62
+ **kwargs,
63
+ )
64
+ if variant == "plain":
65
+ warn_deprecation("'plain' variant deprecated, using 'secondary' instead.")
66
+ variant = "secondary"
67
+ self.variant = variant
68
+ self.size = size
69
+
70
+ def get_config(self):
71
+ return {
72
+ "value": self.value,
73
+ "variant": self.variant,
74
+ "size": self.size,
75
+ "interactive": self.interactive,
76
+ "scale": self.scale,
77
+ "min_width": self.min_width,
78
+ **Component.get_config(self),
79
+ }
80
+
81
+ @staticmethod
82
+ def update(
83
+ value: str | Literal[_Keywords.NO_VALUE] | None = _Keywords.NO_VALUE,
84
+ variant: Literal["primary", "secondary", "stop"] | None = None,
85
+ size: Literal["sm", "lg"] | None = None,
86
+ visible: bool | None = None,
87
+ interactive: bool | None = None,
88
+ scale: int | None = None,
89
+ min_width: int | None = None,
90
+ ):
91
+ return {
92
+ "variant": variant,
93
+ "size": size,
94
+ "visible": visible,
95
+ "value": value,
96
+ "interactive": interactive,
97
+ "scale": scale,
98
+ "min_width": min_width,
99
+ "__type__": "update",
100
+ }
101
+
102
+ def style(
103
+ self,
104
+ *,
105
+ full_width: bool | None = None,
106
+ size: Literal["sm", "lg"] | None = None,
107
+ **kwargs,
108
+ ):
109
+ """
110
+ This method is deprecated. Please set these arguments in the constructor instead.
111
+ """
112
+ warn_style_method_deprecation()
113
+ if full_width is not None:
114
+ warn_deprecation(
115
+ "Use `scale` in place of full_width in the constructor. "
116
+ "scale=1 will make the button expand, whereas 0 will not."
117
+ )
118
+ self.scale = 1 if full_width else None
119
+ if size is not None:
120
+ self.size = size
121
+ return self
gradio/components/carousel.py ADDED
@@ -0,0 +1,22 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """gr.Carousel() component."""
2
+
3
+ from gradio_client.serializing import SimpleSerializable
4
+
5
+ from gradio.components.base import IOComponent
6
+ from gradio.events import Changeable
7
+
8
+
9
+ class Carousel(IOComponent, Changeable, SimpleSerializable):
10
+ """
11
+ Deprecated Component
12
+ """
13
+
14
+ def __init__(
15
+ self,
16
+ *args,
17
+ **kwargs,
18
+ ):
19
+ raise DeprecationWarning(
20
+ "The Carousel component is deprecated. Please consider using the Gallery "
21
+ "component, which can be used to display images (and optional captions).",
22
+ )
gradio/components/chatbot.py ADDED
@@ -0,0 +1,247 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """gr.Chatbot() component."""
2
+
3
+ from __future__ import annotations
4
+
5
+ import inspect
6
+ from pathlib import Path
7
+ from typing import Callable, Literal
8
+
9
+ from gradio_client import utils as client_utils
10
+ from gradio_client.documentation import document, set_documentation_group
11
+ from gradio_client.serializing import JSONSerializable
12
+
13
+ from gradio import utils
14
+ from gradio.components.base import IOComponent, _Keywords
15
+ from gradio.deprecation import warn_deprecation, warn_style_method_deprecation
16
+ from gradio.events import (
17
+ Changeable,
18
+ EventListenerMethod,
19
+ Selectable,
20
+ )
21
+
22
+ set_documentation_group("component")
23
+
24
+
25
+ @document()
26
+ class Chatbot(Changeable, Selectable, IOComponent, JSONSerializable):
27
+ """
28
+ Displays a chatbot output showing both user submitted messages and responses. Supports a subset of Markdown including bold, italics, code, tables. Also supports audio/video/image files, which are displayed in the Chatbot, and other kinds of files which are displayed as links.
29
+ Preprocessing: passes the messages in the Chatbot as a {List[List[str | None | Tuple]]}, i.e. a list of lists. The inner list has 2 elements: the user message and the response message. See `Postprocessing` for the format of these messages.
30
+ Postprocessing: expects function to return a {List[List[str | None | Tuple]]}, i.e. a list of lists. The inner list should have 2 elements: the user message and the response message. The individual messages can be (1) strings in valid Markdown, (2) tuples if sending files: (a filepath or URL to a file, [optional string alt text]) -- if the file is image/video/audio, it is displayed in the Chatbot, or (3) None, in which case the message is not displayed.
31
+
32
+ Demos: chatbot_simple, chatbot_multimodal
33
+ Guides: creating-a-chatbot
34
+ """
35
+
36
+ def __init__(
37
+ self,
38
+ value: list[list[str | tuple[str] | tuple[str | Path, str] | None]]
39
+ | Callable
40
+ | None = None,
41
+ color_map: dict[str, str] | None = None,
42
+ *,
43
+ label: str | None = None,
44
+ every: float | None = None,
45
+ show_label: bool | None = None,
46
+ container: bool = True,
47
+ scale: int | None = None,
48
+ min_width: int = 160,
49
+ visible: bool = True,
50
+ elem_id: str | None = None,
51
+ elem_classes: list[str] | str | None = None,
52
+ height: int | None = None,
53
+ latex_delimiters: list[dict[str, str | bool]] | None = None,
54
+ rtl: bool = False,
55
+ show_share_button: bool | None = None,
56
+ **kwargs,
57
+ ):
58
+ """
59
+ Parameters:
60
+ value: Default value to show in chatbot. If callable, the function will be called whenever the app loads to set the initial value of the component.
61
+ color_map: This parameter is deprecated.
62
+ label: component name in interface.
63
+ every: If `value` is a callable, run the function 'every' number of seconds while the client connection is open. Has no effect otherwise. Queue must be enabled. The event can be accessed (e.g. to cancel it) via this component's .load_event attribute.
64
+ show_label: if True, will display label.
65
+ container: If True, will place the component in a container - providing some extra padding around the border.
66
+ scale: relative width compared to adjacent Components in a Row. For example, if Component A has scale=2, and Component B has scale=1, A will be twice as wide as B. Should be an integer.
67
+ 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.
68
+ visible: If False, component will be hidden.
69
+ 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.
70
+ 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.
71
+ height: height of the component in pixels.
72
+ latex_delimiters: A list of dicts of the form {"left": open delimiter (str), "right": close delimiter (str), "display": whether to display in newline (bool)} that will be used to render LaTeX expressions. If not provided, `latex_delimiters` is set to `[{ "left": "$$", "right": "$$", "display": True }]`, so only expressions enclosed in $$ delimiters will be rendered as LaTeX, and in a new line. Pass in an empty list to disable LaTeX rendering. For more information, see the [KaTeX documentation](https://katex.org/docs/autorender.html).
73
+ rtl: If True, sets the direction of the rendered text to right-to-left. Default is False, which renders text left-to-right.
74
+ show_share_button: If True, will show a share icon in the corner of the component that allows user to share outputs to Hugging Face Spaces Discussions. If False, icon does not appear. If set to None (default behavior), then the icon appears if this Gradio app is launched on Spaces, but not otherwise.
75
+ """
76
+ if color_map is not None:
77
+ warn_deprecation("The 'color_map' parameter has been deprecated.")
78
+ self.select: EventListenerMethod
79
+ """
80
+ Event listener for when the user selects message from Chatbot.
81
+ Uses event data gradio.SelectData to carry `value` referring to text of selected message, and `index` tuple to refer to [message, participant] index.
82
+ See EventData documentation on how to use this event data.
83
+ """
84
+ self.height = height
85
+ self.rtl = rtl
86
+ if latex_delimiters is None:
87
+ latex_delimiters = [{"left": "$$", "right": "$$", "display": True}]
88
+ self.latex_delimiters = latex_delimiters
89
+ self.show_share_button = (
90
+ (utils.get_space() is not None)
91
+ if show_share_button is None
92
+ else show_share_button
93
+ )
94
+
95
+ IOComponent.__init__(
96
+ self,
97
+ label=label,
98
+ every=every,
99
+ show_label=show_label,
100
+ container=container,
101
+ scale=scale,
102
+ min_width=min_width,
103
+ visible=visible,
104
+ elem_id=elem_id,
105
+ elem_classes=elem_classes,
106
+ value=value,
107
+ **kwargs,
108
+ )
109
+
110
+ def get_config(self):
111
+ return {
112
+ "value": self.value,
113
+ "latex_delimiters": self.latex_delimiters,
114
+ "selectable": self.selectable,
115
+ "height": self.height,
116
+ "show_share_button": self.show_share_button,
117
+ "rtl": self.rtl,
118
+ **IOComponent.get_config(self),
119
+ }
120
+
121
+ @staticmethod
122
+ def update(
123
+ value: list[list[str | tuple[str] | tuple[str, str] | None]]
124
+ | Literal[_Keywords.NO_VALUE]
125
+ | None = _Keywords.NO_VALUE,
126
+ label: str | None = None,
127
+ show_label: bool | None = None,
128
+ container: bool | None = None,
129
+ scale: int | None = None,
130
+ min_width: int | None = None,
131
+ visible: bool | None = None,
132
+ height: int | None = None,
133
+ rtl: bool | None = None,
134
+ show_share_button: bool | None = None,
135
+ ):
136
+ updated_config = {
137
+ "label": label,
138
+ "show_label": show_label,
139
+ "container": container,
140
+ "scale": scale,
141
+ "min_width": min_width,
142
+ "visible": visible,
143
+ "value": value,
144
+ "height": height,
145
+ "show_share_button": show_share_button,
146
+ "rtl": rtl,
147
+ "__type__": "update",
148
+ }
149
+ return updated_config
150
+
151
+ def _preprocess_chat_messages(
152
+ self, chat_message: str | dict | None
153
+ ) -> str | tuple[str] | tuple[str, str] | None:
154
+ if chat_message is None:
155
+ return None
156
+ elif isinstance(chat_message, dict):
157
+ if chat_message["alt_text"] is not None:
158
+ return (chat_message["name"], chat_message["alt_text"])
159
+ else:
160
+ return (chat_message["name"],)
161
+ else: # string
162
+ return chat_message
163
+
164
+ def preprocess(
165
+ self,
166
+ y: list[list[str | dict | None] | tuple[str | dict | None, str | dict | None]],
167
+ ) -> list[list[str | tuple[str] | tuple[str, str] | None]]:
168
+ if y is None:
169
+ return y
170
+ processed_messages = []
171
+ for message_pair in y:
172
+ assert isinstance(
173
+ message_pair, (tuple, list)
174
+ ), f"Expected a list of lists or list of tuples. Received: {message_pair}"
175
+ assert (
176
+ len(message_pair) == 2
177
+ ), f"Expected a list of lists of length 2 or list of tuples of length 2. Received: {message_pair}"
178
+ processed_messages.append(
179
+ [
180
+ self._preprocess_chat_messages(message_pair[0]),
181
+ self._preprocess_chat_messages(message_pair[1]),
182
+ ]
183
+ )
184
+ return processed_messages
185
+
186
+ def _postprocess_chat_messages(
187
+ self, chat_message: str | tuple | list | None
188
+ ) -> str | dict | None:
189
+ if chat_message is None:
190
+ return None
191
+ elif isinstance(chat_message, (tuple, list)):
192
+ file_uri = str(chat_message[0])
193
+ if utils.validate_url(file_uri):
194
+ filepath = file_uri
195
+ else:
196
+ filepath = self.make_temp_copy_if_needed(file_uri)
197
+
198
+ mime_type = client_utils.get_mimetype(filepath)
199
+ return {
200
+ "name": filepath,
201
+ "mime_type": mime_type,
202
+ "alt_text": chat_message[1] if len(chat_message) > 1 else None,
203
+ "data": None, # These last two fields are filled in by the frontend
204
+ "is_file": True,
205
+ }
206
+ elif isinstance(chat_message, str):
207
+ chat_message = inspect.cleandoc(chat_message)
208
+ return chat_message
209
+ else:
210
+ raise ValueError(f"Invalid message for Chatbot component: {chat_message}")
211
+
212
+ def postprocess(
213
+ self,
214
+ y: list[list[str | tuple[str] | tuple[str, str] | None] | tuple],
215
+ ) -> list[list[str | dict | None]]:
216
+ """
217
+ Parameters:
218
+ y: List of lists representing the message and response pairs. Each message and response should be a string, which may be in Markdown format. It can also be a tuple whose first element is a string or pathlib.Path filepath or URL to an image/video/audio, and second (optional) element is the alt text, in which case the media file is displayed. It can also be None, in which case that message is not displayed.
219
+ Returns:
220
+ List of lists representing the message and response. Each message and response will be a string of HTML, or a dictionary with media information. Or None if the message is not to be displayed.
221
+ """
222
+ if y is None:
223
+ return []
224
+ processed_messages = []
225
+ for message_pair in y:
226
+ assert isinstance(
227
+ message_pair, (tuple, list)
228
+ ), f"Expected a list of lists or list of tuples. Received: {message_pair}"
229
+ assert (
230
+ len(message_pair) == 2
231
+ ), f"Expected a list of lists of length 2 or list of tuples of length 2. Received: {message_pair}"
232
+ processed_messages.append(
233
+ [
234
+ self._postprocess_chat_messages(message_pair[0]),
235
+ self._postprocess_chat_messages(message_pair[1]),
236
+ ]
237
+ )
238
+ return processed_messages
239
+
240
+ def style(self, height: int | None = None, **kwargs):
241
+ """
242
+ This method is deprecated. Please set these arguments in the constructor instead.
243
+ """
244
+ warn_style_method_deprecation()
245
+ if height is not None:
246
+ self.height = height
247
+ return self
gradio/components/checkbox.py ADDED
@@ -0,0 +1,134 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """gr.Checkbox() component."""
2
+
3
+ from __future__ import annotations
4
+
5
+ from typing import Callable, Literal
6
+
7
+ from gradio_client.documentation import document, set_documentation_group
8
+ from gradio_client.serializing import BooleanSerializable
9
+
10
+ from gradio.components.base import FormComponent, IOComponent, _Keywords
11
+ from gradio.events import Changeable, EventListenerMethod, Inputable, Selectable
12
+ from gradio.interpretation import NeighborInterpretable
13
+
14
+ set_documentation_group("component")
15
+
16
+
17
+ @document()
18
+ class Checkbox(
19
+ FormComponent,
20
+ Changeable,
21
+ Inputable,
22
+ Selectable,
23
+ IOComponent,
24
+ BooleanSerializable,
25
+ NeighborInterpretable,
26
+ ):
27
+ """
28
+ Creates a checkbox that can be set to `True` or `False`.
29
+
30
+ Preprocessing: passes the status of the checkbox as a {bool} into the function.
31
+ Postprocessing: expects a {bool} returned from the function and, if it is True, checks the checkbox.
32
+ Examples-format: a {bool} representing whether the box is checked.
33
+ Demos: sentence_builder, titanic_survival
34
+ """
35
+
36
+ def __init__(
37
+ self,
38
+ value: bool | Callable = False,
39
+ *,
40
+ label: str | None = None,
41
+ info: str | None = None,
42
+ every: float | None = None,
43
+ show_label: bool | None = None,
44
+ container: bool = True,
45
+ scale: int | None = None,
46
+ min_width: int = 160,
47
+ interactive: bool | None = None,
48
+ visible: bool = True,
49
+ elem_id: str | None = None,
50
+ elem_classes: list[str] | str | None = None,
51
+ **kwargs,
52
+ ):
53
+ """
54
+ Parameters:
55
+ value: if True, checked by default. If callable, the function will be called whenever the app loads to set the initial value of the component.
56
+ label: component name in interface.
57
+ info: additional component description.
58
+ every: If `value` is a callable, run the function 'every' number of seconds while the client connection is open. Has no effect otherwise. Queue must be enabled. The event can be accessed (e.g. to cancel it) via this component's .load_event attribute.
59
+ show_label: if True, will display label.
60
+ container: If True, will place the component in a container - providing some extra padding around the border.
61
+ scale: relative width compared to adjacent Components in a Row. For example, if Component A has scale=2, and Component B has scale=1, A will be twice as wide as B. Should be an integer.
62
+ 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.
63
+ interactive: if True, this checkbox can be checked; if False, checking will be disabled. If not provided, this is inferred based on whether the component is used as an input or output.
64
+ visible: If False, component will be hidden.
65
+ 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.
66
+ 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.
67
+ """
68
+ self.select: EventListenerMethod
69
+ """
70
+ Event listener for when the user selects or deselects Checkbox.
71
+ Uses event data gradio.SelectData to carry `value` referring to label of checkbox, and `selected` to refer to state of checkbox.
72
+ See EventData documentation on how to use this event data.
73
+ """
74
+ IOComponent.__init__(
75
+ self,
76
+ label=label,
77
+ info=info,
78
+ every=every,
79
+ show_label=show_label,
80
+ container=container,
81
+ scale=scale,
82
+ min_width=min_width,
83
+ interactive=interactive,
84
+ visible=visible,
85
+ elem_id=elem_id,
86
+ elem_classes=elem_classes,
87
+ value=value,
88
+ **kwargs,
89
+ )
90
+ NeighborInterpretable.__init__(self)
91
+
92
+ def get_config(self):
93
+ return {
94
+ "value": self.value,
95
+ **IOComponent.get_config(self),
96
+ }
97
+
98
+ @staticmethod
99
+ def update(
100
+ value: bool | Literal[_Keywords.NO_VALUE] | None = _Keywords.NO_VALUE,
101
+ label: str | None = None,
102
+ info: str | None = None,
103
+ show_label: bool | None = None,
104
+ container: bool | None = None,
105
+ scale: int | None = None,
106
+ min_width: int | None = None,
107
+ interactive: bool | None = None,
108
+ visible: bool | None = None,
109
+ ):
110
+ return {
111
+ "label": label,
112
+ "info": info,
113
+ "show_label": show_label,
114
+ "container": container,
115
+ "scale": scale,
116
+ "min_width": min_width,
117
+ "interactive": interactive,
118
+ "visible": visible,
119
+ "value": value,
120
+ "__type__": "update",
121
+ }
122
+
123
+ def get_interpretation_neighbors(self, x):
124
+ return [not x], {}
125
+
126
+ def get_interpretation_scores(self, x, neighbors, scores, **kwargs):
127
+ """
128
+ Returns:
129
+ The first value represents the interpretation score if the input is False, and the second if the input is True.
130
+ """
131
+ if x:
132
+ return scores[0], None
133
+ else:
134
+ return None, scores[0]
gradio/components/checkboxgroup.py ADDED
@@ -0,0 +1,213 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """gr.CheckboxGroup() component"""
2
+
3
+ from __future__ import annotations
4
+
5
+ from typing import Any, Callable, Literal
6
+
7
+ from gradio_client.documentation import document, set_documentation_group
8
+ from gradio_client.serializing import ListStringSerializable
9
+
10
+ from gradio.components.base import FormComponent, IOComponent, _Keywords
11
+ from gradio.deprecation import warn_deprecation, warn_style_method_deprecation
12
+ from gradio.events import Changeable, EventListenerMethod, Inputable, Selectable
13
+ from gradio.interpretation import NeighborInterpretable
14
+
15
+ set_documentation_group("component")
16
+
17
+
18
+ @document()
19
+ class CheckboxGroup(
20
+ FormComponent,
21
+ Changeable,
22
+ Inputable,
23
+ Selectable,
24
+ IOComponent,
25
+ ListStringSerializable,
26
+ NeighborInterpretable,
27
+ ):
28
+ """
29
+ Creates a set of checkboxes of which a subset can be checked.
30
+ Preprocessing: passes the list of checked checkboxes as a {List[str]} or their indices as a {List[int]} into the function, depending on `type`.
31
+ Postprocessing: expects a {List[str]}, each element of which becomes a checked checkbox.
32
+ Examples-format: a {List[str]} representing the values to be checked.
33
+ Demos: sentence_builder, titanic_survival
34
+ """
35
+
36
+ def __init__(
37
+ self,
38
+ choices: list[str] | None = None,
39
+ *,
40
+ value: list[str] | str | Callable | None = None,
41
+ type: Literal["value", "index"] = "value",
42
+ label: str | None = None,
43
+ info: str | None = None,
44
+ every: float | None = None,
45
+ show_label: bool | None = None,
46
+ container: bool = True,
47
+ scale: int | None = None,
48
+ min_width: int = 160,
49
+ interactive: bool | None = None,
50
+ visible: bool = True,
51
+ elem_id: str | None = None,
52
+ elem_classes: list[str] | str | None = None,
53
+ **kwargs,
54
+ ):
55
+ """
56
+ Parameters:
57
+ choices: list of options to select from.
58
+ value: default selected list of options. If callable, the function will be called whenever the app loads to set the initial value of the component.
59
+ type: Type of value to be returned by component. "value" returns the list of strings of the choices selected, "index" returns the list of indices of the choices selected.
60
+ label: component name in interface.
61
+ info: additional component description.
62
+ every: If `value` is a callable, run the function 'every' number of seconds while the client connection is open. Has no effect otherwise. Queue must be enabled. The event can be accessed (e.g. to cancel it) via this component's .load_event attribute.
63
+ show_label: if True, will display label.
64
+ container: If True, will place the component in a container - providing some extra padding around the border.
65
+ scale: relative width compared to adjacent Components in a Row. For example, if Component A has scale=2, and Component B has scale=1, A will be twice as wide as B. Should be an integer.
66
+ 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.
67
+ interactive: if True, choices in this checkbox group will be checkable; if False, checking will be disabled. If not provided, this is inferred based on whether the component is used as an input or output.
68
+ visible: If False, component will be hidden.
69
+ 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.
70
+ 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.
71
+ """
72
+ self.choices = choices or []
73
+ valid_types = ["value", "index"]
74
+ if type not in valid_types:
75
+ raise ValueError(
76
+ f"Invalid value for parameter `type`: {type}. Please choose from one of: {valid_types}"
77
+ )
78
+ self.type = type
79
+ self.select: EventListenerMethod
80
+ """
81
+ Event listener for when the user selects or deselects within CheckboxGroup.
82
+ Uses event data gradio.SelectData to carry `value` referring to label of selected checkbox, `index` to refer to index, and `selected` to refer to state of checkbox.
83
+ See EventData documentation on how to use this event data.
84
+ """
85
+ IOComponent.__init__(
86
+ self,
87
+ label=label,
88
+ info=info,
89
+ every=every,
90
+ show_label=show_label,
91
+ container=container,
92
+ scale=scale,
93
+ min_width=min_width,
94
+ interactive=interactive,
95
+ visible=visible,
96
+ elem_id=elem_id,
97
+ elem_classes=elem_classes,
98
+ value=value,
99
+ **kwargs,
100
+ )
101
+ NeighborInterpretable.__init__(self)
102
+
103
+ def get_config(self):
104
+ return {
105
+ "choices": self.choices,
106
+ "value": self.value,
107
+ **IOComponent.get_config(self),
108
+ }
109
+
110
+ def example_inputs(self) -> dict[str, Any]:
111
+ return {
112
+ "raw": self.choices[0] if self.choices else None,
113
+ "serialized": self.choices[0] if self.choices else None,
114
+ }
115
+
116
+ @staticmethod
117
+ def update(
118
+ value: list[str]
119
+ | str
120
+ | Literal[_Keywords.NO_VALUE]
121
+ | None = _Keywords.NO_VALUE,
122
+ choices: list[str] | None = None,
123
+ label: str | None = None,
124
+ info: str | None = None,
125
+ show_label: bool | None = None,
126
+ container: bool | None = None,
127
+ scale: int | None = None,
128
+ min_width: int | None = None,
129
+ interactive: bool | None = None,
130
+ visible: bool | None = None,
131
+ ):
132
+ return {
133
+ "choices": choices,
134
+ "label": label,
135
+ "info": info,
136
+ "show_label": show_label,
137
+ "container": container,
138
+ "scale": scale,
139
+ "min_width": min_width,
140
+ "interactive": interactive,
141
+ "visible": visible,
142
+ "value": value,
143
+ "__type__": "update",
144
+ }
145
+
146
+ def preprocess(self, x: list[str]) -> list[str] | list[int]:
147
+ """
148
+ Parameters:
149
+ x: list of selected choices
150
+ Returns:
151
+ list of selected choices as strings or indices within choice list
152
+ """
153
+ if self.type == "value":
154
+ return x
155
+ elif self.type == "index":
156
+ return [self.choices.index(choice) for choice in x]
157
+ else:
158
+ raise ValueError(
159
+ f"Unknown type: {self.type}. Please choose from: 'value', 'index'."
160
+ )
161
+
162
+ def postprocess(self, y: list[str] | str | None) -> list[str]:
163
+ """
164
+ Any postprocessing needed to be performed on function output.
165
+ Parameters:
166
+ y: List of selected choices. If a single choice is selected, it can be passed in as a string
167
+ Returns:
168
+ List of selected choices
169
+ """
170
+ if y is None:
171
+ return []
172
+ if not isinstance(y, list):
173
+ y = [y]
174
+ return y
175
+
176
+ def get_interpretation_neighbors(self, x):
177
+ leave_one_out_sets = []
178
+ for choice in self.choices:
179
+ leave_one_out_set = list(x)
180
+ if choice in leave_one_out_set:
181
+ leave_one_out_set.remove(choice)
182
+ else:
183
+ leave_one_out_set.append(choice)
184
+ leave_one_out_sets.append(leave_one_out_set)
185
+ return leave_one_out_sets, {}
186
+
187
+ def get_interpretation_scores(self, x, neighbors, scores, **kwargs):
188
+ """
189
+ Returns:
190
+ For each tuple in the list, the first value represents the interpretation score if the input is False, and the second if the input is True.
191
+ """
192
+ final_scores = []
193
+ for choice, score in zip(self.choices, scores):
194
+ score_set = [score, None] if choice in x else [None, score]
195
+ final_scores.append(score_set)
196
+ return final_scores
197
+
198
+ def style(
199
+ self,
200
+ *,
201
+ item_container: bool | None = None,
202
+ container: bool | None = None,
203
+ **kwargs,
204
+ ):
205
+ """
206
+ This method is deprecated. Please set these arguments in the constructor instead.
207
+ """
208
+ warn_style_method_deprecation()
209
+ if item_container is not None:
210
+ warn_deprecation("The `item_container` parameter is deprecated.")
211
+ if container is not None:
212
+ self.container = container
213
+ return self
gradio/components/clear_button.py ADDED
@@ -0,0 +1,70 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """ Predefined buttons with bound events that can be included in a gr.Blocks for convenience. """
2
+
3
+ from __future__ import annotations
4
+
5
+ import json
6
+ from typing import Literal
7
+
8
+ from gradio_client.documentation import document, set_documentation_group
9
+
10
+ from gradio.components import Button, Component
11
+
12
+ set_documentation_group("component")
13
+
14
+
15
+ @document("add")
16
+ class ClearButton(Button):
17
+ """
18
+ Button that clears the value of a component or a list of components when clicked. It is instantiated with the list of components to clear.
19
+ Preprocessing: passes the button value as a {str} into the function
20
+ Postprocessing: expects a {str} to be returned from a function, which is set as the label of the button
21
+ """
22
+
23
+ is_template = True
24
+
25
+ def __init__(
26
+ self,
27
+ components: None | list[Component] | Component = None,
28
+ *,
29
+ value: str = "Clear",
30
+ variant: Literal["primary", "secondary", "stop"] = "secondary",
31
+ size: Literal["sm", "lg"] | None = None,
32
+ visible: bool = True,
33
+ interactive: bool = True,
34
+ elem_id: str | None = None,
35
+ elem_classes: list[str] | str | None = None,
36
+ scale: int | None = None,
37
+ min_width: int | None = None,
38
+ **kwargs,
39
+ ):
40
+ super().__init__(
41
+ value,
42
+ variant=variant,
43
+ size=size,
44
+ visible=visible,
45
+ interactive=interactive,
46
+ elem_id=elem_id,
47
+ elem_classes=elem_classes,
48
+ scale=scale,
49
+ min_width=min_width,
50
+ **kwargs,
51
+ )
52
+ self.add(components)
53
+
54
+ def add(self, components: None | Component | list[Component]) -> ClearButton:
55
+ """
56
+ Adds a component or list of components to the list of components that will be cleared when the button is clicked.
57
+ """
58
+ if not components:
59
+ # This needs to be here because when the ClearButton is created in an gr.Interface, we don't
60
+ # want to create dependencies for it before we have created the dependencies for the submit function.
61
+ # We generally assume that the submit function dependency is the first thing created in an gr.Interface.
62
+ return self
63
+
64
+ if isinstance(components, Component):
65
+ components = [components]
66
+ clear_values = json.dumps(
67
+ [component.postprocess(None) for component in components]
68
+ )
69
+ self.click(None, [], components, _js=f"() => {clear_values}")
70
+ return self
gradio/components/code.py ADDED
@@ -0,0 +1,157 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """gr.Code() component"""
2
+
3
+ from __future__ import annotations
4
+
5
+ from typing import Literal
6
+
7
+ from gradio_client.documentation import document, set_documentation_group
8
+ from gradio_client.serializing import StringSerializable
9
+
10
+ from gradio.components.base import IOComponent, _Keywords
11
+ from gradio.events import Changeable, Inputable
12
+
13
+ set_documentation_group("component")
14
+
15
+
16
+ @document("languages")
17
+ class Code(Changeable, Inputable, IOComponent, StringSerializable):
18
+ """
19
+ Creates a Code editor for entering, editing or viewing code.
20
+ Preprocessing: passes a {str} of code into the function.
21
+ Postprocessing: expects the function to return a {str} of code or a single-elment {tuple}: (string filepath,)
22
+ """
23
+
24
+ languages = [
25
+ "python",
26
+ "markdown",
27
+ "json",
28
+ "html",
29
+ "css",
30
+ "javascript",
31
+ "typescript",
32
+ "yaml",
33
+ "dockerfile",
34
+ "shell",
35
+ "r",
36
+ None,
37
+ ]
38
+
39
+ def __init__(
40
+ self,
41
+ value: str | tuple[str] | None = None,
42
+ language: Literal[
43
+ "python",
44
+ "markdown",
45
+ "json",
46
+ "html",
47
+ "css",
48
+ "javascript",
49
+ "typescript",
50
+ "yaml",
51
+ "dockerfile",
52
+ "shell",
53
+ "r",
54
+ ]
55
+ | None = None,
56
+ *,
57
+ lines: int = 5,
58
+ label: str | None = None,
59
+ interactive: bool | None = None,
60
+ show_label: bool | None = None,
61
+ container: bool = True,
62
+ scale: int | None = None,
63
+ min_width: int = 160,
64
+ visible: bool = True,
65
+ elem_id: str | None = None,
66
+ elem_classes: list[str] | str | None = None,
67
+ **kwargs,
68
+ ):
69
+ """
70
+ Parameters:
71
+ value: Default value to show in the code editor. If callable, the function will be called whenever the app loads to set the initial value of the component.
72
+ language: The language to display the code as. Supported languages listed in `gr.Code.languages`.
73
+ label: component name in interface.
74
+ interactive: Whether user should be able to enter code or only view it.
75
+ show_label: if True, will display label.
76
+ container: If True, will place the component in a container - providing some extra padding around the border.
77
+ scale: relative width compared to adjacent Components in a Row. For example, if Component A has scale=2, and Component B has scale=1, A will be twice as wide as B. Should be an integer.
78
+ 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.
79
+ visible: If False, component will be hidden.
80
+ 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.
81
+ 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.
82
+ """
83
+ assert language in Code.languages, f"Language {language} not supported."
84
+ self.language = language
85
+ self.lines = lines
86
+ IOComponent.__init__(
87
+ self,
88
+ label=label,
89
+ interactive=interactive,
90
+ show_label=show_label,
91
+ container=container,
92
+ scale=scale,
93
+ min_width=min_width,
94
+ visible=visible,
95
+ elem_id=elem_id,
96
+ elem_classes=elem_classes,
97
+ value=value,
98
+ **kwargs,
99
+ )
100
+
101
+ def get_config(self):
102
+ return {
103
+ "value": self.value,
104
+ "language": self.language,
105
+ "lines": self.lines,
106
+ **IOComponent.get_config(self),
107
+ }
108
+
109
+ def postprocess(self, y):
110
+ if y is None:
111
+ return None
112
+ elif isinstance(y, tuple):
113
+ with open(y[0]) as file_data:
114
+ return file_data.read()
115
+ else:
116
+ return y.strip()
117
+
118
+ @staticmethod
119
+ def update(
120
+ value: str
121
+ | tuple[str]
122
+ | None
123
+ | Literal[_Keywords.NO_VALUE] = _Keywords.NO_VALUE,
124
+ label: str | None = None,
125
+ show_label: bool | None = None,
126
+ container: bool | None = None,
127
+ scale: int | None = None,
128
+ min_width: int | None = None,
129
+ visible: bool | None = None,
130
+ language: Literal[
131
+ "python",
132
+ "markdown",
133
+ "json",
134
+ "html",
135
+ "css",
136
+ "javascript",
137
+ "typescript",
138
+ "yaml",
139
+ "dockerfile",
140
+ "shell",
141
+ "r",
142
+ ]
143
+ | None = None,
144
+ interactive: bool | None = None,
145
+ ):
146
+ return {
147
+ "label": label,
148
+ "show_label": show_label,
149
+ "container": container,
150
+ "scale": scale,
151
+ "min_width": min_width,
152
+ "visible": visible,
153
+ "value": value,
154
+ "language": language,
155
+ "interactive": interactive,
156
+ "__type__": "update",
157
+ }
gradio/components/color_picker.py ADDED
@@ -0,0 +1,143 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """gr.ColorPicker() component."""
2
+
3
+ from __future__ import annotations
4
+
5
+ from typing import Any, Callable, Literal
6
+
7
+ from gradio_client.documentation import document, set_documentation_group
8
+ from gradio_client.serializing import StringSerializable
9
+
10
+ from gradio.components.base import IOComponent, _Keywords
11
+ from gradio.events import (
12
+ Blurrable,
13
+ Changeable,
14
+ Inputable,
15
+ Submittable,
16
+ )
17
+
18
+ set_documentation_group("component")
19
+
20
+
21
+ @document()
22
+ class ColorPicker(
23
+ Changeable, Inputable, Submittable, Blurrable, IOComponent, StringSerializable
24
+ ):
25
+ """
26
+ Creates a color picker for user to select a color as string input.
27
+ Preprocessing: passes selected color value as a {str} into the function.
28
+ Postprocessing: expects a {str} returned from function and sets color picker value to it.
29
+ Examples-format: a {str} with a hexadecimal representation of a color, e.g. "#ff0000" for red.
30
+ Demos: color_picker, color_generator
31
+ """
32
+
33
+ def __init__(
34
+ self,
35
+ value: str | Callable | None = None,
36
+ *,
37
+ label: str | None = None,
38
+ info: str | None = None,
39
+ every: float | None = None,
40
+ show_label: bool | None = None,
41
+ container: bool = True,
42
+ scale: int | None = None,
43
+ min_width: int = 160,
44
+ interactive: bool | None = None,
45
+ visible: bool = True,
46
+ elem_id: str | None = None,
47
+ elem_classes: list[str] | str | None = None,
48
+ **kwargs,
49
+ ):
50
+ """
51
+ Parameters:
52
+ value: default text to provide in color picker. If callable, the function will be called whenever the app loads to set the initial value of the component.
53
+ label: component name in interface.
54
+ info: additional component description.
55
+ every: If `value` is a callable, run the function 'every' number of seconds while the client connection is open. Has no effect otherwise. Queue must be enabled. The event can be accessed (e.g. to cancel it) via this component's .load_event attribute.
56
+ show_label: if True, will display label.
57
+ container: If True, will place the component in a container - providing some extra padding around the border.
58
+ scale: relative width compared to adjacent Components in a Row. For example, if Component A has scale=2, and Component B has scale=1, A will be twice as wide as B. Should be an integer.
59
+ 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.
60
+ interactive: if True, will be rendered as an editable color picker; if False, editing will be disabled. If not provided, this is inferred based on whether the component is used as an input or output.
61
+ visible: If False, component will be hidden.
62
+ 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.
63
+ 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.
64
+ """
65
+ IOComponent.__init__(
66
+ self,
67
+ label=label,
68
+ info=info,
69
+ every=every,
70
+ show_label=show_label,
71
+ container=container,
72
+ scale=scale,
73
+ min_width=min_width,
74
+ interactive=interactive,
75
+ visible=visible,
76
+ elem_id=elem_id,
77
+ elem_classes=elem_classes,
78
+ value=value,
79
+ **kwargs,
80
+ )
81
+
82
+ def example_inputs(self) -> dict[str, Any]:
83
+ return {
84
+ "raw": "#000000",
85
+ "serialized": "#000000",
86
+ }
87
+
88
+ def get_config(self):
89
+ return {
90
+ "value": self.value,
91
+ **IOComponent.get_config(self),
92
+ }
93
+
94
+ @staticmethod
95
+ def update(
96
+ value: str | Literal[_Keywords.NO_VALUE] | None = _Keywords.NO_VALUE,
97
+ label: str | None = None,
98
+ info: str | None = None,
99
+ show_label: bool | None = None,
100
+ container: bool | None = None,
101
+ scale: int | None = None,
102
+ min_width: int | None = None,
103
+ visible: bool | None = None,
104
+ interactive: bool | None = None,
105
+ ):
106
+ return {
107
+ "value": value,
108
+ "label": label,
109
+ "info": info,
110
+ "show_label": show_label,
111
+ "container": container,
112
+ "scale": scale,
113
+ "min_width": min_width,
114
+ "visible": visible,
115
+ "interactive": interactive,
116
+ "__type__": "update",
117
+ }
118
+
119
+ def preprocess(self, x: str | None) -> str | None:
120
+ """
121
+ Any preprocessing needed to be performed on function input.
122
+ Parameters:
123
+ x: text
124
+ Returns:
125
+ text
126
+ """
127
+ if x is None:
128
+ return None
129
+ else:
130
+ return str(x)
131
+
132
+ def postprocess(self, y: str | None) -> str | None:
133
+ """
134
+ Any postprocessing needed to be performed on function output.
135
+ Parameters:
136
+ y: text
137
+ Returns:
138
+ text
139
+ """
140
+ if y is None:
141
+ return None
142
+ else:
143
+ return str(y)
gradio/components/dataframe.py ADDED
@@ -0,0 +1,304 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """gr.Dataframe() component"""
2
+
3
+ from __future__ import annotations
4
+
5
+ from typing import TYPE_CHECKING, Any, Callable, Literal
6
+
7
+ import numpy as np
8
+ import pandas as pd
9
+ from gradio_client.documentation import document, set_documentation_group
10
+ from gradio_client.serializing import JSONSerializable
11
+
12
+ from gradio import utils
13
+ from gradio.components.base import IOComponent, _Keywords
14
+ from gradio.events import (
15
+ Changeable,
16
+ EventListenerMethod,
17
+ Inputable,
18
+ Selectable,
19
+ )
20
+
21
+ if TYPE_CHECKING:
22
+ from typing import TypedDict
23
+
24
+ class DataframeData(TypedDict):
25
+ headers: list[str]
26
+ data: list[list[str | int | bool]]
27
+
28
+
29
+ set_documentation_group("component")
30
+
31
+
32
+ @document()
33
+ class Dataframe(Changeable, Inputable, Selectable, IOComponent, JSONSerializable):
34
+ """
35
+ Accepts or displays 2D input through a spreadsheet-like component for dataframes.
36
+ Preprocessing: passes the uploaded spreadsheet data as a {pandas.DataFrame}, {numpy.array}, {List[List]}, or {List} depending on `type`
37
+ Postprocessing: expects a {pandas.DataFrame}, {numpy.array}, {List[List]}, {List}, a {Dict} with keys `data` (and optionally `headers`), or {str} path to a csv, which is rendered in the spreadsheet.
38
+ Examples-format: a {str} filepath to a csv with data, a pandas dataframe, or a list of lists (excluding headers) where each sublist is a row of data.
39
+ Demos: filter_records, matrix_transpose, tax_calculator
40
+ """
41
+
42
+ markdown_parser = None
43
+
44
+ def __init__(
45
+ self,
46
+ value: list[list[Any]] | Callable | None = None,
47
+ *,
48
+ headers: list[str] | None = None,
49
+ row_count: int | tuple[int, str] = (1, "dynamic"),
50
+ col_count: int | tuple[int, str] | None = None,
51
+ datatype: str | list[str] = "str",
52
+ type: Literal["pandas", "numpy", "array"] = "pandas",
53
+ max_rows: int | None = 20,
54
+ max_cols: int | None = None,
55
+ overflow_row_behaviour: Literal["paginate", "show_ends"] = "paginate",
56
+ label: str | None = None,
57
+ every: float | None = None,
58
+ show_label: bool | None = None,
59
+ scale: int | None = None,
60
+ min_width: int = 160,
61
+ interactive: bool | None = None,
62
+ visible: bool = True,
63
+ elem_id: str | None = None,
64
+ elem_classes: list[str] | str | None = None,
65
+ wrap: bool = False,
66
+ **kwargs,
67
+ ):
68
+ """
69
+ Parameters:
70
+ value: Default value as a 2-dimensional list of values. If callable, the function will be called whenever the app loads to set the initial value of the component.
71
+ headers: List of str header names. If None, no headers are shown.
72
+ row_count: Limit number of rows for input and decide whether user can create new rows. The first element of the tuple is an `int`, the row count; the second should be 'fixed' or 'dynamic', the new row behaviour. If an `int` is passed the rows default to 'dynamic'
73
+ col_count: Limit number of columns for input and decide whether user can create new columns. The first element of the tuple is an `int`, the number of columns; the second should be 'fixed' or 'dynamic', the new column behaviour. If an `int` is passed the columns default to 'dynamic'
74
+ datatype: Datatype of values in sheet. Can be provided per column as a list of strings, or for the entire sheet as a single string. Valid datatypes are "str", "number", "bool", "date", and "markdown".
75
+ type: Type of value to be returned by component. "pandas" for pandas dataframe, "numpy" for numpy array, or "array" for a Python array.
76
+ label: component name in interface.
77
+ max_rows: Maximum number of rows to display at once. Set to None for infinite.
78
+ max_cols: Maximum number of columns to display at once. Set to None for infinite.
79
+ overflow_row_behaviour: If set to "paginate", will create pages for overflow rows. If set to "show_ends", will show initial and final rows and truncate middle rows.
80
+ label: component name in interface.
81
+ every: If `value` is a callable, run the function 'every' number of seconds while the client connection is open. Has no effect otherwise. Queue must be enabled. The event can be accessed (e.g. to cancel it) via this component's .load_event attribute.
82
+ show_label: if True, will display label.
83
+ scale: relative width compared to adjacent Components in a Row. For example, if Component A has scale=2, and Component B has scale=1, A will be twice as wide as B. Should be an integer.
84
+ 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.
85
+ interactive: if True, will allow users to edit the dataframe; if False, can only be used to display data. If not provided, this is inferred based on whether the component is used as an input or output.
86
+ visible: If False, component will be hidden.
87
+ 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.
88
+ 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.
89
+ wrap: if True text in table cells will wrap when appropriate, if False the table will scroll horizontally. Defaults to False.
90
+ """
91
+
92
+ self.wrap = wrap
93
+ self.row_count = self.__process_counts(row_count)
94
+ self.col_count = self.__process_counts(
95
+ col_count, len(headers) if headers else 3
96
+ )
97
+
98
+ self.__validate_headers(headers, self.col_count[0])
99
+
100
+ self.headers = (
101
+ headers if headers is not None else list(range(1, self.col_count[0] + 1))
102
+ )
103
+ self.datatype = (
104
+ datatype if isinstance(datatype, list) else [datatype] * self.col_count[0]
105
+ )
106
+ valid_types = ["pandas", "numpy", "array"]
107
+ if type not in valid_types:
108
+ raise ValueError(
109
+ f"Invalid value for parameter `type`: {type}. Please choose from one of: {valid_types}"
110
+ )
111
+ self.type = type
112
+ values = {
113
+ "str": "",
114
+ "number": 0,
115
+ "bool": False,
116
+ "date": "01/01/1970",
117
+ "markdown": "",
118
+ "html": "",
119
+ }
120
+ column_dtypes = (
121
+ [datatype] * self.col_count[0] if isinstance(datatype, str) else datatype
122
+ )
123
+ self.empty_input = [
124
+ [values[c] for c in column_dtypes] for _ in range(self.row_count[0])
125
+ ]
126
+
127
+ self.max_rows = max_rows
128
+ self.max_cols = max_cols
129
+ self.overflow_row_behaviour = overflow_row_behaviour
130
+ self.select: EventListenerMethod
131
+ """
132
+ Event listener for when the user selects cell within Dataframe.
133
+ Uses event data gradio.SelectData to carry `value` referring to value of selected cell, and `index` tuple to refer to index row and column.
134
+ See EventData documentation on how to use this event data.
135
+ """
136
+ IOComponent.__init__(
137
+ self,
138
+ label=label,
139
+ every=every,
140
+ show_label=show_label,
141
+ scale=scale,
142
+ min_width=min_width,
143
+ interactive=interactive,
144
+ visible=visible,
145
+ elem_id=elem_id,
146
+ elem_classes=elem_classes,
147
+ value=value,
148
+ **kwargs,
149
+ )
150
+
151
+ def get_config(self):
152
+ return {
153
+ "headers": self.headers,
154
+ "datatype": self.datatype,
155
+ "row_count": self.row_count,
156
+ "col_count": self.col_count,
157
+ "value": self.value,
158
+ "max_rows": self.max_rows,
159
+ "max_cols": self.max_cols,
160
+ "overflow_row_behaviour": self.overflow_row_behaviour,
161
+ "wrap": self.wrap,
162
+ **IOComponent.get_config(self),
163
+ }
164
+
165
+ @staticmethod
166
+ def update(
167
+ value: Any | Literal[_Keywords.NO_VALUE] | None = _Keywords.NO_VALUE,
168
+ max_rows: int | None = None,
169
+ max_cols: str | None = None,
170
+ label: str | None = None,
171
+ show_label: bool | None = None,
172
+ scale: int | None = None,
173
+ min_width: int | None = None,
174
+ interactive: bool | None = None,
175
+ visible: bool | None = None,
176
+ ):
177
+ return {
178
+ "max_rows": max_rows,
179
+ "max_cols": max_cols,
180
+ "label": label,
181
+ "show_label": show_label,
182
+ "scale": scale,
183
+ "min_width": min_width,
184
+ "interactive": interactive,
185
+ "visible": visible,
186
+ "value": value,
187
+ "__type__": "update",
188
+ }
189
+
190
+ def preprocess(self, x: DataframeData):
191
+ """
192
+ Parameters:
193
+ x: 2D array of str, numeric, or bool data
194
+ Returns:
195
+ Dataframe in requested format
196
+ """
197
+ if self.type == "pandas":
198
+ if x.get("headers") is not None:
199
+ return pd.DataFrame(x["data"], columns=x.get("headers"))
200
+ else:
201
+ return pd.DataFrame(x["data"])
202
+ if self.type == "numpy":
203
+ return np.array(x["data"])
204
+ elif self.type == "array":
205
+ return x["data"]
206
+ else:
207
+ raise ValueError(
208
+ "Unknown type: "
209
+ + str(self.type)
210
+ + ". Please choose from: 'pandas', 'numpy', 'array'."
211
+ )
212
+
213
+ def postprocess(
214
+ self, y: str | pd.DataFrame | np.ndarray | list[list[str | float]] | dict
215
+ ) -> dict:
216
+ """
217
+ Parameters:
218
+ y: dataframe in given format
219
+ Returns:
220
+ JSON object with key 'headers' for list of header names, 'data' for 2D array of string or numeric data
221
+ """
222
+ if y is None:
223
+ return self.postprocess(self.empty_input)
224
+ if isinstance(y, dict):
225
+ return y
226
+ if isinstance(y, str):
227
+ dataframe = pd.read_csv(y)
228
+ return {
229
+ "headers": list(dataframe.columns),
230
+ "data": Dataframe.__process_markdown(
231
+ dataframe.to_dict(orient="split")["data"], self.datatype
232
+ ),
233
+ }
234
+ if isinstance(y, pd.DataFrame):
235
+ return {
236
+ "headers": list(y.columns), # type: ignore
237
+ "data": Dataframe.__process_markdown(
238
+ y.to_dict(orient="split")["data"], self.datatype # type: ignore
239
+ ),
240
+ }
241
+ if isinstance(y, (np.ndarray, list)):
242
+ if len(y) == 0:
243
+ return self.postprocess([[]])
244
+ if isinstance(y, np.ndarray):
245
+ y = y.tolist()
246
+ assert isinstance(y, list), "output cannot be converted to list"
247
+
248
+ _headers = self.headers
249
+
250
+ if len(self.headers) < len(y[0]):
251
+ _headers = [
252
+ *self.headers,
253
+ *list(range(len(self.headers) + 1, len(y[0]) + 1)),
254
+ ]
255
+ elif len(self.headers) > len(y[0]):
256
+ _headers = self.headers[: len(y[0])]
257
+
258
+ return {
259
+ "headers": _headers,
260
+ "data": Dataframe.__process_markdown(y, self.datatype),
261
+ }
262
+ raise ValueError("Cannot process value as a Dataframe")
263
+
264
+ @staticmethod
265
+ def __process_counts(count, default=3) -> tuple[int, str]:
266
+ if count is None:
267
+ return (default, "dynamic")
268
+ if type(count) == int or type(count) == float:
269
+ return (int(count), "dynamic")
270
+ else:
271
+ return count
272
+
273
+ @staticmethod
274
+ def __validate_headers(headers: list[str] | None, col_count: int):
275
+ if headers is not None and len(headers) != col_count:
276
+ raise ValueError(
277
+ f"The length of the headers list must be equal to the col_count int.\n"
278
+ f"The column count is set to {col_count} but `headers` has {len(headers)} items. "
279
+ f"Check the values passed to `col_count` and `headers`."
280
+ )
281
+
282
+ @classmethod
283
+ def __process_markdown(cls, data: list[list[Any]], datatype: list[str]):
284
+ if "markdown" not in datatype:
285
+ return data
286
+
287
+ if cls.markdown_parser is None:
288
+ cls.markdown_parser = utils.get_markdown_parser()
289
+
290
+ for i in range(len(data)):
291
+ for j in range(len(data[i])):
292
+ if datatype[j] == "markdown":
293
+ data[i][j] = cls.markdown_parser.render(data[i][j])
294
+
295
+ return data
296
+
297
+ def as_example(self, input_data: pd.DataFrame | np.ndarray | str | None):
298
+ if input_data is None:
299
+ return ""
300
+ elif isinstance(input_data, pd.DataFrame):
301
+ return input_data.head(n=5).to_dict(orient="split")["data"] # type: ignore
302
+ elif isinstance(input_data, np.ndarray):
303
+ return input_data.tolist()
304
+ return input_data
gradio/components/dataset.py ADDED
@@ -0,0 +1,137 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """gr.Dataset() component."""
2
+
3
+ from __future__ import annotations
4
+
5
+ from typing import Any, Literal
6
+
7
+ from gradio_client.documentation import document, set_documentation_group
8
+ from gradio_client.serializing import StringSerializable
9
+
10
+ from gradio.components.base import (
11
+ Component,
12
+ IOComponent,
13
+ _Keywords,
14
+ get_component_instance,
15
+ )
16
+ from gradio.events import Clickable, Selectable
17
+
18
+ set_documentation_group("component")
19
+
20
+
21
+ @document()
22
+ class Dataset(Clickable, Selectable, Component, StringSerializable):
23
+ """
24
+ Used to create an output widget for showing datasets. Used to render the examples
25
+ box.
26
+ Preprocessing: passes the selected sample either as a {list} of data (if type="value") or as an {int} index (if type="index")
27
+ Postprocessing: expects a {list} of {lists} corresponding to the dataset data.
28
+ """
29
+
30
+ def __init__(
31
+ self,
32
+ *,
33
+ label: str | None = None,
34
+ components: list[IOComponent] | list[str],
35
+ samples: list[list[Any]] | None = None,
36
+ headers: list[str] | None = None,
37
+ type: Literal["values", "index"] = "values",
38
+ samples_per_page: int = 10,
39
+ visible: bool = True,
40
+ elem_id: str | None = None,
41
+ elem_classes: list[str] | str | None = None,
42
+ container: bool = True,
43
+ scale: int | None = None,
44
+ min_width: int = 160,
45
+ **kwargs,
46
+ ):
47
+ """
48
+ Parameters:
49
+ components: Which component types to show in this dataset widget, can be passed in as a list of string names or Components instances. The following components are supported in a Dataset: Audio, Checkbox, CheckboxGroup, ColorPicker, Dataframe, Dropdown, File, HTML, Image, Markdown, Model3D, Number, Radio, Slider, Textbox, TimeSeries, Video
50
+ samples: a nested list of samples. Each sublist within the outer list represents a data sample, and each element within the sublist represents an value for each component
51
+ headers: Column headers in the Dataset widget, should be the same len as components. If not provided, inferred from component labels
52
+ type: 'values' if clicking on a sample should pass the value of the sample, or "index" if it should pass the index of the sample
53
+ samples_per_page: how many examples to show per page.
54
+ visible: If False, component will be hidden.
55
+ 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.
56
+ 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.
57
+ container: If True, will place the component in a container - providing some extra padding around the border.
58
+ scale: relative width compared to adjacent Components in a Row. For example, if Component A has scale=2, and Component B has scale=1, A will be twice as wide as B. Should be an integer.
59
+ 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.
60
+ """
61
+ Component.__init__(
62
+ self, visible=visible, elem_id=elem_id, elem_classes=elem_classes, **kwargs
63
+ )
64
+ self.container = container
65
+ self.scale = scale
66
+ self.min_width = min_width
67
+ self.components = [get_component_instance(c, render=False) for c in components]
68
+
69
+ # Narrow type to IOComponent
70
+ assert all(
71
+ isinstance(c, IOComponent) for c in self.components
72
+ ), "All components in a `Dataset` must be subclasses of `IOComponent`"
73
+ self.components = [c for c in self.components if isinstance(c, IOComponent)]
74
+ for component in self.components:
75
+ component.root_url = self.root_url
76
+
77
+ self.samples = [[]] if samples is None else samples
78
+ for example in self.samples:
79
+ for i, (component, ex) in enumerate(zip(self.components, example)):
80
+ example[i] = component.as_example(ex)
81
+ self.type = type
82
+ self.label = label
83
+ if headers is not None:
84
+ self.headers = headers
85
+ elif all(c.label is None for c in self.components):
86
+ self.headers = []
87
+ else:
88
+ self.headers = [c.label or "" for c in self.components]
89
+ self.samples_per_page = samples_per_page
90
+
91
+ def get_config(self):
92
+ return {
93
+ "components": [component.get_block_name() for component in self.components],
94
+ "headers": self.headers,
95
+ "samples": self.samples,
96
+ "type": self.type,
97
+ "label": self.label,
98
+ "samples_per_page": self.samples_per_page,
99
+ "container": self.container,
100
+ "scale": self.scale,
101
+ "min_width": self.min_width,
102
+ **Component.get_config(self),
103
+ }
104
+
105
+ @staticmethod
106
+ def update(
107
+ samples: Any | Literal[_Keywords.NO_VALUE] | None = _Keywords.NO_VALUE,
108
+ visible: bool | None = None,
109
+ label: str | None = None,
110
+ container: bool | None = None,
111
+ scale: int | None = None,
112
+ min_width: int | None = None,
113
+ ):
114
+ return {
115
+ "samples": samples,
116
+ "visible": visible,
117
+ "label": label,
118
+ "container": container,
119
+ "scale": scale,
120
+ "min_width": min_width,
121
+ "__type__": "update",
122
+ }
123
+
124
+ def preprocess(self, x: Any) -> Any:
125
+ """
126
+ Any preprocessing needed to be performed on function input.
127
+ """
128
+ if self.type == "index":
129
+ return x
130
+ elif self.type == "values":
131
+ return self.samples[x]
132
+
133
+ def postprocess(self, samples: list[list[Any]]) -> dict:
134
+ return {
135
+ "samples": samples,
136
+ "__type__": "update",
137
+ }
gradio/components/dropdown.py ADDED
@@ -0,0 +1,243 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """gr.Dropdown() component."""
2
+
3
+ from __future__ import annotations
4
+
5
+ import warnings
6
+ from typing import Any, Callable, Literal
7
+
8
+ from gradio_client.documentation import document, set_documentation_group
9
+ from gradio_client.serializing import SimpleSerializable
10
+
11
+ from gradio.components.base import FormComponent, IOComponent, _Keywords
12
+ from gradio.deprecation import warn_style_method_deprecation
13
+ from gradio.events import (
14
+ Blurrable,
15
+ Changeable,
16
+ EventListenerMethod,
17
+ Inputable,
18
+ Selectable,
19
+ )
20
+
21
+ set_documentation_group("component")
22
+
23
+
24
+ @document()
25
+ class Dropdown(
26
+ FormComponent,
27
+ Changeable,
28
+ Inputable,
29
+ Selectable,
30
+ Blurrable,
31
+ IOComponent,
32
+ SimpleSerializable,
33
+ ):
34
+ """
35
+ Creates a dropdown of choices from which entries can be selected.
36
+ Preprocessing: passes the value of the selected dropdown entry as a {str} or its index as an {int} into the function, depending on `type`.
37
+ Postprocessing: expects a {str} corresponding to the value of the dropdown entry to be selected.
38
+ Examples-format: a {str} representing the drop down value to select.
39
+ Demos: sentence_builder, titanic_survival
40
+ """
41
+
42
+ def __init__(
43
+ self,
44
+ choices: list[str] | None = None,
45
+ *,
46
+ value: str | list[str] | Callable | None = None,
47
+ type: Literal["value", "index"] = "value",
48
+ multiselect: bool | None = None,
49
+ max_choices: int | None = None,
50
+ label: str | None = None,
51
+ info: str | None = None,
52
+ every: float | None = None,
53
+ show_label: bool | None = None,
54
+ container: bool = True,
55
+ scale: int | None = None,
56
+ min_width: int = 160,
57
+ interactive: bool | None = None,
58
+ visible: bool = True,
59
+ elem_id: str | None = None,
60
+ elem_classes: list[str] | str | None = None,
61
+ allow_custom_value: bool = False,
62
+ **kwargs,
63
+ ):
64
+ """
65
+ Parameters:
66
+ choices: list of options to select from.
67
+ value: default value(s) selected in dropdown. If None, no value is selected by default. If callable, the function will be called whenever the app loads to set the initial value of the component.
68
+ type: Type of value to be returned by component. "value" returns the string of the choice selected, "index" returns the index of the choice selected.
69
+ multiselect: if True, multiple choices can be selected.
70
+ max_choices: maximum number of choices that can be selected. If None, no limit is enforced.
71
+ label: component name in interface.
72
+ info: additional component description.
73
+ every: If `value` is a callable, run the function 'every' number of seconds while the client connection is open. Has no effect otherwise. Queue must be enabled. The event can be accessed (e.g. to cancel it) via this component's .load_event attribute.
74
+ show_label: if True, will display label.
75
+ container: If True, will place the component in a container - providing some extra padding around the border.
76
+ scale: relative width compared to adjacent Components in a Row. For example, if Component A has scale=2, and Component B has scale=1, A will be twice as wide as B. Should be an integer.
77
+ 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.
78
+ interactive: if True, choices in this dropdown will be selectable; if False, selection will be disabled. If not provided, this is inferred based on whether the component is used as an input or output.
79
+ visible: If False, component will be hidden.
80
+ 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.
81
+ 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.
82
+ allow_custom_value: If True, allows user to enter a custom value that is not in the list of choices.
83
+ """
84
+ self.choices = [str(choice) for choice in choices] if choices else []
85
+ valid_types = ["value", "index"]
86
+ if type not in valid_types:
87
+ raise ValueError(
88
+ f"Invalid value for parameter `type`: {type}. Please choose from one of: {valid_types}"
89
+ )
90
+ self.type = type
91
+ self.multiselect = multiselect
92
+ if multiselect and isinstance(value, str):
93
+ value = [value]
94
+ if not multiselect and max_choices is not None:
95
+ warnings.warn(
96
+ "The `max_choices` parameter is ignored when `multiselect` is False."
97
+ )
98
+ self.max_choices = max_choices
99
+ self.allow_custom_value = allow_custom_value
100
+ if multiselect and allow_custom_value:
101
+ raise ValueError(
102
+ "Custom values are not supported when `multiselect` is True."
103
+ )
104
+ self.interpret_by_tokens = False
105
+ self.select: EventListenerMethod
106
+ """
107
+ Event listener for when the user selects Dropdown option.
108
+ Uses event data gradio.SelectData to carry `value` referring to label of selected option, and `index` to refer to index.
109
+ See EventData documentation on how to use this event data.
110
+ """
111
+ IOComponent.__init__(
112
+ self,
113
+ label=label,
114
+ info=info,
115
+ every=every,
116
+ show_label=show_label,
117
+ container=container,
118
+ scale=scale,
119
+ min_width=min_width,
120
+ interactive=interactive,
121
+ visible=visible,
122
+ elem_id=elem_id,
123
+ elem_classes=elem_classes,
124
+ value=value,
125
+ **kwargs,
126
+ )
127
+
128
+ def api_info(self) -> dict[str, dict | bool]:
129
+ if self.multiselect:
130
+ type = {
131
+ "type": "array",
132
+ "items": {"type": "string"},
133
+ "description": f"List of options from: {self.choices}",
134
+ }
135
+ else:
136
+ type = {"type": "string", "description": f"Option from: {self.choices}"}
137
+ return {"info": type, "serialized_info": False}
138
+
139
+ def example_inputs(self) -> dict[str, Any]:
140
+ if self.multiselect:
141
+ return {
142
+ "raw": [self.choices[0]] if self.choices else [],
143
+ "serialized": [self.choices[0]] if self.choices else [],
144
+ }
145
+ else:
146
+ return {
147
+ "raw": self.choices[0] if self.choices else None,
148
+ "serialized": self.choices[0] if self.choices else None,
149
+ }
150
+
151
+ def get_config(self):
152
+ return {
153
+ "choices": self.choices,
154
+ "value": self.value,
155
+ "multiselect": self.multiselect,
156
+ "max_choices": self.max_choices,
157
+ "allow_custom_value": self.allow_custom_value,
158
+ "container": self.container,
159
+ **IOComponent.get_config(self),
160
+ }
161
+
162
+ @staticmethod
163
+ def update(
164
+ value: Any | Literal[_Keywords.NO_VALUE] | None = _Keywords.NO_VALUE,
165
+ choices: str | list[str] | None = None,
166
+ label: str | None = None,
167
+ info: str | None = None,
168
+ show_label: bool | None = None,
169
+ container: bool | None = None,
170
+ scale: int | None = None,
171
+ min_width: int | None = None,
172
+ interactive: bool | None = None,
173
+ placeholder: str | None = None,
174
+ visible: bool | None = None,
175
+ ):
176
+ return {
177
+ "choices": choices,
178
+ "label": label,
179
+ "info": info,
180
+ "show_label": show_label,
181
+ "container": container,
182
+ "scale": scale,
183
+ "min_width": min_width,
184
+ "visible": visible,
185
+ "value": value,
186
+ "interactive": interactive,
187
+ "placeholder": placeholder,
188
+ "__type__": "update",
189
+ }
190
+
191
+ def preprocess(
192
+ self, x: str | list[str]
193
+ ) -> str | int | list[str] | list[int] | None:
194
+ """
195
+ Parameters:
196
+ x: selected choice(s)
197
+ Returns:
198
+ selected choice(s) as string or index within choice list or list of string or indices
199
+ """
200
+ if self.type == "value":
201
+ return x
202
+ elif self.type == "index":
203
+ if x is None:
204
+ return None
205
+ elif self.multiselect:
206
+ return [self.choices.index(c) for c in x]
207
+ else:
208
+ if isinstance(x, str):
209
+ return self.choices.index(x) if x in self.choices else None
210
+ else:
211
+ raise ValueError(
212
+ f"Unknown type: {self.type}. Please choose from: 'value', 'index'."
213
+ )
214
+
215
+ def set_interpret_parameters(self):
216
+ """
217
+ Calculates interpretation score of each choice by comparing the output against each of the outputs when alternative choices are selected.
218
+ """
219
+ return self
220
+
221
+ def get_interpretation_neighbors(self, x):
222
+ choices = list(self.choices)
223
+ choices.remove(x)
224
+ return choices, {}
225
+
226
+ def get_interpretation_scores(
227
+ self, x, neighbors, scores: list[float | None], **kwargs
228
+ ) -> list:
229
+ """
230
+ Returns:
231
+ Each value represents the interpretation score corresponding to each choice.
232
+ """
233
+ scores.insert(self.choices.index(x), None)
234
+ return scores
235
+
236
+ def style(self, *, container: bool | None = None, **kwargs):
237
+ """
238
+ This method is deprecated. Please set these arguments in the constructor instead.
239
+ """
240
+ warn_style_method_deprecation()
241
+ if container is not None:
242
+ self.container = container
243
+ return self
gradio/components/duplicate_button.py ADDED
@@ -0,0 +1,61 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """ Predefined buttons with bound events that can be included in a gr.Blocks for convenience. """
2
+
3
+ from __future__ import annotations
4
+
5
+ from typing import Literal
6
+
7
+ from gradio_client.documentation import document, set_documentation_group
8
+
9
+ from gradio.components import Button
10
+ from gradio.utils import get_space
11
+
12
+ set_documentation_group("component")
13
+
14
+
15
+ @document()
16
+ class DuplicateButton(Button):
17
+ """
18
+ Button that triggers a Spaces Duplication, when the demo is on Hugging Face Spaces. Does nothing locally.
19
+ Preprocessing: passes the button value as a {str} into the function
20
+ Postprocessing: expects a {str} to be returned from a function, which is set as the label of the button
21
+ """
22
+
23
+ is_template = True
24
+
25
+ def __init__(
26
+ self,
27
+ *,
28
+ value: str = "Duplicate Space",
29
+ variant: Literal["primary", "secondary", "stop"] = "secondary",
30
+ size: Literal["sm", "lg"] | None = "sm",
31
+ visible: bool = True,
32
+ interactive: bool = True,
33
+ elem_id: str | None = None,
34
+ elem_classes: list[str] | str | None = None,
35
+ scale: int | None = 0,
36
+ min_width: int | None = None,
37
+ _activate: bool = True,
38
+ **kwargs,
39
+ ):
40
+ super().__init__(
41
+ value,
42
+ variant=variant,
43
+ size=size,
44
+ visible=visible,
45
+ interactive=interactive,
46
+ elem_id=elem_id,
47
+ elem_classes=elem_classes,
48
+ scale=scale,
49
+ min_width=min_width,
50
+ **kwargs,
51
+ )
52
+ if _activate:
53
+ self.activate()
54
+
55
+ def activate(self):
56
+ space_name = get_space()
57
+ if space_name is not None:
58
+ self.click(
59
+ fn=None,
60
+ _js=f"() => {{ window.open(`https://huggingface.co/spaces/{space_name}?duplicate=true`, '_blank') }}",
61
+ )
gradio/components/file.py ADDED
@@ -0,0 +1,281 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """gr.File() component"""
2
+
3
+ from __future__ import annotations
4
+
5
+ import tempfile
6
+ import warnings
7
+ from pathlib import Path
8
+ from typing import Any, Callable, Literal
9
+
10
+ from gradio_client import utils as client_utils
11
+ from gradio_client.documentation import document, set_documentation_group
12
+ from gradio_client.serializing import FileSerializable
13
+
14
+ from gradio import utils
15
+ from gradio.components.base import IOComponent, _Keywords
16
+ from gradio.deprecation import warn_deprecation
17
+ from gradio.events import (
18
+ Changeable,
19
+ Clearable,
20
+ EventListenerMethod,
21
+ Selectable,
22
+ Uploadable,
23
+ )
24
+
25
+ set_documentation_group("component")
26
+
27
+
28
+ @document()
29
+ class File(
30
+ Changeable,
31
+ Selectable,
32
+ Clearable,
33
+ Uploadable,
34
+ IOComponent,
35
+ FileSerializable,
36
+ ):
37
+ """
38
+ Creates a file component that allows uploading generic file (when used as an input) and or displaying generic files (output).
39
+ Preprocessing: passes the uploaded file as a {tempfile._TemporaryFileWrapper} or {List[tempfile._TemporaryFileWrapper]} depending on `file_count` (or a {bytes}/{List{bytes}} depending on `type`)
40
+ Postprocessing: expects function to return a {str} path to a file, or {List[str]} consisting of paths to files.
41
+ Examples-format: a {str} path to a local file that populates the component.
42
+ Demos: zip_to_json, zip_files
43
+ """
44
+
45
+ def __init__(
46
+ self,
47
+ value: str | list[str] | Callable | None = None,
48
+ *,
49
+ file_count: Literal["single", "multiple", "directory"] = "single",
50
+ file_types: list[str] | None = None,
51
+ type: Literal["file", "binary"] = "file",
52
+ label: str | None = None,
53
+ every: float | None = None,
54
+ show_label: bool | None = None,
55
+ container: bool = True,
56
+ scale: int | None = None,
57
+ min_width: int = 160,
58
+ interactive: bool | None = None,
59
+ visible: bool = True,
60
+ elem_id: str | None = None,
61
+ elem_classes: list[str] | str | None = None,
62
+ **kwargs,
63
+ ):
64
+ """
65
+ Parameters:
66
+ value: Default file to display, given as str file path. If callable, the function will be called whenever the app loads to set the initial value of the component.
67
+ file_count: if single, allows user to upload one file. If "multiple", user uploads multiple files. If "directory", user uploads all files in selected directory. Return type will be list for each file in case of "multiple" or "directory".
68
+ file_types: List of file extensions or types of files to be uploaded (e.g. ['image', '.json', '.mp4']). "file" allows any file to be uploaded, "image" allows only image files to be uploaded, "audio" allows only audio files to be uploaded, "video" allows only video files to be uploaded, "text" allows only text files to be uploaded.
69
+ type: Type of value to be returned by component. "file" returns a temporary file object with the same base name as the uploaded file, whose full path can be retrieved by file_obj.name, "binary" returns an bytes object.
70
+ label: component name in interface.
71
+ every: If `value` is a callable, run the function 'every' number of seconds while the client connection is open. Has no effect otherwise. Queue must be enabled. The event can be accessed (e.g. to cancel it) via this component's .load_event attribute.
72
+ show_label: if True, will display label.
73
+ container: If True, will place the component in a container - providing some extra padding around the border.
74
+ scale: relative width compared to adjacent Components in a Row. For example, if Component A has scale=2, and Component B has scale=1, A will be twice as wide as B. Should be an integer.
75
+ 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.
76
+ interactive: if True, will allow users to upload a file; if False, can only be used to display files. If not provided, this is inferred based on whether the component is used as an input or output.
77
+ visible: If False, component will be hidden.
78
+ 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.
79
+ 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.
80
+ """
81
+ self.file_count = file_count
82
+ self.file_types = file_types
83
+ if file_types is not None and not isinstance(file_types, list):
84
+ raise ValueError(
85
+ f"Parameter file_types must be a list. Received {file_types.__class__.__name__}"
86
+ )
87
+ valid_types = [
88
+ "file",
89
+ "binary",
90
+ "bytes",
91
+ ] # "bytes" is included for backwards compatibility
92
+ if type not in valid_types:
93
+ raise ValueError(
94
+ f"Invalid value for parameter `type`: {type}. Please choose from one of: {valid_types}"
95
+ )
96
+ if type == "bytes":
97
+ warn_deprecation(
98
+ "The `bytes` type is deprecated and may not work as expected. Please use `binary` instead."
99
+ )
100
+ if file_count == "directory" and file_types is not None:
101
+ warnings.warn(
102
+ "The `file_types` parameter is ignored when `file_count` is 'directory'."
103
+ )
104
+ self.type = type
105
+ self.select: EventListenerMethod
106
+ """
107
+ Event listener for when the user selects file from list.
108
+ Uses event data gradio.SelectData to carry `value` referring to name of selected file, and `index` to refer to index.
109
+ See EventData documentation on how to use this event data.
110
+ """
111
+ IOComponent.__init__(
112
+ self,
113
+ label=label,
114
+ every=every,
115
+ show_label=show_label,
116
+ container=container,
117
+ scale=scale,
118
+ min_width=min_width,
119
+ interactive=interactive,
120
+ visible=visible,
121
+ elem_id=elem_id,
122
+ elem_classes=elem_classes,
123
+ value=value,
124
+ **kwargs,
125
+ )
126
+
127
+ def get_config(self):
128
+ return {
129
+ "file_count": self.file_count,
130
+ "file_types": self.file_types,
131
+ "value": self.value,
132
+ "selectable": self.selectable,
133
+ **IOComponent.get_config(self),
134
+ }
135
+
136
+ @staticmethod
137
+ def update(
138
+ value: Any | Literal[_Keywords.NO_VALUE] | None = _Keywords.NO_VALUE,
139
+ label: str | None = None,
140
+ show_label: bool | None = None,
141
+ container: bool | None = None,
142
+ scale: int | None = None,
143
+ min_width: int | None = None,
144
+ interactive: bool | None = None,
145
+ visible: bool | None = None,
146
+ ):
147
+ return {
148
+ "label": label,
149
+ "show_label": show_label,
150
+ "container": container,
151
+ "scale": scale,
152
+ "min_width": min_width,
153
+ "interactive": interactive,
154
+ "visible": visible,
155
+ "value": value,
156
+ "__type__": "update",
157
+ }
158
+
159
+ def preprocess(
160
+ self, x: list[dict[str, Any]] | None
161
+ ) -> (
162
+ bytes
163
+ | tempfile._TemporaryFileWrapper
164
+ | list[bytes | tempfile._TemporaryFileWrapper]
165
+ | None
166
+ ):
167
+ """
168
+ Parameters:
169
+ x: List of JSON objects with filename as 'name' property and base64 data as 'data' property
170
+ Returns:
171
+ File objects in requested format
172
+ """
173
+ if x is None:
174
+ return None
175
+
176
+ def process_single_file(f) -> bytes | tempfile._TemporaryFileWrapper:
177
+ file_name, data, is_file = (
178
+ f["name"],
179
+ f["data"],
180
+ f.get("is_file", False),
181
+ )
182
+ if self.type == "file":
183
+ if is_file:
184
+ path = self.make_temp_copy_if_needed(file_name)
185
+ else:
186
+ data, _ = client_utils.decode_base64_to_binary(data)
187
+ path = self.file_bytes_to_file(
188
+ data, dir=self.DEFAULT_TEMP_DIR, file_name=file_name
189
+ )
190
+ path = str(utils.abspath(path))
191
+ self.temp_files.add(path)
192
+
193
+ # Creation of tempfiles here
194
+ file = tempfile.NamedTemporaryFile(
195
+ delete=False, dir=self.DEFAULT_TEMP_DIR
196
+ )
197
+ file.name = path
198
+ file.orig_name = file_name # type: ignore
199
+ return file
200
+ elif (
201
+ self.type == "binary" or self.type == "bytes"
202
+ ): # "bytes" is included for backwards compatibility
203
+ if is_file:
204
+ with open(file_name, "rb") as file_data:
205
+ return file_data.read()
206
+ return client_utils.decode_base64_to_binary(data)[0]
207
+ else:
208
+ raise ValueError(
209
+ "Unknown type: "
210
+ + str(self.type)
211
+ + ". Please choose from: 'file', 'bytes'."
212
+ )
213
+
214
+ if self.file_count == "single":
215
+ if isinstance(x, list):
216
+ return process_single_file(x[0])
217
+ else:
218
+ return process_single_file(x)
219
+ else:
220
+ if isinstance(x, list):
221
+ return [process_single_file(f) for f in x]
222
+ else:
223
+ return process_single_file(x)
224
+
225
+ def postprocess(
226
+ self, y: str | list[str] | None
227
+ ) -> dict[str, Any] | list[dict[str, Any]] | None:
228
+ """
229
+ Parameters:
230
+ y: file path
231
+ Returns:
232
+ JSON object with key 'name' for filename, 'data' for base64 url, and 'size' for filesize in bytes
233
+ """
234
+ if y is None:
235
+ return None
236
+ if isinstance(y, list):
237
+ return [
238
+ {
239
+ "orig_name": Path(file).name,
240
+ "name": self.make_temp_copy_if_needed(file),
241
+ "size": Path(file).stat().st_size,
242
+ "data": None,
243
+ "is_file": True,
244
+ }
245
+ for file in y
246
+ ]
247
+ else:
248
+ d = {
249
+ "orig_name": Path(y).name,
250
+ "name": self.make_temp_copy_if_needed(y),
251
+ "size": Path(y).stat().st_size,
252
+ "data": None,
253
+ "is_file": True,
254
+ }
255
+ return d
256
+
257
+ def as_example(self, input_data: str | list | None) -> str:
258
+ if input_data is None:
259
+ return ""
260
+ elif isinstance(input_data, list):
261
+ return ", ".join([Path(file).name for file in input_data])
262
+ else:
263
+ return Path(input_data).name
264
+
265
+ def api_info(self) -> dict[str, dict | bool]:
266
+ if self.file_count == "single":
267
+ return self._single_file_api_info()
268
+ else:
269
+ return self._multiple_file_api_info()
270
+
271
+ def serialized_info(self):
272
+ if self.file_count == "single":
273
+ return self._single_file_serialized_info()
274
+ else:
275
+ return self._multiple_file_serialized_info()
276
+
277
+ def example_inputs(self) -> dict[str, Any]:
278
+ if self.file_count == "single":
279
+ return self._single_file_example_inputs()
280
+ else:
281
+ return self._multiple_file_example_inputs()
gradio/components/gallery.py ADDED
@@ -0,0 +1,238 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """gr.Gallery() component."""
2
+
3
+ from __future__ import annotations
4
+
5
+ from pathlib import Path
6
+ from typing import Any, Callable, Literal
7
+
8
+ import numpy as np
9
+ from gradio_client.documentation import document, set_documentation_group
10
+ from gradio_client.serializing import GallerySerializable
11
+ from PIL import Image as _Image # using _ to minimize namespace pollution
12
+
13
+ from gradio import utils
14
+ from gradio.components.base import IOComponent, _Keywords
15
+ from gradio.deprecation import warn_deprecation, warn_style_method_deprecation
16
+ from gradio.events import (
17
+ EventListenerMethod,
18
+ Selectable,
19
+ )
20
+
21
+ set_documentation_group("component")
22
+
23
+
24
+ @document()
25
+ class Gallery(IOComponent, GallerySerializable, Selectable):
26
+ """
27
+ Used to display a list of images as a gallery that can be scrolled through.
28
+ Preprocessing: this component does *not* accept input.
29
+ Postprocessing: expects a list of images in any format, {List[numpy.array | PIL.Image | str | pathlib.Path]}, or a {List} of (image, {str} caption) tuples and displays them.
30
+
31
+ Demos: fake_gan
32
+ """
33
+
34
+ def __init__(
35
+ self,
36
+ value: list[np.ndarray | _Image.Image | str | Path | tuple]
37
+ | Callable
38
+ | None = None,
39
+ *,
40
+ label: str | None = None,
41
+ every: float | 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
+ columns: int | tuple | None = 2,
50
+ rows: int | tuple | None = None,
51
+ height: str | None = None,
52
+ preview: bool | None = None,
53
+ object_fit: Literal["contain", "cover", "fill", "none", "scale-down"]
54
+ | None = None,
55
+ allow_preview: bool = True,
56
+ show_share_button: bool | None = None,
57
+ **kwargs,
58
+ ):
59
+ """
60
+ Parameters:
61
+ value: List of images to display in the gallery by default. If callable, the function will be called whenever the app loads to set the initial value of the component.
62
+ label: component name in interface.
63
+ every: If `value` is a callable, run the function 'every' number of seconds while the client connection is open. Has no effect otherwise. Queue must be enabled. The event can be accessed (e.g. to cancel it) via this component's .load_event attribute.
64
+ show_label: if True, will display label.
65
+ container: If True, will place the component in a container - providing some extra padding around the border.
66
+ scale: relative width compared to adjacent Components in a Row. For example, if Component A has scale=2, and Component B has scale=1, A will be twice as wide as B. Should be an integer.
67
+ 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.
68
+ visible: If False, component will be hidden.
69
+ 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.
70
+ 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.
71
+ columns: Represents the number of images that should be shown in one row, for each of the six standard screen sizes (<576px, <768px, <992px, <1200px, <1400px, >1400px). if fewer that 6 are given then the last will be used for all subsequent breakpoints
72
+ rows: Represents the number of rows in the image grid, for each of the six standard screen sizes (<576px, <768px, <992px, <1200px, <1400px, >1400px). if fewer that 6 are given then the last will be used for all subsequent breakpoints
73
+ height: Height of the gallery.
74
+ preview: If True, will display the Gallery in preview mode, which shows all of the images as thumbnails and allows the user to click on them to view them in full size.
75
+ object_fit: CSS object-fit property for the thumbnail images in the gallery. Can be "contain", "cover", "fill", "none", or "scale-down".
76
+ allow_preview: If True, images in the gallery will be enlarged when they are clicked. Default is True.
77
+ show_share_button: If True, will show a share icon in the corner of the component that allows user to share outputs to Hugging Face Spaces Discussions. If False, icon does not appear. If set to None (default behavior), then the icon appears if this Gradio app is launched on Spaces, but not otherwise.
78
+ """
79
+ self.grid_cols = columns
80
+ self.grid_rows = rows
81
+ self.height = height
82
+ self.preview = preview
83
+ self.object_fit = object_fit
84
+ self.allow_preview = allow_preview
85
+ self.select: EventListenerMethod
86
+ """
87
+ Event listener for when the user selects image within Gallery.
88
+ Uses event data gradio.SelectData to carry `value` referring to caption of selected image, and `index` to refer to index.
89
+ See EventData documentation on how to use this event data.
90
+ """
91
+ self.show_share_button = (
92
+ (utils.get_space() is not None)
93
+ if show_share_button is None
94
+ else show_share_button
95
+ )
96
+ IOComponent.__init__(
97
+ self,
98
+ label=label,
99
+ every=every,
100
+ show_label=show_label,
101
+ container=container,
102
+ scale=scale,
103
+ min_width=min_width,
104
+ visible=visible,
105
+ elem_id=elem_id,
106
+ elem_classes=elem_classes,
107
+ value=value,
108
+ **kwargs,
109
+ )
110
+
111
+ @staticmethod
112
+ def update(
113
+ value: Any | Literal[_Keywords.NO_VALUE] | None = _Keywords.NO_VALUE,
114
+ label: str | None = None,
115
+ show_label: bool | None = None,
116
+ container: bool | None = None,
117
+ scale: int | None = None,
118
+ min_width: int | None = None,
119
+ visible: bool | None = None,
120
+ columns: int | tuple | None = None,
121
+ rows: int | tuple | None = None,
122
+ height: str | None = None,
123
+ preview: bool | None = None,
124
+ object_fit: Literal["contain", "cover", "fill", "none", "scale-down"]
125
+ | None = None,
126
+ allow_preview: bool | None = None,
127
+ show_share_button: bool | None = None,
128
+ ):
129
+ updated_config = {
130
+ "label": label,
131
+ "show_label": show_label,
132
+ "container": container,
133
+ "scale": scale,
134
+ "min_width": min_width,
135
+ "visible": visible,
136
+ "value": value,
137
+ "grid_cols": columns,
138
+ "grid_rows": rows,
139
+ "height": height,
140
+ "preview": preview,
141
+ "object_fit": object_fit,
142
+ "allow_preview": allow_preview,
143
+ "show_share_button": show_share_button,
144
+ "__type__": "update",
145
+ }
146
+ return updated_config
147
+
148
+ def get_config(self):
149
+ return {
150
+ "value": self.value,
151
+ "grid_cols": self.grid_cols,
152
+ "grid_rows": self.grid_rows,
153
+ "height": self.height,
154
+ "preview": self.preview,
155
+ "object_fit": self.object_fit,
156
+ "allow_preview": self.allow_preview,
157
+ "show_share_button": self.show_share_button,
158
+ **IOComponent.get_config(self),
159
+ }
160
+
161
+ def postprocess(
162
+ self,
163
+ y: list[np.ndarray | _Image.Image | str]
164
+ | list[tuple[np.ndarray | _Image.Image | str, str]]
165
+ | None,
166
+ ) -> list[str]:
167
+ """
168
+ Parameters:
169
+ y: list of images, or list of (image, caption) tuples
170
+ Returns:
171
+ list of string file paths to images in temp directory
172
+ """
173
+ if y is None:
174
+ return []
175
+ output = []
176
+ for img in y:
177
+ caption = None
178
+ if isinstance(img, (tuple, list)):
179
+ img, caption = img
180
+ if isinstance(img, np.ndarray):
181
+ file = self.img_array_to_temp_file(img, dir=self.DEFAULT_TEMP_DIR)
182
+ file_path = str(utils.abspath(file))
183
+ self.temp_files.add(file_path)
184
+ elif isinstance(img, _Image.Image):
185
+ file = self.pil_to_temp_file(img, dir=self.DEFAULT_TEMP_DIR)
186
+ file_path = str(utils.abspath(file))
187
+ self.temp_files.add(file_path)
188
+ elif isinstance(img, (str, Path)):
189
+ if utils.validate_url(img):
190
+ file_path = img
191
+ else:
192
+ file_path = self.make_temp_copy_if_needed(img)
193
+ else:
194
+ raise ValueError(f"Cannot process type as image: {type(img)}")
195
+
196
+ if caption is not None:
197
+ output.append(
198
+ [{"name": file_path, "data": None, "is_file": True}, caption]
199
+ )
200
+ else:
201
+ output.append({"name": file_path, "data": None, "is_file": True})
202
+
203
+ return output
204
+
205
+ def style(
206
+ self,
207
+ *,
208
+ grid: int | tuple | None = None,
209
+ columns: int | tuple | None = None,
210
+ rows: int | tuple | None = None,
211
+ height: str | None = None,
212
+ container: bool | None = None,
213
+ preview: bool | None = None,
214
+ object_fit: str | None = None,
215
+ **kwargs,
216
+ ):
217
+ """
218
+ This method is deprecated. Please set these arguments in the constructor instead.
219
+ """
220
+ warn_style_method_deprecation()
221
+ if grid is not None:
222
+ warn_deprecation(
223
+ "The 'grid' parameter will be deprecated. Please use 'grid_cols' in the constructor instead.",
224
+ )
225
+ self.grid_cols = grid
226
+ if columns is not None:
227
+ self.grid_cols = columns
228
+ if rows is not None:
229
+ self.grid_rows = rows
230
+ if height is not None:
231
+ self.height = height
232
+ if preview is not None:
233
+ self.preview = preview
234
+ if object_fit is not None:
235
+ self.object_fit = object_fit
236
+ if container is not None:
237
+ self.container = container
238
+ return self
gradio/components/highlighted_text.py ADDED
@@ -0,0 +1,205 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """gr.HighlightedText() component."""
2
+
3
+ from __future__ import annotations
4
+
5
+ from typing import Callable, Literal
6
+
7
+ from gradio_client.documentation import document, set_documentation_group
8
+ from gradio_client.serializing import (
9
+ JSONSerializable,
10
+ )
11
+
12
+ from gradio.components.base import IOComponent, _Keywords
13
+ from gradio.deprecation import warn_style_method_deprecation
14
+ from gradio.events import (
15
+ Changeable,
16
+ EventListenerMethod,
17
+ Selectable,
18
+ )
19
+
20
+ set_documentation_group("component")
21
+
22
+
23
+ @document()
24
+ class HighlightedText(Changeable, Selectable, IOComponent, JSONSerializable):
25
+ """
26
+ Displays text that contains spans that are highlighted by category or numerical value.
27
+ Preprocessing: this component does *not* accept input.
28
+ Postprocessing: expects a {List[Tuple[str, float | str]]]} consisting of spans of text and their associated labels, or a {Dict} with two keys: (1) "text" whose value is the complete text, and "entities", which is a list of dictionaries, each of which have the keys: "entity" (consisting of the entity label), "start" (the character index where the label starts), and "end" (the character index where the label ends). Entities should not overlap.
29
+
30
+ Demos: diff_texts, text_analysis
31
+ Guides: named-entity-recognition
32
+ """
33
+
34
+ def __init__(
35
+ self,
36
+ value: list[tuple[str, str | float | None]] | dict | Callable | None = None,
37
+ *,
38
+ color_map: dict[str, str]
39
+ | None = None, # Parameter moved to HighlightedText.style()
40
+ show_legend: bool = False,
41
+ combine_adjacent: bool = False,
42
+ adjacent_separator: str = "",
43
+ label: str | None = None,
44
+ every: float | None = None,
45
+ show_label: bool | None = None,
46
+ container: bool = True,
47
+ scale: int | None = None,
48
+ min_width: int = 160,
49
+ visible: bool = True,
50
+ elem_id: str | None = None,
51
+ elem_classes: list[str] | str | None = None,
52
+ **kwargs,
53
+ ):
54
+ """
55
+ Parameters:
56
+ value: Default value to show. If callable, the function will be called whenever the app loads to set the initial value of the component.
57
+ show_legend: whether to show span categories in a separate legend or inline.
58
+ combine_adjacent: If True, will merge the labels of adjacent tokens belonging to the same category.
59
+ adjacent_separator: Specifies the separator to be used between tokens if combine_adjacent is True.
60
+ label: component name in interface.
61
+ every: If `value` is a callable, run the function 'every' number of seconds while the client connection is open. Has no effect otherwise. Queue must be enabled. The event can be accessed (e.g. to cancel it) via this component's .load_event attribute.
62
+ show_label: if True, will display label.
63
+ container: If True, will place the component in a container - providing some extra padding around the border.
64
+ scale: relative width compared to adjacent Components in a Row. For example, if Component A has scale=2, and Component B has scale=1, A will be twice as wide as B. Should be an integer.
65
+ 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.
66
+ visible: If False, component will be hidden.
67
+ 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.
68
+ 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.
69
+ """
70
+ self.color_map = color_map
71
+ self.show_legend = show_legend
72
+ self.combine_adjacent = combine_adjacent
73
+ self.adjacent_separator = adjacent_separator
74
+ self.select: EventListenerMethod
75
+ """
76
+ Event listener for when the user selects Highlighted text span.
77
+ Uses event data gradio.SelectData to carry `value` referring to selected [text, label] tuple, and `index` to refer to span index.
78
+ See EventData documentation on how to use this event data.
79
+ """
80
+ IOComponent.__init__(
81
+ self,
82
+ label=label,
83
+ every=every,
84
+ show_label=show_label,
85
+ container=container,
86
+ scale=scale,
87
+ min_width=min_width,
88
+ visible=visible,
89
+ elem_id=elem_id,
90
+ elem_classes=elem_classes,
91
+ value=value,
92
+ **kwargs,
93
+ )
94
+
95
+ def get_config(self):
96
+ return {
97
+ "color_map": self.color_map,
98
+ "show_legend": self.show_legend,
99
+ "value": self.value,
100
+ "selectable": self.selectable,
101
+ **IOComponent.get_config(self),
102
+ }
103
+
104
+ @staticmethod
105
+ def update(
106
+ value: list[tuple[str, str | float | None]]
107
+ | dict
108
+ | Literal[_Keywords.NO_VALUE]
109
+ | None = _Keywords.NO_VALUE,
110
+ color_map: dict[str, str] | None = None,
111
+ show_legend: bool | None = None,
112
+ label: str | None = None,
113
+ show_label: bool | None = None,
114
+ container: bool | None = None,
115
+ scale: int | None = None,
116
+ min_width: int | None = None,
117
+ visible: bool | None = None,
118
+ ):
119
+ updated_config = {
120
+ "color_map": color_map,
121
+ "show_legend": show_legend,
122
+ "label": label,
123
+ "show_label": show_label,
124
+ "container": container,
125
+ "scale": scale,
126
+ "min_width": min_width,
127
+ "visible": visible,
128
+ "value": value,
129
+ "__type__": "update",
130
+ }
131
+ return updated_config
132
+
133
+ def postprocess(
134
+ self, y: list[tuple[str, str | float | None]] | dict | None
135
+ ) -> list[tuple[str, str | float | None]] | None:
136
+ """
137
+ Parameters:
138
+ y: List of (word, category) tuples
139
+ Returns:
140
+ List of (word, category) tuples
141
+ """
142
+ if y is None:
143
+ return None
144
+ if isinstance(y, dict):
145
+ try:
146
+ text = y["text"]
147
+ entities = y["entities"]
148
+ except KeyError as ke:
149
+ raise ValueError(
150
+ "Expected a dictionary with keys 'text' and 'entities' "
151
+ "for the value of the HighlightedText component."
152
+ ) from ke
153
+ if len(entities) == 0:
154
+ y = [(text, None)]
155
+ else:
156
+ list_format = []
157
+ index = 0
158
+ entities = sorted(entities, key=lambda x: x["start"])
159
+ for entity in entities:
160
+ list_format.append((text[index : entity["start"]], None))
161
+ list_format.append(
162
+ (text[entity["start"] : entity["end"]], entity["entity"])
163
+ )
164
+ index = entity["end"]
165
+ list_format.append((text[index:], None))
166
+ y = list_format
167
+ if self.combine_adjacent:
168
+ output = []
169
+ running_text, running_category = None, None
170
+ for text, category in y:
171
+ if running_text is None:
172
+ running_text = text
173
+ running_category = category
174
+ elif category == running_category:
175
+ running_text += self.adjacent_separator + text
176
+ elif not text:
177
+ # Skip fully empty item, these get added in processing
178
+ # of dictionaries.
179
+ pass
180
+ else:
181
+ output.append((running_text, running_category))
182
+ running_text = text
183
+ running_category = category
184
+ if running_text is not None:
185
+ output.append((running_text, running_category))
186
+ return output
187
+ else:
188
+ return y
189
+
190
+ def style(
191
+ self,
192
+ *,
193
+ color_map: dict[str, str] | None = None,
194
+ container: bool | None = None,
195
+ **kwargs,
196
+ ):
197
+ """
198
+ This method is deprecated. Please set these arguments in the constructor instead.
199
+ """
200
+ warn_style_method_deprecation()
201
+ if container is not None:
202
+ self.container = container
203
+ if color_map is not None:
204
+ self.color_map = color_map
205
+ return self
gradio/components/html.py ADDED
@@ -0,0 +1,81 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """gr.HTML() component."""
2
+
3
+ from __future__ import annotations
4
+
5
+ from typing import Any, Callable, Literal
6
+
7
+ from gradio_client.documentation import document, set_documentation_group
8
+ from gradio_client.serializing import StringSerializable
9
+
10
+ from gradio.components.base import IOComponent, _Keywords
11
+ from gradio.events import Changeable
12
+
13
+ set_documentation_group("component")
14
+
15
+
16
+ @document()
17
+ class HTML(Changeable, IOComponent, StringSerializable):
18
+ """
19
+ Used to display arbitrary HTML output.
20
+ Preprocessing: this component does *not* accept input.
21
+ Postprocessing: expects a valid HTML {str}.
22
+
23
+ Demos: text_analysis
24
+ Guides: key-features
25
+ """
26
+
27
+ def __init__(
28
+ self,
29
+ value: str | Callable = "",
30
+ *,
31
+ label: str | None = None,
32
+ every: float | None = None,
33
+ show_label: bool | None = None,
34
+ visible: bool = True,
35
+ elem_id: str | None = None,
36
+ elem_classes: list[str] | str | None = None,
37
+ **kwargs,
38
+ ):
39
+ """
40
+ Parameters:
41
+ value: Default value. If callable, the function will be called whenever the app loads to set the initial value of the component.
42
+ label: component name in interface.
43
+ every: If `value` is a callable, run the function 'every' number of seconds while the client connection is open. Has no effect otherwise. Queue must be enabled. The event can be accessed (e.g. to cancel it) via this component's .load_event attribute.
44
+ show_label: if True, will display label.
45
+ visible: If False, component will be hidden.
46
+ 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.
47
+ 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.
48
+ """
49
+ IOComponent.__init__(
50
+ self,
51
+ label=label,
52
+ every=every,
53
+ show_label=show_label,
54
+ visible=visible,
55
+ elem_id=elem_id,
56
+ elem_classes=elem_classes,
57
+ value=value,
58
+ **kwargs,
59
+ )
60
+
61
+ def get_config(self):
62
+ return {
63
+ "value": self.value,
64
+ **IOComponent.get_config(self),
65
+ }
66
+
67
+ @staticmethod
68
+ def update(
69
+ value: Any | Literal[_Keywords.NO_VALUE] | None = _Keywords.NO_VALUE,
70
+ label: str | None = None,
71
+ show_label: bool | None = None,
72
+ visible: bool | None = None,
73
+ ):
74
+ updated_config = {
75
+ "label": label,
76
+ "show_label": show_label,
77
+ "visible": visible,
78
+ "value": value,
79
+ "__type__": "update",
80
+ }
81
+ return updated_config
gradio/components/image.py ADDED
@@ -0,0 +1,442 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """gr.Image() component."""
2
+
3
+ from __future__ import annotations
4
+
5
+ import warnings
6
+ from pathlib import Path
7
+ from typing import Any, Literal
8
+
9
+ import numpy as np
10
+ import PIL
11
+ import PIL.ImageOps
12
+ from gradio_client import utils as client_utils
13
+ from gradio_client.documentation import document, set_documentation_group
14
+ from gradio_client.serializing import ImgSerializable
15
+ from PIL import Image as _Image # using _ to minimize namespace pollution
16
+
17
+ from gradio import processing_utils, utils
18
+ from gradio.components.base import IOComponent, _Keywords
19
+ from gradio.deprecation import warn_style_method_deprecation
20
+ from gradio.events import (
21
+ Changeable,
22
+ Clearable,
23
+ Editable,
24
+ EventListenerMethod,
25
+ Selectable,
26
+ Streamable,
27
+ Uploadable,
28
+ )
29
+ from gradio.interpretation import TokenInterpretable
30
+
31
+ set_documentation_group("component")
32
+ _Image.init() # fixes https://github.com/gradio-app/gradio/issues/2843
33
+
34
+
35
+ @document()
36
+ class Image(
37
+ Editable,
38
+ Clearable,
39
+ Changeable,
40
+ Streamable,
41
+ Selectable,
42
+ Uploadable,
43
+ IOComponent,
44
+ ImgSerializable,
45
+ TokenInterpretable,
46
+ ):
47
+ """
48
+ Creates an image component that can be used to upload/draw images (as an input) or display images (as an output).
49
+ Preprocessing: passes the uploaded image as a {numpy.array}, {PIL.Image} or {str} filepath depending on `type` -- unless `tool` is `sketch` AND source is one of `upload` or `webcam`. In these cases, a {dict} with keys `image` and `mask` is passed, and the format of the corresponding values depends on `type`.
50
+ Postprocessing: expects a {numpy.array}, {PIL.Image} or {str} or {pathlib.Path} filepath to an image and displays the image.
51
+ Examples-format: a {str} filepath to a local file that contains the image.
52
+ Demos: image_mod, image_mod_default_image
53
+ Guides: image-classification-in-pytorch, image-classification-in-tensorflow, image-classification-with-vision-transformers, building-a-pictionary_app, create-your-own-friends-with-a-gan
54
+ """
55
+
56
+ def __init__(
57
+ self,
58
+ value: str | _Image.Image | np.ndarray | None = None,
59
+ *,
60
+ shape: tuple[int, int] | None = None,
61
+ height: int | None = None,
62
+ width: int | None = None,
63
+ image_mode: Literal[
64
+ "1", "L", "P", "RGB", "RGBA", "CMYK", "YCbCr", "LAB", "HSV", "I", "F"
65
+ ] = "RGB",
66
+ invert_colors: bool = False,
67
+ source: Literal["upload", "webcam", "canvas"] = "upload",
68
+ tool: Literal["editor", "select", "sketch", "color-sketch"] | None = None,
69
+ type: Literal["numpy", "pil", "filepath"] = "numpy",
70
+ label: str | None = None,
71
+ every: float | None = None,
72
+ show_label: bool | None = None,
73
+ show_download_button: bool = True,
74
+ container: bool = True,
75
+ scale: int | None = None,
76
+ min_width: int = 160,
77
+ interactive: bool | None = None,
78
+ visible: bool = True,
79
+ streaming: bool = False,
80
+ elem_id: str | None = None,
81
+ elem_classes: list[str] | str | None = None,
82
+ mirror_webcam: bool = True,
83
+ brush_radius: float | None = None,
84
+ brush_color: str = "#000000",
85
+ mask_opacity: float = 0.7,
86
+ show_share_button: bool | None = None,
87
+ **kwargs,
88
+ ):
89
+ """
90
+ Parameters:
91
+ value: A PIL Image, numpy array, path or URL for the default value that Image component is going to take. If callable, the function will be called whenever the app loads to set the initial value of the component.
92
+ shape: (width, height) shape to crop and resize image when passed to function. If None, matches input image size. Pass None for either width or height to only crop and resize the other.
93
+ height: Height of the displayed image in pixels.
94
+ width: Width of the displayed image in pixels.
95
+ image_mode: "RGB" if color, or "L" if black and white. See https://pillow.readthedocs.io/en/stable/handbook/concepts.html for other supported image modes and their meaning.
96
+ invert_colors: whether to invert the image as a preprocessing step.
97
+ source: Source of image. "upload" creates a box where user can drop an image file, "webcam" allows user to take snapshot from their webcam, "canvas" defaults to a white image that can be edited and drawn upon with tools.
98
+ tool: Tools used for editing. "editor" allows a full screen editor (and is the default if source is "upload" or "webcam"), "select" provides a cropping and zoom tool, "sketch" allows you to create a binary sketch (and is the default if source="canvas"), and "color-sketch" allows you to created a sketch in different colors. "color-sketch" can be used with source="upload" or "webcam" to allow sketching on an image. "sketch" can also be used with "upload" or "webcam" to create a mask over an image and in that case both the image and mask are passed into the function as a dictionary with keys "image" and "mask" respectively.
99
+ type: The format the image is converted to before being passed into the prediction function. "numpy" converts the image to a numpy array with shape (height, width, 3) and values from 0 to 255, "pil" converts the image to a PIL image object, "filepath" passes a str path to a temporary file containing the image.
100
+ label: component name in interface.
101
+ every: If `value` is a callable, run the function 'every' number of seconds while the client connection is open. Has no effect otherwise. Queue must be enabled. The event can be accessed (e.g. to cancel it) via this component's .load_event attribute.
102
+ show_label: if True, will display label.
103
+ show_download_button: If True, will display button to download image.
104
+ container: If True, will place the component in a container - providing some extra padding around the border.
105
+ scale: relative width compared to adjacent Components in a Row. For example, if Component A has scale=2, and Component B has scale=1, A will be twice as wide as B. Should be an integer.
106
+ 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.
107
+ interactive: if True, will allow users to upload and edit an image; if False, can only be used to display images. If not provided, this is inferred based on whether the component is used as an input or output.
108
+ visible: If False, component will be hidden.
109
+ streaming: If True when used in a `live` interface, will automatically stream webcam feed. Only valid is source is 'webcam'.
110
+ 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.
111
+ 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.
112
+ mirror_webcam: If True webcam will be mirrored. Default is True.
113
+ brush_radius: Size of the brush for Sketch. Default is None which chooses a sensible default
114
+ brush_color: Color of the brush for Sketch as hex string. Default is "#000000".
115
+ mask_opacity: Opacity of mask drawn on image, as a value between 0 and 1.
116
+ show_share_button: If True, will show a share icon in the corner of the component that allows user to share outputs to Hugging Face Spaces Discussions. If False, icon does not appear. If set to None (default behavior), then the icon appears if this Gradio app is launched on Spaces, but not otherwise.
117
+ """
118
+ self.brush_radius = brush_radius
119
+ self.brush_color = brush_color
120
+ self.mask_opacity = mask_opacity
121
+ self.mirror_webcam = mirror_webcam
122
+ valid_types = ["numpy", "pil", "filepath"]
123
+ if type not in valid_types:
124
+ raise ValueError(
125
+ f"Invalid value for parameter `type`: {type}. Please choose from one of: {valid_types}"
126
+ )
127
+ self.type = type
128
+ self.shape = shape
129
+ self.height = height
130
+ self.width = width
131
+ self.image_mode = image_mode
132
+ valid_sources = ["upload", "webcam", "canvas"]
133
+ if source not in valid_sources:
134
+ raise ValueError(
135
+ f"Invalid value for parameter `source`: {source}. Please choose from one of: {valid_sources}"
136
+ )
137
+ self.source = source
138
+ if tool is None:
139
+ self.tool = "sketch" if source == "canvas" else "editor"
140
+ else:
141
+ self.tool = tool
142
+ self.invert_colors = invert_colors
143
+ self.streaming = streaming
144
+ self.show_download_button = show_download_button
145
+ if streaming and source != "webcam":
146
+ raise ValueError("Image streaming only available if source is 'webcam'.")
147
+ self.select: EventListenerMethod
148
+ """
149
+ Event listener for when the user clicks on a pixel within the image.
150
+ Uses event data gradio.SelectData to carry `index` to refer to the [x, y] coordinates of the clicked pixel.
151
+ See EventData documentation on how to use this event data.
152
+ """
153
+ self.show_share_button = (
154
+ (utils.get_space() is not None)
155
+ if show_share_button is None
156
+ else show_share_button
157
+ )
158
+ IOComponent.__init__(
159
+ self,
160
+ label=label,
161
+ every=every,
162
+ show_label=show_label,
163
+ container=container,
164
+ scale=scale,
165
+ min_width=min_width,
166
+ interactive=interactive,
167
+ visible=visible,
168
+ elem_id=elem_id,
169
+ elem_classes=elem_classes,
170
+ value=value,
171
+ **kwargs,
172
+ )
173
+ TokenInterpretable.__init__(self)
174
+
175
+ def get_config(self):
176
+ return {
177
+ "image_mode": self.image_mode,
178
+ "shape": self.shape,
179
+ "height": self.height,
180
+ "width": self.width,
181
+ "source": self.source,
182
+ "tool": self.tool,
183
+ "value": self.value,
184
+ "streaming": self.streaming,
185
+ "mirror_webcam": self.mirror_webcam,
186
+ "brush_radius": self.brush_radius,
187
+ "brush_color": self.brush_color,
188
+ "mask_opacity": self.mask_opacity,
189
+ "selectable": self.selectable,
190
+ "show_share_button": self.show_share_button,
191
+ "show_download_button": self.show_download_button,
192
+ **IOComponent.get_config(self),
193
+ }
194
+
195
+ @staticmethod
196
+ def update(
197
+ value: Any | Literal[_Keywords.NO_VALUE] | None = _Keywords.NO_VALUE,
198
+ height: int | None = None,
199
+ width: int | None = None,
200
+ label: str | None = None,
201
+ show_label: bool | None = None,
202
+ show_download_button: bool | None = None,
203
+ container: bool | None = None,
204
+ scale: int | None = None,
205
+ min_width: int | None = None,
206
+ interactive: bool | None = None,
207
+ visible: bool | None = None,
208
+ brush_radius: float | None = None,
209
+ brush_color: str | None = None,
210
+ mask_opacity: float | None = None,
211
+ show_share_button: bool | None = None,
212
+ ):
213
+ return {
214
+ "height": height,
215
+ "width": width,
216
+ "label": label,
217
+ "show_label": show_label,
218
+ "show_download_button": show_download_button,
219
+ "container": container,
220
+ "scale": scale,
221
+ "min_width": min_width,
222
+ "interactive": interactive,
223
+ "visible": visible,
224
+ "value": value,
225
+ "brush_radius": brush_radius,
226
+ "brush_color": brush_color,
227
+ "mask_opacity": mask_opacity,
228
+ "show_share_button": show_share_button,
229
+ "__type__": "update",
230
+ }
231
+
232
+ def _format_image(
233
+ self, im: _Image.Image | None
234
+ ) -> np.ndarray | _Image.Image | str | None:
235
+ """Helper method to format an image based on self.type"""
236
+ if im is None:
237
+ return im
238
+ fmt = im.format
239
+ if self.type == "pil":
240
+ return im
241
+ elif self.type == "numpy":
242
+ return np.array(im)
243
+ elif self.type == "filepath":
244
+ path = self.pil_to_temp_file(
245
+ im, dir=self.DEFAULT_TEMP_DIR, format=fmt or "png"
246
+ )
247
+ self.temp_files.add(path)
248
+ return path
249
+ else:
250
+ raise ValueError(
251
+ "Unknown type: "
252
+ + str(self.type)
253
+ + ". Please choose from: 'numpy', 'pil', 'filepath'."
254
+ )
255
+
256
+ def preprocess(
257
+ self, x: str | dict[str, str]
258
+ ) -> np.ndarray | _Image.Image | str | dict | None:
259
+ """
260
+ Parameters:
261
+ x: base64 url data, or (if tool == "sketch") a dict of image and mask base64 url data
262
+ Returns:
263
+ image in requested format, or (if tool == "sketch") a dict of image and mask in requested format
264
+ """
265
+ if x is None:
266
+ return x
267
+
268
+ mask = ""
269
+ if self.tool == "sketch" and self.source in ["upload", "webcam"]:
270
+ assert isinstance(x, dict)
271
+ x, mask = x["image"], x["mask"]
272
+
273
+ assert isinstance(x, str)
274
+ im = processing_utils.decode_base64_to_image(x)
275
+ with warnings.catch_warnings():
276
+ warnings.simplefilter("ignore")
277
+ im = im.convert(self.image_mode)
278
+ if self.shape is not None:
279
+ im = processing_utils.resize_and_crop(im, self.shape)
280
+ if self.invert_colors:
281
+ im = PIL.ImageOps.invert(im)
282
+ if (
283
+ self.source == "webcam"
284
+ and self.mirror_webcam is True
285
+ and self.tool != "color-sketch"
286
+ ):
287
+ im = PIL.ImageOps.mirror(im)
288
+
289
+ if self.tool == "sketch" and self.source in ["upload", "webcam"]:
290
+ mask_im = processing_utils.decode_base64_to_image(mask)
291
+
292
+ if mask_im.mode == "RGBA": # whiten any opaque pixels in the mask
293
+ alpha_data = mask_im.getchannel("A").convert("L")
294
+ mask_im = _Image.merge("RGB", [alpha_data, alpha_data, alpha_data])
295
+ return {
296
+ "image": self._format_image(im),
297
+ "mask": self._format_image(mask_im),
298
+ }
299
+
300
+ return self._format_image(im)
301
+
302
+ def postprocess(
303
+ self, y: np.ndarray | _Image.Image | str | Path | None
304
+ ) -> str | None:
305
+ """
306
+ Parameters:
307
+ y: image as a numpy array, PIL Image, string/Path filepath, or string URL
308
+ Returns:
309
+ base64 url data
310
+ """
311
+ if y is None:
312
+ return None
313
+ if isinstance(y, np.ndarray):
314
+ return processing_utils.encode_array_to_base64(y)
315
+ elif isinstance(y, _Image.Image):
316
+ return processing_utils.encode_pil_to_base64(y)
317
+ elif isinstance(y, (str, Path)):
318
+ return client_utils.encode_url_or_file_to_base64(y)
319
+ else:
320
+ raise ValueError("Cannot process this value as an Image")
321
+
322
+ def set_interpret_parameters(self, segments: int = 16):
323
+ """
324
+ Calculates interpretation score of image subsections by splitting the image into subsections, then using a "leave one out" method to calculate the score of each subsection by whiting out the subsection and measuring the delta of the output value.
325
+ Parameters:
326
+ segments: Number of interpretation segments to split image into.
327
+ """
328
+ self.interpretation_segments = segments
329
+ return self
330
+
331
+ def _segment_by_slic(self, x):
332
+ """
333
+ Helper method that segments an image into superpixels using slic.
334
+ Parameters:
335
+ x: base64 representation of an image
336
+ """
337
+ x = processing_utils.decode_base64_to_image(x)
338
+ if self.shape is not None:
339
+ x = processing_utils.resize_and_crop(x, self.shape)
340
+ resized_and_cropped_image = np.array(x)
341
+ try:
342
+ from skimage.segmentation import slic
343
+ except (ImportError, ModuleNotFoundError) as err:
344
+ raise ValueError(
345
+ "Error: running this interpretation for images requires scikit-image, please install it first."
346
+ ) from err
347
+ try:
348
+ segments_slic = slic(
349
+ resized_and_cropped_image,
350
+ self.interpretation_segments,
351
+ compactness=10,
352
+ sigma=1,
353
+ start_label=1,
354
+ )
355
+ except TypeError: # For skimage 0.16 and older
356
+ segments_slic = slic(
357
+ resized_and_cropped_image,
358
+ self.interpretation_segments,
359
+ compactness=10,
360
+ sigma=1,
361
+ )
362
+ return segments_slic, resized_and_cropped_image
363
+
364
+ def tokenize(self, x):
365
+ """
366
+ Segments image into tokens, masks, and leave-one-out-tokens
367
+ Parameters:
368
+ x: base64 representation of an image
369
+ Returns:
370
+ tokens: list of tokens, used by the get_masked_input() method
371
+ leave_one_out_tokens: list of left-out tokens, used by the get_interpretation_neighbors() method
372
+ masks: list of masks, used by the get_interpretation_neighbors() method
373
+ """
374
+ segments_slic, resized_and_cropped_image = self._segment_by_slic(x)
375
+ tokens, masks, leave_one_out_tokens = [], [], []
376
+ replace_color = np.mean(resized_and_cropped_image, axis=(0, 1))
377
+ for segment_value in np.unique(segments_slic):
378
+ mask = segments_slic == segment_value
379
+ image_screen = np.copy(resized_and_cropped_image)
380
+ image_screen[segments_slic == segment_value] = replace_color
381
+ leave_one_out_tokens.append(
382
+ processing_utils.encode_array_to_base64(image_screen)
383
+ )
384
+ token = np.copy(resized_and_cropped_image)
385
+ token[segments_slic != segment_value] = 0
386
+ tokens.append(token)
387
+ masks.append(mask)
388
+ return tokens, leave_one_out_tokens, masks
389
+
390
+ def get_masked_inputs(self, tokens, binary_mask_matrix):
391
+ masked_inputs = []
392
+ for binary_mask_vector in binary_mask_matrix:
393
+ masked_input = np.zeros_like(tokens[0], dtype=int)
394
+ for token, b in zip(tokens, binary_mask_vector):
395
+ masked_input = masked_input + token * int(b)
396
+ masked_inputs.append(processing_utils.encode_array_to_base64(masked_input))
397
+ return masked_inputs
398
+
399
+ def get_interpretation_scores(
400
+ self, x, neighbors, scores, masks, tokens=None, **kwargs
401
+ ) -> list[list[float]]:
402
+ """
403
+ Returns:
404
+ A 2D array representing the interpretation score of each pixel of the image.
405
+ """
406
+ x = processing_utils.decode_base64_to_image(x)
407
+ if self.shape is not None:
408
+ x = processing_utils.resize_and_crop(x, self.shape)
409
+ x = np.array(x)
410
+ output_scores = np.zeros((x.shape[0], x.shape[1]))
411
+
412
+ for score, mask in zip(scores, masks):
413
+ output_scores += score * mask
414
+
415
+ max_val, min_val = np.max(output_scores), np.min(output_scores)
416
+ if max_val > 0:
417
+ output_scores = (output_scores - min_val) / (max_val - min_val)
418
+ return output_scores.tolist()
419
+
420
+ def style(self, *, height: int | None = None, width: int | None = None, **kwargs):
421
+ """
422
+ This method is deprecated. Please set these arguments in the constructor instead.
423
+ """
424
+ warn_style_method_deprecation()
425
+ if height is not None:
426
+ self.height = height
427
+ if width is not None:
428
+ self.width = width
429
+ return self
430
+
431
+ def check_streamable(self):
432
+ if self.source != "webcam":
433
+ raise ValueError("Image streaming only available if source is 'webcam'.")
434
+
435
+ def as_example(self, input_data: str | None) -> str:
436
+ if input_data is None:
437
+ return ""
438
+ elif (
439
+ self.root_url
440
+ ): # If an externally hosted image, don't convert to absolute path
441
+ return input_data
442
+ return str(utils.abspath(input_data))
gradio/components/interpretation.py ADDED
@@ -0,0 +1,61 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """gr.Interpretation() component"""
2
+
3
+ from __future__ import annotations
4
+
5
+ from typing import Any, Literal
6
+
7
+ from gradio_client.documentation import document, set_documentation_group
8
+ from gradio_client.serializing import SimpleSerializable
9
+
10
+ from gradio.components.base import Component, _Keywords
11
+
12
+ set_documentation_group("component")
13
+
14
+
15
+ @document()
16
+ class Interpretation(Component, SimpleSerializable):
17
+ """
18
+ Used to create an interpretation widget for a component.
19
+ Preprocessing: this component does *not* accept input.
20
+ Postprocessing: expects a {dict} with keys "original" and "interpretation".
21
+
22
+ Guides: custom-interpretations-with-blocks
23
+ """
24
+
25
+ def __init__(
26
+ self,
27
+ component: Component,
28
+ *,
29
+ visible: bool = True,
30
+ elem_id: str | None = None,
31
+ elem_classes: list[str] | str | None = None,
32
+ **kwargs,
33
+ ):
34
+ """
35
+ Parameters:
36
+ component: Which component to show in the interpretation widget.
37
+ visible: Whether or not the interpretation is visible.
38
+ 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.
39
+ 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.
40
+ """
41
+ Component.__init__(
42
+ self, visible=visible, elem_id=elem_id, elem_classes=elem_classes, **kwargs
43
+ )
44
+ self.component = component
45
+
46
+ def get_config(self):
47
+ return {
48
+ "component": self.component.get_block_name(),
49
+ "component_props": self.component.get_config(),
50
+ }
51
+
52
+ @staticmethod
53
+ def update(
54
+ value: Any | Literal[_Keywords.NO_VALUE] | None = _Keywords.NO_VALUE,
55
+ visible: bool | None = None,
56
+ ):
57
+ return {
58
+ "visible": visible,
59
+ "value": value,
60
+ "__type__": "update",
61
+ }
gradio/components/json_component.py ADDED
@@ -0,0 +1,122 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """gr.JSON() component."""
2
+
3
+ from __future__ import annotations
4
+
5
+ import json
6
+ from typing import Any, Callable, Literal
7
+
8
+ from gradio_client.documentation import document, set_documentation_group
9
+ from gradio_client.serializing import JSONSerializable
10
+
11
+ from gradio.components.base import IOComponent, _Keywords
12
+ from gradio.deprecation import warn_style_method_deprecation
13
+ from gradio.events import (
14
+ Changeable,
15
+ )
16
+
17
+ set_documentation_group("component")
18
+
19
+
20
+ @document()
21
+ class JSON(Changeable, IOComponent, JSONSerializable):
22
+ """
23
+ Used to display arbitrary JSON output prettily.
24
+ Preprocessing: this component does *not* accept input.
25
+ Postprocessing: expects a {str} filepath to a file containing valid JSON -- or a {list} or {dict} that is valid JSON
26
+
27
+ Demos: zip_to_json, blocks_xray
28
+ """
29
+
30
+ def __init__(
31
+ self,
32
+ value: str | dict | list | Callable | None = None,
33
+ *,
34
+ label: str | None = None,
35
+ every: float | None = None,
36
+ show_label: bool | None = None,
37
+ container: bool = True,
38
+ scale: int | None = None,
39
+ min_width: int = 160,
40
+ visible: bool = True,
41
+ elem_id: str | None = None,
42
+ elem_classes: list[str] | str | None = None,
43
+ **kwargs,
44
+ ):
45
+ """
46
+ Parameters:
47
+ value: Default value. If callable, the function will be called whenever the app loads to set the initial value of the component.
48
+ label: component name in interface.
49
+ every: If `value` is a callable, run the function 'every' number of seconds while the client connection is open. Has no effect otherwise. Queue must be enabled. The event can be accessed (e.g. to cancel it) via this component's .load_event attribute.
50
+ show_label: if True, will display label.
51
+ container: If True, will place the component in a container - providing some extra padding around the border.
52
+ scale: relative width compared to adjacent Components in a Row. For example, if Component A has scale=2, and Component B has scale=1, A will be twice as wide as B. Should be an integer.
53
+ 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.
54
+ visible: If False, component will be hidden.
55
+ 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.
56
+ 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.
57
+ """
58
+ IOComponent.__init__(
59
+ self,
60
+ label=label,
61
+ every=every,
62
+ show_label=show_label,
63
+ container=container,
64
+ scale=scale,
65
+ min_width=min_width,
66
+ visible=visible,
67
+ elem_id=elem_id,
68
+ elem_classes=elem_classes,
69
+ value=value,
70
+ **kwargs,
71
+ )
72
+
73
+ def get_config(self):
74
+ return {
75
+ "value": self.value,
76
+ **IOComponent.get_config(self),
77
+ }
78
+
79
+ @staticmethod
80
+ def update(
81
+ value: Any | Literal[_Keywords.NO_VALUE] | None = _Keywords.NO_VALUE,
82
+ label: str | None = None,
83
+ show_label: bool | None = None,
84
+ container: bool | None = None,
85
+ scale: int | None = None,
86
+ min_width: int | None = None,
87
+ visible: bool | None = None,
88
+ ):
89
+ updated_config = {
90
+ "label": label,
91
+ "show_label": show_label,
92
+ "container": container,
93
+ "scale": scale,
94
+ "min_width": min_width,
95
+ "visible": visible,
96
+ "value": value,
97
+ "__type__": "update",
98
+ }
99
+ return updated_config
100
+
101
+ def postprocess(self, y: dict | list | str | None) -> dict | list | None:
102
+ """
103
+ Parameters:
104
+ y: either a string filepath to a JSON file, or a Python list or dict that can be converted to JSON
105
+ Returns:
106
+ JSON output in Python list or dict format
107
+ """
108
+ if y is None:
109
+ return None
110
+ if isinstance(y, str):
111
+ return json.loads(y)
112
+ else:
113
+ return y
114
+
115
+ def style(self, *, container: bool | None = None, **kwargs):
116
+ """
117
+ This method is deprecated. Please set these arguments in the constructor instead.
118
+ """
119
+ warn_style_method_deprecation()
120
+ if container is not None:
121
+ self.container = container
122
+ return self
gradio/components/label.py ADDED
@@ -0,0 +1,182 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """gr.Label() component."""
2
+
3
+ from __future__ import annotations
4
+
5
+ import operator
6
+ from pathlib import Path
7
+ from typing import Callable, Literal
8
+
9
+ from gradio_client.documentation import document, set_documentation_group
10
+ from gradio_client.serializing import (
11
+ JSONSerializable,
12
+ )
13
+
14
+ from gradio.components.base import IOComponent, _Keywords
15
+ from gradio.deprecation import warn_style_method_deprecation
16
+ from gradio.events import (
17
+ Changeable,
18
+ EventListenerMethod,
19
+ Selectable,
20
+ )
21
+
22
+ set_documentation_group("component")
23
+
24
+
25
+ @document()
26
+ class Label(Changeable, Selectable, IOComponent, JSONSerializable):
27
+ """
28
+ Displays a classification label, along with confidence scores of top categories, if provided.
29
+ Preprocessing: this component does *not* accept input.
30
+ Postprocessing: expects a {Dict[str, float]} of classes and confidences, or {str} with just the class or an {int}/{float} for regression outputs, or a {str} path to a .json file containing a json dictionary in the structure produced by Label.postprocess().
31
+
32
+ Demos: main_note, titanic_survival
33
+ Guides: image-classification-in-pytorch, image-classification-in-tensorflow, image-classification-with-vision-transformers, building-a-pictionary-app
34
+ """
35
+
36
+ CONFIDENCES_KEY = "confidences"
37
+
38
+ def __init__(
39
+ self,
40
+ value: dict[str, float] | str | float | Callable | None = None,
41
+ *,
42
+ num_top_classes: int | None = None,
43
+ label: str | None = None,
44
+ every: float | None = None,
45
+ show_label: bool | None = None,
46
+ container: bool = True,
47
+ scale: int | None = None,
48
+ min_width: int = 160,
49
+ visible: bool = True,
50
+ elem_id: str | None = None,
51
+ elem_classes: list[str] | str | None = None,
52
+ color: str | None = None,
53
+ **kwargs,
54
+ ):
55
+ """
56
+ Parameters:
57
+ value: Default value to show in the component. If a str or number is provided, simply displays the string or number. If a {Dict[str, float]} of classes and confidences is provided, displays the top class on top and the `num_top_classes` below, along with their confidence bars. If callable, the function will be called whenever the app loads to set the initial value of the component.
58
+ num_top_classes: number of most confident classes to show.
59
+ label: component name in interface.
60
+ every: If `value` is a callable, run the function 'every' number of seconds while the client connection is open. Has no effect otherwise. Queue must be enabled. The event can be accessed (e.g. to cancel it) via this component's .load_event attribute.
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 width compared to adjacent Components in a Row. For example, if Component A has scale=2, and Component B has scale=1, A will be twice as wide as B. Should be an integer.
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
+ color: The background color of the label (either a valid css color name or hexadecimal string).
69
+ """
70
+ self.num_top_classes = num_top_classes
71
+ self.color = color
72
+ self.select: EventListenerMethod
73
+ """
74
+ Event listener for when the user selects a category from Label.
75
+ Uses event data gradio.SelectData to carry `value` referring to name of selected category, and `index` to refer to index.
76
+ See EventData documentation on how to use this event data.
77
+ """
78
+ IOComponent.__init__(
79
+ self,
80
+ label=label,
81
+ every=every,
82
+ show_label=show_label,
83
+ container=container,
84
+ scale=scale,
85
+ min_width=min_width,
86
+ visible=visible,
87
+ elem_id=elem_id,
88
+ elem_classes=elem_classes,
89
+ value=value,
90
+ **kwargs,
91
+ )
92
+
93
+ def get_config(self):
94
+ return {
95
+ "num_top_classes": self.num_top_classes,
96
+ "value": self.value,
97
+ "color": self.color,
98
+ "selectable": self.selectable,
99
+ **IOComponent.get_config(self),
100
+ }
101
+
102
+ def postprocess(self, y: dict[str, float] | str | float | None) -> dict | None:
103
+ """
104
+ Parameters:
105
+ y: a dictionary mapping labels to confidence value, or just a string/numerical label by itself
106
+ Returns:
107
+ Object with key 'label' representing primary label, and key 'confidences' representing a list of label-confidence pairs
108
+ """
109
+ if y is None or y == {}:
110
+ return {}
111
+ if isinstance(y, str) and y.endswith(".json") and Path(y).exists():
112
+ return self.serialize(y)
113
+ if isinstance(y, (str, float, int)):
114
+ return {"label": str(y)}
115
+ if isinstance(y, dict):
116
+ if "confidences" in y and isinstance(y["confidences"], dict):
117
+ y = y["confidences"]
118
+ y = {c["label"]: c["confidence"] for c in y}
119
+ sorted_pred = sorted(y.items(), key=operator.itemgetter(1), reverse=True)
120
+ if self.num_top_classes is not None:
121
+ sorted_pred = sorted_pred[: self.num_top_classes]
122
+ return {
123
+ "label": sorted_pred[0][0],
124
+ "confidences": [
125
+ {"label": pred[0], "confidence": pred[1]} for pred in sorted_pred
126
+ ],
127
+ }
128
+ raise ValueError(
129
+ "The `Label` output interface expects one of: a string label, or an int label, a "
130
+ "float label, or a dictionary whose keys are labels and values are confidences. "
131
+ f"Instead, got a {type(y)}"
132
+ )
133
+
134
+ @staticmethod
135
+ def update(
136
+ value: dict[str, float]
137
+ | str
138
+ | float
139
+ | Literal[_Keywords.NO_VALUE]
140
+ | None = _Keywords.NO_VALUE,
141
+ label: str | None = None,
142
+ show_label: bool | None = None,
143
+ container: bool | None = None,
144
+ scale: int | None = None,
145
+ min_width: int | None = None,
146
+ visible: bool | None = None,
147
+ color: str | Literal[_Keywords.NO_VALUE] | None = _Keywords.NO_VALUE,
148
+ ):
149
+ # If color is not specified (NO_VALUE) map it to None so that
150
+ # it gets filtered out in postprocess. This will mean the color
151
+ # will not be updated in the front-end
152
+ if color is _Keywords.NO_VALUE:
153
+ color = None
154
+ # If the color was specified by the developer as None
155
+ # Map is so that the color is updated to be transparent,
156
+ # e.g. no background default state.
157
+ elif color is None:
158
+ color = "transparent"
159
+ return {
160
+ "label": label,
161
+ "show_label": show_label,
162
+ "container": container,
163
+ "scale": scale,
164
+ "min_width": min_width,
165
+ "visible": visible,
166
+ "value": value,
167
+ "color": color,
168
+ "__type__": "update",
169
+ }
170
+
171
+ def style(
172
+ self,
173
+ *,
174
+ container: bool | None = None,
175
+ ):
176
+ """
177
+ This method is deprecated. Please set these arguments in the constructor instead.
178
+ """
179
+ warn_style_method_deprecation()
180
+ if container is not None:
181
+ self.container = container
182
+ return self
gradio/components/line_plot.py ADDED
@@ -0,0 +1,430 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """gr.LinePlot() component"""
2
+
3
+ from __future__ import annotations
4
+
5
+ from typing import Callable, Literal
6
+
7
+ import altair as alt
8
+ import pandas as pd
9
+ from gradio_client.documentation import document, set_documentation_group
10
+
11
+ from gradio.components.base import _Keywords
12
+ from gradio.components.plot import AltairPlot, Plot
13
+
14
+ set_documentation_group("component")
15
+
16
+
17
+ @document()
18
+ class LinePlot(Plot):
19
+ """
20
+ Create a line plot.
21
+
22
+ Preprocessing: this component does *not* accept input.
23
+ Postprocessing: expects a pandas dataframe with the data to plot.
24
+
25
+ Demos: line_plot, live_dashboard
26
+ """
27
+
28
+ def __init__(
29
+ self,
30
+ value: pd.DataFrame | Callable | None = None,
31
+ x: str | None = None,
32
+ y: str | None = None,
33
+ *,
34
+ color: str | None = None,
35
+ stroke_dash: str | None = None,
36
+ overlay_point: bool | None = None,
37
+ title: str | None = None,
38
+ tooltip: list[str] | str | None = None,
39
+ x_title: str | None = None,
40
+ y_title: str | None = None,
41
+ color_legend_title: str | None = None,
42
+ stroke_dash_legend_title: str | None = None,
43
+ color_legend_position: Literal[
44
+ "left",
45
+ "right",
46
+ "top",
47
+ "bottom",
48
+ "top-left",
49
+ "top-right",
50
+ "bottom-left",
51
+ "bottom-right",
52
+ "none",
53
+ ]
54
+ | None = None,
55
+ stroke_dash_legend_position: Literal[
56
+ "left",
57
+ "right",
58
+ "top",
59
+ "bottom",
60
+ "top-left",
61
+ "top-right",
62
+ "bottom-left",
63
+ "bottom-right",
64
+ "none",
65
+ ]
66
+ | None = None,
67
+ height: int | None = None,
68
+ width: int | None = None,
69
+ x_lim: list[int] | None = None,
70
+ y_lim: list[int] | None = None,
71
+ caption: str | None = None,
72
+ interactive: bool | None = True,
73
+ label: str | None = None,
74
+ show_label: bool | None = None,
75
+ container: bool = True,
76
+ scale: int | None = None,
77
+ min_width: int = 160,
78
+ every: float | None = None,
79
+ visible: bool = True,
80
+ elem_id: str | None = None,
81
+ elem_classes: list[str] | str | None = None,
82
+ ):
83
+ """
84
+ Parameters:
85
+ value: The pandas dataframe containing the data to display in a scatter plot.
86
+ x: Column corresponding to the x axis.
87
+ y: Column corresponding to the y axis.
88
+ color: The column to determine the point color. If the column contains numeric data, gradio will interpolate the column data so that small values correspond to light colors and large values correspond to dark values.
89
+ stroke_dash: The column to determine the symbol used to draw the line, e.g. dashed lines, dashed lines with points.
90
+ overlay_point: Whether to draw a point on the line for each (x, y) coordinate pair.
91
+ title: The title to display on top of the chart.
92
+ tooltip: The column (or list of columns) to display on the tooltip when a user hovers a point on the plot.
93
+ x_title: The title given to the x axis. By default, uses the value of the x parameter.
94
+ y_title: The title given to the y axis. By default, uses the value of the y parameter.
95
+ color_legend_title: The title given to the color legend. By default, uses the value of color parameter.
96
+ stroke_dash_legend_title: The title given to the stroke_dash legend. By default, uses the value of the stroke_dash parameter.
97
+ color_legend_position: The position of the color legend. If the string value 'none' is passed, this legend is omitted. For other valid position values see: https://vega.github.io/vega/docs/legends/#orientation.
98
+ stroke_dash_legend_position: The position of the stoke_dash legend. If the string value 'none' is passed, this legend is omitted. For other valid position values see: https://vega.github.io/vega/docs/legends/#orientation.
99
+ height: The height of the plot in pixels.
100
+ width: The width of the plot in pixels.
101
+ x_lim: A tuple or list containing the limits for the x-axis, specified as [x_min, x_max].
102
+ y_lim: A tuple of list containing the limits for the y-axis, specified as [y_min, y_max].
103
+ caption: The (optional) caption to display below the plot.
104
+ interactive: Whether users should be able to interact with the plot by panning or zooming with their mouse or trackpad.
105
+ label: The (optional) label to display on the top left corner of the plot.
106
+ show_label: Whether the label should be displayed.
107
+ every: If `value` is a callable, run the function 'every' number of seconds while the client connection is open. Has no effect otherwise. Queue must be enabled. The event can be accessed (e.g. to cancel it) via this component's .load_event attribute.
108
+ visible: Whether the plot should be visible.
109
+ 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.
110
+ 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.
111
+ """
112
+ self.x = x
113
+ self.y = y
114
+ self.color = color
115
+ self.stroke_dash = stroke_dash
116
+ self.tooltip = tooltip
117
+ self.title = title
118
+ self.x_title = x_title
119
+ self.y_title = y_title
120
+ self.color_legend_title = color_legend_title
121
+ self.stroke_dash_legend_title = stroke_dash_legend_title
122
+ self.color_legend_position = color_legend_position
123
+ self.stroke_dash_legend_position = stroke_dash_legend_position
124
+ self.overlay_point = overlay_point
125
+ self.x_lim = x_lim
126
+ self.y_lim = y_lim
127
+ self.caption = caption
128
+ self.interactive_chart = interactive
129
+ self.width = width
130
+ self.height = height
131
+ super().__init__(
132
+ value=value,
133
+ label=label,
134
+ show_label=show_label,
135
+ container=container,
136
+ scale=scale,
137
+ min_width=min_width,
138
+ visible=visible,
139
+ elem_id=elem_id,
140
+ elem_classes=elem_classes,
141
+ every=every,
142
+ )
143
+
144
+ def get_config(self):
145
+ config = super().get_config()
146
+ config["caption"] = self.caption
147
+ return config
148
+
149
+ def get_block_name(self) -> str:
150
+ return "plot"
151
+
152
+ @staticmethod
153
+ def update(
154
+ value: pd.DataFrame | dict | Literal[_Keywords.NO_VALUE] = _Keywords.NO_VALUE,
155
+ x: str | None = None,
156
+ y: str | None = None,
157
+ color: str | None = None,
158
+ stroke_dash: str | None = None,
159
+ overlay_point: bool | None = None,
160
+ title: str | None = None,
161
+ tooltip: list[str] | str | None = None,
162
+ x_title: str | None = None,
163
+ y_title: str | None = None,
164
+ color_legend_title: str | None = None,
165
+ stroke_dash_legend_title: str | None = None,
166
+ color_legend_position: Literal[
167
+ "left",
168
+ "right",
169
+ "top",
170
+ "bottom",
171
+ "top-left",
172
+ "top-right",
173
+ "bottom-left",
174
+ "bottom-right",
175
+ "none",
176
+ ]
177
+ | None = None,
178
+ stroke_dash_legend_position: Literal[
179
+ "left",
180
+ "right",
181
+ "top",
182
+ "bottom",
183
+ "top-left",
184
+ "top-right",
185
+ "bottom-left",
186
+ "bottom-right",
187
+ "none",
188
+ ]
189
+ | None = None,
190
+ height: int | None = None,
191
+ width: int | None = None,
192
+ x_lim: list[int] | None = None,
193
+ y_lim: list[int] | None = None,
194
+ interactive: bool | None = None,
195
+ caption: str | None = None,
196
+ label: str | None = None,
197
+ show_label: bool | None = None,
198
+ container: bool | None = None,
199
+ scale: int | None = None,
200
+ min_width: int | None = None,
201
+ visible: bool | None = None,
202
+ ):
203
+ """Update an existing plot component.
204
+
205
+ If updating any of the plot properties (color, size, etc) the value, x, and y parameters must be specified.
206
+
207
+ Parameters:
208
+ value: The pandas dataframe containing the data to display in a scatter plot.
209
+ x: Column corresponding to the x axis.
210
+ y: Column corresponding to the y axis.
211
+ color: The column to determine the point color. If the column contains numeric data, gradio will interpolate the column data so that small values correspond to light colors and large values correspond to dark values.
212
+ stroke_dash: The column to determine the symbol used to draw the line, e.g. dashed lines, dashed lines with points.
213
+ overlay_point: Whether to draw a point on the line for each (x, y) coordinate pair.
214
+ title: The title to display on top of the chart.
215
+ tooltip: The column (or list of columns) to display on the tooltip when a user hovers a point on the plot.
216
+ x_title: The title given to the x axis. By default, uses the value of the x parameter.
217
+ y_title: The title given to the y axis. By default, uses the value of the y parameter.
218
+ color_legend_title: The title given to the color legend. By default, uses the value of color parameter.
219
+ stroke_dash_legend_title: The title given to the stroke legend. By default, uses the value of stroke parameter.
220
+ color_legend_position: The position of the color legend. If the string value 'none' is passed, this legend is omitted. For other valid position values see: https://vega.github.io/vega/docs/legends/#orientation
221
+ stroke_dash_legend_position: The position of the stoke_dash legend. If the string value 'none' is passed, this legend is omitted. For other valid position values see: https://vega.github.io/vega/docs/legends/#orientation
222
+ height: The height of the plot in pixels.
223
+ width: The width of the plot in pixels.
224
+ x_lim: A tuple or list containing the limits for the x-axis, specified as [x_min, x_max].
225
+ y_lim: A tuple of list containing the limits for the y-axis, specified as [y_min, y_max].
226
+ caption: The (optional) caption to display below the plot.
227
+ interactive: Whether users should be able to interact with the plot by panning or zooming with their mouse or trackpad.
228
+ label: The (optional) label to display in the top left corner of the plot.
229
+ show_label: Whether the label should be displayed.
230
+ visible: Whether the plot should be visible.
231
+ """
232
+ properties = [
233
+ x,
234
+ y,
235
+ color,
236
+ stroke_dash,
237
+ overlay_point,
238
+ title,
239
+ tooltip,
240
+ x_title,
241
+ y_title,
242
+ color_legend_title,
243
+ stroke_dash_legend_title,
244
+ color_legend_position,
245
+ stroke_dash_legend_position,
246
+ height,
247
+ width,
248
+ x_lim,
249
+ y_lim,
250
+ interactive,
251
+ ]
252
+ if any(properties):
253
+ if not isinstance(value, pd.DataFrame):
254
+ raise ValueError(
255
+ "In order to update plot properties the value parameter "
256
+ "must be provided, and it must be a Dataframe. Please pass a value "
257
+ "parameter to gr.LinePlot.update."
258
+ )
259
+ if x is None or y is None:
260
+ raise ValueError(
261
+ "In order to update plot properties, the x and y axis data "
262
+ "must be specified. Please pass valid values for x an y to "
263
+ "gr.LinePlot.update."
264
+ )
265
+ chart = LinePlot.create_plot(value, *properties)
266
+ value = {"type": "altair", "plot": chart.to_json(), "chart": "line"}
267
+
268
+ updated_config = {
269
+ "label": label,
270
+ "show_label": show_label,
271
+ "container": container,
272
+ "scale": scale,
273
+ "min_width": min_width,
274
+ "visible": visible,
275
+ "value": value,
276
+ "caption": caption,
277
+ "__type__": "update",
278
+ }
279
+ return updated_config
280
+
281
+ @staticmethod
282
+ def create_plot(
283
+ value: pd.DataFrame,
284
+ x: str,
285
+ y: str,
286
+ color: str | None = None,
287
+ stroke_dash: str | None = None,
288
+ overlay_point: bool | None = None,
289
+ title: str | None = None,
290
+ tooltip: list[str] | str | None = None,
291
+ x_title: str | None = None,
292
+ y_title: str | None = None,
293
+ color_legend_title: str | None = None,
294
+ stroke_dash_legend_title: str | None = None,
295
+ color_legend_position: Literal[
296
+ "left",
297
+ "right",
298
+ "top",
299
+ "bottom",
300
+ "top-left",
301
+ "top-right",
302
+ "bottom-left",
303
+ "bottom-right",
304
+ "none",
305
+ ]
306
+ | None = None,
307
+ stroke_dash_legend_position: Literal[
308
+ "left",
309
+ "right",
310
+ "top",
311
+ "bottom",
312
+ "top-left",
313
+ "top-right",
314
+ "bottom-left",
315
+ "bottom-right",
316
+ "none",
317
+ ]
318
+ | None = None,
319
+ height: int | None = None,
320
+ width: int | None = None,
321
+ x_lim: list[int] | None = None,
322
+ y_lim: list[int] | None = None,
323
+ interactive: bool | None = None,
324
+ ):
325
+ """Helper for creating the scatter plot."""
326
+ interactive = True if interactive is None else interactive
327
+ encodings = {
328
+ "x": alt.X(
329
+ x, # type: ignore
330
+ title=x_title or x, # type: ignore
331
+ scale=AltairPlot.create_scale(x_lim), # type: ignore
332
+ ),
333
+ "y": alt.Y(
334
+ y, # type: ignore
335
+ title=y_title or y, # type: ignore
336
+ scale=AltairPlot.create_scale(y_lim), # type: ignore
337
+ ),
338
+ }
339
+ properties = {}
340
+ if title:
341
+ properties["title"] = title
342
+ if height:
343
+ properties["height"] = height
344
+ if width:
345
+ properties["width"] = width
346
+
347
+ if color:
348
+ domain = value[color].unique().tolist()
349
+ range_ = list(range(len(domain)))
350
+ encodings["color"] = {
351
+ "field": color,
352
+ "type": "nominal",
353
+ "scale": {"domain": domain, "range": range_},
354
+ "legend": AltairPlot.create_legend(
355
+ position=color_legend_position, title=color_legend_title or color
356
+ ),
357
+ }
358
+
359
+ highlight = None
360
+ if interactive and any([color, stroke_dash]):
361
+ highlight = alt.selection(
362
+ type="single", # type: ignore
363
+ on="mouseover",
364
+ fields=[c for c in [color, stroke_dash] if c],
365
+ nearest=True,
366
+ )
367
+
368
+ if stroke_dash:
369
+ stroke_dash = {
370
+ "field": stroke_dash, # type: ignore
371
+ "legend": AltairPlot.create_legend( # type: ignore
372
+ position=stroke_dash_legend_position, # type: ignore
373
+ title=stroke_dash_legend_title or stroke_dash, # type: ignore
374
+ ), # type: ignore
375
+ } # type: ignore
376
+ else:
377
+ stroke_dash = alt.value(alt.Undefined) # type: ignore
378
+
379
+ if tooltip:
380
+ encodings["tooltip"] = tooltip
381
+
382
+ chart = alt.Chart(value).encode(**encodings) # type: ignore
383
+
384
+ points = chart.mark_point(clip=True).encode(
385
+ opacity=alt.value(alt.Undefined) if overlay_point else alt.value(0),
386
+ )
387
+ lines = chart.mark_line(clip=True).encode(strokeDash=stroke_dash)
388
+
389
+ if highlight:
390
+ points = points.add_selection(highlight)
391
+
392
+ lines = lines.encode(
393
+ size=alt.condition(highlight, alt.value(4), alt.value(1)),
394
+ )
395
+
396
+ chart = (lines + points).properties(background="transparent", **properties)
397
+ if interactive:
398
+ chart = chart.interactive()
399
+
400
+ return chart
401
+
402
+ def postprocess(self, y: pd.DataFrame | dict | None) -> dict[str, str] | None:
403
+ # if None or update
404
+ if y is None or isinstance(y, dict):
405
+ return y
406
+ if self.x is None or self.y is None:
407
+ raise ValueError("No value provided for required parameters `x` and `y`.")
408
+ chart = self.create_plot(
409
+ value=y,
410
+ x=self.x,
411
+ y=self.y,
412
+ color=self.color,
413
+ overlay_point=self.overlay_point,
414
+ title=self.title,
415
+ tooltip=self.tooltip,
416
+ x_title=self.x_title,
417
+ y_title=self.y_title,
418
+ color_legend_title=self.color_legend_title, # type: ignore
419
+ color_legend_position=self.color_legend_position, # type: ignore
420
+ stroke_dash_legend_title=self.stroke_dash_legend_title,
421
+ stroke_dash_legend_position=self.stroke_dash_legend_position, # type: ignore
422
+ x_lim=self.x_lim,
423
+ y_lim=self.y_lim,
424
+ stroke_dash=self.stroke_dash,
425
+ interactive=self.interactive_chart,
426
+ height=self.height,
427
+ width=self.width,
428
+ )
429
+
430
+ return {"type": "altair", "plot": chart.to_json(), "chart": "line"}
gradio/components/markdown.py ADDED
@@ -0,0 +1,95 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """gr.Markdown() component."""
2
+
3
+ from __future__ import annotations
4
+
5
+ import inspect
6
+ from typing import Any, Callable, Literal
7
+
8
+ from gradio_client.documentation import document, set_documentation_group
9
+ from gradio_client.serializing import StringSerializable
10
+
11
+ from gradio import utils
12
+ from gradio.components.base import Component, IOComponent, _Keywords
13
+ from gradio.events import (
14
+ Changeable,
15
+ )
16
+
17
+ set_documentation_group("component")
18
+
19
+
20
+ @document()
21
+ class Markdown(IOComponent, Changeable, StringSerializable):
22
+ """
23
+ Used to render arbitrary Markdown output. Can also render latex enclosed by dollar signs.
24
+ Preprocessing: this component does *not* accept input.
25
+ Postprocessing: expects a valid {str} that can be rendered as Markdown.
26
+
27
+ Demos: blocks_hello, blocks_kinematics
28
+ Guides: key-features
29
+ """
30
+
31
+ def __init__(
32
+ self,
33
+ value: str | Callable = "",
34
+ *,
35
+ visible: bool = True,
36
+ elem_id: str | None = None,
37
+ elem_classes: list[str] | str | None = None,
38
+ rtl: bool = False,
39
+ **kwargs,
40
+ ):
41
+ """
42
+ Parameters:
43
+ value: Value to show in Markdown component. If callable, the function will be called whenever the app loads to set the initial value of the component.
44
+ visible: If False, component will be hidden.
45
+ 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.
46
+ 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.
47
+ rtl: If True, sets the direction of the rendered text to right-to-left. Default is False, which renders text left-to-right.
48
+ """
49
+ self.md = utils.get_markdown_parser()
50
+ self.rtl = rtl
51
+ IOComponent.__init__(
52
+ self,
53
+ visible=visible,
54
+ elem_id=elem_id,
55
+ elem_classes=elem_classes,
56
+ value=value,
57
+ **kwargs,
58
+ )
59
+
60
+ def postprocess(self, y: str | None) -> str | None:
61
+ """
62
+ Parameters:
63
+ y: markdown representation
64
+ Returns:
65
+ HTML rendering of markdown
66
+ """
67
+ if y is None:
68
+ return None
69
+ unindented_y = inspect.cleandoc(y)
70
+ return self.md.render(unindented_y)
71
+
72
+ def get_config(self):
73
+ return {
74
+ "value": self.value,
75
+ "rtl": self.rtl,
76
+ **Component.get_config(self),
77
+ }
78
+
79
+ @staticmethod
80
+ def update(
81
+ value: Any | Literal[_Keywords.NO_VALUE] | None = _Keywords.NO_VALUE,
82
+ visible: bool | None = None,
83
+ rtl: bool | None = None,
84
+ ):
85
+ updated_config = {
86
+ "visible": visible,
87
+ "value": value,
88
+ "rtl": rtl,
89
+ "__type__": "update",
90
+ }
91
+ return updated_config
92
+
93
+ def as_example(self, input_data: str | None) -> str:
94
+ postprocessed = self.postprocess(input_data)
95
+ return postprocessed if postprocessed else ""
gradio/components/model3d.py ADDED
@@ -0,0 +1,155 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """gr.Model3D() component."""
2
+
3
+ from __future__ import annotations
4
+
5
+ from pathlib import Path
6
+ from typing import Any, Callable, Literal
7
+
8
+ from gradio_client import media_data
9
+ from gradio_client.documentation import document, set_documentation_group
10
+ from gradio_client.serializing import FileSerializable
11
+
12
+ from gradio.components.base import IOComponent, _Keywords
13
+ from gradio.events import (
14
+ Changeable,
15
+ Clearable,
16
+ Editable,
17
+ Uploadable,
18
+ )
19
+
20
+ set_documentation_group("component")
21
+
22
+
23
+ @document()
24
+ class Model3D(
25
+ Changeable, Uploadable, Editable, Clearable, IOComponent, FileSerializable
26
+ ):
27
+ """
28
+ Component allows users to upload or view 3D Model files (.obj, .glb, or .gltf).
29
+ Preprocessing: This component passes the uploaded file as a {str}filepath.
30
+ Postprocessing: expects function to return a {str} or {pathlib.Path} filepath of type (.obj, glb, or .gltf)
31
+
32
+ Demos: model3D
33
+ Guides: how-to-use-3D-model-component
34
+ """
35
+
36
+ def __init__(
37
+ self,
38
+ value: str | Callable | None = None,
39
+ *,
40
+ clear_color: list[float] | None = None,
41
+ label: str | None = None,
42
+ every: float | None = None,
43
+ show_label: bool | None = None,
44
+ container: bool = True,
45
+ scale: int | None = None,
46
+ min_width: int = 160,
47
+ visible: bool = True,
48
+ elem_id: str | None = None,
49
+ elem_classes: list[str] | str | None = None,
50
+ **kwargs,
51
+ ):
52
+ """
53
+ Parameters:
54
+ value: path to (.obj, glb, or .gltf) file to show in model3D viewer. If callable, the function will be called whenever the app loads to set the initial value of the component.
55
+ clear_color: background color of scene
56
+ label: component name in interface.
57
+ every: If `value` is a callable, run the function 'every' number of seconds while the client connection is open. Has no effect otherwise. Queue must be enabled. The event can be accessed (e.g. to cancel it) via this component's .load_event attribute.
58
+ show_label: if True, will display label.
59
+ container: If True, will place the component in a container - providing some extra padding around the border.
60
+ scale: relative width compared to adjacent Components in a Row. For example, if Component A has scale=2, and Component B has scale=1, A will be twice as wide as B. Should be an integer.
61
+ 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.
62
+ visible: If False, component will be hidden.
63
+ 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.
64
+ 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.
65
+ """
66
+ self.clear_color = clear_color or [0, 0, 0, 0]
67
+ IOComponent.__init__(
68
+ self,
69
+ label=label,
70
+ every=every,
71
+ show_label=show_label,
72
+ container=container,
73
+ scale=scale,
74
+ min_width=min_width,
75
+ visible=visible,
76
+ elem_id=elem_id,
77
+ elem_classes=elem_classes,
78
+ value=value,
79
+ **kwargs,
80
+ )
81
+
82
+ def get_config(self):
83
+ return {
84
+ "clearColor": self.clear_color,
85
+ "value": self.value,
86
+ **IOComponent.get_config(self),
87
+ }
88
+
89
+ def example_inputs(self) -> dict[str, Any]:
90
+ return {
91
+ "raw": {"is_file": False, "data": media_data.BASE64_MODEL3D},
92
+ "serialized": "https://github.com/gradio-app/gradio/raw/main/test/test_files/Box.gltf",
93
+ }
94
+
95
+ @staticmethod
96
+ def update(
97
+ value: Any | Literal[_Keywords.NO_VALUE] | None = _Keywords.NO_VALUE,
98
+ label: str | None = None,
99
+ show_label: bool | None = None,
100
+ container: bool | None = None,
101
+ scale: int | None = None,
102
+ min_width: int | None = None,
103
+ visible: bool | None = None,
104
+ ):
105
+ updated_config = {
106
+ "label": label,
107
+ "show_label": show_label,
108
+ "container": container,
109
+ "scale": scale,
110
+ "min_width": min_width,
111
+ "visible": visible,
112
+ "value": value,
113
+ "__type__": "update",
114
+ }
115
+ return updated_config
116
+
117
+ def preprocess(self, x: dict[str, str] | None) -> str | None:
118
+ """
119
+ Parameters:
120
+ x: JSON object with filename as 'name' property and base64 data as 'data' property
121
+ Returns:
122
+ string file path to temporary file with the 3D image model
123
+ """
124
+ if x is None:
125
+ return x
126
+ file_name, file_data, is_file = (
127
+ x["name"],
128
+ x["data"],
129
+ x.get("is_file", False),
130
+ )
131
+ if is_file:
132
+ temp_file_path = self.make_temp_copy_if_needed(file_name)
133
+ else:
134
+ temp_file_path = self.base64_to_temp_file_if_needed(file_data, file_name)
135
+
136
+ return temp_file_path
137
+
138
+ def postprocess(self, y: str | Path | None) -> dict[str, str] | None:
139
+ """
140
+ Parameters:
141
+ y: path to the model
142
+ Returns:
143
+ file name mapped to base64 url data
144
+ """
145
+ if y is None:
146
+ return y
147
+ data = {
148
+ "name": self.make_temp_copy_if_needed(y),
149
+ "data": None,
150
+ "is_file": True,
151
+ }
152
+ return data
153
+
154
+ def as_example(self, input_data: str | None) -> str:
155
+ return Path(input_data).name if input_data else ""
gradio/components/number.py ADDED
@@ -0,0 +1,238 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """gr.Number() component."""
2
+
3
+ from __future__ import annotations
4
+
5
+ import math
6
+ from typing import Callable, Literal
7
+
8
+ import numpy as np
9
+ from gradio_client.documentation import document, set_documentation_group
10
+ from gradio_client.serializing import NumberSerializable
11
+
12
+ from gradio.components.base import FormComponent, IOComponent, _Keywords
13
+ from gradio.events import (
14
+ Blurrable,
15
+ Changeable,
16
+ Inputable,
17
+ Submittable,
18
+ )
19
+ from gradio.exceptions import Error
20
+ from gradio.interpretation import NeighborInterpretable
21
+
22
+ set_documentation_group("component")
23
+
24
+
25
+ @document()
26
+ class Number(
27
+ FormComponent,
28
+ Changeable,
29
+ Inputable,
30
+ Submittable,
31
+ Blurrable,
32
+ IOComponent,
33
+ NumberSerializable,
34
+ NeighborInterpretable,
35
+ ):
36
+ """
37
+ Creates a numeric field for user to enter numbers as input or display numeric output.
38
+ Preprocessing: passes field value as a {float} or {int} into the function, depending on `precision`.
39
+ Postprocessing: expects an {int} or {float} returned from the function and sets field value to it.
40
+ Examples-format: a {float} or {int} representing the number's value.
41
+
42
+ Demos: tax_calculator, titanic_survival, blocks_simple_squares
43
+ """
44
+
45
+ def __init__(
46
+ self,
47
+ value: float | Callable | None = None,
48
+ *,
49
+ label: str | None = None,
50
+ info: str | None = None,
51
+ every: float | None = None,
52
+ show_label: bool | None = None,
53
+ container: bool = True,
54
+ scale: int | None = None,
55
+ min_width: int = 160,
56
+ interactive: bool | None = None,
57
+ visible: bool = True,
58
+ elem_id: str | None = None,
59
+ elem_classes: list[str] | str | None = None,
60
+ precision: int | None = None,
61
+ minimum: float | None = None,
62
+ maximum: float | None = None,
63
+ **kwargs,
64
+ ):
65
+ """
66
+ Parameters:
67
+ value: default value. If callable, the function will be called whenever the app loads to set the initial value of the component.
68
+ label: component name in interface.
69
+ info: additional component description.
70
+ every: If `value` is a callable, run the function 'every' number of seconds while the client connection is open. Has no effect otherwise. Queue must be enabled. The event can be accessed (e.g. to cancel it) via this component's .load_event attribute.
71
+ show_label: if True, will display label.
72
+ container: If True, will place the component in a container - providing some extra padding around the border.
73
+ scale: relative width compared to adjacent Components in a Row. For example, if Component A has scale=2, and Component B has scale=1, A will be twice as wide as B. Should be an integer.
74
+ 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.
75
+ interactive: if True, will be editable; if False, editing will be disabled. If not provided, this is inferred based on whether the component is used as an input or output.
76
+ visible: If False, component will be hidden.
77
+ 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.
78
+ 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.
79
+ precision: Precision to round input/output to. If set to 0, will round to nearest integer and convert type to int. If None, no rounding happens.
80
+ minimum: Minimum value. Only applied when component is used as an input. If a user provides a smaller value, a gr.Error exception is raised by the backend.
81
+ maximum: Maximum value. Only applied when component is used as an input. If a user provides a larger value, a gr.Error exception is raised by the backend.
82
+ """
83
+ self.precision = precision
84
+ self.minimum = minimum
85
+ self.maximum = maximum
86
+
87
+ IOComponent.__init__(
88
+ self,
89
+ label=label,
90
+ info=info,
91
+ every=every,
92
+ show_label=show_label,
93
+ container=container,
94
+ scale=scale,
95
+ min_width=min_width,
96
+ interactive=interactive,
97
+ visible=visible,
98
+ elem_id=elem_id,
99
+ elem_classes=elem_classes,
100
+ value=value,
101
+ **kwargs,
102
+ )
103
+ NeighborInterpretable.__init__(self)
104
+
105
+ @staticmethod
106
+ def _round_to_precision(num: float | int, precision: int | None) -> float | int:
107
+ """
108
+ Round to a given precision.
109
+
110
+ If precision is None, no rounding happens. If 0, num is converted to int.
111
+
112
+ Parameters:
113
+ num: Number to round.
114
+ precision: Precision to round to.
115
+ Returns:
116
+ rounded number
117
+ """
118
+ if precision is None:
119
+ return float(num)
120
+ elif precision == 0:
121
+ return int(round(num, precision))
122
+ else:
123
+ return round(num, precision)
124
+
125
+ def get_config(self):
126
+ return {
127
+ "value": self.value,
128
+ "minimum": self.minimum,
129
+ "maximum": self.maximum,
130
+ "container": self.container,
131
+ **IOComponent.get_config(self),
132
+ }
133
+
134
+ @staticmethod
135
+ def update(
136
+ value: float | Literal[_Keywords.NO_VALUE] | None = _Keywords.NO_VALUE,
137
+ minimum: float | None = None,
138
+ maximum: float | None = None,
139
+ label: str | None = None,
140
+ info: str | None = None,
141
+ show_label: bool | None = None,
142
+ container: bool | None = None,
143
+ scale: int | None = None,
144
+ min_width: int | None = None,
145
+ interactive: bool | None = None,
146
+ visible: bool | None = None,
147
+ ):
148
+ return {
149
+ "label": label,
150
+ "info": info,
151
+ "show_label": show_label,
152
+ "container": container,
153
+ "scale": scale,
154
+ "min_width": min_width,
155
+ "visible": visible,
156
+ "value": value,
157
+ "minimum": minimum,
158
+ "maximum": maximum,
159
+ "interactive": interactive,
160
+ "__type__": "update",
161
+ }
162
+
163
+ def preprocess(self, x: float | None) -> float | None:
164
+ """
165
+ Parameters:
166
+ x: numeric input
167
+ Returns:
168
+ number representing function input
169
+ """
170
+ if x is None:
171
+ return None
172
+ elif self.minimum is not None and x < self.minimum:
173
+ raise Error(f"Value {x} is less than minimum value {self.minimum}.")
174
+ elif self.maximum is not None and x > self.maximum:
175
+ raise Error(f"Value {x} is greater than maximum value {self.maximum}.")
176
+ return self._round_to_precision(x, self.precision)
177
+
178
+ def postprocess(self, y: float | None) -> float | None:
179
+ """
180
+ Any postprocessing needed to be performed on function output.
181
+
182
+ Parameters:
183
+ y: numeric output
184
+ Returns:
185
+ number representing function output
186
+ """
187
+ if y is None:
188
+ return None
189
+ return self._round_to_precision(y, self.precision)
190
+
191
+ def set_interpret_parameters(
192
+ self, steps: int = 3, delta: float = 1, delta_type: str = "percent"
193
+ ):
194
+ """
195
+ Calculates interpretation scores of numeric values close to the input number.
196
+ Parameters:
197
+ steps: Number of nearby values to measure in each direction (above and below the input number).
198
+ delta: Size of step in each direction between nearby values.
199
+ delta_type: "percent" if delta step between nearby values should be a calculated as a percent, or "absolute" if delta should be a constant step change.
200
+ """
201
+ self.interpretation_steps = steps
202
+ self.interpretation_delta = delta
203
+ self.interpretation_delta_type = delta_type
204
+ return self
205
+
206
+ def get_interpretation_neighbors(self, x: float | int) -> tuple[list[float], dict]:
207
+ x = self._round_to_precision(x, self.precision)
208
+ if self.interpretation_delta_type == "percent":
209
+ delta = 1.0 * self.interpretation_delta * x / 100
210
+ elif self.interpretation_delta_type == "absolute":
211
+ delta = self.interpretation_delta
212
+ else:
213
+ delta = self.interpretation_delta
214
+ if self.precision == 0 and math.floor(delta) != delta:
215
+ raise ValueError(
216
+ f"Delta value {delta} is not an integer and precision=0. Cannot generate valid set of neighbors. "
217
+ "If delta_type='percent', pick a value of delta such that x * delta is an integer. "
218
+ "If delta_type='absolute', pick a value of delta that is an integer."
219
+ )
220
+ # run_interpretation will preprocess the neighbors so no need to convert to int here
221
+ negatives = (
222
+ np.array(x) + np.arange(-self.interpretation_steps, 0) * delta
223
+ ).tolist()
224
+ positives = (
225
+ np.array(x) + np.arange(1, self.interpretation_steps + 1) * delta
226
+ ).tolist()
227
+ return negatives + positives, {}
228
+
229
+ def get_interpretation_scores(
230
+ self, x: float, neighbors: list[float], scores: list[float | None], **kwargs
231
+ ) -> list[tuple[float, float | None]]:
232
+ """
233
+ Returns:
234
+ Each tuple set represents a numeric value near the input and its corresponding interpretation score.
235
+ """
236
+ interpretation = list(zip(neighbors, scores))
237
+ interpretation.insert(int(len(interpretation) / 2), (x, None))
238
+ return interpretation
gradio/components/plot.py ADDED
@@ -0,0 +1,159 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """gr.Plot() component."""
2
+
3
+ from __future__ import annotations
4
+
5
+ import json
6
+ from types import ModuleType
7
+ from typing import Any, Callable, Literal
8
+
9
+ import altair as alt
10
+ import pandas as pd
11
+ from gradio_client.documentation import document, set_documentation_group
12
+ from gradio_client.serializing import JSONSerializable
13
+
14
+ from gradio import processing_utils
15
+ from gradio.components.base import IOComponent, _Keywords
16
+ from gradio.deprecation import warn_style_method_deprecation
17
+ from gradio.events import Changeable, Clearable
18
+
19
+ set_documentation_group("component")
20
+
21
+
22
+ @document()
23
+ class Plot(Changeable, Clearable, IOComponent, JSONSerializable):
24
+ """
25
+ Used to display various kinds of plots (matplotlib, plotly, or bokeh are supported)
26
+ Preprocessing: this component does *not* accept input.
27
+ Postprocessing: expects either a {matplotlib.figure.Figure}, a {plotly.graph_objects._figure.Figure}, or a {dict} corresponding to a bokeh plot (json_item format)
28
+
29
+ Demos: altair_plot, outbreak_forecast, blocks_kinematics, stock_forecast, map_airbnb
30
+ Guides: plot-component-for-maps
31
+ """
32
+
33
+ def __init__(
34
+ self,
35
+ value: Callable | None | pd.DataFrame = None,
36
+ *,
37
+ label: str | None = None,
38
+ every: float | None = None,
39
+ show_label: bool | None = None,
40
+ container: bool = True,
41
+ scale: int | None = None,
42
+ min_width: int = 160,
43
+ visible: bool = True,
44
+ elem_id: str | None = None,
45
+ elem_classes: list[str] | str | None = None,
46
+ **kwargs,
47
+ ):
48
+ """
49
+ Parameters:
50
+ value: Optionally, supply a default plot object to display, must be a matplotlib, plotly, altair, or bokeh figure, or a callable. If callable, the function will be called whenever the app loads to set the initial value of the component.
51
+ label: component name in interface.
52
+ every: If `value` is a callable, run the function 'every' number of seconds while the client connection is open. Has no effect otherwise. Queue must be enabled. The event can be accessed (e.g. to cancel it) via this component's .load_event attribute.
53
+ show_label: if True, will display label.
54
+ container: If True, will place the component in a container - providing some extra padding around the border.
55
+ scale: relative width compared to adjacent Components in a Row. For example, if Component A has scale=2, and Component B has scale=1, A will be twice as wide as B. Should be an integer.
56
+ 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.
57
+ visible: If False, component will be hidden.
58
+ 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.
59
+ 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.
60
+ """
61
+ IOComponent.__init__(
62
+ self,
63
+ label=label,
64
+ every=every,
65
+ show_label=show_label,
66
+ container=container,
67
+ scale=scale,
68
+ min_width=min_width,
69
+ visible=visible,
70
+ elem_id=elem_id,
71
+ elem_classes=elem_classes,
72
+ value=value,
73
+ **kwargs,
74
+ )
75
+
76
+ def get_config(self):
77
+ try:
78
+ import bokeh # type: ignore
79
+
80
+ bokeh_version = bokeh.__version__
81
+ except ImportError:
82
+ bokeh_version = None
83
+ return {
84
+ "value": self.value,
85
+ "bokeh_version": bokeh_version,
86
+ **IOComponent.get_config(self),
87
+ }
88
+
89
+ @staticmethod
90
+ def update(
91
+ value: Any | Literal[_Keywords.NO_VALUE] | None = _Keywords.NO_VALUE,
92
+ label: str | None = None,
93
+ show_label: bool | None = None,
94
+ container: bool | None = None,
95
+ scale: int | None = None,
96
+ min_width: int | None = None,
97
+ visible: bool | None = None,
98
+ ):
99
+ updated_config = {
100
+ "label": label,
101
+ "show_label": show_label,
102
+ "container": container,
103
+ "scale": scale,
104
+ "min_width": min_width,
105
+ "visible": visible,
106
+ "value": value,
107
+ "__type__": "update",
108
+ }
109
+ return updated_config
110
+
111
+ def postprocess(self, y) -> dict[str, str] | None:
112
+ """
113
+ Parameters:
114
+ y: plot data
115
+ Returns:
116
+ plot type mapped to plot base64 data
117
+ """
118
+ import matplotlib.figure
119
+
120
+ if y is None:
121
+ return None
122
+ if isinstance(y, (ModuleType, matplotlib.figure.Figure)): # type: ignore
123
+ dtype = "matplotlib"
124
+ out_y = processing_utils.encode_plot_to_base64(y)
125
+ elif "bokeh" in y.__module__:
126
+ dtype = "bokeh"
127
+ from bokeh.embed import json_item # type: ignore
128
+
129
+ out_y = json.dumps(json_item(y))
130
+ else:
131
+ is_altair = "altair" in y.__module__
132
+ dtype = "altair" if is_altair else "plotly"
133
+ out_y = y.to_json()
134
+ return {"type": dtype, "plot": out_y}
135
+
136
+ def style(self, container: bool | None = None):
137
+ """
138
+ This method is deprecated. Please set these arguments in the constructor instead.
139
+ """
140
+ warn_style_method_deprecation()
141
+ if container is not None:
142
+ self.container = container
143
+ return self
144
+
145
+
146
+ class AltairPlot:
147
+ @staticmethod
148
+ def create_legend(position, title):
149
+ if position == "none":
150
+ legend = None
151
+ else:
152
+ position = {"orient": position} if position else {}
153
+ legend = {"title": title, **position}
154
+
155
+ return legend
156
+
157
+ @staticmethod
158
+ def create_scale(limit):
159
+ return alt.Scale(domain=limit) if limit else alt.Undefined
gradio/components/radio.py ADDED
@@ -0,0 +1,193 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """gr.Radio() component."""
2
+
3
+ from __future__ import annotations
4
+
5
+ from typing import Any, Callable, Literal
6
+
7
+ from gradio_client.documentation import document, set_documentation_group
8
+ from gradio_client.serializing import StringSerializable
9
+
10
+ from gradio.components.base import FormComponent, IOComponent, _Keywords
11
+ from gradio.deprecation import warn_deprecation, warn_style_method_deprecation
12
+ from gradio.events import Changeable, EventListenerMethod, Inputable, Selectable
13
+ from gradio.interpretation import NeighborInterpretable
14
+
15
+ set_documentation_group("component")
16
+
17
+
18
+ @document()
19
+ class Radio(
20
+ FormComponent,
21
+ Selectable,
22
+ Changeable,
23
+ Inputable,
24
+ IOComponent,
25
+ StringSerializable,
26
+ NeighborInterpretable,
27
+ ):
28
+ """
29
+ Creates a set of radio buttons of which only one can be selected.
30
+ Preprocessing: passes the value of the selected radio button as a {str} or its index as an {int} into the function, depending on `type`.
31
+ Postprocessing: expects a {str} corresponding to the value of the radio button to be selected.
32
+ Examples-format: a {str} representing the radio option to select.
33
+
34
+ Demos: sentence_builder, titanic_survival, blocks_essay
35
+ """
36
+
37
+ def __init__(
38
+ self,
39
+ choices: list[str] | None = None,
40
+ *,
41
+ value: str | Callable | None = None,
42
+ type: str = "value",
43
+ label: str | None = None,
44
+ info: str | None = None,
45
+ every: float | None = None,
46
+ show_label: bool | None = None,
47
+ container: bool = True,
48
+ scale: int | None = None,
49
+ min_width: int = 160,
50
+ interactive: bool | None = None,
51
+ visible: bool = True,
52
+ elem_id: str | None = None,
53
+ elem_classes: list[str] | str | None = None,
54
+ **kwargs,
55
+ ):
56
+ """
57
+ Parameters:
58
+ choices: list of options to select from.
59
+ value: the button selected by default. If None, no button is selected by default. If callable, the function will be called whenever the app loads to set the initial value of the component.
60
+ type: Type of value to be returned by component. "value" returns the string of the choice selected, "index" returns the index of the choice selected.
61
+ label: component name in interface.
62
+ info: additional component description.
63
+ every: If `value` is a callable, run the function 'every' number of seconds while the client connection is open. Has no effect otherwise. Queue must be enabled. The event can be accessed (e.g. to cancel it) via this component's .load_event attribute.
64
+ show_label: if True, will display label.
65
+ container: If True, will place the component in a container - providing some extra padding around the border.
66
+ scale: relative width compared to adjacent Components in a Row. For example, if Component A has scale=2, and Component B has scale=1, A will be twice as wide as B. Should be an integer.
67
+ 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.
68
+ interactive: if True, choices in this radio group will be selectable; if False, selection will be disabled. If not provided, this is inferred based on whether the component is used as an input or output.
69
+ visible: If False, component will be hidden.
70
+ 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.
71
+ 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.
72
+ """
73
+ self.choices = choices or []
74
+ valid_types = ["value", "index"]
75
+ if type not in valid_types:
76
+ raise ValueError(
77
+ f"Invalid value for parameter `type`: {type}. Please choose from one of: {valid_types}"
78
+ )
79
+ self.type = type
80
+ self.select: EventListenerMethod
81
+ """
82
+ Event listener for when the user selects Radio option.
83
+ Uses event data gradio.SelectData to carry `value` referring to label of selected option, and `index` to refer to index.
84
+ See EventData documentation on how to use this event data.
85
+ """
86
+ IOComponent.__init__(
87
+ self,
88
+ label=label,
89
+ info=info,
90
+ every=every,
91
+ show_label=show_label,
92
+ container=container,
93
+ scale=scale,
94
+ min_width=min_width,
95
+ interactive=interactive,
96
+ visible=visible,
97
+ elem_id=elem_id,
98
+ elem_classes=elem_classes,
99
+ value=value,
100
+ **kwargs,
101
+ )
102
+ NeighborInterpretable.__init__(self)
103
+
104
+ def get_config(self):
105
+ return {
106
+ "choices": self.choices,
107
+ "value": self.value,
108
+ **IOComponent.get_config(self),
109
+ }
110
+
111
+ def example_inputs(self) -> dict[str, Any]:
112
+ return {
113
+ "raw": self.choices[0] if self.choices else None,
114
+ "serialized": self.choices[0] if self.choices else None,
115
+ }
116
+
117
+ @staticmethod
118
+ def update(
119
+ value: Any | Literal[_Keywords.NO_VALUE] | None = _Keywords.NO_VALUE,
120
+ choices: list[str] | None = None,
121
+ label: str | None = None,
122
+ info: str | None = None,
123
+ show_label: bool | None = None,
124
+ container: bool | None = None,
125
+ scale: int | None = None,
126
+ min_width: int | None = None,
127
+ interactive: bool | None = None,
128
+ visible: bool | None = None,
129
+ ):
130
+ return {
131
+ "choices": choices,
132
+ "label": label,
133
+ "info": info,
134
+ "show_label": show_label,
135
+ "container": container,
136
+ "scale": scale,
137
+ "min_width": min_width,
138
+ "interactive": interactive,
139
+ "visible": visible,
140
+ "value": value,
141
+ "__type__": "update",
142
+ }
143
+
144
+ def preprocess(self, x: str | None) -> str | int | None:
145
+ """
146
+ Parameters:
147
+ x: selected choice
148
+ Returns:
149
+ selected choice as string or index within choice list
150
+ """
151
+ if self.type == "value":
152
+ return x
153
+ elif self.type == "index":
154
+ if x is None:
155
+ return None
156
+ else:
157
+ return self.choices.index(x)
158
+ else:
159
+ raise ValueError(
160
+ f"Unknown type: {self.type}. Please choose from: 'value', 'index'."
161
+ )
162
+
163
+ def get_interpretation_neighbors(self, x):
164
+ choices = list(self.choices)
165
+ choices.remove(x)
166
+ return choices, {}
167
+
168
+ def get_interpretation_scores(
169
+ self, x, neighbors, scores: list[float | None], **kwargs
170
+ ) -> list:
171
+ """
172
+ Returns:
173
+ Each value represents the interpretation score corresponding to each choice.
174
+ """
175
+ scores.insert(self.choices.index(x), None)
176
+ return scores
177
+
178
+ def style(
179
+ self,
180
+ *,
181
+ item_container: bool | None = None,
182
+ container: bool | None = None,
183
+ **kwargs,
184
+ ):
185
+ """
186
+ This method is deprecated. Please set these arguments in the constructor instead.
187
+ """
188
+ warn_style_method_deprecation()
189
+ if item_container is not None:
190
+ warn_deprecation("The `item_container` parameter is deprecated.")
191
+ if container is not None:
192
+ self.container = container
193
+ return self
gradio/components/scatter_plot.py ADDED
@@ -0,0 +1,472 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """gr.ScatterPlot() component."""
2
+
3
+ from __future__ import annotations
4
+
5
+ from typing import Callable, Literal
6
+
7
+ import altair as alt
8
+ import pandas as pd
9
+ from gradio_client.documentation import document, set_documentation_group
10
+ from pandas.api.types import is_numeric_dtype
11
+
12
+ from gradio.components.base import _Keywords
13
+ from gradio.components.plot import AltairPlot, Plot
14
+
15
+ set_documentation_group("component")
16
+
17
+
18
+ @document()
19
+ class ScatterPlot(Plot):
20
+ """
21
+ Create a scatter plot.
22
+
23
+ Preprocessing: this component does *not* accept input.
24
+ Postprocessing: expects a pandas dataframe with the data to plot.
25
+
26
+ Demos: scatter_plot
27
+ Guides: creating-a-dashboard-from-bigquery-data
28
+ """
29
+
30
+ def __init__(
31
+ self,
32
+ value: pd.DataFrame | Callable | None = None,
33
+ x: str | None = None,
34
+ y: str | None = None,
35
+ *,
36
+ color: str | None = None,
37
+ size: str | None = None,
38
+ shape: str | None = None,
39
+ title: str | None = None,
40
+ tooltip: list[str] | str | None = None,
41
+ x_title: str | None = None,
42
+ y_title: str | None = None,
43
+ color_legend_title: str | None = None,
44
+ size_legend_title: str | None = None,
45
+ shape_legend_title: str | None = None,
46
+ color_legend_position: Literal[
47
+ "left",
48
+ "right",
49
+ "top",
50
+ "bottom",
51
+ "top-left",
52
+ "top-right",
53
+ "bottom-left",
54
+ "bottom-right",
55
+ "none",
56
+ ]
57
+ | None = None,
58
+ size_legend_position: Literal[
59
+ "left",
60
+ "right",
61
+ "top",
62
+ "bottom",
63
+ "top-left",
64
+ "top-right",
65
+ "bottom-left",
66
+ "bottom-right",
67
+ "none",
68
+ ]
69
+ | None = None,
70
+ shape_legend_position: Literal[
71
+ "left",
72
+ "right",
73
+ "top",
74
+ "bottom",
75
+ "top-left",
76
+ "top-right",
77
+ "bottom-left",
78
+ "bottom-right",
79
+ "none",
80
+ ]
81
+ | None = None,
82
+ height: int | None = None,
83
+ width: int | None = None,
84
+ x_lim: list[int | float] | None = None,
85
+ y_lim: list[int | float] | None = None,
86
+ caption: str | None = None,
87
+ interactive: bool | None = True,
88
+ label: str | None = None,
89
+ every: float | None = None,
90
+ show_label: bool | None = None,
91
+ container: bool = True,
92
+ scale: int | None = None,
93
+ min_width: int = 160,
94
+ visible: bool = True,
95
+ elem_id: str | None = None,
96
+ elem_classes: list[str] | str | None = None,
97
+ ):
98
+ """
99
+ Parameters:
100
+ value: The pandas dataframe containing the data to display in a scatter plot, or a callable. If callable, the function will be called whenever the app loads to set the initial value of the component.
101
+ x: Column corresponding to the x axis.
102
+ y: Column corresponding to the y axis.
103
+ color: The column to determine the point color. If the column contains numeric data, gradio will interpolate the column data so that small values correspond to light colors and large values correspond to dark values.
104
+ size: The column used to determine the point size. Should contain numeric data so that gradio can map the data to the point size.
105
+ shape: The column used to determine the point shape. Should contain categorical data. Gradio will map each unique value to a different shape.
106
+ title: The title to display on top of the chart.
107
+ tooltip: The column (or list of columns) to display on the tooltip when a user hovers a point on the plot.
108
+ x_title: The title given to the x axis. By default, uses the value of the x parameter.
109
+ y_title: The title given to the y axis. By default, uses the value of the y parameter.
110
+ color_legend_title: The title given to the color legend. By default, uses the value of color parameter.
111
+ size_legend_title: The title given to the size legend. By default, uses the value of the size parameter.
112
+ shape_legend_title: The title given to the shape legend. By default, uses the value of the shape parameter.
113
+ color_legend_position: The position of the color legend. If the string value 'none' is passed, this legend is omitted. For other valid position values see: https://vega.github.io/vega/docs/legends/#orientation.
114
+ size_legend_position: The position of the size legend. If the string value 'none' is passed, this legend is omitted. For other valid position values see: https://vega.github.io/vega/docs/legends/#orientation.
115
+ shape_legend_position: The position of the shape legend. If the string value 'none' is passed, this legend is omitted. For other valid position values see: https://vega.github.io/vega/docs/legends/#orientation.
116
+ height: The height of the plot in pixels.
117
+ width: The width of the plot in pixels.
118
+ x_lim: A tuple or list containing the limits for the x-axis, specified as [x_min, x_max].
119
+ y_lim: A tuple of list containing the limits for the y-axis, specified as [y_min, y_max].
120
+ caption: The (optional) caption to display below the plot.
121
+ interactive: Whether users should be able to interact with the plot by panning or zooming with their mouse or trackpad.
122
+ label: The (optional) label to display on the top left corner of the plot.
123
+ every: If `value` is a callable, run the function 'every' number of seconds while the client connection is open. Has no effect otherwise. Queue must be enabled. The event can be accessed (e.g. to cancel it) via this component's .load_event attribute.
124
+ show_label: Whether the label should be displayed.
125
+ visible: Whether the plot should be visible.
126
+ 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.
127
+ 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.
128
+ """
129
+ self.x = x
130
+ self.y = y
131
+ self.color = color
132
+ self.size = size
133
+ self.shape = shape
134
+ self.tooltip = tooltip
135
+ self.title = title
136
+ self.x_title = x_title
137
+ self.y_title = y_title
138
+ self.color_legend_title = color_legend_title
139
+ self.color_legend_position = color_legend_position
140
+ self.size_legend_title = size_legend_title
141
+ self.size_legend_position = size_legend_position
142
+ self.shape_legend_title = shape_legend_title
143
+ self.shape_legend_position = shape_legend_position
144
+ self.caption = caption
145
+ self.interactive_chart = interactive
146
+ self.width = width
147
+ self.height = height
148
+ self.x_lim = x_lim
149
+ self.y_lim = y_lim
150
+ super().__init__(
151
+ value=value,
152
+ label=label,
153
+ every=every,
154
+ show_label=show_label,
155
+ container=container,
156
+ scale=scale,
157
+ min_width=min_width,
158
+ visible=visible,
159
+ elem_id=elem_id,
160
+ elem_classes=elem_classes,
161
+ )
162
+
163
+ def get_config(self):
164
+ config = super().get_config()
165
+ config["caption"] = self.caption
166
+ return config
167
+
168
+ def get_block_name(self) -> str:
169
+ return "plot"
170
+
171
+ @staticmethod
172
+ def update(
173
+ value: pd.DataFrame | dict | Literal[_Keywords.NO_VALUE] = _Keywords.NO_VALUE,
174
+ x: str | None = None,
175
+ y: str | None = None,
176
+ color: str | None = None,
177
+ size: str | None = None,
178
+ shape: str | None = None,
179
+ title: str | None = None,
180
+ tooltip: list[str] | str | None = None,
181
+ x_title: str | None = None,
182
+ y_title: str | None = None,
183
+ color_legend_title: str | None = None,
184
+ size_legend_title: str | None = None,
185
+ shape_legend_title: str | None = None,
186
+ color_legend_position: Literal[
187
+ "left",
188
+ "right",
189
+ "top",
190
+ "bottom",
191
+ "top-left",
192
+ "top-right",
193
+ "bottom-left",
194
+ "bottom-right",
195
+ "none",
196
+ ]
197
+ | None = None,
198
+ size_legend_position: Literal[
199
+ "left",
200
+ "right",
201
+ "top",
202
+ "bottom",
203
+ "top-left",
204
+ "top-right",
205
+ "bottom-left",
206
+ "bottom-right",
207
+ "none",
208
+ ]
209
+ | None = None,
210
+ shape_legend_position: Literal[
211
+ "left",
212
+ "right",
213
+ "top",
214
+ "bottom",
215
+ "top-left",
216
+ "top-right",
217
+ "bottom-left",
218
+ "bottom-right",
219
+ "none",
220
+ ]
221
+ | None = None,
222
+ height: int | None = None,
223
+ width: int | None = None,
224
+ x_lim: list[int | float] | None = None,
225
+ y_lim: list[int | float] | None = None,
226
+ interactive: bool | None = None,
227
+ caption: str | None = None,
228
+ label: str | None = None,
229
+ show_label: bool | None = None,
230
+ container: bool | None = None,
231
+ scale: int | None = None,
232
+ min_width: int | None = None,
233
+ visible: bool | None = None,
234
+ ):
235
+ """Update an existing plot component.
236
+
237
+ If updating any of the plot properties (color, size, etc) the value, x, and y parameters must be specified.
238
+
239
+ Parameters:
240
+ value: The pandas dataframe containing the data to display in a scatter plot.
241
+ x: Column corresponding to the x axis.
242
+ y: Column corresponding to the y axis.
243
+ color: The column to determine the point color. If the column contains numeric data, gradio will interpolate the column data so that small values correspond to light colors and large values correspond to dark values.
244
+ size: The column used to determine the point size. Should contain numeric data so that gradio can map the data to the point size.
245
+ shape: The column used to determine the point shape. Should contain categorical data. Gradio will map each unique value to a different shape.
246
+ title: The title to display on top of the chart.
247
+ tooltip: The column (or list of columns) to display on the tooltip when a user hovers a point on the plot.
248
+ x_title: The title given to the x axis. By default, uses the value of the x parameter.
249
+ y_title: The title given to the y axis. By default, uses the value of the y parameter.
250
+ color_legend_title: The title given to the color legend. By default, uses the value of color parameter.
251
+ size_legend_title: The title given to the size legend. By default, uses the value of the size parameter.
252
+ shape_legend_title: The title given to the shape legend. By default, uses the value of the shape parameter.
253
+ color_legend_position: The position of the color legend. If the string value 'none' is passed, this legend is omitted. For other valid position values see: https://vega.github.io/vega/docs/legends/#orientation.
254
+ size_legend_position: The position of the size legend. If the string value 'none' is passed, this legend is omitted. For other valid position values see: https://vega.github.io/vega/docs/legends/#orientation.
255
+ shape_legend_position: The position of the shape legend. If the string value 'none' is passed, this legend is omitted. For other valid position values see: https://vega.github.io/vega/docs/legends/#orientation.
256
+ height: The height of the plot in pixels.
257
+ width: The width of the plot in pixels.
258
+ x_lim: A tuple or list containing the limits for the x-axis, specified as [x_min, x_max].
259
+ y_lim: A tuple of list containing the limits for the y-axis, specified as [y_min, y_max].
260
+ interactive: Whether users should be able to interact with the plot by panning or zooming with their mouse or trackpad.
261
+ caption: The (optional) caption to display below the plot.
262
+ label: The (optional) label to display in the top left corner of the plot.
263
+ show_label: Whether the label should be displayed.
264
+ visible: Whether the plot should be visible.
265
+ """
266
+ properties = [
267
+ x,
268
+ y,
269
+ color,
270
+ size,
271
+ shape,
272
+ title,
273
+ tooltip,
274
+ x_title,
275
+ y_title,
276
+ color_legend_title,
277
+ size_legend_title,
278
+ shape_legend_title,
279
+ color_legend_position,
280
+ size_legend_position,
281
+ shape_legend_position,
282
+ height,
283
+ width,
284
+ x_lim,
285
+ y_lim,
286
+ interactive,
287
+ ]
288
+ if any(properties):
289
+ if not isinstance(value, pd.DataFrame):
290
+ raise ValueError(
291
+ "In order to update plot properties the value parameter "
292
+ "must be provided, and it must be a Dataframe. Please pass a value "
293
+ "parameter to gr.ScatterPlot.update."
294
+ )
295
+ if x is None or y is None:
296
+ raise ValueError(
297
+ "In order to update plot properties, the x and y axis data "
298
+ "must be specified. Please pass valid values for x an y to "
299
+ "gr.ScatterPlot.update."
300
+ )
301
+ chart = ScatterPlot.create_plot(value, *properties)
302
+ value = {"type": "altair", "plot": chart.to_json(), "chart": "scatter"}
303
+
304
+ updated_config = {
305
+ "label": label,
306
+ "show_label": show_label,
307
+ "container": container,
308
+ "scale": scale,
309
+ "min_width": min_width,
310
+ "visible": visible,
311
+ "value": value,
312
+ "caption": caption,
313
+ "__type__": "update",
314
+ }
315
+ return updated_config
316
+
317
+ @staticmethod
318
+ def create_plot(
319
+ value: pd.DataFrame,
320
+ x: str,
321
+ y: str,
322
+ color: str | None = None,
323
+ size: str | None = None,
324
+ shape: str | None = None,
325
+ title: str | None = None,
326
+ tooltip: list[str] | str | None = None,
327
+ x_title: str | None = None,
328
+ y_title: str | None = None,
329
+ color_legend_title: str | None = None,
330
+ size_legend_title: str | None = None,
331
+ shape_legend_title: str | None = None,
332
+ color_legend_position: Literal[
333
+ "left",
334
+ "right",
335
+ "top",
336
+ "bottom",
337
+ "top-left",
338
+ "top-right",
339
+ "bottom-left",
340
+ "bottom-right",
341
+ "none",
342
+ ]
343
+ | None = None,
344
+ size_legend_position: Literal[
345
+ "left",
346
+ "right",
347
+ "top",
348
+ "bottom",
349
+ "top-left",
350
+ "top-right",
351
+ "bottom-left",
352
+ "bottom-right",
353
+ "none",
354
+ ]
355
+ | None = None,
356
+ shape_legend_position: Literal[
357
+ "left",
358
+ "right",
359
+ "top",
360
+ "bottom",
361
+ "top-left",
362
+ "top-right",
363
+ "bottom-left",
364
+ "bottom-right",
365
+ "none",
366
+ ]
367
+ | None = None,
368
+ height: int | None = None,
369
+ width: int | None = None,
370
+ x_lim: list[int | float] | None = None,
371
+ y_lim: list[int | float] | None = None,
372
+ interactive: bool | None = True,
373
+ ):
374
+ """Helper for creating the scatter plot."""
375
+ interactive = True if interactive is None else interactive
376
+ encodings = {
377
+ "x": alt.X(
378
+ x, # type: ignore
379
+ title=x_title or x, # type: ignore
380
+ scale=AltairPlot.create_scale(x_lim), # type: ignore
381
+ ), # ignore: type
382
+ "y": alt.Y(
383
+ y, # type: ignore
384
+ title=y_title or y, # type: ignore
385
+ scale=AltairPlot.create_scale(y_lim), # type: ignore
386
+ ),
387
+ }
388
+ properties = {}
389
+ if title:
390
+ properties["title"] = title
391
+ if height:
392
+ properties["height"] = height
393
+ if width:
394
+ properties["width"] = width
395
+ if color:
396
+ if is_numeric_dtype(value[color]):
397
+ domain = [value[color].min(), value[color].max()]
398
+ range_ = [0, 1]
399
+ type_ = "quantitative"
400
+ else:
401
+ domain = value[color].unique().tolist()
402
+ range_ = list(range(len(domain)))
403
+ type_ = "nominal"
404
+
405
+ encodings["color"] = {
406
+ "field": color,
407
+ "type": type_,
408
+ "legend": AltairPlot.create_legend(
409
+ position=color_legend_position, title=color_legend_title or color
410
+ ),
411
+ "scale": {"domain": domain, "range": range_},
412
+ }
413
+ if tooltip:
414
+ encodings["tooltip"] = tooltip
415
+ if size:
416
+ encodings["size"] = {
417
+ "field": size,
418
+ "type": "quantitative" if is_numeric_dtype(value[size]) else "nominal",
419
+ "legend": AltairPlot.create_legend(
420
+ position=size_legend_position, title=size_legend_title or size
421
+ ),
422
+ }
423
+ if shape:
424
+ encodings["shape"] = {
425
+ "field": shape,
426
+ "type": "quantitative" if is_numeric_dtype(value[shape]) else "nominal",
427
+ "legend": AltairPlot.create_legend(
428
+ position=shape_legend_position, title=shape_legend_title or shape
429
+ ),
430
+ }
431
+ chart = (
432
+ alt.Chart(value) # type: ignore
433
+ .mark_point(clip=True) # type: ignore
434
+ .encode(**encodings)
435
+ .properties(background="transparent", **properties)
436
+ )
437
+ if interactive:
438
+ chart = chart.interactive()
439
+
440
+ return chart
441
+
442
+ def postprocess(self, y: pd.DataFrame | dict | None) -> dict[str, str] | None:
443
+ # if None or update
444
+ if y is None or isinstance(y, dict):
445
+ return y
446
+ if self.x is None or self.y is None:
447
+ raise ValueError("No value provided for required parameters `x` and `y`.")
448
+ chart = self.create_plot(
449
+ value=y,
450
+ x=self.x,
451
+ y=self.y,
452
+ color=self.color,
453
+ size=self.size,
454
+ shape=self.shape,
455
+ title=self.title,
456
+ tooltip=self.tooltip,
457
+ x_title=self.x_title,
458
+ y_title=self.y_title,
459
+ color_legend_title=self.color_legend_title,
460
+ size_legend_title=self.size_legend_title,
461
+ shape_legend_title=self.size_legend_title,
462
+ color_legend_position=self.color_legend_position, # type: ignore
463
+ size_legend_position=self.size_legend_position, # type: ignore
464
+ shape_legend_position=self.shape_legend_position, # type: ignore
465
+ interactive=self.interactive_chart,
466
+ height=self.height,
467
+ width=self.width,
468
+ x_lim=self.x_lim,
469
+ y_lim=self.y_lim,
470
+ )
471
+
472
+ return {"type": "altair", "plot": chart.to_json(), "chart": "scatter"}
gradio/components/slider.py ADDED
@@ -0,0 +1,210 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """gr.Slider() component."""
2
+
3
+ from __future__ import annotations
4
+
5
+ import math
6
+ import random
7
+ from typing import Any, Callable, Literal
8
+
9
+ import numpy as np
10
+ from gradio_client.documentation import document, set_documentation_group
11
+ from gradio_client.serializing import NumberSerializable
12
+
13
+ from gradio.components.base import FormComponent, IOComponent, _Keywords
14
+ from gradio.deprecation import warn_style_method_deprecation
15
+ from gradio.events import Changeable, Inputable, Releaseable
16
+ from gradio.interpretation import NeighborInterpretable
17
+
18
+ set_documentation_group("component")
19
+
20
+
21
+ @document()
22
+ class Slider(
23
+ FormComponent,
24
+ Changeable,
25
+ Inputable,
26
+ Releaseable,
27
+ IOComponent,
28
+ NumberSerializable,
29
+ NeighborInterpretable,
30
+ ):
31
+ """
32
+ Creates a slider that ranges from `minimum` to `maximum` with a step size of `step`.
33
+ Preprocessing: passes slider value as a {float} into the function.
34
+ Postprocessing: expects an {int} or {float} returned from function and sets slider value to it as long as it is within range.
35
+ Examples-format: A {float} or {int} representing the slider's value.
36
+
37
+ Demos: sentence_builder, slider_release, generate_tone, titanic_survival, interface_random_slider, blocks_random_slider
38
+ Guides: create-your-own-friends-with-a-gan
39
+ """
40
+
41
+ def __init__(
42
+ self,
43
+ minimum: float = 0,
44
+ maximum: float = 100,
45
+ value: float | Callable | None = None,
46
+ *,
47
+ step: float | None = None,
48
+ label: str | None = None,
49
+ info: str | None = None,
50
+ every: float | None = None,
51
+ show_label: bool | None = None,
52
+ container: bool = True,
53
+ scale: int | None = None,
54
+ min_width: int = 160,
55
+ interactive: bool | None = None,
56
+ visible: bool = True,
57
+ elem_id: str | None = None,
58
+ elem_classes: list[str] | str | None = None,
59
+ randomize: bool = False,
60
+ **kwargs,
61
+ ):
62
+ """
63
+ Parameters:
64
+ minimum: minimum value for slider.
65
+ maximum: maximum value for slider.
66
+ value: default value. If callable, the function will be called whenever the app loads to set the initial value of the component. Ignored if randomized=True.
67
+ step: increment between slider values.
68
+ label: component name in interface.
69
+ info: additional component description.
70
+ every: If `value` is a callable, run the function 'every' number of seconds while the client connection is open. Has no effect otherwise. Queue must be enabled. The event can be accessed (e.g. to cancel it) via this component's .load_event attribute.
71
+ show_label: if True, will display label.
72
+ container: If True, will place the component in a container - providing some extra padding around the border.
73
+ scale: relative width compared to adjacent Components in a Row. For example, if Component A has scale=2, and Component B has scale=1, A will be twice as wide as B. Should be an integer.
74
+ 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.
75
+ interactive: if True, slider will be adjustable; if False, adjusting will be disabled. If not provided, this is inferred based on whether the component is used as an input or output.
76
+ visible: If False, component will be hidden.
77
+ 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.
78
+ 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.
79
+ randomize: If True, the value of the slider when the app loads is taken uniformly at random from the range given by the minimum and maximum.
80
+ """
81
+ self.minimum = minimum
82
+ self.maximum = maximum
83
+ if step is None:
84
+ difference = maximum - minimum
85
+ power = math.floor(math.log10(difference) - 2)
86
+ self.step = 10**power
87
+ else:
88
+ self.step = step
89
+ if randomize:
90
+ value = self.get_random_value
91
+ IOComponent.__init__(
92
+ self,
93
+ label=label,
94
+ info=info,
95
+ every=every,
96
+ show_label=show_label,
97
+ container=container,
98
+ scale=scale,
99
+ min_width=min_width,
100
+ interactive=interactive,
101
+ visible=visible,
102
+ elem_id=elem_id,
103
+ elem_classes=elem_classes,
104
+ value=value,
105
+ **kwargs,
106
+ )
107
+ NeighborInterpretable.__init__(self)
108
+
109
+ def api_info(self) -> dict[str, dict | bool]:
110
+ return {
111
+ "info": {
112
+ "type": "number",
113
+ "description": f"numeric value between {self.minimum} and {self.maximum}",
114
+ },
115
+ "serialized_info": False,
116
+ }
117
+
118
+ def example_inputs(self) -> dict[str, Any]:
119
+ return {
120
+ "raw": self.minimum,
121
+ "serialized": self.minimum,
122
+ }
123
+
124
+ def get_config(self):
125
+ return {
126
+ "minimum": self.minimum,
127
+ "maximum": self.maximum,
128
+ "step": self.step,
129
+ "value": self.value,
130
+ **IOComponent.get_config(self),
131
+ }
132
+
133
+ def get_random_value(self):
134
+ n_steps = int((self.maximum - self.minimum) / self.step)
135
+ step = random.randint(0, n_steps)
136
+ value = self.minimum + step * self.step
137
+ # Round to number of decimals in step so that UI doesn't display long decimals
138
+ n_decimals = max(str(self.step)[::-1].find("."), 0)
139
+ if n_decimals:
140
+ value = round(value, n_decimals)
141
+ return value
142
+
143
+ @staticmethod
144
+ def update(
145
+ value: float | Literal[_Keywords.NO_VALUE] | None = _Keywords.NO_VALUE,
146
+ minimum: float | None = None,
147
+ maximum: float | None = None,
148
+ step: float | None = None,
149
+ label: str | None = None,
150
+ info: str | None = None,
151
+ show_label: bool | None = None,
152
+ container: bool | None = None,
153
+ scale: int | None = None,
154
+ min_width: int | None = None,
155
+ interactive: bool | None = None,
156
+ visible: bool | None = None,
157
+ ):
158
+ return {
159
+ "minimum": minimum,
160
+ "maximum": maximum,
161
+ "step": step,
162
+ "label": label,
163
+ "info": info,
164
+ "show_label": show_label,
165
+ "container": container,
166
+ "scale": scale,
167
+ "min_width": min_width,
168
+ "interactive": interactive,
169
+ "visible": visible,
170
+ "value": value,
171
+ "__type__": "update",
172
+ }
173
+
174
+ def postprocess(self, y: float | None) -> float | None:
175
+ """
176
+ Any postprocessing needed to be performed on function output.
177
+ Parameters:
178
+ y: numeric output
179
+ Returns:
180
+ numeric output or minimum number if None
181
+ """
182
+ return self.minimum if y is None else y
183
+
184
+ def set_interpret_parameters(self, steps: int = 8) -> Slider:
185
+ """
186
+ Calculates interpretation scores of numeric values ranging between the minimum and maximum values of the slider.
187
+ Parameters:
188
+ steps: Number of neighboring values to measure between the minimum and maximum values of the slider range.
189
+ """
190
+ self.interpretation_steps = steps
191
+ return self
192
+
193
+ def get_interpretation_neighbors(self, x) -> tuple[object, dict]:
194
+ return (
195
+ np.linspace(self.minimum, self.maximum, self.interpretation_steps).tolist(),
196
+ {},
197
+ )
198
+
199
+ def style(
200
+ self,
201
+ *,
202
+ container: bool | None = None,
203
+ ):
204
+ """
205
+ This method is deprecated. Please set these arguments in the constructor instead.
206
+ """
207
+ warn_style_method_deprecation()
208
+ if container is not None:
209
+ self.container = container
210
+ return self
gradio/components/state.py ADDED
@@ -0,0 +1,50 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """gr.State() component."""
2
+
3
+ from __future__ import annotations
4
+
5
+ from copy import deepcopy
6
+ from typing import Any
7
+
8
+ from gradio_client.documentation import document, set_documentation_group
9
+ from gradio_client.serializing import SimpleSerializable
10
+
11
+ from gradio.components.base import IOComponent
12
+
13
+ set_documentation_group("component")
14
+
15
+
16
+ @document()
17
+ class State(IOComponent, SimpleSerializable):
18
+ """
19
+ Special hidden component that stores session state across runs of the demo by the
20
+ same user. The value of the State variable is cleared when the user refreshes the page.
21
+
22
+ Preprocessing: No preprocessing is performed
23
+ Postprocessing: No postprocessing is performed
24
+ Demos: blocks_simple_squares
25
+ Guides: real-time-speech-recognition
26
+ """
27
+
28
+ allow_string_shortcut = False
29
+
30
+ def __init__(
31
+ self,
32
+ value: Any = None,
33
+ **kwargs,
34
+ ):
35
+ """
36
+ Parameters:
37
+ value: the initial value (of arbitrary type) of the state. The provided argument is deepcopied. If a callable is provided, the function will be called whenever the app loads to set the initial value of the state.
38
+ """
39
+ self.stateful = True
40
+ IOComponent.__init__(self, value=deepcopy(value), **kwargs)
41
+
42
+
43
+ class Variable(State):
44
+ """Variable was renamed to State. This class is kept for backwards compatibility."""
45
+
46
+ def __init__(self, *args, **kwargs):
47
+ super().__init__(*args, **kwargs)
48
+
49
+ def get_block_name(self):
50
+ return "state"
gradio/components/status_tracker.py ADDED
@@ -0,0 +1,13 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """gr.StatusTracker() component."""
2
+ from gradio_client.serializing import SimpleSerializable
3
+
4
+ from gradio.components.base import Component
5
+ from gradio.deprecation import warn_deprecation
6
+
7
+
8
+ class StatusTracker(Component, SimpleSerializable):
9
+ def __init__(
10
+ self,
11
+ **kwargs,
12
+ ):
13
+ warn_deprecation("The StatusTracker component is deprecated.")
gradio/components/textbox.py ADDED
@@ -0,0 +1,284 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """gr.Textbox() component."""
2
+
3
+ from __future__ import annotations
4
+
5
+ from typing import Callable, Literal
6
+
7
+ import numpy as np
8
+ from gradio_client.documentation import document, set_documentation_group
9
+ from gradio_client.serializing import StringSerializable
10
+
11
+ from gradio.components.base import (
12
+ FormComponent,
13
+ IOComponent,
14
+ _Keywords,
15
+ )
16
+ from gradio.deprecation import warn_style_method_deprecation
17
+ from gradio.events import (
18
+ Blurrable,
19
+ Changeable,
20
+ EventListenerMethod,
21
+ Inputable,
22
+ Selectable,
23
+ Submittable,
24
+ )
25
+ from gradio.interpretation import TokenInterpretable
26
+
27
+ set_documentation_group("component")
28
+
29
+
30
+ @document()
31
+ class Textbox(
32
+ FormComponent,
33
+ Changeable,
34
+ Inputable,
35
+ Selectable,
36
+ Submittable,
37
+ Blurrable,
38
+ IOComponent,
39
+ StringSerializable,
40
+ TokenInterpretable,
41
+ ):
42
+ """
43
+ Creates a textarea for user to enter string input or display string output.
44
+ Preprocessing: passes textarea value as a {str} into the function.
45
+ Postprocessing: expects a {str} returned from function and sets textarea value to it.
46
+ Examples-format: a {str} representing the textbox input.
47
+
48
+ Demos: hello_world, diff_texts, sentence_builder
49
+ Guides: creating-a-chatbot, real-time-speech-recognition
50
+ """
51
+
52
+ def __init__(
53
+ self,
54
+ value: str | Callable | None = "",
55
+ *,
56
+ lines: int = 1,
57
+ max_lines: int = 20,
58
+ placeholder: str | None = None,
59
+ label: str | None = None,
60
+ info: str | None = None,
61
+ every: float | None = None,
62
+ show_label: bool | None = None,
63
+ container: bool = True,
64
+ scale: int | None = None,
65
+ min_width: int = 160,
66
+ interactive: bool | None = None,
67
+ visible: bool = True,
68
+ elem_id: str | None = None,
69
+ autofocus: bool = False,
70
+ elem_classes: list[str] | str | None = None,
71
+ type: Literal["text", "password", "email"] = "text",
72
+ text_align: Literal["left", "right"] | None = None,
73
+ rtl: bool = False,
74
+ show_copy_button: bool = False,
75
+ **kwargs,
76
+ ):
77
+ """
78
+ Parameters:
79
+ value: default text to provide in textarea. If callable, the function will be called whenever the app loads to set the initial value of the component.
80
+ lines: minimum number of line rows to provide in textarea.
81
+ max_lines: maximum number of line rows to provide in textarea.
82
+ placeholder: placeholder hint to provide behind textarea.
83
+ label: component name in interface.
84
+ info: additional component description.
85
+ every: If `value` is a callable, run the function 'every' number of seconds while the client connection is open. Has no effect otherwise. Queue must be enabled. The event can be accessed (e.g. to cancel it) via this component's .load_event attribute.
86
+ show_label: if True, will display label.
87
+ container: If True, will place the component in a container - providing some extra padding around the border.
88
+ scale: relative width compared to adjacent Components in a Row. For example, if Component A has scale=2, and Component B has scale=1, A will be twice as wide as B. Should be an integer.
89
+ 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.
90
+ interactive: if True, will be rendered as an editable textbox; if False, editing will be disabled. If not provided, this is inferred based on whether the component is used as an input or output.
91
+ visible: If False, component will be hidden.
92
+ autofocus: If True, will focus on the textbox when the page loads.
93
+ 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.
94
+ 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.
95
+ type: The type of textbox. One of: 'text', 'password', 'email', Default is 'text'.
96
+ text_align: How to align the text in the textbox, can be: "left", "right", or None (default). If None, the alignment is left if `rtl` is False, or right if `rtl` is True. Can only be changed if `type` is "text".
97
+ rtl: If True and `type` is "text", sets the direction of the text to right-to-left (cursor appears on the left of the text). Default is False, which renders cursor on the right.
98
+ show_copy_button: If True, includes a copy button to copy the text in the textbox. Only applies if show_label is True.
99
+ """
100
+ if type not in ["text", "password", "email"]:
101
+ raise ValueError('`type` must be one of "text", "password", or "email".')
102
+
103
+ self.lines = lines
104
+ if type == "text":
105
+ self.max_lines = max(lines, max_lines)
106
+ else:
107
+ self.max_lines = 1
108
+ self.placeholder = placeholder
109
+ self.show_copy_button = show_copy_button
110
+ self.autofocus = autofocus
111
+ self.select: EventListenerMethod
112
+ """
113
+ Event listener for when the user selects text in the Textbox.
114
+ Uses event data gradio.SelectData to carry `value` referring to selected substring, and `index` tuple referring to selected range endpoints.
115
+ See EventData documentation on how to use this event data.
116
+ """
117
+ IOComponent.__init__(
118
+ self,
119
+ label=label,
120
+ info=info,
121
+ every=every,
122
+ show_label=show_label,
123
+ container=container,
124
+ scale=scale,
125
+ min_width=min_width,
126
+ interactive=interactive,
127
+ visible=visible,
128
+ elem_id=elem_id,
129
+ elem_classes=elem_classes,
130
+ value=value,
131
+ **kwargs,
132
+ )
133
+ TokenInterpretable.__init__(self)
134
+ self.type = type
135
+ self.rtl = rtl
136
+ self.text_align = text_align
137
+
138
+ def get_config(self):
139
+ return {
140
+ "lines": self.lines,
141
+ "max_lines": self.max_lines,
142
+ "placeholder": self.placeholder,
143
+ "value": self.value,
144
+ "type": self.type,
145
+ "autofocus": self.autofocus,
146
+ "show_copy_button": self.show_copy_button,
147
+ "container": self.container,
148
+ "text_align": self.text_align,
149
+ "rtl": self.rtl,
150
+ **IOComponent.get_config(self),
151
+ }
152
+
153
+ @staticmethod
154
+ def update(
155
+ value: str | Literal[_Keywords.NO_VALUE] | None = _Keywords.NO_VALUE,
156
+ lines: int | None = None,
157
+ max_lines: int | None = None,
158
+ placeholder: str | None = None,
159
+ label: str | None = None,
160
+ info: str | None = None,
161
+ show_label: bool | None = None,
162
+ container: bool | None = None,
163
+ scale: int | None = None,
164
+ min_width: int | None = None,
165
+ visible: bool | None = None,
166
+ interactive: bool | None = None,
167
+ type: Literal["text", "password", "email"] | None = None,
168
+ text_align: Literal["left", "right"] | None = None,
169
+ rtl: bool | None = None,
170
+ show_copy_button: bool | None = None,
171
+ autofocus: bool | None = None,
172
+ ):
173
+ return {
174
+ "lines": lines,
175
+ "max_lines": max_lines,
176
+ "placeholder": placeholder,
177
+ "label": label,
178
+ "info": info,
179
+ "show_label": show_label,
180
+ "container": container,
181
+ "scale": scale,
182
+ "min_width": min_width,
183
+ "visible": visible,
184
+ "value": value,
185
+ "type": type,
186
+ "interactive": interactive,
187
+ "show_copy_button": show_copy_button,
188
+ "autofocus": autofocus,
189
+ "text_align": text_align,
190
+ "rtl": rtl,
191
+ "__type__": "update",
192
+ }
193
+
194
+ def preprocess(self, x: str | None) -> str | None:
195
+ """
196
+ Preprocesses input (converts it to a string) before passing it to the function.
197
+ Parameters:
198
+ x: text
199
+ Returns:
200
+ text
201
+ """
202
+ return None if x is None else str(x)
203
+
204
+ def postprocess(self, y: str | None) -> str | None:
205
+ """
206
+ Postproccess the function output y by converting it to a str before passing it to the frontend.
207
+ Parameters:
208
+ y: function output to postprocess.
209
+ Returns:
210
+ text
211
+ """
212
+ return None if y is None else str(y)
213
+
214
+ def set_interpret_parameters(
215
+ self, separator: str = " ", replacement: str | None = None
216
+ ):
217
+ """
218
+ Calculates interpretation score of characters in input by splitting input into tokens, then using a "leave one out" method to calculate the score of each token by removing each token and measuring the delta of the output value.
219
+ Parameters:
220
+ separator: Separator to use to split input into tokens.
221
+ replacement: In the "leave one out" step, the text that the token should be replaced with. If None, the token is removed altogether.
222
+ """
223
+ self.interpretation_separator = separator
224
+ self.interpretation_replacement = replacement
225
+ return self
226
+
227
+ def tokenize(self, x: str) -> tuple[list[str], list[str], None]:
228
+ """
229
+ Tokenizes an input string by dividing into "words" delimited by self.interpretation_separator
230
+ """
231
+ tokens = x.split(self.interpretation_separator)
232
+ leave_one_out_strings = []
233
+ for index in range(len(tokens)):
234
+ leave_one_out_set = list(tokens)
235
+ if self.interpretation_replacement is None:
236
+ leave_one_out_set.pop(index)
237
+ else:
238
+ leave_one_out_set[index] = self.interpretation_replacement
239
+ leave_one_out_strings.append(
240
+ self.interpretation_separator.join(leave_one_out_set)
241
+ )
242
+ return tokens, leave_one_out_strings, None
243
+
244
+ def get_masked_inputs(
245
+ self, tokens: list[str], binary_mask_matrix: list[list[int]]
246
+ ) -> list[str]:
247
+ """
248
+ Constructs partially-masked sentences for SHAP interpretation
249
+ """
250
+ masked_inputs = []
251
+ for binary_mask_vector in binary_mask_matrix:
252
+ masked_input = np.array(tokens)[np.array(binary_mask_vector, dtype=bool)]
253
+ masked_inputs.append(self.interpretation_separator.join(masked_input))
254
+ return masked_inputs
255
+
256
+ def get_interpretation_scores(
257
+ self, x, neighbors, scores: list[float], tokens: list[str], masks=None, **kwargs
258
+ ) -> list[tuple[str, float]]:
259
+ """
260
+ Returns:
261
+ Each tuple set represents a set of characters and their corresponding interpretation score.
262
+ """
263
+ result = []
264
+ for token, score in zip(tokens, scores):
265
+ result.append((token, score))
266
+ result.append((self.interpretation_separator, 0))
267
+ return result
268
+
269
+ def style(
270
+ self,
271
+ *,
272
+ show_copy_button: bool | None = None,
273
+ container: bool | None = None,
274
+ **kwargs,
275
+ ):
276
+ """
277
+ This method is deprecated. Please set these arguments in the constructor instead.
278
+ """
279
+ warn_style_method_deprecation()
280
+ if show_copy_button is not None:
281
+ self.show_copy_button = show_copy_button
282
+ if container is not None:
283
+ self.container = container
284
+ return self
gradio/components/timeseries.py ADDED
@@ -0,0 +1,157 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """gr.Timeseries() component."""
2
+
3
+ from __future__ import annotations
4
+
5
+ from pathlib import Path
6
+ from typing import Any, Callable, Literal
7
+
8
+ import pandas as pd
9
+ from gradio_client.documentation import document, set_documentation_group
10
+ from gradio_client.serializing import JSONSerializable
11
+
12
+ from gradio.components.base import IOComponent, _Keywords
13
+ from gradio.events import Changeable
14
+
15
+ set_documentation_group("component")
16
+
17
+
18
+ @document()
19
+ class Timeseries(Changeable, IOComponent, JSONSerializable):
20
+ """
21
+ Creates a component that can be used to upload/preview timeseries csv files or display a dataframe consisting of a time series graphically.
22
+ Preprocessing: passes the uploaded timeseries data as a {pandas.DataFrame} into the function
23
+ Postprocessing: expects a {pandas.DataFrame} or {str} path to a csv to be returned, which is then displayed as a timeseries graph
24
+ Examples-format: a {str} filepath of csv data with time series data.
25
+ Demos: fraud_detector
26
+ """
27
+
28
+ def __init__(
29
+ self,
30
+ value: str | Callable | None = None,
31
+ *,
32
+ x: str | None = None,
33
+ y: str | list[str] | None = None,
34
+ colors: list[str] | None = None,
35
+ label: str | None = None,
36
+ every: float | None = None,
37
+ show_label: bool | None = None,
38
+ container: bool = True,
39
+ scale: int | None = None,
40
+ min_width: int = 160,
41
+ interactive: bool | None = None,
42
+ visible: bool = True,
43
+ elem_id: str | None = None,
44
+ elem_classes: list[str] | str | None = None,
45
+ **kwargs,
46
+ ):
47
+ """
48
+ Parameters:
49
+ value: File path for the timeseries csv file. If callable, the function will be called whenever the app loads to set the initial value of the component.
50
+ x: Column name of x (time) series. None if csv has no headers, in which case first column is x series.
51
+ y: Column name of y series, or list of column names if multiple series. None if csv has no headers, in which case every column after first is a y series.
52
+ label: component name in interface.
53
+ every: If `value` is a callable, run the function 'every' number of seconds while the client connection is open. Has no effect otherwise. Queue must be enabled. The event can be accessed (e.g. to cancel it) via this component's .load_event attribute.
54
+ colors: an ordered list of colors to use for each line plot
55
+ show_label: if True, will display label.
56
+ container: If True, will place the component in a container - providing some extra padding around the border.
57
+ scale: relative width compared to adjacent Components in a Row. For example, if Component A has scale=2, and Component B has scale=1, A will be twice as wide as B. Should be an integer.
58
+ 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.
59
+ interactive: if True, will allow users to upload a timeseries csv; if False, can only be used to display timeseries data. If not provided, this is inferred based on whether the component is used as an input or output.
60
+ visible: If False, component will be hidden.
61
+ 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.
62
+ 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.
63
+ """
64
+ self.x = x
65
+ if isinstance(y, str):
66
+ y = [y]
67
+ self.y = y
68
+ self.colors = colors
69
+ IOComponent.__init__(
70
+ self,
71
+ label=label,
72
+ every=every,
73
+ show_label=show_label,
74
+ container=container,
75
+ scale=scale,
76
+ min_width=min_width,
77
+ interactive=interactive,
78
+ visible=visible,
79
+ elem_id=elem_id,
80
+ elem_classes=elem_classes,
81
+ value=value,
82
+ **kwargs,
83
+ )
84
+
85
+ def get_config(self):
86
+ return {
87
+ "x": self.x,
88
+ "y": self.y,
89
+ "value": self.value,
90
+ "colors": self.colors,
91
+ **IOComponent.get_config(self),
92
+ }
93
+
94
+ @staticmethod
95
+ def update(
96
+ value: Any | Literal[_Keywords.NO_VALUE] | None = _Keywords.NO_VALUE,
97
+ colors: list[str] | None = None,
98
+ label: str | None = None,
99
+ show_label: bool | None = None,
100
+ container: bool | None = None,
101
+ scale: int | None = None,
102
+ min_width: int | None = None,
103
+ interactive: bool | None = None,
104
+ visible: bool | None = None,
105
+ ):
106
+ return {
107
+ "colors": colors,
108
+ "label": label,
109
+ "show_label": show_label,
110
+ "container": container,
111
+ "scale": scale,
112
+ "min_width": min_width,
113
+ "interactive": interactive,
114
+ "visible": visible,
115
+ "value": value,
116
+ "__type__": "update",
117
+ }
118
+
119
+ def preprocess(self, x: dict | None) -> pd.DataFrame | None:
120
+ """
121
+ Parameters:
122
+ x: Dict with keys 'data': 2D array of str, numeric, or bool data, 'headers': list of strings for header names, 'range': optional two element list designating start of end of subrange.
123
+ Returns:
124
+ Dataframe of timeseries data
125
+ """
126
+ if x is None:
127
+ return x
128
+ elif x.get("is_file"):
129
+ dataframe = pd.read_csv(x["name"])
130
+ else:
131
+ dataframe = pd.DataFrame(data=x["data"], columns=x["headers"])
132
+ if x.get("range") is not None:
133
+ dataframe = dataframe.loc[dataframe[self.x or 0] >= x["range"][0]]
134
+ dataframe = dataframe.loc[dataframe[self.x or 0] <= x["range"][1]]
135
+ return dataframe
136
+
137
+ def postprocess(self, y: str | pd.DataFrame | None) -> dict | None:
138
+ """
139
+ Parameters:
140
+ y: csv or dataframe with timeseries data
141
+ Returns:
142
+ JSON object with key 'headers' for list of header names, 'data' for 2D array of string or numeric data
143
+ """
144
+ if y is None:
145
+ return None
146
+ if isinstance(y, str):
147
+ dataframe = pd.read_csv(y)
148
+ return {
149
+ "headers": dataframe.columns.values.tolist(),
150
+ "data": dataframe.values.tolist(),
151
+ }
152
+ if isinstance(y, pd.DataFrame):
153
+ return {"headers": y.columns.values.tolist(), "data": y.values.tolist()}
154
+ raise ValueError("Cannot process value as Timeseries data")
155
+
156
+ def as_example(self, input_data: str | None) -> str:
157
+ return Path(input_data).name if input_data else ""
gradio/components/upload_button.py ADDED
@@ -0,0 +1,211 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """gr.UploadButton() component."""
2
+
3
+ from __future__ import annotations
4
+
5
+ import tempfile
6
+ import warnings
7
+ from typing import Any, Callable, Literal
8
+
9
+ from gradio_client import utils as client_utils
10
+ from gradio_client.documentation import document, set_documentation_group
11
+ from gradio_client.serializing import FileSerializable
12
+
13
+ from gradio import utils
14
+ from gradio.components.base import Component, IOComponent, _Keywords
15
+ from gradio.deprecation import warn_deprecation, warn_style_method_deprecation
16
+ from gradio.events import Clickable, Uploadable
17
+
18
+ set_documentation_group("component")
19
+
20
+
21
+ @document()
22
+ class UploadButton(Clickable, Uploadable, IOComponent, FileSerializable):
23
+ """
24
+ Used to create an upload button, when cicked allows a user to upload files that satisfy the specified file type or generic files (if file_type not set).
25
+ Preprocessing: passes the uploaded file as a {file-object} or {List[file-object]} depending on `file_count` (or a {bytes}/{List{bytes}} depending on `type`)
26
+ Postprocessing: expects function to return a {str} path to a file, or {List[str]} consisting of paths to files.
27
+ Examples-format: a {str} path to a local file that populates the component.
28
+ Demos: upload_button
29
+ """
30
+
31
+ def __init__(
32
+ self,
33
+ label: str = "Upload a File",
34
+ value: str | list[str] | Callable | None = None,
35
+ *,
36
+ variant: Literal["primary", "secondary", "stop"] = "secondary",
37
+ visible: bool = True,
38
+ size: Literal["sm", "lg"] | None = None,
39
+ scale: int | None = None,
40
+ min_width: int | None = None,
41
+ interactive: bool = True,
42
+ elem_id: str | None = None,
43
+ elem_classes: list[str] | str | None = None,
44
+ type: Literal["file", "bytes"] = "file",
45
+ file_count: Literal["single", "multiple", "directory"] = "single",
46
+ file_types: list[str] | None = None,
47
+ **kwargs,
48
+ ):
49
+ """
50
+ Parameters:
51
+ label: Text to display on the button. Defaults to "Upload a File".
52
+ value: File or list of files to upload by default.
53
+ variant: 'primary' for main call-to-action, 'secondary' for a more subdued style, 'stop' for a stop button.
54
+ visible: If False, component will be hidden.
55
+ size: Size of the button. Can be "sm" or "lg".
56
+ scale: relative width compared to adjacent Components in a Row. For example, if Component A has scale=2, and Component B has scale=1, A will be twice as wide as B. Should be an integer.
57
+ 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.
58
+ interactive: If False, the UploadButton will be in a disabled state.
59
+ 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.
60
+ 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.
61
+ type: Type of value to be returned by component. "file" returns a temporary file object with the same base name as the uploaded file, whose full path can be retrieved by file_obj.name, "binary" returns an bytes object.
62
+ file_count: if single, allows user to upload one file. If "multiple", user uploads multiple files. If "directory", user uploads all files in selected directory. Return type will be list for each file in case of "multiple" or "directory".
63
+ file_types: List of type of files to be uploaded. "file" allows any file to be uploaded, "image" allows only image files to be uploaded, "audio" allows only audio files to be uploaded, "video" allows only video files to be uploaded, "text" allows only text files to be uploaded.
64
+ """
65
+ self.type = type
66
+ self.file_count = file_count
67
+ if file_count == "directory" and file_types is not None:
68
+ warnings.warn(
69
+ "The `file_types` parameter is ignored when `file_count` is 'directory'."
70
+ )
71
+ if file_types is not None and not isinstance(file_types, list):
72
+ raise ValueError(
73
+ f"Parameter file_types must be a list. Received {file_types.__class__.__name__}"
74
+ )
75
+ self.size = size
76
+ self.file_types = file_types
77
+ self.label = label
78
+ self.variant = variant
79
+ IOComponent.__init__(
80
+ self,
81
+ label=label,
82
+ visible=visible,
83
+ elem_id=elem_id,
84
+ elem_classes=elem_classes,
85
+ value=value,
86
+ scale=scale,
87
+ min_width=min_width,
88
+ interactive=interactive,
89
+ **kwargs,
90
+ )
91
+
92
+ def get_config(self):
93
+ return {
94
+ "label": self.label,
95
+ "value": self.value,
96
+ "size": self.size,
97
+ "file_count": self.file_count,
98
+ "file_types": self.file_types,
99
+ "scale": self.scale,
100
+ "min_width": self.min_width,
101
+ "variant": self.variant,
102
+ "interactive": self.interactive,
103
+ **Component.get_config(self),
104
+ }
105
+
106
+ @staticmethod
107
+ def update(
108
+ value: str
109
+ | list[str]
110
+ | Literal[_Keywords.NO_VALUE]
111
+ | None = _Keywords.NO_VALUE,
112
+ size: Literal["sm", "lg"] | None = None,
113
+ variant: Literal["primary", "secondary", "stop"] | None = None,
114
+ interactive: bool | None = None,
115
+ visible: bool | None = None,
116
+ scale: int | None = None,
117
+ min_width: int | None = None,
118
+ ):
119
+ return {
120
+ "variant": variant,
121
+ "interactive": interactive,
122
+ "size": size,
123
+ "visible": visible,
124
+ "value": value,
125
+ "scale": scale,
126
+ "min_width": min_width,
127
+ "__type__": "update",
128
+ }
129
+
130
+ def preprocess(
131
+ self, x: list[dict[str, Any]] | None
132
+ ) -> (
133
+ bytes
134
+ | tempfile._TemporaryFileWrapper
135
+ | list[bytes | tempfile._TemporaryFileWrapper]
136
+ | None
137
+ ):
138
+ """
139
+ Parameters:
140
+ x: List of JSON objects with filename as 'name' property and base64 data as 'data' property
141
+ Returns:
142
+ File objects in requested format
143
+ """
144
+ if x is None:
145
+ return None
146
+
147
+ def process_single_file(f) -> bytes | tempfile._TemporaryFileWrapper:
148
+ file_name, data, is_file = (
149
+ f["name"],
150
+ f["data"],
151
+ f.get("is_file", False),
152
+ )
153
+ if self.type == "file":
154
+ if is_file:
155
+ path = self.make_temp_copy_if_needed(file_name)
156
+ else:
157
+ data, _ = client_utils.decode_base64_to_binary(data)
158
+ path = self.file_bytes_to_file(
159
+ data, dir=self.DEFAULT_TEMP_DIR, file_name=file_name
160
+ )
161
+ path = str(utils.abspath(path))
162
+ self.temp_files.add(path)
163
+ file = tempfile.NamedTemporaryFile(
164
+ delete=False, dir=self.DEFAULT_TEMP_DIR
165
+ )
166
+ file.name = path
167
+ file.orig_name = file_name # type: ignore
168
+ return file
169
+ elif self.type == "bytes":
170
+ if is_file:
171
+ with open(file_name, "rb") as file_data:
172
+ return file_data.read()
173
+ return client_utils.decode_base64_to_binary(data)[0]
174
+ else:
175
+ raise ValueError(
176
+ "Unknown type: "
177
+ + str(self.type)
178
+ + ". Please choose from: 'file', 'bytes'."
179
+ )
180
+
181
+ if self.file_count == "single":
182
+ if isinstance(x, list):
183
+ return process_single_file(x[0])
184
+ else:
185
+ return process_single_file(x)
186
+ else:
187
+ if isinstance(x, list):
188
+ return [process_single_file(f) for f in x]
189
+ else:
190
+ return process_single_file(x)
191
+
192
+ def style(
193
+ self,
194
+ *,
195
+ full_width: bool | None = None,
196
+ size: Literal["sm", "lg"] | None = None,
197
+ **kwargs,
198
+ ):
199
+ """
200
+ This method is deprecated. Please set these arguments in the constructor instead.
201
+ """
202
+ warn_style_method_deprecation()
203
+ if full_width is not None:
204
+ warn_deprecation(
205
+ "Use `scale` in place of full_width in the constructor. "
206
+ "scale=1 will make the button expand, whereas 0 will not."
207
+ )
208
+ self.scale = 1 if full_width else None
209
+ if size is not None:
210
+ self.size = size
211
+ return self