gradio_docs_rag_hfchattool / sources /documenting-custom-components.json
Csplk's picture
updated gradio sources
c840e14
{"guide": {"name": "documenting-custom-components", "category": "custom-components", "pretty_category": "Custom Components", "guide_index": 9, "absolute_index": 47, "pretty_name": "Documenting Custom Components", "content": "# Documenting Custom Components\n\nIn 4.15, we added a new `gradio cc docs` command to the Gradio CLI to generate rich documentation for your custom component. This command will generate documentation for users automatically, but to get the most out of it, you need to do a few things.\n\n## How do I use it?\n\nThe documentation will be generated when running `gradio cc build`. You can pass the `--no-generate-docs` argument to turn off this behaviour.\n\nThere is also a standalone `docs` command that allows for greater customisation. If you are running this command manually it should be run _after_ the `version` in your `pyproject.toml` has been bumped but before building the component.\n\nAll arguments are optional.\n\n```bash\ngradio cc docs\n path # The directory of the custom component.\n --demo-dir # Path to the demo directory.\n --demo-name # Name of the demo file\n --space-url # URL of the Hugging Face Space to link to\n --generate-space # create a documentation space.\n --no-generate-space # do not create a documentation space\n --readme-path # Path to the README.md file.\n --generate-readme # create a REAMDE.md file\n --no-generate-readme # do not create a README.md file\n --suppress-demo-check # suppress validation checks and warnings\n```\n\n## What gets generated?\n\nThe `gradio cc docs` command will generate an interactive Gradio app and a static README file with various features. You can see an example here:\n\n- [Gradio app deployed on Hugging Face Spaces]()\n- [README.md rendered by GitHub]()\n\nThe README.md and space both have the following features:\n\n- A description.\n- Installation instructions.\n- A fully functioning code snippet.\n- Optional links to PyPi, GitHub, and Hugging Face Spaces.\n- API documentation including:\n - An argument table for component initialisation showing types, defaults, and descriptions.\n - A description of how the component affects the user's predict function.\n - A table of events and their descriptions.\n - Any additional interfaces or classes that may be used during initialisation or in the pre- or post- processors.\n\nAdditionally, the Gradio includes:\n\n- A live demo.\n- A richer, interactive version of the parameter tables.\n- Nicer styling!\n\n## What do I need to do?\n\nThe documentation generator uses existing standards to extract the necessary information, namely Type Hints and Docstrings. There are no Gradio-specific APIs for documentation, so following best practices will generally yield the best results.\n\nIf you already use type hints and docstrings in your component source code, you don't need to do much to benefit from this feature, but there are some details that you should be aware of.\n\n### Python version\n\nTo get the best documentation experience, you need to use Python `3.10` or greater when generating documentation. This is because some introspection features used to generate the documentation were only added in `3.10`.\n\n### Type hints\n\nPython type hints are used extensively to provide helpful information for users. \n\n<details> \n<summary> What are type hints?</summary>\n\n\nIf you need to become more familiar with type hints in Python, they are a simple way to express what Python types are expected for arguments and return values of functions and methods. They provide a helpful in-editor experience, aid in maintenance, and integrate with various other tools. These types can be simple primitives, like `list` `str` `bool`; they could be more compound types like `list[str]`, `str | None` or `tuple[str, float | int]`; or they can be more complex types using utility classed like [`TypedDict`](https://peps.python.org/pep-0589/#abstract).\n\n[Read more about type hints in Python.](https://realpython.com/lessons/type-hinting/)\n\n\n</details>\n\n#### What do I need to add hints to?\n\nYou do not need to add type hints to every part of your code. For the documentation to work correctly, you will need to add type hints to the following component methods:\n\n- `__init__` parameters should be typed.\n- `postprocess` parameters and return value should be typed.\n- `preprocess` parameters and return value should be typed.\n\nIf you are using `gradio cc create`, these types should already exist, but you may need to tweak them based on any changes you make.\n\n##### `__init__`\n\nHere, you only need to type the parameters. If you have cloned a template with `gradio` cc create`, these should already be in place. You will only need to add new hints for anything you have added or changed:\n\n```py\ndef __init__(\n self,\n value: str | None = None,\n *,\n sources: Literal[\"upload\", \"microphone\"] = \"upload,\n every: Timer | float | None = None,\n ...\n):\n ...\n```\n\n##### `preprocess` and `postprocess`\n\nThe `preprocess` and `postprocess` methods determine the value passed to the user function and the value that needs to be returned.\n\nEven if the design of your component is primarily as an input or an output, it is worth adding type hints to both the input parameters and the return values because Gradio has no way of limiting how components can be used.\n\nIn this case, we specifically care about:\n\n- The return type of `preprocess`.\n- The input type of `postprocess`.\n\n```py\ndef preprocess(\n self, payload: FileData | None # input is optional\n) -> tuple[int, str] | str | None:\n\n# user function input is the preprocess return \u25b2\n# user function output is the postprocess input \u25bc\n\ndef postprocess(\n self, value: tuple[int, str] | None\n) -> FileData | bytes | None: # return is optional\n ...\n```\n\n### Docstrings\n\nDocstrings are also used extensively to extract more meaningful, human-readable descriptions of certain parts of the API.\n\n<details> \n<summary> What are docstrings?</summary>\n\n\nIf you need to become more familiar with docstrings in Python, they are a way to annotate parts of your code with human-readable decisions and explanations. They offer a rich in-editor experience like type hints, but unlike type hints, they don't have any specific syntax requirements. They are simple strings and can take almost any form. The only requirement is where they appear. Docstrings should be \"a string literal that occurs as the first statement in a module, function, class, or method definition\".\n\n[Read more about Python docstrings.](https://peps.python.org/pep-0257/#what-is-a-docstring)\n\n</details>\n\nWhile docstrings don't have any syntax requirements, we need a particular structure for documentation purposes.\n\nAs with type hint, the specific information we care about is as follows:\n\n- `__init__` parameter docstrings.\n- `preprocess` return docstrings.\n- `postprocess` input parameter docstrings.\n\nEverything else is optional.\n\nDocstrings should always take this format to be picked up by the documentation generator:\n\n#### Classes\n\n```py\n\"\"\"\nA description of the class.\n\nThis can span multiple lines and can _contain_ *markdown*.\n\"\"\"\n```\n\n#### Methods and functions \n\nMarkdown in these descriptions will not be converted into formatted text.\n\n```py\n\"\"\"\nParameters:\n param_one: A description for this parameter.\n param_two: A description for this parameter.\nReturns:\n A description for this return value.\n\"\"\"\n```\n\n### Events\n\nIn custom components, events are expressed as a list stored on the `events` field of the component class. While we do not need types for events, we _do_ need a human-readable description so users can understand the behaviour of the event.\n\nTo facilitate this, we must create the event in a specific way.\n\nThere are two ways to add events to a custom component.\n\n#### Built-in events\n\nGradio comes with a variety of built-in events that may be enough for your component. If you are using built-in events, you do not need to do anything as they already have descriptions we can extract:\n\n```py\nfrom gradio.events import Events\n\nclass ParamViewer(Component):\n ...\n\n EVENTS = [\n Events.change,\n Events.upload,\n ]\n```\n\n#### Custom events\n\nYou can define a custom event if the built-in events are unsuitable for your use case. This is a straightforward process, but you must create the event in this way for docstrings to work correctly:\n\n```py\nfrom gradio.events import Events, EventListener\n\nclass ParamViewer(Component):\n ...\n\n EVENTS = [\n Events.change,\n EventListener(\n \"bingbong\",\n doc=\"This listener is triggered when the user does a bingbong.\"\n )\n ]\n```\n\n### Demo\n\nThe `demo/app.py`, often used for developing the component, generates the live demo and code snippet. The only strict rule here is that the `demo.launch()` command must be contained with a `__name__ == \"__main__\"` conditional as below:\n\n```py\nif __name__ == \"__main__\":\n demo.launch()\n```\n\nThe documentation generator will scan for such a clause and error if absent. If you are _not_ launching the demo inside the `demo/app.py`, then you can pass `--suppress-demo-check` to turn off this check.\n\n#### Demo recommendations\n\nAlthough there are no additional rules, there are some best practices you should bear in mind to get the best experience from the documentation generator.\n\nThese are only guidelines, and every situation is unique, but they are sound principles to remember.\n\n##### Keep the demo compact\n\nCompact demos look better and make it easier for users to understand what the demo does. Try to remove as many extraneous UI elements as possible to focus the users' attention on the core use case. \n\nSometimes, it might make sense to have a `demo/app.py` just for the docs and an additional, more complex app for your testing purposes. You can also create other spaces, showcasing more complex examples and linking to them from the main class docstring or the `pyproject.toml` description.\n\n#### Keep the code concise\n\nThe 'getting started' snippet utilises the demo code, which should be as short as possible to keep users engaged and avoid confusion.\n\nIt isn't the job of the sample snippet to demonstrate the whole API; this snippet should be the shortest path to success for a new user. It should be easy to type or copy-paste and easy to understand. Explanatory comments should be brief and to the point.\n\n#### Avoid external dependencies\n\nAs mentioned above, users should be able to copy-paste a snippet and have a fully working app. Try to avoid third-party library dependencies to facilitate this.\n\nYou should carefully consider any examples; avoiding examples that require additional files or that make assumptions about the environment is generally a good idea.\n\n#### Ensure the `demo` directory is self-contained\n\nOnly the `demo` directory will be uploaded to Hugging Face spaces in certain instances, as the component will be installed via PyPi if possible. It is essential that this directory is self-contained and any files needed for the correct running of the demo are present.\n\n### Additional URLs\n\nThe documentation generator will generate a few buttons, providing helpful information and links to users. They are obtained automatically in some cases, but some need to be explicitly included in the `pyproject.yaml`. \n\n- PyPi Version and link - This is generated automatically.\n- GitHub Repository - This is populated via the `pyproject.toml`'s `project.urls.repository`.\n- Hugging Face Space - This is populated via the `pyproject.toml`'s `project.urls.space`.\n\nAn example `pyproject.toml` urls section might look like this:\n\n```toml\n[project.urls]\nrepository = \"https://github.com/user/repo-name\"\nspace = \"https://huggingface.co/spaces/user/space-name\"\n```", "tags": [], "spaces": [], "url": "/guides/documenting-custom-components/", "contributor": null}}