Document FileData class in docs (#8757)

* expose class + add docs

* add filedata section

* add changeset

* * add example usage
* expose FileData in Python client

* add changeset

* format

* tweaks

* tweaks

* fix test

* lint

* ruff lint

* lint again

* revert test

* remove desc from schema

---------

Co-authored-by: gradio-pr-bot <gradio-pr-bot@users.noreply.github.com>
Co-authored-by: Abubakar Abid <abubakar@huggingface.co>
This commit is contained in:
Hannah 2024-07-17 20:23:19 +01:00 committed by GitHub
parent e36bab77e5
commit 6073736651
No known key found for this signature in database
GPG Key ID: B5690EEEBB952194
6 changed files with 175 additions and 3 deletions

View File

@ -0,0 +1,7 @@
---
"gradio": patch
"gradio_client": patch
"website": patch
---
feat:Document `FileData` class in docs

View File

@ -1,9 +1,11 @@
from gradio_client.client import Client
from gradio_client.data_classes import FileData
from gradio_client.utils import __version__, file, handle_file
__all__ = [
"Client",
"file",
"handle_file",
"FileData",
"__version__",
]

View File

@ -49,6 +49,7 @@ _module_prefixes = [
("gradio.chat", "chatinterface"),
("gradio.component", "component"),
("gradio.events", "helpers"),
("gradio.data_classes", "helpers"),
("gradio.exceptions", "helpers"),
("gradio.external", "helpers"),
("gradio.flag", "flagging"),

View File

@ -317,7 +317,9 @@ class Component(ComponentBase, Block):
Keys of the dictionary are: raw_input, raw_output, serialized_input, serialized_output
"""
if self.data_model is not None:
return self.data_model.model_json_schema()
schema = self.data_model.model_json_schema()
schema.pop("description", None)
return schema
raise NotImplementedError(
f"The api_info method has not been implemented for {self.get_block_name()}"
)

View File

@ -11,6 +11,7 @@ from enum import Enum, auto
from typing import TYPE_CHECKING, Any, List, Literal, Optional, Tuple, TypedDict, Union
from fastapi import Request
from gradio_client.documentation import document
from gradio_client.utils import traverse
from typing_extensions import NotRequired
@ -219,7 +220,21 @@ class FileDataDict(TypedDict):
meta: dict
@document()
class FileData(GradioModel):
"""
The FileData class is a subclass of the GradioModel class that represents a file object within a Gradio interface. It is used to store file data and metadata when a file is uploaded.
Attributes:
path: The server file path where the file is stored.
url: The normalized server URL pointing to the file.
size: The size of the file in bytes.
orig_name: The original filename before upload.
mime_type: The MIME type of the file.
is_stream: Indicates whether the file is a stream.
meta: Additional metadata used internally (should not be changed).
"""
path: str # server filepath
url: Optional[str] = None # normalised server url
size: Optional[int] = None # size in bytes
@ -229,7 +244,13 @@ class FileData(GradioModel):
meta: dict = {"_type": "gradio.FileData"}
@property
def is_none(self):
def is_none(self) -> bool:
"""
Checks if the FileData object is empty, i.e., all attributes are None.
Returns:
bool: True if all attributes (except 'is_stream' and 'meta') are None, False otherwise.
"""
return all(
f is None
for f in [
@ -243,9 +264,30 @@ class FileData(GradioModel):
@classmethod
def from_path(cls, path: str) -> FileData:
"""
Creates a FileData object from a given file path.
Args:
path: The file path.
Returns:
FileData: An instance of FileData representing the file at the specified path.
"""
return cls(path=path)
def _copy_to_dir(self, dir: str) -> FileData:
"""
Copies the file to a specified directory and returns a new FileData object representing the copied file.
Args:
dir: The destination directory.
Returns:
FileData: A new FileData object representing the copied file.
Raises:
ValueError: If the source file path is not set.
"""
pathlib.Path(dir).mkdir(exist_ok=True)
new_obj = dict(self)
@ -256,7 +298,16 @@ class FileData(GradioModel):
return self.__class__(**new_obj)
@classmethod
def is_file_data(cls, obj: Any):
def is_file_data(cls, obj: Any) -> bool:
"""
Checks if an object is a valid FileData instance.
Args:
obj: The object to check.
Returns:
bool: True if the object is a valid FileData instance, False otherwise.
"""
if isinstance(obj, dict):
try:
return not FileData(**obj).is_none

View File

@ -0,0 +1,109 @@
<script lang="ts">
import {get_object} from "../../process_json.ts";
import ParamTable from "$lib/components/ParamTable.svelte";
import ShortcutTable from "$lib/components/ShortcutTable.svelte";
import DemosSection from "$lib/components/DemosSection.svelte";
import FunctionsSection from "$lib/components/FunctionsSection.svelte";
import GuidesSection from "$lib/components/GuidesSection.svelte";
import CopyButton from "$lib/components/CopyButton.svelte";
import { style_formatted_text } from "$lib/text";
let obj = get_object("filedata");
obj["attributes"] = [
{
name: "path",
annotation: "str",
doc: "The server file path where the file is stored.",
kwargs: null
},
{
name: "url",
annotation: "Optional[str]",
doc: "The normalized server URL pointing to the file.",
kwargs: null
},
{
name: "size",
annotation: "Optional[int]",
doc: "The size of the file in bytes.",
kwargs: null
},
{
name: "orig_name",
annotation: "Optional[str]",
doc: "The original filename before upload.",
kwargs: null
},
{
name: "mime_type",
annotation: "Optional[str]",
doc: "The MIME type of the file.",
kwargs: null
},
{
name: "is_stream",
annotation: "bool",
doc: "Indicates whether the file is a stream.",
kwargs: null
},
{
name: "meta",
annotation: "dict",
doc: "Additional metadata used internally (should not be changed).",
kwargs: null
}
]
</script>
<!--- Title -->
# {obj.name}
<!--- Usage -->
```python
gradio.FileData(···)
```
<!--- Description -->
### Description
## {@html style_formatted_text(obj.description)}
<!-- Example Usage -->
### Example Usage
```python
from gradio_client import Client, FileData, handle_file
def get_url_on_server(data: FileData):
print(data['url'])
client = Client("gradio/gif_maker_main", download_files=False)
job = client.submit([handle_file("./cheetah.jpg")], api_name="/predict")
data = job.result()
video: FileData = data['video']
get_url_on_server(video)
```
<!--- Initialization -->
### Attributes
<ParamTable parameters={obj.attributes} />
{#if obj.demos && obj.demos.length > 0}
<!--- Demos -->
### Demos
<DemosSection demos={obj.demos} />
{/if}
{#if obj.fns && obj.fns.length > 0}
<!--- Methods -->
### Methods
<FunctionsSection fns={obj.fns} event_listeners={false} />
{/if}
{#if obj.guides && obj.guides.length > 0}
<!--- Guides -->
### Guides
<GuidesSection guides={obj.guides}/>
{/if}