diff --git a/mantis_evalkit/lib/python3.10/site-packages/gradio/components/__pycache__/api_component.cpython-310.pyc b/mantis_evalkit/lib/python3.10/site-packages/gradio/components/__pycache__/api_component.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..4fb7ebd94b75f291cde5dfd8aad34b6fc2d4cd5b Binary files /dev/null and b/mantis_evalkit/lib/python3.10/site-packages/gradio/components/__pycache__/api_component.cpython-310.pyc differ diff --git a/mantis_evalkit/lib/python3.10/site-packages/gradio/components/__pycache__/audio.cpython-310.pyc b/mantis_evalkit/lib/python3.10/site-packages/gradio/components/__pycache__/audio.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..8909e0fce04e238f1ad679a028c46ef16b29bece Binary files /dev/null and b/mantis_evalkit/lib/python3.10/site-packages/gradio/components/__pycache__/audio.cpython-310.pyc differ diff --git a/mantis_evalkit/lib/python3.10/site-packages/gradio/components/__pycache__/bar_plot.cpython-310.pyc b/mantis_evalkit/lib/python3.10/site-packages/gradio/components/__pycache__/bar_plot.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..9efbfb863657f9044173cdb0942a7d618f7b9453 Binary files /dev/null and b/mantis_evalkit/lib/python3.10/site-packages/gradio/components/__pycache__/bar_plot.cpython-310.pyc differ diff --git a/mantis_evalkit/lib/python3.10/site-packages/gradio/components/__pycache__/base.cpython-310.pyc b/mantis_evalkit/lib/python3.10/site-packages/gradio/components/__pycache__/base.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..8c3bb078ca6d00f138f074e04a7fa61427c5e555 Binary files /dev/null and b/mantis_evalkit/lib/python3.10/site-packages/gradio/components/__pycache__/base.cpython-310.pyc differ diff --git a/mantis_evalkit/lib/python3.10/site-packages/gradio/components/__pycache__/browser_state.cpython-310.pyc b/mantis_evalkit/lib/python3.10/site-packages/gradio/components/__pycache__/browser_state.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..232425fb15c4938925804e7a7e5708e0e7dd0709 Binary files /dev/null and b/mantis_evalkit/lib/python3.10/site-packages/gradio/components/__pycache__/browser_state.cpython-310.pyc differ diff --git a/mantis_evalkit/lib/python3.10/site-packages/gradio/components/__pycache__/button.cpython-310.pyc b/mantis_evalkit/lib/python3.10/site-packages/gradio/components/__pycache__/button.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..ee1cece3a92fb6089745f6e163a391c827b92413 Binary files /dev/null and b/mantis_evalkit/lib/python3.10/site-packages/gradio/components/__pycache__/button.cpython-310.pyc differ diff --git a/mantis_evalkit/lib/python3.10/site-packages/gradio/components/__pycache__/chatbot.cpython-310.pyc b/mantis_evalkit/lib/python3.10/site-packages/gradio/components/__pycache__/chatbot.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..06e46df889260195de3b5bb7c5dac929d0893946 Binary files /dev/null and b/mantis_evalkit/lib/python3.10/site-packages/gradio/components/__pycache__/chatbot.cpython-310.pyc differ diff --git a/mantis_evalkit/lib/python3.10/site-packages/gradio/components/__pycache__/checkbox.cpython-310.pyc b/mantis_evalkit/lib/python3.10/site-packages/gradio/components/__pycache__/checkbox.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..a0525eb6aede1544dec8260c2637d987989c5c40 Binary files /dev/null and b/mantis_evalkit/lib/python3.10/site-packages/gradio/components/__pycache__/checkbox.cpython-310.pyc differ diff --git a/mantis_evalkit/lib/python3.10/site-packages/gradio/components/__pycache__/checkboxgroup.cpython-310.pyc b/mantis_evalkit/lib/python3.10/site-packages/gradio/components/__pycache__/checkboxgroup.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..a698690a7ed7566f0bb34f26a0cd253b978146bf Binary files /dev/null and b/mantis_evalkit/lib/python3.10/site-packages/gradio/components/__pycache__/checkboxgroup.cpython-310.pyc differ diff --git a/mantis_evalkit/lib/python3.10/site-packages/gradio/components/__pycache__/clear_button.cpython-310.pyc b/mantis_evalkit/lib/python3.10/site-packages/gradio/components/__pycache__/clear_button.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..0e658de009ccbdd40532225c2ce16a0426871ea5 Binary files /dev/null and b/mantis_evalkit/lib/python3.10/site-packages/gradio/components/__pycache__/clear_button.cpython-310.pyc differ diff --git a/mantis_evalkit/lib/python3.10/site-packages/gradio/components/__pycache__/code.cpython-310.pyc b/mantis_evalkit/lib/python3.10/site-packages/gradio/components/__pycache__/code.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..4b5bb555b7b4243647faa1dd681ab38b7453d21d Binary files /dev/null and b/mantis_evalkit/lib/python3.10/site-packages/gradio/components/__pycache__/code.cpython-310.pyc differ diff --git a/mantis_evalkit/lib/python3.10/site-packages/gradio/components/__pycache__/color_picker.cpython-310.pyc b/mantis_evalkit/lib/python3.10/site-packages/gradio/components/__pycache__/color_picker.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..cc2d006a4017a2233a7f78b30e2713aa66c0a064 Binary files /dev/null and b/mantis_evalkit/lib/python3.10/site-packages/gradio/components/__pycache__/color_picker.cpython-310.pyc differ diff --git a/mantis_evalkit/lib/python3.10/site-packages/gradio/components/__pycache__/dataframe.cpython-310.pyc b/mantis_evalkit/lib/python3.10/site-packages/gradio/components/__pycache__/dataframe.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..c99dfbdc4838e1f47bcd180be854330930a87426 Binary files /dev/null and b/mantis_evalkit/lib/python3.10/site-packages/gradio/components/__pycache__/dataframe.cpython-310.pyc differ diff --git a/mantis_evalkit/lib/python3.10/site-packages/gradio/components/__pycache__/dataset.cpython-310.pyc b/mantis_evalkit/lib/python3.10/site-packages/gradio/components/__pycache__/dataset.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..6939d47e4e3713c63e93930c8e357ce27d380160 Binary files /dev/null and b/mantis_evalkit/lib/python3.10/site-packages/gradio/components/__pycache__/dataset.cpython-310.pyc differ diff --git a/mantis_evalkit/lib/python3.10/site-packages/gradio/components/__pycache__/download_button.cpython-310.pyc b/mantis_evalkit/lib/python3.10/site-packages/gradio/components/__pycache__/download_button.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..8455940a828d9c749d4dc378abaca0bfb773855d Binary files /dev/null and b/mantis_evalkit/lib/python3.10/site-packages/gradio/components/__pycache__/download_button.cpython-310.pyc differ diff --git a/mantis_evalkit/lib/python3.10/site-packages/gradio/components/__pycache__/duplicate_button.cpython-310.pyc b/mantis_evalkit/lib/python3.10/site-packages/gradio/components/__pycache__/duplicate_button.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..b3d1c3d8b7624241d1b22ed2da8441f4ab929aee Binary files /dev/null and b/mantis_evalkit/lib/python3.10/site-packages/gradio/components/__pycache__/duplicate_button.cpython-310.pyc differ diff --git a/mantis_evalkit/lib/python3.10/site-packages/gradio/components/__pycache__/fallback.cpython-310.pyc b/mantis_evalkit/lib/python3.10/site-packages/gradio/components/__pycache__/fallback.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..23f4addbdadaccf4196c40ecda4469eacd8de13e Binary files /dev/null and b/mantis_evalkit/lib/python3.10/site-packages/gradio/components/__pycache__/fallback.cpython-310.pyc differ diff --git a/mantis_evalkit/lib/python3.10/site-packages/gradio/components/__pycache__/file.cpython-310.pyc b/mantis_evalkit/lib/python3.10/site-packages/gradio/components/__pycache__/file.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..1b8cefdd3403de2123c0e72a5093d8125775c843 Binary files /dev/null and b/mantis_evalkit/lib/python3.10/site-packages/gradio/components/__pycache__/file.cpython-310.pyc differ diff --git a/mantis_evalkit/lib/python3.10/site-packages/gradio/components/__pycache__/file_explorer.cpython-310.pyc b/mantis_evalkit/lib/python3.10/site-packages/gradio/components/__pycache__/file_explorer.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..31f46ba80f97013a23c43bc6b3b3ca94d83dd797 Binary files /dev/null and b/mantis_evalkit/lib/python3.10/site-packages/gradio/components/__pycache__/file_explorer.cpython-310.pyc differ diff --git a/mantis_evalkit/lib/python3.10/site-packages/gradio/components/__pycache__/gallery.cpython-310.pyc b/mantis_evalkit/lib/python3.10/site-packages/gradio/components/__pycache__/gallery.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..61f55d3ef886b1e0087b334745435bcacb3860f9 Binary files /dev/null and b/mantis_evalkit/lib/python3.10/site-packages/gradio/components/__pycache__/gallery.cpython-310.pyc differ diff --git a/mantis_evalkit/lib/python3.10/site-packages/gradio/components/__pycache__/highlighted_text.cpython-310.pyc b/mantis_evalkit/lib/python3.10/site-packages/gradio/components/__pycache__/highlighted_text.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..a333d437a15077b00130348b0038c302f4eda745 Binary files /dev/null and b/mantis_evalkit/lib/python3.10/site-packages/gradio/components/__pycache__/highlighted_text.cpython-310.pyc differ diff --git a/mantis_evalkit/lib/python3.10/site-packages/gradio/components/__pycache__/image.cpython-310.pyc b/mantis_evalkit/lib/python3.10/site-packages/gradio/components/__pycache__/image.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..9ef07b4f2242e06493509f7e956adb02e87310fc Binary files /dev/null and b/mantis_evalkit/lib/python3.10/site-packages/gradio/components/__pycache__/image.cpython-310.pyc differ diff --git a/mantis_evalkit/lib/python3.10/site-packages/gradio/components/__pycache__/image_editor.cpython-310.pyc b/mantis_evalkit/lib/python3.10/site-packages/gradio/components/__pycache__/image_editor.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..d74f47b746ea249217f89752e5de1abae5636870 Binary files /dev/null and b/mantis_evalkit/lib/python3.10/site-packages/gradio/components/__pycache__/image_editor.cpython-310.pyc differ diff --git a/mantis_evalkit/lib/python3.10/site-packages/gradio/components/__pycache__/json_component.cpython-310.pyc b/mantis_evalkit/lib/python3.10/site-packages/gradio/components/__pycache__/json_component.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..5fc11114262cd01c6d513d57455ca79b96fabb77 Binary files /dev/null and b/mantis_evalkit/lib/python3.10/site-packages/gradio/components/__pycache__/json_component.cpython-310.pyc differ diff --git a/mantis_evalkit/lib/python3.10/site-packages/gradio/components/__pycache__/label.cpython-310.pyc b/mantis_evalkit/lib/python3.10/site-packages/gradio/components/__pycache__/label.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..86b507e92543668508ee697be501458783d07a37 Binary files /dev/null and b/mantis_evalkit/lib/python3.10/site-packages/gradio/components/__pycache__/label.cpython-310.pyc differ diff --git a/mantis_evalkit/lib/python3.10/site-packages/gradio/components/__pycache__/line_plot.cpython-310.pyc b/mantis_evalkit/lib/python3.10/site-packages/gradio/components/__pycache__/line_plot.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..f9f2a93ce694576e92d7f0dd3cc38a8145fe7274 Binary files /dev/null and b/mantis_evalkit/lib/python3.10/site-packages/gradio/components/__pycache__/line_plot.cpython-310.pyc differ diff --git a/mantis_evalkit/lib/python3.10/site-packages/gradio/components/__pycache__/login_button.cpython-310.pyc b/mantis_evalkit/lib/python3.10/site-packages/gradio/components/__pycache__/login_button.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..c68ab6f457a64ac0d2c5faf35bc15f006286281f Binary files /dev/null and b/mantis_evalkit/lib/python3.10/site-packages/gradio/components/__pycache__/login_button.cpython-310.pyc differ diff --git a/mantis_evalkit/lib/python3.10/site-packages/gradio/components/__pycache__/logout_button.cpython-310.pyc b/mantis_evalkit/lib/python3.10/site-packages/gradio/components/__pycache__/logout_button.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..cb2b015a211f4887e8332451506e64528d27a5b4 Binary files /dev/null and b/mantis_evalkit/lib/python3.10/site-packages/gradio/components/__pycache__/logout_button.cpython-310.pyc differ diff --git a/mantis_evalkit/lib/python3.10/site-packages/gradio/components/__pycache__/markdown.cpython-310.pyc b/mantis_evalkit/lib/python3.10/site-packages/gradio/components/__pycache__/markdown.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..bc8f0e914b20151bec7a44b0ee1cda549ef59d4e Binary files /dev/null and b/mantis_evalkit/lib/python3.10/site-packages/gradio/components/__pycache__/markdown.cpython-310.pyc differ diff --git a/mantis_evalkit/lib/python3.10/site-packages/gradio/components/__pycache__/model3d.cpython-310.pyc b/mantis_evalkit/lib/python3.10/site-packages/gradio/components/__pycache__/model3d.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..362471cef6291270dcf769e8ee66afdfaa896ab7 Binary files /dev/null and b/mantis_evalkit/lib/python3.10/site-packages/gradio/components/__pycache__/model3d.cpython-310.pyc differ diff --git a/mantis_evalkit/lib/python3.10/site-packages/gradio/components/__pycache__/multimodal_textbox.cpython-310.pyc b/mantis_evalkit/lib/python3.10/site-packages/gradio/components/__pycache__/multimodal_textbox.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..2a2902bed29ab2e8ebb0ed72307200042eb4eb30 Binary files /dev/null and b/mantis_evalkit/lib/python3.10/site-packages/gradio/components/__pycache__/multimodal_textbox.cpython-310.pyc differ diff --git a/mantis_evalkit/lib/python3.10/site-packages/gradio/components/__pycache__/number.cpython-310.pyc b/mantis_evalkit/lib/python3.10/site-packages/gradio/components/__pycache__/number.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..299d58abf6068702dedb53b3d66cf98f4d472222 Binary files /dev/null and b/mantis_evalkit/lib/python3.10/site-packages/gradio/components/__pycache__/number.cpython-310.pyc differ diff --git a/mantis_evalkit/lib/python3.10/site-packages/gradio/components/__pycache__/paramviewer.cpython-310.pyc b/mantis_evalkit/lib/python3.10/site-packages/gradio/components/__pycache__/paramviewer.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..7807ecaf0c3d80b5ae69c7743cee03ba1602e619 Binary files /dev/null and b/mantis_evalkit/lib/python3.10/site-packages/gradio/components/__pycache__/paramviewer.cpython-310.pyc differ diff --git a/mantis_evalkit/lib/python3.10/site-packages/gradio/components/__pycache__/plot.cpython-310.pyc b/mantis_evalkit/lib/python3.10/site-packages/gradio/components/__pycache__/plot.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..0cabda8cccb18edce70be1a2cdd7a848ea3b236f Binary files /dev/null and b/mantis_evalkit/lib/python3.10/site-packages/gradio/components/__pycache__/plot.cpython-310.pyc differ diff --git a/mantis_evalkit/lib/python3.10/site-packages/gradio/components/__pycache__/scatter_plot.cpython-310.pyc b/mantis_evalkit/lib/python3.10/site-packages/gradio/components/__pycache__/scatter_plot.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..3033de09c6ed1c23e4bab8d39589e540ab63384c Binary files /dev/null and b/mantis_evalkit/lib/python3.10/site-packages/gradio/components/__pycache__/scatter_plot.cpython-310.pyc differ diff --git a/mantis_evalkit/lib/python3.10/site-packages/gradio/components/__pycache__/state.cpython-310.pyc b/mantis_evalkit/lib/python3.10/site-packages/gradio/components/__pycache__/state.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..d51bb724162f4a140c1140b490f40a993a338633 Binary files /dev/null and b/mantis_evalkit/lib/python3.10/site-packages/gradio/components/__pycache__/state.cpython-310.pyc differ diff --git a/mantis_evalkit/lib/python3.10/site-packages/gradio/components/__pycache__/textbox.cpython-310.pyc b/mantis_evalkit/lib/python3.10/site-packages/gradio/components/__pycache__/textbox.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..71dbccc80e08a1aa496f8db44ecb254535b00d40 Binary files /dev/null and b/mantis_evalkit/lib/python3.10/site-packages/gradio/components/__pycache__/textbox.cpython-310.pyc differ diff --git a/mantis_evalkit/lib/python3.10/site-packages/gradio/components/__pycache__/timer.cpython-310.pyc b/mantis_evalkit/lib/python3.10/site-packages/gradio/components/__pycache__/timer.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..d376b3cf57a8f9c6efcfdb20691101bcf9d8a3ff Binary files /dev/null and b/mantis_evalkit/lib/python3.10/site-packages/gradio/components/__pycache__/timer.cpython-310.pyc differ diff --git a/mantis_evalkit/lib/python3.10/site-packages/gradio/components/__pycache__/upload_button.cpython-310.pyc b/mantis_evalkit/lib/python3.10/site-packages/gradio/components/__pycache__/upload_button.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..99aa1c0ba3f672db47f9a5694995e3de1f9d5d3a Binary files /dev/null and b/mantis_evalkit/lib/python3.10/site-packages/gradio/components/__pycache__/upload_button.cpython-310.pyc differ diff --git a/mantis_evalkit/lib/python3.10/site-packages/gradio/components/__pycache__/video.cpython-310.pyc b/mantis_evalkit/lib/python3.10/site-packages/gradio/components/__pycache__/video.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..cb4fb2425f42a666245f1e9da983d51438627c69 Binary files /dev/null and b/mantis_evalkit/lib/python3.10/site-packages/gradio/components/__pycache__/video.cpython-310.pyc differ diff --git a/mantis_evalkit/lib/python3.10/site-packages/gradio/components/bar_plot.py b/mantis_evalkit/lib/python3.10/site-packages/gradio/components/bar_plot.py new file mode 100644 index 0000000000000000000000000000000000000000..f2adef960db9a2def17eff17a79c218f54ebb130 --- /dev/null +++ b/mantis_evalkit/lib/python3.10/site-packages/gradio/components/bar_plot.py @@ -0,0 +1,331 @@ +"""gr.BarPlot() component.""" + +from __future__ import annotations + +import warnings +from collections.abc import Callable, Sequence +from typing import TYPE_CHECKING, Any, Literal + +from gradio_client.documentation import document + +from gradio.components.base import Component +from gradio.components.plot import AltairPlot, AltairPlotData, Plot + +if TYPE_CHECKING: + import pandas as pd + + from gradio.components import Timer + + +@document() +class BarPlot(Plot): + """ + Creates a bar plot component to display data from a pandas DataFrame (as output). As this component does + not accept user input, it is rarely used as an input component. + + Demos: bar_plot + """ + + data_model = AltairPlotData + + def __init__( + self, + value: pd.DataFrame | Callable | None = None, + x: str | None = None, + y: str | None = None, + *, + color: str | None = None, + vertical: bool = True, + group: str | None = None, + title: str | None = None, + tooltip: list[str] | str | None = None, + x_title: str | None = None, + y_title: str | None = None, + x_label_angle: float | None = None, + y_label_angle: float | None = None, + color_legend_title: str | None = None, + group_title: str | None = None, + color_legend_position: Literal[ + "left", + "right", + "top", + "bottom", + "top-left", + "top-right", + "bottom-left", + "bottom-right", + "none", + ] + | None = None, + height: int | None = None, + width: int | None = None, + y_lim: list[int] | None = None, + caption: str | None = None, + interactive: bool | None = True, + label: str | None = None, + show_label: bool | None = None, + container: bool = True, + scale: int | None = None, + min_width: int = 160, + every: Timer | float | None = None, + inputs: Component | Sequence[Component] | set[Component] | None = None, + visible: bool = True, + elem_id: str | None = None, + elem_classes: list[str] | str | None = None, + render: bool = True, + key: int | str | None = None, + sort: Literal["x", "y", "-x", "-y"] | None = None, + show_actions_button: bool = False, + ): + """ + Parameters: + 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. + x: Column corresponding to the x axis. + y: Column corresponding to the y axis. + color: The column to determine the bar color. Must be categorical (discrete values). + 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. + group: The column with which to split the overall plot into smaller subplots. + title: The title to display on top of the chart. + tooltip: The column (or list of columns) to display on the tooltip when a user hovers over a bar. + x_title: The title given to the x axis. By default, uses the value of the x parameter. + y_title: The title given to the y axis. By default, uses the value of the y parameter. + x_label_angle: The angle (in degrees) of the x axis labels. Positive values are clockwise, and negative values are counter-clockwise. + y_label_angle: The angle (in degrees) of the y axis labels. Positive values are clockwise, and negative values are counter-clockwise. + color_legend_title: The title given to the color legend. By default, uses the value of color parameter. + group_title: The label displayed on top of the subplot columns (or rows if vertical=True). Use an empty string to omit. + 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. + height: The height of the plot in pixels. + width: The width of the plot in pixels. If None, expands to fit. + y_lim: A tuple of list containing the limits for the y-axis, specified as [y_min, y_max]. + caption: The (optional) caption to display below the plot. + interactive: Whether users should be able to interact with the plot by panning or zooming with their mouse or trackpad. + label: The (optional) label to display on the top left corner of the plot. + show_label: Whether the label should be displayed. + 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. + 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. + visible: Whether the plot should be visible. + 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. + 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. + 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. + 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. + sort: Specifies the sorting axis as either "x", "y", "-x" or "-y". If None, no sorting is applied. + show_actions_button: Whether to show the actions button on the top right corner of the plot. + """ + self.x = x + self.y = y + self.color = color + self.vertical = vertical + self.group = group + self.group_title = group_title + self.tooltip = tooltip + self.title = title + self.x_title = x_title + self.y_title = y_title + self.x_label_angle = x_label_angle + self.y_label_angle = y_label_angle + self.color_legend_title = color_legend_title + self.group_title = group_title + self.color_legend_position = color_legend_position + self.y_lim = y_lim + self.caption = caption + self.interactive_chart = interactive + if isinstance(width, str): + width = None + warnings.warn( + "Width should be an integer, not a string. Setting width to None." + ) + if isinstance(height, str): + warnings.warn( + "Height should be an integer, not a string. Setting height to None." + ) + height = None + self.width = width + self.height = height + self.sort = sort + self.show_actions_button = show_actions_button + if label is None and show_label is None: + show_label = False + super().__init__( + value=value, + label=label, + show_label=show_label, + container=container, + scale=scale, + min_width=min_width, + visible=visible, + elem_id=elem_id, + elem_classes=elem_classes, + render=render, + key=key, + every=every, + inputs=inputs, + ) + + def get_block_name(self) -> str: + return "plot" + + @staticmethod + def create_plot( + value: pd.DataFrame, + x: str, + y: str, + color: str | None = None, + vertical: bool = True, + group: str | None = None, + title: str | None = None, + tooltip: list[str] | str | None = None, + x_title: str | None = None, + y_title: str | None = None, + x_label_angle: float | None = None, + y_label_angle: float | None = None, + color_legend_title: str | None = None, + group_title: str | None = None, + color_legend_position: Literal[ + "left", + "right", + "top", + "bottom", + "top-left", + "top-right", + "bottom-left", + "bottom-right", + "none", + ] + | None = None, + height: int | None = None, + width: int | None = None, + y_lim: list[int] | None = None, + interactive: bool | None = True, + sort: Literal["x", "y", "-x", "-y"] | None = None, + ): + """Helper for creating the bar plot.""" + import altair as alt + + interactive = True if interactive is None else interactive + orientation = {"field": group, "title": group_title} if group else {} + + x_title = x_title or x + y_title = y_title or y + + # If horizontal, switch x and y + if not vertical: + y, x = x, y + x = f"sum({x}):Q" + y_title, x_title = x_title, y_title + orientation = {"row": alt.Row(**orientation)} if orientation else {} # type: ignore + x_lim = y_lim + y_lim = None + else: + y = f"sum({y}):Q" + x_lim = None + orientation = {"column": alt.Column(**orientation)} if orientation else {} # type: ignore + + encodings = dict( + x=alt.X( + x, # type: ignore + title=x_title, # type: ignore + scale=AltairPlot.create_scale(x_lim), # type: ignore + axis=alt.Axis(labelAngle=x_label_angle) + if x_label_angle is not None + else alt.Axis(), + sort=sort if vertical and sort is not None else None, + ), + y=alt.Y( + y, # type: ignore + title=y_title, # type: ignore + scale=AltairPlot.create_scale(y_lim), # type: ignore + axis=alt.Axis(labelAngle=y_label_angle) + if y_label_angle is not None + else alt.Axis(), + sort=sort if not vertical and sort is not None else None, + ), + **orientation, + ) + properties = {} + if title: + properties["title"] = title + if height: + properties["height"] = height + if width: + properties["width"] = width + + if color: + color_legend_position = color_legend_position or "bottom" + domain = value[color].unique().tolist() + range_ = list(range(len(domain))) + encodings["color"] = { + "field": color, + "type": "nominal", + "scale": {"domain": domain, "range": range_}, + "legend": AltairPlot.create_legend( + position=color_legend_position, title=color_legend_title + ), + } + + if tooltip: + encodings["tooltip"] = tooltip # type: ignore + + chart = ( + alt.Chart(value) # type: ignore + .mark_bar() # type: ignore + .encode(**encodings) + .properties(background="transparent", **properties) + ) + if interactive: + chart = chart.interactive() + + return chart + + def preprocess(self, payload: AltairPlotData) -> AltairPlotData: + """ + Parameters: + payload: The data to display in a bar plot. + Returns: + (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"). + """ + return payload + + def postprocess(self, value: pd.DataFrame | None) -> AltairPlotData | None: + """ + Parameters: + 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`). + Returns: + 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"). + """ + # if None or update + if value is None: + return value + if self.x is None or self.y is None: + raise ValueError("No value provided for required parameters `x` and `y`.") + chart = self.create_plot( + value=value, + x=self.x, + y=self.y, + color=self.color, + vertical=self.vertical, + group=self.group, + title=self.title, + tooltip=self.tooltip, + x_title=self.x_title, + y_title=self.y_title, + x_label_angle=self.x_label_angle, + y_label_angle=self.y_label_angle, + color_legend_title=self.color_legend_title, + color_legend_position=self.color_legend_position, # type: ignore + group_title=self.group_title, + y_lim=self.y_lim, + interactive=self.interactive_chart, + height=self.height, + width=self.width, + sort=self.sort, # type: ignore + ) + + return AltairPlotData(type="altair", plot=chart.to_json(), chart="bar") + + def example_payload(self) -> Any: + return None + + def example_value(self) -> Any: + import pandas as pd + + return pd.DataFrame({self.x: [1, 2, 3], self.y: [4, 5, 6]}) diff --git a/mantis_evalkit/lib/python3.10/site-packages/gradio/components/browser_state.pyi b/mantis_evalkit/lib/python3.10/site-packages/gradio/components/browser_state.pyi new file mode 100644 index 0000000000000000000000000000000000000000..ad10e83a7e55cee73f3d1d68878ff8d2554c1ef1 --- /dev/null +++ b/mantis_evalkit/lib/python3.10/site-packages/gradio/components/browser_state.pyi @@ -0,0 +1,122 @@ +"""gr.BrowserState() component.""" + +from __future__ import annotations + +import secrets +import string +from typing import Any + +from gradio_client.documentation import document + +from gradio.components.base import Component +from gradio.events import Events + +from gradio.events import Dependency + +@document() +class BrowserState(Component): + EVENTS = [Events.change] + """ + Special component that stores state in the browser's localStorage in an encrypted format. + """ + + def __init__( + self, + default_value: Any = None, + *, + storage_key: str | None = None, + secret: str | None = None, + render: bool = True, + ): + """ + Parameters: + default_value: the default value that will be used if no value is found in localStorage. Should be a json-serializable value. + storage_key: the key to use in localStorage. If None, a random key will be generated. + secret: the secret key to use for encryption. If None, a random key will be generated (recommended). + render: should always be True, is included for consistency with other components. + """ + self.default_value = default_value + self.secret = secret or "".join( + secrets.choice(string.ascii_letters + string.digits) for _ in range(16) + ) + self.storage_key = storage_key or "".join( + secrets.choice(string.ascii_letters + string.digits) for _ in range(16) + ) + super().__init__(render=render) + + def preprocess(self, payload: Any) -> Any: + """ + Parameters: + payload: Value from local storage + Returns: + Passes value through unchanged + """ + return payload + + def postprocess(self, value: Any) -> Any: + """ + Parameters: + value: Value to store in local storage + Returns: + Passes value through unchanged + """ + return value + + def api_info(self) -> dict[str, Any]: + return {"type": {}, "description": "any json-serializable value"} + + def example_payload(self) -> Any: + return "test" + + def example_value(self) -> Any: + return "test" + from typing import Callable, Literal, Sequence, Any, TYPE_CHECKING + from gradio.blocks import Block + if TYPE_CHECKING: + from gradio.components import Timer + + + def change(self, + fn: Callable[..., Any] | None = None, + inputs: Block | Sequence[Block] | set[Block] | None = None, + outputs: Block | Sequence[Block] | None = None, + api_name: str | None | Literal[False] = None, + scroll_to_output: bool = False, + show_progress: Literal["full", "minimal", "hidden"] = "full", + queue: bool | None = None, + batch: bool = False, + max_batch_size: int = 4, + preprocess: bool = True, + postprocess: bool = True, + cancels: dict[str, Any] | list[dict[str, Any]] | None = None, + every: Timer | float | None = None, + trigger_mode: Literal["once", "multiple", "always_last"] | None = None, + js: str | None = None, + concurrency_limit: int | None | Literal["default"] = "default", + concurrency_id: str | None = None, + show_api: bool = True, + + ) -> Dependency: + """ + Parameters: + 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. + inputs: list of gradio.components to use as inputs. If the function takes no inputs, this should be an empty list. + outputs: list of gradio.components to use as outputs. If the function returns no outputs, this should be an empty list. + 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. + scroll_to_output: if True, will scroll to output component on completion + 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 + 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. + 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. + max_batch_size: maximum number of inputs to batch together if this is called from the queue (only relevant if batch=True) + 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). + postprocess: if False, will not run postprocessing of component data before returning 'fn' output to the browser. + 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. + 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. + 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. + 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. + 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). + 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. + 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. + + """ + ... \ No newline at end of file diff --git a/mantis_evalkit/lib/python3.10/site-packages/gradio/components/checkbox.pyi b/mantis_evalkit/lib/python3.10/site-packages/gradio/components/checkbox.pyi new file mode 100644 index 0000000000000000000000000000000000000000..49f627948bf2e610dd4be35a230dbdfd483f51db --- /dev/null +++ b/mantis_evalkit/lib/python3.10/site-packages/gradio/components/checkbox.pyi @@ -0,0 +1,249 @@ +"""gr.Checkbox() component.""" + +from __future__ import annotations + +from collections.abc import Callable, Sequence +from typing import TYPE_CHECKING, Any + +from gradio_client.documentation import document + +from gradio.components.base import Component, FormComponent +from gradio.events import Events + +if TYPE_CHECKING: + from gradio.components import Timer + +from gradio.events import Dependency + +@document() +class Checkbox(FormComponent): + """ + 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 + to display a boolean value. + + Demos: sentence_builder, hello_world_3 + """ + + EVENTS = [Events.change, Events.input, Events.select] + + def __init__( + self, + value: bool | Callable = False, + *, + label: str | None = None, + info: str | None = None, + every: Timer | float | None = None, + inputs: Component | Sequence[Component] | set[Component] | None = None, + show_label: bool | None = None, + container: bool = True, + scale: int | None = None, + min_width: int = 160, + interactive: bool | None = None, + visible: bool = True, + elem_id: str | None = None, + elem_classes: list[str] | str | None = None, + render: bool = True, + key: int | str | None = None, + ): + """ + Parameters: + 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. + 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. + info: additional component description, appears below the label in smaller font. Supports markdown / HTML syntax. + 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. + 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. + show_label: if True, will display label. + container: If True, will place the component in a container - providing some extra padding around the border. + 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. + 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. + 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. + visible: If False, component will be hidden. + 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. + 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. + 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. + 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. + """ + super().__init__( + label=label, + info=info, + every=every, + inputs=inputs, + show_label=show_label, + container=container, + scale=scale, + min_width=min_width, + interactive=interactive, + visible=visible, + elem_id=elem_id, + elem_classes=elem_classes, + render=render, + key=key, + value=value, + ) + + def api_info(self) -> dict[str, Any]: + return {"type": "boolean"} + + def example_payload(self) -> bool: + return True + + def example_value(self) -> bool: + return True + + def preprocess(self, payload: bool | None) -> bool | None: + """ + Parameters: + payload: the status of the checkbox + Returns: + Passes the status of the checkbox as a `bool`. + """ + return payload + + def postprocess(self, value: bool | None) -> bool | None: + """ + Parameters: + value: Expects a `bool` value that is set as the status of the checkbox + Returns: + The same `bool` value that is set as the status of the checkbox + """ + return bool(value) + from typing import Callable, Literal, Sequence, Any, TYPE_CHECKING + from gradio.blocks import Block + if TYPE_CHECKING: + from gradio.components import Timer + + + def change(self, + fn: Callable[..., Any] | None = None, + inputs: Block | Sequence[Block] | set[Block] | None = None, + outputs: Block | Sequence[Block] | None = None, + api_name: str | None | Literal[False] = None, + scroll_to_output: bool = False, + show_progress: Literal["full", "minimal", "hidden"] = "full", + queue: bool | None = None, + batch: bool = False, + max_batch_size: int = 4, + preprocess: bool = True, + postprocess: bool = True, + cancels: dict[str, Any] | list[dict[str, Any]] | None = None, + every: Timer | float | None = None, + trigger_mode: Literal["once", "multiple", "always_last"] | None = None, + js: str | None = None, + concurrency_limit: int | None | Literal["default"] = "default", + concurrency_id: str | None = None, + show_api: bool = True, + + ) -> Dependency: + """ + Parameters: + 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. + inputs: list of gradio.components to use as inputs. If the function takes no inputs, this should be an empty list. + outputs: list of gradio.components to use as outputs. If the function returns no outputs, this should be an empty list. + 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. + scroll_to_output: if True, will scroll to output component on completion + 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 + 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. + 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. + max_batch_size: maximum number of inputs to batch together if this is called from the queue (only relevant if batch=True) + 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). + postprocess: if False, will not run postprocessing of component data before returning 'fn' output to the browser. + 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. + 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. + 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. + 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. + 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). + 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. + 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. + + """ + ... + + def input(self, + fn: Callable[..., Any] | None = None, + inputs: Block | Sequence[Block] | set[Block] | None = None, + outputs: Block | Sequence[Block] | None = None, + api_name: str | None | Literal[False] = None, + scroll_to_output: bool = False, + show_progress: Literal["full", "minimal", "hidden"] = "full", + queue: bool | None = None, + batch: bool = False, + max_batch_size: int = 4, + preprocess: bool = True, + postprocess: bool = True, + cancels: dict[str, Any] | list[dict[str, Any]] | None = None, + every: Timer | float | None = None, + trigger_mode: Literal["once", "multiple", "always_last"] | None = None, + js: str | None = None, + concurrency_limit: int | None | Literal["default"] = "default", + concurrency_id: str | None = None, + show_api: bool = True, + + ) -> Dependency: + """ + Parameters: + 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. + inputs: list of gradio.components to use as inputs. If the function takes no inputs, this should be an empty list. + outputs: list of gradio.components to use as outputs. If the function returns no outputs, this should be an empty list. + 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. + scroll_to_output: if True, will scroll to output component on completion + 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 + 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. + 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. + max_batch_size: maximum number of inputs to batch together if this is called from the queue (only relevant if batch=True) + 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). + postprocess: if False, will not run postprocessing of component data before returning 'fn' output to the browser. + 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. + 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. + 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. + 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. + 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). + 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. + 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. + + """ + ... + + def select(self, + fn: Callable[..., Any] | None = None, + inputs: Block | Sequence[Block] | set[Block] | None = None, + outputs: Block | Sequence[Block] | None = None, + api_name: str | None | Literal[False] = None, + scroll_to_output: bool = False, + show_progress: Literal["full", "minimal", "hidden"] = "full", + queue: bool | None = None, + batch: bool = False, + max_batch_size: int = 4, + preprocess: bool = True, + postprocess: bool = True, + cancels: dict[str, Any] | list[dict[str, Any]] | None = None, + every: Timer | float | None = None, + trigger_mode: Literal["once", "multiple", "always_last"] | None = None, + js: str | None = None, + concurrency_limit: int | None | Literal["default"] = "default", + concurrency_id: str | None = None, + show_api: bool = True, + + ) -> Dependency: + """ + Parameters: + 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. + inputs: list of gradio.components to use as inputs. If the function takes no inputs, this should be an empty list. + outputs: list of gradio.components to use as outputs. If the function returns no outputs, this should be an empty list. + 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. + scroll_to_output: if True, will scroll to output component on completion + 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 + 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. + 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. + max_batch_size: maximum number of inputs to batch together if this is called from the queue (only relevant if batch=True) + 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). + postprocess: if False, will not run postprocessing of component data before returning 'fn' output to the browser. + 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. + 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. + 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. + 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. + 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). + 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. + 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. + + """ + ... \ No newline at end of file diff --git a/mantis_evalkit/lib/python3.10/site-packages/gradio/components/clear_button.py b/mantis_evalkit/lib/python3.10/site-packages/gradio/components/clear_button.py new file mode 100644 index 0000000000000000000000000000000000000000..6056990e87ba033f7e3bd68a48458119df1cc5b9 --- /dev/null +++ b/mantis_evalkit/lib/python3.10/site-packages/gradio/components/clear_button.py @@ -0,0 +1,143 @@ +"""Predefined buttons with bound events that can be included in a gr.Blocks for convenience.""" + +from __future__ import annotations + +import copy +import json +from collections.abc import Sequence +from pathlib import Path +from typing import TYPE_CHECKING, Any, Literal + +from gradio_client.documentation import document + +from gradio.components import Button, Component +from gradio.context import get_blocks_context +from gradio.data_classes import GradioModel, GradioRootModel +from gradio.utils import resolve_singleton + +if TYPE_CHECKING: + from gradio.components import Timer + + +@document("add") +class ClearButton(Button): + """ + 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. + Preprocessing: passes the button value as a {str} into the function + Postprocessing: expects a {str} to be returned from a function, which is set as the label of the button + """ + + is_template = True + + def __init__( + self, + components: None | Sequence[Component] | Component = None, + *, + value: str = "Clear", + every: Timer | float | None = None, + inputs: Component | Sequence[Component] | set[Component] | None = None, + variant: Literal["primary", "secondary", "stop"] = "secondary", + size: Literal["sm", "md", "lg"] = "lg", + icon: str | Path | None = None, + link: str | None = None, + visible: bool = True, + interactive: bool = True, + elem_id: str | None = None, + elem_classes: list[str] | str | None = None, + render: bool = True, + key: int | str | None = None, + scale: int | None = None, + min_width: int | None = None, + api_name: str | None | Literal["False"] = None, + show_api: bool = False, + ): + super().__init__( + value, + every=every, + inputs=inputs, + variant=variant, + size=size, + icon=icon, + link=link, + visible=visible, + interactive=interactive, + elem_id=elem_id, + elem_classes=elem_classes, + render=render, + key=key, + scale=scale, + min_width=min_width, + ) + self.api_name = api_name + self.show_api = show_api + + if get_blocks_context(): + self.add(components) + + def add(self, components: None | Component | Sequence[Component]) -> ClearButton: + """ + Adds a component or list of components to the list of components that will be cleared when the button is clicked. + """ + from gradio.components import State # Avoid circular import + + if not components: + # This needs to be here because when the ClearButton is created in an gr.Interface, we don't + # want to create dependencies for it before we have created the dependencies for the submit function. + # We generally assume that the submit function dependency is the first thing created in an gr.Interface. + return self + + if isinstance(components, Component): + components = [components] + none_values = [] + state_components = [] + initial_states = [] + for component in components: + if isinstance(component, State): + state_components.append(component) + initial_states.append(copy.deepcopy(component.value)) + none = component.postprocess(None) + if isinstance(none, (GradioModel, GradioRootModel)): + none = none.model_dump() + none_values.append(none) + clear_values = json.dumps(none_values) + self.click( + None, + [], + components, + js=f"() => {clear_values}", + api_name=self.api_name, + show_api=self.show_api, + ) + if state_components: + self.click( + lambda: resolve_singleton(initial_states), + None, + state_components, + api_name=self.api_name, + show_api=self.show_api, + ) + return self + + def preprocess(self, payload: str | None) -> str | None: + """ + Parameters: + payload: string corresponding to the button label + Returns: + (Rarely used) the `str` corresponding to the button label when the button is clicked + """ + return payload + + def postprocess(self, value: str | None) -> str | None: + """ + Parameters: + value: string corresponding to the button label + Returns: + Expects a `str` value that is set as the button label + """ + return value + + def example_payload(self) -> Any: + return "Clear" + + def example_value(self) -> Any: + return "Clear" diff --git a/mantis_evalkit/lib/python3.10/site-packages/gradio/components/dataframe.py b/mantis_evalkit/lib/python3.10/site-packages/gradio/components/dataframe.py new file mode 100644 index 0000000000000000000000000000000000000000..bca45d4a79669071b3db208d6c341b290b5f58a1 --- /dev/null +++ b/mantis_evalkit/lib/python3.10/site-packages/gradio/components/dataframe.py @@ -0,0 +1,390 @@ +"""gr.Dataframe() component""" + +from __future__ import annotations + +import warnings +from collections.abc import Callable, Sequence +from typing import ( + TYPE_CHECKING, + Any, + Literal, + Optional, + Union, +) + +import numpy as np +import semantic_version +from gradio_client.documentation import document + +from gradio.components.base import Component +from gradio.data_classes import GradioModel +from gradio.events import Events + +if TYPE_CHECKING: + import pandas as pd + import polars as pl # type: ignore + from pandas.io.formats.style import Styler + + from gradio.components import Timer + + +def _is_polars_available(): + import importlib.util + + spec = importlib.util.find_spec("polars") + return bool(spec) + + +def _import_polars(): + import polars as pl # type: ignore + + return pl + + +class DataframeData(GradioModel): + headers: list[str] + data: Union[list[list[Any]], list[tuple[Any, ...]]] + metadata: Optional[dict[str, Optional[list[Any]]]] = None + + +@document() +class Dataframe(Component): + """ + 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. + Demos: filter_records, matrix_transpose, tax_calculator, sort_records + """ + + EVENTS = [Events.change, Events.input, Events.select] + + data_model = DataframeData + + def __init__( + self, + value: pd.DataFrame + | Styler + | np.ndarray + | pl.DataFrame + | list + | list[list] + | dict + | str + | Callable + | None = None, + *, + headers: list[str] | None = None, + row_count: int | tuple[int, str] = (1, "dynamic"), + col_count: int | tuple[int, str] | None = None, + datatype: str | list[str] = "str", + type: Literal["pandas", "numpy", "array", "polars"] = "pandas", + latex_delimiters: list[dict[str, str | bool]] | None = None, + label: str | None = None, + show_label: bool | None = None, + every: Timer | float | None = None, + inputs: Component | Sequence[Component] | set[Component] | None = None, + max_height: int | str = 500, + scale: int | None = None, + min_width: int = 160, + interactive: bool | None = None, + visible: bool = True, + elem_id: str | None = None, + elem_classes: list[str] | str | None = None, + render: bool = True, + key: int | str | None = None, + wrap: bool = False, + line_breaks: bool = True, + column_widths: list[str | int] | None = None, + ): + """ + Parameters: + 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. + headers: List of str header names. If None, no headers are shown. + 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' + 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' + 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". + 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. + 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. + 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". + 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. + show_label: if True, will display label. + 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. + 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. + 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. + 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. + 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. + 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. + visible: If False, component will be hidden. + 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. + 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. + 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. + 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. + 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. + 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." + 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. + """ + self.wrap = wrap + self.row_count = self.__process_counts(row_count) + self.col_count = self.__process_counts( + col_count, len(headers) if headers else 3 + ) + self.__validate_headers(headers, self.col_count[0]) + + self.headers = ( + headers + if headers is not None + else [str(i) for i in (range(1, self.col_count[0] + 1))] + ) + self.datatype = datatype + valid_types = ["pandas", "numpy", "array", "polars"] + if type not in valid_types: + raise ValueError( + f"Invalid value for parameter `type`: {type}. Please choose from one of: {valid_types}" + ) + if type == "polars" and not _is_polars_available(): + raise ImportError( + "Polars is not installed. Please install using `pip install polars`." + ) + self.type = type + values = { + "str": "", + "number": 0, + "bool": False, + "date": "01/01/1970", + "markdown": "", + "html": "", + } + column_dtypes = ( + [datatype] * self.col_count[0] if isinstance(datatype, str) else datatype + ) + self.empty_input = { + "headers": self.headers, + "data": [ + [values[c] for c in column_dtypes] for _ in range(self.row_count[0]) + ], + "metadata": None, + } + + if latex_delimiters is None: + latex_delimiters = [{"left": "$$", "right": "$$", "display": True}] + self.latex_delimiters = latex_delimiters + self.max_height = max_height + self.line_breaks = line_breaks + self.column_widths = [ + w if isinstance(w, str) else f"{w}px" for w in (column_widths or []) + ] + super().__init__( + label=label, + every=every, + inputs=inputs, + show_label=show_label, + scale=scale, + min_width=min_width, + interactive=interactive, + visible=visible, + elem_id=elem_id, + elem_classes=elem_classes, + render=render, + key=key, + value=value, + ) + + def preprocess( + self, payload: DataframeData + ) -> pd.DataFrame | np.ndarray | pl.DataFrame | list[list]: + """ + Parameters: + 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. + Returns: + Passes the uploaded spreadsheet data as a `pandas.DataFrame`, `numpy.array`, `polars.DataFrame`, or native 2D Python `list[list]` depending on `type` + """ + import pandas as pd + + if self.type == "pandas": + if payload.headers is not None: + return pd.DataFrame( + [] if payload.data == [[]] else payload.data, + columns=payload.headers, # type: ignore + ) + else: + return pd.DataFrame(payload.data) + if self.type == "polars": + polars = _import_polars() + if payload.headers is not None: + return polars.DataFrame( + [] if payload.data == [[]] else payload.data, schema=payload.headers + ) + else: + return polars.DataFrame(payload.data) + if self.type == "numpy": + return np.array(payload.data) + elif self.type == "array": + return payload.data # type: ignore + else: + raise ValueError( + "Unknown type: " + + str(self.type) + + ". Please choose from: 'pandas', 'numpy', 'array', 'polars'." + ) + + def postprocess( + self, + value: pd.DataFrame + | Styler + | np.ndarray + | pl.DataFrame + | list + | list[list] + | dict + | str + | None, + ) -> DataframeData: + """ + Parameters: + 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. + Returns: + the uploaded spreadsheet data as an object with `headers` and `data` attributes + """ + import pandas as pd + from pandas.io.formats.style import Styler + + if value is None: + return self.postprocess(self.empty_input) + if isinstance(value, dict): + if len(value) == 0: + return DataframeData(headers=self.headers, data=[[]]) + return DataframeData( + headers=value.get("headers", []), data=value.get("data", [[]]) + ) + if isinstance(value, (str, pd.DataFrame)): + if isinstance(value, str): + value = pd.read_csv(value) # type: ignore + if len(value) == 0: + return DataframeData( + headers=list(value.columns), # type: ignore + data=[[]], # type: ignore + ) + return DataframeData( + headers=list(value.columns), # type: ignore + data=value.to_dict(orient="split")["data"], # type: ignore + ) + elif isinstance(value, Styler): + if semantic_version.Version(pd.__version__) < semantic_version.Version( + "1.5.0" + ): + raise ValueError( + "Styler objects are only supported in pandas version 1.5.0 or higher. Please try: `pip install --upgrade pandas` to use this feature." + ) + if self.interactive: + warnings.warn( + "Cannot display Styler object in interactive mode. Will display as a regular pandas dataframe instead." + ) + df: pd.DataFrame = value.data # type: ignore + if len(df) == 0: + return DataframeData( + headers=list(df.columns), + data=[[]], + metadata=self.__extract_metadata(value), # type: ignore + ) + return DataframeData( + headers=list(df.columns), + data=df.to_dict(orient="split")["data"], # type: ignore + metadata=self.__extract_metadata(value), # type: ignore + ) + elif _is_polars_available() and isinstance(value, _import_polars().DataFrame): + if len(value) == 0: + return DataframeData(headers=list(value.to_dict().keys()), data=[[]]) # type: ignore + df_dict = value.to_dict() # type: ignore + headers = list(df_dict.keys()) + data = list(zip(*df_dict.values())) + return DataframeData(headers=headers, data=data) + elif isinstance(value, (np.ndarray, list)): + if len(value) == 0: + return DataframeData(headers=self.headers, data=[[]]) + if isinstance(value, np.ndarray): + value = value.tolist() + if not isinstance(value, list): + raise ValueError("output cannot be converted to list") + + _headers = self.headers + if len(self.headers) < len(value[0]): + _headers: list[str] = [ + *self.headers, + *[str(i) for i in range(len(self.headers) + 1, len(value[0]) + 1)], + ] + elif len(self.headers) > len(value[0]): + _headers = self.headers[: len(value[0])] + + return DataframeData(headers=_headers, data=value) + else: + raise ValueError("Cannot process value as a Dataframe") + + @staticmethod + def __get_cell_style(cell_id: str, cell_styles: list[dict]) -> str: + styles_for_cell = [] + for style in cell_styles: + if cell_id in style.get("selectors", []): + styles_for_cell.extend(style.get("props", [])) + styles_str = "; ".join([f"{prop}: {value}" for prop, value in styles_for_cell]) + return styles_str + + @staticmethod + def __extract_metadata(df: Styler) -> dict[str, list[list]]: + metadata = {"display_value": [], "styling": []} + style_data = df._compute()._translate(None, None) # type: ignore + cell_styles = style_data.get("cellstyle", []) + for i in range(len(style_data["body"])): + metadata["display_value"].append([]) + metadata["styling"].append([]) + for j in range(len(style_data["body"][i])): + cell_type = style_data["body"][i][j]["type"] + if cell_type != "td": + continue + display_value = style_data["body"][i][j]["display_value"] + cell_id = style_data["body"][i][j]["id"] + styles_str = Dataframe.__get_cell_style(cell_id, cell_styles) + metadata["display_value"][i].append(display_value) + metadata["styling"][i].append(styles_str) + return metadata + + @staticmethod + def __process_counts(count, default=3) -> tuple[int, str]: + if count is None: + return (default, "dynamic") + if isinstance(count, (int, float)): + return (int(count), "dynamic") + else: + return count + + @staticmethod + def __validate_headers(headers: list[str] | None, col_count: int): + if headers is not None and len(headers) != col_count: + raise ValueError( + f"The length of the headers list must be equal to the col_count int.\n" + f"The column count is set to {col_count} but `headers` has {len(headers)} items. " + f"Check the values passed to `col_count` and `headers`." + ) + + def process_example( + self, + value: pd.DataFrame + | Styler + | np.ndarray + | pl.DataFrame + | list + | list[list] + | dict + | str + | None, + ): + import pandas as pd + + if value is None: + return "" + value_df_data = self.postprocess(value) + value_df = pd.DataFrame(value_df_data.data, columns=value_df_data.headers) # type: ignore + return value_df.head(n=5).to_dict(orient="split")["data"] + + def example_payload(self) -> Any: + return {"headers": ["a", "b"], "data": [["foo", "bar"]]} + + def example_value(self) -> Any: + return {"headers": ["a", "b"], "data": [["foo", "bar"]]} diff --git a/mantis_evalkit/lib/python3.10/site-packages/gradio/components/dataframe.pyi b/mantis_evalkit/lib/python3.10/site-packages/gradio/components/dataframe.pyi new file mode 100644 index 0000000000000000000000000000000000000000..6dc03e5175c63e2faf936d32af76bf59b067ef5d --- /dev/null +++ b/mantis_evalkit/lib/python3.10/site-packages/gradio/components/dataframe.pyi @@ -0,0 +1,531 @@ +"""gr.Dataframe() component""" + +from __future__ import annotations + +import warnings +from collections.abc import Callable, Sequence +from typing import ( + TYPE_CHECKING, + Any, + Literal, + Optional, + Union, +) + +import numpy as np +import semantic_version +from gradio_client.documentation import document + +from gradio.components.base import Component +from gradio.data_classes import GradioModel +from gradio.events import Events + +if TYPE_CHECKING: + import pandas as pd + import polars as pl # type: ignore + from pandas.io.formats.style import Styler + + from gradio.components import Timer + + +def _is_polars_available(): + import importlib.util + + spec = importlib.util.find_spec("polars") + return bool(spec) + + +def _import_polars(): + import polars as pl # type: ignore + + return pl + + +class DataframeData(GradioModel): + headers: list[str] + data: Union[list[list[Any]], list[tuple[Any, ...]]] + metadata: Optional[dict[str, Optional[list[Any]]]] = None + +from gradio.events import Dependency + +@document() +class Dataframe(Component): + """ + 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. + Demos: filter_records, matrix_transpose, tax_calculator, sort_records + """ + + EVENTS = [Events.change, Events.input, Events.select] + + data_model = DataframeData + + def __init__( + self, + value: pd.DataFrame + | Styler + | np.ndarray + | pl.DataFrame + | list + | list[list] + | dict + | str + | Callable + | None = None, + *, + headers: list[str] | None = None, + row_count: int | tuple[int, str] = (1, "dynamic"), + col_count: int | tuple[int, str] | None = None, + datatype: str | list[str] = "str", + type: Literal["pandas", "numpy", "array", "polars"] = "pandas", + latex_delimiters: list[dict[str, str | bool]] | None = None, + label: str | None = None, + show_label: bool | None = None, + every: Timer | float | None = None, + inputs: Component | Sequence[Component] | set[Component] | None = None, + max_height: int | str = 500, + scale: int | None = None, + min_width: int = 160, + interactive: bool | None = None, + visible: bool = True, + elem_id: str | None = None, + elem_classes: list[str] | str | None = None, + render: bool = True, + key: int | str | None = None, + wrap: bool = False, + line_breaks: bool = True, + column_widths: list[str | int] | None = None, + ): + """ + Parameters: + 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. + headers: List of str header names. If None, no headers are shown. + 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' + 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' + 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". + 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. + 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. + 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". + 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. + show_label: if True, will display label. + 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. + 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. + 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. + 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. + 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. + 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. + visible: If False, component will be hidden. + 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. + 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. + 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. + 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. + 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. + 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." + 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. + """ + self.wrap = wrap + self.row_count = self.__process_counts(row_count) + self.col_count = self.__process_counts( + col_count, len(headers) if headers else 3 + ) + self.__validate_headers(headers, self.col_count[0]) + + self.headers = ( + headers + if headers is not None + else [str(i) for i in (range(1, self.col_count[0] + 1))] + ) + self.datatype = datatype + valid_types = ["pandas", "numpy", "array", "polars"] + if type not in valid_types: + raise ValueError( + f"Invalid value for parameter `type`: {type}. Please choose from one of: {valid_types}" + ) + if type == "polars" and not _is_polars_available(): + raise ImportError( + "Polars is not installed. Please install using `pip install polars`." + ) + self.type = type + values = { + "str": "", + "number": 0, + "bool": False, + "date": "01/01/1970", + "markdown": "", + "html": "", + } + column_dtypes = ( + [datatype] * self.col_count[0] if isinstance(datatype, str) else datatype + ) + self.empty_input = { + "headers": self.headers, + "data": [ + [values[c] for c in column_dtypes] for _ in range(self.row_count[0]) + ], + "metadata": None, + } + + if latex_delimiters is None: + latex_delimiters = [{"left": "$$", "right": "$$", "display": True}] + self.latex_delimiters = latex_delimiters + self.max_height = max_height + self.line_breaks = line_breaks + self.column_widths = [ + w if isinstance(w, str) else f"{w}px" for w in (column_widths or []) + ] + super().__init__( + label=label, + every=every, + inputs=inputs, + show_label=show_label, + scale=scale, + min_width=min_width, + interactive=interactive, + visible=visible, + elem_id=elem_id, + elem_classes=elem_classes, + render=render, + key=key, + value=value, + ) + + def preprocess( + self, payload: DataframeData + ) -> pd.DataFrame | np.ndarray | pl.DataFrame | list[list]: + """ + Parameters: + 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. + Returns: + Passes the uploaded spreadsheet data as a `pandas.DataFrame`, `numpy.array`, `polars.DataFrame`, or native 2D Python `list[list]` depending on `type` + """ + import pandas as pd + + if self.type == "pandas": + if payload.headers is not None: + return pd.DataFrame( + [] if payload.data == [[]] else payload.data, + columns=payload.headers, # type: ignore + ) + else: + return pd.DataFrame(payload.data) + if self.type == "polars": + polars = _import_polars() + if payload.headers is not None: + return polars.DataFrame( + [] if payload.data == [[]] else payload.data, schema=payload.headers + ) + else: + return polars.DataFrame(payload.data) + if self.type == "numpy": + return np.array(payload.data) + elif self.type == "array": + return payload.data # type: ignore + else: + raise ValueError( + "Unknown type: " + + str(self.type) + + ". Please choose from: 'pandas', 'numpy', 'array', 'polars'." + ) + + def postprocess( + self, + value: pd.DataFrame + | Styler + | np.ndarray + | pl.DataFrame + | list + | list[list] + | dict + | str + | None, + ) -> DataframeData: + """ + Parameters: + 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. + Returns: + the uploaded spreadsheet data as an object with `headers` and `data` attributes + """ + import pandas as pd + from pandas.io.formats.style import Styler + + if value is None: + return self.postprocess(self.empty_input) + if isinstance(value, dict): + if len(value) == 0: + return DataframeData(headers=self.headers, data=[[]]) + return DataframeData( + headers=value.get("headers", []), data=value.get("data", [[]]) + ) + if isinstance(value, (str, pd.DataFrame)): + if isinstance(value, str): + value = pd.read_csv(value) # type: ignore + if len(value) == 0: + return DataframeData( + headers=list(value.columns), # type: ignore + data=[[]], # type: ignore + ) + return DataframeData( + headers=list(value.columns), # type: ignore + data=value.to_dict(orient="split")["data"], # type: ignore + ) + elif isinstance(value, Styler): + if semantic_version.Version(pd.__version__) < semantic_version.Version( + "1.5.0" + ): + raise ValueError( + "Styler objects are only supported in pandas version 1.5.0 or higher. Please try: `pip install --upgrade pandas` to use this feature." + ) + if self.interactive: + warnings.warn( + "Cannot display Styler object in interactive mode. Will display as a regular pandas dataframe instead." + ) + df: pd.DataFrame = value.data # type: ignore + if len(df) == 0: + return DataframeData( + headers=list(df.columns), + data=[[]], + metadata=self.__extract_metadata(value), # type: ignore + ) + return DataframeData( + headers=list(df.columns), + data=df.to_dict(orient="split")["data"], # type: ignore + metadata=self.__extract_metadata(value), # type: ignore + ) + elif _is_polars_available() and isinstance(value, _import_polars().DataFrame): + if len(value) == 0: + return DataframeData(headers=list(value.to_dict().keys()), data=[[]]) # type: ignore + df_dict = value.to_dict() # type: ignore + headers = list(df_dict.keys()) + data = list(zip(*df_dict.values())) + return DataframeData(headers=headers, data=data) + elif isinstance(value, (np.ndarray, list)): + if len(value) == 0: + return DataframeData(headers=self.headers, data=[[]]) + if isinstance(value, np.ndarray): + value = value.tolist() + if not isinstance(value, list): + raise ValueError("output cannot be converted to list") + + _headers = self.headers + if len(self.headers) < len(value[0]): + _headers: list[str] = [ + *self.headers, + *[str(i) for i in range(len(self.headers) + 1, len(value[0]) + 1)], + ] + elif len(self.headers) > len(value[0]): + _headers = self.headers[: len(value[0])] + + return DataframeData(headers=_headers, data=value) + else: + raise ValueError("Cannot process value as a Dataframe") + + @staticmethod + def __get_cell_style(cell_id: str, cell_styles: list[dict]) -> str: + styles_for_cell = [] + for style in cell_styles: + if cell_id in style.get("selectors", []): + styles_for_cell.extend(style.get("props", [])) + styles_str = "; ".join([f"{prop}: {value}" for prop, value in styles_for_cell]) + return styles_str + + @staticmethod + def __extract_metadata(df: Styler) -> dict[str, list[list]]: + metadata = {"display_value": [], "styling": []} + style_data = df._compute()._translate(None, None) # type: ignore + cell_styles = style_data.get("cellstyle", []) + for i in range(len(style_data["body"])): + metadata["display_value"].append([]) + metadata["styling"].append([]) + for j in range(len(style_data["body"][i])): + cell_type = style_data["body"][i][j]["type"] + if cell_type != "td": + continue + display_value = style_data["body"][i][j]["display_value"] + cell_id = style_data["body"][i][j]["id"] + styles_str = Dataframe.__get_cell_style(cell_id, cell_styles) + metadata["display_value"][i].append(display_value) + metadata["styling"][i].append(styles_str) + return metadata + + @staticmethod + def __process_counts(count, default=3) -> tuple[int, str]: + if count is None: + return (default, "dynamic") + if isinstance(count, (int, float)): + return (int(count), "dynamic") + else: + return count + + @staticmethod + def __validate_headers(headers: list[str] | None, col_count: int): + if headers is not None and len(headers) != col_count: + raise ValueError( + f"The length of the headers list must be equal to the col_count int.\n" + f"The column count is set to {col_count} but `headers` has {len(headers)} items. " + f"Check the values passed to `col_count` and `headers`." + ) + + def process_example( + self, + value: pd.DataFrame + | Styler + | np.ndarray + | pl.DataFrame + | list + | list[list] + | dict + | str + | None, + ): + import pandas as pd + + if value is None: + return "" + value_df_data = self.postprocess(value) + value_df = pd.DataFrame(value_df_data.data, columns=value_df_data.headers) # type: ignore + return value_df.head(n=5).to_dict(orient="split")["data"] + + def example_payload(self) -> Any: + return {"headers": ["a", "b"], "data": [["foo", "bar"]]} + + def example_value(self) -> Any: + return {"headers": ["a", "b"], "data": [["foo", "bar"]]} + from typing import Callable, Literal, Sequence, Any, TYPE_CHECKING + from gradio.blocks import Block + if TYPE_CHECKING: + from gradio.components import Timer + + + def change(self, + fn: Callable[..., Any] | None = None, + inputs: Block | Sequence[Block] | set[Block] | None = None, + outputs: Block | Sequence[Block] | None = None, + api_name: str | None | Literal[False] = None, + scroll_to_output: bool = False, + show_progress: Literal["full", "minimal", "hidden"] = "full", + queue: bool | None = None, + batch: bool = False, + max_batch_size: int = 4, + preprocess: bool = True, + postprocess: bool = True, + cancels: dict[str, Any] | list[dict[str, Any]] | None = None, + every: Timer | float | None = None, + trigger_mode: Literal["once", "multiple", "always_last"] | None = None, + js: str | None = None, + concurrency_limit: int | None | Literal["default"] = "default", + concurrency_id: str | None = None, + show_api: bool = True, + + ) -> Dependency: + """ + Parameters: + 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. + inputs: list of gradio.components to use as inputs. If the function takes no inputs, this should be an empty list. + outputs: list of gradio.components to use as outputs. If the function returns no outputs, this should be an empty list. + 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. + scroll_to_output: if True, will scroll to output component on completion + 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 + 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. + 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. + max_batch_size: maximum number of inputs to batch together if this is called from the queue (only relevant if batch=True) + 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). + postprocess: if False, will not run postprocessing of component data before returning 'fn' output to the browser. + 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. + 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. + 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. + 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. + 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). + 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. + 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. + + """ + ... + + def input(self, + fn: Callable[..., Any] | None = None, + inputs: Block | Sequence[Block] | set[Block] | None = None, + outputs: Block | Sequence[Block] | None = None, + api_name: str | None | Literal[False] = None, + scroll_to_output: bool = False, + show_progress: Literal["full", "minimal", "hidden"] = "full", + queue: bool | None = None, + batch: bool = False, + max_batch_size: int = 4, + preprocess: bool = True, + postprocess: bool = True, + cancels: dict[str, Any] | list[dict[str, Any]] | None = None, + every: Timer | float | None = None, + trigger_mode: Literal["once", "multiple", "always_last"] | None = None, + js: str | None = None, + concurrency_limit: int | None | Literal["default"] = "default", + concurrency_id: str | None = None, + show_api: bool = True, + + ) -> Dependency: + """ + Parameters: + 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. + inputs: list of gradio.components to use as inputs. If the function takes no inputs, this should be an empty list. + outputs: list of gradio.components to use as outputs. If the function returns no outputs, this should be an empty list. + 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. + scroll_to_output: if True, will scroll to output component on completion + 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 + 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. + 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. + max_batch_size: maximum number of inputs to batch together if this is called from the queue (only relevant if batch=True) + 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). + postprocess: if False, will not run postprocessing of component data before returning 'fn' output to the browser. + 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. + 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. + 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. + 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. + 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). + 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. + 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. + + """ + ... + + def select(self, + fn: Callable[..., Any] | None = None, + inputs: Block | Sequence[Block] | set[Block] | None = None, + outputs: Block | Sequence[Block] | None = None, + api_name: str | None | Literal[False] = None, + scroll_to_output: bool = False, + show_progress: Literal["full", "minimal", "hidden"] = "full", + queue: bool | None = None, + batch: bool = False, + max_batch_size: int = 4, + preprocess: bool = True, + postprocess: bool = True, + cancels: dict[str, Any] | list[dict[str, Any]] | None = None, + every: Timer | float | None = None, + trigger_mode: Literal["once", "multiple", "always_last"] | None = None, + js: str | None = None, + concurrency_limit: int | None | Literal["default"] = "default", + concurrency_id: str | None = None, + show_api: bool = True, + + ) -> Dependency: + """ + Parameters: + 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. + inputs: list of gradio.components to use as inputs. If the function takes no inputs, this should be an empty list. + outputs: list of gradio.components to use as outputs. If the function returns no outputs, this should be an empty list. + 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. + scroll_to_output: if True, will scroll to output component on completion + 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 + 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. + 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. + max_batch_size: maximum number of inputs to batch together if this is called from the queue (only relevant if batch=True) + 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). + postprocess: if False, will not run postprocessing of component data before returning 'fn' output to the browser. + 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. + 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. + 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. + 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. + 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). + 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. + 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. + + """ + ... \ No newline at end of file diff --git a/mantis_evalkit/lib/python3.10/site-packages/gradio/components/datetime.pyi b/mantis_evalkit/lib/python3.10/site-packages/gradio/components/datetime.pyi new file mode 100644 index 0000000000000000000000000000000000000000..17472ca70b4644bd6e3fd0ba240b1df872d03ebf --- /dev/null +++ b/mantis_evalkit/lib/python3.10/site-packages/gradio/components/datetime.pyi @@ -0,0 +1,253 @@ +"""gr.DateTime() component.""" + +from __future__ import annotations + +import re +from datetime import datetime, timedelta +from typing import Any, Literal + +import pytz +from gradio_client.documentation import document + +from gradio.components.base import FormComponent +from gradio.events import Events + +from gradio.events import Dependency + +@document() +class DateTime(FormComponent): + """ + Component to select a date and (optionally) a time. + """ + + EVENTS = [ + Events.change, + Events.submit, + ] + + def __init__( + self, + value: float | str | datetime | None = None, + *, + include_time: bool = True, + type: Literal["timestamp", "datetime", "string"] = "timestamp", + timezone: str | None = None, + label: str | None = None, + show_label: bool | None = None, + info: str | None = None, + every: float | None = None, + scale: int | None = None, + min_width: int = 160, + visible: bool = True, + interactive: bool | None = None, + elem_id: str | None = None, + elem_classes: list[str] | str | None = None, + render: bool = True, + key: int | str | None = None, + ): + """ + Parameters: + value: default value for datetime. + 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. + info: additional component description, appears below the label in smaller font. Supports markdown / HTML syntax. + show_label: if True, will display label. + include_time: If True, the component will include time selection. If False, only date selection will be available. + 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. + timezone: The timezone to use for timestamps, such as "US/Pacific" or "Europe/Paris". If None, the timezone will be the local timezone. + 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. + 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. + 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. + visible: If False, component will be hidden. + 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. + 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. + 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. + """ + super().__init__( + every=every, + scale=scale, + min_width=min_width, + visible=visible, + label=label, + show_label=show_label, + info=info, + elem_id=elem_id, + elem_classes=elem_classes, + render=render, + key=key, + value=value, + ) + self.type = type + self.include_time = include_time + self.interactive = interactive + self.time_format = "%Y-%m-%d %H:%M:%S" if include_time else "%Y-%m-%d" + self.timezone = timezone + + def preprocess(self, payload: str | None) -> str | float | datetime | None: + """ + Parameters: + payload: the text entered in the textarea. + Returns: + Passes text value as a {str} into the function. + """ + if payload is None or payload == "": + return None + if self.type == "string" and "now" not in payload: + return payload + datetime = self.get_datetime_from_str(payload) + if self.type == "string": + return datetime.strftime(self.time_format) + if self.type == "datetime": + return datetime + elif self.type == "timestamp": + return datetime.timestamp() + + def postprocess(self, value: float | datetime | str | None) -> str | None: + """ + Parameters: + value: Expects a tuple pair of datetimes. + Returns: + A tuple pair of timestamps. + """ + if value is None: + return None + + if isinstance(value, datetime): + return datetime.strftime(value, self.time_format) + elif isinstance(value, str): + return value + else: + return datetime.fromtimestamp( + value, tz=pytz.timezone(self.timezone) if self.timezone else None + ).strftime(self.time_format) + + def api_info(self) -> dict[str, Any]: + return { + "type": "string", + "description": f"Formatted as YYYY-MM-DD{' HH:MM:SS' if self.include_time else ''}", + } + + def example_payload(self) -> str: + return "2020-10-01 05:20:15" + + def example_value(self) -> str: + return "2020-10-01 05:20:15" + + def get_datetime_from_str(self, date: str) -> datetime: + now_regex = r"^(?:\s*now\s*(?:-\s*(\d+)\s*([dmhs]))?)?\s*$" + + if "now" in date: + match = re.match(now_regex, date) + if match: + num = int(match.group(1) or 0) + unit = match.group(2) or "s" + if unit == "d": + delta = timedelta(days=num) + elif unit == "h": + delta = timedelta(hours=num) + elif unit == "m": + delta = timedelta(minutes=num) + else: + delta = timedelta(seconds=num) + return datetime.now() - delta + else: + raise ValueError("Invalid 'now' time format") + else: + dt = datetime.strptime(date, self.time_format) + if self.timezone: + dt = pytz.timezone(self.timezone).localize(dt) + return dt + from typing import Callable, Literal, Sequence, Any, TYPE_CHECKING + from gradio.blocks import Block + if TYPE_CHECKING: + from gradio.components import Timer + + + def change(self, + fn: Callable[..., Any] | None = None, + inputs: Block | Sequence[Block] | set[Block] | None = None, + outputs: Block | Sequence[Block] | None = None, + api_name: str | None | Literal[False] = None, + scroll_to_output: bool = False, + show_progress: Literal["full", "minimal", "hidden"] = "full", + queue: bool | None = None, + batch: bool = False, + max_batch_size: int = 4, + preprocess: bool = True, + postprocess: bool = True, + cancels: dict[str, Any] | list[dict[str, Any]] | None = None, + every: Timer | float | None = None, + trigger_mode: Literal["once", "multiple", "always_last"] | None = None, + js: str | None = None, + concurrency_limit: int | None | Literal["default"] = "default", + concurrency_id: str | None = None, + show_api: bool = True, + + ) -> Dependency: + """ + Parameters: + 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. + inputs: list of gradio.components to use as inputs. If the function takes no inputs, this should be an empty list. + outputs: list of gradio.components to use as outputs. If the function returns no outputs, this should be an empty list. + 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. + scroll_to_output: if True, will scroll to output component on completion + 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 + 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. + 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. + max_batch_size: maximum number of inputs to batch together if this is called from the queue (only relevant if batch=True) + 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). + postprocess: if False, will not run postprocessing of component data before returning 'fn' output to the browser. + 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. + 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. + 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. + 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. + 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). + 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. + 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. + + """ + ... + + def submit(self, + fn: Callable[..., Any] | None = None, + inputs: Block | Sequence[Block] | set[Block] | None = None, + outputs: Block | Sequence[Block] | None = None, + api_name: str | None | Literal[False] = None, + scroll_to_output: bool = False, + show_progress: Literal["full", "minimal", "hidden"] = "full", + queue: bool | None = None, + batch: bool = False, + max_batch_size: int = 4, + preprocess: bool = True, + postprocess: bool = True, + cancels: dict[str, Any] | list[dict[str, Any]] | None = None, + every: Timer | float | None = None, + trigger_mode: Literal["once", "multiple", "always_last"] | None = None, + js: str | None = None, + concurrency_limit: int | None | Literal["default"] = "default", + concurrency_id: str | None = None, + show_api: bool = True, + + ) -> Dependency: + """ + Parameters: + 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. + inputs: list of gradio.components to use as inputs. If the function takes no inputs, this should be an empty list. + outputs: list of gradio.components to use as outputs. If the function returns no outputs, this should be an empty list. + 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. + scroll_to_output: if True, will scroll to output component on completion + 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 + 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. + 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. + max_batch_size: maximum number of inputs to batch together if this is called from the queue (only relevant if batch=True) + 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). + postprocess: if False, will not run postprocessing of component data before returning 'fn' output to the browser. + 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. + 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. + 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. + 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. + 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). + 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. + 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. + + """ + ... \ No newline at end of file diff --git a/mantis_evalkit/lib/python3.10/site-packages/gradio/components/download_button.pyi b/mantis_evalkit/lib/python3.10/site-packages/gradio/components/download_button.pyi new file mode 100644 index 0000000000000000000000000000000000000000..7a6acee2d9af1ad9537e47301cbeccb95b272d2c --- /dev/null +++ b/mantis_evalkit/lib/python3.10/site-packages/gradio/components/download_button.pyi @@ -0,0 +1,174 @@ +"""gr.DownloadButton() component.""" + +from __future__ import annotations + +import tempfile +from collections.abc import Callable, Sequence +from pathlib import Path +from typing import TYPE_CHECKING, Literal + +from gradio_client import handle_file +from gradio_client.documentation import document + +from gradio.components.base import Component +from gradio.data_classes import FileData +from gradio.events import Events + +if TYPE_CHECKING: + from gradio.components import Timer + +from gradio.events import Dependency + +@document() +class DownloadButton(Component): + """ + Creates a button, that when clicked, allows a user to download a single file of arbitrary type. + + Demos: upload_and_download + """ + + EVENTS = [Events.click] + + def __init__( + self, + label: str = "Download", + value: str | Path | Callable | None = None, + *, + every: Timer | float | None = None, + inputs: Component | Sequence[Component] | set[Component] | None = None, + variant: Literal["primary", "secondary", "stop"] = "secondary", + visible: bool = True, + size: Literal["sm", "md", "lg"] = "lg", + icon: str | None = None, + scale: int | None = None, + min_width: int | None = None, + interactive: bool = True, + elem_id: str | None = None, + elem_classes: list[str] | str | None = None, + render: bool = True, + key: int | str | None = None, + ): + """ + Parameters: + label: Text to display on the button. Defaults to "Download". + 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. + 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. + 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. + variant: 'primary' for main call-to-action, 'secondary' for a more subdued style, 'stop' for a stop button. + visible: If False, component will be hidden. + size: size of the button. Can be "sm", "md", or "lg". + icon: URL or path to the icon file to display within the button. If None, no icon will be displayed. + 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. + 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. + interactive: If False, the UploadButton will be in a disabled state. + 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. + 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. + 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. + 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. + """ + self.data_model = FileData + self.size = size + self.label = label + self.variant = variant + super().__init__( + label=label, + every=every, + inputs=inputs, + visible=visible, + elem_id=elem_id, + elem_classes=elem_classes, + render=render, + key=key, + value=value, + scale=scale, + min_width=min_width, + interactive=interactive, + ) + self.icon = self.serve_static_file(icon) + + def preprocess(self, payload: FileData | None) -> str | None: + """ + Parameters: + payload: File information as a FileData object, + Returns: + (Rarely used) passes the file as a `str` into the function. + """ + if payload is None: + return None + file_name = payload.path + file = tempfile.NamedTemporaryFile(delete=False, dir=self.GRADIO_CACHE) + file.name = file_name + return file_name + + def postprocess(self, value: str | Path | None) -> FileData | None: + """ + Parameters: + value: Expects a `str` or `pathlib.Path` filepath + Returns: + File information as a FileData object + """ + if value is None: + return None + return FileData(path=str(value), orig_name=Path(value).name) + + def example_payload(self) -> dict: + return handle_file( + "https://github.com/gradio-app/gradio/raw/main/test/test_files/sample_file.pdf" + ) + + def example_value(self) -> str: + return "https://github.com/gradio-app/gradio/raw/main/test/test_files/sample_file.pdf" + + @property + def skip_api(self): + return False + from typing import Callable, Literal, Sequence, Any, TYPE_CHECKING + from gradio.blocks import Block + if TYPE_CHECKING: + from gradio.components import Timer + + + def click(self, + fn: Callable[..., Any] | None = None, + inputs: Block | Sequence[Block] | set[Block] | None = None, + outputs: Block | Sequence[Block] | None = None, + api_name: str | None | Literal[False] = None, + scroll_to_output: bool = False, + show_progress: Literal["full", "minimal", "hidden"] = "full", + queue: bool | None = None, + batch: bool = False, + max_batch_size: int = 4, + preprocess: bool = True, + postprocess: bool = True, + cancels: dict[str, Any] | list[dict[str, Any]] | None = None, + every: Timer | float | None = None, + trigger_mode: Literal["once", "multiple", "always_last"] | None = None, + js: str | None = None, + concurrency_limit: int | None | Literal["default"] = "default", + concurrency_id: str | None = None, + show_api: bool = True, + + ) -> Dependency: + """ + Parameters: + 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. + inputs: list of gradio.components to use as inputs. If the function takes no inputs, this should be an empty list. + outputs: list of gradio.components to use as outputs. If the function returns no outputs, this should be an empty list. + 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. + scroll_to_output: if True, will scroll to output component on completion + 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 + 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. + 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. + max_batch_size: maximum number of inputs to batch together if this is called from the queue (only relevant if batch=True) + 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). + postprocess: if False, will not run postprocessing of component data before returning 'fn' output to the browser. + 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. + 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. + 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. + 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. + 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). + 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. + 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. + + """ + ... \ No newline at end of file diff --git a/mantis_evalkit/lib/python3.10/site-packages/gradio/components/dropdown.py b/mantis_evalkit/lib/python3.10/site-packages/gradio/components/dropdown.py new file mode 100644 index 0000000000000000000000000000000000000000..bea3d5df22c1f378da7a514cf9a8d4c5cdb633ff --- /dev/null +++ b/mantis_evalkit/lib/python3.10/site-packages/gradio/components/dropdown.py @@ -0,0 +1,247 @@ +"""gr.Dropdown() component.""" + +from __future__ import annotations + +import warnings +from collections.abc import Callable, Sequence +from typing import TYPE_CHECKING, Any, Literal + +from gradio_client.documentation import document + +from gradio.components.base import Component, FormComponent +from gradio.events import Events +from gradio.exceptions import Error + +if TYPE_CHECKING: + from gradio.components import Timer + + +class DefaultValue: + # This sentinel is used to indicate that if the value is not explicitly set, + # the first choice should be selected in the dropdown if multiselect is False, + # and an empty list should be selected if multiselect is True. + pass + + +DEFAULT_VALUE = DefaultValue() + + +@document() +class Dropdown(FormComponent): + """ + 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). + + Demos: sentence_builder + """ + + EVENTS = [ + Events.change, + Events.input, + Events.select, + Events.focus, + Events.blur, + Events.key_up, + ] + + def __init__( + self, + choices: Sequence[str | int | float | tuple[str, str | int | float]] + | None = None, + *, + value: str + | int + | float + | Sequence[str | int | float] + | Callable + | DefaultValue + | None = DEFAULT_VALUE, + type: Literal["value", "index"] = "value", + multiselect: bool | None = None, + allow_custom_value: bool = False, + max_choices: int | None = None, + filterable: bool = True, + label: str | None = None, + info: str | None = None, + every: Timer | float | None = None, + inputs: Component | Sequence[Component] | set[Component] | None = None, + show_label: bool | None = None, + container: bool = True, + scale: int | None = None, + min_width: int = 160, + interactive: bool | None = None, + visible: bool = True, + elem_id: str | None = None, + elem_classes: list[str] | str | None = None, + render: bool = True, + key: int | str | None = None, + ): + """ + Parameters: + 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. + 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. + 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. + multiselect: if True, multiple choices can be selected. + allow_custom_value: if True, allows user to enter a custom value that is not in the list of choices. + max_choices: maximum number of choices that can be selected. If None, no limit is enforced. + 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. + 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. + info: additional component description, appears below the label in smaller font. Supports markdown / HTML syntax. + 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. + 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. + show_label: if True, will display label. + container: if True, will place the component in a container - providing some extra padding around the border. + 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. + 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. + 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. + visible: if False, component will be hidden. + 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. + 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. + 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. + """ + self.choices = ( + # Although we expect choices to be a list of tuples, it can be a list of lists if the Gradio app + # is loaded with gr.load() since Python tuples are converted to lists in JSON. + [tuple(c) if isinstance(c, (tuple, list)) else (str(c), c) for c in choices] + if choices + else [] + ) + valid_types = ["value", "index"] + if type not in valid_types: + raise ValueError( + f"Invalid value for parameter `type`: {type}. Please choose from one of: {valid_types}" + ) + self.type = type + self.multiselect = multiselect + + if value == DEFAULT_VALUE: + if multiselect: + value = [] + elif self.choices: + value = self.choices[0][1] + else: + value = None + if multiselect and isinstance(value, str): + value = [value] + + if not multiselect and max_choices is not None: + warnings.warn( + "The `max_choices` parameter is ignored when `multiselect` is False." + ) + if not filterable and allow_custom_value: + filterable = True + warnings.warn( + "The `filterable` parameter cannot be set to False when `allow_custom_value` is True. Setting `filterable` to True." + ) + self.max_choices = max_choices + self.allow_custom_value = allow_custom_value + self.filterable = filterable + super().__init__( + label=label, + info=info, + every=every, + inputs=inputs, + show_label=show_label, + container=container, + scale=scale, + min_width=min_width, + interactive=interactive, + visible=visible, + elem_id=elem_id, + elem_classes=elem_classes, + render=render, + key=key, + value=value, + ) + + def api_info(self) -> dict[str, Any]: + if self.multiselect: + json_type = { + "type": "array", + "items": {"type": "string", "enum": [c[1] for c in self.choices]}, + } + else: + json_type = { + "type": "string", + "enum": [c[1] for c in self.choices], + } + return json_type + + def example_payload(self) -> Any: + if self.multiselect: + return [self.choices[0][1]] if self.choices else [] + else: + return self.choices[0][1] if self.choices else None + + def example_value(self) -> Any: + if self.multiselect: + return [self.choices[0][1]] if self.choices else [] + else: + return self.choices[0][1] if self.choices else None + + def preprocess( + self, payload: str | int | float | list[str | int | float] | None + ) -> str | int | float | list[str | int | float] | list[int | None] | None: + """ + Parameters: + payload: the value of the selected dropdown choice(s) + Returns: + 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. + """ + if payload is None: + return None + + choice_values = [value for _, value in self.choices] + if not self.allow_custom_value: + if isinstance(payload, list): + for value in payload: + if value not in choice_values: + raise Error( + f"Value: {value!r} (type: {type(value)}) is not in the list of choices: {choice_values}" + ) + elif payload not in choice_values: + raise Error( + f"Value: {payload} is not in the list of choices: {choice_values}" + ) + + if self.type == "value": + return payload + elif self.type == "index": + if isinstance(payload, list): + return [ + choice_values.index(choice) if choice in choice_values else None + for choice in payload + ] + else: + return ( + choice_values.index(payload) if payload in choice_values else None + ) + else: + raise ValueError( + f"Unknown type: {self.type}. Please choose from: 'value', 'index'." + ) + + def _warn_if_invalid_choice(self, value): + if self.allow_custom_value or value in [value for _, value in self.choices]: + return + warnings.warn( + 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." + ) + + def postprocess( + self, value: str | int | float | list[str | int | float] | None + ) -> str | int | float | list[str | int | float] | None: + """ + Parameters: + 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. + Returns: + Returns the values of the selected dropdown entry or entries. + """ + if value is None: + return None + if self.multiselect: + if not isinstance(value, list): + value = [value] + [self._warn_if_invalid_choice(_y) for _y in value] + else: + self._warn_if_invalid_choice(value) + return value diff --git a/mantis_evalkit/lib/python3.10/site-packages/gradio/components/duplicate_button.py b/mantis_evalkit/lib/python3.10/site-packages/gradio/components/duplicate_button.py new file mode 100644 index 0000000000000000000000000000000000000000..f7a9a6a1f13f7e533d20b7ad7f6835b72909a1d7 --- /dev/null +++ b/mantis_evalkit/lib/python3.10/site-packages/gradio/components/duplicate_button.py @@ -0,0 +1,92 @@ +"""gr.DuplicateButton() component""" + +from __future__ import annotations + +from collections.abc import Sequence +from pathlib import Path +from typing import TYPE_CHECKING, Literal + +from gradio_client.documentation import document + +from gradio.components import Button, Component +from gradio.context import get_blocks_context +from gradio.utils import get_space + +if TYPE_CHECKING: + from gradio.components import Timer + + +@document() +class DuplicateButton(Button): + """ + Button that triggers a Spaces Duplication, when the demo is on Hugging Face Spaces. Does nothing locally. + """ + + is_template = True + + def __init__( + self, + value: str = "Duplicate Space", + *, + every: Timer | float | None = None, + inputs: Component | Sequence[Component] | set[Component] | None = None, + variant: Literal["primary", "secondary", "stop", "huggingface"] = "huggingface", + size: Literal["sm", "md", "lg"] = "sm", + icon: str | Path | None = None, + link: str | None = None, + visible: bool = True, + interactive: bool = True, + elem_id: str | None = None, + elem_classes: list[str] | str | None = None, + render: bool = True, + key: int | str | None = None, + scale: int | None = 0, + min_width: int | None = None, + _activate: bool = True, + ): + """ + Parameters: + Parameters: + 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. + 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. + 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. + 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. + size: size of the button. Can be "sm", "md", or "lg". + icon: URL or path to the icon file to display within the button. If None, no icon will be displayed. + link: URL to open when the button is clicked. If None, no link will be used. + visible: if False, component will be hidden. + interactive: if False, the Button will be in a disabled state. + 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. + 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. + 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. + 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. + 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. + 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. + """ + super().__init__( + value=value, + every=every, + inputs=inputs, + variant=variant, + size=size, + icon=icon, + link=link, + visible=visible, + interactive=interactive, + elem_id=elem_id, + elem_classes=elem_classes, + render=render, + key=key, + scale=scale, + min_width=min_width, + ) + if _activate and get_blocks_context(): + self.activate() + + def activate(self): + space_name = get_space() + if space_name is not None: + self.click( + fn=None, + js=f"() => {{ window.open(`https://huggingface.co/spaces/{space_name}?duplicate=true`, '_blank') }}", + ) diff --git a/mantis_evalkit/lib/python3.10/site-packages/gradio/components/fallback.py b/mantis_evalkit/lib/python3.10/site-packages/gradio/components/fallback.py new file mode 100644 index 0000000000000000000000000000000000000000..dce172d0057bcdd4b1b16740ddc13cf4e87b1e9c --- /dev/null +++ b/mantis_evalkit/lib/python3.10/site-packages/gradio/components/fallback.py @@ -0,0 +1,32 @@ +from gradio.components.base import Component + + +class Fallback(Component): + def preprocess(self, payload): + """ + This docstring is used to generate the docs for this custom component. + Parameters: + payload: the data to be preprocessed, sent from the frontend + Returns: + the data after preprocessing, sent to the user's function in the backend + """ + return payload + + def postprocess(self, value): + """ + This docstring is used to generate the docs for this custom component. + Parameters: + payload: the data to be postprocessed, sent from the user's function in the backend + Returns: + the data after postprocessing, sent to the frontend + """ + return value + + def example_payload(self): + return {"foo": "bar"} + + def example_value(self): + return {"foo": "bar"} + + def api_info(self): + return {"type": {}, "description": "any valid json"} diff --git a/mantis_evalkit/lib/python3.10/site-packages/gradio/components/file.pyi b/mantis_evalkit/lib/python3.10/site-packages/gradio/components/file.pyi new file mode 100644 index 0000000000000000000000000000000000000000..05bddeb8ffbbc34df8fbae7ff402f662995ae300 --- /dev/null +++ b/mantis_evalkit/lib/python3.10/site-packages/gradio/components/file.pyi @@ -0,0 +1,528 @@ +"""gr.File() component""" + +from __future__ import annotations + +import tempfile +import warnings +from collections.abc import Callable, Sequence +from pathlib import Path +from typing import TYPE_CHECKING, Any, Literal + +import gradio_client.utils as client_utils +from gradio_client import handle_file +from gradio_client.documentation import document + +from gradio import processing_utils +from gradio.components.base import Component +from gradio.data_classes import FileData, ListFiles +from gradio.events import Events +from gradio.exceptions import Error +from gradio.utils import NamedString + +if TYPE_CHECKING: + from gradio.components import Timer + +from gradio.events import Dependency + +@document() +class File(Component): + """ + Creates a file component that allows uploading one or more generic files (when used as an input) or displaying generic files or URLs for download (as output). + + Demo: zip_files, zip_to_json + """ + + EVENTS = [ + Events.change, + Events.select, + Events.clear, + Events.upload, + Events.delete, + Events.download, + ] + + def __init__( + self, + value: str | list[str] | Callable | None = None, + *, + file_count: Literal["single", "multiple", "directory"] = "single", + file_types: list[str] | None = None, + type: Literal["filepath", "binary"] = "filepath", + label: str | None = None, + every: Timer | float | None = None, + inputs: Component | Sequence[Component] | set[Component] | None = None, + show_label: bool | None = None, + container: bool = True, + scale: int | None = None, + min_width: int = 160, + height: int | str | float | None = None, + interactive: bool | None = None, + visible: bool = True, + elem_id: str | None = None, + elem_classes: list[str] | str | None = None, + render: bool = True, + key: int | str | None = None, + allow_reordering: bool = False, + ): + """ + Parameters: + value: Default file(s) to display, given as a str file path or URL, or a list of str file paths / URLs. If callable, the function will be called whenever the app loads to set the initial value of the component. + file_count: if single, allows user to upload one file. If "multiple", user uploads multiple files. If "directory", user uploads all files in selected directory. Return type will be list for each file in case of "multiple" or "directory". + file_types: List of file extensions or types of files to be uploaded (e.g. ['image', '.json', '.mp4']). "file" allows any file to be uploaded, "image" allows only image files to be uploaded, "audio" allows only audio files to be uploaded, "video" allows only video files to be uploaded, "text" allows only text files to be uploaded. + type: Type of value to be returned by component. "file" returns a temporary file object with the same base name as the uploaded file, whose full path can be retrieved by file_obj.name, "binary" returns an bytes object. + 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. + 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. + 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. + show_label: if True, will display label. + container: If True, will place the component in a container - providing some extra padding around the border. + 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. + 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. + height: The default height of the file component when no files have been uploaded, or the maximum height of the file component when files are present. Specified in pixels if a number is passed, or in CSS units if a string is passed. If more files are uploaded than can fit in the height, a scrollbar will appear. + interactive: if True, will allow users to upload a file; if False, can only be used to display files. If not provided, this is inferred based on whether the component is used as an input or output. + visible: If False, component will be hidden. + 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. + 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. + 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. + 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. + allow_reordering: if True, will allow users to reorder uploaded files by dragging and dropping. + """ + file_count_valid_types = ["single", "multiple", "directory"] + self.file_count = file_count + + if self.file_count not in file_count_valid_types: + raise ValueError( + f"Parameter file_count must be one of them: {file_count_valid_types}" + ) + elif self.file_count in ["multiple", "directory"]: + self.data_model = ListFiles + else: + self.data_model = FileData + self.file_types = file_types + if file_types is not None and not isinstance(file_types, list): + raise ValueError( + f"Parameter file_types must be a list. Received {file_types.__class__.__name__}" + ) + valid_types = [ + "filepath", + "binary", + ] + if type not in valid_types: + raise ValueError( + f"Invalid value for parameter `type`: {type}. Please choose from one of: {valid_types}" + ) + if file_count == "directory" and file_types is not None: + warnings.warn( + "The `file_types` parameter is ignored when `file_count` is 'directory'." + ) + super().__init__( + label=label, + every=every, + inputs=inputs, + show_label=show_label, + container=container, + scale=scale, + min_width=min_width, + interactive=interactive, + visible=visible, + elem_id=elem_id, + elem_classes=elem_classes, + render=render, + key=key, + value=value, + ) + self.type = type + self.height = height + self.allow_reordering = allow_reordering + + def _process_single_file(self, f: FileData) -> NamedString | bytes: + file_name = f.path + if self.type == "filepath": + if self.file_types and not client_utils.is_valid_file( + file_name, self.file_types + ): + raise Error( + f"Invalid file type. Please upload a file that is one of these formats: {self.file_types}" + ) + file = tempfile.NamedTemporaryFile(delete=False, dir=self.GRADIO_CACHE) + file.name = file_name + return NamedString(file_name) + elif self.type == "binary": + with open(file_name, "rb") as file_data: + return file_data.read() + else: + raise ValueError( + "Unknown type: " + + str(type) + + ". Please choose from: 'filepath', 'binary'." + ) + + def preprocess( + self, payload: ListFiles | FileData | None + ) -> bytes | str | list[bytes] | list[str] | None: + """ + Parameters: + payload: File information as a FileData object, or a list of FileData objects. + Returns: + Passes the file as a `str` or `bytes` object, or a list of `str` or list of `bytes` objects, depending on `type` and `file_count`. + """ + if payload is None: + return None + + if self.file_count == "single": + if isinstance(payload, ListFiles): + return self._process_single_file(payload[0]) + return self._process_single_file(payload) + if isinstance(payload, ListFiles): + return [self._process_single_file(f) for f in payload] # type: ignore + return [self._process_single_file(payload)] # type: ignore + + def _download_files(self, value: str | list[str]) -> str | list[str]: + downloaded_files = [] + if isinstance(value, list): + for file in value: + if client_utils.is_http_url_like(file): + downloaded_file = processing_utils.save_url_to_cache( + file, self.GRADIO_CACHE + ) + downloaded_files.append(downloaded_file) + else: + downloaded_files.append(file) + return downloaded_files + if client_utils.is_http_url_like(value): + downloaded_file = processing_utils.save_url_to_cache( + value, self.GRADIO_CACHE + ) + return downloaded_file + else: + return value + + def postprocess(self, value: str | list[str] | None) -> ListFiles | FileData | None: + """ + Parameters: + value: Expects a `str` filepath or URL, or a `list[str]` of filepaths/URLs. + Returns: + File information as a FileData object, or a list of FileData objects. + """ + if value is None: + return None + value = self._download_files(value) + if isinstance(value, list): + return ListFiles( + root=[ + FileData( + path=file, + orig_name=Path(file).name, + size=Path(file).stat().st_size, + ) + for file in value + ] + ) + else: + return FileData( + path=value, + orig_name=Path(value).name, + size=Path(value).stat().st_size, + ) + + def process_example(self, value: str | list | None) -> str: + if value is None: + return "" + elif isinstance(value, list): + return ", ".join([Path(file).name for file in value]) + else: + return Path(value).name + + def example_payload(self) -> Any: + if self.file_count == "single": + return handle_file( + "https://github.com/gradio-app/gradio/raw/main/test/test_files/sample_file.pdf" + ) + else: + return [ + handle_file( + "https://github.com/gradio-app/gradio/raw/main/test/test_files/sample_file.pdf" + ) + ] + + def example_value(self) -> Any: + if self.file_count == "single": + return "https://github.com/gradio-app/gradio/raw/main/test/test_files/sample_file.pdf" + else: + return [ + "https://github.com/gradio-app/gradio/raw/main/test/test_files/sample_file.pdf" + ] + from typing import Callable, Literal, Sequence, Any, TYPE_CHECKING + from gradio.blocks import Block + if TYPE_CHECKING: + from gradio.components import Timer + + + def change(self, + fn: Callable[..., Any] | None = None, + inputs: Block | Sequence[Block] | set[Block] | None = None, + outputs: Block | Sequence[Block] | None = None, + api_name: str | None | Literal[False] = None, + scroll_to_output: bool = False, + show_progress: Literal["full", "minimal", "hidden"] = "full", + queue: bool | None = None, + batch: bool = False, + max_batch_size: int = 4, + preprocess: bool = True, + postprocess: bool = True, + cancels: dict[str, Any] | list[dict[str, Any]] | None = None, + every: Timer | float | None = None, + trigger_mode: Literal["once", "multiple", "always_last"] | None = None, + js: str | None = None, + concurrency_limit: int | None | Literal["default"] = "default", + concurrency_id: str | None = None, + show_api: bool = True, + + ) -> Dependency: + """ + Parameters: + 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. + inputs: list of gradio.components to use as inputs. If the function takes no inputs, this should be an empty list. + outputs: list of gradio.components to use as outputs. If the function returns no outputs, this should be an empty list. + 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. + scroll_to_output: if True, will scroll to output component on completion + 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 + 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. + 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. + max_batch_size: maximum number of inputs to batch together if this is called from the queue (only relevant if batch=True) + 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). + postprocess: if False, will not run postprocessing of component data before returning 'fn' output to the browser. + 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. + 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. + 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. + 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. + 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). + 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. + 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. + + """ + ... + + def select(self, + fn: Callable[..., Any] | None = None, + inputs: Block | Sequence[Block] | set[Block] | None = None, + outputs: Block | Sequence[Block] | None = None, + api_name: str | None | Literal[False] = None, + scroll_to_output: bool = False, + show_progress: Literal["full", "minimal", "hidden"] = "full", + queue: bool | None = None, + batch: bool = False, + max_batch_size: int = 4, + preprocess: bool = True, + postprocess: bool = True, + cancels: dict[str, Any] | list[dict[str, Any]] | None = None, + every: Timer | float | None = None, + trigger_mode: Literal["once", "multiple", "always_last"] | None = None, + js: str | None = None, + concurrency_limit: int | None | Literal["default"] = "default", + concurrency_id: str | None = None, + show_api: bool = True, + + ) -> Dependency: + """ + Parameters: + 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. + inputs: list of gradio.components to use as inputs. If the function takes no inputs, this should be an empty list. + outputs: list of gradio.components to use as outputs. If the function returns no outputs, this should be an empty list. + 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. + scroll_to_output: if True, will scroll to output component on completion + 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 + 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. + 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. + max_batch_size: maximum number of inputs to batch together if this is called from the queue (only relevant if batch=True) + 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). + postprocess: if False, will not run postprocessing of component data before returning 'fn' output to the browser. + 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. + 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. + 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. + 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. + 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). + 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. + 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. + + """ + ... + + def clear(self, + fn: Callable[..., Any] | None = None, + inputs: Block | Sequence[Block] | set[Block] | None = None, + outputs: Block | Sequence[Block] | None = None, + api_name: str | None | Literal[False] = None, + scroll_to_output: bool = False, + show_progress: Literal["full", "minimal", "hidden"] = "full", + queue: bool | None = None, + batch: bool = False, + max_batch_size: int = 4, + preprocess: bool = True, + postprocess: bool = True, + cancels: dict[str, Any] | list[dict[str, Any]] | None = None, + every: Timer | float | None = None, + trigger_mode: Literal["once", "multiple", "always_last"] | None = None, + js: str | None = None, + concurrency_limit: int | None | Literal["default"] = "default", + concurrency_id: str | None = None, + show_api: bool = True, + + ) -> Dependency: + """ + Parameters: + 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. + inputs: list of gradio.components to use as inputs. If the function takes no inputs, this should be an empty list. + outputs: list of gradio.components to use as outputs. If the function returns no outputs, this should be an empty list. + 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. + scroll_to_output: if True, will scroll to output component on completion + 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 + 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. + 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. + max_batch_size: maximum number of inputs to batch together if this is called from the queue (only relevant if batch=True) + 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). + postprocess: if False, will not run postprocessing of component data before returning 'fn' output to the browser. + 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. + 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. + 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. + 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. + 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). + 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. + 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. + + """ + ... + + def upload(self, + fn: Callable[..., Any] | None = None, + inputs: Block | Sequence[Block] | set[Block] | None = None, + outputs: Block | Sequence[Block] | None = None, + api_name: str | None | Literal[False] = None, + scroll_to_output: bool = False, + show_progress: Literal["full", "minimal", "hidden"] = "full", + queue: bool | None = None, + batch: bool = False, + max_batch_size: int = 4, + preprocess: bool = True, + postprocess: bool = True, + cancels: dict[str, Any] | list[dict[str, Any]] | None = None, + every: Timer | float | None = None, + trigger_mode: Literal["once", "multiple", "always_last"] | None = None, + js: str | None = None, + concurrency_limit: int | None | Literal["default"] = "default", + concurrency_id: str | None = None, + show_api: bool = True, + + ) -> Dependency: + """ + Parameters: + 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. + inputs: list of gradio.components to use as inputs. If the function takes no inputs, this should be an empty list. + outputs: list of gradio.components to use as outputs. If the function returns no outputs, this should be an empty list. + 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. + scroll_to_output: if True, will scroll to output component on completion + 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 + 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. + 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. + max_batch_size: maximum number of inputs to batch together if this is called from the queue (only relevant if batch=True) + 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). + postprocess: if False, will not run postprocessing of component data before returning 'fn' output to the browser. + 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. + 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. + 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. + 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. + 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). + 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. + 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. + + """ + ... + + def delete(self, + fn: Callable[..., Any] | None = None, + inputs: Block | Sequence[Block] | set[Block] | None = None, + outputs: Block | Sequence[Block] | None = None, + api_name: str | None | Literal[False] = None, + scroll_to_output: bool = False, + show_progress: Literal["full", "minimal", "hidden"] = "full", + queue: bool | None = None, + batch: bool = False, + max_batch_size: int = 4, + preprocess: bool = True, + postprocess: bool = True, + cancels: dict[str, Any] | list[dict[str, Any]] | None = None, + every: Timer | float | None = None, + trigger_mode: Literal["once", "multiple", "always_last"] | None = None, + js: str | None = None, + concurrency_limit: int | None | Literal["default"] = "default", + concurrency_id: str | None = None, + show_api: bool = True, + + ) -> Dependency: + """ + Parameters: + 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. + inputs: list of gradio.components to use as inputs. If the function takes no inputs, this should be an empty list. + outputs: list of gradio.components to use as outputs. If the function returns no outputs, this should be an empty list. + 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. + scroll_to_output: if True, will scroll to output component on completion + 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 + 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. + 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. + max_batch_size: maximum number of inputs to batch together if this is called from the queue (only relevant if batch=True) + 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). + postprocess: if False, will not run postprocessing of component data before returning 'fn' output to the browser. + 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. + 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. + 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. + 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. + 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). + 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. + 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. + + """ + ... + + def download(self, + fn: Callable[..., Any] | None = None, + inputs: Block | Sequence[Block] | set[Block] | None = None, + outputs: Block | Sequence[Block] | None = None, + api_name: str | None | Literal[False] = None, + scroll_to_output: bool = False, + show_progress: Literal["full", "minimal", "hidden"] = "full", + queue: bool | None = None, + batch: bool = False, + max_batch_size: int = 4, + preprocess: bool = True, + postprocess: bool = True, + cancels: dict[str, Any] | list[dict[str, Any]] | None = None, + every: Timer | float | None = None, + trigger_mode: Literal["once", "multiple", "always_last"] | None = None, + js: str | None = None, + concurrency_limit: int | None | Literal["default"] = "default", + concurrency_id: str | None = None, + show_api: bool = True, + + ) -> Dependency: + """ + Parameters: + 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. + inputs: list of gradio.components to use as inputs. If the function takes no inputs, this should be an empty list. + outputs: list of gradio.components to use as outputs. If the function returns no outputs, this should be an empty list. + 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. + scroll_to_output: if True, will scroll to output component on completion + 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 + 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. + 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. + max_batch_size: maximum number of inputs to batch together if this is called from the queue (only relevant if batch=True) + 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). + postprocess: if False, will not run postprocessing of component data before returning 'fn' output to the browser. + 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. + 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. + 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. + 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. + 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). + 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. + 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. + + """ + ... \ No newline at end of file diff --git a/mantis_evalkit/lib/python3.10/site-packages/gradio/components/login_button.pyi b/mantis_evalkit/lib/python3.10/site-packages/gradio/components/login_button.pyi new file mode 100644 index 0000000000000000000000000000000000000000..11e694ea7c29573cfd50f83e33b4eba3db9dc47f --- /dev/null +++ b/mantis_evalkit/lib/python3.10/site-packages/gradio/components/login_button.pyi @@ -0,0 +1,129 @@ +"""Predefined button to sign in with Hugging Face in a Gradio Space.""" + +from __future__ import annotations + +import json +import time +import warnings +from collections.abc import Sequence +from pathlib import Path +from typing import TYPE_CHECKING, Literal + +from gradio_client.documentation import document + +from gradio import utils +from gradio.components import Button, Component +from gradio.context import get_blocks_context +from gradio.routes import Request + +if TYPE_CHECKING: + from gradio.components import Timer + +from gradio.events import Dependency + +@document() +class LoginButton(Button): + """ + Creates a button that redirects the user to Sign with Hugging Face using OAuth. + """ + + is_template = True + + def __init__( + self, + value: str = "Sign in with Hugging Face", + logout_value: str = "Logout ({})", + *, + every: Timer | float | None = None, + inputs: Component | Sequence[Component] | set[Component] | None = None, + variant: Literal["primary", "secondary", "stop", "huggingface"] = "huggingface", + size: Literal["sm", "md", "lg"] = "lg", + icon: str | Path | None = utils.get_icon_path("huggingface-logo.svg"), + link: str | None = None, + visible: bool = True, + interactive: bool = True, + elem_id: str | None = None, + elem_classes: list[str] | str | None = None, + render: bool = True, + key: int | str | None = None, + scale: int | None = None, + min_width: int | None = None, + ): + """ + Parameters: + logout_value: The text to display when the user is signed in. The string should contain a placeholder for the username with a call-to-action to logout, e.g. "Logout ({})". + """ + self.logout_value = logout_value + super().__init__( + value, + every=every, + inputs=inputs, + variant=variant, + size=size, + icon=icon, + link=link, + visible=visible, + interactive=interactive, + elem_id=elem_id, + elem_classes=elem_classes, + render=render, + key=key, + scale=scale, + min_width=min_width, + ) + if get_blocks_context(): + self.activate() + else: + warnings.warn( + "LoginButton created outside of a Blocks context. May not work unless you call its `activate()` method manually." + ) + + def activate(self): + # Taken from https://cmgdo.com/external-link-in-gradio-button/ + # Taking `self` as input to check if user is logged in + # ('self' value will be either "Sign in with Hugging Face" or "Signed in as ...") + _js = _js_handle_redirect.replace( + "BUTTON_DEFAULT_VALUE", json.dumps(self.value) + ) + self.click(fn=None, inputs=[self], outputs=None, js=_js) + + self.attach_load_event(self._check_login_status, None) + + def _check_login_status(self, request: Request) -> LoginButton: + # Each time the page is refreshed or loaded, check if the user is logged in and adapt label + session = getattr(request, "session", None) or getattr( + request.request, "session", None + ) + + if session is None or "oauth_info" not in session: + # Cookie set but user not logged in + return LoginButton(self.value, interactive=True) + + oauth_info = session["oauth_info"] + expires_at = oauth_info.get("expires_at") + if expires_at is not None and expires_at < time.time(): + # User is logged in but token has expired => logout + session.pop("oauth_info", None) + return LoginButton(self.value, interactive=True) + + # User is correctly logged in + username = oauth_info["userinfo"]["preferred_username"] + return LoginButton(self.logout_value.format(username), interactive=True) + from typing import Callable, Literal, Sequence, Any, TYPE_CHECKING + from gradio.blocks import Block + if TYPE_CHECKING: + from gradio.components import Timer + + +# JS code to redirects to /login/huggingface if user is not logged in. +# If user is logged in, redirect to /logout page. Always happens +# on the same tab. +_js_handle_redirect = """ +(buttonValue) => { + uri = buttonValue === BUTTON_DEFAULT_VALUE ? '/login/huggingface' : '/logout'; + window.parent?.postMessage({ type: "SET_SCROLLING", enabled: true }, "*"); + setTimeout(() => { + window.location.assign(uri + window.location.search); + }, 500); +} +""" \ No newline at end of file diff --git a/mantis_evalkit/lib/python3.10/site-packages/gradio/components/native_plot.py b/mantis_evalkit/lib/python3.10/site-packages/gradio/components/native_plot.py new file mode 100644 index 0000000000000000000000000000000000000000..dfe9a675d7a5efd1c6d984b6230585074f8e67dd --- /dev/null +++ b/mantis_evalkit/lib/python3.10/site-packages/gradio/components/native_plot.py @@ -0,0 +1,270 @@ +from __future__ import annotations + +import json +import warnings +from collections.abc import Callable, Sequence, Set +from typing import ( + TYPE_CHECKING, + Any, + Literal, +) + +import pandas as pd +from gradio_client.documentation import document + +from gradio.components.base import Component +from gradio.data_classes import GradioModel +from gradio.events import Events + +if TYPE_CHECKING: + from gradio.components import Timer + + +class PlotData(GradioModel): + columns: list[str] + data: list[list[Any]] + datatypes: dict[str, Literal["quantitative", "nominal", "temporal"]] + mark: str + + +class NativePlot(Component): + """ + Creates a native Gradio plot component to display data from a pandas DataFrame. Supports interactivity and updates. + + Demos: native_plots + """ + + EVENTS = [Events.select, Events.double_click] + + def __init__( + self, + value: pd.DataFrame | Callable | None = None, + x: str | None = None, + y: str | None = None, + *, + color: str | None = None, + title: str | None = None, + x_title: str | None = None, + y_title: str | None = None, + color_title: str | None = None, + x_bin: str | float | None = None, + y_aggregate: Literal["sum", "mean", "median", "min", "max", "count"] + | None = None, + color_map: dict[str, str] | None = None, + x_lim: list[float] | None = None, + y_lim: list[float] | None = None, + x_label_angle: float = 0, + y_label_angle: float = 0, + x_axis_labels_visible: bool = True, + caption: str | None = None, + sort: Literal["x", "y", "-x", "-y"] | list[str] | None = None, + tooltip: Literal["axis", "none", "all"] | list[str] = "axis", + height: int | None = None, + label: str | None = None, + show_label: bool | None = None, + container: bool = True, + scale: int | None = None, + min_width: int = 160, + every: Timer | float | None = None, + inputs: Component | Sequence[Component] | Set[Component] | None = None, + visible: bool = True, + elem_id: str | None = None, + elem_classes: list[str] | str | None = None, + render: bool = True, + key: int | str | None = None, + **kwargs, + ): + """ + Parameters: + value: The pandas dataframe containing the data to display in the plot. + x: Column corresponding to the x axis. Column can be numeric, datetime, or string/category. + y: Column corresponding to the y axis. Column must be numeric. + color: Column corresponding to series, visualized by color. Column must be string/category. + title: The title to display on top of the chart. + x_title: The title given to the x axis. By default, uses the value of the x parameter. + y_title: The title given to the y axis. By default, uses the value of the y parameter. + color_title: The title given to the color legend. By default, uses the value of color parameter. + x_bin: Grouping used to cluster x values. If x column is numeric, should be number to bin the x values. If x column is datetime, should be string such as "1h", "15m", "10s", using "s", "m", "h", "d" suffixes. + y_aggregate: Aggregation function used to aggregate y values, used if x_bin is provided or x is a string/category. Must be one of "sum", "mean", "median", "min", "max". + color_map: Mapping of series to color names or codes. For example, {"success": "green", "fail": "#FF8888"}. + height: The height of the plot in pixels. + x_lim: A tuple or list containing the limits for the x-axis, specified as [x_min, x_max]. If x column is datetime type, x_lim should be timestamps. + y_lim: A tuple of list containing the limits for the y-axis, specified as [y_min, y_max]. + x_label_angle: The angle of the x-axis labels in degrees offset clockwise. + y_label_angle: The angle of the y-axis labels in degrees offset clockwise. + x_axis_labels_visible: Whether the x-axis labels should be visible. Can be hidden when many x-axis labels are present. + caption: The (optional) caption to display below the plot. + sort: The sorting order of the x values, if x column is type string/category. Can be "x", "y", "-x", "-y", or list of strings that represent the order of the categories. + tooltip: The tooltip to display when hovering on a point. "axis" shows the values for the axis columns, "all" shows all column values, and "none" shows no tooltips. Can also provide a list of strings representing columns to show in the tooltip, which will be displayed along with axis values. + height: The height of the plot in pixels. + label: The (optional) label to display on the top left corner of the plot. + show_label: Whether the label should be displayed. + container: If True, will place the component in a container - providing some extra padding around the border. + 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. + 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. + 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. + 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. + visible: Whether the plot should be visible. + 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. + 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. + 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. + 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. + """ + self.x = x + self.y = y + self.color = color + self.title = title + self.x_title = x_title + self.y_title = y_title + self.color_title = color_title + self.x_bin = x_bin + self.y_aggregate = y_aggregate + self.color_map = color_map + self.x_lim = x_lim + self.y_lim = y_lim + self.x_label_angle = x_label_angle + self.y_label_angle = y_label_angle + self.x_axis_labels_visible = x_axis_labels_visible + self.caption = caption + self.sort = sort + self.tooltip = tooltip + self.height = height + + if label is None and show_label is None: + show_label = False + super().__init__( + value=value, + label=label, + show_label=show_label, + container=container, + scale=scale, + min_width=min_width, + visible=visible, + elem_id=elem_id, + elem_classes=elem_classes, + render=render, + key=key, + every=every, + inputs=inputs, + ) + for key_, val in kwargs.items(): + if key_ == "color_legend_title": + self.color_title = val + if key_ in [ + "stroke_dash", + "overlay_point", + "x_label_angle", + "y_label_angle", + "interactive", + "show_actions_button", + "color_legend_title", + "width", + ]: + warnings.warn( + f"Argument '{key_}' has been deprecated.", DeprecationWarning + ) + + def get_block_name(self) -> str: + return "nativeplot" + + def get_mark(self) -> str: + return "native" + + def preprocess(self, payload: PlotData | None) -> PlotData | None: + """ + Parameters: + payload: The data to display in a line plot. + Returns: + The data to display in a line plot. + """ + return payload + + def postprocess(self, value: pd.DataFrame | dict | None) -> PlotData | None: + """ + Parameters: + value: Expects a pandas DataFrame containing the data to display in the line 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`). + Returns: + The data to display in a line 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, "line"). + """ + # if None or update + if value is None or isinstance(value, dict): + return value + + def get_simplified_type(dtype): + if pd.api.types.is_numeric_dtype(dtype): + return "quantitative" + elif pd.api.types.is_string_dtype( + dtype + ) or pd.api.types.is_categorical_dtype(dtype): + return "nominal" + elif pd.api.types.is_datetime64_any_dtype(dtype): + return "temporal" + else: + raise ValueError(f"Unsupported data type: {dtype}") + + split_json = json.loads(value.to_json(orient="split", date_unit="ms")) + datatypes = { + col: get_simplified_type(value[col].dtype) for col in value.columns + } + return PlotData( + columns=split_json["columns"], + data=split_json["data"], + datatypes=datatypes, + mark=self.get_mark(), + ) + + def example_payload(self) -> Any: + return None + + def example_value(self) -> Any: + import pandas as pd + + return pd.DataFrame({self.x: [1, 2, 3], self.y: [4, 5, 6]}) + + def api_info(self) -> dict[str, Any]: + return {"type": {}, "description": "any valid json"} + + +@document() +class BarPlot(NativePlot): + """ + Creates a bar plot component to display data from a pandas DataFrame. + + Demos: bar_plot_demo + """ + + def get_block_name(self) -> str: + return "nativeplot" + + def get_mark(self) -> str: + return "bar" + + +@document() +class LinePlot(NativePlot): + """ + Creates a line plot component to display data from a pandas DataFrame. + + Demos: line_plot_demo + """ + + def get_block_name(self) -> str: + return "nativeplot" + + def get_mark(self) -> str: + return "line" + + +@document() +class ScatterPlot(NativePlot): + """ + Creates a scatter plot component to display data from a pandas DataFrame. + + Demos: scatter_plot_demo + """ + + def get_block_name(self) -> str: + return "nativeplot" + + def get_mark(self) -> str: + return "point" diff --git a/mantis_evalkit/lib/python3.10/site-packages/gradio/components/timer.py b/mantis_evalkit/lib/python3.10/site-packages/gradio/components/timer.py new file mode 100644 index 0000000000000000000000000000000000000000..87fccbccf120d6274e9ac1545e4ecd68cdc0aed7 --- /dev/null +++ b/mantis_evalkit/lib/python3.10/site-packages/gradio/components/timer.py @@ -0,0 +1,67 @@ +"""gr.Timer() component.""" + +from __future__ import annotations + +from typing import TYPE_CHECKING + +from gradio_client.documentation import document + +from gradio.components.base import Component +from gradio.events import Events + +if TYPE_CHECKING: + pass + + +@document() +class Timer(Component): + """ + Special component that ticks at regular intervals when active. It is not visible, and only used to trigger events at a regular interval through the `tick` event listener. + """ + + EVENTS = [ + Events.tick, + ] + + def __init__( + self, + value: float = 1, + *, + active: bool = True, + render: bool = True, + ): + """ + Parameters: + value: Interval in seconds between each tick. + active: Whether the timer is active. + 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. + """ + self.active = active + super().__init__(value=value, render=render) + + def preprocess(self, payload: float | None) -> float | None: + """ + Parameters: + payload: The interval of the timer as a float or None. + Returns: + The interval of the timer as a float. + """ + return payload + + def postprocess(self, value: float | None) -> float | None: + """ + Parameters: + value: The interval of the timer as a float or None. + Returns: + The interval of the timer as a float. + """ + return value + + def api_info(self) -> dict: + return {"type": "number"} + + def example_payload(self): + return 1 + + def example_value(self): + return 1 diff --git a/mantis_evalkit/lib/python3.10/site-packages/gradio/components/video.py b/mantis_evalkit/lib/python3.10/site-packages/gradio/components/video.py new file mode 100644 index 0000000000000000000000000000000000000000..f84471e65c77cc05a2b4374b8c3495337d060937 --- /dev/null +++ b/mantis_evalkit/lib/python3.10/site-packages/gradio/components/video.py @@ -0,0 +1,588 @@ +"""gr.Video() component.""" + +from __future__ import annotations + +import asyncio +import json +import subprocess +import tempfile +import warnings +from collections.abc import Callable, Sequence +from pathlib import Path +from typing import TYPE_CHECKING, Any, Literal, Optional + +from gradio_client import handle_file +from gradio_client import utils as client_utils +from gradio_client.documentation import document + +import gradio as gr +from gradio import processing_utils, utils, wasm_utils +from gradio.components.base import Component, StreamingOutput +from gradio.data_classes import FileData, GradioModel, MediaStreamChunk +from gradio.events import Events + +if TYPE_CHECKING: + from gradio.components import Timer + + +if not wasm_utils.IS_WASM: + # TODO: Support ffmpeg on Wasm + from ffmpy import FFmpeg + + +class VideoData(GradioModel): + video: FileData + subtitles: Optional[FileData] = None + + +@document() +class Video(StreamingOutput, Component): + """ + Creates a video component that can be used to upload/record videos (as an input) or display videos (as an output). + For the video to be playable in the browser it must have a compatible container and codec combination. Allowed + combinations are .mp4 with h264 codec, .ogg with theora codec, and .webm with vp9 codec. If the component detects + that the output video would not be playable in the browser it will attempt to convert it to a playable mp4 video. + If the conversion fails, the original video is returned. + + Demos: video_identity_2 + """ + + data_model = VideoData + + EVENTS = [ + Events.change, + Events.clear, + Events.start_recording, + Events.stop_recording, + Events.stop, + Events.play, + Events.pause, + Events.end, + Events.upload, + ] + + def __init__( + self, + value: str + | Path + | tuple[str | Path, str | Path | None] + | Callable + | None = None, + *, + format: str | None = None, + sources: list[Literal["upload", "webcam"]] + | Literal["upload", "webcam"] + | None = None, + height: int | str | None = None, + width: int | str | None = None, + label: str | None = None, + every: Timer | float | None = None, + inputs: Component | Sequence[Component] | set[Component] | None = None, + show_label: bool | None = None, + container: bool = True, + scale: int | None = None, + min_width: int = 160, + interactive: bool | None = None, + visible: bool = True, + elem_id: str | None = None, + elem_classes: list[str] | str | None = None, + render: bool = True, + key: int | str | None = None, + mirror_webcam: bool = True, + include_audio: bool | None = None, + autoplay: bool = False, + show_share_button: bool | None = None, + show_download_button: bool | None = None, + min_length: int | None = None, + max_length: int | None = None, + loop: bool = False, + streaming: bool = False, + watermark: str | Path | None = None, + webcam_constraints: dict[str, Any] | None = None, + ): + """ + Parameters: + value: path or URL for the default value that Video component is going to take. Can also be a tuple consisting of (video filepath, subtitle filepath). If a subtitle file is provided, it should be of type .srt or .vtt. Or can be callable, in which case the function will be called whenever the app loads to set the initial value of the component. + format: the file extension with which to save video, such as 'avi' or 'mp4'. This parameter applies both when this component is used as an input to determine which file format to convert user-provided video to, and when this component is used as an output to determine the format of video returned to the user. If None, no file format conversion is done and the video is kept as is. Use 'mp4' to ensure browser playability. + sources: list of sources permitted for video. "upload" creates a box where user can drop a video file, "webcam" allows user to record a video from their webcam. If None, defaults to both ["upload, "webcam"]. + height: The height of the component, specified in pixels if a number is passed, or in CSS units if a string is passed. This has no effect on the preprocessed video file, but will affect the displayed video. + width: The width of the component, specified in pixels if a number is passed, or in CSS units if a string is passed. This has no effect on the preprocessed video file, but will affect the displayed video. + 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. + 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. + 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. + show_label: if True, will display label. + container: if True, will place the component in a container - providing some extra padding around the border. + 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. + 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. + interactive: if True, will allow users to upload a video; if False, can only be used to display videos. If not provided, this is inferred based on whether the component is used as an input or output. + visible: if False, component will be hidden. + 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. + 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. + 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. + 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. + mirror_webcam: if True webcam will be mirrored. Default is True. + include_audio: whether the component should record/retain the audio track for a video. By default, audio is excluded for webcam videos and included for uploaded videos. + autoplay: whether to automatically play the video when the component is used as an output. Note: browsers will not autoplay video files if the user has not interacted with the page yet. + show_share_button: if True, will show a share icon in the corner of the component that allows user to share outputs to Hugging Face Spaces Discussions. If False, icon does not appear. If set to None (default behavior), then the icon appears if this Gradio app is launched on Spaces, but not otherwise. + show_download_button: if True, will show a download icon in the corner of the component that allows user to download the output. If False, icon does not appear. By default, it will be True for output components and False for input components. + min_length: the minimum length of video (in seconds) that the user can pass into the prediction function. If None, there is no minimum length. + max_length: the maximum length of video (in seconds) that the user can pass into the prediction function. If None, there is no maximum length. + loop: if True, the video will loop when it reaches the end and continue playing from the beginning. + streaming: when used set as an output, takes video chunks yielded from the backend and combines them into one streaming video output. Each chunk should be a video file with a .ts extension using an h.264 encoding. Mp4 files are also accepted but they will be converted to h.264 encoding. + watermark: an image file to be included as a watermark on the video. The image is not scaled and is displayed on the bottom right of the video. Valid formats for the image are: jpeg, png. + webcam_constraints: A dictionary that allows developers to specify custom media constraints for the webcam stream. This parameter provides flexibility to control the video stream's properties, such as resolution and front or rear camera on mobile devices. See $demo/webcam_constraints + """ + valid_sources: list[Literal["upload", "webcam"]] = ["upload", "webcam"] + if sources is None: + self.sources = valid_sources + elif isinstance(sources, str) and sources in valid_sources: + self.sources = [sources] + elif isinstance(sources, list) and all(s in valid_sources for s in sources): + self.sources = sources + else: + raise ValueError( + f"`sources` must be a list consisting of elements in {valid_sources}" + ) + for source in self.sources: + if source not in valid_sources: + raise ValueError( + f"`sources` must a list consisting of elements in {valid_sources}" + ) + self.format = format + self.autoplay = autoplay + self.height = height + self.width = width + self.loop = loop + self.mirror_webcam = mirror_webcam + self.include_audio = ( + include_audio if include_audio is not None else "upload" in self.sources + ) + self.show_share_button = ( + (utils.get_space() is not None) + if show_share_button is None + else show_share_button + ) + self.show_download_button = show_download_button + self.min_length = min_length + self.max_length = max_length + self.streaming = streaming + self.watermark = watermark + self.webcam_constraints = webcam_constraints + super().__init__( + label=label, + every=every, + inputs=inputs, + show_label=show_label, + container=container, + scale=scale, + min_width=min_width, + interactive=interactive, + visible=visible, + elem_id=elem_id, + elem_classes=elem_classes, + render=render, + key=key, + value=value, + ) + + def preprocess(self, payload: VideoData | None) -> str | None: + """ + Parameters: + payload: An instance of VideoData containing the video and subtitle files. + Returns: + Passes the uploaded video as a `str` filepath or URL whose extension can be modified by `format`. + """ + if payload is None: + return None + if not payload.video.path: + raise ValueError("Payload path missing") + file_name = Path(payload.video.path) + uploaded_format = file_name.suffix.replace(".", "") + needs_formatting = self.format is not None and uploaded_format != self.format + flip = self.sources == ["webcam"] and self.mirror_webcam + + if self.min_length is not None or self.max_length is not None: + # With this if-clause, avoid unnecessary execution of `processing_utils.get_video_length`. + # This is necessary for the Wasm-mode, because it uses ffprobe, which is not available in the browser. + duration = processing_utils.get_video_length(file_name) + if self.min_length is not None and duration < self.min_length: + raise gr.Error( + f"Video is too short, and must be at least {self.min_length} seconds" + ) + if self.max_length is not None and duration > self.max_length: + raise gr.Error( + f"Video is too long, and must be at most {self.max_length} seconds" + ) + # TODO: Check other image extensions to see if they work. + valid_watermark_extensions = [".png", ".jpg", ".jpeg"] + if self.watermark is not None: + if not isinstance(self.watermark, (str, Path)): + raise ValueError( + f"Provided watermark file not an expected file type. " + f"Received: {self.watermark}" + ) + if Path(self.watermark).suffix not in valid_watermark_extensions: + raise ValueError( + f"Watermark file does not have a supported extension. " + f"Expected one of {','.join(valid_watermark_extensions)}. " + f"Received: {Path(self.watermark).suffix}." + ) + if needs_formatting or flip: + format = f".{self.format if needs_formatting else uploaded_format}" + output_options = ["-vf", "hflip", "-c:a", "copy"] if flip else [] + output_options += ["-an"] if not self.include_audio else [] + flip_suffix = "_flip" if flip else "" + output_file_name = str( + file_name.with_name(f"{file_name.stem}{flip_suffix}{format}") + ) + output_filepath = Path(output_file_name) + if output_filepath.exists(): + return str(output_filepath.resolve()) + if wasm_utils.IS_WASM: + raise wasm_utils.WasmUnsupportedError( + "Video formatting is not supported in the Wasm mode." + ) + ff = FFmpeg( # type: ignore + inputs={str(file_name): None}, + outputs={output_file_name: output_options}, + ) + ff.run() + return str(output_filepath.resolve()) + elif not self.include_audio: + output_file_name = str(file_name.with_name(f"muted_{file_name.name}")) + if Path(output_file_name).exists(): + return output_file_name + if wasm_utils.IS_WASM: + raise wasm_utils.WasmUnsupportedError( + "include_audio=False is not supported in the Wasm mode." + ) + ff = FFmpeg( # type: ignore + inputs={str(file_name): None}, + outputs={output_file_name: ["-an"]}, + ) + ff.run() + return output_file_name + else: + return str(file_name) + + def postprocess( + self, value: str | Path | tuple[str | Path, str | Path | None] | None + ) -> VideoData | None: + """ + Parameters: + value: Expects a {str} or {pathlib.Path} filepath to a video which is displayed, or a {Tuple[str | pathlib.Path, str | pathlib.Path | None]} where the first element is a filepath to a video and the second element is an optional filepath to a subtitle file. + Returns: + VideoData object containing the video and subtitle files. + """ + if self.streaming: + return value # type: ignore + if value is None or value in ([None, None], (None, None)): + return None + if isinstance(value, (str, Path)): + processed_files = (self._format_video(value), None) + + elif isinstance(value, (tuple, list)): + if len(value) != 2: + raise ValueError( + f"Expected lists of length 2 or tuples of length 2. Received: {value}" + ) + + if not ( + isinstance(value[0], (str, Path)) and isinstance(value[1], (str, Path)) + ): + raise TypeError( + f"If a tuple is provided, both elements must be strings or Path objects. Received: {value}" + ) + video = value[0] + subtitle = value[1] + processed_files = ( + self._format_video(video), + self._format_subtitle(subtitle), + ) + + else: + raise Exception(f"Cannot process type as video: {type(value)}") + if not processed_files[0]: + raise ValueError("Video data missing") + return VideoData(video=processed_files[0], subtitles=processed_files[1]) + + def _format_video(self, video: str | Path | None) -> FileData | None: + """ + Processes a video to ensure that it is in the correct format + and adds a watermark if requested. + """ + if video is None: + return None + video = str(video) + returned_format = video.split(".")[-1].lower() + if self.format is None or returned_format == self.format: + conversion_needed = False + else: + conversion_needed = True + + is_url = client_utils.is_http_url_like(video) + + # For cases where the video is a URL and does not need to be converted + # to another format and have a watermark added, we can just return the URL + if not self.watermark and (is_url and not conversion_needed): + return FileData(path=video) + + # For cases where the video needs to be converted to another format + # or have a watermark added. + if is_url: + video = processing_utils.save_url_to_cache( + video, cache_dir=self.GRADIO_CACHE + ) + if ( + processing_utils.ffmpeg_installed() + and not processing_utils.video_is_playable(video) + ): + warnings.warn( + "Video does not have browser-compatible container or codec. Converting to mp4." + ) + video = processing_utils.convert_video_to_playable_mp4(video) + # Recalculate the format in case convert_video_to_playable_mp4 already made it the selected format + returned_format = utils.get_extension_from_file_path_or_url(video).lower() + if ( + self.format is not None and returned_format != self.format + ) or self.watermark: + if wasm_utils.IS_WASM: + raise wasm_utils.WasmUnsupportedError( + "Modifying a video is not supported in the Wasm mode." + ) + global_option_list = ["-y"] + inputs_dict = {video: None} + output_file_name = video[0 : video.rindex(".") + 1] + if self.format is not None: + output_file_name += self.format + else: + output_file_name += returned_format + if self.watermark: + inputs_dict[str(self.watermark)] = None + watermark_cmd = "overlay=W-w-5:H-h-5" + global_option_list += ["-filter_complex", watermark_cmd] + output_file_name = ( + Path(output_file_name).stem + + "_watermarked" + + Path(output_file_name).suffix + ) + ff = FFmpeg( # type: ignore + inputs=inputs_dict, + outputs={output_file_name: None}, + global_options=global_option_list, + ) + ff.run() + video = output_file_name + + return FileData(path=video, orig_name=Path(video).name) + + def _format_subtitle(self, subtitle: str | Path | None) -> FileData | None: + """ + Convert subtitle format to VTT and process the video to ensure it meets the HTML5 requirements. + """ + + def srt_to_vtt(srt_file_path, vtt_file_path): + """Convert an SRT subtitle file to a VTT subtitle file""" + with ( + open(srt_file_path, encoding="utf-8") as srt_file, + open(vtt_file_path, "w", encoding="utf-8") as vtt_file, + ): + vtt_file.write("WEBVTT\n\n") + for subtitle_block in srt_file.read().strip().split("\n\n"): + subtitle_lines = subtitle_block.split("\n") + subtitle_timing = subtitle_lines[1].replace(",", ".") + subtitle_text = "\n".join(subtitle_lines[2:]) + vtt_file.write(f"{subtitle_timing} --> {subtitle_timing}\n") + vtt_file.write(f"{subtitle_text}\n\n") + + if subtitle is None: + return None + + valid_extensions = (".srt", ".vtt") + + if Path(subtitle).suffix not in valid_extensions: + raise ValueError( + f"Invalid value for parameter `subtitle`: {subtitle}. Please choose a file with one of these extensions: {valid_extensions}" + ) + + # HTML5 only support vtt format + if Path(subtitle).suffix == ".srt": + temp_file = tempfile.NamedTemporaryFile( + delete=False, suffix=".vtt", dir=self.GRADIO_CACHE + ) + + srt_to_vtt(subtitle, temp_file.name) + subtitle = temp_file.name + + return FileData(path=str(subtitle)) + + def example_payload(self) -> Any: + return { + "video": handle_file( + "https://github.com/gradio-app/gradio/raw/main/demo/video_component/files/world.mp4" + ), + } + + def example_value(self) -> Any: + return "https://github.com/gradio-app/gradio/raw/main/demo/video_component/files/world.mp4" + + @staticmethod + def get_video_duration_ffprobe(filename: str): + if wasm_utils.IS_WASM: + raise wasm_utils.WasmUnsupportedError( + "ffprobe is not supported in the Wasm mode." + ) + + result = subprocess.run( + [ + "ffprobe", + "-v", + "quiet", + "-print_format", + "json", + "-show_format", + "-show_streams", + filename, + ], + capture_output=True, + check=True, + ) + + data = json.loads(result.stdout) + + duration = None + if "format" in data and "duration" in data["format"]: + duration = float(data["format"]["duration"]) + else: + for stream in data.get("streams", []): + if "duration" in stream: + duration = float(stream["duration"]) + break + + return duration + + @staticmethod + async def async_convert_mp4_to_ts(mp4_file, ts_file): + if wasm_utils.IS_WASM: + raise wasm_utils.WasmUnsupportedError( + "Streaming is not supported in the Wasm mode." + ) + + ff = FFmpeg( # type: ignore + inputs={mp4_file: None}, + outputs={ + ts_file: "-c:v libx264 -c:a aac -f mpegts -bsf:v h264_mp4toannexb -bsf:a aac_adtstoasc" + }, + global_options=["-y"], + ) + + command = ff.cmd.split(" ") + process = await asyncio.create_subprocess_exec( + *command, stdout=asyncio.subprocess.PIPE, stderr=asyncio.subprocess.PIPE + ) + + _, stderr = await process.communicate() + + if process.returncode != 0: + error_message = stderr.decode().strip() + raise RuntimeError(f"FFmpeg command failed: {error_message}") + + return ts_file + + async def combine_stream( + self, + stream: list[bytes], + desired_output_format: str | None = None, # noqa: ARG002 + only_file=False, + ) -> VideoData | FileData: + """Combine video chunks into a single video file. + + Do not take desired_output_format into consideration as + mp4 is a safe format for playing in browser. + """ + if wasm_utils.IS_WASM: + raise wasm_utils.WasmUnsupportedError( + "Streaming is not supported in the Wasm mode." + ) + + # Use an mp4 extension here so that the cached example + # is playable in the browser + output_file = tempfile.NamedTemporaryFile( + delete=False, suffix=".mp4", dir=self.GRADIO_CACHE + ) + + ts_files = [ + processing_utils.save_bytes_to_cache( + s, "video_chunk.ts", cache_dir=self.GRADIO_CACHE + ) + for s in stream + ] + + command = [ + "ffmpeg", + "-i", + f'concat:{"|".join(ts_files)}', + "-y", + "-safe", + "0", + "-c", + "copy", + output_file.name, + ] + process = await asyncio.create_subprocess_exec( + *command, stdout=asyncio.subprocess.PIPE, stderr=asyncio.subprocess.PIPE + ) + + _, stderr = await process.communicate() + + if process.returncode != 0: + error_message = stderr.decode().strip() + raise RuntimeError(f"FFmpeg command failed: {error_message}") + video = FileData( + path=output_file.name, + is_stream=False, + orig_name="video-stream.mp4", + ) + if only_file: + return video + + output = VideoData(video=video) + return output + + async def stream_output( + self, + value: str | None, + output_id: str, + first_chunk: bool, # noqa: ARG002 + ) -> tuple[MediaStreamChunk | None, dict]: + output_file = { + "video": { + "path": output_id, + "is_stream": True, + # Need to set orig_name so that downloaded file has correct + # extension + "orig_name": "video-stream.mp4", + "meta": {"_type": "gradio.FileData"}, + } + } + if value is None: + return None, output_file + + ts_file = value + if not value.endswith(".ts"): + if not value.endswith(".mp4"): + raise RuntimeError( + "Video must be in .mp4 or .ts format to be streamed as chunks", + ) + ts_file = value.replace(".mp4", ".ts") + await self.async_convert_mp4_to_ts(value, ts_file) + + duration = self.get_video_duration_ffprobe(ts_file) + if not duration: + raise RuntimeError("Cannot determine video chunk duration") + chunk: MediaStreamChunk = { + "data": Path(ts_file).read_bytes(), + "duration": duration, + "extension": ".ts", + } + return chunk, output_file diff --git a/moondream/lib/python3.10/site-packages/pip/_vendor/requests/__pycache__/__version__.cpython-310.pyc b/moondream/lib/python3.10/site-packages/pip/_vendor/requests/__pycache__/__version__.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..58077eb55c2b4659581286e4801109dd7b9c3454 Binary files /dev/null and b/moondream/lib/python3.10/site-packages/pip/_vendor/requests/__pycache__/__version__.cpython-310.pyc differ diff --git a/moondream/lib/python3.10/site-packages/pip/_vendor/requests/__pycache__/_internal_utils.cpython-310.pyc b/moondream/lib/python3.10/site-packages/pip/_vendor/requests/__pycache__/_internal_utils.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..4ffd349b82a7a71016139fdf33ff4f5f93d9a7ce Binary files /dev/null and b/moondream/lib/python3.10/site-packages/pip/_vendor/requests/__pycache__/_internal_utils.cpython-310.pyc differ diff --git a/moondream/lib/python3.10/site-packages/pip/_vendor/requests/__pycache__/adapters.cpython-310.pyc b/moondream/lib/python3.10/site-packages/pip/_vendor/requests/__pycache__/adapters.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..f55b8fbe523b66a8c940ef04ce7b2913afa118f3 Binary files /dev/null and b/moondream/lib/python3.10/site-packages/pip/_vendor/requests/__pycache__/adapters.cpython-310.pyc differ diff --git a/moondream/lib/python3.10/site-packages/pip/_vendor/requests/__pycache__/api.cpython-310.pyc b/moondream/lib/python3.10/site-packages/pip/_vendor/requests/__pycache__/api.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..f8eafcd5ed0e678d88975332e84b35413b9fd015 Binary files /dev/null and b/moondream/lib/python3.10/site-packages/pip/_vendor/requests/__pycache__/api.cpython-310.pyc differ diff --git a/moondream/lib/python3.10/site-packages/pip/_vendor/requests/__pycache__/auth.cpython-310.pyc b/moondream/lib/python3.10/site-packages/pip/_vendor/requests/__pycache__/auth.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..42858098b918fa9b1eb79765ba30361c26551597 Binary files /dev/null and b/moondream/lib/python3.10/site-packages/pip/_vendor/requests/__pycache__/auth.cpython-310.pyc differ diff --git a/moondream/lib/python3.10/site-packages/pip/_vendor/requests/__pycache__/certs.cpython-310.pyc b/moondream/lib/python3.10/site-packages/pip/_vendor/requests/__pycache__/certs.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..0895633cd9dfc307e24ef8f4898eea354bfc914c Binary files /dev/null and b/moondream/lib/python3.10/site-packages/pip/_vendor/requests/__pycache__/certs.cpython-310.pyc differ diff --git a/moondream/lib/python3.10/site-packages/pip/_vendor/requests/__pycache__/cookies.cpython-310.pyc b/moondream/lib/python3.10/site-packages/pip/_vendor/requests/__pycache__/cookies.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..abbd1edf1b510813a10ec73e4b417c2654a12b34 Binary files /dev/null and b/moondream/lib/python3.10/site-packages/pip/_vendor/requests/__pycache__/cookies.cpython-310.pyc differ diff --git a/moondream/lib/python3.10/site-packages/pip/_vendor/requests/__pycache__/help.cpython-310.pyc b/moondream/lib/python3.10/site-packages/pip/_vendor/requests/__pycache__/help.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..43ba2ce1ed2bbef2039e69dcd7c256c061f81022 Binary files /dev/null and b/moondream/lib/python3.10/site-packages/pip/_vendor/requests/__pycache__/help.cpython-310.pyc differ diff --git a/moondream/lib/python3.10/site-packages/pip/_vendor/requests/__pycache__/models.cpython-310.pyc b/moondream/lib/python3.10/site-packages/pip/_vendor/requests/__pycache__/models.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..2e9c2da7cbc808a8dacd6a0f85929bd9ae2863b0 Binary files /dev/null and b/moondream/lib/python3.10/site-packages/pip/_vendor/requests/__pycache__/models.cpython-310.pyc differ diff --git a/moondream/lib/python3.10/site-packages/pip/_vendor/requests/__pycache__/packages.cpython-310.pyc b/moondream/lib/python3.10/site-packages/pip/_vendor/requests/__pycache__/packages.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..c26bcc6aca859167035bb2b8ad13e37cfd5af5ca Binary files /dev/null and b/moondream/lib/python3.10/site-packages/pip/_vendor/requests/__pycache__/packages.cpython-310.pyc differ diff --git a/moondream/lib/python3.10/site-packages/pip/_vendor/requests/__pycache__/status_codes.cpython-310.pyc b/moondream/lib/python3.10/site-packages/pip/_vendor/requests/__pycache__/status_codes.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..32da072320fbb75d265e9afdadba0a9d1970ba96 Binary files /dev/null and b/moondream/lib/python3.10/site-packages/pip/_vendor/requests/__pycache__/status_codes.cpython-310.pyc differ diff --git a/moondream/lib/python3.10/site-packages/pip/_vendor/requests/__pycache__/structures.cpython-310.pyc b/moondream/lib/python3.10/site-packages/pip/_vendor/requests/__pycache__/structures.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..7c7f819a8befea51a90a9f64ae34856f71615103 Binary files /dev/null and b/moondream/lib/python3.10/site-packages/pip/_vendor/requests/__pycache__/structures.cpython-310.pyc differ diff --git a/moondream/lib/python3.10/site-packages/pip/_vendor/requests/auth.py b/moondream/lib/python3.10/site-packages/pip/_vendor/requests/auth.py new file mode 100644 index 0000000000000000000000000000000000000000..4a7ce6dc1460e0de8aa0c38ea9123faa69bd5110 --- /dev/null +++ b/moondream/lib/python3.10/site-packages/pip/_vendor/requests/auth.py @@ -0,0 +1,314 @@ +""" +requests.auth +~~~~~~~~~~~~~ + +This module contains the authentication handlers for Requests. +""" + +import hashlib +import os +import re +import threading +import time +import warnings +from base64 import b64encode + +from ._internal_utils import to_native_string +from .compat import basestring, str, urlparse +from .cookies import extract_cookies_to_jar +from .utils import parse_dict_header + +CONTENT_TYPE_FORM_URLENCODED = "application/x-www-form-urlencoded" +CONTENT_TYPE_MULTI_PART = "multipart/form-data" + + +def _basic_auth_str(username, password): + """Returns a Basic Auth string.""" + + # "I want us to put a big-ol' comment on top of it that + # says that this behaviour is dumb but we need to preserve + # it because people are relying on it." + # - Lukasa + # + # These are here solely to maintain backwards compatibility + # for things like ints. This will be removed in 3.0.0. + if not isinstance(username, basestring): + warnings.warn( + "Non-string usernames will no longer be supported in Requests " + "3.0.0. Please convert the object you've passed in ({!r}) to " + "a string or bytes object in the near future to avoid " + "problems.".format(username), + category=DeprecationWarning, + ) + username = str(username) + + if not isinstance(password, basestring): + warnings.warn( + "Non-string passwords will no longer be supported in Requests " + "3.0.0. Please convert the object you've passed in ({!r}) to " + "a string or bytes object in the near future to avoid " + "problems.".format(type(password)), + category=DeprecationWarning, + ) + password = str(password) + # -- End Removal -- + + if isinstance(username, str): + username = username.encode("latin1") + + if isinstance(password, str): + password = password.encode("latin1") + + authstr = "Basic " + to_native_string( + b64encode(b":".join((username, password))).strip() + ) + + return authstr + + +class AuthBase: + """Base class that all auth implementations derive from""" + + def __call__(self, r): + raise NotImplementedError("Auth hooks must be callable.") + + +class HTTPBasicAuth(AuthBase): + """Attaches HTTP Basic Authentication to the given Request object.""" + + def __init__(self, username, password): + self.username = username + self.password = password + + def __eq__(self, other): + return all( + [ + self.username == getattr(other, "username", None), + self.password == getattr(other, "password", None), + ] + ) + + def __ne__(self, other): + return not self == other + + def __call__(self, r): + r.headers["Authorization"] = _basic_auth_str(self.username, self.password) + return r + + +class HTTPProxyAuth(HTTPBasicAuth): + """Attaches HTTP Proxy Authentication to a given Request object.""" + + def __call__(self, r): + r.headers["Proxy-Authorization"] = _basic_auth_str(self.username, self.password) + return r + + +class HTTPDigestAuth(AuthBase): + """Attaches HTTP Digest Authentication to the given Request object.""" + + def __init__(self, username, password): + self.username = username + self.password = password + # Keep state in per-thread local storage + self._thread_local = threading.local() + + def init_per_thread_state(self): + # Ensure state is initialized just once per-thread + if not hasattr(self._thread_local, "init"): + self._thread_local.init = True + self._thread_local.last_nonce = "" + self._thread_local.nonce_count = 0 + self._thread_local.chal = {} + self._thread_local.pos = None + self._thread_local.num_401_calls = None + + def build_digest_header(self, method, url): + """ + :rtype: str + """ + + realm = self._thread_local.chal["realm"] + nonce = self._thread_local.chal["nonce"] + qop = self._thread_local.chal.get("qop") + algorithm = self._thread_local.chal.get("algorithm") + opaque = self._thread_local.chal.get("opaque") + hash_utf8 = None + + if algorithm is None: + _algorithm = "MD5" + else: + _algorithm = algorithm.upper() + # lambdas assume digest modules are imported at the top level + if _algorithm == "MD5" or _algorithm == "MD5-SESS": + + def md5_utf8(x): + if isinstance(x, str): + x = x.encode("utf-8") + return hashlib.md5(x).hexdigest() + + hash_utf8 = md5_utf8 + elif _algorithm == "SHA": + + def sha_utf8(x): + if isinstance(x, str): + x = x.encode("utf-8") + return hashlib.sha1(x).hexdigest() + + hash_utf8 = sha_utf8 + elif _algorithm == "SHA-256": + + def sha256_utf8(x): + if isinstance(x, str): + x = x.encode("utf-8") + return hashlib.sha256(x).hexdigest() + + hash_utf8 = sha256_utf8 + elif _algorithm == "SHA-512": + + def sha512_utf8(x): + if isinstance(x, str): + x = x.encode("utf-8") + return hashlib.sha512(x).hexdigest() + + hash_utf8 = sha512_utf8 + + KD = lambda s, d: hash_utf8(f"{s}:{d}") # noqa:E731 + + if hash_utf8 is None: + return None + + # XXX not implemented yet + entdig = None + p_parsed = urlparse(url) + #: path is request-uri defined in RFC 2616 which should not be empty + path = p_parsed.path or "/" + if p_parsed.query: + path += f"?{p_parsed.query}" + + A1 = f"{self.username}:{realm}:{self.password}" + A2 = f"{method}:{path}" + + HA1 = hash_utf8(A1) + HA2 = hash_utf8(A2) + + if nonce == self._thread_local.last_nonce: + self._thread_local.nonce_count += 1 + else: + self._thread_local.nonce_count = 1 + ncvalue = f"{self._thread_local.nonce_count:08x}" + s = str(self._thread_local.nonce_count).encode("utf-8") + s += nonce.encode("utf-8") + s += time.ctime().encode("utf-8") + s += os.urandom(8) + + cnonce = hashlib.sha1(s).hexdigest()[:16] + if _algorithm == "MD5-SESS": + HA1 = hash_utf8(f"{HA1}:{nonce}:{cnonce}") + + if not qop: + respdig = KD(HA1, f"{nonce}:{HA2}") + elif qop == "auth" or "auth" in qop.split(","): + noncebit = f"{nonce}:{ncvalue}:{cnonce}:auth:{HA2}" + respdig = KD(HA1, noncebit) + else: + # XXX handle auth-int. + return None + + self._thread_local.last_nonce = nonce + + # XXX should the partial digests be encoded too? + base = ( + f'username="{self.username}", realm="{realm}", nonce="{nonce}", ' + f'uri="{path}", response="{respdig}"' + ) + if opaque: + base += f', opaque="{opaque}"' + if algorithm: + base += f', algorithm="{algorithm}"' + if entdig: + base += f', digest="{entdig}"' + if qop: + base += f', qop="auth", nc={ncvalue}, cnonce="{cnonce}"' + + return f"Digest {base}" + + def handle_redirect(self, r, **kwargs): + """Reset num_401_calls counter on redirects.""" + if r.is_redirect: + self._thread_local.num_401_calls = 1 + + def handle_401(self, r, **kwargs): + """ + Takes the given response and tries digest-auth, if needed. + + :rtype: requests.Response + """ + + # If response is not 4xx, do not auth + # See https://github.com/psf/requests/issues/3772 + if not 400 <= r.status_code < 500: + self._thread_local.num_401_calls = 1 + return r + + if self._thread_local.pos is not None: + # Rewind the file position indicator of the body to where + # it was to resend the request. + r.request.body.seek(self._thread_local.pos) + s_auth = r.headers.get("www-authenticate", "") + + if "digest" in s_auth.lower() and self._thread_local.num_401_calls < 2: + self._thread_local.num_401_calls += 1 + pat = re.compile(r"digest ", flags=re.IGNORECASE) + self._thread_local.chal = parse_dict_header(pat.sub("", s_auth, count=1)) + + # Consume content and release the original connection + # to allow our new request to reuse the same one. + r.content + r.close() + prep = r.request.copy() + extract_cookies_to_jar(prep._cookies, r.request, r.raw) + prep.prepare_cookies(prep._cookies) + + prep.headers["Authorization"] = self.build_digest_header( + prep.method, prep.url + ) + _r = r.connection.send(prep, **kwargs) + _r.history.append(r) + _r.request = prep + + return _r + + self._thread_local.num_401_calls = 1 + return r + + def __call__(self, r): + # Initialize per-thread state, if needed + self.init_per_thread_state() + # If we have a saved nonce, skip the 401 + if self._thread_local.last_nonce: + r.headers["Authorization"] = self.build_digest_header(r.method, r.url) + try: + self._thread_local.pos = r.body.tell() + except AttributeError: + # In the case of HTTPDigestAuth being reused and the body of + # the previous request was a file-like object, pos has the + # file position of the previous body. Ensure it's set to + # None. + self._thread_local.pos = None + r.register_hook("response", self.handle_401) + r.register_hook("response", self.handle_redirect) + self._thread_local.num_401_calls = 1 + + return r + + def __eq__(self, other): + return all( + [ + self.username == getattr(other, "username", None), + self.password == getattr(other, "password", None), + ] + ) + + def __ne__(self, other): + return not self == other diff --git a/moondream/lib/python3.10/site-packages/pip/_vendor/requests/packages.py b/moondream/lib/python3.10/site-packages/pip/_vendor/requests/packages.py new file mode 100644 index 0000000000000000000000000000000000000000..200c38287f49ed338f30677c13543465185b0435 --- /dev/null +++ b/moondream/lib/python3.10/site-packages/pip/_vendor/requests/packages.py @@ -0,0 +1,25 @@ +import sys + +from .compat import chardet + +# This code exists for backwards compatibility reasons. +# I don't like it either. Just look the other way. :) + +for package in ("urllib3", "idna"): + vendored_package = "pip._vendor." + package + locals()[package] = __import__(vendored_package) + # This traversal is apparently necessary such that the identities are + # preserved (requests.packages.urllib3.* is urllib3.*) + for mod in list(sys.modules): + if mod == vendored_package or mod.startswith(vendored_package + '.'): + unprefixed_mod = mod[len("pip._vendor."):] + sys.modules['pip._vendor.requests.packages.' + unprefixed_mod] = sys.modules[mod] + +if chardet is not None: + target = chardet.__name__ + for mod in list(sys.modules): + if mod == target or mod.startswith(f"{target}."): + imported_mod = sys.modules[mod] + sys.modules[f"requests.packages.{mod}"] = imported_mod + mod = mod.replace(target, "chardet") + sys.modules[f"requests.packages.{mod}"] = imported_mod diff --git a/moondream/lib/python3.10/site-packages/pip/_vendor/requests/structures.py b/moondream/lib/python3.10/site-packages/pip/_vendor/requests/structures.py new file mode 100644 index 0000000000000000000000000000000000000000..188e13e4829591facb23ae0e2eda84b9807cb818 --- /dev/null +++ b/moondream/lib/python3.10/site-packages/pip/_vendor/requests/structures.py @@ -0,0 +1,99 @@ +""" +requests.structures +~~~~~~~~~~~~~~~~~~~ + +Data structures that power Requests. +""" + +from collections import OrderedDict + +from .compat import Mapping, MutableMapping + + +class CaseInsensitiveDict(MutableMapping): + """A case-insensitive ``dict``-like object. + + Implements all methods and operations of + ``MutableMapping`` as well as dict's ``copy``. Also + provides ``lower_items``. + + All keys are expected to be strings. The structure remembers the + case of the last key to be set, and ``iter(instance)``, + ``keys()``, ``items()``, ``iterkeys()``, and ``iteritems()`` + will contain case-sensitive keys. However, querying and contains + testing is case insensitive:: + + cid = CaseInsensitiveDict() + cid['Accept'] = 'application/json' + cid['aCCEPT'] == 'application/json' # True + list(cid) == ['Accept'] # True + + For example, ``headers['content-encoding']`` will return the + value of a ``'Content-Encoding'`` response header, regardless + of how the header name was originally stored. + + If the constructor, ``.update``, or equality comparison + operations are given keys that have equal ``.lower()``s, the + behavior is undefined. + """ + + def __init__(self, data=None, **kwargs): + self._store = OrderedDict() + if data is None: + data = {} + self.update(data, **kwargs) + + def __setitem__(self, key, value): + # Use the lowercased key for lookups, but store the actual + # key alongside the value. + self._store[key.lower()] = (key, value) + + def __getitem__(self, key): + return self._store[key.lower()][1] + + def __delitem__(self, key): + del self._store[key.lower()] + + def __iter__(self): + return (casedkey for casedkey, mappedvalue in self._store.values()) + + def __len__(self): + return len(self._store) + + def lower_items(self): + """Like iteritems(), but with all lowercase keys.""" + return ((lowerkey, keyval[1]) for (lowerkey, keyval) in self._store.items()) + + def __eq__(self, other): + if isinstance(other, Mapping): + other = CaseInsensitiveDict(other) + else: + return NotImplemented + # Compare insensitively + return dict(self.lower_items()) == dict(other.lower_items()) + + # Copy is required + def copy(self): + return CaseInsensitiveDict(self._store.values()) + + def __repr__(self): + return str(dict(self.items())) + + +class LookupDict(dict): + """Dictionary lookup object.""" + + def __init__(self, name=None): + self.name = name + super().__init__() + + def __repr__(self): + return f"" + + def __getitem__(self, key): + # We allow fall-through here, so values default to None + + return self.__dict__.get(key, None) + + def get(self, key, default=None): + return self.__dict__.get(key, default) diff --git a/moondream/lib/python3.10/site-packages/pip/_vendor/requests/utils.py b/moondream/lib/python3.10/site-packages/pip/_vendor/requests/utils.py new file mode 100644 index 0000000000000000000000000000000000000000..a35ce478667b469e769a086cddb2d6b2e89e6a51 --- /dev/null +++ b/moondream/lib/python3.10/site-packages/pip/_vendor/requests/utils.py @@ -0,0 +1,1096 @@ +""" +requests.utils +~~~~~~~~~~~~~~ + +This module provides utility functions that are used within Requests +that are also useful for external consumption. +""" + +import codecs +import contextlib +import io +import os +import re +import socket +import struct +import sys +import tempfile +import warnings +import zipfile +from collections import OrderedDict + +from pip._vendor.urllib3.util import make_headers, parse_url + +from . import certs +from .__version__ import __version__ + +# to_native_string is unused here, but imported here for backwards compatibility +from ._internal_utils import ( # noqa: F401 + _HEADER_VALIDATORS_BYTE, + _HEADER_VALIDATORS_STR, + HEADER_VALIDATORS, + to_native_string, +) +from .compat import ( + Mapping, + basestring, + bytes, + getproxies, + getproxies_environment, + integer_types, +) +from .compat import parse_http_list as _parse_list_header +from .compat import ( + proxy_bypass, + proxy_bypass_environment, + quote, + str, + unquote, + urlparse, + urlunparse, +) +from .cookies import cookiejar_from_dict +from .exceptions import ( + FileModeWarning, + InvalidHeader, + InvalidURL, + UnrewindableBodyError, +) +from .structures import CaseInsensitiveDict + +NETRC_FILES = (".netrc", "_netrc") + +DEFAULT_CA_BUNDLE_PATH = certs.where() + +DEFAULT_PORTS = {"http": 80, "https": 443} + +# Ensure that ', ' is used to preserve previous delimiter behavior. +DEFAULT_ACCEPT_ENCODING = ", ".join( + re.split(r",\s*", make_headers(accept_encoding=True)["accept-encoding"]) +) + + +if sys.platform == "win32": + # provide a proxy_bypass version on Windows without DNS lookups + + def proxy_bypass_registry(host): + try: + import winreg + except ImportError: + return False + + try: + internetSettings = winreg.OpenKey( + winreg.HKEY_CURRENT_USER, + r"Software\Microsoft\Windows\CurrentVersion\Internet Settings", + ) + # ProxyEnable could be REG_SZ or REG_DWORD, normalizing it + proxyEnable = int(winreg.QueryValueEx(internetSettings, "ProxyEnable")[0]) + # ProxyOverride is almost always a string + proxyOverride = winreg.QueryValueEx(internetSettings, "ProxyOverride")[0] + except (OSError, ValueError): + return False + if not proxyEnable or not proxyOverride: + return False + + # make a check value list from the registry entry: replace the + # '' string by the localhost entry and the corresponding + # canonical entry. + proxyOverride = proxyOverride.split(";") + # filter out empty strings to avoid re.match return true in the following code. + proxyOverride = filter(None, proxyOverride) + # now check if we match one of the registry values. + for test in proxyOverride: + if test == "": + if "." not in host: + return True + test = test.replace(".", r"\.") # mask dots + test = test.replace("*", r".*") # change glob sequence + test = test.replace("?", r".") # change glob char + if re.match(test, host, re.I): + return True + return False + + def proxy_bypass(host): # noqa + """Return True, if the host should be bypassed. + + Checks proxy settings gathered from the environment, if specified, + or the registry. + """ + if getproxies_environment(): + return proxy_bypass_environment(host) + else: + return proxy_bypass_registry(host) + + +def dict_to_sequence(d): + """Returns an internal sequence dictionary update.""" + + if hasattr(d, "items"): + d = d.items() + + return d + + +def super_len(o): + total_length = None + current_position = 0 + + if isinstance(o, str): + o = o.encode("utf-8") + + if hasattr(o, "__len__"): + total_length = len(o) + + elif hasattr(o, "len"): + total_length = o.len + + elif hasattr(o, "fileno"): + try: + fileno = o.fileno() + except (io.UnsupportedOperation, AttributeError): + # AttributeError is a surprising exception, seeing as how we've just checked + # that `hasattr(o, 'fileno')`. It happens for objects obtained via + # `Tarfile.extractfile()`, per issue 5229. + pass + else: + total_length = os.fstat(fileno).st_size + + # Having used fstat to determine the file length, we need to + # confirm that this file was opened up in binary mode. + if "b" not in o.mode: + warnings.warn( + ( + "Requests has determined the content-length for this " + "request using the binary size of the file: however, the " + "file has been opened in text mode (i.e. without the 'b' " + "flag in the mode). This may lead to an incorrect " + "content-length. In Requests 3.0, support will be removed " + "for files in text mode." + ), + FileModeWarning, + ) + + if hasattr(o, "tell"): + try: + current_position = o.tell() + except OSError: + # This can happen in some weird situations, such as when the file + # is actually a special file descriptor like stdin. In this + # instance, we don't know what the length is, so set it to zero and + # let requests chunk it instead. + if total_length is not None: + current_position = total_length + else: + if hasattr(o, "seek") and total_length is None: + # StringIO and BytesIO have seek but no usable fileno + try: + # seek to end of file + o.seek(0, 2) + total_length = o.tell() + + # seek back to current position to support + # partially read file-like objects + o.seek(current_position or 0) + except OSError: + total_length = 0 + + if total_length is None: + total_length = 0 + + return max(0, total_length - current_position) + + +def get_netrc_auth(url, raise_errors=False): + """Returns the Requests tuple auth for a given url from netrc.""" + + netrc_file = os.environ.get("NETRC") + if netrc_file is not None: + netrc_locations = (netrc_file,) + else: + netrc_locations = (f"~/{f}" for f in NETRC_FILES) + + try: + from netrc import NetrcParseError, netrc + + netrc_path = None + + for f in netrc_locations: + try: + loc = os.path.expanduser(f) + except KeyError: + # os.path.expanduser can fail when $HOME is undefined and + # getpwuid fails. See https://bugs.python.org/issue20164 & + # https://github.com/psf/requests/issues/1846 + return + + if os.path.exists(loc): + netrc_path = loc + break + + # Abort early if there isn't one. + if netrc_path is None: + return + + ri = urlparse(url) + + # Strip port numbers from netloc. This weird `if...encode`` dance is + # used for Python 3.2, which doesn't support unicode literals. + splitstr = b":" + if isinstance(url, str): + splitstr = splitstr.decode("ascii") + host = ri.netloc.split(splitstr)[0] + + try: + _netrc = netrc(netrc_path).authenticators(host) + if _netrc: + # Return with login / password + login_i = 0 if _netrc[0] else 1 + return (_netrc[login_i], _netrc[2]) + except (NetrcParseError, OSError): + # If there was a parsing error or a permissions issue reading the file, + # we'll just skip netrc auth unless explicitly asked to raise errors. + if raise_errors: + raise + + # App Engine hackiness. + except (ImportError, AttributeError): + pass + + +def guess_filename(obj): + """Tries to guess the filename of the given object.""" + name = getattr(obj, "name", None) + if name and isinstance(name, basestring) and name[0] != "<" and name[-1] != ">": + return os.path.basename(name) + + +def extract_zipped_paths(path): + """Replace nonexistent paths that look like they refer to a member of a zip + archive with the location of an extracted copy of the target, or else + just return the provided path unchanged. + """ + if os.path.exists(path): + # this is already a valid path, no need to do anything further + return path + + # find the first valid part of the provided path and treat that as a zip archive + # assume the rest of the path is the name of a member in the archive + archive, member = os.path.split(path) + while archive and not os.path.exists(archive): + archive, prefix = os.path.split(archive) + if not prefix: + # If we don't check for an empty prefix after the split (in other words, archive remains unchanged after the split), + # we _can_ end up in an infinite loop on a rare corner case affecting a small number of users + break + member = "/".join([prefix, member]) + + if not zipfile.is_zipfile(archive): + return path + + zip_file = zipfile.ZipFile(archive) + if member not in zip_file.namelist(): + return path + + # we have a valid zip archive and a valid member of that archive + tmp = tempfile.gettempdir() + extracted_path = os.path.join(tmp, member.split("/")[-1]) + if not os.path.exists(extracted_path): + # use read + write to avoid the creating nested folders, we only want the file, avoids mkdir racing condition + with atomic_open(extracted_path) as file_handler: + file_handler.write(zip_file.read(member)) + return extracted_path + + +@contextlib.contextmanager +def atomic_open(filename): + """Write a file to the disk in an atomic fashion""" + tmp_descriptor, tmp_name = tempfile.mkstemp(dir=os.path.dirname(filename)) + try: + with os.fdopen(tmp_descriptor, "wb") as tmp_handler: + yield tmp_handler + os.replace(tmp_name, filename) + except BaseException: + os.remove(tmp_name) + raise + + +def from_key_val_list(value): + """Take an object and test to see if it can be represented as a + dictionary. Unless it can not be represented as such, return an + OrderedDict, e.g., + + :: + + >>> from_key_val_list([('key', 'val')]) + OrderedDict([('key', 'val')]) + >>> from_key_val_list('string') + Traceback (most recent call last): + ... + ValueError: cannot encode objects that are not 2-tuples + >>> from_key_val_list({'key': 'val'}) + OrderedDict([('key', 'val')]) + + :rtype: OrderedDict + """ + if value is None: + return None + + if isinstance(value, (str, bytes, bool, int)): + raise ValueError("cannot encode objects that are not 2-tuples") + + return OrderedDict(value) + + +def to_key_val_list(value): + """Take an object and test to see if it can be represented as a + dictionary. If it can be, return a list of tuples, e.g., + + :: + + >>> to_key_val_list([('key', 'val')]) + [('key', 'val')] + >>> to_key_val_list({'key': 'val'}) + [('key', 'val')] + >>> to_key_val_list('string') + Traceback (most recent call last): + ... + ValueError: cannot encode objects that are not 2-tuples + + :rtype: list + """ + if value is None: + return None + + if isinstance(value, (str, bytes, bool, int)): + raise ValueError("cannot encode objects that are not 2-tuples") + + if isinstance(value, Mapping): + value = value.items() + + return list(value) + + +# From mitsuhiko/werkzeug (used with permission). +def parse_list_header(value): + """Parse lists as described by RFC 2068 Section 2. + + In particular, parse comma-separated lists where the elements of + the list may include quoted-strings. A quoted-string could + contain a comma. A non-quoted string could have quotes in the + middle. Quotes are removed automatically after parsing. + + It basically works like :func:`parse_set_header` just that items + may appear multiple times and case sensitivity is preserved. + + The return value is a standard :class:`list`: + + >>> parse_list_header('token, "quoted value"') + ['token', 'quoted value'] + + To create a header from the :class:`list` again, use the + :func:`dump_header` function. + + :param value: a string with a list header. + :return: :class:`list` + :rtype: list + """ + result = [] + for item in _parse_list_header(value): + if item[:1] == item[-1:] == '"': + item = unquote_header_value(item[1:-1]) + result.append(item) + return result + + +# From mitsuhiko/werkzeug (used with permission). +def parse_dict_header(value): + """Parse lists of key, value pairs as described by RFC 2068 Section 2 and + convert them into a python dict: + + >>> d = parse_dict_header('foo="is a fish", bar="as well"') + >>> type(d) is dict + True + >>> sorted(d.items()) + [('bar', 'as well'), ('foo', 'is a fish')] + + If there is no value for a key it will be `None`: + + >>> parse_dict_header('key_without_value') + {'key_without_value': None} + + To create a header from the :class:`dict` again, use the + :func:`dump_header` function. + + :param value: a string with a dict header. + :return: :class:`dict` + :rtype: dict + """ + result = {} + for item in _parse_list_header(value): + if "=" not in item: + result[item] = None + continue + name, value = item.split("=", 1) + if value[:1] == value[-1:] == '"': + value = unquote_header_value(value[1:-1]) + result[name] = value + return result + + +# From mitsuhiko/werkzeug (used with permission). +def unquote_header_value(value, is_filename=False): + r"""Unquotes a header value. (Reversal of :func:`quote_header_value`). + This does not use the real unquoting but what browsers are actually + using for quoting. + + :param value: the header value to unquote. + :rtype: str + """ + if value and value[0] == value[-1] == '"': + # this is not the real unquoting, but fixing this so that the + # RFC is met will result in bugs with internet explorer and + # probably some other browsers as well. IE for example is + # uploading files with "C:\foo\bar.txt" as filename + value = value[1:-1] + + # if this is a filename and the starting characters look like + # a UNC path, then just return the value without quotes. Using the + # replace sequence below on a UNC path has the effect of turning + # the leading double slash into a single slash and then + # _fix_ie_filename() doesn't work correctly. See #458. + if not is_filename or value[:2] != "\\\\": + return value.replace("\\\\", "\\").replace('\\"', '"') + return value + + +def dict_from_cookiejar(cj): + """Returns a key/value dictionary from a CookieJar. + + :param cj: CookieJar object to extract cookies from. + :rtype: dict + """ + + cookie_dict = {cookie.name: cookie.value for cookie in cj} + return cookie_dict + + +def add_dict_to_cookiejar(cj, cookie_dict): + """Returns a CookieJar from a key/value dictionary. + + :param cj: CookieJar to insert cookies into. + :param cookie_dict: Dict of key/values to insert into CookieJar. + :rtype: CookieJar + """ + + return cookiejar_from_dict(cookie_dict, cj) + + +def get_encodings_from_content(content): + """Returns encodings from given content string. + + :param content: bytestring to extract encodings from. + """ + warnings.warn( + ( + "In requests 3.0, get_encodings_from_content will be removed. For " + "more information, please see the discussion on issue #2266. (This" + " warning should only appear once.)" + ), + DeprecationWarning, + ) + + charset_re = re.compile(r']', flags=re.I) + pragma_re = re.compile(r']', flags=re.I) + xml_re = re.compile(r'^<\?xml.*?encoding=["\']*(.+?)["\'>]') + + return ( + charset_re.findall(content) + + pragma_re.findall(content) + + xml_re.findall(content) + ) + + +def _parse_content_type_header(header): + """Returns content type and parameters from given header + + :param header: string + :return: tuple containing content type and dictionary of + parameters + """ + + tokens = header.split(";") + content_type, params = tokens[0].strip(), tokens[1:] + params_dict = {} + items_to_strip = "\"' " + + for param in params: + param = param.strip() + if param: + key, value = param, True + index_of_equals = param.find("=") + if index_of_equals != -1: + key = param[:index_of_equals].strip(items_to_strip) + value = param[index_of_equals + 1 :].strip(items_to_strip) + params_dict[key.lower()] = value + return content_type, params_dict + + +def get_encoding_from_headers(headers): + """Returns encodings from given HTTP Header Dict. + + :param headers: dictionary to extract encoding from. + :rtype: str + """ + + content_type = headers.get("content-type") + + if not content_type: + return None + + content_type, params = _parse_content_type_header(content_type) + + if "charset" in params: + return params["charset"].strip("'\"") + + if "text" in content_type: + return "ISO-8859-1" + + if "application/json" in content_type: + # Assume UTF-8 based on RFC 4627: https://www.ietf.org/rfc/rfc4627.txt since the charset was unset + return "utf-8" + + +def stream_decode_response_unicode(iterator, r): + """Stream decodes an iterator.""" + + if r.encoding is None: + yield from iterator + return + + decoder = codecs.getincrementaldecoder(r.encoding)(errors="replace") + for chunk in iterator: + rv = decoder.decode(chunk) + if rv: + yield rv + rv = decoder.decode(b"", final=True) + if rv: + yield rv + + +def iter_slices(string, slice_length): + """Iterate over slices of a string.""" + pos = 0 + if slice_length is None or slice_length <= 0: + slice_length = len(string) + while pos < len(string): + yield string[pos : pos + slice_length] + pos += slice_length + + +def get_unicode_from_response(r): + """Returns the requested content back in unicode. + + :param r: Response object to get unicode content from. + + Tried: + + 1. charset from content-type + 2. fall back and replace all unicode characters + + :rtype: str + """ + warnings.warn( + ( + "In requests 3.0, get_unicode_from_response will be removed. For " + "more information, please see the discussion on issue #2266. (This" + " warning should only appear once.)" + ), + DeprecationWarning, + ) + + tried_encodings = [] + + # Try charset from content-type + encoding = get_encoding_from_headers(r.headers) + + if encoding: + try: + return str(r.content, encoding) + except UnicodeError: + tried_encodings.append(encoding) + + # Fall back: + try: + return str(r.content, encoding, errors="replace") + except TypeError: + return r.content + + +# The unreserved URI characters (RFC 3986) +UNRESERVED_SET = frozenset( + "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz" + "0123456789-._~" +) + + +def unquote_unreserved(uri): + """Un-escape any percent-escape sequences in a URI that are unreserved + characters. This leaves all reserved, illegal and non-ASCII bytes encoded. + + :rtype: str + """ + parts = uri.split("%") + for i in range(1, len(parts)): + h = parts[i][0:2] + if len(h) == 2 and h.isalnum(): + try: + c = chr(int(h, 16)) + except ValueError: + raise InvalidURL(f"Invalid percent-escape sequence: '{h}'") + + if c in UNRESERVED_SET: + parts[i] = c + parts[i][2:] + else: + parts[i] = f"%{parts[i]}" + else: + parts[i] = f"%{parts[i]}" + return "".join(parts) + + +def requote_uri(uri): + """Re-quote the given URI. + + This function passes the given URI through an unquote/quote cycle to + ensure that it is fully and consistently quoted. + + :rtype: str + """ + safe_with_percent = "!#$%&'()*+,/:;=?@[]~" + safe_without_percent = "!#$&'()*+,/:;=?@[]~" + try: + # Unquote only the unreserved characters + # Then quote only illegal characters (do not quote reserved, + # unreserved, or '%') + return quote(unquote_unreserved(uri), safe=safe_with_percent) + except InvalidURL: + # We couldn't unquote the given URI, so let's try quoting it, but + # there may be unquoted '%'s in the URI. We need to make sure they're + # properly quoted so they do not cause issues elsewhere. + return quote(uri, safe=safe_without_percent) + + +def address_in_network(ip, net): + """This function allows you to check if an IP belongs to a network subnet + + Example: returns True if ip = 192.168.1.1 and net = 192.168.1.0/24 + returns False if ip = 192.168.1.1 and net = 192.168.100.0/24 + + :rtype: bool + """ + ipaddr = struct.unpack("=L", socket.inet_aton(ip))[0] + netaddr, bits = net.split("/") + netmask = struct.unpack("=L", socket.inet_aton(dotted_netmask(int(bits))))[0] + network = struct.unpack("=L", socket.inet_aton(netaddr))[0] & netmask + return (ipaddr & netmask) == (network & netmask) + + +def dotted_netmask(mask): + """Converts mask from /xx format to xxx.xxx.xxx.xxx + + Example: if mask is 24 function returns 255.255.255.0 + + :rtype: str + """ + bits = 0xFFFFFFFF ^ (1 << 32 - mask) - 1 + return socket.inet_ntoa(struct.pack(">I", bits)) + + +def is_ipv4_address(string_ip): + """ + :rtype: bool + """ + try: + socket.inet_aton(string_ip) + except OSError: + return False + return True + + +def is_valid_cidr(string_network): + """ + Very simple check of the cidr format in no_proxy variable. + + :rtype: bool + """ + if string_network.count("/") == 1: + try: + mask = int(string_network.split("/")[1]) + except ValueError: + return False + + if mask < 1 or mask > 32: + return False + + try: + socket.inet_aton(string_network.split("/")[0]) + except OSError: + return False + else: + return False + return True + + +@contextlib.contextmanager +def set_environ(env_name, value): + """Set the environment variable 'env_name' to 'value' + + Save previous value, yield, and then restore the previous value stored in + the environment variable 'env_name'. + + If 'value' is None, do nothing""" + value_changed = value is not None + if value_changed: + old_value = os.environ.get(env_name) + os.environ[env_name] = value + try: + yield + finally: + if value_changed: + if old_value is None: + del os.environ[env_name] + else: + os.environ[env_name] = old_value + + +def should_bypass_proxies(url, no_proxy): + """ + Returns whether we should bypass proxies or not. + + :rtype: bool + """ + + # Prioritize lowercase environment variables over uppercase + # to keep a consistent behaviour with other http projects (curl, wget). + def get_proxy(key): + return os.environ.get(key) or os.environ.get(key.upper()) + + # First check whether no_proxy is defined. If it is, check that the URL + # we're getting isn't in the no_proxy list. + no_proxy_arg = no_proxy + if no_proxy is None: + no_proxy = get_proxy("no_proxy") + parsed = urlparse(url) + + if parsed.hostname is None: + # URLs don't always have hostnames, e.g. file:/// urls. + return True + + if no_proxy: + # We need to check whether we match here. We need to see if we match + # the end of the hostname, both with and without the port. + no_proxy = (host for host in no_proxy.replace(" ", "").split(",") if host) + + if is_ipv4_address(parsed.hostname): + for proxy_ip in no_proxy: + if is_valid_cidr(proxy_ip): + if address_in_network(parsed.hostname, proxy_ip): + return True + elif parsed.hostname == proxy_ip: + # If no_proxy ip was defined in plain IP notation instead of cidr notation & + # matches the IP of the index + return True + else: + host_with_port = parsed.hostname + if parsed.port: + host_with_port += f":{parsed.port}" + + for host in no_proxy: + if parsed.hostname.endswith(host) or host_with_port.endswith(host): + # The URL does match something in no_proxy, so we don't want + # to apply the proxies on this URL. + return True + + with set_environ("no_proxy", no_proxy_arg): + # parsed.hostname can be `None` in cases such as a file URI. + try: + bypass = proxy_bypass(parsed.hostname) + except (TypeError, socket.gaierror): + bypass = False + + if bypass: + return True + + return False + + +def get_environ_proxies(url, no_proxy=None): + """ + Return a dict of environment proxies. + + :rtype: dict + """ + if should_bypass_proxies(url, no_proxy=no_proxy): + return {} + else: + return getproxies() + + +def select_proxy(url, proxies): + """Select a proxy for the url, if applicable. + + :param url: The url being for the request + :param proxies: A dictionary of schemes or schemes and hosts to proxy URLs + """ + proxies = proxies or {} + urlparts = urlparse(url) + if urlparts.hostname is None: + return proxies.get(urlparts.scheme, proxies.get("all")) + + proxy_keys = [ + urlparts.scheme + "://" + urlparts.hostname, + urlparts.scheme, + "all://" + urlparts.hostname, + "all", + ] + proxy = None + for proxy_key in proxy_keys: + if proxy_key in proxies: + proxy = proxies[proxy_key] + break + + return proxy + + +def resolve_proxies(request, proxies, trust_env=True): + """This method takes proxy information from a request and configuration + input to resolve a mapping of target proxies. This will consider settings + such as NO_PROXY to strip proxy configurations. + + :param request: Request or PreparedRequest + :param proxies: A dictionary of schemes or schemes and hosts to proxy URLs + :param trust_env: Boolean declaring whether to trust environment configs + + :rtype: dict + """ + proxies = proxies if proxies is not None else {} + url = request.url + scheme = urlparse(url).scheme + no_proxy = proxies.get("no_proxy") + new_proxies = proxies.copy() + + if trust_env and not should_bypass_proxies(url, no_proxy=no_proxy): + environ_proxies = get_environ_proxies(url, no_proxy=no_proxy) + + proxy = environ_proxies.get(scheme, environ_proxies.get("all")) + + if proxy: + new_proxies.setdefault(scheme, proxy) + return new_proxies + + +def default_user_agent(name="python-requests"): + """ + Return a string representing the default user agent. + + :rtype: str + """ + return f"{name}/{__version__}" + + +def default_headers(): + """ + :rtype: requests.structures.CaseInsensitiveDict + """ + return CaseInsensitiveDict( + { + "User-Agent": default_user_agent(), + "Accept-Encoding": DEFAULT_ACCEPT_ENCODING, + "Accept": "*/*", + "Connection": "keep-alive", + } + ) + + +def parse_header_links(value): + """Return a list of parsed link headers proxies. + + i.e. Link: ; rel=front; type="image/jpeg",; rel=back;type="image/jpeg" + + :rtype: list + """ + + links = [] + + replace_chars = " '\"" + + value = value.strip(replace_chars) + if not value: + return links + + for val in re.split(", *<", value): + try: + url, params = val.split(";", 1) + except ValueError: + url, params = val, "" + + link = {"url": url.strip("<> '\"")} + + for param in params.split(";"): + try: + key, value = param.split("=") + except ValueError: + break + + link[key.strip(replace_chars)] = value.strip(replace_chars) + + links.append(link) + + return links + + +# Null bytes; no need to recreate these on each call to guess_json_utf +_null = "\x00".encode("ascii") # encoding to ASCII for Python 3 +_null2 = _null * 2 +_null3 = _null * 3 + + +def guess_json_utf(data): + """ + :rtype: str + """ + # JSON always starts with two ASCII characters, so detection is as + # easy as counting the nulls and from their location and count + # determine the encoding. Also detect a BOM, if present. + sample = data[:4] + if sample in (codecs.BOM_UTF32_LE, codecs.BOM_UTF32_BE): + return "utf-32" # BOM included + if sample[:3] == codecs.BOM_UTF8: + return "utf-8-sig" # BOM included, MS style (discouraged) + if sample[:2] in (codecs.BOM_UTF16_LE, codecs.BOM_UTF16_BE): + return "utf-16" # BOM included + nullcount = sample.count(_null) + if nullcount == 0: + return "utf-8" + if nullcount == 2: + if sample[::2] == _null2: # 1st and 3rd are null + return "utf-16-be" + if sample[1::2] == _null2: # 2nd and 4th are null + return "utf-16-le" + # Did not detect 2 valid UTF-16 ascii-range characters + if nullcount == 3: + if sample[:3] == _null3: + return "utf-32-be" + if sample[1:] == _null3: + return "utf-32-le" + # Did not detect a valid UTF-32 ascii-range character + return None + + +def prepend_scheme_if_needed(url, new_scheme): + """Given a URL that may or may not have a scheme, prepend the given scheme. + Does not replace a present scheme with the one provided as an argument. + + :rtype: str + """ + parsed = parse_url(url) + scheme, auth, host, port, path, query, fragment = parsed + + # A defect in urlparse determines that there isn't a netloc present in some + # urls. We previously assumed parsing was overly cautious, and swapped the + # netloc and path. Due to a lack of tests on the original defect, this is + # maintained with parse_url for backwards compatibility. + netloc = parsed.netloc + if not netloc: + netloc, path = path, netloc + + if auth: + # parse_url doesn't provide the netloc with auth + # so we'll add it ourselves. + netloc = "@".join([auth, netloc]) + if scheme is None: + scheme = new_scheme + if path is None: + path = "" + + return urlunparse((scheme, netloc, path, "", query, fragment)) + + +def get_auth_from_url(url): + """Given a url with authentication components, extract them into a tuple of + username,password. + + :rtype: (str,str) + """ + parsed = urlparse(url) + + try: + auth = (unquote(parsed.username), unquote(parsed.password)) + except (AttributeError, TypeError): + auth = ("", "") + + return auth + + +def check_header_validity(header): + """Verifies that header parts don't contain leading whitespace + reserved characters, or return characters. + + :param header: tuple, in the format (name, value). + """ + name, value = header + _validate_header_part(header, name, 0) + _validate_header_part(header, value, 1) + + +def _validate_header_part(header, header_part, header_validator_index): + if isinstance(header_part, str): + validator = _HEADER_VALIDATORS_STR[header_validator_index] + elif isinstance(header_part, bytes): + validator = _HEADER_VALIDATORS_BYTE[header_validator_index] + else: + raise InvalidHeader( + f"Header part ({header_part!r}) from {header} " + f"must be of type str or bytes, not {type(header_part)}" + ) + + if not validator.match(header_part): + header_kind = "name" if header_validator_index == 0 else "value" + raise InvalidHeader( + f"Invalid leading whitespace, reserved character(s), or return " + f"character(s) in header {header_kind}: {header_part!r}" + ) + + +def urldefragauth(url): + """ + Given a url remove the fragment and the authentication part. + + :rtype: str + """ + scheme, netloc, path, params, query, fragment = urlparse(url) + + # see func:`prepend_scheme_if_needed` + if not netloc: + netloc, path = path, netloc + + netloc = netloc.rsplit("@", 1)[-1] + + return urlunparse((scheme, netloc, path, params, query, "")) + + +def rewind_body(prepared_request): + """Move file pointer back to its recorded starting position + so it can be read again on redirect. + """ + body_seek = getattr(prepared_request.body, "seek", None) + if body_seek is not None and isinstance( + prepared_request._body_position, integer_types + ): + try: + body_seek(prepared_request._body_position) + except OSError: + raise UnrewindableBodyError( + "An error occurred when rewinding request body for redirect." + ) + else: + raise UnrewindableBodyError("Unable to rewind request body for redirect.") diff --git a/moondream/lib/python3.10/site-packages/pip/_vendor/rich/__pycache__/__init__.cpython-310.pyc b/moondream/lib/python3.10/site-packages/pip/_vendor/rich/__pycache__/__init__.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..127786c1fa1dce2faa49f9de04ea8812c0625720 Binary files /dev/null and b/moondream/lib/python3.10/site-packages/pip/_vendor/rich/__pycache__/__init__.cpython-310.pyc differ diff --git a/moondream/lib/python3.10/site-packages/pip/_vendor/rich/__pycache__/json.cpython-310.pyc b/moondream/lib/python3.10/site-packages/pip/_vendor/rich/__pycache__/json.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..a7fd6c4eccf9819540b54b32ff4f8a103f8df43c Binary files /dev/null and b/moondream/lib/python3.10/site-packages/pip/_vendor/rich/__pycache__/json.cpython-310.pyc differ diff --git a/moondream/lib/python3.10/site-packages/pip/_vendor/rich/__pycache__/terminal_theme.cpython-310.pyc b/moondream/lib/python3.10/site-packages/pip/_vendor/rich/__pycache__/terminal_theme.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..ac2ffa84494cb547429e06479631fe5441d51112 Binary files /dev/null and b/moondream/lib/python3.10/site-packages/pip/_vendor/rich/__pycache__/terminal_theme.cpython-310.pyc differ