code
stringlengths
26
870k
docstring
stringlengths
1
65.6k
func_name
stringlengths
1
194
language
stringclasses
1 value
repo
stringlengths
8
68
path
stringlengths
5
194
url
stringlengths
46
254
license
stringclasses
4 values
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))
Convert subtitle format to VTT and process the video to ensure it meets the HTML5 requirements.
_format_subtitle
python
gradio-app/gradio
gradio/components/video.py
https://github.com/gradio-app/gradio/blob/master/gradio/components/video.py
Apache-2.0
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
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.
combine_stream
python
gradio-app/gradio
gradio/components/video.py
https://github.com/gradio-app/gradio/blob/master/gradio/components/video.py
Apache-2.0
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)
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.
__init__
python
gradio-app/gradio
gradio/components/timer.py
https://github.com/gradio-app/gradio/blob/master/gradio/components/timer.py
Apache-2.0
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
Parameters: payload: The interval of the timer as a float or None. Returns: The interval of the timer as a float.
preprocess
python
gradio-app/gradio
gradio/components/timer.py
https://github.com/gradio-app/gradio/blob/master/gradio/components/timer.py
Apache-2.0
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
Parameters: value: The interval of the timer as a float or None. Returns: The interval of the timer as a float.
postprocess
python
gradio-app/gradio
gradio/components/timer.py
https://github.com/gradio-app/gradio/blob/master/gradio/components/timer.py
Apache-2.0
def __init__( self, value: str | Callable | None = None, *, 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: default text to provide in color picker. If a function is provided, the function will be called each time the app loads to set the initial value of this 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, will be rendered as an editable color picker; if False, editing will be disabled. If not provided, this is inferred based on whether the component is used as an input or output. 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, )
Parameters: value: default text to provide in color picker. If a function is provided, the function will be called each time the app loads to set the initial value of this 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, will be rendered as an editable color picker; if False, editing will be disabled. If not provided, this is inferred based on whether the component is used as an input or output. 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.
__init__
python
gradio-app/gradio
gradio/components/color_picker.py
https://github.com/gradio-app/gradio/blob/master/gradio/components/color_picker.py
Apache-2.0
def preprocess(self, payload: str | None) -> str | None: """ Parameters: payload: Color as hex string Returns: Passes selected color value as a hex `str` into the function. """ if payload is None: return None else: return str(payload)
Parameters: payload: Color as hex string Returns: Passes selected color value as a hex `str` into the function.
preprocess
python
gradio-app/gradio
gradio/components/color_picker.py
https://github.com/gradio-app/gradio/blob/master/gradio/components/color_picker.py
Apache-2.0
def postprocess(self, value: str | None) -> str | None: """ Parameters: value: Expects a hex `str` returned from function and sets color picker value to it. Returns: A `str` value that is set as the color picker value. """ if value is None: return None else: return str(value)
Parameters: value: Expects a hex `str` returned from function and sets color picker value to it. Returns: A `str` value that is set as the color picker value.
postprocess
python
gradio-app/gradio
gradio/components/color_picker.py
https://github.com/gradio-app/gradio/blob/master/gradio/components/color_picker.py
Apache-2.0
def __init__( self, value: str | Callable = "Run", *, every: Timer | float | None = None, inputs: Component | Sequence[Component] | set[Component] | None = None, variant: Literal["primary", "secondary", "stop", "huggingface"] = "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, ): """ Parameters: value: default text for the button to display. If a function is provided, the function will be called each time the app loads to set the initial value of this 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__( every=every, inputs=inputs, visible=visible, elem_id=elem_id, elem_classes=elem_classes, render=render, key=key, value=value, interactive=interactive, scale=scale, min_width=min_width, ) self.icon = self.serve_static_file(icon) self.variant = variant self.size = size self.link = link
Parameters: value: default text for the button to display. If a function is provided, the function will be called each time the app loads to set the initial value of this 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.
__init__
python
gradio-app/gradio
gradio/components/button.py
https://github.com/gradio-app/gradio/blob/master/gradio/components/button.py
Apache-2.0
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
Parameters: payload: string corresponding to the button label Returns: (Rarely used) the `str` corresponding to the button label when the button is clicked
preprocess
python
gradio-app/gradio
gradio/components/button.py
https://github.com/gradio-app/gradio/blob/master/gradio/components/button.py
Apache-2.0
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 str(value)
Parameters: value: string corresponding to the button label Returns: Expects a `str` value that is set as the button label
postprocess
python
gradio-app/gradio
gradio/components/button.py
https://github.com/gradio-app/gradio/blob/master/gradio/components/button.py
Apache-2.0
def __init__( self, label: str = "Upload a File", value: str | list[str] | 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, type: Literal["filepath", "binary"] = "filepath", file_count: Literal["single", "multiple", "directory"] = "single", file_types: list[str] | None = None, ): """ Parameters: label: Text to display on the button. Defaults to "Upload a File". value: File or list of files to upload by default. 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. 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. 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 type of files to be uploaded. "file" allows any file to be uploaded, "image" allows only image files to be uploaded, "audio" allows only audio files to be uploaded, "video" allows only video files to be uploaded, "text" allows only text files to be uploaded. """ 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}" ) self.type = type self.file_count = file_count if file_count == "directory" and file_types is not None: warnings.warn( "The `file_types` parameter is ignored when `file_count` is 'directory'." ) 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__}" ) if self.file_count in ["multiple", "directory"]: self.data_model = ListFiles else: self.data_model = FileData self.size = size self.file_types = file_types 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)
Parameters: label: Text to display on the button. Defaults to "Upload a File". value: File or list of files to upload by default. 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. 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. 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 type of files to be uploaded. "file" allows any file to be uploaded, "image" allows only image files to be uploaded, "audio" allows only audio files to be uploaded, "video" allows only video files to be uploaded, "text" allows only text files to be uploaded.
__init__
python
gradio-app/gradio
gradio/components/upload_button.py
https://github.com/gradio-app/gradio/blob/master/gradio/components/upload_button.py
Apache-2.0
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
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`.
preprocess
python
gradio-app/gradio
gradio/components/upload_button.py
https://github.com/gradio-app/gradio/blob/master/gradio/components/upload_button.py
Apache-2.0
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, )
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.
postprocess
python
gradio-app/gradio
gradio/components/upload_button.py
https://github.com/gradio-app/gradio/blob/master/gradio/components/upload_button.py
Apache-2.0
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()
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 ({})".
__init__
python
gradio-app/gradio
gradio/components/login_button.py
https://github.com/gradio-app/gradio/blob/master/gradio/components/login_button.py
Apache-2.0
def __init__( self, choices: Sequence[str | int | float | tuple[str, str | int | float]] | None = None, *, value: str | int | float | Callable | None = None, type: Literal["value", "index"] = "value", 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 select from. An option can also be a tuple of the form (name, value), where name is the displayed name of the radio button and value is the value to be passed to the function, or returned by the function. value: The option selected by default. If None, no option is selected by default. If a function is provided, the function will be called each time the app loads to set the initial value of this 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. 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 width compared to adjacent Components in a Row. For example, if Component A has scale=2, and Component B has scale=1, A will be twice as wide as B. Should be an integer. 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 radio group will be selectable; if False, selection will be disabled. If not provided, this is inferred based on whether the component is used as an input or output. 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. """ self.choices = ( # Although we expect choices to be a list of tuples, it can be a list of tuples 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 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, )
Parameters: choices: A list of string or numeric options to select from. An option can also be a tuple of the form (name, value), where name is the displayed name of the radio button and value is the value to be passed to the function, or returned by the function. value: The option selected by default. If None, no option is selected by default. If a function is provided, the function will be called each time the app loads to set the initial value of this 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. 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 width compared to adjacent Components in a Row. For example, if Component A has scale=2, and Component B has scale=1, A will be twice as wide as B. Should be an integer. 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 radio group will be selectable; if False, selection will be disabled. If not provided, this is inferred based on whether the component is used as an input or output. 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.
__init__
python
gradio-app/gradio
gradio/components/radio.py
https://github.com/gradio-app/gradio/blob/master/gradio/components/radio.py
Apache-2.0
def preprocess(self, payload: str | int | float | None) -> str | int | float | None: """ Parameters: payload: Selected choice in the radio group Returns: Passes the value of the selected radio button as a `str | int | float`, or its index as an `int` into the function, depending on `type`. """ if payload is None: return None choice_values = [value for _, value in self.choices] if payload not in choice_values: raise Error( f"Value: {payload!r} (type: {type(payload)}) is not in the list of choices: {choice_values}" ) if self.type == "value": return payload elif self.type == "index": return choice_values.index(payload) else: raise ValueError( f"Unknown type: {self.type}. Please choose from: 'value', 'index'." )
Parameters: payload: Selected choice in the radio group Returns: Passes the value of the selected radio button as a `str | int | float`, or its index as an `int` into the function, depending on `type`.
preprocess
python
gradio-app/gradio
gradio/components/radio.py
https://github.com/gradio-app/gradio/blob/master/gradio/components/radio.py
Apache-2.0
def postprocess(self, value: str | int | float | None) -> str | int | float | None: """ Parameters: value: Expects a `str | int | float` corresponding to the value of the radio button to be selected Returns: The same value """ return value
Parameters: value: Expects a `str | int | float` corresponding to the value of the radio button to be selected Returns: The same value
postprocess
python
gradio-app/gradio
gradio/components/radio.py
https://github.com/gradio-app/gradio/blob/master/gradio/components/radio.py
Apache-2.0
def __init__( self, value: Any | None = None, *, format: str = "png" if wasm_utils.IS_WASM else "webp", # webp is a good default for speed (see #7845) but can't be used in Wasm because the the version of matplotlib used in Wasm (3.5.2 in the case of Pyodide 0.26.1) doesn't support it. 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, 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: Optionally, supply a default plot object to display, must be a matplotlib, plotly, altair, or bokeh figure, or a callable. If a function is provided, the function will be called each time the app loads to set the initial value of this component. format: File format in which to send matplotlib plots to the front end, such as 'jpg' or 'png'. 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. 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. """ self.format = format super().__init__( label=label, every=every, inputs=inputs, 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, value=value, )
Parameters: value: Optionally, supply a default plot object to display, must be a matplotlib, plotly, altair, or bokeh figure, or a callable. If a function is provided, the function will be called each time the app loads to set the initial value of this component. format: File format in which to send matplotlib plots to the front end, such as 'jpg' or 'png'. 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. 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.
__init__
python
gradio-app/gradio
gradio/components/plot.py
https://github.com/gradio-app/gradio/blob/master/gradio/components/plot.py
Apache-2.0
def preprocess(self, payload: PlotData | None) -> PlotData | None: """ Parameters: payload: The data to display in the plot. Returns: (Rarely used) passes the data displayed in the plot as an PlotData dataclass, which includes the plot information as a JSON string, as well as the type of chart and the plotting library. """ return payload
Parameters: payload: The data to display in the plot. Returns: (Rarely used) passes the data displayed in the plot as an PlotData dataclass, which includes the plot information as a JSON string, as well as the type of chart and the plotting library.
preprocess
python
gradio-app/gradio
gradio/components/plot.py
https://github.com/gradio-app/gradio/blob/master/gradio/components/plot.py
Apache-2.0
def postprocess(self, value: Any) -> PlotData | None: """ Parameters: value: Expects plot data in one of these formats: a matplotlib.Figure, bokeh.Model, plotly.Figure, or altair.Chart object. Returns: PlotData: A dataclass containing the plot data as a JSON string, as well as the type of chart and the plotting library. """ if value is None: return None if isinstance(value, PlotData): return value if isinstance(value, ModuleType) or "matplotlib" in value.__module__: dtype = "matplotlib" out_y = processing_utils.encode_plot_to_base64(value, self.format) elif "bokeh" in value.__module__: dtype = "bokeh" from bokeh.embed import json_item out_y = json.dumps(json_item(value)) else: is_altair = "altair" in value.__module__ dtype = "altair" if is_altair else "plotly" out_y = value.to_json() return PlotData(type=dtype, plot=out_y)
Parameters: value: Expects plot data in one of these formats: a matplotlib.Figure, bokeh.Model, plotly.Figure, or altair.Chart object. Returns: PlotData: A dataclass containing the plot data as a JSON string, as well as the type of chart and the plotting library.
postprocess
python
gradio-app/gradio
gradio/components/plot.py
https://github.com/gradio-app/gradio/blob/master/gradio/components/plot.py
Apache-2.0
def __init__( self, value: Any, _api_info: dict[str, str], label: str = "API", ): """ Parameters: value: default value. """ self._api_info = _api_info super().__init__(value=value, label=label)
Parameters: value: default value.
__init__
python
gradio-app/gradio
gradio/components/api_component.py
https://github.com/gradio-app/gradio/blob/master/gradio/components/api_component.py
Apache-2.0
def __init__( self, value: Mapping[str, Parameter] | None = None, language: Literal["python", "typescript"] = "python", linkify: list[str] | None = None, every: Timer | float | None = None, inputs: Component | Sequence[Component] | set[Component] | None = None, render: bool = True, key: int | str | None = None, header: str | None = "Parameters", anchor_links: bool | str = False, ): """ Parameters: value: A dictionary of dictionaries. The key in the outer dictionary is the parameter name, while the inner dictionary has keys "type", "description", and "default" for each parameter. Markdown links are supported in "description". language: The language to display the code in. One of "python" or "typescript". linkify: A list of strings to linkify. If any of these strings is found in the description, it will be rendered as a link. 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. 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. header: The header to display above the table of parameters, also includes a toggle button that closes/opens all details at once. If None, no header will be displayed. anchor_links: If True, creates anchor links for each parameter that can be used to link directly to that parameter. If a string, creates anchor links with the given string as the prefix to prevent conflicts with other ParamViewer components. """ self.value = value or {} self.language = language self.linkify = linkify self.header = header self.anchor_links = anchor_links super().__init__( every=every, inputs=inputs, value=value, render=render, key=key, )
Parameters: value: A dictionary of dictionaries. The key in the outer dictionary is the parameter name, while the inner dictionary has keys "type", "description", and "default" for each parameter. Markdown links are supported in "description". language: The language to display the code in. One of "python" or "typescript". linkify: A list of strings to linkify. If any of these strings is found in the description, it will be rendered as a link. 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. 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. header: The header to display above the table of parameters, also includes a toggle button that closes/opens all details at once. If None, no header will be displayed. anchor_links: If True, creates anchor links for each parameter that can be used to link directly to that parameter. If a string, creates anchor links with the given string as the prefix to prevent conflicts with other ParamViewer components.
__init__
python
gradio-app/gradio
gradio/components/paramviewer.py
https://github.com/gradio-app/gradio/blob/master/gradio/components/paramviewer.py
Apache-2.0
def preprocess(self, payload: dict[str, Parameter]) -> dict[str, Parameter]: """ Parameters: payload: A `dict[str, dict]`. The key in the outer dictionary is the parameter name, while the inner dictionary has keys "type", "description", and "default" for each parameter. Returns: (Rarely used) passes value as a `dict[str, dict]`. The key in the outer dictionary is the parameter name, while the inner dictionary has keys "type", "description", and "default" for each parameter. """ return payload
Parameters: payload: A `dict[str, dict]`. The key in the outer dictionary is the parameter name, while the inner dictionary has keys "type", "description", and "default" for each parameter. Returns: (Rarely used) passes value as a `dict[str, dict]`. The key in the outer dictionary is the parameter name, while the inner dictionary has keys "type", "description", and "default" for each parameter.
preprocess
python
gradio-app/gradio
gradio/components/paramviewer.py
https://github.com/gradio-app/gradio/blob/master/gradio/components/paramviewer.py
Apache-2.0
def postprocess(self, value: dict[str, Parameter]) -> dict[str, Parameter]: """ Parameters: value: Expects value as a `dict[str, dict]`. The key in the outer dictionary is the parameter name, while the inner dictionary has keys "type", "description", and "default" for each parameter. Returns: The same value. """ return value
Parameters: value: Expects value as a `dict[str, dict]`. The key in the outer dictionary is the parameter name, while the inner dictionary has keys "type", "description", and "default" for each parameter. Returns: The same value.
postprocess
python
gradio-app/gradio
gradio/components/paramviewer.py
https://github.com/gradio-app/gradio/blob/master/gradio/components/paramviewer.py
Apache-2.0
def __init__( self, value: str | Callable | None = None, *, label: str | None = None, every: Timer | float | None = None, inputs: Component | Sequence[Component] | set[Component] | None = None, show_label: bool = False, visible: bool = True, elem_id: str | None = None, elem_classes: list[str] | str | None = None, render: bool = True, key: int | str | None = None, min_height: int | None = None, max_height: int | None = None, container: bool = False, padding: bool = True, ): """ Parameters: value: The HTML content to display. Only static HTML is rendered (e.g. no JavaScript. To render JavaScript, use the `js` or `head` parameters in the `Blocks` constructor). If a function is provided, the function will be called each time the app loads to set the initial value of this component. label: The label for this component. Is 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, the label will be displayed. If False, the label will be hidden. 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. min_height: The minimum height of the component, specified in pixels if a number is passed, or in CSS units if a string is passed. If HTML content exceeds the height, the component will expand to fit the content. max_height: The maximum height of the component, specified in pixels if a number is passed, or in CSS units if a string is passed. If content exceeds the height, the component will scroll. container: If True, the HTML component will be displayed in a container. Default is False. padding: If True, the HTML component will have a certain padding (set by the `--block-padding` CSS variable) in all directions. Default is True. """ self.min_height = min_height self.max_height = max_height self.padding = padding super().__init__( label=label, every=every, inputs=inputs, show_label=show_label, visible=visible, elem_id=elem_id, elem_classes=elem_classes, render=render, key=key, value=value, container=container, )
Parameters: value: The HTML content to display. Only static HTML is rendered (e.g. no JavaScript. To render JavaScript, use the `js` or `head` parameters in the `Blocks` constructor). If a function is provided, the function will be called each time the app loads to set the initial value of this component. label: The label for this component. Is 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, the label will be displayed. If False, the label will be hidden. 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. min_height: The minimum height of the component, specified in pixels if a number is passed, or in CSS units if a string is passed. If HTML content exceeds the height, the component will expand to fit the content. max_height: The maximum height of the component, specified in pixels if a number is passed, or in CSS units if a string is passed. If content exceeds the height, the component will scroll. container: If True, the HTML component will be displayed in a container. Default is False. padding: If True, the HTML component will have a certain padding (set by the `--block-padding` CSS variable) in all directions. Default is True.
__init__
python
gradio-app/gradio
gradio/components/html.py
https://github.com/gradio-app/gradio/blob/master/gradio/components/html.py
Apache-2.0
def preprocess(self, payload: str | None) -> str | None: """ Parameters: payload: string corresponding to the HTML Returns: (Rarely used) passes the HTML as a `str`. """ return payload
Parameters: payload: string corresponding to the HTML Returns: (Rarely used) passes the HTML as a `str`.
preprocess
python
gradio-app/gradio
gradio/components/html.py
https://github.com/gradio-app/gradio/blob/master/gradio/components/html.py
Apache-2.0
def postprocess(self, value: str | None) -> str | None: """ Parameters: value: Expects a `str` consisting of valid HTML. Returns: Returns the HTML string. """ return value
Parameters: value: Expects a `str` consisting of valid HTML. Returns: Returns the HTML string.
postprocess
python
gradio-app/gradio
gradio/components/html.py
https://github.com/gradio-app/gradio/blob/master/gradio/components/html.py
Apache-2.0
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
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.
__init__
python
gradio-app/gradio
gradio/components/datetime.py
https://github.com/gradio-app/gradio/blob/master/gradio/components/datetime.py
Apache-2.0
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()
Parameters: payload: the text entered in the textarea. Returns: Passes text value as a {str} into the function.
preprocess
python
gradio-app/gradio
gradio/components/datetime.py
https://github.com/gradio-app/gradio/blob/master/gradio/components/datetime.py
Apache-2.0
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)
Parameters: value: Expects a tuple pair of datetimes. Returns: A tuple pair of timestamps.
postprocess
python
gradio-app/gradio
gradio/components/datetime.py
https://github.com/gradio-app/gradio/blob/master/gradio/components/datetime.py
Apache-2.0
def __init__( self, value: dict[str, float] | str | float | Callable | None = None, *, num_top_classes: int | 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, visible: bool = True, elem_id: str | None = None, elem_classes: list[str] | str | None = None, render: bool = True, key: int | str | None = None, color: str | None = None, show_heading: bool = True, ): """ Parameters: value: Default value to show in the component. If a str or number is provided, simply displays the string or number. If a {Dict[str, float]} of classes and confidences is provided, displays the top class on top and the `num_top_classes` below, along with their confidence bars. If a function is provided, the function will be called each time the app loads to set the initial value of this component. num_top_classes: number of most confident classes to show. 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. 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. color: The background color of the label (either a valid css color name or hexadecimal string). show_heading: If False, the heading will not be displayed if a dictionary of labels and confidences is provided. The heading will still be visible if the value is a string or number. """ self.num_top_classes = num_top_classes self.color = color self.show_heading = show_heading super().__init__( label=label, every=every, inputs=inputs, 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, value=value, )
Parameters: value: Default value to show in the component. If a str or number is provided, simply displays the string or number. If a {Dict[str, float]} of classes and confidences is provided, displays the top class on top and the `num_top_classes` below, along with their confidence bars. If a function is provided, the function will be called each time the app loads to set the initial value of this component. num_top_classes: number of most confident classes to show. 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. 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. color: The background color of the label (either a valid css color name or hexadecimal string). show_heading: If False, the heading will not be displayed if a dictionary of labels and confidences is provided. The heading will still be visible if the value is a string or number.
__init__
python
gradio-app/gradio
gradio/components/label.py
https://github.com/gradio-app/gradio/blob/master/gradio/components/label.py
Apache-2.0
def preprocess( self, payload: LabelData | None ) -> dict[str, float] | str | int | float | None: """ Parameters: payload: An instance of `LabelData` containing the label and confidences. Returns: Depending on the value, passes the label as a `str | int | float`, or the labels and confidences as a `dict[str, float]`. """ if payload is None: return None if payload.confidences is None: return payload.label return { d["label"]: d["confidence"] for d in payload.model_dump()["confidences"] }
Parameters: payload: An instance of `LabelData` containing the label and confidences. Returns: Depending on the value, passes the label as a `str | int | float`, or the labels and confidences as a `dict[str, float]`.
preprocess
python
gradio-app/gradio
gradio/components/label.py
https://github.com/gradio-app/gradio/blob/master/gradio/components/label.py
Apache-2.0
def postprocess( self, value: dict[str | float, float] | str | int | float | None ) -> LabelData | dict | None: """ Parameters: value: Expects a `dict[str, float]` of classes and confidences, or `str` with just the class or an `int | float` for regression outputs, or a `str` path to a .json file containing a json dictionary in one of the preceding formats. Returns: Returns a `LabelData` object with the label and confidences, or a `dict` of the same format, or a `str` or `int` or `float` if the input was a single label. """ if value is None or value == {}: return {} if isinstance(value, str) and value.endswith(".json") and Path(value).exists(): return LabelData(**json.loads(Path(value).read_text())) if isinstance(value, (str, float, int)): return LabelData(label=str(value)) if isinstance(value, dict): if "confidences" in value and isinstance(value["confidences"], dict): value = value["confidences"] value = {c["label"]: c["confidence"] for c in value} sorted_pred = sorted( value.items(), key=operator.itemgetter(1), reverse=True ) if self.num_top_classes is not None: sorted_pred = sorted_pred[: self.num_top_classes] return LabelData( label=sorted_pred[0][0], confidences=[ LabelConfidence(label=pred[0], confidence=pred[1]) for pred in sorted_pred ], ) raise ValueError( "The `Label` output interface expects one of: a string label, or an int label, a " "float label, or a dictionary whose keys are labels and values are confidences. " f"Instead, got a {type(value)}" )
Parameters: value: Expects a `dict[str, float]` of classes and confidences, or `str` with just the class or an `int | float` for regression outputs, or a `str` path to a .json file containing a json dictionary in one of the preceding formats. Returns: Returns a `LabelData` object with the label and confidences, or a `dict` of the same format, or a `str` or `int` or `float` if the input was a single label.
postprocess
python
gradio-app/gradio
gradio/components/label.py
https://github.com/gradio-app/gradio/blob/master/gradio/components/label.py
Apache-2.0
def preprocess(self, payload: Any) -> Any: """ Any preprocessing needed to be performed on function input. Parameters: payload: The input data received by the component from the frontend. Returns: The preprocessed input data sent to the user's function in the backend. """ return payload
Any preprocessing needed to be performed on function input. Parameters: payload: The input data received by the component from the frontend. Returns: The preprocessed input data sent to the user's function in the backend.
preprocess
python
gradio-app/gradio
gradio/components/base.py
https://github.com/gradio-app/gradio/blob/master/gradio/components/base.py
Apache-2.0
def postprocess(self, value): """ Any postprocessing needed to be performed on function output. Parameters: value: The output data received by the component from the user's function in the backend. Returns: The postprocessed output data sent to the frontend. """ return value
Any postprocessing needed to be performed on function output. Parameters: value: The output data received by the component from the user's function in the backend. Returns: The postprocessed output data sent to the frontend.
postprocess
python
gradio-app/gradio
gradio/components/base.py
https://github.com/gradio-app/gradio/blob/master/gradio/components/base.py
Apache-2.0
def process_example(self, value): """ Process the input data in a way that can be displayed by the examples dataset component in the front-end. For example, only return the name of a file as opposed to a full path. Or get the head of a dataframe. The return value must be able to be json-serializable to put in the config. """ pass
Process the input data in a way that can be displayed by the examples dataset component in the front-end. For example, only return the name of a file as opposed to a full path. Or get the head of a dataframe. The return value must be able to be json-serializable to put in the config.
process_example
python
gradio-app/gradio
gradio/components/base.py
https://github.com/gradio-app/gradio/blob/master/gradio/components/base.py
Apache-2.0
def api_info(self) -> dict[str, list[str]]: """ The typing information for this component as a dictionary whose values are a list of 2 strings: [Python type, language-agnostic description]. Keys of the dictionary are: raw_input, raw_output, serialized_input, serialized_output """ pass
The typing information for this component as a dictionary whose values are a list of 2 strings: [Python type, language-agnostic description]. Keys of the dictionary are: raw_input, raw_output, serialized_input, serialized_output
api_info
python
gradio-app/gradio
gradio/components/base.py
https://github.com/gradio-app/gradio/blob/master/gradio/components/base.py
Apache-2.0
def example_inputs(self) -> Any: """ Deprecated and replaced by `example_payload()` and `example_value()`. """ pass
Deprecated and replaced by `example_payload()` and `example_value()`.
example_inputs
python
gradio-app/gradio
gradio/components/base.py
https://github.com/gradio-app/gradio/blob/master/gradio/components/base.py
Apache-2.0
def flag(self, payload: Any | GradioDataModel, flag_dir: str | Path = "") -> str: """ Write the component's value to a format that can be stored in a csv or jsonl format for flagging. """ pass
Write the component's value to a format that can be stored in a csv or jsonl format for flagging.
flag
python
gradio-app/gradio
gradio/components/base.py
https://github.com/gradio-app/gradio/blob/master/gradio/components/base.py
Apache-2.0
def read_from_flag(self, payload: Any) -> GradioDataModel | Any: """ Convert the data from the csv or jsonl file into the component state. """ return payload
Convert the data from the csv or jsonl file into the component state.
read_from_flag
python
gradio-app/gradio
gradio/components/base.py
https://github.com/gradio-app/gradio/blob/master/gradio/components/base.py
Apache-2.0
def skip_api(self) -> bool: """Whether this component should be skipped from the api return value"""
Whether this component should be skipped from the api return value
skip_api
python
gradio-app/gradio
gradio/components/base.py
https://github.com/gradio-app/gradio/blob/master/gradio/components/base.py
Apache-2.0
def attach_load_event( self, callable: Callable, every: Timer | float | None, inputs: Component | Sequence[Component] | set[Component] | None = None, ): """Add an event that runs `callable`, optionally at interval specified by `every`.""" if isinstance(inputs, Component): inputs = [inputs] changeable_events: list[tuple[Block, str]] = ( [(i, "change") for i in inputs if hasattr(i, "change")] if inputs else [] ) if isinstance(every, (int, float)): from gradio.components import Timer every = Timer(every) if every: changeable_events.append((every, "tick")) self.load_event_to_attach = ( callable, changeable_events, inputs, )
Add an event that runs `callable`, optionally at interval specified by `every`.
attach_load_event
python
gradio-app/gradio
gradio/components/base.py
https://github.com/gradio-app/gradio/blob/master/gradio/components/base.py
Apache-2.0
def process_example(self, value): """ Process the input data in a way that can be displayed by the examples dataset component in the front-end. By default, this calls the `.postprocess()` method of the component. However, if the `.postprocess()` method is computationally intensive, or returns a large payload, a custom implementation may be appropriate. For example, the `process_example()` method of the `gr.Audio()` component only returns the name of the file, not the processed audio file. The `.process_example()` method of the `gr.Dataframe()` returns the head of a dataframe instead of the full dataframe. The return value of this method must be json-serializable to put in the config. """ return self.postprocess(value)
Process the input data in a way that can be displayed by the examples dataset component in the front-end. By default, this calls the `.postprocess()` method of the component. However, if the `.postprocess()` method is computationally intensive, or returns a large payload, a custom implementation may be appropriate. For example, the `process_example()` method of the `gr.Audio()` component only returns the name of the file, not the processed audio file. The `.process_example()` method of the `gr.Dataframe()` returns the head of a dataframe instead of the full dataframe. The return value of this method must be json-serializable to put in the config.
process_example
python
gradio-app/gradio
gradio/components/base.py
https://github.com/gradio-app/gradio/blob/master/gradio/components/base.py
Apache-2.0
def as_example(self, value): """Deprecated and replaced by `process_example()`.""" return self.process_example(value)
Deprecated and replaced by `process_example()`.
as_example
python
gradio-app/gradio
gradio/components/base.py
https://github.com/gradio-app/gradio/blob/master/gradio/components/base.py
Apache-2.0
def example_inputs(self) -> Any: """Deprecated and replaced by `example_payload()` and `example_value()`.""" return self.example_payload()
Deprecated and replaced by `example_payload()` and `example_value()`.
example_inputs
python
gradio-app/gradio
gradio/components/base.py
https://github.com/gradio-app/gradio/blob/master/gradio/components/base.py
Apache-2.0
def example_payload(self) -> Any: """ An example input data for this component, e.g. what is passed to this component's preprocess() method. This is used to generate the docs for the View API page for Gradio apps using this component. """ raise NotImplementedError()
An example input data for this component, e.g. what is passed to this component's preprocess() method. This is used to generate the docs for the View API page for Gradio apps using this component.
example_payload
python
gradio-app/gradio
gradio/components/base.py
https://github.com/gradio-app/gradio/blob/master/gradio/components/base.py
Apache-2.0
def example_value(self) -> Any: """ An example output data for this component, e.g. what is passed to this component's postprocess() method. This is used to generate an example value if this component is used as a template for a custom component. """ raise NotImplementedError()
An example output data for this component, e.g. what is passed to this component's postprocess() method. This is used to generate an example value if this component is used as a template for a custom component.
example_value
python
gradio-app/gradio
gradio/components/base.py
https://github.com/gradio-app/gradio/blob/master/gradio/components/base.py
Apache-2.0
def api_info(self) -> dict[str, Any]: """ The typing information for this component as a dictionary whose values are a list of 2 strings: [Python type, language-agnostic description]. Keys of the dictionary are: raw_input, raw_output, serialized_input, serialized_output """ if self.data_model is not None: schema = self.data_model.model_json_schema() desc = schema.pop("description", None) schema["additional_description"] = desc return schema raise NotImplementedError( f"The api_info method has not been implemented for {self.get_block_name()}" )
The typing information for this component as a dictionary whose values are a list of 2 strings: [Python type, language-agnostic description]. Keys of the dictionary are: raw_input, raw_output, serialized_input, serialized_output
api_info
python
gradio-app/gradio
gradio/components/base.py
https://github.com/gradio-app/gradio/blob/master/gradio/components/base.py
Apache-2.0
def flag(self, payload: Any, flag_dir: str | Path = "") -> str: """ Write the component's value to a format that can be stored in a csv or jsonl format for flagging. """ if self.data_model: payload = self.data_model.from_json(payload) Path(flag_dir).mkdir(exist_ok=True) payload = payload.copy_to_dir(flag_dir).model_dump() if isinstance(payload, BaseModel): payload = payload.model_dump() if not isinstance(payload, str): payload = json.dumps(payload) return payload
Write the component's value to a format that can be stored in a csv or jsonl format for flagging.
flag
python
gradio-app/gradio
gradio/components/base.py
https://github.com/gradio-app/gradio/blob/master/gradio/components/base.py
Apache-2.0
def read_from_flag(self, payload: Any): """ Convert the data from the csv or jsonl file into the component state. """ if self.data_model: return self.data_model.from_json(json.loads(payload)) return payload
Convert the data from the csv or jsonl file into the component state.
read_from_flag
python
gradio-app/gradio
gradio/components/base.py
https://github.com/gradio-app/gradio/blob/master/gradio/components/base.py
Apache-2.0
async def combine_stream( self, stream: list[bytes], desired_output_format: str | None = None, only_file=False, ) -> GradioDataModel | FileData: """Combine all of the stream chunks into a single file. This is needed for downloading the stream and for caching examples. If `only_file` is True, only the FileData corresponding to the file should be returned (needed for downloading the stream). The desired_output_format optionally converts the combined file. Should only be used for cached examples. """ pass
Combine all of the stream chunks into a single file. This is needed for downloading the stream and for caching examples. If `only_file` is True, only the FileData corresponding to the file should be returned (needed for downloading the stream). The desired_output_format optionally converts the combined file. Should only be used for cached examples.
combine_stream
python
gradio-app/gradio
gradio/components/base.py
https://github.com/gradio-app/gradio/blob/master/gradio/components/base.py
Apache-2.0
def check_streamable(self): """Used to check if streaming is supported given the input.""" pass
Used to check if streaming is supported given the input.
check_streamable
python
gradio-app/gradio
gradio/components/base.py
https://github.com/gradio-app/gradio/blob/master/gradio/components/base.py
Apache-2.0
def get_component_instance( comp: str | dict | Component, render: bool = False, unrender: bool = False ) -> Component: """ Returns a component instance from a string, dict, or Component object. Parameters: comp: the component to instantiate. If a string, must be the name of a component, e.g. "dropdown". If a dict, must have a "name" key, e.g. {"name": "dropdown", "choices": ["a", "b"]}. If a Component object, will be returned as is. render: whether to render the component. If True, renders the component (if not already rendered). If False, does not do anything. unrender: whether to unrender the component. If True, unrenders the the component (if already rendered) -- this is useful when constructing an Interface or ChatInterface inside of a Blocks. If False, does not do anything. """ if isinstance(comp, str): component_obj = component(comp, render=render) elif isinstance(comp, dict): name = comp.pop("name") component_cls = utils.component_or_layout_class(name) component_obj = component_cls(**comp, render=render) if isinstance(component_obj, BlockContext): raise ValueError(f"Invalid component: {name}") elif isinstance(comp, Component): component_obj = comp else: raise ValueError( f"Component must be provided as a `str` or `dict` or `Component` but is {comp}" ) if render and not component_obj.is_rendered: component_obj.render() elif unrender and component_obj.is_rendered: component_obj.unrender() if not isinstance(component_obj, Component): raise TypeError( f"Expected a Component instance, but got {component_obj.__class__}" ) return component_obj
Returns a component instance from a string, dict, or Component object. Parameters: comp: the component to instantiate. If a string, must be the name of a component, e.g. "dropdown". If a dict, must have a "name" key, e.g. {"name": "dropdown", "choices": ["a", "b"]}. If a Component object, will be returned as is. render: whether to render the component. If True, renders the component (if not already rendered). If False, does not do anything. unrender: whether to unrender the component. If True, unrenders the the component (if already rendered) -- this is useful when constructing an Interface or ChatInterface inside of a Blocks. If False, does not do anything.
get_component_instance
python
gradio-app/gradio
gradio/components/base.py
https://github.com/gradio-app/gradio/blob/master/gradio/components/base.py
Apache-2.0
def __init__( self, value: str | dict[str, str | list] | Callable | None = None, *, sources: list[Literal["upload", "microphone"]] | Literal["upload", "microphone"] | None = None, file_types: list[str] | None = None, file_count: Literal["single", "multiple", "directory"] = "single", lines: int = 1, max_lines: int = 20, placeholder: str | None = None, 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, autofocus: bool = False, autoscroll: bool = True, elem_classes: list[str] | str | None = None, render: bool = True, key: int | str | None = None, text_align: Literal["left", "right"] | None = None, rtl: bool = False, submit_btn: str | bool | None = True, stop_btn: str | bool | None = False, max_plain_text_length: int = 1000, ): """ Parameters: value: Default value to show in MultimodalTextbox. A string value, or a dictionary of the form {"text": "sample text", "files": [{path: "files/file.jpg", orig_name: "file.jpg", url: "http://image_url.jpg", size: 100}]}. If a function is provided, the function will be called each time the app loads to set the initial value of this component. sources: A list of sources permitted. "upload" creates a button where users can click to upload or drop files, "microphone" creates a microphone input. If None, defaults to ["upload"]. 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. lines: minimum number of line rows to provide in textarea. max_lines: maximum number of line rows to provide in textarea. placeholder: placeholder hint to provide behind textarea. 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, will be rendered as an editable textbox; if False, editing will be disabled. If not provided, this is inferred based on whether the component is used as an input or output. visible: If False, component will be hidden. autofocus: If True, will focus on the textbox when the page loads. Use this carefully, as it can cause usability issues for sighted and non-sighted users. 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. text_align: How to align the text in the textbox, can be: "left", "right", or None (default). If None, the alignment is left if `rtl` is False, or right if `rtl` is True. Can only be changed if `type` is "text". rtl: If True and `type` is "text", sets the direction of the text to right-to-left (cursor appears on the left of the text). Default is False, which renders cursor on the right. autoscroll: If True, will automatically scroll to the bottom of the textbox when the value changes, unless the user scrolls up. If False, will not scroll to the bottom of the textbox when the value changes. submit_btn: If False, will not show a submit button. If a string, will use that string as the submit button text. stop_btn: If True, will show a stop button (useful for streaming demos). If a string, will use that string as the stop button text. max_plain_text_length: Maximum length of plain text in the textbox. If the text exceeds this length, the text will be pasted as a file. Default is 1000. """ valid_sources: list[Literal["upload", "microphone"]] = ["upload", "microphone"] if sources is None: self.sources = ["upload"] elif isinstance(sources, str) and sources in valid_sources: self.sources = [sources] elif isinstance(sources, list): 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.file_types = file_types self.file_count = file_count 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__}" ) self.lines = lines self.max_lines = max(lines, max_lines) self.placeholder = placeholder self.submit_btn = submit_btn self.stop_btn = stop_btn self.autofocus = autofocus self.autoscroll = autoscroll self.max_plain_text_length = max_plain_text_length 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, ) self.rtl = rtl self.text_align = text_align
Parameters: value: Default value to show in MultimodalTextbox. A string value, or a dictionary of the form {"text": "sample text", "files": [{path: "files/file.jpg", orig_name: "file.jpg", url: "http://image_url.jpg", size: 100}]}. If a function is provided, the function will be called each time the app loads to set the initial value of this component. sources: A list of sources permitted. "upload" creates a button where users can click to upload or drop files, "microphone" creates a microphone input. If None, defaults to ["upload"]. 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. lines: minimum number of line rows to provide in textarea. max_lines: maximum number of line rows to provide in textarea. placeholder: placeholder hint to provide behind textarea. 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, will be rendered as an editable textbox; if False, editing will be disabled. If not provided, this is inferred based on whether the component is used as an input or output. visible: If False, component will be hidden. autofocus: If True, will focus on the textbox when the page loads. Use this carefully, as it can cause usability issues for sighted and non-sighted users. 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. text_align: How to align the text in the textbox, can be: "left", "right", or None (default). If None, the alignment is left if `rtl` is False, or right if `rtl` is True. Can only be changed if `type` is "text". rtl: If True and `type` is "text", sets the direction of the text to right-to-left (cursor appears on the left of the text). Default is False, which renders cursor on the right. autoscroll: If True, will automatically scroll to the bottom of the textbox when the value changes, unless the user scrolls up. If False, will not scroll to the bottom of the textbox when the value changes. submit_btn: If False, will not show a submit button. If a string, will use that string as the submit button text. stop_btn: If True, will show a stop button (useful for streaming demos). If a string, will use that string as the stop button text. max_plain_text_length: Maximum length of plain text in the textbox. If the text exceeds this length, the text will be pasted as a file. Default is 1000.
__init__
python
gradio-app/gradio
gradio/components/multimodal_textbox.py
https://github.com/gradio-app/gradio/blob/master/gradio/components/multimodal_textbox.py
Apache-2.0
def preprocess(self, payload: MultimodalData | None) -> MultimodalValue | None: """ Parameters: payload: the text and list of file(s) entered in the multimodal textbox. Returns: Passes text value and list of file(s) as a {dict} into the function. """ if payload is None: return None if self.file_types is not None: for f in payload.files: if not client_utils.is_valid_file(f.path, self.file_types): raise Error( f"Invalid file type: {f.mime_type}. Please upload a file that is one of these formats: {self.file_types}" ) return { "text": payload.text, "files": [f.path for f in payload.files], }
Parameters: payload: the text and list of file(s) entered in the multimodal textbox. Returns: Passes text value and list of file(s) as a {dict} into the function.
preprocess
python
gradio-app/gradio
gradio/components/multimodal_textbox.py
https://github.com/gradio-app/gradio/blob/master/gradio/components/multimodal_textbox.py
Apache-2.0
def postprocess(self, value: MultimodalValue | str | None) -> MultimodalData | None: """ Parameters: value: Expects a {dict} with "text" and "files", both optional. The files array is a list of file paths or URLs. Returns: The value to display in the multimodal textbox. Files information as a list of FileData objects. """ if value is None: return None if not isinstance(value, (dict, str)): raise ValueError( f"MultimodalTextbox expects a string or a dictionary with optional keys 'text' and 'files'. Received {value.__class__.__name__}" ) if isinstance(value, str): return MultimodalData(text=value, files=[]) text = value.get("text", "") if "files" in value and isinstance(value["files"], list): files = [ cast(FileData, file) if isinstance(file, FileData | dict) else FileData( path=file, orig_name=Path(file).name, mime_type=client_utils.get_mimetype(file), ) for file in value["files"] ] else: files = [] if not isinstance(text, str): raise TypeError( f"Expected 'text' to be a string, but got {type(text).__name__}" ) if not isinstance(files, list): raise TypeError( f"Expected 'files' to be a list, but got {type(files).__name__}" ) return MultimodalData(text=text, files=files)
Parameters: value: Expects a {dict} with "text" and "files", both optional. The files array is a list of file paths or URLs. Returns: The value to display in the multimodal textbox. Files information as a list of FileData objects.
postprocess
python
gradio-app/gradio
gradio/components/multimodal_textbox.py
https://github.com/gradio-app/gradio/blob/master/gradio/components/multimodal_textbox.py
Apache-2.0
def __init__( self, value: str | Callable | None = None, *, display_mode: Literal["solid", "point_cloud", "wireframe"] | None = None, clear_color: tuple[float, float, float, float] | None = None, camera_position: tuple[ int | float | None, int | float | None, int | float | None ] = ( None, None, None, ), zoom_speed: float = 1, pan_speed: float = 1, height: int | str | None = None, label: str | None = None, show_label: bool | None = None, every: Timer | float | None = None, inputs: Component | Sequence[Component] | set[Component] | 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: path to (.obj, .glb, .stl, .gltf, .splat, or .ply) file to show in model3D viewer. If a function is provided, the function will be called each time the app loads to set the initial value of this component. display_mode: the display mode of the 3D model in the scene. Can be "solid" (which renders the model as a solid object), "point_cloud", or "wireframe". For .splat, or .ply files, this parameter is ignored, as those files can only be rendered as solid objects. clear_color: background color of scene, should be a tuple of 4 floats between 0 and 1 representing RGBA values. camera_position: initial camera position of scene, provided as a tuple of `(alpha, beta, radius)`. Each value is optional. If provided, `alpha` and `beta` should be in degrees reflecting the angular position along the longitudinal and latitudinal axes, respectively. Radius corresponds to the distance from the center of the object to the camera. zoom_speed: the speed of zooming in and out of the scene when the cursor wheel is rotated or when screen is pinched on a mobile device. Should be a positive float, increase this value to make zooming faster, decrease to make it slower. Affects the wheelPrecision property of the camera. pan_speed: the speed of panning the scene when the cursor is dragged or when the screen is dragged on a mobile device. Should be a positive float, increase this value to make panning faster, decrease to make it slower. Affects the panSensibility property of the camera. height: The height of the model3D component, specified in pixels if a number is passed, or in CSS units if a string is passed. 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. 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. 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. 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. """ self.display_mode = display_mode self.clear_color = clear_color or [0, 0, 0, 0] self.camera_position = camera_position self.height = height self.zoom_speed = zoom_speed self.pan_speed = pan_speed 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, )
Parameters: value: path to (.obj, .glb, .stl, .gltf, .splat, or .ply) file to show in model3D viewer. If a function is provided, the function will be called each time the app loads to set the initial value of this component. display_mode: the display mode of the 3D model in the scene. Can be "solid" (which renders the model as a solid object), "point_cloud", or "wireframe". For .splat, or .ply files, this parameter is ignored, as those files can only be rendered as solid objects. clear_color: background color of scene, should be a tuple of 4 floats between 0 and 1 representing RGBA values. camera_position: initial camera position of scene, provided as a tuple of `(alpha, beta, radius)`. Each value is optional. If provided, `alpha` and `beta` should be in degrees reflecting the angular position along the longitudinal and latitudinal axes, respectively. Radius corresponds to the distance from the center of the object to the camera. zoom_speed: the speed of zooming in and out of the scene when the cursor wheel is rotated or when screen is pinched on a mobile device. Should be a positive float, increase this value to make zooming faster, decrease to make it slower. Affects the wheelPrecision property of the camera. pan_speed: the speed of panning the scene when the cursor is dragged or when the screen is dragged on a mobile device. Should be a positive float, increase this value to make panning faster, decrease to make it slower. Affects the panSensibility property of the camera. height: The height of the model3D component, specified in pixels if a number is passed, or in CSS units if a string is passed. 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. 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. 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. 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.
__init__
python
gradio-app/gradio
gradio/components/model3d.py
https://github.com/gradio-app/gradio/blob/master/gradio/components/model3d.py
Apache-2.0
def preprocess(self, payload: FileData | None) -> str | None: """ Parameters: payload: the uploaded file as an instance of `FileData`. Returns: Passes the uploaded file as a {str} filepath to the function. """ if payload is None: return payload return payload.path
Parameters: payload: the uploaded file as an instance of `FileData`. Returns: Passes the uploaded file as a {str} filepath to the function.
preprocess
python
gradio-app/gradio
gradio/components/model3d.py
https://github.com/gradio-app/gradio/blob/master/gradio/components/model3d.py
Apache-2.0
def postprocess(self, value: str | Path | None) -> FileData | None: """ Parameters: value: Expects function to return a {str} or {pathlib.Path} filepath of type (.obj, .glb, .stl, or .gltf) Returns: The uploaded file as an instance of `FileData`. """ if value is None: return value return FileData(path=str(value), orig_name=Path(value).name)
Parameters: value: Expects function to return a {str} or {pathlib.Path} filepath of type (.obj, .glb, .stl, or .gltf) Returns: The uploaded file as an instance of `FileData`.
postprocess
python
gradio-app/gradio
gradio/components/model3d.py
https://github.com/gradio-app/gradio/blob/master/gradio/components/model3d.py
Apache-2.0
def __init__( self, value: ( tuple[ np.ndarray | PIL.Image.Image | str, list[tuple[np.ndarray | tuple[int, int, int, int], str]], ] | None ) = None, *, format: str = "webp", show_legend: bool = True, height: int | str | None = None, width: int | str | None = None, color_map: dict[str, 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, visible: bool = True, elem_id: str | None = None, elem_classes: list[str] | str | None = None, render: bool = True, key: int | str | None = None, show_fullscreen_button: bool = True, ): """ Parameters: value: Tuple of base image and list of (annotation, label) pairs. format: Format used to save images before it is returned to the front end, such as 'jpeg' or 'png'. This parameter only takes effect when the base image is returned from the prediction function as a numpy array or a PIL Image. The format should be supported by the PIL library. show_legend: If True, will show a legend of the annotations. 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 image file or numpy array, but will affect the displayed image. 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 image file or numpy array, but will affect the displayed image. color_map: A dictionary mapping labels to colors. The colors must be specified as hex codes. 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 width compared to adjacent Components in a Row. For example, if Component A has scale=2, and Component B has scale=1, A will be twice as wide as B. Should be an integer. 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_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. show_fullscreen_button: If True, will show a button to allow the image to be viewed in fullscreen mode. """ self.format = format self.show_legend = show_legend self.height = height self.width = width self.color_map = color_map self.show_fullscreen_button = show_fullscreen_button super().__init__( label=label, every=every, inputs=inputs, 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, value=value, )
Parameters: value: Tuple of base image and list of (annotation, label) pairs. format: Format used to save images before it is returned to the front end, such as 'jpeg' or 'png'. This parameter only takes effect when the base image is returned from the prediction function as a numpy array or a PIL Image. The format should be supported by the PIL library. show_legend: If True, will show a legend of the annotations. 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 image file or numpy array, but will affect the displayed image. 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 image file or numpy array, but will affect the displayed image. color_map: A dictionary mapping labels to colors. The colors must be specified as hex codes. 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 width compared to adjacent Components in a Row. For example, if Component A has scale=2, and Component B has scale=1, A will be twice as wide as B. Should be an integer. 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_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. show_fullscreen_button: If True, will show a button to allow the image to be viewed in fullscreen mode.
__init__
python
gradio-app/gradio
gradio/components/annotated_image.py
https://github.com/gradio-app/gradio/blob/master/gradio/components/annotated_image.py
Apache-2.0
def preprocess( self, payload: AnnotatedImageData | None ) -> tuple[str, list[tuple[str, str]]] | None: """ Parameters: payload: Dict of base image and list of annotations. Returns: Passes its value as a `tuple` consisting of a `str` filepath to a base image and `list` of annotations. Each annotation itself is `tuple` of a mask (as a `str` filepath to image) and a `str` label. """ if payload is None: return None base_img = payload.image.path annotations = [(a.image.path, a.label) for a in payload.annotations] return (base_img, annotations)
Parameters: payload: Dict of base image and list of annotations. Returns: Passes its value as a `tuple` consisting of a `str` filepath to a base image and `list` of annotations. Each annotation itself is `tuple` of a mask (as a `str` filepath to image) and a `str` label.
preprocess
python
gradio-app/gradio
gradio/components/annotated_image.py
https://github.com/gradio-app/gradio/blob/master/gradio/components/annotated_image.py
Apache-2.0
def postprocess( self, value: ( tuple[ np.ndarray | PIL.Image.Image | str, Sequence[tuple[np.ndarray | tuple[int, int, int, int], str]], ] | None ), ) -> AnnotatedImageData | None: """ Parameters: value: Expects a a tuple of a base image and list of annotations: a `tuple[Image, list[Annotation]]`. The `Image` itself can be `str` filepath, `numpy.ndarray`, or `PIL.Image`. Each `Annotation` is a `tuple[Mask, str]`. The `Mask` can be either a `tuple` of 4 `int`'s representing the bounding box coordinates (x1, y1, x2, y2), or 0-1 confidence mask in the form of a `numpy.ndarray` of the same shape as the image, while the second element of the `Annotation` tuple is a `str` label. Returns: Tuple of base image file and list of annotations, with each annotation a two-part tuple where the first element image path of the mask, and the second element is the label. """ if value is None: return None base_img = value[0] if isinstance(base_img, str): if client_utils.is_http_url_like(base_img): base_img = processing_utils.save_url_to_cache( base_img, cache_dir=self.GRADIO_CACHE ) base_img_path = base_img base_img = np.array(PIL.Image.open(base_img)) elif isinstance(base_img, np.ndarray): base_file = processing_utils.save_img_array_to_cache( base_img, cache_dir=self.GRADIO_CACHE, format=self.format ) base_img_path = str(utils.abspath(base_file)) elif isinstance(base_img, PIL.Image.Image): base_file = processing_utils.save_pil_to_cache( base_img, cache_dir=self.GRADIO_CACHE, format=self.format ) base_img_path = str(utils.abspath(base_file)) base_img = np.array(base_img) else: raise ValueError( "AnnotatedImage only accepts filepaths, PIL images or numpy arrays for the base image." ) sections = [] color_map = self.color_map or {} def hex_to_rgb(value): value = value.lstrip("#") lv = len(value) return [int(value[i : i + lv // 3], 16) for i in range(0, lv, lv // 3)] for mask, label in value[1]: mask_array = np.zeros((base_img.shape[0], base_img.shape[1])) if isinstance(mask, np.ndarray): mask_array = mask else: x1, y1, x2, y2 = mask border_width = 3 mask_array[y1:y2, x1:x2] = 0.5 mask_array[y1:y2, x1 : x1 + border_width] = 1 mask_array[y1:y2, x2 - border_width : x2] = 1 mask_array[y1 : y1 + border_width, x1:x2] = 1 mask_array[y2 - border_width : y2, x1:x2] = 1 if label in color_map: rgb_color = hex_to_rgb(color_map[label]) else: rgb_color = [255, 0, 0] colored_mask = np.zeros((base_img.shape[0], base_img.shape[1], 4)) solid_mask = np.copy(mask_array) solid_mask[solid_mask > 0] = 1 colored_mask[:, :, 0] = rgb_color[0] * solid_mask colored_mask[:, :, 1] = rgb_color[1] * solid_mask colored_mask[:, :, 2] = rgb_color[2] * solid_mask colored_mask[:, :, 3] = mask_array * 255 colored_mask_img = PIL.Image.fromarray((colored_mask).astype(np.uint8)) # RGBA does not support transparency mask_file = processing_utils.save_pil_to_cache( colored_mask_img, cache_dir=self.GRADIO_CACHE, format="png" ) mask_file_path = str(utils.abspath(mask_file)) sections.append( Annotation(image=FileData(path=mask_file_path), label=label) ) return AnnotatedImageData( image=FileData(path=base_img_path), annotations=sections, )
Parameters: value: Expects a a tuple of a base image and list of annotations: a `tuple[Image, list[Annotation]]`. The `Image` itself can be `str` filepath, `numpy.ndarray`, or `PIL.Image`. Each `Annotation` is a `tuple[Mask, str]`. The `Mask` can be either a `tuple` of 4 `int`'s representing the bounding box coordinates (x1, y1, x2, y2), or 0-1 confidence mask in the form of a `numpy.ndarray` of the same shape as the image, while the second element of the `Annotation` tuple is a `str` label. Returns: Tuple of base image file and list of annotations, with each annotation a two-part tuple where the first element image path of the mask, and the second element is the label.
postprocess
python
gradio-app/gradio
gradio/components/annotated_image.py
https://github.com/gradio-app/gradio/blob/master/gradio/components/annotated_image.py
Apache-2.0
def __init__( self, value: str | PIL.Image.Image | np.ndarray | Callable | None = None, *, format: str = "webp", height: int | str | None = None, width: int | str | None = None, image_mode: Literal[ "1", "L", "P", "RGB", "RGBA", "CMYK", "YCbCr", "LAB", "HSV", "I", "F" ] | None = "RGB", sources: list[Literal["upload", "webcam", "clipboard"]] | Literal["upload", "webcam", "clipboard"] | None = None, type: Literal["numpy", "pil", "filepath"] = "numpy", label: str | None = None, every: Timer | float | None = None, inputs: Component | Sequence[Component] | set[Component] | None = None, show_label: bool | None = None, show_download_button: bool = True, container: bool = True, scale: int | None = None, min_width: int = 160, interactive: bool | None = None, visible: bool = True, streaming: bool = False, elem_id: str | None = None, elem_classes: list[str] | str | None = None, render: bool = True, key: int | str | None = None, mirror_webcam: bool = True, show_share_button: bool | None = None, placeholder: str | None = None, show_fullscreen_button: bool = True, webcam_constraints: dict[str, Any] | None = None, ): """ Parameters: value: A PIL Image, numpy array, path or URL for the default value that Image component is going to take. If a function is provided, the function will be called each time the app loads to set the initial value of this component. format: File format (e.g. "png" or "gif"). Used to save image if it does not already have a valid format (e.g. if the image is being returned to the frontend as a numpy array or PIL Image). The format should be supported by the PIL library. Applies both when this component is used as an input or output. This parameter has no effect on SVG files. 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 image file or numpy array, but will affect the displayed image. 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 image file or numpy array, but will affect the displayed image. image_mode: The pixel format and color depth that the image should be loaded and preprocessed as. "RGB" will load the image as a color image, or "L" as black-and-white. See https://pillow.readthedocs.io/en/stable/handbook/concepts.html for other supported image modes and their meaning. This parameter has no effect on SVG or GIF files. If set to None, the image_mode will be inferred from the image file type (e.g. "RGBA" for a .png image, "RGB" in most other cases). sources: List of sources for the image. "upload" creates a box where user can drop an image file, "webcam" allows user to take snapshot from their webcam, "clipboard" allows users to paste an image from the clipboard. If None, defaults to ["upload", "webcam", "clipboard"] if streaming is False, otherwise defaults to ["webcam"]. type: The format the image is converted before being passed into the prediction function. "numpy" converts the image to a numpy array with shape (height, width, 3) and values from 0 to 255, "pil" converts the image to a PIL image object, "filepath" passes a str path to a temporary file containing the image. To support animated GIFs in input, the `type` should be set to "filepath" or "pil". To support SVGs, the `type` should be set to "filepath". 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. show_download_button: If True, will display button to download image. Only applies if interactive is False (e.g. if the component is used as an output). 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 and edit an image; if False, can only be used to display images. If not provided, this is inferred based on whether the component is used as an input or output. visible: If False, component will be hidden. streaming: If True when used in a `live` interface, will automatically stream webcam feed. Only valid is source is 'webcam'. If the component is an output component, will automatically convert images to base64. 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. 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. placeholder: Custom text for the upload area. Overrides default upload messages when provided. Accepts new lines and `#` to designate a heading. show_fullscreen_button: If True, will show a fullscreen icon in the corner of the component that allows user to view the image in fullscreen mode. If False, icon does not appear. 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 """ self.format = format self.mirror_webcam = mirror_webcam valid_types = ["numpy", "pil", "filepath"] 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.height = height self.width = width self.image_mode = image_mode valid_sources = ["upload", "webcam", "clipboard"] if sources is None: self.sources = ( ["webcam"] if streaming else ["upload", "webcam", "clipboard"] ) elif isinstance(sources, str): self.sources = [sources] # type: ignore else: self.sources = sources for source in self.sources: # type: ignore if source not in valid_sources: raise ValueError( f"`sources` must a list consisting of elements in {valid_sources}" ) self.streaming = streaming self.show_download_button = show_download_button if streaming and self.sources != ["webcam"]: raise ValueError( "Image streaming only available if sources is ['webcam']. Streaming not supported with multiple sources." ) self.show_share_button = ( (utils.get_space() is not None) if show_share_button is None else show_share_button ) self.show_fullscreen_button = show_fullscreen_button self.placeholder = placeholder 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, )
Parameters: value: A PIL Image, numpy array, path or URL for the default value that Image component is going to take. If a function is provided, the function will be called each time the app loads to set the initial value of this component. format: File format (e.g. "png" or "gif"). Used to save image if it does not already have a valid format (e.g. if the image is being returned to the frontend as a numpy array or PIL Image). The format should be supported by the PIL library. Applies both when this component is used as an input or output. This parameter has no effect on SVG files. 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 image file or numpy array, but will affect the displayed image. 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 image file or numpy array, but will affect the displayed image. image_mode: The pixel format and color depth that the image should be loaded and preprocessed as. "RGB" will load the image as a color image, or "L" as black-and-white. See https://pillow.readthedocs.io/en/stable/handbook/concepts.html for other supported image modes and their meaning. This parameter has no effect on SVG or GIF files. If set to None, the image_mode will be inferred from the image file type (e.g. "RGBA" for a .png image, "RGB" in most other cases). sources: List of sources for the image. "upload" creates a box where user can drop an image file, "webcam" allows user to take snapshot from their webcam, "clipboard" allows users to paste an image from the clipboard. If None, defaults to ["upload", "webcam", "clipboard"] if streaming is False, otherwise defaults to ["webcam"]. type: The format the image is converted before being passed into the prediction function. "numpy" converts the image to a numpy array with shape (height, width, 3) and values from 0 to 255, "pil" converts the image to a PIL image object, "filepath" passes a str path to a temporary file containing the image. To support animated GIFs in input, the `type` should be set to "filepath" or "pil". To support SVGs, the `type` should be set to "filepath". 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. show_download_button: If True, will display button to download image. Only applies if interactive is False (e.g. if the component is used as an output). 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 and edit an image; if False, can only be used to display images. If not provided, this is inferred based on whether the component is used as an input or output. visible: If False, component will be hidden. streaming: If True when used in a `live` interface, will automatically stream webcam feed. Only valid is source is 'webcam'. If the component is an output component, will automatically convert images to base64. 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. 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. placeholder: Custom text for the upload area. Overrides default upload messages when provided. Accepts new lines and `#` to designate a heading. show_fullscreen_button: If True, will show a fullscreen icon in the corner of the component that allows user to view the image in fullscreen mode. If False, icon does not appear. 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
__init__
python
gradio-app/gradio
gradio/components/image.py
https://github.com/gradio-app/gradio/blob/master/gradio/components/image.py
Apache-2.0
def preprocess( self, payload: ImageData | None ) -> np.ndarray | PIL.Image.Image | str | None: """ Parameters: payload: image data in the form of a FileData object Returns: Passes the uploaded image as a `numpy.array`, `PIL.Image` or `str` filepath depending on `type`. """ if payload is None: return payload if payload.url and payload.url.startswith("data:"): if self.type == "pil": return image_utils.decode_base64_to_image(payload.url) elif self.type == "numpy": return image_utils.decode_base64_to_image_array(payload.url) elif self.type == "filepath": return image_utils.decode_base64_to_file( payload.url, self.GRADIO_CACHE, self.format ) if payload.path is None: raise ValueError("Image path is None.") file_path = Path(payload.path) if payload.orig_name: p = Path(payload.orig_name) name = p.stem suffix = p.suffix.replace(".", "") if suffix in ["jpg", "jpeg"]: suffix = "jpeg" else: name = "image" suffix = "webp" if suffix.lower() == "svg": if self.type == "filepath": return str(file_path) raise Error("SVG files are not supported as input images for this app.") im = PIL.Image.open(file_path) if self.type == "filepath" and (self.image_mode in [None, im.mode]): return str(file_path) exif = im.getexif() # 274 is the code for image rotation and 1 means "correct orientation" if exif.get(274, 1) != 1 and hasattr(ImageOps, "exif_transpose"): try: im = ImageOps.exif_transpose(im) except Exception: warnings.warn( f"Failed to transpose image {file_path} based on EXIF data." ) if suffix.lower() != "gif" and im is not None: with warnings.catch_warnings(): warnings.simplefilter("ignore") if self.image_mode is not None: im = im.convert(self.image_mode) return image_utils.format_image( im, cast(Literal["numpy", "pil", "filepath"], self.type), self.GRADIO_CACHE, name=name, format=suffix, )
Parameters: payload: image data in the form of a FileData object Returns: Passes the uploaded image as a `numpy.array`, `PIL.Image` or `str` filepath depending on `type`.
preprocess
python
gradio-app/gradio
gradio/components/image.py
https://github.com/gradio-app/gradio/blob/master/gradio/components/image.py
Apache-2.0
def postprocess( self, value: np.ndarray | PIL.Image.Image | str | Path | None ) -> ImageData | Base64ImageData | None: """ Parameters: value: Expects a `numpy.array`, `PIL.Image`, or `str` or `pathlib.Path` filepath to an image which is displayed. Returns: Returns the image as a `FileData` object. """ if value is None: return None if isinstance(value, str) and value.lower().endswith(".svg"): svg_content = image_utils.extract_svg_content(value) return ImageData( orig_name=Path(value).name, url=f"data:image/svg+xml,{quote(svg_content)}", ) if self.streaming: if isinstance(value, np.ndarray): return Base64ImageData( url=image_utils.encode_image_array_to_base64(value) ) elif isinstance(value, PIL.Image.Image): return Base64ImageData(url=image_utils.encode_image_to_base64(value)) elif isinstance(value, (Path, str)): return Base64ImageData( url=image_utils.encode_image_file_to_base64(value) ) saved = image_utils.save_image(value, self.GRADIO_CACHE, self.format) orig_name = Path(saved).name if Path(saved).exists() else None return ImageData(path=saved, orig_name=orig_name)
Parameters: value: Expects a `numpy.array`, `PIL.Image`, or `str` or `pathlib.Path` filepath to an image which is displayed. Returns: Returns the image as a `FileData` object.
postprocess
python
gradio-app/gradio
gradio/components/image.py
https://github.com/gradio-app/gradio/blob/master/gradio/components/image.py
Apache-2.0
def __init__( self, *, label: str | None = None, show_label: bool = True, components: Sequence[Component] | list[str] | None = None, component_props: list[dict[str, Any]] | None = None, samples: list[list[Any]] | None = None, headers: list[str] | None = None, type: Literal["values", "index", "tuple"] = "values", layout: Literal["gallery", "table"] | None = None, samples_per_page: int = 10, visible: bool = True, elem_id: str | None = None, elem_classes: list[str] | str | None = None, render: bool = True, key: int | str | None = None, container: bool = True, scale: int | None = None, min_width: int = 160, proxy_url: str | None = None, sample_labels: list[str] | None = None, ): """ Parameters: label: the label for this component, appears above the component. show_label: If True, the label will be shown above the component. components: Which component types to show in this dataset widget, can be passed in as a list of string names or Components instances. The following components are supported in a Dataset: Audio, Checkbox, CheckboxGroup, ColorPicker, Dataframe, Dropdown, File, HTML, Image, Markdown, Model3D, Number, Radio, Slider, Textbox, TimeSeries, Video samples: a nested list of samples. Each sublist within the outer list represents a data sample, and each element within the sublist represents an value for each component headers: Column headers in the Dataset widget, should be the same len as components. If not provided, inferred from component labels type: "values" if clicking on a sample should pass the value of the sample, "index" if it should pass the index of the sample, or "tuple" if it should pass both the index and the value of the sample. layout: "gallery" if the dataset should be displayed as a gallery with each sample in a clickable card, or "table" if it should be displayed as a table with each sample in a row. By default, "gallery" is used if there is a single component, and "table" is used if there are more than one component. If there are more than one component, the layout can only be "table". samples_per_page: how many examples to show per page. 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. 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. proxy_url: The URL of the external Space used to load this component. Set automatically when using `gr.load()`. This should not be set manually. sample_labels: A list of labels for each sample. If provided, the length of this list should be the same as the number of samples, and these labels will be used in the UI instead of rendering the sample values. """ super().__init__( visible=visible, elem_id=elem_id, elem_classes=elem_classes, render=render, key=key, ) self.container = container self.scale = scale self.min_width = min_width self.layout = layout self.show_label = show_label self._components = [get_component_instance(c) for c in components or []] if component_props is None: self.component_props = [ component.recover_kwargs( component.get_config(), ["value"], ) for component in self._components ] else: self.component_props = component_props # Narrow type to Component if not all(isinstance(c, Component) for c in self._components): raise TypeError( "All components in a `Dataset` must be subclasses of `Component`" ) self._components = [c for c in self._components if isinstance(c, Component)] self.proxy_url = proxy_url for component in self._components: component.proxy_url = proxy_url self.raw_samples = [[]] if samples is None else samples self.samples: list[list] = [] for example in self.raw_samples: self.samples.append([]) for component, ex in zip(self._components, example, strict=False): # If proxy_url is set, that means it is being loaded from an external Gradio app # which means that the example has already been processed. if self.proxy_url is None: # We do not need to process examples if the Gradio app is being loaded from # an external Space because the examples have already been processed. Also, # the `as_example()` method has been renamed to `process_example()` but we # use the previous name to be backwards-compatible with previously-created # custom components ex = component.as_example(ex) self.samples[-1].append( processing_utils.move_files_to_cache( ex, component, keep_in_cache=True ) ) self.type = type self.label = label if headers is not None: self.headers = headers elif all(c.label is None for c in self._components): self.headers = [] else: self.headers = [c.label or "" for c in self._components] self.samples_per_page = samples_per_page self.sample_labels = sample_labels
Parameters: label: the label for this component, appears above the component. show_label: If True, the label will be shown above the component. components: Which component types to show in this dataset widget, can be passed in as a list of string names or Components instances. The following components are supported in a Dataset: Audio, Checkbox, CheckboxGroup, ColorPicker, Dataframe, Dropdown, File, HTML, Image, Markdown, Model3D, Number, Radio, Slider, Textbox, TimeSeries, Video samples: a nested list of samples. Each sublist within the outer list represents a data sample, and each element within the sublist represents an value for each component headers: Column headers in the Dataset widget, should be the same len as components. If not provided, inferred from component labels type: "values" if clicking on a sample should pass the value of the sample, "index" if it should pass the index of the sample, or "tuple" if it should pass both the index and the value of the sample. layout: "gallery" if the dataset should be displayed as a gallery with each sample in a clickable card, or "table" if it should be displayed as a table with each sample in a row. By default, "gallery" is used if there is a single component, and "table" is used if there are more than one component. If there are more than one component, the layout can only be "table". samples_per_page: how many examples to show per page. 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. 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. proxy_url: The URL of the external Space used to load this component. Set automatically when using `gr.load()`. This should not be set manually. sample_labels: A list of labels for each sample. If provided, the length of this list should be the same as the number of samples, and these labels will be used in the UI instead of rendering the sample values.
__init__
python
gradio-app/gradio
gradio/components/dataset.py
https://github.com/gradio-app/gradio/blob/master/gradio/components/dataset.py
Apache-2.0
def preprocess(self, payload: int | None) -> int | list | tuple[int, list] | None: """ Parameters: payload: the index of the selected example in the dataset Returns: Passes the selected sample either as a `list` of data corresponding to each input component (if `type` is "value") or as an `int` index (if `type` is "index"), or as a `tuple` of the index and the data (if `type` is "tuple"). """ if payload is None: return None if self.type == "index": return payload elif self.type == "values": return self.raw_samples[payload] elif self.type == "tuple": return payload, self.raw_samples[payload]
Parameters: payload: the index of the selected example in the dataset Returns: Passes the selected sample either as a `list` of data corresponding to each input component (if `type` is "value") or as an `int` index (if `type` is "index"), or as a `tuple` of the index and the data (if `type` is "tuple").
preprocess
python
gradio-app/gradio
gradio/components/dataset.py
https://github.com/gradio-app/gradio/blob/master/gradio/components/dataset.py
Apache-2.0
def postprocess(self, value: int | list | None) -> int | None: """ Parameters: value: Expects an `int` index or `list` of sample data. Returns the index of the sample in the dataset or `None` if the sample is not found. Returns: Returns the index of the sample in the dataset. """ if value is None or isinstance(value, int): return value if isinstance(value, list): try: index = self.samples.index(value) except ValueError: index = None warnings.warn( "The `Dataset` component does not support updating the dataset data by providing " "a set of list values. Instead, you should return a new Dataset(samples=...) object." ) return index
Parameters: value: Expects an `int` index or `list` of sample data. Returns the index of the sample in the dataset or `None` if the sample is not found. Returns: Returns the index of the sample in the dataset.
postprocess
python
gradio-app/gradio
gradio/components/dataset.py
https://github.com/gradio-app/gradio/blob/master/gradio/components/dataset.py
Apache-2.0
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 )
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.
__init__
python
gradio-app/gradio
gradio/components/native_plot.py
https://github.com/gradio-app/gradio/blob/master/gradio/components/native_plot.py
Apache-2.0
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
Parameters: payload: The data to display in a line plot. Returns: The data to display in a line plot.
preprocess
python
gradio-app/gradio
gradio/components/native_plot.py
https://github.com/gradio-app/gradio/blob/master/gradio/components/native_plot.py
Apache-2.0
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(), )
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").
postprocess
python
gradio-app/gradio
gradio/components/native_plot.py
https://github.com/gradio-app/gradio/blob/master/gradio/components/native_plot.py
Apache-2.0
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 from among `choices`. By default, the first choice in `choices` is initally selected. If set explicitly to None, no value is initally selected. If a function is provided, the function will be called each time the app loads to set the initial value of this 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, )
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 from among `choices`. By default, the first choice in `choices` is initally selected. If set explicitly to None, no value is initally selected. If a function is provided, the function will be called each time the app loads to set the initial value of this 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.
__init__
python
gradio-app/gradio
gradio/components/dropdown.py
https://github.com/gradio-app/gradio/blob/master/gradio/components/dropdown.py
Apache-2.0
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 corresponding 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'." )
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 corresponding values/indices instead.
preprocess
python
gradio-app/gradio
gradio/components/dropdown.py
https://github.com/gradio-app/gradio/blob/master/gradio/components/dropdown.py
Apache-2.0
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
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.
postprocess
python
gradio-app/gradio
gradio/components/dropdown.py
https://github.com/gradio-app/gradio/blob/master/gradio/components/dropdown.py
Apache-2.0
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 a function is provided, the function will be called each time the app loads to set the initial value of this 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, )
Parameters: value: if True, checked by default. If a function is provided, the function will be called each time the app loads to set the initial value of this 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.
__init__
python
gradio-app/gradio
gradio/components/checkbox.py
https://github.com/gradio-app/gradio/blob/master/gradio/components/checkbox.py
Apache-2.0
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
Parameters: payload: the status of the checkbox Returns: Passes the status of the checkbox as a `bool`.
preprocess
python
gradio-app/gradio
gradio/components/checkbox.py
https://github.com/gradio-app/gradio/blob/master/gradio/components/checkbox.py
Apache-2.0
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)
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
postprocess
python
gradio-app/gradio
gradio/components/checkbox.py
https://github.com/gradio-app/gradio/blob/master/gradio/components/checkbox.py
Apache-2.0
def __init__( self, value: (list[MessageDict | Message] | TupleFormat | Callable | None) = None, *, type: Literal["messages", "tuples"] | 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, visible: bool = True, elem_id: str | None = None, elem_classes: list[str] | str | None = None, autoscroll: bool = True, render: bool = True, key: int | str | None = None, height: int | str | None = 400, resizable: bool = False, resizeable: bool = False, # Deprecated, TODO: Remove max_height: int | str | None = None, min_height: int | str | None = None, editable: Literal["user", "all"] | None = None, latex_delimiters: list[dict[str, str | bool]] | None = None, rtl: bool = False, show_share_button: bool | None = None, show_copy_button: bool = False, avatar_images: tuple[str | Path | None, str | Path | None] | None = None, sanitize_html: bool = True, render_markdown: bool = True, feedback_options: list[str] | tuple[str, ...] | None = ("Like", "Dislike"), feedback_value: Sequence[str | None] | None = None, bubble_full_width=None, line_breaks: bool = True, layout: Literal["panel", "bubble"] | None = None, placeholder: str | None = None, examples: list[ExampleMessage] | None = None, show_copy_all_button=False, allow_file_downloads=True, group_consecutive_messages: bool = True, allow_tags: list[str] | bool = False, ): """ Parameters: value: Default list of messages to show in chatbot, where each message is of the format {"role": "user", "content": "Help me."}. Role can be one of "user", "assistant", or "system". Content should be either text, or media passed as a Gradio component, e.g. {"content": gr.Image("lion.jpg")}. If a function is provided, the function will be called each time the app loads to set the initial value of this component. type: The format of the messages passed into the chat history parameter of `fn`. If "messages", passes the value as a list of dictionaries with openai-style "role" and "content" keys. The "content" key's value should be one of the following - (1) strings in valid Markdown (2) a dictionary with a "path" key and value corresponding to the file to display or (3) an instance of a Gradio component. At the moment Image, Plot, Video, Gallery, Audio, and HTML are supported. The "role" key should be one of 'user' or 'assistant'. Any other roles will not be displayed in the output. If this parameter is 'tuples', expects a `list[list[str | None | tuple]]`, i.e. a list of lists. The inner list should have 2 elements: the user message and the response message, but this format is deprecated. 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. 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. autoscroll: If True, will automatically scroll to the bottom of the textbox when the value changes, unless the user scrolls up. If False, will not scroll to the bottom of the textbox when the value changes. 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. height: The height of the component, specified in pixels if a number is passed, or in CSS units if a string is passed. If messages exceed the height, the component will scroll. resizable: If True, the user of the Gradio app can resize the chatbot by dragging the bottom right corner. max_height: The maximum height of the component, specified in pixels if a number is passed, or in CSS units if a string is passed. If messages exceed the height, the component will scroll. If messages are shorter than the height, the component will shrink to fit the content. Will not have any effect if `height` is set and is smaller than `max_height`. min_height: The minimum height of the component, specified in pixels if a number is passed, or in CSS units if a string is passed. If messages exceed the height, the component will expand to fit the content. Will not have any effect if `height` is set and is larger than `min_height`. editable: Allows user to edit messages in the chatbot. If set to "user", allows editing of user messages. If set to "all", allows editing of assistant messages as well. 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). rtl: If True, sets the direction of the rendered text to right-to-left. Default is False, which renders text left-to-right. 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_copy_button: If True, will show a copy button for each chatbot message. avatar_images: Tuple of two avatar image paths or URLs for user and bot (in that order). Pass None for either the user or bot image to skip. Must be within the working directory of the Gradio app or an external URL. sanitize_html: If False, will disable HTML sanitization for chatbot messages. This is not recommended, as it can lead to security vulnerabilities. render_markdown: If False, will disable Markdown rendering for chatbot messages. feedback_options: A list of strings representing the feedback options that will be displayed to the user. The exact case-sensitive strings "Like" and "Dislike" will render as thumb icons, but any other choices will appear under a separate flag icon. feedback_value: A list of strings representing the feedback state for entire chat. Only works when type="messages". Each entry in the list corresponds to that assistant message, in order, and the value is the feedback given (e.g. "Like", "Dislike", or any custom feedback option) or None if no feedback was given for that message. bubble_full_width: Deprecated. 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 if `render_markdown` is True. layout: If "panel", will display the chatbot in a llm style layout. If "bubble", will display the chatbot with message bubbles, with the user and bot messages on alterating sides. Will default to "bubble". placeholder: a placeholder message to display in the chatbot when it is empty. Centered vertically and horizontally in the Chatbot. Supports Markdown and HTML. If None, no placeholder is displayed. examples: A list of example messages to display in the chatbot before any user/assistant messages are shown. Each example should be a dictionary with an optional "text" key representing the message that should be populated in the Chatbot when clicked, an optional "files" key, whose value should be a list of files to populate in the Chatbot, an optional "icon" key, whose value should be a filepath or URL to an image to display in the example box, and an optional "display_text" key, whose value should be the text to display in the example box. If "display_text" is not provided, the value of "text" will be displayed. show_copy_all_button: If True, will show a copy all button that copies all chatbot messages to the clipboard. allow_file_downloads: If True, will show a download button for chatbot messages that contain media. Defaults to True. group_consecutive_messages: If True, will display consecutive messages from the same role in the same bubble. If False, will display each message in a separate bubble. Defaults to True. allow_tags: If a list of tags is provided, these tags will be preserved in the output chatbot messages, even if `sanitize_html` is `True`. For example, if this list is ["thinking"], the tags `<thinking>` and `</thinking>` will not be removed. If True, all custom tags (non-standard HTML tags) will be preserved. If False, no tags will be preserved (default behavior). """ if type is None: warnings.warn( "You have not specified a value for the `type` parameter. Defaulting to the 'tuples' format for chatbot messages, but this is deprecated and will be removed in a future version of Gradio. Please set type='messages' instead, which uses openai-style dictionaries with 'role' and 'content' keys.", UserWarning, stacklevel=3, ) type = "tuples" elif type == "tuples": warnings.warn( "The 'tuples' format for chatbot messages is deprecated and will be removed in a future version of Gradio. Please set type='messages' instead, which uses openai-style 'role' and 'content' keys.", UserWarning, stacklevel=3, ) if type not in ["messages", "tuples"]: raise ValueError( f"The `type` parameter must be 'messages' or 'tuples', received: {type}" ) self.type: Literal["tuples", "messages"] = type self._setup_data_model() self.autoscroll = autoscroll self.height = height if resizeable is not False: warnings.warn( "The 'resizeable' parameter is deprecated and will be removed in a future version. Please use the 'resizable' (note the corrected spelling) parameter instead.", DeprecationWarning, stacklevel=3, ) self.resizable = resizeable self.resizable = resizable self.max_height = max_height self.min_height = min_height self.editable = editable self.rtl = rtl self.group_consecutive_messages = group_consecutive_messages if latex_delimiters is None: latex_delimiters = [{"left": "$$", "right": "$$", "display": True}] self.latex_delimiters = latex_delimiters self.show_share_button = ( (utils.get_space() is not None) if show_share_button is None else show_share_button ) self.render_markdown = render_markdown self.show_copy_button = show_copy_button self.sanitize_html = sanitize_html if bubble_full_width is not None: warnings.warn( "The 'bubble_full_width' parameter is deprecated and will be removed in a future version. This parameter no longer has any effect.", DeprecationWarning, stacklevel=3, ) self.bubble_full_width = None self.line_breaks = line_breaks self.layout = layout self.show_copy_all_button = show_copy_all_button self.allow_file_downloads = allow_file_downloads self.feedback_options = feedback_options self.feedback_value = feedback_value self.allow_tags = allow_tags if allow_tags else False super().__init__( label=label, every=every, inputs=inputs, 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, value=value, ) self.avatar_images: list[dict | None] = [None, None] if avatar_images is None: pass else: self.avatar_images = [ self.serve_static_file(avatar_images[0]), self.serve_static_file(avatar_images[1]), ] self.placeholder = placeholder self.examples = examples self._setup_examples()
Parameters: value: Default list of messages to show in chatbot, where each message is of the format {"role": "user", "content": "Help me."}. Role can be one of "user", "assistant", or "system". Content should be either text, or media passed as a Gradio component, e.g. {"content": gr.Image("lion.jpg")}. If a function is provided, the function will be called each time the app loads to set the initial value of this component. type: The format of the messages passed into the chat history parameter of `fn`. If "messages", passes the value as a list of dictionaries with openai-style "role" and "content" keys. The "content" key's value should be one of the following - (1) strings in valid Markdown (2) a dictionary with a "path" key and value corresponding to the file to display or (3) an instance of a Gradio component. At the moment Image, Plot, Video, Gallery, Audio, and HTML are supported. The "role" key should be one of 'user' or 'assistant'. Any other roles will not be displayed in the output. If this parameter is 'tuples', expects a `list[list[str | None | tuple]]`, i.e. a list of lists. The inner list should have 2 elements: the user message and the response message, but this format is deprecated. 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. 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. autoscroll: If True, will automatically scroll to the bottom of the textbox when the value changes, unless the user scrolls up. If False, will not scroll to the bottom of the textbox when the value changes. 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. height: The height of the component, specified in pixels if a number is passed, or in CSS units if a string is passed. If messages exceed the height, the component will scroll. resizable: If True, the user of the Gradio app can resize the chatbot by dragging the bottom right corner. max_height: The maximum height of the component, specified in pixels if a number is passed, or in CSS units if a string is passed. If messages exceed the height, the component will scroll. If messages are shorter than the height, the component will shrink to fit the content. Will not have any effect if `height` is set and is smaller than `max_height`. min_height: The minimum height of the component, specified in pixels if a number is passed, or in CSS units if a string is passed. If messages exceed the height, the component will expand to fit the content. Will not have any effect if `height` is set and is larger than `min_height`. editable: Allows user to edit messages in the chatbot. If set to "user", allows editing of user messages. If set to "all", allows editing of assistant messages as well. 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). rtl: If True, sets the direction of the rendered text to right-to-left. Default is False, which renders text left-to-right. 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_copy_button: If True, will show a copy button for each chatbot message. avatar_images: Tuple of two avatar image paths or URLs for user and bot (in that order). Pass None for either the user or bot image to skip. Must be within the working directory of the Gradio app or an external URL. sanitize_html: If False, will disable HTML sanitization for chatbot messages. This is not recommended, as it can lead to security vulnerabilities. render_markdown: If False, will disable Markdown rendering for chatbot messages. feedback_options: A list of strings representing the feedback options that will be displayed to the user. The exact case-sensitive strings "Like" and "Dislike" will render as thumb icons, but any other choices will appear under a separate flag icon. feedback_value: A list of strings representing the feedback state for entire chat. Only works when type="messages". Each entry in the list corresponds to that assistant message, in order, and the value is the feedback given (e.g. "Like", "Dislike", or any custom feedback option) or None if no feedback was given for that message. bubble_full_width: Deprecated. 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 if `render_markdown` is True. layout: If "panel", will display the chatbot in a llm style layout. If "bubble", will display the chatbot with message bubbles, with the user and bot messages on alterating sides. Will default to "bubble". placeholder: a placeholder message to display in the chatbot when it is empty. Centered vertically and horizontally in the Chatbot. Supports Markdown and HTML. If None, no placeholder is displayed. examples: A list of example messages to display in the chatbot before any user/assistant messages are shown. Each example should be a dictionary with an optional "text" key representing the message that should be populated in the Chatbot when clicked, an optional "files" key, whose value should be a list of files to populate in the Chatbot, an optional "icon" key, whose value should be a filepath or URL to an image to display in the example box, and an optional "display_text" key, whose value should be the text to display in the example box. If "display_text" is not provided, the value of "text" will be displayed. show_copy_all_button: If True, will show a copy all button that copies all chatbot messages to the clipboard. allow_file_downloads: If True, will show a download button for chatbot messages that contain media. Defaults to True. group_consecutive_messages: If True, will display consecutive messages from the same role in the same bubble. If False, will display each message in a separate bubble. Defaults to True. allow_tags: If a list of tags is provided, these tags will be preserved in the output chatbot messages, even if `sanitize_html` is `True`. For example, if this list is ["thinking"], the tags `<thinking>` and `</thinking>` will not be removed. If True, all custom tags (non-standard HTML tags) will be preserved. If False, no tags will be preserved (default behavior).
__init__
python
gradio-app/gradio
gradio/components/chatbot.py
https://github.com/gradio-app/gradio/blob/master/gradio/components/chatbot.py
Apache-2.0
def preprocess( self, payload: ChatbotDataTuples | ChatbotDataMessages | None, ) -> list[list[str | tuple[str] | tuple[str, str] | None]] | list[MessageDict]: """ Parameters: payload: data as a ChatbotData object Returns: If type is 'tuples', passes the messages in the chatbot as a `list[list[str | None | tuple]]`, i.e. a list of lists. The inner list has 2 elements: the user message and the response message. Each message can be (1) a string in valid Markdown, (2) a tuple if there are displayed files: (a filepath or URL to a file, [optional string alt text]), or (3) None, if there is no message displayed. If type is 'messages', passes the value as a list of dictionaries with 'role' and 'content' keys. The `content` key's value supports everything the `tuples` format supports. """ if payload is None: return [] if self.type == "tuples": if not isinstance(payload, ChatbotDataTuples): raise Error("Data incompatible with the tuples format") return self._preprocess_messages_tuples(cast(ChatbotDataTuples, payload)) if not isinstance(payload, ChatbotDataMessages): raise Error("Data incompatible with the messages format") message_dicts = [] for message in payload.root: message_dict = cast(MessageDict, message.model_dump()) message_dict["content"] = self._preprocess_content(message.content) message_dicts.append(message_dict) return message_dicts
Parameters: payload: data as a ChatbotData object Returns: If type is 'tuples', passes the messages in the chatbot as a `list[list[str | None | tuple]]`, i.e. a list of lists. The inner list has 2 elements: the user message and the response message. Each message can be (1) a string in valid Markdown, (2) a tuple if there are displayed files: (a filepath or URL to a file, [optional string alt text]), or (3) None, if there is no message displayed. If type is 'messages', passes the value as a list of dictionaries with 'role' and 'content' keys. The `content` key's value supports everything the `tuples` format supports.
preprocess
python
gradio-app/gradio
gradio/components/chatbot.py
https://github.com/gradio-app/gradio/blob/master/gradio/components/chatbot.py
Apache-2.0
def postprocess( self, value: TupleFormat | list[MessageDict | Message] | None, ) -> ChatbotDataTuples | ChatbotDataMessages: """ Parameters: value: If type is `tuples`, expects a `list[list[str | None | tuple]]`, i.e. a list of lists. The inner list should have 2 elements: the user message and the response message. The individual messages can be (1) strings in valid Markdown, (2) tuples if sending files: (a filepath or URL to a file, [optional string alt text]) -- if the file is image/video/audio, it is displayed in the Chatbot, or (3) None, in which case the message is not displayed. If type is 'messages', passes the value as a list of dictionaries with 'role' and 'content' keys. The `content` key's value supports everything the `tuples` format supports. Returns: an object of type ChatbotData """ data_model = cast( Union[type[ChatbotDataTuples], type[ChatbotDataMessages]], self.data_model ) if value is None: return data_model(root=[]) if self.type == "tuples": self._check_format(value, "tuples") return self._postprocess_messages_tuples(cast(TupleFormat, value)) self._check_format(value, "messages") processed_messages = [ self._postprocess_message_messages(cast(MessageDict, message)) for message in value ] return ChatbotDataMessages(root=processed_messages)
Parameters: value: If type is `tuples`, expects a `list[list[str | None | tuple]]`, i.e. a list of lists. The inner list should have 2 elements: the user message and the response message. The individual messages can be (1) strings in valid Markdown, (2) tuples if sending files: (a filepath or URL to a file, [optional string alt text]) -- if the file is image/video/audio, it is displayed in the Chatbot, or (3) None, in which case the message is not displayed. If type is 'messages', passes the value as a list of dictionaries with 'role' and 'content' keys. The `content` key's value supports everything the `tuples` format supports. Returns: an object of type ChatbotData
postprocess
python
gradio-app/gradio
gradio/components/chatbot.py
https://github.com/gradio-app/gradio/blob/master/gradio/components/chatbot.py
Apache-2.0
def __init__( self, glob: str = "**/*", *, value: str | list[str] | Callable | None = None, file_count: Literal["single", "multiple"] = "multiple", root_dir: str | Path = ".", ignore_glob: 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, height: int | str | None = None, max_height: int | str | None = 500, min_height: int | str | 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, ): """ Parameters: glob: The glob-style pattern used to select which files to display, e.g. "*" to match all files, "*.png" to match all .png files, "**/*.txt" to match any .txt file in any subdirectory, etc. The default value matches all files and folders recursively. See the Python glob documentation at https://docs.python.org/3/library/glob.html for more information. value: The file (or list of files, depending on the `file_count` parameter) to show as "selected" when the component is first loaded. If a callable is provided, it will be called when the app loads to set the initial value of the component. If not provided, no files are shown as selected. file_count: Whether to allow single or multiple files to be selected. If "single", the component will return a single absolute file path as a string. If "multiple", the component will return a list of absolute file paths as a list of strings. root_dir: Path to root directory to select files from. If not provided, defaults to current working directory. ignore_glob: The glob-style, case-sensitive pattern that will be used to exclude files from the list. For example, "*.py" will exclude all .py files from the list. See the Python glob documentation at https://docs.python.org/3/library/glob.html for more information. 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 maximum height of the file component, 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 select file(s); if False, will only 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. """ self.root_dir = DeveloperPath(os.path.abspath(root_dir)) self.glob = glob self.ignore_glob = ignore_glob valid_file_count = ["single", "multiple"] if file_count not in valid_file_count: raise ValueError( f"Invalid value for parameter `file_count`: {file_count}. Please choose from one of: {valid_file_count}" ) self.file_count = file_count self.height = height self.max_height = max_height self.min_height = min_height 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, )
Parameters: glob: The glob-style pattern used to select which files to display, e.g. "*" to match all files, "*.png" to match all .png files, "**/*.txt" to match any .txt file in any subdirectory, etc. The default value matches all files and folders recursively. See the Python glob documentation at https://docs.python.org/3/library/glob.html for more information. value: The file (or list of files, depending on the `file_count` parameter) to show as "selected" when the component is first loaded. If a callable is provided, it will be called when the app loads to set the initial value of the component. If not provided, no files are shown as selected. file_count: Whether to allow single or multiple files to be selected. If "single", the component will return a single absolute file path as a string. If "multiple", the component will return a list of absolute file paths as a list of strings. root_dir: Path to root directory to select files from. If not provided, defaults to current working directory. ignore_glob: The glob-style, case-sensitive pattern that will be used to exclude files from the list. For example, "*.py" will exclude all .py files from the list. See the Python glob documentation at https://docs.python.org/3/library/glob.html for more information. 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 maximum height of the file component, 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 select file(s); if False, will only 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.
__init__
python
gradio-app/gradio
gradio/components/file_explorer.py
https://github.com/gradio-app/gradio/blob/master/gradio/components/file_explorer.py
Apache-2.0
def preprocess(self, payload: FileExplorerData | None) -> list[str] | str | None: """ Parameters: payload: List of selected files as a FileExplorerData object. Returns: Passes the selected file or directory as a `str` path (relative to `root`) or `list[str}` depending on `file_count` """ if payload is None: return None if self.file_count == "single": if len(payload.root) > 1: raise ValueError( f"Expected only one file, but {len(payload.root)} were selected." ) elif len(payload.root) == 0: return None else: return os.path.normpath(os.path.join(self.root_dir, *payload.root[0])) files = [] for file in payload.root: file_ = os.path.normpath(os.path.join(self.root_dir, *file)) files.append(file_) return files
Parameters: payload: List of selected files as a FileExplorerData object. Returns: Passes the selected file or directory as a `str` path (relative to `root`) or `list[str}` depending on `file_count`
preprocess
python
gradio-app/gradio
gradio/components/file_explorer.py
https://github.com/gradio-app/gradio/blob/master/gradio/components/file_explorer.py
Apache-2.0
def postprocess(self, value: str | list[str] | None) -> FileExplorerData | None: """ Parameters: value: Expects function to return a `str` path to a file, or `list[str]` consisting of paths to files. Returns: A FileExplorerData object containing the selected files as a list of strings. """ if value is None: return None files = [value] if isinstance(value, str) else value root = [] for file in files: root.append(self._strip_root(file).split(os.path.sep)) return FileExplorerData(root=root)
Parameters: value: Expects function to return a `str` path to a file, or `list[str]` consisting of paths to files. Returns: A FileExplorerData object containing the selected files as a list of strings.
postprocess
python
gradio-app/gradio
gradio/components/file_explorer.py
https://github.com/gradio-app/gradio/blob/master/gradio/components/file_explorer.py
Apache-2.0
def ls(self, subdirectory: list[str] | None = None) -> list[dict[str, str]] | None: """ Returns: a list of dictionaries, where each dictionary represents a file or subdirectory in the given subdirectory """ if subdirectory is None: subdirectory = [] full_subdir_path = self._safe_join(subdirectory) try: subdir_items = sorted(os.listdir(full_subdir_path)) except FileNotFoundError: return [] files, folders = [], [] for item in subdir_items: full_path = os.path.join(full_subdir_path, item) is_file = not os.path.isdir(full_path) valid_by_glob = fnmatch.fnmatch(full_path, self.glob) if is_file and not valid_by_glob: continue if self.ignore_glob and fnmatch.fnmatch(full_path, self.ignore_glob): continue target = files if is_file else folders target.append( { "name": item, "type": "file" if is_file else "folder", "valid": valid_by_glob, } ) return folders + files
Returns: a list of dictionaries, where each dictionary represents a file or subdirectory in the given subdirectory
ls
python
gradio-app/gradio
gradio/components/file_explorer.py
https://github.com/gradio-app/gradio/blob/master/gradio/components/file_explorer.py
Apache-2.0
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)
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.
__init__
python
gradio-app/gradio
gradio/components/download_button.py
https://github.com/gradio-app/gradio/blob/master/gradio/components/download_button.py
Apache-2.0
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
Parameters: payload: File information as a FileData object, Returns: (Rarely used) passes the file as a `str` into the function.
preprocess
python
gradio-app/gradio
gradio/components/download_button.py
https://github.com/gradio-app/gradio/blob/master/gradio/components/download_button.py
Apache-2.0
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)
Parameters: value: Expects a `str` or `pathlib.Path` filepath Returns: File information as a FileData object
postprocess
python
gradio-app/gradio
gradio/components/download_button.py
https://github.com/gradio-app/gradio/blob/master/gradio/components/download_button.py
Apache-2.0
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, )
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.
__init__
python
gradio-app/gradio
gradio/components/bar_plot.py
https://github.com/gradio-app/gradio/blob/master/gradio/components/bar_plot.py
Apache-2.0
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
Helper for creating the bar plot.
create_plot
python
gradio-app/gradio
gradio/components/bar_plot.py
https://github.com/gradio-app/gradio/blob/master/gradio/components/bar_plot.py
Apache-2.0
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
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").
preprocess
python
gradio-app/gradio
gradio/components/bar_plot.py
https://github.com/gradio-app/gradio/blob/master/gradio/components/bar_plot.py
Apache-2.0
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")
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").
postprocess
python
gradio-app/gradio
gradio/components/bar_plot.py
https://github.com/gradio-app/gradio/blob/master/gradio/components/bar_plot.py
Apache-2.0
def __init__( self, value: EditorValue | ImageType | None = None, *, height: int | str | None = None, width: int | str | None = None, image_mode: Literal[ "1", "L", "P", "RGB", "RGBA", "CMYK", "YCbCr", "LAB", "HSV", "I", "F" ] = "RGBA", sources: Iterable[Literal["upload", "webcam", "clipboard"]] | Literal["upload", "webcam", "clipboard"] | None = ( "upload", "webcam", "clipboard", ), type: Literal["numpy", "pil", "filepath"] = "numpy", label: str | None = None, every: Timer | float | None = None, inputs: Component | Sequence[Component] | set[Component] | None = None, show_label: bool | None = None, show_download_button: bool = True, 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, placeholder: str | None = None, mirror_webcam: bool = True, show_share_button: bool | None = None, _selectable: bool = False, crop_size: tuple[int | float, int | float] | str | None = None, transforms: Iterable[Literal["crop"]] = ("crop",), eraser: Eraser | None | Literal[False] = None, brush: Brush | None | Literal[False] = None, format: str = "webp", layers: bool = True, canvas_size: tuple[int, int] = (800, 800), fixed_canvas: bool = False, show_fullscreen_button: bool = True, ): """ Parameters: value: Optional initial image(s) to populate the image editor. Should be a dictionary with keys: `background`, `layers`, and `composite`. The values corresponding to `background` and `composite` should be images or None, while `layers` should be a list of images. Images can be of type PIL.Image, np.array, or str filepath/URL. Or, the value can be a callable, in which case the function will be called whenever the app loads to set the initial value of the component. 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 image files or numpy arrays, but will affect the displayed images. Beware of conflicting values with the canvas_size paramter. If the canvas_size is larger than the height, the editing canvas will not fit in the component. 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 image files or numpy arrays, but will affect the displayed images. Beware of conflicting values with the canvas_size paramter. If the canvas_size is larger than the height, the editing canvas will not fit in the component. image_mode: "RGB" if color, or "L" if black and white. See https://pillow.readthedocs.io/en/stable/handbook/concepts.html for other supported image modes and their meaning. sources: List of sources that can be used to set the background image. "upload" creates a box where user can drop an image file, "webcam" allows user to take snapshot from their webcam, "clipboard" allows users to paste an image from the clipboard. type: The format the images are converted to before being passed into the prediction function. "numpy" converts the images to numpy arrays with shape (height, width, 3) and values from 0 to 255, "pil" converts the images to PIL image objects, "filepath" passes images as str filepaths to temporary copies of the images. 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. show_download_button: If True, will display button to download image. 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 and edit an image; if False, can only be used to display images. If not provided, this is inferred based on whether the component is used as an input or output. 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. placeholder: Custom text for the upload area. Overrides default upload messages when provided. Accepts new lines and `#` to designate a heading. mirror_webcam: If True webcam will be mirrored. Default is True. 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. crop_size: Deprecated. Used to set the `canvas_size` parameter. transforms: The transforms tools to make available to users. "crop" allows the user to crop the image. eraser: The options for the eraser tool in the image editor. Should be an instance of the `gr.Eraser` class, or None to use the default settings. Can also be False to hide the eraser tool. [See `gr.Eraser` docs](#eraser). brush: The options for the brush tool in the image editor. Should be an instance of the `gr.Brush` class, or None to use the default settings. Can also be False to hide the brush tool, which will also hide the eraser tool. [See `gr.Brush` docs](#brush). format: Format to save image if it does not already have a valid format (e.g. if the image is being returned to the frontend as a numpy array or PIL Image). The format should be supported by the PIL library. This parameter has no effect on SVG files. layers: If True, will allow users to add layers to the image. If False, the layers option will be hidden. canvas_size: The size of the canvas in pixels. The first value is the width and the second value is the height. If its set, uploaded images will be rescaled to fit the canvas size while preserving the aspect ratio. The canvas size will always change to match the size of an uploaded image unless fixed_canvas is set to True. fixed_canvas: If True, the canvas size will not change based on the size of the background image and the image will be rescaled to fit (while preserving the aspect ratio) and placed in the center of the canvas. show_fullscreen_button: If True, will display button to view image in fullscreen mode. """ self._selectable = _selectable self.mirror_webcam = mirror_webcam valid_types = ["numpy", "pil", "filepath"] 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.height = height self.width = width self.image_mode = image_mode valid_sources = ["upload", "webcam", "clipboard"] if isinstance(sources, str): sources = [sources] if sources is not None: for source in sources: if source not in valid_sources: raise ValueError( f"`sources` must be a list consisting of elements in {valid_sources}" ) self.sources = sources else: self.sources = [] self.show_download_button = show_download_button self.show_share_button = ( (utils.get_space() is not None) if show_share_button is None else show_share_button ) if crop_size is not None: warnings.warn( "`crop_size` parameter is deprecated. Please use `canvas_size` instead." ) if isinstance(crop_size, str): # convert ratio to tuple proportion = [ int(crop_size.split(":")[0]), int(crop_size.split(":")[1]), ] ratio = proportion[0] / proportion[1] canvas_size = ( (int(800 * ratio), 800) if ratio > 1 else (800, int(800 / ratio)) ) else: canvas_size = (int(crop_size[0]), int(crop_size[1])) self.transforms = transforms self.eraser = Eraser() if eraser is None else eraser self.brush = Brush() if brush is None else brush self.blob_storage: dict[str, EditorDataBlobs] = {} self.format = format self.layers = layers self.canvas_size = canvas_size self.fixed_canvas = fixed_canvas self.show_fullscreen_button = show_fullscreen_button self.placeholder = placeholder 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, )
Parameters: value: Optional initial image(s) to populate the image editor. Should be a dictionary with keys: `background`, `layers`, and `composite`. The values corresponding to `background` and `composite` should be images or None, while `layers` should be a list of images. Images can be of type PIL.Image, np.array, or str filepath/URL. Or, the value can be a callable, in which case the function will be called whenever the app loads to set the initial value of the component. 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 image files or numpy arrays, but will affect the displayed images. Beware of conflicting values with the canvas_size paramter. If the canvas_size is larger than the height, the editing canvas will not fit in the component. 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 image files or numpy arrays, but will affect the displayed images. Beware of conflicting values with the canvas_size paramter. If the canvas_size is larger than the height, the editing canvas will not fit in the component. image_mode: "RGB" if color, or "L" if black and white. See https://pillow.readthedocs.io/en/stable/handbook/concepts.html for other supported image modes and their meaning. sources: List of sources that can be used to set the background image. "upload" creates a box where user can drop an image file, "webcam" allows user to take snapshot from their webcam, "clipboard" allows users to paste an image from the clipboard. type: The format the images are converted to before being passed into the prediction function. "numpy" converts the images to numpy arrays with shape (height, width, 3) and values from 0 to 255, "pil" converts the images to PIL image objects, "filepath" passes images as str filepaths to temporary copies of the images. 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. show_download_button: If True, will display button to download image. 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 and edit an image; if False, can only be used to display images. If not provided, this is inferred based on whether the component is used as an input or output. 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. placeholder: Custom text for the upload area. Overrides default upload messages when provided. Accepts new lines and `#` to designate a heading. mirror_webcam: If True webcam will be mirrored. Default is True. 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. crop_size: Deprecated. Used to set the `canvas_size` parameter. transforms: The transforms tools to make available to users. "crop" allows the user to crop the image. eraser: The options for the eraser tool in the image editor. Should be an instance of the `gr.Eraser` class, or None to use the default settings. Can also be False to hide the eraser tool. [See `gr.Eraser` docs](#eraser). brush: The options for the brush tool in the image editor. Should be an instance of the `gr.Brush` class, or None to use the default settings. Can also be False to hide the brush tool, which will also hide the eraser tool. [See `gr.Brush` docs](#brush). format: Format to save image if it does not already have a valid format (e.g. if the image is being returned to the frontend as a numpy array or PIL Image). The format should be supported by the PIL library. This parameter has no effect on SVG files. layers: If True, will allow users to add layers to the image. If False, the layers option will be hidden. canvas_size: The size of the canvas in pixels. The first value is the width and the second value is the height. If its set, uploaded images will be rescaled to fit the canvas size while preserving the aspect ratio. The canvas size will always change to match the size of an uploaded image unless fixed_canvas is set to True. fixed_canvas: If True, the canvas size will not change based on the size of the background image and the image will be rescaled to fit (while preserving the aspect ratio) and placed in the center of the canvas. show_fullscreen_button: If True, will display button to view image in fullscreen mode.
__init__
python
gradio-app/gradio
gradio/components/image_editor.py
https://github.com/gradio-app/gradio/blob/master/gradio/components/image_editor.py
Apache-2.0
def preprocess(self, payload: EditorData | None) -> EditorValue | None: """ Parameters: payload: An instance of `EditorData` consisting of the background image, layers, and composite image. Returns: Passes the uploaded images as an instance of EditorValue, which is just a `dict` with keys: 'background', 'layers', and 'composite'. The values corresponding to 'background' and 'composite' are images, while 'layers' is a `list` of images. The images are of type `PIL.Image`, `np.array`, or `str` filepath, depending on the `type` parameter. """ _payload = payload if payload is not None and payload.id is not None: cached = self.blob_storage.get(payload.id) _payload = ( EditorDataBlobs( background=cached.background, layers=cached.layers, composite=cached.composite, ) if cached else None ) elif _payload is None: return _payload else: _payload = payload bg = None layers = None composite = None if _payload is not None: bg = self.convert_and_format_image(_payload.background) layers = ( [self.convert_and_format_image(layer) for layer in _payload.layers] if _payload.layers else None ) composite = self.convert_and_format_image(_payload.composite) if payload is not None and payload.id is not None: self.blob_storage.pop(payload.id) return { "background": bg, "layers": [x for x in layers if x is not None] if layers else [], "composite": composite, }
Parameters: payload: An instance of `EditorData` consisting of the background image, layers, and composite image. Returns: Passes the uploaded images as an instance of EditorValue, which is just a `dict` with keys: 'background', 'layers', and 'composite'. The values corresponding to 'background' and 'composite' are images, while 'layers' is a `list` of images. The images are of type `PIL.Image`, `np.array`, or `str` filepath, depending on the `type` parameter.
preprocess
python
gradio-app/gradio
gradio/components/image_editor.py
https://github.com/gradio-app/gradio/blob/master/gradio/components/image_editor.py
Apache-2.0
def postprocess(self, value: EditorValue | ImageType | None) -> EditorData | None: """ Parameters: value: Expects a EditorValue, which is just a dictionary with keys: 'background', 'layers', and 'composite'. The values corresponding to 'background' and 'composite' should be images or None, while `layers` should be a list of images. Images can be of type `PIL.Image`, `np.array`, or `str` filepath/URL. Or, the value can be simply a single image (`ImageType`), in which case it will be used as the background. Returns: An instance of `EditorData` consisting of the background image, layers, and composite image. """ if value is None: return None elif isinstance(value, dict): pass elif isinstance(value, (np.ndarray, PIL.Image.Image, str)): value = {"background": value, "layers": [], "composite": value} else: raise ValueError( "The value to `gr.ImageEditor` must be a dictionary of images or a single image." ) layers = ( [ FileData( path=image_utils.save_image( cast(Union[np.ndarray, PIL.Image.Image, str], layer), self.GRADIO_CACHE, format=self.format, ) ) for layer in value["layers"] ] if value["layers"] else [] ) return EditorData( background=( FileData( path=image_utils.save_image( value["background"], self.GRADIO_CACHE, format=self.format ) ) if value["background"] is not None else None ), layers=layers, composite=( FileData( path=image_utils.save_image( cast( Union[np.ndarray, PIL.Image.Image, str], value["composite"] ), self.GRADIO_CACHE, format=self.format, ) ) if value["composite"] is not None else None ), )
Parameters: value: Expects a EditorValue, which is just a dictionary with keys: 'background', 'layers', and 'composite'. The values corresponding to 'background' and 'composite' should be images or None, while `layers` should be a list of images. Images can be of type `PIL.Image`, `np.array`, or `str` filepath/URL. Or, the value can be simply a single image (`ImageType`), in which case it will be used as the background. Returns: An instance of `EditorData` consisting of the background image, layers, and composite image.
postprocess
python
gradio-app/gradio
gradio/components/image_editor.py
https://github.com/gradio-app/gradio/blob/master/gradio/components/image_editor.py
Apache-2.0
def accept_blobs(self, data: AcceptBlobs): """ Accepts a dictionary of image blobs, where the keys are 'background', 'layers', and 'composite', and the values are binary file-like objects. """ type = data.data["type"] index = ( int(data.data["index"]) if data.data["index"] and data.data["index"] != "null" else None ) file = data.files[0][1] id = data.data["id"] current = self.blob_storage.get( id, EditorDataBlobs(background=None, layers=[], composite=None) ) if type == "layer" and index is not None: if index >= len(current.layers): current.layers.extend([None] * (index + 1 - len(current.layers))) current.layers[index] = file elif type == "background": current.background = file elif type == "composite": current.composite = file self.blob_storage[id] = current
Accepts a dictionary of image blobs, where the keys are 'background', 'layers', and 'composite', and the values are binary file-like objects.
accept_blobs
python
gradio-app/gradio
gradio/components/image_editor.py
https://github.com/gradio-app/gradio/blob/master/gradio/components/image_editor.py
Apache-2.0
def __init__( self, value: Any = None, render: bool = True, *, time_to_live: int | float | None = None, delete_callback: Callable[[Any], None] | None = None, ): """ Parameters: value: the initial value (of arbitrary type) of the state. The provided argument is deepcopied. If a callable is provided, the function will be called whenever the app loads to set the initial value of the state. render: should always be True, is included for consistency with other components. time_to_live: The number of seconds the state should be stored for after it is created or updated. If None, the state will be stored indefinitely. Gradio automatically deletes state variables after a user closes the browser tab or refreshes the page, so this is useful for clearing state for potentially long running sessions. delete_callback: A function that is called when the state is deleted. The function should take the state value as an argument. """ self.time_to_live = self.time_to_live = ( math.inf if time_to_live is None else time_to_live ) self.delete_callback = delete_callback or (lambda a: None) # noqa: ARG005 try: value = deepcopy(value) except TypeError as err: raise TypeError( f"The initial value of `gr.State` must be able to be deepcopied. The initial value of type {type(value)} cannot be deepcopied." ) from err super().__init__(value=value, render=render) self.value = value
Parameters: value: the initial value (of arbitrary type) of the state. The provided argument is deepcopied. If a callable is provided, the function will be called whenever the app loads to set the initial value of the state. render: should always be True, is included for consistency with other components. time_to_live: The number of seconds the state should be stored for after it is created or updated. If None, the state will be stored indefinitely. Gradio automatically deletes state variables after a user closes the browser tab or refreshes the page, so this is useful for clearing state for potentially long running sessions. delete_callback: A function that is called when the state is deleted. The function should take the state value as an argument.
__init__
python
gradio-app/gradio
gradio/components/state.py
https://github.com/gradio-app/gradio/blob/master/gradio/components/state.py
Apache-2.0
def preprocess(self, payload: Any) -> Any: """ Parameters: payload: Value Returns: Passes a value of arbitrary type through. """ return payload
Parameters: payload: Value Returns: Passes a value of arbitrary type through.
preprocess
python
gradio-app/gradio
gradio/components/state.py
https://github.com/gradio-app/gradio/blob/master/gradio/components/state.py
Apache-2.0
def postprocess(self, value: Any) -> Any: """ Parameters: value: Expects a value of arbitrary type, as long as it can be deepcopied. Returns: Passes a value of arbitrary type through. """ return value
Parameters: value: Expects a value of arbitrary type, as long as it can be deepcopied. Returns: Passes a value of arbitrary type through.
postprocess
python
gradio-app/gradio
gradio/components/state.py
https://github.com/gradio-app/gradio/blob/master/gradio/components/state.py
Apache-2.0
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 a function is provided, the function will be called each time the app loads to set the initial value of this 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
Parameters: value: Default file(s) to display, given as a str file path or URL, or a list of str file paths / URLs. If a function is provided, the function will be called each time the app loads to set the initial value of this 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.
__init__
python
gradio-app/gradio
gradio/components/file.py
https://github.com/gradio-app/gradio/blob/master/gradio/components/file.py
Apache-2.0