ZTWHHH commited on
Commit
aaecd7a
·
verified ·
1 Parent(s): e3a19c1

Add files using upload-large-folder tool

Browse files
This view is limited to 50 files because it contains too many changes.   See raw diff
Files changed (50) hide show
  1. mantis_evalkit/lib/python3.10/site-packages/gradio/components/__pycache__/api_component.cpython-310.pyc +0 -0
  2. mantis_evalkit/lib/python3.10/site-packages/gradio/components/__pycache__/audio.cpython-310.pyc +0 -0
  3. mantis_evalkit/lib/python3.10/site-packages/gradio/components/__pycache__/bar_plot.cpython-310.pyc +0 -0
  4. mantis_evalkit/lib/python3.10/site-packages/gradio/components/__pycache__/base.cpython-310.pyc +0 -0
  5. mantis_evalkit/lib/python3.10/site-packages/gradio/components/__pycache__/browser_state.cpython-310.pyc +0 -0
  6. mantis_evalkit/lib/python3.10/site-packages/gradio/components/__pycache__/button.cpython-310.pyc +0 -0
  7. mantis_evalkit/lib/python3.10/site-packages/gradio/components/__pycache__/chatbot.cpython-310.pyc +0 -0
  8. mantis_evalkit/lib/python3.10/site-packages/gradio/components/__pycache__/checkbox.cpython-310.pyc +0 -0
  9. mantis_evalkit/lib/python3.10/site-packages/gradio/components/__pycache__/checkboxgroup.cpython-310.pyc +0 -0
  10. mantis_evalkit/lib/python3.10/site-packages/gradio/components/__pycache__/clear_button.cpython-310.pyc +0 -0
  11. mantis_evalkit/lib/python3.10/site-packages/gradio/components/__pycache__/code.cpython-310.pyc +0 -0
  12. mantis_evalkit/lib/python3.10/site-packages/gradio/components/__pycache__/color_picker.cpython-310.pyc +0 -0
  13. mantis_evalkit/lib/python3.10/site-packages/gradio/components/__pycache__/dataframe.cpython-310.pyc +0 -0
  14. mantis_evalkit/lib/python3.10/site-packages/gradio/components/__pycache__/dataset.cpython-310.pyc +0 -0
  15. mantis_evalkit/lib/python3.10/site-packages/gradio/components/__pycache__/download_button.cpython-310.pyc +0 -0
  16. mantis_evalkit/lib/python3.10/site-packages/gradio/components/__pycache__/duplicate_button.cpython-310.pyc +0 -0
  17. mantis_evalkit/lib/python3.10/site-packages/gradio/components/__pycache__/fallback.cpython-310.pyc +0 -0
  18. mantis_evalkit/lib/python3.10/site-packages/gradio/components/__pycache__/file.cpython-310.pyc +0 -0
  19. mantis_evalkit/lib/python3.10/site-packages/gradio/components/__pycache__/file_explorer.cpython-310.pyc +0 -0
  20. mantis_evalkit/lib/python3.10/site-packages/gradio/components/__pycache__/gallery.cpython-310.pyc +0 -0
  21. mantis_evalkit/lib/python3.10/site-packages/gradio/components/__pycache__/highlighted_text.cpython-310.pyc +0 -0
  22. mantis_evalkit/lib/python3.10/site-packages/gradio/components/__pycache__/image.cpython-310.pyc +0 -0
  23. mantis_evalkit/lib/python3.10/site-packages/gradio/components/__pycache__/image_editor.cpython-310.pyc +0 -0
  24. mantis_evalkit/lib/python3.10/site-packages/gradio/components/__pycache__/json_component.cpython-310.pyc +0 -0
  25. mantis_evalkit/lib/python3.10/site-packages/gradio/components/__pycache__/label.cpython-310.pyc +0 -0
  26. mantis_evalkit/lib/python3.10/site-packages/gradio/components/__pycache__/line_plot.cpython-310.pyc +0 -0
  27. mantis_evalkit/lib/python3.10/site-packages/gradio/components/__pycache__/login_button.cpython-310.pyc +0 -0
  28. mantis_evalkit/lib/python3.10/site-packages/gradio/components/__pycache__/logout_button.cpython-310.pyc +0 -0
  29. mantis_evalkit/lib/python3.10/site-packages/gradio/components/__pycache__/markdown.cpython-310.pyc +0 -0
  30. mantis_evalkit/lib/python3.10/site-packages/gradio/components/__pycache__/model3d.cpython-310.pyc +0 -0
  31. mantis_evalkit/lib/python3.10/site-packages/gradio/components/__pycache__/multimodal_textbox.cpython-310.pyc +0 -0
  32. mantis_evalkit/lib/python3.10/site-packages/gradio/components/__pycache__/number.cpython-310.pyc +0 -0
  33. mantis_evalkit/lib/python3.10/site-packages/gradio/components/__pycache__/paramviewer.cpython-310.pyc +0 -0
  34. mantis_evalkit/lib/python3.10/site-packages/gradio/components/__pycache__/plot.cpython-310.pyc +0 -0
  35. mantis_evalkit/lib/python3.10/site-packages/gradio/components/__pycache__/scatter_plot.cpython-310.pyc +0 -0
  36. mantis_evalkit/lib/python3.10/site-packages/gradio/components/__pycache__/state.cpython-310.pyc +0 -0
  37. mantis_evalkit/lib/python3.10/site-packages/gradio/components/__pycache__/textbox.cpython-310.pyc +0 -0
  38. mantis_evalkit/lib/python3.10/site-packages/gradio/components/__pycache__/timer.cpython-310.pyc +0 -0
  39. mantis_evalkit/lib/python3.10/site-packages/gradio/components/__pycache__/upload_button.cpython-310.pyc +0 -0
  40. mantis_evalkit/lib/python3.10/site-packages/gradio/components/__pycache__/video.cpython-310.pyc +0 -0
  41. mantis_evalkit/lib/python3.10/site-packages/gradio/components/bar_plot.py +331 -0
  42. mantis_evalkit/lib/python3.10/site-packages/gradio/components/browser_state.pyi +122 -0
  43. mantis_evalkit/lib/python3.10/site-packages/gradio/components/checkbox.pyi +249 -0
  44. mantis_evalkit/lib/python3.10/site-packages/gradio/components/clear_button.py +143 -0
  45. mantis_evalkit/lib/python3.10/site-packages/gradio/components/dataframe.py +390 -0
  46. mantis_evalkit/lib/python3.10/site-packages/gradio/components/dataframe.pyi +531 -0
  47. mantis_evalkit/lib/python3.10/site-packages/gradio/components/datetime.pyi +253 -0
  48. mantis_evalkit/lib/python3.10/site-packages/gradio/components/download_button.pyi +174 -0
  49. mantis_evalkit/lib/python3.10/site-packages/gradio/components/dropdown.py +247 -0
  50. mantis_evalkit/lib/python3.10/site-packages/gradio/components/duplicate_button.py +92 -0
mantis_evalkit/lib/python3.10/site-packages/gradio/components/__pycache__/api_component.cpython-310.pyc ADDED
Binary file (1.75 kB). View file
 
mantis_evalkit/lib/python3.10/site-packages/gradio/components/__pycache__/audio.cpython-310.pyc ADDED
Binary file (17.6 kB). View file
 
mantis_evalkit/lib/python3.10/site-packages/gradio/components/__pycache__/bar_plot.cpython-310.pyc ADDED
Binary file (11.3 kB). View file
 
mantis_evalkit/lib/python3.10/site-packages/gradio/components/__pycache__/base.cpython-310.pyc ADDED
Binary file (16.8 kB). View file
 
mantis_evalkit/lib/python3.10/site-packages/gradio/components/__pycache__/browser_state.cpython-310.pyc ADDED
Binary file (3.04 kB). View file
 
mantis_evalkit/lib/python3.10/site-packages/gradio/components/__pycache__/button.cpython-310.pyc ADDED
Binary file (5.78 kB). View file
 
mantis_evalkit/lib/python3.10/site-packages/gradio/components/__pycache__/chatbot.cpython-310.pyc ADDED
Binary file (28.2 kB). View file
 
mantis_evalkit/lib/python3.10/site-packages/gradio/components/__pycache__/checkbox.cpython-310.pyc ADDED
Binary file (5.86 kB). View file
 
mantis_evalkit/lib/python3.10/site-packages/gradio/components/__pycache__/checkboxgroup.cpython-310.pyc ADDED
Binary file (8.17 kB). View file
 
mantis_evalkit/lib/python3.10/site-packages/gradio/components/__pycache__/clear_button.cpython-310.pyc ADDED
Binary file (4.68 kB). View file
 
mantis_evalkit/lib/python3.10/site-packages/gradio/components/__pycache__/code.cpython-310.pyc ADDED
Binary file (7.16 kB). View file
 
mantis_evalkit/lib/python3.10/site-packages/gradio/components/__pycache__/color_picker.cpython-310.pyc ADDED
Binary file (5.93 kB). View file
 
mantis_evalkit/lib/python3.10/site-packages/gradio/components/__pycache__/dataframe.cpython-310.pyc ADDED
Binary file (16.6 kB). View file
 
mantis_evalkit/lib/python3.10/site-packages/gradio/components/__pycache__/dataset.cpython-310.pyc ADDED
Binary file (9.25 kB). View file
 
mantis_evalkit/lib/python3.10/site-packages/gradio/components/__pycache__/download_button.cpython-310.pyc ADDED
Binary file (6.03 kB). View file
 
mantis_evalkit/lib/python3.10/site-packages/gradio/components/__pycache__/duplicate_button.cpython-310.pyc ADDED
Binary file (4.99 kB). View file
 
mantis_evalkit/lib/python3.10/site-packages/gradio/components/__pycache__/fallback.cpython-310.pyc ADDED
Binary file (1.66 kB). View file
 
mantis_evalkit/lib/python3.10/site-packages/gradio/components/__pycache__/file.cpython-310.pyc ADDED
Binary file (10.8 kB). View file
 
mantis_evalkit/lib/python3.10/site-packages/gradio/components/__pycache__/file_explorer.cpython-310.pyc ADDED
Binary file (10.1 kB). View file
 
mantis_evalkit/lib/python3.10/site-packages/gradio/components/__pycache__/gallery.cpython-310.pyc ADDED
Binary file (14.4 kB). View file
 
mantis_evalkit/lib/python3.10/site-packages/gradio/components/__pycache__/highlighted_text.cpython-310.pyc ADDED
Binary file (8.78 kB). View file
 
mantis_evalkit/lib/python3.10/site-packages/gradio/components/__pycache__/image.cpython-310.pyc ADDED
Binary file (13.8 kB). View file
 
mantis_evalkit/lib/python3.10/site-packages/gradio/components/__pycache__/image_editor.cpython-310.pyc ADDED
Binary file (19.2 kB). View file
 
mantis_evalkit/lib/python3.10/site-packages/gradio/components/__pycache__/json_component.cpython-310.pyc ADDED
Binary file (6.74 kB). View file
 
mantis_evalkit/lib/python3.10/site-packages/gradio/components/__pycache__/label.cpython-310.pyc ADDED
Binary file (8.63 kB). View file
 
mantis_evalkit/lib/python3.10/site-packages/gradio/components/__pycache__/line_plot.cpython-310.pyc ADDED
Binary file (12.8 kB). View file
 
mantis_evalkit/lib/python3.10/site-packages/gradio/components/__pycache__/login_button.cpython-310.pyc ADDED
Binary file (3.76 kB). View file
 
mantis_evalkit/lib/python3.10/site-packages/gradio/components/__pycache__/logout_button.cpython-310.pyc ADDED
Binary file (2.26 kB). View file
 
mantis_evalkit/lib/python3.10/site-packages/gradio/components/__pycache__/markdown.cpython-310.pyc ADDED
Binary file (7.58 kB). View file
 
mantis_evalkit/lib/python3.10/site-packages/gradio/components/__pycache__/model3d.cpython-310.pyc ADDED
Binary file (8.08 kB). View file
 
mantis_evalkit/lib/python3.10/site-packages/gradio/components/__pycache__/multimodal_textbox.cpython-310.pyc ADDED
Binary file (12.2 kB). View file
 
mantis_evalkit/lib/python3.10/site-packages/gradio/components/__pycache__/number.cpython-310.pyc ADDED
Binary file (7.69 kB). View file
 
mantis_evalkit/lib/python3.10/site-packages/gradio/components/__pycache__/paramviewer.cpython-310.pyc ADDED
Binary file (5.29 kB). View file
 
mantis_evalkit/lib/python3.10/site-packages/gradio/components/__pycache__/plot.cpython-310.pyc ADDED
Binary file (7.75 kB). View file
 
mantis_evalkit/lib/python3.10/site-packages/gradio/components/__pycache__/scatter_plot.cpython-310.pyc ADDED
Binary file (12.4 kB). View file
 
mantis_evalkit/lib/python3.10/site-packages/gradio/components/__pycache__/state.cpython-310.pyc ADDED
Binary file (3.77 kB). View file
 
mantis_evalkit/lib/python3.10/site-packages/gradio/components/__pycache__/textbox.cpython-310.pyc ADDED
Binary file (8.52 kB). View file
 
mantis_evalkit/lib/python3.10/site-packages/gradio/components/__pycache__/timer.cpython-310.pyc ADDED
Binary file (2.57 kB). View file
 
mantis_evalkit/lib/python3.10/site-packages/gradio/components/__pycache__/upload_button.cpython-310.pyc ADDED
Binary file (9.87 kB). View file
 
mantis_evalkit/lib/python3.10/site-packages/gradio/components/__pycache__/video.cpython-310.pyc ADDED
Binary file (20.4 kB). View file
 
mantis_evalkit/lib/python3.10/site-packages/gradio/components/bar_plot.py ADDED
@@ -0,0 +1,331 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """gr.BarPlot() component."""
2
+
3
+ from __future__ import annotations
4
+
5
+ import warnings
6
+ from collections.abc import Callable, Sequence
7
+ from typing import TYPE_CHECKING, Any, Literal
8
+
9
+ from gradio_client.documentation import document
10
+
11
+ from gradio.components.base import Component
12
+ from gradio.components.plot import AltairPlot, AltairPlotData, Plot
13
+
14
+ if TYPE_CHECKING:
15
+ import pandas as pd
16
+
17
+ from gradio.components import Timer
18
+
19
+
20
+ @document()
21
+ class BarPlot(Plot):
22
+ """
23
+ Creates a bar plot component to display data from a pandas DataFrame (as output). As this component does
24
+ not accept user input, it is rarely used as an input component.
25
+
26
+ Demos: bar_plot
27
+ """
28
+
29
+ data_model = AltairPlotData
30
+
31
+ def __init__(
32
+ self,
33
+ value: pd.DataFrame | Callable | None = None,
34
+ x: str | None = None,
35
+ y: str | None = None,
36
+ *,
37
+ color: str | None = None,
38
+ vertical: bool = True,
39
+ group: str | None = None,
40
+ title: str | None = None,
41
+ tooltip: list[str] | str | None = None,
42
+ x_title: str | None = None,
43
+ y_title: str | None = None,
44
+ x_label_angle: float | None = None,
45
+ y_label_angle: float | None = None,
46
+ color_legend_title: str | None = None,
47
+ group_title: str | None = None,
48
+ color_legend_position: Literal[
49
+ "left",
50
+ "right",
51
+ "top",
52
+ "bottom",
53
+ "top-left",
54
+ "top-right",
55
+ "bottom-left",
56
+ "bottom-right",
57
+ "none",
58
+ ]
59
+ | None = None,
60
+ height: int | None = None,
61
+ width: int | None = None,
62
+ y_lim: list[int] | None = None,
63
+ caption: str | None = None,
64
+ interactive: bool | None = True,
65
+ label: str | None = None,
66
+ show_label: bool | None = None,
67
+ container: bool = True,
68
+ scale: int | None = None,
69
+ min_width: int = 160,
70
+ every: Timer | float | None = None,
71
+ inputs: Component | Sequence[Component] | set[Component] | None = None,
72
+ visible: bool = True,
73
+ elem_id: str | None = None,
74
+ elem_classes: list[str] | str | None = None,
75
+ render: bool = True,
76
+ key: int | str | None = None,
77
+ sort: Literal["x", "y", "-x", "-y"] | None = None,
78
+ show_actions_button: bool = False,
79
+ ):
80
+ """
81
+ Parameters:
82
+ value: The pandas dataframe containing the data to display in a scatter plot. If a callable is provided, the function will be called whenever the app loads to set the initial value of the plot.
83
+ x: Column corresponding to the x axis.
84
+ y: Column corresponding to the y axis.
85
+ color: The column to determine the bar color. Must be categorical (discrete values).
86
+ 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.
87
+ group: The column with which to split the overall plot into smaller subplots.
88
+ title: The title to display on top of the chart.
89
+ tooltip: The column (or list of columns) to display on the tooltip when a user hovers over a bar.
90
+ x_title: The title given to the x axis. By default, uses the value of the x parameter.
91
+ y_title: The title given to the y axis. By default, uses the value of the y parameter.
92
+ x_label_angle: The angle (in degrees) of the x axis labels. Positive values are clockwise, and negative values are counter-clockwise.
93
+ y_label_angle: The angle (in degrees) of the y axis labels. Positive values are clockwise, and negative values are counter-clockwise.
94
+ color_legend_title: The title given to the color legend. By default, uses the value of color parameter.
95
+ group_title: The label displayed on top of the subplot columns (or rows if vertical=True). Use an empty string to omit.
96
+ 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.
97
+ height: The height of the plot in pixels.
98
+ width: The width of the plot in pixels. If None, expands to fit.
99
+ y_lim: A tuple of list containing the limits for the y-axis, specified as [y_min, y_max].
100
+ caption: The (optional) caption to display below the plot.
101
+ interactive: Whether users should be able to interact with the plot by panning or zooming with their mouse or trackpad.
102
+ label: The (optional) label to display on the top left corner of the plot.
103
+ show_label: Whether the label should be displayed.
104
+ every: Continously calls `value` to recalculate it if `value` is a function (has no effect otherwise). Can provide a Timer whose tick resets `value`, or a float that provides the regular interval for the reset Timer.
105
+ inputs: Components that are used as inputs to calculate `value` if `value` is a function (has no effect otherwise). `value` is recalculated any time the inputs change.
106
+ visible: Whether the plot should be visible.
107
+ 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.
108
+ 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.
109
+ render: If False, component will not render be rendered in the Blocks context. Should be used if the intention is to assign event listeners now but render the component later.
110
+ key: if assigned, will be used to assume identity across a re-render. Components that have the same key across a re-render will have their value preserved.
111
+ sort: Specifies the sorting axis as either "x", "y", "-x" or "-y". If None, no sorting is applied.
112
+ show_actions_button: Whether to show the actions button on the top right corner of the plot.
113
+ """
114
+ self.x = x
115
+ self.y = y
116
+ self.color = color
117
+ self.vertical = vertical
118
+ self.group = group
119
+ self.group_title = group_title
120
+ self.tooltip = tooltip
121
+ self.title = title
122
+ self.x_title = x_title
123
+ self.y_title = y_title
124
+ self.x_label_angle = x_label_angle
125
+ self.y_label_angle = y_label_angle
126
+ self.color_legend_title = color_legend_title
127
+ self.group_title = group_title
128
+ self.color_legend_position = color_legend_position
129
+ self.y_lim = y_lim
130
+ self.caption = caption
131
+ self.interactive_chart = interactive
132
+ if isinstance(width, str):
133
+ width = None
134
+ warnings.warn(
135
+ "Width should be an integer, not a string. Setting width to None."
136
+ )
137
+ if isinstance(height, str):
138
+ warnings.warn(
139
+ "Height should be an integer, not a string. Setting height to None."
140
+ )
141
+ height = None
142
+ self.width = width
143
+ self.height = height
144
+ self.sort = sort
145
+ self.show_actions_button = show_actions_button
146
+ if label is None and show_label is None:
147
+ show_label = False
148
+ super().__init__(
149
+ value=value,
150
+ label=label,
151
+ show_label=show_label,
152
+ container=container,
153
+ scale=scale,
154
+ min_width=min_width,
155
+ visible=visible,
156
+ elem_id=elem_id,
157
+ elem_classes=elem_classes,
158
+ render=render,
159
+ key=key,
160
+ every=every,
161
+ inputs=inputs,
162
+ )
163
+
164
+ def get_block_name(self) -> str:
165
+ return "plot"
166
+
167
+ @staticmethod
168
+ def create_plot(
169
+ value: pd.DataFrame,
170
+ x: str,
171
+ y: str,
172
+ color: str | None = None,
173
+ vertical: bool = True,
174
+ group: str | None = None,
175
+ title: str | None = None,
176
+ tooltip: list[str] | str | None = None,
177
+ x_title: str | None = None,
178
+ y_title: str | None = None,
179
+ x_label_angle: float | None = None,
180
+ y_label_angle: float | None = None,
181
+ color_legend_title: str | None = None,
182
+ group_title: str | None = None,
183
+ color_legend_position: Literal[
184
+ "left",
185
+ "right",
186
+ "top",
187
+ "bottom",
188
+ "top-left",
189
+ "top-right",
190
+ "bottom-left",
191
+ "bottom-right",
192
+ "none",
193
+ ]
194
+ | None = None,
195
+ height: int | None = None,
196
+ width: int | None = None,
197
+ y_lim: list[int] | None = None,
198
+ interactive: bool | None = True,
199
+ sort: Literal["x", "y", "-x", "-y"] | None = None,
200
+ ):
201
+ """Helper for creating the bar plot."""
202
+ import altair as alt
203
+
204
+ interactive = True if interactive is None else interactive
205
+ orientation = {"field": group, "title": group_title} if group else {}
206
+
207
+ x_title = x_title or x
208
+ y_title = y_title or y
209
+
210
+ # If horizontal, switch x and y
211
+ if not vertical:
212
+ y, x = x, y
213
+ x = f"sum({x}):Q"
214
+ y_title, x_title = x_title, y_title
215
+ orientation = {"row": alt.Row(**orientation)} if orientation else {} # type: ignore
216
+ x_lim = y_lim
217
+ y_lim = None
218
+ else:
219
+ y = f"sum({y}):Q"
220
+ x_lim = None
221
+ orientation = {"column": alt.Column(**orientation)} if orientation else {} # type: ignore
222
+
223
+ encodings = dict(
224
+ x=alt.X(
225
+ x, # type: ignore
226
+ title=x_title, # type: ignore
227
+ scale=AltairPlot.create_scale(x_lim), # type: ignore
228
+ axis=alt.Axis(labelAngle=x_label_angle)
229
+ if x_label_angle is not None
230
+ else alt.Axis(),
231
+ sort=sort if vertical and sort is not None else None,
232
+ ),
233
+ y=alt.Y(
234
+ y, # type: ignore
235
+ title=y_title, # type: ignore
236
+ scale=AltairPlot.create_scale(y_lim), # type: ignore
237
+ axis=alt.Axis(labelAngle=y_label_angle)
238
+ if y_label_angle is not None
239
+ else alt.Axis(),
240
+ sort=sort if not vertical and sort is not None else None,
241
+ ),
242
+ **orientation,
243
+ )
244
+ properties = {}
245
+ if title:
246
+ properties["title"] = title
247
+ if height:
248
+ properties["height"] = height
249
+ if width:
250
+ properties["width"] = width
251
+
252
+ if color:
253
+ color_legend_position = color_legend_position or "bottom"
254
+ domain = value[color].unique().tolist()
255
+ range_ = list(range(len(domain)))
256
+ encodings["color"] = {
257
+ "field": color,
258
+ "type": "nominal",
259
+ "scale": {"domain": domain, "range": range_},
260
+ "legend": AltairPlot.create_legend(
261
+ position=color_legend_position, title=color_legend_title
262
+ ),
263
+ }
264
+
265
+ if tooltip:
266
+ encodings["tooltip"] = tooltip # type: ignore
267
+
268
+ chart = (
269
+ alt.Chart(value) # type: ignore
270
+ .mark_bar() # type: ignore
271
+ .encode(**encodings)
272
+ .properties(background="transparent", **properties)
273
+ )
274
+ if interactive:
275
+ chart = chart.interactive()
276
+
277
+ return chart
278
+
279
+ def preprocess(self, payload: AltairPlotData) -> AltairPlotData:
280
+ """
281
+ Parameters:
282
+ payload: The data to display in a bar plot.
283
+ Returns:
284
+ (Rarely used) passes the data displayed in the bar plot as an AltairPlotData dataclass, which includes the plot information as a JSON string, as well as the type of plot (in this case, "bar").
285
+ """
286
+ return payload
287
+
288
+ def postprocess(self, value: pd.DataFrame | None) -> AltairPlotData | None:
289
+ """
290
+ Parameters:
291
+ value: Expects a pandas DataFrame containing the data to display in the bar plot. The DataFrame should contain at least two columns, one for the x-axis (corresponding to this component's `x` argument) and one for the y-axis (corresponding to `y`).
292
+ Returns:
293
+ The data to display in a bar plot, in the form of an AltairPlotData dataclass, which includes the plot information as a JSON string, as well as the type of plot (in this case, "bar").
294
+ """
295
+ # if None or update
296
+ if value is None:
297
+ return value
298
+ if self.x is None or self.y is None:
299
+ raise ValueError("No value provided for required parameters `x` and `y`.")
300
+ chart = self.create_plot(
301
+ value=value,
302
+ x=self.x,
303
+ y=self.y,
304
+ color=self.color,
305
+ vertical=self.vertical,
306
+ group=self.group,
307
+ title=self.title,
308
+ tooltip=self.tooltip,
309
+ x_title=self.x_title,
310
+ y_title=self.y_title,
311
+ x_label_angle=self.x_label_angle,
312
+ y_label_angle=self.y_label_angle,
313
+ color_legend_title=self.color_legend_title,
314
+ color_legend_position=self.color_legend_position, # type: ignore
315
+ group_title=self.group_title,
316
+ y_lim=self.y_lim,
317
+ interactive=self.interactive_chart,
318
+ height=self.height,
319
+ width=self.width,
320
+ sort=self.sort, # type: ignore
321
+ )
322
+
323
+ return AltairPlotData(type="altair", plot=chart.to_json(), chart="bar")
324
+
325
+ def example_payload(self) -> Any:
326
+ return None
327
+
328
+ def example_value(self) -> Any:
329
+ import pandas as pd
330
+
331
+ return pd.DataFrame({self.x: [1, 2, 3], self.y: [4, 5, 6]})
mantis_evalkit/lib/python3.10/site-packages/gradio/components/browser_state.pyi ADDED
@@ -0,0 +1,122 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """gr.BrowserState() component."""
2
+
3
+ from __future__ import annotations
4
+
5
+ import secrets
6
+ import string
7
+ from typing import Any
8
+
9
+ from gradio_client.documentation import document
10
+
11
+ from gradio.components.base import Component
12
+ from gradio.events import Events
13
+
14
+ from gradio.events import Dependency
15
+
16
+ @document()
17
+ class BrowserState(Component):
18
+ EVENTS = [Events.change]
19
+ """
20
+ Special component that stores state in the browser's localStorage in an encrypted format.
21
+ """
22
+
23
+ def __init__(
24
+ self,
25
+ default_value: Any = None,
26
+ *,
27
+ storage_key: str | None = None,
28
+ secret: str | None = None,
29
+ render: bool = True,
30
+ ):
31
+ """
32
+ Parameters:
33
+ default_value: the default value that will be used if no value is found in localStorage. Should be a json-serializable value.
34
+ storage_key: the key to use in localStorage. If None, a random key will be generated.
35
+ secret: the secret key to use for encryption. If None, a random key will be generated (recommended).
36
+ render: should always be True, is included for consistency with other components.
37
+ """
38
+ self.default_value = default_value
39
+ self.secret = secret or "".join(
40
+ secrets.choice(string.ascii_letters + string.digits) for _ in range(16)
41
+ )
42
+ self.storage_key = storage_key or "".join(
43
+ secrets.choice(string.ascii_letters + string.digits) for _ in range(16)
44
+ )
45
+ super().__init__(render=render)
46
+
47
+ def preprocess(self, payload: Any) -> Any:
48
+ """
49
+ Parameters:
50
+ payload: Value from local storage
51
+ Returns:
52
+ Passes value through unchanged
53
+ """
54
+ return payload
55
+
56
+ def postprocess(self, value: Any) -> Any:
57
+ """
58
+ Parameters:
59
+ value: Value to store in local storage
60
+ Returns:
61
+ Passes value through unchanged
62
+ """
63
+ return value
64
+
65
+ def api_info(self) -> dict[str, Any]:
66
+ return {"type": {}, "description": "any json-serializable value"}
67
+
68
+ def example_payload(self) -> Any:
69
+ return "test"
70
+
71
+ def example_value(self) -> Any:
72
+ return "test"
73
+ from typing import Callable, Literal, Sequence, Any, TYPE_CHECKING
74
+ from gradio.blocks import Block
75
+ if TYPE_CHECKING:
76
+ from gradio.components import Timer
77
+
78
+
79
+ def change(self,
80
+ fn: Callable[..., Any] | None = None,
81
+ inputs: Block | Sequence[Block] | set[Block] | None = None,
82
+ outputs: Block | Sequence[Block] | None = None,
83
+ api_name: str | None | Literal[False] = None,
84
+ scroll_to_output: bool = False,
85
+ show_progress: Literal["full", "minimal", "hidden"] = "full",
86
+ queue: bool | None = None,
87
+ batch: bool = False,
88
+ max_batch_size: int = 4,
89
+ preprocess: bool = True,
90
+ postprocess: bool = True,
91
+ cancels: dict[str, Any] | list[dict[str, Any]] | None = None,
92
+ every: Timer | float | None = None,
93
+ trigger_mode: Literal["once", "multiple", "always_last"] | None = None,
94
+ js: str | None = None,
95
+ concurrency_limit: int | None | Literal["default"] = "default",
96
+ concurrency_id: str | None = None,
97
+ show_api: bool = True,
98
+
99
+ ) -> Dependency:
100
+ """
101
+ Parameters:
102
+ fn: the function to call when this event is triggered. 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.
103
+ inputs: list of gradio.components to use as inputs. If the function takes no inputs, this should be an empty list.
104
+ outputs: list of gradio.components to use as outputs. If the function returns no outputs, this should be an empty list.
105
+ 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, will use the functions name as the endpoint route. If set to a string, the endpoint will be exposed in the api docs with the given name.
106
+ scroll_to_output: if True, will scroll to output component on completion
107
+ show_progress: how to show the progress animation while event is running: "full" shows a spinner which covers the output component area as well as a runtime display in the upper right corner, "minimal" only shows the runtime display, "hidden" shows no progress animation at all
108
+ 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.
109
+ batch: 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.
110
+ max_batch_size: maximum number of inputs to batch together if this is called from the queue (only relevant if batch=True)
111
+ preprocess: 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).
112
+ postprocess: if False, will not run postprocessing of component data before returning 'fn' output to the browser.
113
+ cancels: a list of other events to cancel when this listener 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. Functions that have not yet run (or generators that are iterating) will be cancelled, but functions that are currently running will be allowed to finish.
114
+ every: continously calls `value` to recalculate it if `value` is a function (has no effect otherwise). Can provide a Timer whose tick resets `value`, or a float that provides the regular interval for the reset Timer.
115
+ trigger_mode: if "once" (default for all events except `.change()`) would not allow any submissions while an event is pending. If set to "multiple", unlimited submissions are allowed while pending, and "always_last" (default for `.change()` and `.key_up()` events) would allow a second submission after the pending event is complete.
116
+ js: 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.
117
+ concurrency_limit: if set, this is the maximum number of this event that can be running simultaneously. Can be set to None to mean no concurrency_limit (any number of this event can be running simultaneously). Set to "default" to use the default concurrency limit (defined by the `default_concurrency_limit` parameter in `Blocks.queue()`, which itself is 1 by default).
118
+ concurrency_id: if set, this is the id of the concurrency group. Events with the same concurrency_id will be limited by the lowest set concurrency_limit.
119
+ show_api: whether to show this event in the "view API" page of the Gradio app, or in the ".view_api()" method of the Gradio clients. Unlike setting api_name to False, setting show_api to False will still allow downstream apps as well as the Clients to use this event. If fn is None, show_api will automatically be set to False.
120
+
121
+ """
122
+ ...
mantis_evalkit/lib/python3.10/site-packages/gradio/components/checkbox.pyi ADDED
@@ -0,0 +1,249 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """gr.Checkbox() component."""
2
+
3
+ from __future__ import annotations
4
+
5
+ from collections.abc import Callable, Sequence
6
+ from typing import TYPE_CHECKING, Any
7
+
8
+ from gradio_client.documentation import document
9
+
10
+ from gradio.components.base import Component, FormComponent
11
+ from gradio.events import Events
12
+
13
+ if TYPE_CHECKING:
14
+ from gradio.components import Timer
15
+
16
+ from gradio.events import Dependency
17
+
18
+ @document()
19
+ class Checkbox(FormComponent):
20
+ """
21
+ Creates a checkbox that can be set to `True` or `False`. Can be used as an input to pass a boolean value to a function or as an output
22
+ to display a boolean value.
23
+
24
+ Demos: sentence_builder, hello_world_3
25
+ """
26
+
27
+ EVENTS = [Events.change, Events.input, Events.select]
28
+
29
+ def __init__(
30
+ self,
31
+ value: bool | Callable = False,
32
+ *,
33
+ label: str | None = None,
34
+ info: str | None = None,
35
+ every: Timer | float | None = None,
36
+ inputs: Component | Sequence[Component] | set[Component] | 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
+ render: bool = True,
46
+ key: int | str | None = None,
47
+ ):
48
+ """
49
+ Parameters:
50
+ 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.
51
+ label: the label for this component, displayed above the component if `show_label` is `True` and is also used as the header if there are a table of examples for this component. If None and used in a `gr.Interface`, the label will be the name of the parameter this component corresponds to.
52
+ info: additional component description, appears below the label in smaller font. Supports markdown / HTML syntax.
53
+ every: Continously calls `value` to recalculate it if `value` is a function (has no effect otherwise). Can provide a Timer whose tick resets `value`, or a float that provides the regular interval for the reset Timer.
54
+ inputs: Components that are used as inputs to calculate `value` if `value` is a function (has no effect otherwise). `value` is recalculated any time the inputs change.
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 size compared to adjacent Components. For example if Components A and B are in a Row, and A has scale=2, and B has scale=1, A will be twice as wide as B. Should be an integer. scale applies in Rows, and to top-level Components in Blocks where fill_height=True.
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, 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.
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
+ render: If False, component will not render be rendered in the Blocks context. Should be used if the intention is to assign event listeners now but render the component later.
64
+ key: if assigned, will be used to assume identity across a re-render. Components that have the same key across a re-render will have their value preserved.
65
+ """
66
+ super().__init__(
67
+ label=label,
68
+ info=info,
69
+ every=every,
70
+ inputs=inputs,
71
+ show_label=show_label,
72
+ container=container,
73
+ scale=scale,
74
+ min_width=min_width,
75
+ interactive=interactive,
76
+ visible=visible,
77
+ elem_id=elem_id,
78
+ elem_classes=elem_classes,
79
+ render=render,
80
+ key=key,
81
+ value=value,
82
+ )
83
+
84
+ def api_info(self) -> dict[str, Any]:
85
+ return {"type": "boolean"}
86
+
87
+ def example_payload(self) -> bool:
88
+ return True
89
+
90
+ def example_value(self) -> bool:
91
+ return True
92
+
93
+ def preprocess(self, payload: bool | None) -> bool | None:
94
+ """
95
+ Parameters:
96
+ payload: the status of the checkbox
97
+ Returns:
98
+ Passes the status of the checkbox as a `bool`.
99
+ """
100
+ return payload
101
+
102
+ def postprocess(self, value: bool | None) -> bool | None:
103
+ """
104
+ Parameters:
105
+ value: Expects a `bool` value that is set as the status of the checkbox
106
+ Returns:
107
+ The same `bool` value that is set as the status of the checkbox
108
+ """
109
+ return bool(value)
110
+ from typing import Callable, Literal, Sequence, Any, TYPE_CHECKING
111
+ from gradio.blocks import Block
112
+ if TYPE_CHECKING:
113
+ from gradio.components import Timer
114
+
115
+
116
+ def change(self,
117
+ fn: Callable[..., Any] | None = None,
118
+ inputs: Block | Sequence[Block] | set[Block] | None = None,
119
+ outputs: Block | Sequence[Block] | None = None,
120
+ api_name: str | None | Literal[False] = None,
121
+ scroll_to_output: bool = False,
122
+ show_progress: Literal["full", "minimal", "hidden"] = "full",
123
+ queue: bool | None = None,
124
+ batch: bool = False,
125
+ max_batch_size: int = 4,
126
+ preprocess: bool = True,
127
+ postprocess: bool = True,
128
+ cancels: dict[str, Any] | list[dict[str, Any]] | None = None,
129
+ every: Timer | float | None = None,
130
+ trigger_mode: Literal["once", "multiple", "always_last"] | None = None,
131
+ js: str | None = None,
132
+ concurrency_limit: int | None | Literal["default"] = "default",
133
+ concurrency_id: str | None = None,
134
+ show_api: bool = True,
135
+
136
+ ) -> Dependency:
137
+ """
138
+ Parameters:
139
+ fn: the function to call when this event is triggered. 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.
140
+ inputs: list of gradio.components to use as inputs. If the function takes no inputs, this should be an empty list.
141
+ outputs: list of gradio.components to use as outputs. If the function returns no outputs, this should be an empty list.
142
+ 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, will use the functions name as the endpoint route. If set to a string, the endpoint will be exposed in the api docs with the given name.
143
+ scroll_to_output: if True, will scroll to output component on completion
144
+ show_progress: how to show the progress animation while event is running: "full" shows a spinner which covers the output component area as well as a runtime display in the upper right corner, "minimal" only shows the runtime display, "hidden" shows no progress animation at all
145
+ 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.
146
+ batch: 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.
147
+ max_batch_size: maximum number of inputs to batch together if this is called from the queue (only relevant if batch=True)
148
+ preprocess: 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).
149
+ postprocess: if False, will not run postprocessing of component data before returning 'fn' output to the browser.
150
+ cancels: a list of other events to cancel when this listener 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. Functions that have not yet run (or generators that are iterating) will be cancelled, but functions that are currently running will be allowed to finish.
151
+ every: continously calls `value` to recalculate it if `value` is a function (has no effect otherwise). Can provide a Timer whose tick resets `value`, or a float that provides the regular interval for the reset Timer.
152
+ trigger_mode: if "once" (default for all events except `.change()`) would not allow any submissions while an event is pending. If set to "multiple", unlimited submissions are allowed while pending, and "always_last" (default for `.change()` and `.key_up()` events) would allow a second submission after the pending event is complete.
153
+ js: 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.
154
+ concurrency_limit: if set, this is the maximum number of this event that can be running simultaneously. Can be set to None to mean no concurrency_limit (any number of this event can be running simultaneously). Set to "default" to use the default concurrency limit (defined by the `default_concurrency_limit` parameter in `Blocks.queue()`, which itself is 1 by default).
155
+ concurrency_id: if set, this is the id of the concurrency group. Events with the same concurrency_id will be limited by the lowest set concurrency_limit.
156
+ show_api: whether to show this event in the "view API" page of the Gradio app, or in the ".view_api()" method of the Gradio clients. Unlike setting api_name to False, setting show_api to False will still allow downstream apps as well as the Clients to use this event. If fn is None, show_api will automatically be set to False.
157
+
158
+ """
159
+ ...
160
+
161
+ def input(self,
162
+ fn: Callable[..., Any] | None = None,
163
+ inputs: Block | Sequence[Block] | set[Block] | None = None,
164
+ outputs: Block | Sequence[Block] | None = None,
165
+ api_name: str | None | Literal[False] = None,
166
+ scroll_to_output: bool = False,
167
+ show_progress: Literal["full", "minimal", "hidden"] = "full",
168
+ queue: bool | None = None,
169
+ batch: bool = False,
170
+ max_batch_size: int = 4,
171
+ preprocess: bool = True,
172
+ postprocess: bool = True,
173
+ cancels: dict[str, Any] | list[dict[str, Any]] | None = None,
174
+ every: Timer | float | None = None,
175
+ trigger_mode: Literal["once", "multiple", "always_last"] | None = None,
176
+ js: str | None = None,
177
+ concurrency_limit: int | None | Literal["default"] = "default",
178
+ concurrency_id: str | None = None,
179
+ show_api: bool = True,
180
+
181
+ ) -> Dependency:
182
+ """
183
+ Parameters:
184
+ fn: the function to call when this event is triggered. 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.
185
+ inputs: list of gradio.components to use as inputs. If the function takes no inputs, this should be an empty list.
186
+ outputs: list of gradio.components to use as outputs. If the function returns no outputs, this should be an empty list.
187
+ 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, will use the functions name as the endpoint route. If set to a string, the endpoint will be exposed in the api docs with the given name.
188
+ scroll_to_output: if True, will scroll to output component on completion
189
+ show_progress: how to show the progress animation while event is running: "full" shows a spinner which covers the output component area as well as a runtime display in the upper right corner, "minimal" only shows the runtime display, "hidden" shows no progress animation at all
190
+ 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.
191
+ batch: 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.
192
+ max_batch_size: maximum number of inputs to batch together if this is called from the queue (only relevant if batch=True)
193
+ preprocess: 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).
194
+ postprocess: if False, will not run postprocessing of component data before returning 'fn' output to the browser.
195
+ cancels: a list of other events to cancel when this listener 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. Functions that have not yet run (or generators that are iterating) will be cancelled, but functions that are currently running will be allowed to finish.
196
+ every: continously calls `value` to recalculate it if `value` is a function (has no effect otherwise). Can provide a Timer whose tick resets `value`, or a float that provides the regular interval for the reset Timer.
197
+ trigger_mode: if "once" (default for all events except `.change()`) would not allow any submissions while an event is pending. If set to "multiple", unlimited submissions are allowed while pending, and "always_last" (default for `.change()` and `.key_up()` events) would allow a second submission after the pending event is complete.
198
+ js: 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.
199
+ concurrency_limit: if set, this is the maximum number of this event that can be running simultaneously. Can be set to None to mean no concurrency_limit (any number of this event can be running simultaneously). Set to "default" to use the default concurrency limit (defined by the `default_concurrency_limit` parameter in `Blocks.queue()`, which itself is 1 by default).
200
+ concurrency_id: if set, this is the id of the concurrency group. Events with the same concurrency_id will be limited by the lowest set concurrency_limit.
201
+ show_api: whether to show this event in the "view API" page of the Gradio app, or in the ".view_api()" method of the Gradio clients. Unlike setting api_name to False, setting show_api to False will still allow downstream apps as well as the Clients to use this event. If fn is None, show_api will automatically be set to False.
202
+
203
+ """
204
+ ...
205
+
206
+ def select(self,
207
+ fn: Callable[..., Any] | None = None,
208
+ inputs: Block | Sequence[Block] | set[Block] | None = None,
209
+ outputs: Block | Sequence[Block] | None = None,
210
+ api_name: str | None | Literal[False] = None,
211
+ scroll_to_output: bool = False,
212
+ show_progress: Literal["full", "minimal", "hidden"] = "full",
213
+ queue: bool | None = None,
214
+ batch: bool = False,
215
+ max_batch_size: int = 4,
216
+ preprocess: bool = True,
217
+ postprocess: bool = True,
218
+ cancels: dict[str, Any] | list[dict[str, Any]] | None = None,
219
+ every: Timer | float | None = None,
220
+ trigger_mode: Literal["once", "multiple", "always_last"] | None = None,
221
+ js: str | None = None,
222
+ concurrency_limit: int | None | Literal["default"] = "default",
223
+ concurrency_id: str | None = None,
224
+ show_api: bool = True,
225
+
226
+ ) -> Dependency:
227
+ """
228
+ Parameters:
229
+ fn: the function to call when this event is triggered. 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.
230
+ inputs: list of gradio.components to use as inputs. If the function takes no inputs, this should be an empty list.
231
+ outputs: list of gradio.components to use as outputs. If the function returns no outputs, this should be an empty list.
232
+ 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, will use the functions name as the endpoint route. If set to a string, the endpoint will be exposed in the api docs with the given name.
233
+ scroll_to_output: if True, will scroll to output component on completion
234
+ show_progress: how to show the progress animation while event is running: "full" shows a spinner which covers the output component area as well as a runtime display in the upper right corner, "minimal" only shows the runtime display, "hidden" shows no progress animation at all
235
+ 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.
236
+ batch: 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.
237
+ max_batch_size: maximum number of inputs to batch together if this is called from the queue (only relevant if batch=True)
238
+ preprocess: 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).
239
+ postprocess: if False, will not run postprocessing of component data before returning 'fn' output to the browser.
240
+ cancels: a list of other events to cancel when this listener 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. Functions that have not yet run (or generators that are iterating) will be cancelled, but functions that are currently running will be allowed to finish.
241
+ every: continously calls `value` to recalculate it if `value` is a function (has no effect otherwise). Can provide a Timer whose tick resets `value`, or a float that provides the regular interval for the reset Timer.
242
+ trigger_mode: if "once" (default for all events except `.change()`) would not allow any submissions while an event is pending. If set to "multiple", unlimited submissions are allowed while pending, and "always_last" (default for `.change()` and `.key_up()` events) would allow a second submission after the pending event is complete.
243
+ js: 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.
244
+ concurrency_limit: if set, this is the maximum number of this event that can be running simultaneously. Can be set to None to mean no concurrency_limit (any number of this event can be running simultaneously). Set to "default" to use the default concurrency limit (defined by the `default_concurrency_limit` parameter in `Blocks.queue()`, which itself is 1 by default).
245
+ concurrency_id: if set, this is the id of the concurrency group. Events with the same concurrency_id will be limited by the lowest set concurrency_limit.
246
+ show_api: whether to show this event in the "view API" page of the Gradio app, or in the ".view_api()" method of the Gradio clients. Unlike setting api_name to False, setting show_api to False will still allow downstream apps as well as the Clients to use this event. If fn is None, show_api will automatically be set to False.
247
+
248
+ """
249
+ ...
mantis_evalkit/lib/python3.10/site-packages/gradio/components/clear_button.py ADDED
@@ -0,0 +1,143 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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 copy
6
+ import json
7
+ from collections.abc import Sequence
8
+ from pathlib import Path
9
+ from typing import TYPE_CHECKING, Any, Literal
10
+
11
+ from gradio_client.documentation import document
12
+
13
+ from gradio.components import Button, Component
14
+ from gradio.context import get_blocks_context
15
+ from gradio.data_classes import GradioModel, GradioRootModel
16
+ from gradio.utils import resolve_singleton
17
+
18
+ if TYPE_CHECKING:
19
+ from gradio.components import Timer
20
+
21
+
22
+ @document("add")
23
+ class ClearButton(Button):
24
+ """
25
+ 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.
26
+ Preprocessing: passes the button value as a {str} into the function
27
+ Postprocessing: expects a {str} to be returned from a function, which is set as the label of the button
28
+ """
29
+
30
+ is_template = True
31
+
32
+ def __init__(
33
+ self,
34
+ components: None | Sequence[Component] | Component = None,
35
+ *,
36
+ value: str = "Clear",
37
+ every: Timer | float | None = None,
38
+ inputs: Component | Sequence[Component] | set[Component] | None = None,
39
+ variant: Literal["primary", "secondary", "stop"] = "secondary",
40
+ size: Literal["sm", "md", "lg"] = "lg",
41
+ icon: str | Path | None = None,
42
+ link: str | None = None,
43
+ visible: bool = True,
44
+ interactive: bool = True,
45
+ elem_id: str | None = None,
46
+ elem_classes: list[str] | str | None = None,
47
+ render: bool = True,
48
+ key: int | str | None = None,
49
+ scale: int | None = None,
50
+ min_width: int | None = None,
51
+ api_name: str | None | Literal["False"] = None,
52
+ show_api: bool = False,
53
+ ):
54
+ super().__init__(
55
+ value,
56
+ every=every,
57
+ inputs=inputs,
58
+ variant=variant,
59
+ size=size,
60
+ icon=icon,
61
+ link=link,
62
+ visible=visible,
63
+ interactive=interactive,
64
+ elem_id=elem_id,
65
+ elem_classes=elem_classes,
66
+ render=render,
67
+ key=key,
68
+ scale=scale,
69
+ min_width=min_width,
70
+ )
71
+ self.api_name = api_name
72
+ self.show_api = show_api
73
+
74
+ if get_blocks_context():
75
+ self.add(components)
76
+
77
+ def add(self, components: None | Component | Sequence[Component]) -> ClearButton:
78
+ """
79
+ Adds a component or list of components to the list of components that will be cleared when the button is clicked.
80
+ """
81
+ from gradio.components import State # Avoid circular import
82
+
83
+ if not components:
84
+ # This needs to be here because when the ClearButton is created in an gr.Interface, we don't
85
+ # want to create dependencies for it before we have created the dependencies for the submit function.
86
+ # We generally assume that the submit function dependency is the first thing created in an gr.Interface.
87
+ return self
88
+
89
+ if isinstance(components, Component):
90
+ components = [components]
91
+ none_values = []
92
+ state_components = []
93
+ initial_states = []
94
+ for component in components:
95
+ if isinstance(component, State):
96
+ state_components.append(component)
97
+ initial_states.append(copy.deepcopy(component.value))
98
+ none = component.postprocess(None)
99
+ if isinstance(none, (GradioModel, GradioRootModel)):
100
+ none = none.model_dump()
101
+ none_values.append(none)
102
+ clear_values = json.dumps(none_values)
103
+ self.click(
104
+ None,
105
+ [],
106
+ components,
107
+ js=f"() => {clear_values}",
108
+ api_name=self.api_name,
109
+ show_api=self.show_api,
110
+ )
111
+ if state_components:
112
+ self.click(
113
+ lambda: resolve_singleton(initial_states),
114
+ None,
115
+ state_components,
116
+ api_name=self.api_name,
117
+ show_api=self.show_api,
118
+ )
119
+ return self
120
+
121
+ def preprocess(self, payload: str | None) -> str | None:
122
+ """
123
+ Parameters:
124
+ payload: string corresponding to the button label
125
+ Returns:
126
+ (Rarely used) the `str` corresponding to the button label when the button is clicked
127
+ """
128
+ return payload
129
+
130
+ def postprocess(self, value: str | None) -> str | None:
131
+ """
132
+ Parameters:
133
+ value: string corresponding to the button label
134
+ Returns:
135
+ Expects a `str` value that is set as the button label
136
+ """
137
+ return value
138
+
139
+ def example_payload(self) -> Any:
140
+ return "Clear"
141
+
142
+ def example_value(self) -> Any:
143
+ return "Clear"
mantis_evalkit/lib/python3.10/site-packages/gradio/components/dataframe.py ADDED
@@ -0,0 +1,390 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """gr.Dataframe() component"""
2
+
3
+ from __future__ import annotations
4
+
5
+ import warnings
6
+ from collections.abc import Callable, Sequence
7
+ from typing import (
8
+ TYPE_CHECKING,
9
+ Any,
10
+ Literal,
11
+ Optional,
12
+ Union,
13
+ )
14
+
15
+ import numpy as np
16
+ import semantic_version
17
+ from gradio_client.documentation import document
18
+
19
+ from gradio.components.base import Component
20
+ from gradio.data_classes import GradioModel
21
+ from gradio.events import Events
22
+
23
+ if TYPE_CHECKING:
24
+ import pandas as pd
25
+ import polars as pl # type: ignore
26
+ from pandas.io.formats.style import Styler
27
+
28
+ from gradio.components import Timer
29
+
30
+
31
+ def _is_polars_available():
32
+ import importlib.util
33
+
34
+ spec = importlib.util.find_spec("polars")
35
+ return bool(spec)
36
+
37
+
38
+ def _import_polars():
39
+ import polars as pl # type: ignore
40
+
41
+ return pl
42
+
43
+
44
+ class DataframeData(GradioModel):
45
+ headers: list[str]
46
+ data: Union[list[list[Any]], list[tuple[Any, ...]]]
47
+ metadata: Optional[dict[str, Optional[list[Any]]]] = None
48
+
49
+
50
+ @document()
51
+ class Dataframe(Component):
52
+ """
53
+ This component displays a table of value spreadsheet-like component. Can be used to display data as an output component, or as an input to collect data from the user.
54
+ Demos: filter_records, matrix_transpose, tax_calculator, sort_records
55
+ """
56
+
57
+ EVENTS = [Events.change, Events.input, Events.select]
58
+
59
+ data_model = DataframeData
60
+
61
+ def __init__(
62
+ self,
63
+ value: pd.DataFrame
64
+ | Styler
65
+ | np.ndarray
66
+ | pl.DataFrame
67
+ | list
68
+ | list[list]
69
+ | dict
70
+ | str
71
+ | Callable
72
+ | None = None,
73
+ *,
74
+ headers: list[str] | None = None,
75
+ row_count: int | tuple[int, str] = (1, "dynamic"),
76
+ col_count: int | tuple[int, str] | None = None,
77
+ datatype: str | list[str] = "str",
78
+ type: Literal["pandas", "numpy", "array", "polars"] = "pandas",
79
+ latex_delimiters: list[dict[str, str | bool]] | None = None,
80
+ label: str | None = None,
81
+ show_label: bool | None = None,
82
+ every: Timer | float | None = None,
83
+ inputs: Component | Sequence[Component] | set[Component] | None = None,
84
+ max_height: int | str = 500,
85
+ scale: int | None = None,
86
+ min_width: int = 160,
87
+ interactive: bool | None = None,
88
+ visible: bool = True,
89
+ elem_id: str | None = None,
90
+ elem_classes: list[str] | str | None = None,
91
+ render: bool = True,
92
+ key: int | str | None = None,
93
+ wrap: bool = False,
94
+ line_breaks: bool = True,
95
+ column_widths: list[str | int] | None = None,
96
+ ):
97
+ """
98
+ Parameters:
99
+ value: Default value to display in the DataFrame. If a Styler is provided, it will be used to set the displayed value in the DataFrame (e.g. to set precision of numbers) if the `interactive` is False. If a Callable function is provided, the function will be called whenever the app loads to set the initial value of the component.
100
+ headers: List of str header names. If None, no headers are shown.
101
+ 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'
102
+ 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'
103
+ 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".
104
+ type: Type of value to be returned by component. "pandas" for pandas dataframe, "numpy" for numpy array, "polars" for polars dataframe, or "array" for a Python list of lists.
105
+ label: the label for this component. Appears above the component and is also used as the header if there are a table of examples for this component. If None and used in a `gr.Interface`, the label will be the name of the parameter this component is assigned to.
106
+ 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). Only applies to columns whose datatype is "markdown".
107
+ label: the label for this component. Appears above the component and is also used as the header if there are a table of examples for this component. If None and used in a `gr.Interface`, the label will be the name of the parameter this component is assigned to.
108
+ show_label: if True, will display label.
109
+ every: Continously calls `value` to recalculate it if `value` is a function (has no effect otherwise). Can provide a Timer whose tick resets `value`, or a float that provides the regular interval for the reset Timer.
110
+ inputs: Components that are used as inputs to calculate `value` if `value` is a function (has no effect otherwise). `value` is recalculated any time the inputs change.
111
+ max_height: The maximum height of the dataframe, specified in pixels if a number is passed, or in CSS units if a string is passed. If more rows are created than can fit in the height, a scrollbar will appear.
112
+ scale: relative size compared to adjacent Components. For example if Components A and B are in a Row, and A has scale=2, and B has scale=1, A will be twice as wide as B. Should be an integer. scale applies in Rows, and to top-level Components in Blocks where fill_height=True.
113
+ 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.
114
+ 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.
115
+ visible: If False, component will be hidden.
116
+ 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.
117
+ 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.
118
+ render: If False, component will not render be rendered in the Blocks context. Should be used if the intention is to assign event listeners now but render the component later.
119
+ key: if assigned, will be used to assume identity across a re-render. Components that have the same key across a re-render will have their value preserved.
120
+ wrap: If True, the text in table cells will wrap when appropriate. If False and the `column_width` parameter is not set, the column widths will expand based on the cell contents and the table may need to be horizontally scrolled. If `column_width` is set, then any overflow text will be hidden.
121
+ line_breaks: If True (default), will enable Github-flavored Markdown line breaks in chatbot messages. If False, single new lines will be ignored. Only applies for columns of type "markdown."
122
+ column_widths: An optional list representing the width of each column. The elements of the list should be in the format "100px" (ints are also accepted and converted to pixel values) or "10%". If not provided, the column widths will be automatically determined based on the content of the cells. Setting this parameter will cause the browser to try to fit the table within the page width.
123
+ """
124
+ self.wrap = wrap
125
+ self.row_count = self.__process_counts(row_count)
126
+ self.col_count = self.__process_counts(
127
+ col_count, len(headers) if headers else 3
128
+ )
129
+ self.__validate_headers(headers, self.col_count[0])
130
+
131
+ self.headers = (
132
+ headers
133
+ if headers is not None
134
+ else [str(i) for i in (range(1, self.col_count[0] + 1))]
135
+ )
136
+ self.datatype = datatype
137
+ valid_types = ["pandas", "numpy", "array", "polars"]
138
+ if type not in valid_types:
139
+ raise ValueError(
140
+ f"Invalid value for parameter `type`: {type}. Please choose from one of: {valid_types}"
141
+ )
142
+ if type == "polars" and not _is_polars_available():
143
+ raise ImportError(
144
+ "Polars is not installed. Please install using `pip install polars`."
145
+ )
146
+ self.type = type
147
+ values = {
148
+ "str": "",
149
+ "number": 0,
150
+ "bool": False,
151
+ "date": "01/01/1970",
152
+ "markdown": "",
153
+ "html": "",
154
+ }
155
+ column_dtypes = (
156
+ [datatype] * self.col_count[0] if isinstance(datatype, str) else datatype
157
+ )
158
+ self.empty_input = {
159
+ "headers": self.headers,
160
+ "data": [
161
+ [values[c] for c in column_dtypes] for _ in range(self.row_count[0])
162
+ ],
163
+ "metadata": None,
164
+ }
165
+
166
+ if latex_delimiters is None:
167
+ latex_delimiters = [{"left": "$$", "right": "$$", "display": True}]
168
+ self.latex_delimiters = latex_delimiters
169
+ self.max_height = max_height
170
+ self.line_breaks = line_breaks
171
+ self.column_widths = [
172
+ w if isinstance(w, str) else f"{w}px" for w in (column_widths or [])
173
+ ]
174
+ super().__init__(
175
+ label=label,
176
+ every=every,
177
+ inputs=inputs,
178
+ show_label=show_label,
179
+ scale=scale,
180
+ min_width=min_width,
181
+ interactive=interactive,
182
+ visible=visible,
183
+ elem_id=elem_id,
184
+ elem_classes=elem_classes,
185
+ render=render,
186
+ key=key,
187
+ value=value,
188
+ )
189
+
190
+ def preprocess(
191
+ self, payload: DataframeData
192
+ ) -> pd.DataFrame | np.ndarray | pl.DataFrame | list[list]:
193
+ """
194
+ Parameters:
195
+ payload: the uploaded spreadsheet data as an object with `headers` and `data` attributes. Note that sorting the columns in the browser will not affect the values passed to this function.
196
+ Returns:
197
+ Passes the uploaded spreadsheet data as a `pandas.DataFrame`, `numpy.array`, `polars.DataFrame`, or native 2D Python `list[list]` depending on `type`
198
+ """
199
+ import pandas as pd
200
+
201
+ if self.type == "pandas":
202
+ if payload.headers is not None:
203
+ return pd.DataFrame(
204
+ [] if payload.data == [[]] else payload.data,
205
+ columns=payload.headers, # type: ignore
206
+ )
207
+ else:
208
+ return pd.DataFrame(payload.data)
209
+ if self.type == "polars":
210
+ polars = _import_polars()
211
+ if payload.headers is not None:
212
+ return polars.DataFrame(
213
+ [] if payload.data == [[]] else payload.data, schema=payload.headers
214
+ )
215
+ else:
216
+ return polars.DataFrame(payload.data)
217
+ if self.type == "numpy":
218
+ return np.array(payload.data)
219
+ elif self.type == "array":
220
+ return payload.data # type: ignore
221
+ else:
222
+ raise ValueError(
223
+ "Unknown type: "
224
+ + str(self.type)
225
+ + ". Please choose from: 'pandas', 'numpy', 'array', 'polars'."
226
+ )
227
+
228
+ def postprocess(
229
+ self,
230
+ value: pd.DataFrame
231
+ | Styler
232
+ | np.ndarray
233
+ | pl.DataFrame
234
+ | list
235
+ | list[list]
236
+ | dict
237
+ | str
238
+ | None,
239
+ ) -> DataframeData:
240
+ """
241
+ Parameters:
242
+ value: Expects data any of these formats: `pandas.DataFrame`, `pandas.Styler`, `numpy.array`, `polars.DataFrame`, `list[list]`, `list`, or a `dict` with keys 'data' (and optionally 'headers'), or `str` path to a csv, which is rendered as the spreadsheet.
243
+ Returns:
244
+ the uploaded spreadsheet data as an object with `headers` and `data` attributes
245
+ """
246
+ import pandas as pd
247
+ from pandas.io.formats.style import Styler
248
+
249
+ if value is None:
250
+ return self.postprocess(self.empty_input)
251
+ if isinstance(value, dict):
252
+ if len(value) == 0:
253
+ return DataframeData(headers=self.headers, data=[[]])
254
+ return DataframeData(
255
+ headers=value.get("headers", []), data=value.get("data", [[]])
256
+ )
257
+ if isinstance(value, (str, pd.DataFrame)):
258
+ if isinstance(value, str):
259
+ value = pd.read_csv(value) # type: ignore
260
+ if len(value) == 0:
261
+ return DataframeData(
262
+ headers=list(value.columns), # type: ignore
263
+ data=[[]], # type: ignore
264
+ )
265
+ return DataframeData(
266
+ headers=list(value.columns), # type: ignore
267
+ data=value.to_dict(orient="split")["data"], # type: ignore
268
+ )
269
+ elif isinstance(value, Styler):
270
+ if semantic_version.Version(pd.__version__) < semantic_version.Version(
271
+ "1.5.0"
272
+ ):
273
+ raise ValueError(
274
+ "Styler objects are only supported in pandas version 1.5.0 or higher. Please try: `pip install --upgrade pandas` to use this feature."
275
+ )
276
+ if self.interactive:
277
+ warnings.warn(
278
+ "Cannot display Styler object in interactive mode. Will display as a regular pandas dataframe instead."
279
+ )
280
+ df: pd.DataFrame = value.data # type: ignore
281
+ if len(df) == 0:
282
+ return DataframeData(
283
+ headers=list(df.columns),
284
+ data=[[]],
285
+ metadata=self.__extract_metadata(value), # type: ignore
286
+ )
287
+ return DataframeData(
288
+ headers=list(df.columns),
289
+ data=df.to_dict(orient="split")["data"], # type: ignore
290
+ metadata=self.__extract_metadata(value), # type: ignore
291
+ )
292
+ elif _is_polars_available() and isinstance(value, _import_polars().DataFrame):
293
+ if len(value) == 0:
294
+ return DataframeData(headers=list(value.to_dict().keys()), data=[[]]) # type: ignore
295
+ df_dict = value.to_dict() # type: ignore
296
+ headers = list(df_dict.keys())
297
+ data = list(zip(*df_dict.values()))
298
+ return DataframeData(headers=headers, data=data)
299
+ elif isinstance(value, (np.ndarray, list)):
300
+ if len(value) == 0:
301
+ return DataframeData(headers=self.headers, data=[[]])
302
+ if isinstance(value, np.ndarray):
303
+ value = value.tolist()
304
+ if not isinstance(value, list):
305
+ raise ValueError("output cannot be converted to list")
306
+
307
+ _headers = self.headers
308
+ if len(self.headers) < len(value[0]):
309
+ _headers: list[str] = [
310
+ *self.headers,
311
+ *[str(i) for i in range(len(self.headers) + 1, len(value[0]) + 1)],
312
+ ]
313
+ elif len(self.headers) > len(value[0]):
314
+ _headers = self.headers[: len(value[0])]
315
+
316
+ return DataframeData(headers=_headers, data=value)
317
+ else:
318
+ raise ValueError("Cannot process value as a Dataframe")
319
+
320
+ @staticmethod
321
+ def __get_cell_style(cell_id: str, cell_styles: list[dict]) -> str:
322
+ styles_for_cell = []
323
+ for style in cell_styles:
324
+ if cell_id in style.get("selectors", []):
325
+ styles_for_cell.extend(style.get("props", []))
326
+ styles_str = "; ".join([f"{prop}: {value}" for prop, value in styles_for_cell])
327
+ return styles_str
328
+
329
+ @staticmethod
330
+ def __extract_metadata(df: Styler) -> dict[str, list[list]]:
331
+ metadata = {"display_value": [], "styling": []}
332
+ style_data = df._compute()._translate(None, None) # type: ignore
333
+ cell_styles = style_data.get("cellstyle", [])
334
+ for i in range(len(style_data["body"])):
335
+ metadata["display_value"].append([])
336
+ metadata["styling"].append([])
337
+ for j in range(len(style_data["body"][i])):
338
+ cell_type = style_data["body"][i][j]["type"]
339
+ if cell_type != "td":
340
+ continue
341
+ display_value = style_data["body"][i][j]["display_value"]
342
+ cell_id = style_data["body"][i][j]["id"]
343
+ styles_str = Dataframe.__get_cell_style(cell_id, cell_styles)
344
+ metadata["display_value"][i].append(display_value)
345
+ metadata["styling"][i].append(styles_str)
346
+ return metadata
347
+
348
+ @staticmethod
349
+ def __process_counts(count, default=3) -> tuple[int, str]:
350
+ if count is None:
351
+ return (default, "dynamic")
352
+ if isinstance(count, (int, float)):
353
+ return (int(count), "dynamic")
354
+ else:
355
+ return count
356
+
357
+ @staticmethod
358
+ def __validate_headers(headers: list[str] | None, col_count: int):
359
+ if headers is not None and len(headers) != col_count:
360
+ raise ValueError(
361
+ f"The length of the headers list must be equal to the col_count int.\n"
362
+ f"The column count is set to {col_count} but `headers` has {len(headers)} items. "
363
+ f"Check the values passed to `col_count` and `headers`."
364
+ )
365
+
366
+ def process_example(
367
+ self,
368
+ value: pd.DataFrame
369
+ | Styler
370
+ | np.ndarray
371
+ | pl.DataFrame
372
+ | list
373
+ | list[list]
374
+ | dict
375
+ | str
376
+ | None,
377
+ ):
378
+ import pandas as pd
379
+
380
+ if value is None:
381
+ return ""
382
+ value_df_data = self.postprocess(value)
383
+ value_df = pd.DataFrame(value_df_data.data, columns=value_df_data.headers) # type: ignore
384
+ return value_df.head(n=5).to_dict(orient="split")["data"]
385
+
386
+ def example_payload(self) -> Any:
387
+ return {"headers": ["a", "b"], "data": [["foo", "bar"]]}
388
+
389
+ def example_value(self) -> Any:
390
+ return {"headers": ["a", "b"], "data": [["foo", "bar"]]}
mantis_evalkit/lib/python3.10/site-packages/gradio/components/dataframe.pyi ADDED
@@ -0,0 +1,531 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """gr.Dataframe() component"""
2
+
3
+ from __future__ import annotations
4
+
5
+ import warnings
6
+ from collections.abc import Callable, Sequence
7
+ from typing import (
8
+ TYPE_CHECKING,
9
+ Any,
10
+ Literal,
11
+ Optional,
12
+ Union,
13
+ )
14
+
15
+ import numpy as np
16
+ import semantic_version
17
+ from gradio_client.documentation import document
18
+
19
+ from gradio.components.base import Component
20
+ from gradio.data_classes import GradioModel
21
+ from gradio.events import Events
22
+
23
+ if TYPE_CHECKING:
24
+ import pandas as pd
25
+ import polars as pl # type: ignore
26
+ from pandas.io.formats.style import Styler
27
+
28
+ from gradio.components import Timer
29
+
30
+
31
+ def _is_polars_available():
32
+ import importlib.util
33
+
34
+ spec = importlib.util.find_spec("polars")
35
+ return bool(spec)
36
+
37
+
38
+ def _import_polars():
39
+ import polars as pl # type: ignore
40
+
41
+ return pl
42
+
43
+
44
+ class DataframeData(GradioModel):
45
+ headers: list[str]
46
+ data: Union[list[list[Any]], list[tuple[Any, ...]]]
47
+ metadata: Optional[dict[str, Optional[list[Any]]]] = None
48
+
49
+ from gradio.events import Dependency
50
+
51
+ @document()
52
+ class Dataframe(Component):
53
+ """
54
+ This component displays a table of value spreadsheet-like component. Can be used to display data as an output component, or as an input to collect data from the user.
55
+ Demos: filter_records, matrix_transpose, tax_calculator, sort_records
56
+ """
57
+
58
+ EVENTS = [Events.change, Events.input, Events.select]
59
+
60
+ data_model = DataframeData
61
+
62
+ def __init__(
63
+ self,
64
+ value: pd.DataFrame
65
+ | Styler
66
+ | np.ndarray
67
+ | pl.DataFrame
68
+ | list
69
+ | list[list]
70
+ | dict
71
+ | str
72
+ | Callable
73
+ | None = None,
74
+ *,
75
+ headers: list[str] | None = None,
76
+ row_count: int | tuple[int, str] = (1, "dynamic"),
77
+ col_count: int | tuple[int, str] | None = None,
78
+ datatype: str | list[str] = "str",
79
+ type: Literal["pandas", "numpy", "array", "polars"] = "pandas",
80
+ latex_delimiters: list[dict[str, str | bool]] | None = None,
81
+ label: str | None = None,
82
+ show_label: bool | None = None,
83
+ every: Timer | float | None = None,
84
+ inputs: Component | Sequence[Component] | set[Component] | None = None,
85
+ max_height: int | str = 500,
86
+ scale: int | None = None,
87
+ min_width: int = 160,
88
+ interactive: bool | None = None,
89
+ visible: bool = True,
90
+ elem_id: str | None = None,
91
+ elem_classes: list[str] | str | None = None,
92
+ render: bool = True,
93
+ key: int | str | None = None,
94
+ wrap: bool = False,
95
+ line_breaks: bool = True,
96
+ column_widths: list[str | int] | None = None,
97
+ ):
98
+ """
99
+ Parameters:
100
+ value: Default value to display in the DataFrame. If a Styler is provided, it will be used to set the displayed value in the DataFrame (e.g. to set precision of numbers) if the `interactive` is False. If a Callable function is provided, the function will be called whenever the app loads to set the initial value of the component.
101
+ headers: List of str header names. If None, no headers are shown.
102
+ 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'
103
+ 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'
104
+ 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".
105
+ type: Type of value to be returned by component. "pandas" for pandas dataframe, "numpy" for numpy array, "polars" for polars dataframe, or "array" for a Python list of lists.
106
+ label: the label for this component. Appears above the component and is also used as the header if there are a table of examples for this component. If None and used in a `gr.Interface`, the label will be the name of the parameter this component is assigned to.
107
+ 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). Only applies to columns whose datatype is "markdown".
108
+ label: the label for this component. Appears above the component and is also used as the header if there are a table of examples for this component. If None and used in a `gr.Interface`, the label will be the name of the parameter this component is assigned to.
109
+ show_label: if True, will display label.
110
+ every: Continously calls `value` to recalculate it if `value` is a function (has no effect otherwise). Can provide a Timer whose tick resets `value`, or a float that provides the regular interval for the reset Timer.
111
+ inputs: Components that are used as inputs to calculate `value` if `value` is a function (has no effect otherwise). `value` is recalculated any time the inputs change.
112
+ max_height: The maximum height of the dataframe, specified in pixels if a number is passed, or in CSS units if a string is passed. If more rows are created than can fit in the height, a scrollbar will appear.
113
+ scale: relative size compared to adjacent Components. For example if Components A and B are in a Row, and A has scale=2, and B has scale=1, A will be twice as wide as B. Should be an integer. scale applies in Rows, and to top-level Components in Blocks where fill_height=True.
114
+ 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.
115
+ 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.
116
+ visible: If False, component will be hidden.
117
+ 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.
118
+ 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.
119
+ render: If False, component will not render be rendered in the Blocks context. Should be used if the intention is to assign event listeners now but render the component later.
120
+ key: if assigned, will be used to assume identity across a re-render. Components that have the same key across a re-render will have their value preserved.
121
+ wrap: If True, the text in table cells will wrap when appropriate. If False and the `column_width` parameter is not set, the column widths will expand based on the cell contents and the table may need to be horizontally scrolled. If `column_width` is set, then any overflow text will be hidden.
122
+ line_breaks: If True (default), will enable Github-flavored Markdown line breaks in chatbot messages. If False, single new lines will be ignored. Only applies for columns of type "markdown."
123
+ column_widths: An optional list representing the width of each column. The elements of the list should be in the format "100px" (ints are also accepted and converted to pixel values) or "10%". If not provided, the column widths will be automatically determined based on the content of the cells. Setting this parameter will cause the browser to try to fit the table within the page width.
124
+ """
125
+ self.wrap = wrap
126
+ self.row_count = self.__process_counts(row_count)
127
+ self.col_count = self.__process_counts(
128
+ col_count, len(headers) if headers else 3
129
+ )
130
+ self.__validate_headers(headers, self.col_count[0])
131
+
132
+ self.headers = (
133
+ headers
134
+ if headers is not None
135
+ else [str(i) for i in (range(1, self.col_count[0] + 1))]
136
+ )
137
+ self.datatype = datatype
138
+ valid_types = ["pandas", "numpy", "array", "polars"]
139
+ if type not in valid_types:
140
+ raise ValueError(
141
+ f"Invalid value for parameter `type`: {type}. Please choose from one of: {valid_types}"
142
+ )
143
+ if type == "polars" and not _is_polars_available():
144
+ raise ImportError(
145
+ "Polars is not installed. Please install using `pip install polars`."
146
+ )
147
+ self.type = type
148
+ values = {
149
+ "str": "",
150
+ "number": 0,
151
+ "bool": False,
152
+ "date": "01/01/1970",
153
+ "markdown": "",
154
+ "html": "",
155
+ }
156
+ column_dtypes = (
157
+ [datatype] * self.col_count[0] if isinstance(datatype, str) else datatype
158
+ )
159
+ self.empty_input = {
160
+ "headers": self.headers,
161
+ "data": [
162
+ [values[c] for c in column_dtypes] for _ in range(self.row_count[0])
163
+ ],
164
+ "metadata": None,
165
+ }
166
+
167
+ if latex_delimiters is None:
168
+ latex_delimiters = [{"left": "$$", "right": "$$", "display": True}]
169
+ self.latex_delimiters = latex_delimiters
170
+ self.max_height = max_height
171
+ self.line_breaks = line_breaks
172
+ self.column_widths = [
173
+ w if isinstance(w, str) else f"{w}px" for w in (column_widths or [])
174
+ ]
175
+ super().__init__(
176
+ label=label,
177
+ every=every,
178
+ inputs=inputs,
179
+ show_label=show_label,
180
+ scale=scale,
181
+ min_width=min_width,
182
+ interactive=interactive,
183
+ visible=visible,
184
+ elem_id=elem_id,
185
+ elem_classes=elem_classes,
186
+ render=render,
187
+ key=key,
188
+ value=value,
189
+ )
190
+
191
+ def preprocess(
192
+ self, payload: DataframeData
193
+ ) -> pd.DataFrame | np.ndarray | pl.DataFrame | list[list]:
194
+ """
195
+ Parameters:
196
+ payload: the uploaded spreadsheet data as an object with `headers` and `data` attributes. Note that sorting the columns in the browser will not affect the values passed to this function.
197
+ Returns:
198
+ Passes the uploaded spreadsheet data as a `pandas.DataFrame`, `numpy.array`, `polars.DataFrame`, or native 2D Python `list[list]` depending on `type`
199
+ """
200
+ import pandas as pd
201
+
202
+ if self.type == "pandas":
203
+ if payload.headers is not None:
204
+ return pd.DataFrame(
205
+ [] if payload.data == [[]] else payload.data,
206
+ columns=payload.headers, # type: ignore
207
+ )
208
+ else:
209
+ return pd.DataFrame(payload.data)
210
+ if self.type == "polars":
211
+ polars = _import_polars()
212
+ if payload.headers is not None:
213
+ return polars.DataFrame(
214
+ [] if payload.data == [[]] else payload.data, schema=payload.headers
215
+ )
216
+ else:
217
+ return polars.DataFrame(payload.data)
218
+ if self.type == "numpy":
219
+ return np.array(payload.data)
220
+ elif self.type == "array":
221
+ return payload.data # type: ignore
222
+ else:
223
+ raise ValueError(
224
+ "Unknown type: "
225
+ + str(self.type)
226
+ + ". Please choose from: 'pandas', 'numpy', 'array', 'polars'."
227
+ )
228
+
229
+ def postprocess(
230
+ self,
231
+ value: pd.DataFrame
232
+ | Styler
233
+ | np.ndarray
234
+ | pl.DataFrame
235
+ | list
236
+ | list[list]
237
+ | dict
238
+ | str
239
+ | None,
240
+ ) -> DataframeData:
241
+ """
242
+ Parameters:
243
+ value: Expects data any of these formats: `pandas.DataFrame`, `pandas.Styler`, `numpy.array`, `polars.DataFrame`, `list[list]`, `list`, or a `dict` with keys 'data' (and optionally 'headers'), or `str` path to a csv, which is rendered as the spreadsheet.
244
+ Returns:
245
+ the uploaded spreadsheet data as an object with `headers` and `data` attributes
246
+ """
247
+ import pandas as pd
248
+ from pandas.io.formats.style import Styler
249
+
250
+ if value is None:
251
+ return self.postprocess(self.empty_input)
252
+ if isinstance(value, dict):
253
+ if len(value) == 0:
254
+ return DataframeData(headers=self.headers, data=[[]])
255
+ return DataframeData(
256
+ headers=value.get("headers", []), data=value.get("data", [[]])
257
+ )
258
+ if isinstance(value, (str, pd.DataFrame)):
259
+ if isinstance(value, str):
260
+ value = pd.read_csv(value) # type: ignore
261
+ if len(value) == 0:
262
+ return DataframeData(
263
+ headers=list(value.columns), # type: ignore
264
+ data=[[]], # type: ignore
265
+ )
266
+ return DataframeData(
267
+ headers=list(value.columns), # type: ignore
268
+ data=value.to_dict(orient="split")["data"], # type: ignore
269
+ )
270
+ elif isinstance(value, Styler):
271
+ if semantic_version.Version(pd.__version__) < semantic_version.Version(
272
+ "1.5.0"
273
+ ):
274
+ raise ValueError(
275
+ "Styler objects are only supported in pandas version 1.5.0 or higher. Please try: `pip install --upgrade pandas` to use this feature."
276
+ )
277
+ if self.interactive:
278
+ warnings.warn(
279
+ "Cannot display Styler object in interactive mode. Will display as a regular pandas dataframe instead."
280
+ )
281
+ df: pd.DataFrame = value.data # type: ignore
282
+ if len(df) == 0:
283
+ return DataframeData(
284
+ headers=list(df.columns),
285
+ data=[[]],
286
+ metadata=self.__extract_metadata(value), # type: ignore
287
+ )
288
+ return DataframeData(
289
+ headers=list(df.columns),
290
+ data=df.to_dict(orient="split")["data"], # type: ignore
291
+ metadata=self.__extract_metadata(value), # type: ignore
292
+ )
293
+ elif _is_polars_available() and isinstance(value, _import_polars().DataFrame):
294
+ if len(value) == 0:
295
+ return DataframeData(headers=list(value.to_dict().keys()), data=[[]]) # type: ignore
296
+ df_dict = value.to_dict() # type: ignore
297
+ headers = list(df_dict.keys())
298
+ data = list(zip(*df_dict.values()))
299
+ return DataframeData(headers=headers, data=data)
300
+ elif isinstance(value, (np.ndarray, list)):
301
+ if len(value) == 0:
302
+ return DataframeData(headers=self.headers, data=[[]])
303
+ if isinstance(value, np.ndarray):
304
+ value = value.tolist()
305
+ if not isinstance(value, list):
306
+ raise ValueError("output cannot be converted to list")
307
+
308
+ _headers = self.headers
309
+ if len(self.headers) < len(value[0]):
310
+ _headers: list[str] = [
311
+ *self.headers,
312
+ *[str(i) for i in range(len(self.headers) + 1, len(value[0]) + 1)],
313
+ ]
314
+ elif len(self.headers) > len(value[0]):
315
+ _headers = self.headers[: len(value[0])]
316
+
317
+ return DataframeData(headers=_headers, data=value)
318
+ else:
319
+ raise ValueError("Cannot process value as a Dataframe")
320
+
321
+ @staticmethod
322
+ def __get_cell_style(cell_id: str, cell_styles: list[dict]) -> str:
323
+ styles_for_cell = []
324
+ for style in cell_styles:
325
+ if cell_id in style.get("selectors", []):
326
+ styles_for_cell.extend(style.get("props", []))
327
+ styles_str = "; ".join([f"{prop}: {value}" for prop, value in styles_for_cell])
328
+ return styles_str
329
+
330
+ @staticmethod
331
+ def __extract_metadata(df: Styler) -> dict[str, list[list]]:
332
+ metadata = {"display_value": [], "styling": []}
333
+ style_data = df._compute()._translate(None, None) # type: ignore
334
+ cell_styles = style_data.get("cellstyle", [])
335
+ for i in range(len(style_data["body"])):
336
+ metadata["display_value"].append([])
337
+ metadata["styling"].append([])
338
+ for j in range(len(style_data["body"][i])):
339
+ cell_type = style_data["body"][i][j]["type"]
340
+ if cell_type != "td":
341
+ continue
342
+ display_value = style_data["body"][i][j]["display_value"]
343
+ cell_id = style_data["body"][i][j]["id"]
344
+ styles_str = Dataframe.__get_cell_style(cell_id, cell_styles)
345
+ metadata["display_value"][i].append(display_value)
346
+ metadata["styling"][i].append(styles_str)
347
+ return metadata
348
+
349
+ @staticmethod
350
+ def __process_counts(count, default=3) -> tuple[int, str]:
351
+ if count is None:
352
+ return (default, "dynamic")
353
+ if isinstance(count, (int, float)):
354
+ return (int(count), "dynamic")
355
+ else:
356
+ return count
357
+
358
+ @staticmethod
359
+ def __validate_headers(headers: list[str] | None, col_count: int):
360
+ if headers is not None and len(headers) != col_count:
361
+ raise ValueError(
362
+ f"The length of the headers list must be equal to the col_count int.\n"
363
+ f"The column count is set to {col_count} but `headers` has {len(headers)} items. "
364
+ f"Check the values passed to `col_count` and `headers`."
365
+ )
366
+
367
+ def process_example(
368
+ self,
369
+ value: pd.DataFrame
370
+ | Styler
371
+ | np.ndarray
372
+ | pl.DataFrame
373
+ | list
374
+ | list[list]
375
+ | dict
376
+ | str
377
+ | None,
378
+ ):
379
+ import pandas as pd
380
+
381
+ if value is None:
382
+ return ""
383
+ value_df_data = self.postprocess(value)
384
+ value_df = pd.DataFrame(value_df_data.data, columns=value_df_data.headers) # type: ignore
385
+ return value_df.head(n=5).to_dict(orient="split")["data"]
386
+
387
+ def example_payload(self) -> Any:
388
+ return {"headers": ["a", "b"], "data": [["foo", "bar"]]}
389
+
390
+ def example_value(self) -> Any:
391
+ return {"headers": ["a", "b"], "data": [["foo", "bar"]]}
392
+ from typing import Callable, Literal, Sequence, Any, TYPE_CHECKING
393
+ from gradio.blocks import Block
394
+ if TYPE_CHECKING:
395
+ from gradio.components import Timer
396
+
397
+
398
+ def change(self,
399
+ fn: Callable[..., Any] | None = None,
400
+ inputs: Block | Sequence[Block] | set[Block] | None = None,
401
+ outputs: Block | Sequence[Block] | None = None,
402
+ api_name: str | None | Literal[False] = None,
403
+ scroll_to_output: bool = False,
404
+ show_progress: Literal["full", "minimal", "hidden"] = "full",
405
+ queue: bool | None = None,
406
+ batch: bool = False,
407
+ max_batch_size: int = 4,
408
+ preprocess: bool = True,
409
+ postprocess: bool = True,
410
+ cancels: dict[str, Any] | list[dict[str, Any]] | None = None,
411
+ every: Timer | float | None = None,
412
+ trigger_mode: Literal["once", "multiple", "always_last"] | None = None,
413
+ js: str | None = None,
414
+ concurrency_limit: int | None | Literal["default"] = "default",
415
+ concurrency_id: str | None = None,
416
+ show_api: bool = True,
417
+
418
+ ) -> Dependency:
419
+ """
420
+ Parameters:
421
+ fn: the function to call when this event is triggered. 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.
422
+ inputs: list of gradio.components to use as inputs. If the function takes no inputs, this should be an empty list.
423
+ outputs: list of gradio.components to use as outputs. If the function returns no outputs, this should be an empty list.
424
+ 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, will use the functions name as the endpoint route. If set to a string, the endpoint will be exposed in the api docs with the given name.
425
+ scroll_to_output: if True, will scroll to output component on completion
426
+ show_progress: how to show the progress animation while event is running: "full" shows a spinner which covers the output component area as well as a runtime display in the upper right corner, "minimal" only shows the runtime display, "hidden" shows no progress animation at all
427
+ 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.
428
+ batch: 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.
429
+ max_batch_size: maximum number of inputs to batch together if this is called from the queue (only relevant if batch=True)
430
+ preprocess: 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).
431
+ postprocess: if False, will not run postprocessing of component data before returning 'fn' output to the browser.
432
+ cancels: a list of other events to cancel when this listener 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. Functions that have not yet run (or generators that are iterating) will be cancelled, but functions that are currently running will be allowed to finish.
433
+ every: continously calls `value` to recalculate it if `value` is a function (has no effect otherwise). Can provide a Timer whose tick resets `value`, or a float that provides the regular interval for the reset Timer.
434
+ trigger_mode: if "once" (default for all events except `.change()`) would not allow any submissions while an event is pending. If set to "multiple", unlimited submissions are allowed while pending, and "always_last" (default for `.change()` and `.key_up()` events) would allow a second submission after the pending event is complete.
435
+ js: 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.
436
+ concurrency_limit: if set, this is the maximum number of this event that can be running simultaneously. Can be set to None to mean no concurrency_limit (any number of this event can be running simultaneously). Set to "default" to use the default concurrency limit (defined by the `default_concurrency_limit` parameter in `Blocks.queue()`, which itself is 1 by default).
437
+ concurrency_id: if set, this is the id of the concurrency group. Events with the same concurrency_id will be limited by the lowest set concurrency_limit.
438
+ show_api: whether to show this event in the "view API" page of the Gradio app, or in the ".view_api()" method of the Gradio clients. Unlike setting api_name to False, setting show_api to False will still allow downstream apps as well as the Clients to use this event. If fn is None, show_api will automatically be set to False.
439
+
440
+ """
441
+ ...
442
+
443
+ def input(self,
444
+ fn: Callable[..., Any] | None = None,
445
+ inputs: Block | Sequence[Block] | set[Block] | None = None,
446
+ outputs: Block | Sequence[Block] | None = None,
447
+ api_name: str | None | Literal[False] = None,
448
+ scroll_to_output: bool = False,
449
+ show_progress: Literal["full", "minimal", "hidden"] = "full",
450
+ queue: bool | None = None,
451
+ batch: bool = False,
452
+ max_batch_size: int = 4,
453
+ preprocess: bool = True,
454
+ postprocess: bool = True,
455
+ cancels: dict[str, Any] | list[dict[str, Any]] | None = None,
456
+ every: Timer | float | None = None,
457
+ trigger_mode: Literal["once", "multiple", "always_last"] | None = None,
458
+ js: str | None = None,
459
+ concurrency_limit: int | None | Literal["default"] = "default",
460
+ concurrency_id: str | None = None,
461
+ show_api: bool = True,
462
+
463
+ ) -> Dependency:
464
+ """
465
+ Parameters:
466
+ fn: the function to call when this event is triggered. 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.
467
+ inputs: list of gradio.components to use as inputs. If the function takes no inputs, this should be an empty list.
468
+ outputs: list of gradio.components to use as outputs. If the function returns no outputs, this should be an empty list.
469
+ 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, will use the functions name as the endpoint route. If set to a string, the endpoint will be exposed in the api docs with the given name.
470
+ scroll_to_output: if True, will scroll to output component on completion
471
+ show_progress: how to show the progress animation while event is running: "full" shows a spinner which covers the output component area as well as a runtime display in the upper right corner, "minimal" only shows the runtime display, "hidden" shows no progress animation at all
472
+ 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.
473
+ batch: 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.
474
+ max_batch_size: maximum number of inputs to batch together if this is called from the queue (only relevant if batch=True)
475
+ preprocess: 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).
476
+ postprocess: if False, will not run postprocessing of component data before returning 'fn' output to the browser.
477
+ cancels: a list of other events to cancel when this listener 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. Functions that have not yet run (or generators that are iterating) will be cancelled, but functions that are currently running will be allowed to finish.
478
+ every: continously calls `value` to recalculate it if `value` is a function (has no effect otherwise). Can provide a Timer whose tick resets `value`, or a float that provides the regular interval for the reset Timer.
479
+ trigger_mode: if "once" (default for all events except `.change()`) would not allow any submissions while an event is pending. If set to "multiple", unlimited submissions are allowed while pending, and "always_last" (default for `.change()` and `.key_up()` events) would allow a second submission after the pending event is complete.
480
+ js: 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.
481
+ concurrency_limit: if set, this is the maximum number of this event that can be running simultaneously. Can be set to None to mean no concurrency_limit (any number of this event can be running simultaneously). Set to "default" to use the default concurrency limit (defined by the `default_concurrency_limit` parameter in `Blocks.queue()`, which itself is 1 by default).
482
+ concurrency_id: if set, this is the id of the concurrency group. Events with the same concurrency_id will be limited by the lowest set concurrency_limit.
483
+ show_api: whether to show this event in the "view API" page of the Gradio app, or in the ".view_api()" method of the Gradio clients. Unlike setting api_name to False, setting show_api to False will still allow downstream apps as well as the Clients to use this event. If fn is None, show_api will automatically be set to False.
484
+
485
+ """
486
+ ...
487
+
488
+ def select(self,
489
+ fn: Callable[..., Any] | None = None,
490
+ inputs: Block | Sequence[Block] | set[Block] | None = None,
491
+ outputs: Block | Sequence[Block] | None = None,
492
+ api_name: str | None | Literal[False] = None,
493
+ scroll_to_output: bool = False,
494
+ show_progress: Literal["full", "minimal", "hidden"] = "full",
495
+ queue: bool | None = None,
496
+ batch: bool = False,
497
+ max_batch_size: int = 4,
498
+ preprocess: bool = True,
499
+ postprocess: bool = True,
500
+ cancels: dict[str, Any] | list[dict[str, Any]] | None = None,
501
+ every: Timer | float | None = None,
502
+ trigger_mode: Literal["once", "multiple", "always_last"] | None = None,
503
+ js: str | None = None,
504
+ concurrency_limit: int | None | Literal["default"] = "default",
505
+ concurrency_id: str | None = None,
506
+ show_api: bool = True,
507
+
508
+ ) -> Dependency:
509
+ """
510
+ Parameters:
511
+ fn: the function to call when this event is triggered. 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.
512
+ inputs: list of gradio.components to use as inputs. If the function takes no inputs, this should be an empty list.
513
+ outputs: list of gradio.components to use as outputs. If the function returns no outputs, this should be an empty list.
514
+ 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, will use the functions name as the endpoint route. If set to a string, the endpoint will be exposed in the api docs with the given name.
515
+ scroll_to_output: if True, will scroll to output component on completion
516
+ show_progress: how to show the progress animation while event is running: "full" shows a spinner which covers the output component area as well as a runtime display in the upper right corner, "minimal" only shows the runtime display, "hidden" shows no progress animation at all
517
+ 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.
518
+ batch: 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.
519
+ max_batch_size: maximum number of inputs to batch together if this is called from the queue (only relevant if batch=True)
520
+ preprocess: 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).
521
+ postprocess: if False, will not run postprocessing of component data before returning 'fn' output to the browser.
522
+ cancels: a list of other events to cancel when this listener 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. Functions that have not yet run (or generators that are iterating) will be cancelled, but functions that are currently running will be allowed to finish.
523
+ every: continously calls `value` to recalculate it if `value` is a function (has no effect otherwise). Can provide a Timer whose tick resets `value`, or a float that provides the regular interval for the reset Timer.
524
+ trigger_mode: if "once" (default for all events except `.change()`) would not allow any submissions while an event is pending. If set to "multiple", unlimited submissions are allowed while pending, and "always_last" (default for `.change()` and `.key_up()` events) would allow a second submission after the pending event is complete.
525
+ js: 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.
526
+ concurrency_limit: if set, this is the maximum number of this event that can be running simultaneously. Can be set to None to mean no concurrency_limit (any number of this event can be running simultaneously). Set to "default" to use the default concurrency limit (defined by the `default_concurrency_limit` parameter in `Blocks.queue()`, which itself is 1 by default).
527
+ concurrency_id: if set, this is the id of the concurrency group. Events with the same concurrency_id will be limited by the lowest set concurrency_limit.
528
+ show_api: whether to show this event in the "view API" page of the Gradio app, or in the ".view_api()" method of the Gradio clients. Unlike setting api_name to False, setting show_api to False will still allow downstream apps as well as the Clients to use this event. If fn is None, show_api will automatically be set to False.
529
+
530
+ """
531
+ ...
mantis_evalkit/lib/python3.10/site-packages/gradio/components/datetime.pyi ADDED
@@ -0,0 +1,253 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """gr.DateTime() component."""
2
+
3
+ from __future__ import annotations
4
+
5
+ import re
6
+ from datetime import datetime, timedelta
7
+ from typing import Any, Literal
8
+
9
+ import pytz
10
+ from gradio_client.documentation import document
11
+
12
+ from gradio.components.base import FormComponent
13
+ from gradio.events import Events
14
+
15
+ from gradio.events import Dependency
16
+
17
+ @document()
18
+ class DateTime(FormComponent):
19
+ """
20
+ Component to select a date and (optionally) a time.
21
+ """
22
+
23
+ EVENTS = [
24
+ Events.change,
25
+ Events.submit,
26
+ ]
27
+
28
+ def __init__(
29
+ self,
30
+ value: float | str | datetime | None = None,
31
+ *,
32
+ include_time: bool = True,
33
+ type: Literal["timestamp", "datetime", "string"] = "timestamp",
34
+ timezone: str | None = None,
35
+ label: str | None = None,
36
+ show_label: bool | None = None,
37
+ info: str | None = None,
38
+ every: float | None = None,
39
+ scale: int | None = None,
40
+ min_width: int = 160,
41
+ visible: bool = True,
42
+ interactive: bool | None = None,
43
+ elem_id: str | None = None,
44
+ elem_classes: list[str] | str | None = None,
45
+ render: bool = True,
46
+ key: int | str | None = None,
47
+ ):
48
+ """
49
+ Parameters:
50
+ value: default value for datetime.
51
+ label: the label for this component, displayed above the component if `show_label` is `True` and is also used as the header if there are a table of examples for this component. If None and used in a `gr.Interface`, the label will be the name of the parameter this component corresponds to.
52
+ info: additional component description, appears below the label in smaller font. Supports markdown / HTML syntax.
53
+ show_label: if True, will display label.
54
+ include_time: If True, the component will include time selection. If False, only date selection will be available.
55
+ type: The type of the value. Can be "timestamp", "datetime", or "string". If "timestamp", the value will be a number representing the start and end date in seconds since epoch. If "datetime", the value will be a datetime object. If "string", the value will be the date entered by the user.
56
+ timezone: The timezone to use for timestamps, such as "US/Pacific" or "Europe/Paris". If None, the timezone will be the local timezone.
57
+ every: If `value` is a callable, run the function 'every' number of seconds while the client connection is open. Has no effect otherwise. The event can be accessed (e.g. to cancel it) via this component's .load_event attribute.
58
+ scale: relative size compared to adjacent Components. For example if Components A and B are in a Row, and A has scale=2, and B has scale=1, A will be twice as wide as B. Should be an integer. scale applies in Rows, and to top-level Components in Blocks where fill_height=True.
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
+ visible: If False, component will be hidden.
61
+ 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.
62
+ render: If False, component will not render be rendered in the Blocks context. Should be used if the intention is to assign event listeners now but render the component later.
63
+ key: if assigned, will be used to assume identity across a re-render. Components that have the same key across a re-render will have their value preserved.
64
+ """
65
+ super().__init__(
66
+ every=every,
67
+ scale=scale,
68
+ min_width=min_width,
69
+ visible=visible,
70
+ label=label,
71
+ show_label=show_label,
72
+ info=info,
73
+ elem_id=elem_id,
74
+ elem_classes=elem_classes,
75
+ render=render,
76
+ key=key,
77
+ value=value,
78
+ )
79
+ self.type = type
80
+ self.include_time = include_time
81
+ self.interactive = interactive
82
+ self.time_format = "%Y-%m-%d %H:%M:%S" if include_time else "%Y-%m-%d"
83
+ self.timezone = timezone
84
+
85
+ def preprocess(self, payload: str | None) -> str | float | datetime | None:
86
+ """
87
+ Parameters:
88
+ payload: the text entered in the textarea.
89
+ Returns:
90
+ Passes text value as a {str} into the function.
91
+ """
92
+ if payload is None or payload == "":
93
+ return None
94
+ if self.type == "string" and "now" not in payload:
95
+ return payload
96
+ datetime = self.get_datetime_from_str(payload)
97
+ if self.type == "string":
98
+ return datetime.strftime(self.time_format)
99
+ if self.type == "datetime":
100
+ return datetime
101
+ elif self.type == "timestamp":
102
+ return datetime.timestamp()
103
+
104
+ def postprocess(self, value: float | datetime | str | None) -> str | None:
105
+ """
106
+ Parameters:
107
+ value: Expects a tuple pair of datetimes.
108
+ Returns:
109
+ A tuple pair of timestamps.
110
+ """
111
+ if value is None:
112
+ return None
113
+
114
+ if isinstance(value, datetime):
115
+ return datetime.strftime(value, self.time_format)
116
+ elif isinstance(value, str):
117
+ return value
118
+ else:
119
+ return datetime.fromtimestamp(
120
+ value, tz=pytz.timezone(self.timezone) if self.timezone else None
121
+ ).strftime(self.time_format)
122
+
123
+ def api_info(self) -> dict[str, Any]:
124
+ return {
125
+ "type": "string",
126
+ "description": f"Formatted as YYYY-MM-DD{' HH:MM:SS' if self.include_time else ''}",
127
+ }
128
+
129
+ def example_payload(self) -> str:
130
+ return "2020-10-01 05:20:15"
131
+
132
+ def example_value(self) -> str:
133
+ return "2020-10-01 05:20:15"
134
+
135
+ def get_datetime_from_str(self, date: str) -> datetime:
136
+ now_regex = r"^(?:\s*now\s*(?:-\s*(\d+)\s*([dmhs]))?)?\s*$"
137
+
138
+ if "now" in date:
139
+ match = re.match(now_regex, date)
140
+ if match:
141
+ num = int(match.group(1) or 0)
142
+ unit = match.group(2) or "s"
143
+ if unit == "d":
144
+ delta = timedelta(days=num)
145
+ elif unit == "h":
146
+ delta = timedelta(hours=num)
147
+ elif unit == "m":
148
+ delta = timedelta(minutes=num)
149
+ else:
150
+ delta = timedelta(seconds=num)
151
+ return datetime.now() - delta
152
+ else:
153
+ raise ValueError("Invalid 'now' time format")
154
+ else:
155
+ dt = datetime.strptime(date, self.time_format)
156
+ if self.timezone:
157
+ dt = pytz.timezone(self.timezone).localize(dt)
158
+ return dt
159
+ from typing import Callable, Literal, Sequence, Any, TYPE_CHECKING
160
+ from gradio.blocks import Block
161
+ if TYPE_CHECKING:
162
+ from gradio.components import Timer
163
+
164
+
165
+ def change(self,
166
+ fn: Callable[..., Any] | None = None,
167
+ inputs: Block | Sequence[Block] | set[Block] | None = None,
168
+ outputs: Block | Sequence[Block] | None = None,
169
+ api_name: str | None | Literal[False] = None,
170
+ scroll_to_output: bool = False,
171
+ show_progress: Literal["full", "minimal", "hidden"] = "full",
172
+ queue: bool | None = None,
173
+ batch: bool = False,
174
+ max_batch_size: int = 4,
175
+ preprocess: bool = True,
176
+ postprocess: bool = True,
177
+ cancels: dict[str, Any] | list[dict[str, Any]] | None = None,
178
+ every: Timer | float | None = None,
179
+ trigger_mode: Literal["once", "multiple", "always_last"] | None = None,
180
+ js: str | None = None,
181
+ concurrency_limit: int | None | Literal["default"] = "default",
182
+ concurrency_id: str | None = None,
183
+ show_api: bool = True,
184
+
185
+ ) -> Dependency:
186
+ """
187
+ Parameters:
188
+ fn: the function to call when this event is triggered. 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.
189
+ inputs: list of gradio.components to use as inputs. If the function takes no inputs, this should be an empty list.
190
+ outputs: list of gradio.components to use as outputs. If the function returns no outputs, this should be an empty list.
191
+ 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, will use the functions name as the endpoint route. If set to a string, the endpoint will be exposed in the api docs with the given name.
192
+ scroll_to_output: if True, will scroll to output component on completion
193
+ show_progress: how to show the progress animation while event is running: "full" shows a spinner which covers the output component area as well as a runtime display in the upper right corner, "minimal" only shows the runtime display, "hidden" shows no progress animation at all
194
+ 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.
195
+ batch: 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.
196
+ max_batch_size: maximum number of inputs to batch together if this is called from the queue (only relevant if batch=True)
197
+ preprocess: 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).
198
+ postprocess: if False, will not run postprocessing of component data before returning 'fn' output to the browser.
199
+ cancels: a list of other events to cancel when this listener 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. Functions that have not yet run (or generators that are iterating) will be cancelled, but functions that are currently running will be allowed to finish.
200
+ every: continously calls `value` to recalculate it if `value` is a function (has no effect otherwise). Can provide a Timer whose tick resets `value`, or a float that provides the regular interval for the reset Timer.
201
+ trigger_mode: if "once" (default for all events except `.change()`) would not allow any submissions while an event is pending. If set to "multiple", unlimited submissions are allowed while pending, and "always_last" (default for `.change()` and `.key_up()` events) would allow a second submission after the pending event is complete.
202
+ js: 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.
203
+ concurrency_limit: if set, this is the maximum number of this event that can be running simultaneously. Can be set to None to mean no concurrency_limit (any number of this event can be running simultaneously). Set to "default" to use the default concurrency limit (defined by the `default_concurrency_limit` parameter in `Blocks.queue()`, which itself is 1 by default).
204
+ concurrency_id: if set, this is the id of the concurrency group. Events with the same concurrency_id will be limited by the lowest set concurrency_limit.
205
+ show_api: whether to show this event in the "view API" page of the Gradio app, or in the ".view_api()" method of the Gradio clients. Unlike setting api_name to False, setting show_api to False will still allow downstream apps as well as the Clients to use this event. If fn is None, show_api will automatically be set to False.
206
+
207
+ """
208
+ ...
209
+
210
+ def submit(self,
211
+ fn: Callable[..., Any] | None = None,
212
+ inputs: Block | Sequence[Block] | set[Block] | None = None,
213
+ outputs: Block | Sequence[Block] | None = None,
214
+ api_name: str | None | Literal[False] = None,
215
+ scroll_to_output: bool = False,
216
+ show_progress: Literal["full", "minimal", "hidden"] = "full",
217
+ queue: bool | None = None,
218
+ batch: bool = False,
219
+ max_batch_size: int = 4,
220
+ preprocess: bool = True,
221
+ postprocess: bool = True,
222
+ cancels: dict[str, Any] | list[dict[str, Any]] | None = None,
223
+ every: Timer | float | None = None,
224
+ trigger_mode: Literal["once", "multiple", "always_last"] | None = None,
225
+ js: str | None = None,
226
+ concurrency_limit: int | None | Literal["default"] = "default",
227
+ concurrency_id: str | None = None,
228
+ show_api: bool = True,
229
+
230
+ ) -> Dependency:
231
+ """
232
+ Parameters:
233
+ fn: the function to call when this event is triggered. 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.
234
+ inputs: list of gradio.components to use as inputs. If the function takes no inputs, this should be an empty list.
235
+ outputs: list of gradio.components to use as outputs. If the function returns no outputs, this should be an empty list.
236
+ 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, will use the functions name as the endpoint route. If set to a string, the endpoint will be exposed in the api docs with the given name.
237
+ scroll_to_output: if True, will scroll to output component on completion
238
+ show_progress: how to show the progress animation while event is running: "full" shows a spinner which covers the output component area as well as a runtime display in the upper right corner, "minimal" only shows the runtime display, "hidden" shows no progress animation at all
239
+ 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.
240
+ batch: 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.
241
+ max_batch_size: maximum number of inputs to batch together if this is called from the queue (only relevant if batch=True)
242
+ preprocess: 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).
243
+ postprocess: if False, will not run postprocessing of component data before returning 'fn' output to the browser.
244
+ cancels: a list of other events to cancel when this listener 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. Functions that have not yet run (or generators that are iterating) will be cancelled, but functions that are currently running will be allowed to finish.
245
+ every: continously calls `value` to recalculate it if `value` is a function (has no effect otherwise). Can provide a Timer whose tick resets `value`, or a float that provides the regular interval for the reset Timer.
246
+ trigger_mode: if "once" (default for all events except `.change()`) would not allow any submissions while an event is pending. If set to "multiple", unlimited submissions are allowed while pending, and "always_last" (default for `.change()` and `.key_up()` events) would allow a second submission after the pending event is complete.
247
+ js: 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.
248
+ concurrency_limit: if set, this is the maximum number of this event that can be running simultaneously. Can be set to None to mean no concurrency_limit (any number of this event can be running simultaneously). Set to "default" to use the default concurrency limit (defined by the `default_concurrency_limit` parameter in `Blocks.queue()`, which itself is 1 by default).
249
+ concurrency_id: if set, this is the id of the concurrency group. Events with the same concurrency_id will be limited by the lowest set concurrency_limit.
250
+ show_api: whether to show this event in the "view API" page of the Gradio app, or in the ".view_api()" method of the Gradio clients. Unlike setting api_name to False, setting show_api to False will still allow downstream apps as well as the Clients to use this event. If fn is None, show_api will automatically be set to False.
251
+
252
+ """
253
+ ...
mantis_evalkit/lib/python3.10/site-packages/gradio/components/download_button.pyi ADDED
@@ -0,0 +1,174 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """gr.DownloadButton() component."""
2
+
3
+ from __future__ import annotations
4
+
5
+ import tempfile
6
+ from collections.abc import Callable, Sequence
7
+ from pathlib import Path
8
+ from typing import TYPE_CHECKING, Literal
9
+
10
+ from gradio_client import handle_file
11
+ from gradio_client.documentation import document
12
+
13
+ from gradio.components.base import Component
14
+ from gradio.data_classes import FileData
15
+ from gradio.events import Events
16
+
17
+ if TYPE_CHECKING:
18
+ from gradio.components import Timer
19
+
20
+ from gradio.events import Dependency
21
+
22
+ @document()
23
+ class DownloadButton(Component):
24
+ """
25
+ Creates a button, that when clicked, allows a user to download a single file of arbitrary type.
26
+
27
+ Demos: upload_and_download
28
+ """
29
+
30
+ EVENTS = [Events.click]
31
+
32
+ def __init__(
33
+ self,
34
+ label: str = "Download",
35
+ value: str | Path | Callable | None = None,
36
+ *,
37
+ every: Timer | float | None = None,
38
+ inputs: Component | Sequence[Component] | set[Component] | None = None,
39
+ variant: Literal["primary", "secondary", "stop"] = "secondary",
40
+ visible: bool = True,
41
+ size: Literal["sm", "md", "lg"] = "lg",
42
+ icon: str | None = None,
43
+ scale: int | None = None,
44
+ min_width: int | None = None,
45
+ interactive: bool = True,
46
+ elem_id: str | None = None,
47
+ elem_classes: list[str] | str | None = None,
48
+ render: bool = True,
49
+ key: int | str | None = None,
50
+ ):
51
+ """
52
+ Parameters:
53
+ label: Text to display on the button. Defaults to "Download".
54
+ value: A str or pathlib.Path filepath or URL to download, or a Callable that returns a str or pathlib.Path filepath or URL to download.
55
+ every: Continously calls `value` to recalculate it if `value` is a function (has no effect otherwise). Can provide a Timer whose tick resets `value`, or a float that provides the regular interval for the reset Timer.
56
+ inputs: Components that are used as inputs to calculate `value` if `value` is a function (has no effect otherwise). `value` is recalculated any time the inputs change.
57
+ variant: 'primary' for main call-to-action, 'secondary' for a more subdued style, 'stop' for a stop button.
58
+ visible: If False, component will be hidden.
59
+ size: size of the button. Can be "sm", "md", or "lg".
60
+ icon: URL or path to the icon file to display within the button. If None, no icon will be displayed.
61
+ scale: relative size compared to adjacent Components. For example if Components A and B are in a Row, and A has scale=2, and B has scale=1, A will be twice as wide as B. Should be an integer. scale applies in Rows, and to top-level Components in Blocks where fill_height=True.
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 False, the UploadButton will be in a disabled state.
64
+ 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.
65
+ 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.
66
+ render: If False, component will not render be rendered in the Blocks context. Should be used if the intention is to assign event listeners now but render the component later.
67
+ key: if assigned, will be used to assume identity across a re-render. Components that have the same key across a re-render will have their value preserved.
68
+ """
69
+ self.data_model = FileData
70
+ self.size = size
71
+ self.label = label
72
+ self.variant = variant
73
+ super().__init__(
74
+ label=label,
75
+ every=every,
76
+ inputs=inputs,
77
+ visible=visible,
78
+ elem_id=elem_id,
79
+ elem_classes=elem_classes,
80
+ render=render,
81
+ key=key,
82
+ value=value,
83
+ scale=scale,
84
+ min_width=min_width,
85
+ interactive=interactive,
86
+ )
87
+ self.icon = self.serve_static_file(icon)
88
+
89
+ def preprocess(self, payload: FileData | None) -> str | None:
90
+ """
91
+ Parameters:
92
+ payload: File information as a FileData object,
93
+ Returns:
94
+ (Rarely used) passes the file as a `str` into the function.
95
+ """
96
+ if payload is None:
97
+ return None
98
+ file_name = payload.path
99
+ file = tempfile.NamedTemporaryFile(delete=False, dir=self.GRADIO_CACHE)
100
+ file.name = file_name
101
+ return file_name
102
+
103
+ def postprocess(self, value: str | Path | None) -> FileData | None:
104
+ """
105
+ Parameters:
106
+ value: Expects a `str` or `pathlib.Path` filepath
107
+ Returns:
108
+ File information as a FileData object
109
+ """
110
+ if value is None:
111
+ return None
112
+ return FileData(path=str(value), orig_name=Path(value).name)
113
+
114
+ def example_payload(self) -> dict:
115
+ return handle_file(
116
+ "https://github.com/gradio-app/gradio/raw/main/test/test_files/sample_file.pdf"
117
+ )
118
+
119
+ def example_value(self) -> str:
120
+ return "https://github.com/gradio-app/gradio/raw/main/test/test_files/sample_file.pdf"
121
+
122
+ @property
123
+ def skip_api(self):
124
+ return False
125
+ from typing import Callable, Literal, Sequence, Any, TYPE_CHECKING
126
+ from gradio.blocks import Block
127
+ if TYPE_CHECKING:
128
+ from gradio.components import Timer
129
+
130
+
131
+ def click(self,
132
+ fn: Callable[..., Any] | None = None,
133
+ inputs: Block | Sequence[Block] | set[Block] | None = None,
134
+ outputs: Block | Sequence[Block] | None = None,
135
+ api_name: str | None | Literal[False] = None,
136
+ scroll_to_output: bool = False,
137
+ show_progress: Literal["full", "minimal", "hidden"] = "full",
138
+ queue: bool | None = None,
139
+ batch: bool = False,
140
+ max_batch_size: int = 4,
141
+ preprocess: bool = True,
142
+ postprocess: bool = True,
143
+ cancels: dict[str, Any] | list[dict[str, Any]] | None = None,
144
+ every: Timer | float | None = None,
145
+ trigger_mode: Literal["once", "multiple", "always_last"] | None = None,
146
+ js: str | None = None,
147
+ concurrency_limit: int | None | Literal["default"] = "default",
148
+ concurrency_id: str | None = None,
149
+ show_api: bool = True,
150
+
151
+ ) -> Dependency:
152
+ """
153
+ Parameters:
154
+ fn: the function to call when this event is triggered. 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.
155
+ inputs: list of gradio.components to use as inputs. If the function takes no inputs, this should be an empty list.
156
+ outputs: list of gradio.components to use as outputs. If the function returns no outputs, this should be an empty list.
157
+ 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, will use the functions name as the endpoint route. If set to a string, the endpoint will be exposed in the api docs with the given name.
158
+ scroll_to_output: if True, will scroll to output component on completion
159
+ show_progress: how to show the progress animation while event is running: "full" shows a spinner which covers the output component area as well as a runtime display in the upper right corner, "minimal" only shows the runtime display, "hidden" shows no progress animation at all
160
+ 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.
161
+ batch: 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.
162
+ max_batch_size: maximum number of inputs to batch together if this is called from the queue (only relevant if batch=True)
163
+ preprocess: 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).
164
+ postprocess: if False, will not run postprocessing of component data before returning 'fn' output to the browser.
165
+ cancels: a list of other events to cancel when this listener 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. Functions that have not yet run (or generators that are iterating) will be cancelled, but functions that are currently running will be allowed to finish.
166
+ every: continously calls `value` to recalculate it if `value` is a function (has no effect otherwise). Can provide a Timer whose tick resets `value`, or a float that provides the regular interval for the reset Timer.
167
+ trigger_mode: if "once" (default for all events except `.change()`) would not allow any submissions while an event is pending. If set to "multiple", unlimited submissions are allowed while pending, and "always_last" (default for `.change()` and `.key_up()` events) would allow a second submission after the pending event is complete.
168
+ js: 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.
169
+ concurrency_limit: if set, this is the maximum number of this event that can be running simultaneously. Can be set to None to mean no concurrency_limit (any number of this event can be running simultaneously). Set to "default" to use the default concurrency limit (defined by the `default_concurrency_limit` parameter in `Blocks.queue()`, which itself is 1 by default).
170
+ concurrency_id: if set, this is the id of the concurrency group. Events with the same concurrency_id will be limited by the lowest set concurrency_limit.
171
+ show_api: whether to show this event in the "view API" page of the Gradio app, or in the ".view_api()" method of the Gradio clients. Unlike setting api_name to False, setting show_api to False will still allow downstream apps as well as the Clients to use this event. If fn is None, show_api will automatically be set to False.
172
+
173
+ """
174
+ ...
mantis_evalkit/lib/python3.10/site-packages/gradio/components/dropdown.py ADDED
@@ -0,0 +1,247 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """gr.Dropdown() component."""
2
+
3
+ from __future__ import annotations
4
+
5
+ import warnings
6
+ from collections.abc import Callable, Sequence
7
+ from typing import TYPE_CHECKING, Any, Literal
8
+
9
+ from gradio_client.documentation import document
10
+
11
+ from gradio.components.base import Component, FormComponent
12
+ from gradio.events import Events
13
+ from gradio.exceptions import Error
14
+
15
+ if TYPE_CHECKING:
16
+ from gradio.components import Timer
17
+
18
+
19
+ class DefaultValue:
20
+ # This sentinel is used to indicate that if the value is not explicitly set,
21
+ # the first choice should be selected in the dropdown if multiselect is False,
22
+ # and an empty list should be selected if multiselect is True.
23
+ pass
24
+
25
+
26
+ DEFAULT_VALUE = DefaultValue()
27
+
28
+
29
+ @document()
30
+ class Dropdown(FormComponent):
31
+ """
32
+ Creates a dropdown of choices from which a single entry or multiple entries can be selected (as an input component) or displayed (as an output component).
33
+
34
+ Demos: sentence_builder
35
+ """
36
+
37
+ EVENTS = [
38
+ Events.change,
39
+ Events.input,
40
+ Events.select,
41
+ Events.focus,
42
+ Events.blur,
43
+ Events.key_up,
44
+ ]
45
+
46
+ def __init__(
47
+ self,
48
+ choices: Sequence[str | int | float | tuple[str, str | int | float]]
49
+ | None = None,
50
+ *,
51
+ value: str
52
+ | int
53
+ | float
54
+ | Sequence[str | int | float]
55
+ | Callable
56
+ | DefaultValue
57
+ | None = DEFAULT_VALUE,
58
+ type: Literal["value", "index"] = "value",
59
+ multiselect: bool | None = None,
60
+ allow_custom_value: bool = False,
61
+ max_choices: int | None = None,
62
+ filterable: bool = True,
63
+ label: str | None = None,
64
+ info: str | None = None,
65
+ every: Timer | float | None = None,
66
+ inputs: Component | Sequence[Component] | set[Component] | None = None,
67
+ show_label: bool | None = None,
68
+ container: bool = True,
69
+ scale: int | None = None,
70
+ min_width: int = 160,
71
+ interactive: bool | None = None,
72
+ visible: bool = True,
73
+ elem_id: str | None = None,
74
+ elem_classes: list[str] | str | None = None,
75
+ render: bool = True,
76
+ key: int | str | None = None,
77
+ ):
78
+ """
79
+ Parameters:
80
+ choices: a list of string or numeric options to choose from. An option can also be a tuple of the form (name, value), where name is the displayed name of the dropdown choice and value is the value to be passed to the function, or returned by the function.
81
+ value: the value selected in dropdown. If `multiselect` is true, this should be list, otherwise a single string or number. By default, the first choice is initally selected. If set to None, no value is initally selected. If a callable, the function will be called whenever the app loads to set the initial value of the component.
82
+ 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.
83
+ multiselect: if True, multiple choices can be selected.
84
+ allow_custom_value: if True, allows user to enter a custom value that is not in the list of choices.
85
+ max_choices: maximum number of choices that can be selected. If None, no limit is enforced.
86
+ filterable: if True, user will be able to type into the dropdown and filter the choices by typing. Can only be set to False if `allow_custom_value` is False.
87
+ label: the label for this component, displayed above the component if `show_label` is `True` and is also used as the header if there are a table of examples for this component. If None and used in a `gr.Interface`, the label will be the name of the parameter this component corresponds to.
88
+ info: additional component description, appears below the label in smaller font. Supports markdown / HTML syntax.
89
+ every: continously calls `value` to recalculate it if `value` is a function (has no effect otherwise). Can provide a Timer whose tick resets `value`, or a float that provides the regular interval for the reset Timer.
90
+ inputs: components that are used as inputs to calculate `value` if `value` is a function (has no effect otherwise). `value` is recalculated any time the inputs change.
91
+ show_label: if True, will display label.
92
+ container: if True, will place the component in a container - providing some extra padding around the border.
93
+ scale: relative size compared to adjacent Components. For example if Components A and B are in a Row, and A has scale=2, and B has scale=1, A will be twice as wide as B. Should be an integer. scale applies in Rows, and to top-level Components in Blocks where fill_height=True.
94
+ 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.
95
+ 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.
96
+ visible: if False, component will be hidden.
97
+ 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.
98
+ 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.
99
+ render: if False, component will not be rendered in the Blocks context. Should be used if the intention is to assign event listeners now but render the component later.
100
+ """
101
+ self.choices = (
102
+ # Although we expect choices to be a list of tuples, it can be a list of lists if the Gradio app
103
+ # is loaded with gr.load() since Python tuples are converted to lists in JSON.
104
+ [tuple(c) if isinstance(c, (tuple, list)) else (str(c), c) for c in choices]
105
+ if choices
106
+ else []
107
+ )
108
+ valid_types = ["value", "index"]
109
+ if type not in valid_types:
110
+ raise ValueError(
111
+ f"Invalid value for parameter `type`: {type}. Please choose from one of: {valid_types}"
112
+ )
113
+ self.type = type
114
+ self.multiselect = multiselect
115
+
116
+ if value == DEFAULT_VALUE:
117
+ if multiselect:
118
+ value = []
119
+ elif self.choices:
120
+ value = self.choices[0][1]
121
+ else:
122
+ value = None
123
+ if multiselect and isinstance(value, str):
124
+ value = [value]
125
+
126
+ if not multiselect and max_choices is not None:
127
+ warnings.warn(
128
+ "The `max_choices` parameter is ignored when `multiselect` is False."
129
+ )
130
+ if not filterable and allow_custom_value:
131
+ filterable = True
132
+ warnings.warn(
133
+ "The `filterable` parameter cannot be set to False when `allow_custom_value` is True. Setting `filterable` to True."
134
+ )
135
+ self.max_choices = max_choices
136
+ self.allow_custom_value = allow_custom_value
137
+ self.filterable = filterable
138
+ super().__init__(
139
+ label=label,
140
+ info=info,
141
+ every=every,
142
+ inputs=inputs,
143
+ show_label=show_label,
144
+ container=container,
145
+ scale=scale,
146
+ min_width=min_width,
147
+ interactive=interactive,
148
+ visible=visible,
149
+ elem_id=elem_id,
150
+ elem_classes=elem_classes,
151
+ render=render,
152
+ key=key,
153
+ value=value,
154
+ )
155
+
156
+ def api_info(self) -> dict[str, Any]:
157
+ if self.multiselect:
158
+ json_type = {
159
+ "type": "array",
160
+ "items": {"type": "string", "enum": [c[1] for c in self.choices]},
161
+ }
162
+ else:
163
+ json_type = {
164
+ "type": "string",
165
+ "enum": [c[1] for c in self.choices],
166
+ }
167
+ return json_type
168
+
169
+ def example_payload(self) -> Any:
170
+ if self.multiselect:
171
+ return [self.choices[0][1]] if self.choices else []
172
+ else:
173
+ return self.choices[0][1] if self.choices else None
174
+
175
+ def example_value(self) -> Any:
176
+ if self.multiselect:
177
+ return [self.choices[0][1]] if self.choices else []
178
+ else:
179
+ return self.choices[0][1] if self.choices else None
180
+
181
+ def preprocess(
182
+ self, payload: str | int | float | list[str | int | float] | None
183
+ ) -> str | int | float | list[str | int | float] | list[int | None] | None:
184
+ """
185
+ Parameters:
186
+ payload: the value of the selected dropdown choice(s)
187
+ Returns:
188
+ Passes the value of the selected dropdown choice as a `str | int | float` or its index as an `int` into the function, depending on `type`. Or, if `multiselect` is True, passes the values of the selected dropdown choices as a list of correspoding values/indices instead.
189
+ """
190
+ if payload is None:
191
+ return None
192
+
193
+ choice_values = [value for _, value in self.choices]
194
+ if not self.allow_custom_value:
195
+ if isinstance(payload, list):
196
+ for value in payload:
197
+ if value not in choice_values:
198
+ raise Error(
199
+ f"Value: {value!r} (type: {type(value)}) is not in the list of choices: {choice_values}"
200
+ )
201
+ elif payload not in choice_values:
202
+ raise Error(
203
+ f"Value: {payload} is not in the list of choices: {choice_values}"
204
+ )
205
+
206
+ if self.type == "value":
207
+ return payload
208
+ elif self.type == "index":
209
+ if isinstance(payload, list):
210
+ return [
211
+ choice_values.index(choice) if choice in choice_values else None
212
+ for choice in payload
213
+ ]
214
+ else:
215
+ return (
216
+ choice_values.index(payload) if payload in choice_values else None
217
+ )
218
+ else:
219
+ raise ValueError(
220
+ f"Unknown type: {self.type}. Please choose from: 'value', 'index'."
221
+ )
222
+
223
+ def _warn_if_invalid_choice(self, value):
224
+ if self.allow_custom_value or value in [value for _, value in self.choices]:
225
+ return
226
+ warnings.warn(
227
+ f"The value passed into gr.Dropdown() is not in the list of choices. Please update the list of choices to include: {value} or set allow_custom_value=True."
228
+ )
229
+
230
+ def postprocess(
231
+ self, value: str | int | float | list[str | int | float] | None
232
+ ) -> str | int | float | list[str | int | float] | None:
233
+ """
234
+ Parameters:
235
+ value: Expects a `str | int | float` corresponding to the value of the dropdown entry to be selected. Or, if `multiselect` is True, expects a `list` of values corresponding to the selected dropdown entries.
236
+ Returns:
237
+ Returns the values of the selected dropdown entry or entries.
238
+ """
239
+ if value is None:
240
+ return None
241
+ if self.multiselect:
242
+ if not isinstance(value, list):
243
+ value = [value]
244
+ [self._warn_if_invalid_choice(_y) for _y in value]
245
+ else:
246
+ self._warn_if_invalid_choice(value)
247
+ return value
mantis_evalkit/lib/python3.10/site-packages/gradio/components/duplicate_button.py ADDED
@@ -0,0 +1,92 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """gr.DuplicateButton() component"""
2
+
3
+ from __future__ import annotations
4
+
5
+ from collections.abc import Sequence
6
+ from pathlib import Path
7
+ from typing import TYPE_CHECKING, Literal
8
+
9
+ from gradio_client.documentation import document
10
+
11
+ from gradio.components import Button, Component
12
+ from gradio.context import get_blocks_context
13
+ from gradio.utils import get_space
14
+
15
+ if TYPE_CHECKING:
16
+ from gradio.components import Timer
17
+
18
+
19
+ @document()
20
+ class DuplicateButton(Button):
21
+ """
22
+ Button that triggers a Spaces Duplication, when the demo is on Hugging Face Spaces. Does nothing locally.
23
+ """
24
+
25
+ is_template = True
26
+
27
+ def __init__(
28
+ self,
29
+ value: str = "Duplicate Space",
30
+ *,
31
+ every: Timer | float | None = None,
32
+ inputs: Component | Sequence[Component] | set[Component] | None = None,
33
+ variant: Literal["primary", "secondary", "stop", "huggingface"] = "huggingface",
34
+ size: Literal["sm", "md", "lg"] = "sm",
35
+ icon: str | Path | None = None,
36
+ link: str | None = None,
37
+ visible: bool = True,
38
+ interactive: bool = True,
39
+ elem_id: str | None = None,
40
+ elem_classes: list[str] | str | None = None,
41
+ render: bool = True,
42
+ key: int | str | None = None,
43
+ scale: int | None = 0,
44
+ min_width: int | None = None,
45
+ _activate: bool = True,
46
+ ):
47
+ """
48
+ Parameters:
49
+ Parameters:
50
+ 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.
51
+ every: continuously calls `value` to recalculate it if `value` is a function (has no effect otherwise). Can provide a Timer whose tick resets `value`, or a float that provides the regular interval for the reset Timer.
52
+ inputs: components that are used as inputs to calculate `value` if `value` is a function (has no effect otherwise). `value` is recalculated any time the inputs change.
53
+ variant: sets the background and text color of the button. Use 'primary' for main call-to-action buttons, 'secondary' for a more subdued style, 'stop' for a stop button, 'huggingface' for a black background with white text, consistent with Hugging Face's button styles.
54
+ size: size of the button. Can be "sm", "md", or "lg".
55
+ icon: URL or path to the icon file to display within the button. If None, no icon will be displayed.
56
+ link: URL to open when the button is clicked. If None, no link will be used.
57
+ visible: if False, component will be hidden.
58
+ interactive: if False, the Button 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
+ render: if False, component will not render be rendered in the Blocks context. Should be used if the intention is to assign event listeners now but render the component later.
62
+ key: if assigned, will be used to assume identity across a re-render. Components that have the same key across a re-render will have their value preserved.
63
+ scale: relative size compared to adjacent Components. For example if Components A and B are in a Row, and A has scale=2, and B has scale=1, A will be twice as wide as B. Should be an integer. scale applies in Rows, and to top-level Components in Blocks where fill_height=True.
64
+ min_width: minimum pixel width, will wrap if not sufficient screen space to satisfy this value. If a certain scale value results in this Component being narrower than min_width, the min_width parameter will be respected first.
65
+ """
66
+ super().__init__(
67
+ value=value,
68
+ every=every,
69
+ inputs=inputs,
70
+ variant=variant,
71
+ size=size,
72
+ icon=icon,
73
+ link=link,
74
+ visible=visible,
75
+ interactive=interactive,
76
+ elem_id=elem_id,
77
+ elem_classes=elem_classes,
78
+ render=render,
79
+ key=key,
80
+ scale=scale,
81
+ min_width=min_width,
82
+ )
83
+ if _activate and get_blocks_context():
84
+ self.activate()
85
+
86
+ def activate(self):
87
+ space_name = get_space()
88
+ if space_name is not None:
89
+ self.click(
90
+ fn=None,
91
+ js=f"() => {{ window.open(`https://huggingface.co/spaces/{space_name}?duplicate=true`, '_blank') }}",
92
+ )