Repository: gradio-app/gradio
Pull request: add autodocs
## Description

This is the bulk of the work for autodocumenting custom components. To test this you will need to install `gradio_paramviewer` from pip. 

I will be moving this component into gradio core, so we don't need an additional dependency but I haven't quite got round to that.

I also had to remove the readme generation out while i fixed some issues but I'll add that back very shortly.

Closes #6684. Closes #6648.

## 🎯 PRs Should Target Issues

Before your create a PR, please check to see if there is [an existing issue](https://github.com/gradio-app/gradio/issues) for this change. If not, please create an issue before you create this PR, unless the fix is very small. 

Not adhering to this guideline will result in the PR being closed. 

## Tests

1. PRs will only be merged if tests pass on CI. To run the tests locally, please set up [your Gradio environment locally](https://github.com/gradio-app/gradio/blob/main/CONTRIBUTING.md) and run the tests: `bash scripts/run_all_tests.sh`

2. You may need to run the linters: `bash scripts/format_backend.sh` and `bash scripts/format_frontend.sh`
  


Problem statement:
Autogenerate docs for custom components
It would be nice to document a few things for custom components:

* How to import them and use them in a Gradio app (e.g. `from gradio_richtextbox import RichTextbox`)
* What parameters the custom component supports
* What events the custom component supports

This could be included in the Custom Components gallery that @freddyaboulton is building, as well as potentially on the pypi package itself.

add command to autodocument custom components
CLI command to autodocument custom components.

- generate nice docs space 
- generate readme (for pypi and github)

Hints from issue discussion:
Maybe the build command can autodocument by default and it can be disabled with an optional argument
Dupe of #6648

Commit message: add changeset

Patch to review:
diff --git a/.changeset/eager-grapes-relate.md b/.changeset/eager-grapes-relate.md
new file mode 100644
index 0000000000..87fe2e8325
--- /dev/null
+++ b/.changeset/eager-grapes-relate.md
@@ -0,0 +1,7 @@
+---
+"@gradio/app": minor
+"@gradio/paramviewer": minor
+"gradio": minor
+---
+
+feat:add autodocs
diff --git a/gradio/__init__.py b/gradio/__init__.py
index aff15dd4d1..0a29ad49d1 100644
--- a/gradio/__init__.py
+++ b/gradio/__init__.py
@@ -46,6 +46,7 @@
     Markdown,
     Model3D,
     Number,
+    ParamViewer,
     Plot,
     Radio,
     ScatterPlot,
diff --git a/gradio/cli/commands/components/_docs_utils.py b/gradio/cli/commands/components/_docs_utils.py
new file mode 100644
index 0000000000..426ea0a0bc
--- /dev/null
+++ b/gradio/cli/commands/components/_docs_utils.py
@@ -0,0 +1,747 @@
+import inspect
+import json
+import re
+import types
+import typing
+from subprocess import PIPE, Popen
+
+
+def find_first_non_return_key(some_dict):
+    """Finds the first key in a dictionary that is not "return"."""
+    for key, value in some_dict.items():
+        if key != "return":
+            return value
+    return None
+
+
+def format(code: str, type: str):
+    """Formats code using ruff."""
+    if type == "value":
+        code = f"value = {code}"
+
+    ruff_args = ["ruff", "format", "-", "--line-length=60"]
+
+    process = Popen(
+        ruff_args,
+        stdin=PIPE,
+        stdout=PIPE,
+        stderr=PIPE,
+        universal_newlines=True,
+    )
+    formatted_code, err = process.communicate(input=code)
+
+    if type == "value":
+        formatted_code = re.sub(
+            r"^\s*value =\s*", "", formatted_code, flags=re.MULTILINE
+        )
+
+    stripped_source = re.search(r"^\s*\((.*)\)\s*$", formatted_code, re.DOTALL)
+
+    return (
+        stripped_source.group(1).strip() if stripped_source else formatted_code.strip()
+    )
+
+
+def get_param_name(param):
+    """Gets the name of a parameter."""
+
+    if isinstance(param, str):
+        return f'"{param}"'
+    if inspect.isclass(param) and param.__module__ == "builtins":
+        p = getattr(param, "__name__", None)
+        if p is None and inspect.isclass(param):
+            p = f"{param.__module__}.{param.__name__}"
+        return p
+
+    if inspect.isclass(param):
+        return f"{param.__module__}.{param.__name__}"
+
+    param_name = getattr(param, "__name__", None)
+
+    if param_name is None:
+        param_name = str(param)
+
+    return param_name
+
+
+def format_none(value):
+    """Formats None and NonType values."""
+    if value is None or value is type(None) or value == "None" or value == "NoneType":
+        return "None"
+    return value
+
+
+def format_value(value):
+    """Formats a value."""
+    if value is None:
+        return "None"
+    if isinstance(value, str):
+        return f'"{value}"'
+    return str(value)
+
+
+def get_parameter_docstring(docstring: str, parameter_name: str):
+    """Gets the docstring for a parameter."""
+    pattern = rf"\b{parameter_name}\b:[ \t]*(.*?)(?=\n|$)"
+
+    match = re.search(pattern, docstring, flags=re.DOTALL)
+    if match:
+        return match.group(1).strip()
+
+    return None
+
+
+def get_return_docstring(docstring: str):
+    """Gets the docstring for a return value."""
+    pattern = r"\bReturn(?:s){0,1}\b:[ \t\n]*(.*?)(?=\n|$)"
+
+    match = re.search(pattern, docstring, flags=re.DOTALL | re.IGNORECASE)
+    if match:
+        return match.group(1).strip()
+
+    return None
+
+
+def add_value(obj, key, value):
+    """Adds a value to a dictionary."""
+    type = "value" if key == "default" else "type"
+    obj[key] = format(value, type)
+
+    return obj
+
+
+def set_deep(dictionary, keys, value):
+    """Sets a value in a nested dictionary for a key path that may not exist"""
+    for key in keys[:-1]:
+        dictionary = dictionary.setdefault(key, {})
+    dictionary[keys[-1]] = value
+
+
+def get_deep(dictionary, keys):
+    """Gets a value from a nested dictionary without erroring if the key doesn't exist."""
+    try:
+        for key in keys:
+            dictionary = dictionary[key]
+        return dictionary
+    except KeyError:
+        return None
+
+
+def get_type_arguments(type_hint) -> tuple:
+    """Gets the type arguments for a type hint."""
+    if hasattr(type_hint, "__args__"):
+        return type_hint.__args__
+    elif hasattr(type_hint, "__extra__"):
+        return type_hint.__extra__.__args__
+    else:
+        return typing.get_args(type_hint)
+
+
+def get_container_name(arg):
+    """Gets a human readable name for a type."""
+
+    # This is a bit of a hack to get the generic type for python 3.8
+    generic_type = getattr(typing, "_GenericAlias", None)
+    generic_type_tuple = (
+        (types.GenericAlias,)
+        if generic_type is None
+        else (types.GenericAlias, generic_type)
+    )
+
+    if inspect.isclass(arg):
+        return arg.__name__
+    if isinstance(arg, (generic_type_tuple)):
+        return arg.__origin__.__name__
+    elif isinstance(arg, types.UnionType):
+        return "Union"
+    elif getattr(arg, "__origin__", None) is typing.Literal:
+        return "Literal"
+
+    else:
+        return str(arg)
+
+
+def format_type(_type: list[typing.Any], current=None):
+    """Pretty formats a possibly nested type hint."""
+    s = []
+    _current = None
+    for t in _type:
+        if isinstance(t, str):
+            _current = format_none(t)
+            continue
+
+        elif isinstance(t, list):
+            if len(t) == 0:
+                continue
+            s.append(f"{format_type(t, _current)}")
+        else:
+            s.append(t)
+    if len(s) == 0:
+        return _current
+    elif _current == "Literal" or _current == "Union":
+        return "| ".join(s)
+    else:
+        return f"{_current}[{','.join(s)}]"
+
+
+def get_type_hints(param, module, ignore=None):
+    """Gets the type hints for a parameter."""
+
+    def extract_args(
+        arg,
+        module_name_prefix,
+        additional_interfaces,
+        user_fn_refs,
+        append=True,
+        arg_of=None,
+    ):
+        """Recursively extracts the arguments from a type hint."""
+        arg_names = []
+        args = get_type_arguments(arg)
+
+        # These are local classes that are used in types
+        if inspect.isclass(arg) and arg.__module__.startswith(module_name_prefix):
+            # get sourcecode for the class
+
+            source_code = inspect.getsource(arg)
+
+            if arg_of is not None:
+                refs = get_deep(additional_interfaces, [arg_of, "refs"])
+
+                if refs is None:
+                    refs = [arg.__name__]
+                elif arg.__name__ not in refs:
+                    refs.append(arg.__name__)
+
+                set_deep(additional_interfaces, [arg_of, "refs"], refs)
+
+            if get_deep(additional_interfaces, [arg.__name__, "source"]) is None:
+                set_deep(additional_interfaces, [arg.__name__, "source"], source_code)
+
+            for field_type in typing.get_type_hints(arg).values():
+                # We want to recursively extract the source code for the fields but we don't want to add them to the list of arguments
+                new_args = extract_args(
+                    field_type,
+                    module_name_prefix,
+                    additional_interfaces,
+                    user_fn_refs,
+                    False,
+                    arg.__name__,
+                )
+
+                if len(new_args) > 0:
+                    arg_names.append(new_args)
+
+            if append:
+                arg_names.append(arg.__name__)
+                if arg.__name__ not in user_fn_refs:
+                    user_fn_refs.append(arg.__name__)
+        elif len(args) > 0:
+            if append:
+                arg_names.append(get_container_name(arg))
+            for inner_arg in list(args):
+                new_args = extract_args(
+                    inner_arg,
+                    module_name_prefix,
+                    additional_interfaces,
+                    user_fn_refs,
+                    True,
+                )
+
+                if len(new_args) > 0:
+                    arg_names.append(new_args)
+        else:
+            if append:
+                arg_names.append(get_param_name(arg))
+        return arg_names
+
+    module_name_prefix = module.__name__ + "."
+    additional_interfaces = {}
+    user_fn_refs = []
+
+    args = extract_args(
+        param,
+        module_name_prefix,
+        additional_interfaces,
+        user_fn_refs,
+    )
+
+    formatted_type = format_type(args)
+
+    return (formatted_type, additional_interfaces, user_fn_refs)
+
+
+def extract_docstrings(module):
+    docs = {}
+    for name, obj in inspect.getmembers(module):
+        # filter out the builtins etc
+        if name.startswith("_"):
+            continue
+        #  this could be expanded but i think is ok for now
+        if inspect.isfunction(obj) or inspect.isclass(obj):
+            docs[name] = {}
+
+            main_docstring = inspect.getdoc(obj) or ""
+            cleaned_docstring = str.join(
+                "\n",
+                [s for s in main_docstring.split("\n") if not re.match(r"^\S+:", s)],
+            )
+
+            docs[name]["description"] = cleaned_docstring
+            docs[name]["members"] = {}
+            docs["__meta__"] = {"additional_interfaces": {}}
+            for member_name, member in inspect.getmembers(obj):
+                if inspect.ismethod(member) or inspect.isfunction(member):
+                    # we are are only interested in these methods
+                    if (
+                        member_name != "__init__"
+                        and member_name != "preprocess"
+                        and member_name != "postprocess"
+                    ):
+                        continue
+
+                    docs[name]["members"][member_name] = {}
+
+                    member_docstring = inspect.getdoc(member) or ""
+                    hints = typing.get_type_hints(member)
+                    signature = inspect.signature(member)
+
+                    #  we iterate over the parameters and get the type information
+                    for param_name, param in hints.items():
+                        if (
+                            param_name == "return" and member_name == "postprocess"
+                        ) or (param_name != "return" and member_name == "preprocess"):
+                            continue
+                        _hints = get_type_hints(param, module)
+                        arg_names, additional_interfaces, user_fn_refs = _hints
+
+                        #  These interfaces belong to the whole module, so we add them 'globally' for later
+                        docs["__meta__"]["additional_interfaces"].update(
+                            additional_interfaces
+                        )
+
+                        docs[name]["members"][member_name][param_name] = {}
+
+                        if param_name == "return":
+                            docstring = get_return_docstring(member_docstring)
+                        else:
+                            docstring = get_parameter_docstring(
+                                member_docstring, param_name
+                            )
+
+                        add_value(
+                            docs[name]["members"][member_name][param_name],
+                            "type",
+                            arg_names,
+                        )
+
+                        if signature.parameters.get(param_name, None) is not None:
+                            default_value = signature.parameters[param_name].default
+
+                            add_value(
+                                docs[name]["members"][member_name][param_name],
+                                "default",
+                                format_value(default_value),
+                            )
+
+                        docs[name]["members"][member_name][param_name][
+                            "description"
+                        ] = docstring
+
+                        # We just want to normalise the arg name to 'value' for the preprocess and postprocess methods
+                        if member_name == "postprocess" or member_name == "preprocess":
+                            docs[name]["members"][member_name][
+                                "value"
+                            ] = find_first_non_return_key(
+                                docs[name]["members"][member_name]
+                            )
+                            additional_refs = get_deep(
+                                docs, ["__meta__", "user_fn_refs", name]
+                            )
+                            if additional_refs is None:
+                                set_deep(
+                                    docs,
+                                    ["__meta__", "user_fn_refs", name],
+                                    set(user_fn_refs),
+                                )
+                            else:
+                                additional_refs = set(additional_refs)
+                                additional_refs.update(user_fn_refs)
+                                set_deep(
+                                    docs,
+                                    ["__meta__", "user_fn_refs", name],
+                                    additional_refs,
+                                )
+                if member_name == "EVENTS":
+                    docs[name]["events"] = {}
+                    if isinstance(member, list):
+                        for event in member:
+                            docs[name]["events"][str(event)] = {
+                                "type": None,
+                                "default": None,
+                                "description": event.doc.replace(
+                                    "{{ component }}", name
+                                ),
+                            }
+        final_user_fn_refs = get_deep(docs, ["__meta__", "user_fn_refs", name])
+        if final_user_fn_refs is not None:
+            set_deep(docs, ["__meta__", "user_fn_refs", name], list(final_user_fn_refs))
+    with open("docs.json", "w") as f:
+        f.write(json.dumps(docs, indent=4))
+    return docs
+
+
+class AdditionalInterface(typing.TypedDict):
+    refs: list[str]
+    source: str
+
+
+def make_js(
+    interfaces: dict[str, AdditionalInterface],
+    user_fn_refs: dict[str, list[str]] | None = None,
+):
+    """Makes the javascript code for the additional interfaces."""
+    js_obj_interfaces = "{"
+    for interface_name, interface in interfaces.items():
+        js_obj_interfaces += f"""
+        {interface_name}: {interface.get("refs", None) or "[]"}, """
+    js_obj_interfaces += "}"
+
+    js_obj_user_fn_refs = "{"
+    if user_fn_refs is not None:
+        for class_name, refs in user_fn_refs.items():
+            js_obj_user_fn_refs += f"""
+          {class_name}: {refs}, """
+
+    js_obj_user_fn_refs += "}"
+
+    return rf"""function() {{
+    const refs = {js_obj_interfaces};
+    const user_fn_refs = {js_obj_user_fn_refs};
+    requestAnimationFrame(() => {{
+
+        Object.entries(user_fn_refs).forEach(([key, refs]) => {{
+            if (refs.length > 0) {{
+                const el = document.querySelector(`.${{key}}-user-fn`);
+                if (!el) return;
+                refs.forEach(ref => {{
+                    el.innerHTML = el.innerHTML.replace(
+                        new RegExp("\\b"+ref+"\\b", "g"),
+                        `<a href="#h-${{ref.toLowerCase()}}">${{ref}}</a>`
+                    );
+                }})
+            }}
+        }})
+        
+        Object.entries(refs).forEach(([key, refs]) => {{
+            if (refs.length > 0) {{
+                const el = document.querySelector(`.${{key}}`);
+                if (!el) return;
+                refs.forEach(ref => {{
+                    el.innerHTML = el.innerHTML.replace(
+                        new RegExp("\\b"+ref+"\\b", "g"),
+                        `<a href="#h-${{ref.toLowerCase()}}">${{ref}}</a>`
+                    );
+                }})
+            }}
+        }})
+    }})
+}}
+"""
+
+
+def render_additional_interfaces(interfaces):
+    """Renders additional helper classes or types that were extracted earlier."""
+
+    source = ""
+    for interface_name, interface in interfaces.items():
+        source += f"""
+    code_{interface_name} = gr.Markdown(\"\"\"
+## `{interface_name}`
+```python
+{interface["source"]}
+```\"\"\", elem_classes=["md-custom", "{interface_name}"], header_links=True)
+"""
+    return source
+
+
+def render_additional_interfaces_markdown(interfaces):
+    """Renders additional helper classes or types that were extracted earlier."""
+
+    source = ""
+    for interface_name, interface in interfaces.items():
+        source += f"""
+## `{interface_name}`
+```python
+{interface["source"]}
+```
+"""
+    return source
+
+
+def render_version_badge(pypi_exists, local_version, name):
+    """Renders a version badge for the package. PyPi badge if it exists, otherwise a static badge."""
+    if pypi_exists:
+        return f"""<a href="https://pypi.org/project/{name}/" target="_blank"><img alt="PyPI - Version" src="https://img.shields.io/pypi/v/{name}"></a>"""
+    else:
+        return f"""<img alt="Static Badge" src="https://img.shields.io/badge/version%20-%20{local_version}%20-%20orange">"""
+
+
+def render_github_badge(repo):
+    """Renders a github badge for the package if a repo is specified."""
+    if repo:
+        return f"""<a href="{repo}/issues" target="_blank"><img alt="Static Badge" src="https://img.shields.io/badge/Issues-white?logo=github&logoColor=black"></a>"""
+    else:
+        """"""
+
+
+def render_discuss_badge(space):
+    """Renders a discuss badge for the package if a space is specified."""
+    if space:
+        return f"""<a href="{space}/discussions" target="_blank"><img alt="Static Badge" src="https://img.shields.io/badge/%F0%9F%A4%97%20Discuss-%23097EFF?style=flat&logoColor=black"></a>"""
+    else:
+        """"""
+
+
+def render_class_events(events, name):
+    """Renders the events for a class."""
+    if events is not None:
+        return f"""
+    gr.Markdown("### Events")
+    gr.ParamViewer(value=_docs["{name}"]["events"], linkify={["Event"]})
+
+"""
+
+
+def render_class_events_markdown(events):
+    """Renders the events for a class."""
+    if events is None:
+        return ""
+
+    event_table = """
+### Events
+
+| name | description |
+|:-----|:------------|
+"""
+
+    for event_name, event in events.items():
+        event_table += f"| `{event_name}` | {event['description']} |\n"
+
+    return event_table
+
+
+def render_class_docs(exports, docs):
+    """Renders the class documentation for the package."""
+    docs_classes = ""
+    for class_name in exports:
+        docs_classes += f"""
+    gr.Markdown(\"\"\"
+## `{class_name}`
+
+### Initialization
+\"\"\", elem_classes=["md-custom"], header_links=True)
+
+    gr.ParamViewer(value=_docs["{class_name}"]["members"]["__init__"], linkify={["Parameter"]})
+
+{render_class_events(docs[class_name].get("events", None), class_name)}
+
+    gr.Markdown(\"\"\"
+
+### User function
+
+- **As output:** Is passed, {docs[class_name]["members"]["preprocess"]["return"]["description"]}.
+- **As input:** Should return, {docs[class_name]["members"]["postprocess"]["value"]["description"]}.
+
+```python
+def predict(
+    value: {docs[class_name]["members"]["preprocess"]["return"]["type"]}
+) -> {docs[class_name]["members"]["postprocess"]["value"]["type"]}:
+    return value 
+```
+\"\"\", elem_classes=["md-custom", "{class_name}-user-fn"], header_links=True)
+
+
+    """
+    return docs_classes
+
+
+html = """
+<table>
+<thead>
+<tr>
+<th align="left">name</th>
+<th align="left">type</th>
+<th align="left">default</th>
+<th align="left">description</th>
+</tr>
+</thead>
+<tbody><tr>
+<td align="left"><code>value</code></td>
+<td align="left"><code>list[Parameter] | None</code></td>
+<td align="left"><code>None</code></td>
+<td align="left">A list of dictionaries with keys "type", "description", and "default" for each parameter.</td>
+</tr>
+</tbody></table>
+"""
+
+
+def render_param_table(params):
+    """Renders the parameter table for the package."""
+    table = """<table>
+<thead>
+<tr>
+<th align="left">name</th>
+<th align="left" style="width: 25%;">type</th>
+<th align="left">default</th>
+<th align="left">description</th>
+</tr>
+</thead>
+<tbody>"""
+
+    # for class_name in exports:
+    #     docs_classes += f"""
+    #     """
+    for param_name, param in params.items():
+        table += f"""
+<tr>
+<td align="left"><code>{param_name}</code></td>
+<td align="left" style="width: 25%;">
+
+```python
+{param["type"]}
+```
+
+</td>
+<td align="left"><code>{param["default"]}</code></td>
+<td align="left">{param['description']}</td>
+</tr>
+"""
+    return table + "</tbody></table>"
+
+
+def render_class_docs_markdown(exports, docs):
+    """Renders the class documentation for the package."""
+    docs_classes = ""
+    for class_name in exports:
+        docs_classes += f"""
+## `{class_name}`
+
+### Initialization
+
+{render_param_table(docs[class_name]["members"]["__init__"])}
+
+{render_class_events_markdown(docs[class_name].get("events", None))}
+
+### User function
+
+- **As output:** Is passed, {docs[class_name]["members"]["preprocess"]["return"]["description"]}.
+- **As input:** Should return, {docs[class_name]["members"]["postprocess"]["value"]["description"]}.
+
+```python
+def predict(
+    value: {docs[class_name]["members"]["preprocess"]["return"]["type"]}
+) -> {docs[class_name]["members"]["postprocess"]["value"]["type"]}:
+    return value 
+```
+"""
+    return docs_classes
+
+
+def make_space(docs, name, description, local_version, demo, space, repo, pypi_exists):
+    filtered_keys = [key for key in docs if key != "__meta__"]
+
+    source = f"""
+import gradio as gr
+from app import demo as app
+from {name} import {",".join(filtered_keys)}
+import os
+"""
+
+    docs_classes = render_class_docs(filtered_keys, docs)
+
+    source += f"""
+_docs = {docs}
+    
+abs_path = os.path.join(os.path.dirname(__file__), "css.css")
+
+with gr.Blocks(
+    css=abs_path,
+    theme=gr.themes.Default(
+        font_mono=[
+            gr.themes.GoogleFont("Inconsolata"),
+            "monospace",
+        ],
+    ),
+) as demo:
+    gr.Markdown(
+\"\"\"
+# `{name}`
+
+<div style="display: flex; gap: 7px;">
+{render_version_badge(pypi_exists, local_version, name)}{render_github_badge(repo)}{render_discuss_badge(space)}
+</div>
+
+{description}
+\"\"\", elem_classes=["md-custom"], header_links=True)
+    app.render()
+    gr.Markdown(
+\"\"\"
+## Installation
+
+```bash
+pip install {name}
+```
+
+## Usage
+
+```python
+{demo}
+```
+\"\"\", elem_classes=["md-custom"], header_links=True)
+
+{docs_classes}
+
+{render_additional_interfaces(docs["__meta__"]["additional_interfaces"])}
+    demo.load(None, js=r\"\"\"{make_js(docs["__meta__"]["additional_interfaces"], docs["__meta__"]["user_fn_refs"])}
+\"\"\")
+
+demo.launch()
+"""
+
+    return source
+
+
+def make_markdown(
+    docs, name, description, local_version, demo, space, repo, pypi_exists
+):
+    filtered_keys = [key for key in docs if key != "__meta__"]
+
+    source = f"""
+# `{name}`
+{render_version_badge(pypi_exists, local_version, name)}{render_github_badge(repo)}{render_discuss_badge(space)}
+
+{description}
+
+## Installation
+    
+```bash 
+pip install {name}
+```
+
+## Usage
+
+```python
+{demo}
+```
+"""
+
+    docs_classes = render_class_docs_markdown(filtered_keys, docs)
+
+    source += docs_classes
+
+    source += render_additional_interfaces_markdown(
+        docs["__meta__"]["additional_interfaces"]
+    )
+
+    return source
diff --git a/gradio/cli/commands/components/app.py b/gradio/cli/commands/components/app.py
index e8984c0fb4..d42252a024 100644
--- a/gradio/cli/commands/components/app.py
+++ b/gradio/cli/commands/components/app.py
@@ -3,6 +3,7 @@
 from .build import _build
 from .create import _create
 from .dev import _dev
+from .docs import _docs
 from .install_component import _install
 from .publish import _publish
 from .show import _show
@@ -20,3 +21,4 @@
     _install
 )
 app.command("publish", help="Publish a component to PyPI and HuggingFace Hub")(_publish)
+app.command("docs", help="Generate documentation for a custom components")(_docs)
diff --git a/gradio/cli/commands/components/docs.py b/gradio/cli/commands/components/docs.py
new file mode 100644
index 0000000000..da55c872a8
--- /dev/null
+++ b/gradio/cli/commands/components/docs.py
@@ -0,0 +1,101 @@
+import importlib
+from pathlib import Path
+from typing import Optional
+
+import requests
+import toml
+from typer import Argument, Option
+from typing_extensions import Annotated
+
+from ._docs_utils import extract_docstrings, get_deep, make_markdown, make_space
+
+
+def _docs(
+    path: Annotated[
+        Path, Argument(help="The directory of the custom component.")
+    ] = Path("."),
+    demo_dir: Annotated[
+        Optional[Path], Option(help="Path to the demo directory.")
+    ] = None,
+    demo_name: Annotated[Optional[str], Option(help="Name of the demo file.")] = None,
+    readme_path: Annotated[
+        Optional[Path], Option(help="Path to the README.md file.")
+    ] = None,
+    space_url: Annotated[
+        Optional[str], Option(help="URL of the Space to use for the demo.")
+    ] = None,
+    generate_space: Annotated[
+        bool,
+        Option(
+            help="Create a documentation space for the custom compone.", is_flag=True
+        ),
+    ] = True,
+    generate_readme: Annotated[
+        bool,
+        Option(help="Create a README.md file for the custom component.", is_flag=True),
+    ] = True,
+):
+    """Runs the documentation generator."""
+
+    _component_dir = Path(path).resolve()
+    _demo_dir = Path(demo_dir).resolve() if demo_dir else Path("demo").resolve()
+    _demo_name = demo_name if demo_name else "app.py"
+    _demo_path = _demo_dir / _demo_name
+    _readme_path = (
+        Path(readme_path).resolve() if readme_path else _component_dir / "README.md"
+    )
+
+    if not generate_space and not generate_readme:
+        raise ValueError("Must generate at least one of space or readme")
+
+    print(f"Reading project metadata from {_component_dir}/pyproject.toml\n")
+
+    if not (_component_dir / "pyproject.toml").exists():
+        raise ValueError(f"Cannot find pyproject.toml file in {_component_dir}")
+
+    with open(_component_dir / "pyproject.toml") as f:
+        data = toml.loads(f.read())
+    with open(_demo_path) as f:
+        demo = f.read()
+
+    name = data["project"]["name"]
+
+    pypi_exists = requests.get(f"https://pypi.org/pypi/{name}/json").status_code
+
+    pypi_exists = pypi_exists == 200 or False
+
+    local_version = get_deep(data, ["project", "version"])
+    description = get_deep(data, ["project", "description"])
+    repo = get_deep(data, ["project", "urls", "repository"])
+    space = space_url if space_url else get_deep(data, ["project", "urls", "space"])
+
+    module = importlib.import_module(name)
+    docs = extract_docstrings(module)
+
+    if generate_space:
+        print("Generating space.")
+
+        source = make_space(
+            docs,
+            name,
+            description,
+            local_version,
+            demo,
+            space,
+            repo,
+            pypi_exists,
+        )
+
+        with open(_demo_dir / "space.py", "w") as f:
+            f.write(source)
+            print(f"  - Space created in {_demo_dir}/space.py\n")
+
+    if generate_readme:
+        print("Generating README.")
+        readme = make_markdown(
+            docs, name, description, local_version, demo, space, repo, pypi_exists
+        )
+
+        with open(_readme_path, "w") as f:
+            f.write(readme)
+            print(f"  - README generated in {_readme_path}")
diff --git a/gradio/components/__init__.py b/gradio/components/__init__.py
index 7031d1710c..14cf404a7b 100644
--- a/gradio/components/__init__.py
+++ b/gradio/components/__init__.py
@@ -37,6 +37,7 @@
 from gradio.components.markdown import Markdown
 from gradio.components.model3d import Model3D
 from gradio.components.number import Number
+from gradio.components.paramviewer import ParamViewer
 from gradio.components.plot import Plot
 from gradio.components.radio import Radio
 from gradio.components.scatter_plot import ScatterPlot
@@ -110,4 +111,5 @@
     "StreamingInput",
     "StreamingOutput",
     "ImageEditor",
+    "ParamViewer",
 ]
diff --git a/gradio/components/paramviewer.py b/gradio/components/paramviewer.py
new file mode 100644
index 0000000000..e6456336fb
--- /dev/null
+++ b/gradio/components/paramviewer.py
@@ -0,0 +1,84 @@
+from typing import Literal, TypedDict
+
+from gradio.components.base import Component
+from gradio.events import Events
+
+lang_type = Literal["python", "typescript"]
+
+
+class ParameterThree(TypedDict):
+    type: str
+    description: str
+    default: str
+
+
+class ParameterTwo(TypedDict):
+    type: str
+    description: str
+    default: ParameterThree
+
+
+class ParameterOne(TypedDict):
+    type: str
+    description: str
+    default: ParameterTwo
+
+
+class Parameter(TypedDict):
+    type: str
+    description: ParameterOne
+    default: ParameterTwo
+
+
+class ParamViewer(Component):
+    """
+    Displays an interactive table of parameters and their descriptions and default values width syntax highlighting
+    """
+
+    EVENTS = [
+        Events.change,
+        Events.upload,
+    ]
+
+    def __init__(
+        self,
+        value: list[Parameter] | None = None,
+        language: lang_type = "python",
+        linkify: list[str] | None = None,
+    ):
+        """
+        Parameters:
+            value: A list of dictionaries with keys "type", "description", and "default" for each parameter.
+            language: The language to display the code in. One of "python" or "typescript".
+            linkify: A list of strings to linkify. If a string is found in the description, it will be linked to the corresponding url.
+        """
+        self.value = value
+        self.language = language
+        self.linkify = linkify
+        super().__init__(
+            value=value,
+        )
+
+    def preprocess(self, payload: list[Parameter]) -> list[Parameter]:
+        """
+        Parameters:
+            payload: A list of dictionaries with keys "type", "description", and "default" for each parameter.
+        Returns:
+            A list of dictionaries with keys "type", "description", and "default" for each parameter.
+        """
+        return payload
+
+    def postprocess(self, value: list[Parameter]) -> list[Parameter]:
+        """
+        Parameters:
+            value: A list of dictionaries with keys "type", "description", and "default" for each parameter.
+        Returns:
+            A list of dictionaries with keys "type", "description", and "default" for each parameter.
+        """
+        return value
+
+    def example_inputs(self):
+        return [{"type": "numpy", "description": "any valid json", "default": "None"}]
+
+    def api_info(self):
+        return {"type": {}, "description": "any valid json"}
diff --git a/js/app/package.json b/js/app/package.json
index 71decae834..ee0f560b7c 100644
--- a/js/app/package.json
+++ b/js/app/package.json
@@ -53,6 +53,7 @@
 		"@gradio/markdown": "workspace:^",
 		"@gradio/model3d": "workspace:^",
 		"@gradio/number": "workspace:^",
+		"@gradio/paramviewer": "workspace:^",
 		"@gradio/plot": "workspace:^",
 		"@gradio/radio": "workspace:^",
 		"@gradio/row": "workspace:^",
diff --git a/js/paramviewer/Example.svelte b/js/paramviewer/Example.svelte
new file mode 100644
index 0000000000..18eacb16c9
--- /dev/null
+++ b/js/paramviewer/Example.svelte
@@ -0,0 +1,19 @@
+<script lang="ts">
+	export let value: string;
+	export let type: "gallery" | "table";
+	export let selected = false;
+</script>
+
+<div
+	class:table={type === "table"}
+	class:gallery={type === "gallery"}
+	class:selected
+>
+	<pre>{JSON.stringify(value, null, 2)}</pre>
+</div>
+
+<style>
+	.gallery {
+		padding: var(--size-1) var(--size-2);
+	}
+</style>
diff --git a/js/paramviewer/Index.svelte b/js/paramviewer/Index.svelte
new file mode 100644
index 0000000000..cab019eb0b
--- /dev/null
+++ b/js/paramviewer/Index.svelte
@@ -0,0 +1,16 @@
+<script lang="ts">
+	import ParamViewer from "./ParamViewer.svelte";
+
+	export let value: Record<
+		string,
+		{
+			type: string;
+			description: string;
+			default: string;
+		}
+	>;
+
+	export let linkify: string[] = [];
+</script>
+
+<ParamViewer docs={value} {linkify} />
diff --git a/js/paramviewer/ParamViewer.svelte b/js/paramviewer/ParamViewer.svelte
new file mode 100644
index 0000000000..5573b76017
--- /dev/null
+++ b/js/paramviewer/ParamViewer.svelte
@@ -0,0 +1,223 @@
+<script lang="ts">
+	import "./prism.css";
+
+	import Prism from "prismjs";
+	import "prismjs/components/prism-python";
+	import "prismjs/components/prism-typescript";
+
+	interface Param {
+		type: string | null;
+		description: string;
+		default: string | null;
+		name?: string;
+	}
+
+	export let docs: Record<string, Param>;
+
+	export let lang: "python" | "typescript" = "python";
+	export let linkify: string[] = [];
+	let _docs: Param[];
+
+	$: {
+		setTimeout(() => {
+			_docs = highlight_code(docs, lang);
+		}, 0);
+	}
+	$: show_desc = _docs && _docs.map((x) => false);
+
+	function highlight(code: string, lang: "python" | "typescript"): string {
+		let highlighted = Prism.highlight(code, Prism.languages[lang], lang);
+
+		for (const link of linkify) {
+			highlighted = highlighted.replace(
+				new RegExp(link, "g"),
+				`<a href="#h-${link.toLocaleLowerCase()}">${link}</a>`
+			);
+		}
+
+		return highlighted;
+	}
+
+	function highlight_code(
+		_docs: typeof docs,
+		lang: "python" | "typescript"
+	): Param[] {
+		return Object.entries(_docs).map(
+			([name, { type, description, default: _default }]) => {
+				let highlighted_type = type ? highlight(type, lang) : null;
+
+				return {
+					name: name,
+					type: highlighted_type,
+					description: description,
+					default: _default ? highlight(_default, lang) : null
+				};
+			}
+		);
+	}
+	let el = [];
+</script>
+
+<div class="wrap">
+	{#if _docs}
+		{#each _docs as { type, description, default: _default, name }, i (name)}
+			<div class="param md" class:open={show_desc[i]}>
+				<div class="type">
+					<pre class="language-{lang}"><code bind:this={el[i]}
+							>{name}{#if type}: {@html type}{/if}</code
+						></pre>
+					<button
+						on:click={() => (show_desc[i] = !show_desc[i])}
+						class="arrow"
+						class:hidden={!show_desc[i]}>▲</button
+					>
+				</div>
+				{#if show_desc[i]}
+					{#if _default}
+						<div class="default">
+							<span style:padding-right={"4px"}>default</span>
+							<code>= {@html _default}</code>
+						</div>
+					{/if}
+					<div class="description"><p>{description}</p></div>
+				{/if}
+			</div>
+		{/each}
+	{/if}
+</div>
+
+<style>
+	.default :global(pre),
+	.default :global(.highlight) {
+		display: inline-block;
+	}
+
+	.wrap :global(pre),
+	.wrap :global(.highlight) {
+		margin: 0;
+		background: transparent !important;
+		font-family: var(--font-mono);
+		font-weight: 400;
+		padding: 0;
+	}
+
+	.wrap :global(pre a) {
+		color: var(--link-text-color-hover);
+		text-decoration: underline;
+	}
+
+	.wrap :global(pre a:hover) {
+		color: var(--link-text-color-hover);
+	}
+
+	.default > span {
+		text-transform: uppercase;
+		font-size: 0.7rem;
+		font-weight: 600;
+	}
+
+	.default > code {
+		border: none;
+	}
+	code {
+		background: none;
+		font-family: var(--font-mono);
+	}
+
+	.wrap {
+		padding: 0rem;
+		border-radius: 5px;
+		border: 1px solid #eee;
+		overflow: hidden;
+		position: relative;
+		margin: 0;
+		box-shadow: var(--block-shadow);
+		border-width: var(--block-border-width);
+		border-color: var(--block-border-color);
+		border-radius: var(--block-radius);
+		background: #fff;
+		width: 100%;
+		line-height: var(--line-sm);
+		color: var(--body-text-color);
+	}
+
+	.type {
+		position: relative;
+		padding: 0.7rem 1rem;
+		background: var(--neutral-900);
+		background: var(--neutral-50);
+		border-bottom: 1px solid var(--neutral-700);
+		border-bottom: 0px solid var(--neutral-200);
+	}
+
+	.arrow {
+		position: absolute;
+		top: 0;
+		bottom: 0;
+		right: 15px;
+		transform: rotate(180deg);
+		height: 100;
+		display: flex;
+		align-items: center;
+		cursor: pointer;
+	}
+
+	.arrow.hidden {
+		transform: rotate(270deg);
+	}
+
+	.default {
+		padding: 0.2rem 1rem 0.3rem 1rem;
+		border-bottom: 1px solid var(--neutral-700);
+		border-bottom: 1px solid var(--neutral-200);
+	}
+
+	.description {
+		padding: 0.7rem 1rem;
+		font-size: var(--scale-00);
+		font-family: var(--font-sans);
+	}
+
+	.param {
+		border-bottom: 1px solid var(--neutral-200);
+	}
+
+	.param:last-child .description {
+		border-bottom: none;
+	}
+
+	.open .type {
+		border-bottom-width: 1px;
+	}
+
+	.param.md code {
+		background: none;
+	}
+
+	@media (prefers-color-scheme: dark) {
+		.wrap {
+			background: var(--neutral-800);
+		}
+
+		.default {
+			border-bottom: 1px solid var(--neutral-700);
+		}
+
+		.type {
+			background: var(--neutral-900);
+			border-bottom: 0px solid var(--neutral-700);
+		}
+
+		.arrow {
+			color: var(--neutral-200);
+		}
+
+		.param {
+			border-bottom: 1px solid var(--neutral-700);
+		}
+
+		.param:last-child {
+			border-bottom: none;
+		}
+	}
+</style>
diff --git a/js/paramviewer/package.json b/js/paramviewer/package.json
new file mode 100644
index 0000000000..a4c04b342c
--- /dev/null
+++ b/js/paramviewer/package.json
@@ -0,0 +1,24 @@
+{
+	"name": "@gradio/paramviewer",
+	"version": "0.2.3",
+	"description": "Gradio UI packages",
+	"type": "module",
+	"author": "",
+	"license": "ISC",
+	"private": false,
+	"main_changeset": true,
+	"exports": {
+		".": "./Index.svelte",
+		"./example": "./Example.svelte",
+		"./package.json": "./package.json"
+	},
+	"dependencies": {
+		"@gradio/atoms": "0.3.0",
+		"@gradio/statustracker": "0.4.0",
+		"@gradio/utils": "0.2.0",
+		"prismjs": "^1.29.0"
+	},
+	"devDependencies": {
+		"@types/prismjs": "^1.26.3"
+	}
+}
diff --git a/js/paramviewer/prism.css b/js/paramviewer/prism.css
new file mode 100644
index 0000000000..f7f5f4e3ff
--- /dev/null
+++ b/js/paramviewer/prism.css
@@ -0,0 +1,211 @@
+Tables */ table,
+tr,
+td,
+th {
+	margin-top: var(--spacing-sm);
+	margin-bottom: var(--spacing-sm);
+	padding: var(--spacing-xl);
+}
+
+/* .message-wrap :global(pre[class*="language-"]),
+	.message-wrap :global(pre) {
+		border: none;
+		background: none;
+		position: relative;
+		direction: ltr;
+		white-space: no-wrap;
+		overflow-x: auto;
+	}
+	.message-wrap :global(code) {
+	} */
+
+/* .message-wrap :global(div[class*="code_wrap"]) {
+		
+	} */
+
+.md code,
+.md pre {
+	background: none;
+	font-family: var(--font-mono);
+	font-size: var(--text-md);
+
+	text-align: left;
+	white-space: pre;
+	word-spacing: normal;
+	word-break: normal;
+	word-wrap: normal;
+	line-height: 1.5;
+	tab-size: 2;
+
+	hyphens: none;
+}
+
+.md pre[class*="language-"]::-moz-selection,
+.md pre[class*="language-"] ::-moz-selection,
+.md code[class*="language-"]::-moz-selection,
+.md code[class*="language-"] ::-moz-selection {
+}
+
+.md pre[class*="language-"]::selection,
+.md pre[class*="language-"] ::selection,
+.md code[class*="language-"]::selection,
+.md code[class*="language-"] ::selection {
+	text-shadow: none;
+	background: #b3d4fc;
+}
+
+/* Code blocks */
+.md pre {
+	padding: 1em;
+	margin: 0.5em 0;
+	overflow: auto;
+	position: relative;
+	margin-top: var(--spacing-sm);
+	margin-bottom: var(--spacing-sm);
+	box-shadow: none;
+	border: none;
+	border-radius: var(--radius-md);
+	background: var(--code-background-fill);
+	font-family: var(--font-mono);
+	display: block;
+	white-space: pre;
+	border-radius: var(--radius-sm);
+	text-shadow: none;
+	border-radius: var(--radius-sm);
+	/* font-size: 85%; */
+	white-space: nowrap;
+	display: block;
+	white-space: pre;
+}
+
+.prose code {
+}
+.prose pre > code {
+}
+
+/* Inline code */
+.md :not(pre) > code {
+	padding: 0.1em;
+	border-radius: var(--radius-xs);
+	white-space: normal;
+	background: var(--code-background-fill);
+	border: 1px solid var(--panel-border-color);
+	padding: var(--spacing-xxs) var(--spacing-xs);
+}
+
+.md .token.comment,
+.md .token.prolog,
+.md .token.doctype,
+.md .token.cdata {
+	color: slategray;
+}
+
+.md .token.punctuation {
+	color: #999;
+}
+
+.md .token.namespace {
+	opacity: 0.7;
+}
+
+.md .token.property,
+.md .token.tag,
+.md .token.boolean,
+.md .token.number,
+.md .token.constant,
+.md .token.symbol,
+.md .token.deleted {
+	color: #905;
+}
+
+.md .token.selector,
+.md .token.attr-name,
+.md .token.string,
+.md .token.char,
+.md .token.builtin,
+.md .token.inserted {
+	color: #690;
+}
+
+.md .token.atrule,
+.md .token.attr-value,
+.md .token.keyword {
+	color: #07a;
+}
+
+.md .token.function,
+.md .token.class-name {
+	color: #dd4a68;
+}
+
+.md .token.regex,
+.md .token.important,
+.md .token.variable {
+	color: #e90;
+}
+
+.md .token.important,
+.md .token.bold {
+	font-weight: bold;
+}
+.md .token.italic {
+	font-style: italic;
+}
+
+.md .token.entity {
+	cursor: help;
+}
+
+.dark .md .token.comment,
+.dark .md .token.prolog,
+.dark .md .token.cdata {
+	color: hsl(220, 10%, 40%);
+}
+
+.dark .md .token.doctype,
+.dark .md .token.punctuation,
+.dark .md .token.entity {
+	color: hsl(220, 14%, 71%);
+}
+
+.dark .md .token.attr-name,
+.dark .md .token.class-name,
+.dark .md .token.boolean,
+.dark .md .token.constant,
+.dark .md .token.number,
+.dark .md .token.atrule {
+	color: hsl(29, 54%, 61%);
+}
+
+.dark .md .token.keyword {
+	color: hsl(286, 60%, 67%);
+}
+
+.dark .md .token.property,
+.dark .md .token.tag,
+.dark .md .token.symbol,
+.dark .md .token.deleted,
+.dark .md .token.important {
+	color: hsl(355, 65%, 65%);
+}
+
+.dark .md .token.selector,
+.dark .md .token.string,
+.dark .md .token.char,
+.dark .md .token.builtin,
+.dark .md .token.inserted,
+.dark .md .token.regex,
+.dark .md .token.attr-value,
+.dark .md .token.attr-value > .token.punctuation {
+	color: hsl(95, 38%, 62%);
+}
+
+.dark .md .token.variable,
+.dark .md .token.operator,
+.dark .md .token.function {
+	color: hsl(207, 82%, 66%);
+}
+
+.dark .md .token.url {
+	color: hsl(187, 47%, 55%);
+}
diff --git a/pnpm-lock.yaml b/pnpm-lock.yaml
index 99a43ad53b..ab64bbffd2 100644
--- a/pnpm-lock.yaml
+++ b/pnpm-lock.yaml
@@ -1,4 +1,4 @@
-lockfileVersion: '6.1'
+lockfileVersion: '6.0'
 
 settings:
   autoInstallPeers: true
@@ -262,16 +262,16 @@ importers:
         version: 2.0.0(@sveltejs/kit@1.26.0)
       '@sveltejs/kit':
         specifier: ^1.5.0
-        version: 1.26.0(svelte@4.2.2)(vite@4.5.0)
+        version: 1.26.0(svelte@4.2.3)(vite@4.5.0)
       prettier:
         specifier: ^3.0.0
         version: 3.0.0
       prettier-plugin-svelte:
         specifier: ^3.0.0
-        version: 3.0.0(prettier@3.0.0)(svelte@4.2.2)
+        version: 3.0.0(prettier@3.0.0)(svelte@4.2.3)
       svelte-check:
         specifier: ^3.0.1
-        version: 3.4.4(@babel/core@7.23.3)(less@4.2.0)(postcss@8.4.27)(svelte@4.2.2)
+        version: 3.4.4(@babel/core@7.23.3)(less@4.2.0)(postcss@8.4.27)(svelte@4.2.3)
       typescript:
         specifier: ^5.0.0
         version: 5.0.2
@@ -292,7 +292,7 @@ importers:
         version: 3.0.0
       mdsvex:
         specifier: ^0.11.0
-        version: 0.11.0(svelte@4.2.2)
+        version: 0.11.0(svelte@4.2.3)
       postcss:
         specifier: '>=8.3.3 <9.0.0'
         version: 8.4.27
@@ -305,7 +305,7 @@ importers:
         version: 2.0.2(@sveltejs/kit@1.27.6)
       '@sveltejs/kit':
         specifier: ^1.27.6
-        version: 1.27.6(svelte@4.2.2)(vite@4.5.0)
+        version: 1.27.6(svelte@4.2.3)(vite@4.5.0)
       '@tailwindcss/forms':
         specifier: ^0.5.0
         version: 0.5.0(tailwindcss@3.1.6)
@@ -459,6 +459,9 @@ importers:
       '@gradio/number':
         specifier: workspace:^
         version: link:../number
+      '@gradio/paramviewer':
+        specifier: workspace:^
+        version: link:../paramviewer
       '@gradio/plot':
         specifier: workspace:^
         version: link:../plot
@@ -1183,6 +1186,25 @@ importers:
         specifier: workspace:^
         version: link:../utils
 
+  js/paramviewer:
+    dependencies:
+      '@gradio/atoms':
+        specifier: 0.3.0
+        version: 0.3.0(svelte@3.59.2)
+      '@gradio/statustracker':
+        specifier: 0.4.0
+        version: 0.4.0(svelte@3.59.2)
+      '@gradio/utils':
+        specifier: 0.2.0
+        version: link:../utils
+      prismjs:
+        specifier: ^1.29.0
+        version: 1.29.0
+    devDependencies:
+      '@types/prismjs':
+        specifier: ^1.26.3
+        version: 1.26.3
+
   js/plot:
     dependencies:
       '@gradio/atoms':
@@ -4164,6 +4186,47 @@ packages:
       tslib: 2.6.2
     dev: false
 
+  /@gradio/atoms@0.3.0(svelte@3.59.2):
+    resolution: {integrity: sha512-7WQktAb+d8wEjTIYGzyQ8OdWsFSr0NA8adp8G/jAKoMZILJEoAAZSTnahCTSSQcbYIomVdfYA0ZmM342RCd8gg==}
+    dependencies:
+      '@gradio/icons': 0.3.2
+      '@gradio/utils': 0.2.0(svelte@3.59.2)
+    transitivePeerDependencies:
+      - svelte
+    dev: false
+
+  /@gradio/column@0.1.0:
+    resolution: {integrity: sha512-P24nqqVnMXBaDA1f/zSN5HZRho4PxP8Dq+7VltPHlmxIEiZYik2AJ4J0LeuIha34FDO0guu/16evdrpvGIUAfw==}
+    dev: false
+
+  /@gradio/icons@0.3.2:
+    resolution: {integrity: sha512-l0jGfSRFiZ/doAXz6L+JEp6MN/a1BTZm88kqVoSnYrKSytP6bnBLRWeF4UvOi2T2fbVrNKenAEt/lwxJE5vK4w==}
+    dev: false
+
+  /@gradio/statustracker@0.4.0(svelte@3.59.2):
+    resolution: {integrity: sha512-Kgk4R2edFX4IK2UBit4UwmRfSrmvkYjKbiMfupj3qxHFwiDHT4YH4rAOqBlvdEWbCYMmLN6EyqqFaYb2+0GwXA==}
+    dependencies:
+      '@gradio/atoms': 0.3.0(svelte@3.59.2)
+      '@gradio/column': 0.1.0
+      '@gradio/icons': 0.3.2
+      '@gradio/utils': 0.2.0(svelte@3.59.2)
+    transitivePeerDependencies:
+      - svelte
+    dev: false
+
+  /@gradio/theme@0.2.0:
+    resolution: {integrity: sha512-33c68Nk7oRXLn08OxPfjcPm7S4tXGOUV1I1bVgzdM2YV5o1QBOS1GEnXPZPu/CEYPePLMB6bsDwffrLEyLGWVQ==}
+    dev: false
+
+  /@gradio/utils@0.2.0(svelte@3.59.2):
+    resolution: {integrity: sha512-YkwzXufi6IxQrlMW+1sFo8Yn6F9NLL69ZoBsbo7QEhms0v5L7pmOTw+dfd7M3dwbRP2lgjrb52i1kAIN3n6aqQ==}
+    dependencies:
+      '@gradio/theme': 0.2.0
+      svelte-i18n: 3.6.0(svelte@3.59.2)
+    transitivePeerDependencies:
+      - svelte
+    dev: false
+
   /@humanwhocodes/config-array@0.11.13:
     resolution: {integrity: sha512-JSBDMiDKSzQVngfRjOdFXgFfklaXI4K9nLF49Auh21lmBWRLIK3+xTErTWD4KU54pb6coM6ESE7Awz/FNU3zgQ==}
     engines: {node: '>=10.10.0'}
@@ -6755,7 +6818,7 @@ packages:
     peerDependencies:
       '@sveltejs/kit': ^1.0.0
     dependencies:
-      '@sveltejs/kit': 1.26.0(svelte@4.2.2)(vite@4.5.0)
+      '@sveltejs/kit': 1.26.0(svelte@4.2.3)(vite@4.5.0)
       import-meta-resolve: 2.2.2
     dev: true
 
@@ -6764,7 +6827,7 @@ packages:
     peerDependencies:
       '@sveltejs/kit': ^1.0.0
     dependencies:
-      '@sveltejs/kit': 1.27.6(svelte@4.2.2)(vite@4.5.0)
+      '@sveltejs/kit': 1.27.6(svelte@4.2.3)(vite@4.5.0)
       import-meta-resolve: 2.2.2
     dev: true
 
@@ -6773,7 +6836,7 @@ packages:
     peerDependencies:
       '@sveltejs/kit': ^1.5.0
     dependencies:
-      '@sveltejs/kit': 1.27.6(svelte@4.2.2)(vite@4.5.0)
+      '@sveltejs/kit': 1.27.6(svelte@4.2.3)(vite@4.5.0)
     dev: true
 
   /@sveltejs/adapter-vercel@3.0.3(@sveltejs/kit@1.27.6):
@@ -6781,7 +6844,7 @@ packages:
     peerDependencies:
       '@sveltejs/kit': ^1.5.0
     dependencies:
-      '@sveltejs/kit': 1.27.6(svelte@4.2.2)(vite@4.5.0)
+      '@sveltejs/kit': 1.27.6(svelte@4.2.3)(vite@4.5.0)
       '@vercel/nft': 0.23.1
       esbuild: 0.18.20
     transitivePeerDependencies:
@@ -6789,7 +6852,7 @@ packages:
       - supports-color
     dev: false
 
-  /@sveltejs/kit@1.26.0(svelte@4.2.2)(vite@4.5.0):
+  /@sveltejs/kit@1.26.0(svelte@4.2.3)(vite@4.5.0):
     resolution: {integrity: sha512-CV/AlTziC05yrz7UjVqEd0pH6+2dnrbmcnHGr2d3jXtmOgzNnlDkXtX8g3BfJ6nntsPD+0jtS2PzhvRHblRz4A==}
     engines: {node: ^16.14 || >=18}
     hasBin: true
@@ -6798,7 +6861,7 @@ packages:
       svelte: ^3.54.0 || ^4.0.0-next.0
       vite: ^4.0.0
     dependencies:
-      '@sveltejs/vite-plugin-svelte': 2.5.2(svelte@4.2.2)(vite@4.5.0)
+      '@sveltejs/vite-plugin-svelte': 2.5.2(svelte@4.2.3)(vite@4.5.0)
       '@types/cookie': 0.5.4
       cookie: 0.5.0
       devalue: 4.3.2
@@ -6809,7 +6872,7 @@ packages:
       sade: 1.8.1
       set-cookie-parser: 2.6.0
       sirv: 2.0.3
-      svelte: 4.2.2
+      svelte: 4.2.3
       tiny-glob: 0.2.9
       undici: 5.26.5
       vite: 4.5.0(@types/node@20.3.2)(less@4.2.0)(lightningcss@1.21.7)(sass@1.66.1)(stylus@0.62.0)(sugarss@4.0.1)
@@ -6817,7 +6880,7 @@ packages:
       - supports-color
     dev: true
 
-  /@sveltejs/kit@1.27.6(svelte@4.2.2)(vite@4.5.0):
+  /@sveltejs/kit@1.27.6(svelte@4.2.3)(vite@4.5.0):
     resolution: {integrity: sha512-GsjTkMbKzXdbeRg0tk8S7HNShQ4879ftRr0ZHaZfjbig1xQwG57Bvcm9U9/mpLJtCapLbLWUnygKrgcLISLC8A==}
     engines: {node: ^16.14 || >=18}
     hasBin: true
@@ -6826,7 +6889,7 @@ packages:
       svelte: ^3.54.0 || ^4.0.0-next.0 || ^5.0.0-next.0
       vite: ^4.0.0
     dependencies:
-      '@sveltejs/vite-plugin-svelte': 2.5.2(svelte@4.2.2)(vite@4.5.0)
+      '@sveltejs/vite-plugin-svelte': 2.5.2(svelte@4.2.3)(vite@4.5.0)
       '@types/cookie': 0.5.4
       cookie: 0.5.0
       devalue: 4.3.2
@@ -6837,7 +6900,7 @@ packages:
       sade: 1.8.1
       set-cookie-parser: 2.6.0
       sirv: 2.0.3
-      svelte: 4.2.2
+      svelte: 4.2.3
       tiny-glob: 0.2.9
       undici: 5.26.5
       vite: 4.5.0(@types/node@20.3.2)(less@4.2.0)(lightningcss@1.21.7)(sass@1.66.1)(stylus@0.62.0)(sugarss@4.0.1)
@@ -6859,21 +6922,6 @@ packages:
     transitivePeerDependencies:
       - supports-color
 
-  /@sveltejs/vite-plugin-svelte-inspector@1.0.4(@sveltejs/vite-plugin-svelte@2.5.2)(svelte@4.2.2)(vite@4.5.0):
-    resolution: {integrity: sha512-zjiuZ3yydBtwpF3bj0kQNV0YXe+iKE545QGZVTaylW3eAzFr+pJ/cwK8lZEaRp4JtaJXhD5DyWAV4AxLh6DgaQ==}
-    engines: {node: ^14.18.0 || >= 16}
-    peerDependencies:
-      '@sveltejs/vite-plugin-svelte': ^2.2.0
-      svelte: ^3.54.0 || ^4.0.0
-      vite: ^4.0.0
-    dependencies:
-      '@sveltejs/vite-plugin-svelte': 2.5.2(svelte@4.2.2)(vite@4.5.0)
-      debug: 4.3.4
-      svelte: 4.2.2
-      vite: 4.5.0(@types/node@20.3.2)(less@4.2.0)(lightningcss@1.21.7)(sass@1.66.1)(stylus@0.62.0)(sugarss@4.0.1)
-    transitivePeerDependencies:
-      - supports-color
-
   /@sveltejs/vite-plugin-svelte-inspector@1.0.4(@sveltejs/vite-plugin-svelte@2.5.2)(svelte@4.2.3)(vite@4.5.0):
     resolution: {integrity: sha512-zjiuZ3yydBtwpF3bj0kQNV0YXe+iKE545QGZVTaylW3eAzFr+pJ/cwK8lZEaRp4JtaJXhD5DyWAV4AxLh6DgaQ==}
     engines: {node: ^14.18.0 || >= 16}
@@ -6888,7 +6936,6 @@ packages:
       vite: 4.5.0(@types/node@20.3.2)(less@4.2.0)(lightningcss@1.21.7)(sass@1.66.1)(stylus@0.62.0)(sugarss@4.0.1)
     transitivePeerDependencies:
       - supports-color
-    dev: false
 
   /@sveltejs/vite-plugin-svelte@2.5.2(svelte@4.2.2)(vite@4.3.9):
     resolution: {integrity: sha512-Dfy0Rbl+IctOVfJvWGxrX/3m6vxPLH8o0x+8FA5QEyMUQMo4kGOVIojjryU7YomBAexOTAuYf1RT7809yDziaA==}
@@ -6909,25 +6956,6 @@ packages:
     transitivePeerDependencies:
       - supports-color
 
-  /@sveltejs/vite-plugin-svelte@2.5.2(svelte@4.2.2)(vite@4.5.0):
-    resolution: {integrity: sha512-Dfy0Rbl+IctOVfJvWGxrX/3m6vxPLH8o0x+8FA5QEyMUQMo4kGOVIojjryU7YomBAexOTAuYf1RT7809yDziaA==}
-    engines: {node: ^14.18.0 || >= 16}
-    peerDependencies:
-      svelte: ^3.54.0 || ^4.0.0 || ^5.0.0-next.0
-      vite: ^4.0.0
-    dependencies:
-      '@sveltejs/vite-plugin-svelte-inspector': 1.0.4(@sveltejs/vite-plugin-svelte@2.5.2)(svelte@4.2.2)(vite@4.5.0)
-      debug: 4.3.4
-      deepmerge: 4.3.1
-      kleur: 4.1.5
-      magic-string: 0.30.5
-      svelte: 4.2.2
-      svelte-hmr: 0.15.3(svelte@4.2.2)
-      vite: 4.5.0(@types/node@20.3.2)(less@4.2.0)(lightningcss@1.21.7)(sass@1.66.1)(stylus@0.62.0)(sugarss@4.0.1)
-      vitefu: 0.2.5(vite@4.5.0)
-    transitivePeerDependencies:
-      - supports-color
-
   /@sveltejs/vite-plugin-svelte@2.5.2(svelte@4.2.3)(vite@4.5.0):
     resolution: {integrity: sha512-Dfy0Rbl+IctOVfJvWGxrX/3m6vxPLH8o0x+8FA5QEyMUQMo4kGOVIojjryU7YomBAexOTAuYf1RT7809yDziaA==}
     engines: {node: ^14.18.0 || >= 16}
@@ -6946,7 +6974,6 @@ packages:
       vitefu: 0.2.5(vite@4.5.0)
     transitivePeerDependencies:
       - supports-color
-    dev: false
 
   /@tailwindcss/forms@0.5.0(tailwindcss@3.1.6):
     resolution: {integrity: sha512-KzWugryEBFkmoaYcBE18rs6gthWCFHHO7cAZm2/hv3hwD67AzwP7udSCa22E7R1+CEJL/FfhYsJWrc0b1aeSzw==}
@@ -7309,7 +7336,6 @@ packages:
 
   /@types/prismjs@1.26.3:
     resolution: {integrity: sha512-A0D0aTXvjlqJ5ZILMz3rNfDBOx9hHxLZYv2by47Sm/pqW35zzjusrZTryatjN/Rf8Us2gZrJD+KeHbUSTux1Cw==}
-    dev: false
 
   /@types/prop-types@15.7.10:
     resolution: {integrity: sha512-mxSnDQxPqsZxmeShFH+uwQ4kO4gcJcGahjjMFeLbKE95IAZiiZyiEepGZjtXJ7hN/yfu0bu9xN2ajcU0JcxX6A==}
@@ -12178,7 +12204,7 @@ packages:
   /mdn-data@2.0.30:
     resolution: {integrity: sha512-GaqWWShW4kv/G9IEucWScBx9G1/vsFZZJUO+tD26M8J8z3Kw5RDQjaoZe03YAClgeS/SWPOcb4nkFBTEi5DUEA==}
 
-  /mdsvex@0.11.0(svelte@4.2.2):
+  /mdsvex@0.11.0(svelte@4.2.3):
     resolution: {integrity: sha512-gJF1s0N2nCmdxcKn8HDn0LKrN8poStqAicp6bBcsKFd/zkUBGLP5e7vnxu+g0pjBbDFOscUyI1mtHz+YK2TCDw==}
     peerDependencies:
       svelte: '>=3 <5'
@@ -12186,7 +12212,7 @@ packages:
       '@types/unist': 2.0.10
       prism-svelte: 0.4.7
       prismjs: 1.29.0
-      svelte: 4.2.2
+      svelte: 4.2.3
       vfile-message: 2.0.4
     dev: false
 
@@ -13317,6 +13343,17 @@ packages:
     dependencies:
       prettier: 3.0.0
       svelte: 4.2.2
+    dev: false
+
+  /prettier-plugin-svelte@3.0.0(prettier@3.0.0)(svelte@4.2.3):
+    resolution: {integrity: sha512-l3RQcPty2UBCoRh3yb9c5XCAmxkrc4BptAnbd5acO1gmSJtChOWkiEjnOvh7hvmtT4V80S8gXCOKAq8RNeIzSw==}
+    peerDependencies:
+      prettier: ^3.0.0
+      svelte: ^3.2.0 || ^4.0.0-next.0
+    dependencies:
+      prettier: 3.0.0
+      svelte: 4.2.3
+    dev: true
 
   /prettier@2.8.8:
     resolution: {integrity: sha512-tdN8qQGvNjw4CHbY+XXk0JgCXn9QiF21a55rBe5LJAU+kDyC4WQn4+awm2Xfk2lQMk5fKup9XgzTZtGkjBdP9Q==}
@@ -14670,6 +14707,34 @@ packages:
       - sass
       - stylus
       - sugarss
+    dev: false
+
+  /svelte-check@3.4.4(@babel/core@7.23.3)(less@4.2.0)(postcss@8.4.27)(svelte@4.2.3):
+    resolution: {integrity: sha512-Uys9+R65cj8TmP8f5UpS7B2xKpNLYNxEWJsA5ZoKcWq/uwvABFF7xS6iPQGLoa7hxz0DS6xU60YFpmq06E4JxA==}
+    hasBin: true
+    peerDependencies:
+      svelte: ^3.55.0 || ^4.0.0-next.0 || ^4.0.0
+    dependencies:
+      '@jridgewell/trace-mapping': 0.3.20
+      chokidar: 3.5.3
+      fast-glob: 3.3.2
+      import-fresh: 3.3.0
+      picocolors: 1.0.0
+      sade: 1.8.1
+      svelte: 4.2.3
+      svelte-preprocess: 5.0.4(@babel/core@7.23.3)(less@4.2.0)(postcss@8.4.27)(svelte@4.2.3)(typescript@5.2.2)
+      typescript: 5.2.2
+    transitivePeerDependencies:
+      - '@babel/core'
+      - coffeescript
+      - less
+      - postcss
+      - postcss-load-config
+      - pug
+      - sass
+      - stylus
+      - sugarss
+    dev: true
 
   /svelte-eslint-parser@0.32.2(svelte@4.2.2):
     resolution: {integrity: sha512-Ok9D3A4b23iLQsONrjqtXtYDu5ZZ/826Blaw2LeFZVTg1pwofKDG4mz3/GYTax8fQ0plRGHI6j+d9VQYy5Lo/A==}
@@ -14834,6 +14899,57 @@ packages:
       strip-indent: 3.0.0
       svelte: 4.2.2
       typescript: 5.2.2
+    dev: false
+
+  /svelte-preprocess@5.0.4(@babel/core@7.23.3)(less@4.2.0)(postcss@8.4.27)(svelte@4.2.3)(typescript@5.2.2):
+    resolution: {integrity: sha512-ABia2QegosxOGsVlsSBJvoWeXy1wUKSfF7SWJdTjLAbx/Y3SrVevvvbFNQqrSJw89+lNSsM58SipmZJ5SRi5iw==}
+    engines: {node: '>= 14.10.0'}
+    requiresBuild: true
+    peerDependencies:
+      '@babel/core': ^7.10.2
+      coffeescript: ^2.5.1
+      less: ^3.11.3 || ^4.0.0
+      postcss: ^7 || ^8
+      postcss-load-config: ^2.1.0 || ^3.0.0 || ^4.0.0
+      pug: ^3.0.0
+      sass: ^1.26.8
+      stylus: ^0.55.0
+      sugarss: ^2.0.0 || ^3.0.0 || ^4.0.0
+      svelte: ^3.23.0 || ^4.0.0-next.0 || ^4.0.0
+      typescript: '>=3.9.5 || ^4.0.0 || ^5.0.0'
+    peerDependenciesMeta:
+      '@babel/core':
+        optional: true
+      coffeescript:
+        optional: true
+      less:
+        optional: true
+      postcss:
+        optional: true
+      postcss-load-config:
+        optional: true
+      pug:
+        optional: true
+      sass:
+        optional: true
+      stylus:
+        optional: true
+      sugarss:
+        optional: true
+      typescript:
+        optional: true
+    dependencies:
+      '@babel/core': 7.23.3
+      '@types/pug': 2.0.9
+      detect-indent: 6.1.0
+      less: 4.2.0
+      magic-string: 0.27.0
+      postcss: 8.4.27
+      sorcery: 0.11.0
+      strip-indent: 3.0.0
+      svelte: 4.2.3
+      typescript: 5.2.2
+    dev: true
 
   /svelte-range-slider-pips@2.0.1:
     resolution: {integrity: sha512-sCHvcTgi0ZYE4c/mwSsdALRsfuqEmpwTsSUdL+PUrumZ8u2gv1GKwZ3GohcAcTB6gfmqRBkyn6ujRXrOIga1gw==}


Code review comments:
diff_hunk: @@ -0,0 +1,747 @@
+import inspect
+import json
+import re
+import types
+import typing
+from subprocess import PIPE, Popen
+
+
+def find_first_non_return_key(some_dict):
+    """Finds the first key in a dictionary that is not "return"."""
+    for key, value in some_dict.items():
+        if key != "return":
+            return value
+    return None
+
+
+def format(code: str, type: str):
+    """Formats code using ruff."""
+    if type == "value":
+        code = f"value = {code}"
+
+    ruff_args = ["ruff", "format", "-", "--line-length=60"]
+
+    process = Popen(
+        ruff_args,
+        stdin=PIPE,
+        stdout=PIPE,
+        stderr=PIPE,
+        universal_newlines=True,
+    )
+    formatted_code, err = process.communicate(input=code)
+
+    if type == "value":
+        formatted_code = re.sub(
+            r"^\s*value =\s*", "", formatted_code, flags=re.MULTILINE
+        )
+
+    stripped_source = re.search(r"^\s*\((.*)\)\s*$", formatted_code, re.DOTALL)
+
+    return (
+        stripped_source.group(1).strip() if stripped_source else formatted_code.strip()
+    )
+
+
+def get_param_name(param):
+    """Gets the name of a parameter."""
+
+    if isinstance(param, str):
+        return f'"{param}"'
+    if inspect.isclass(param) and param.__module__ == "builtins":
+        p = getattr(param, "__name__", None)
+        if p is None and inspect.isclass(param):
+            p = f"{param.__module__}.{param.__name__}"
+        return p
+
+    if inspect.isclass(param):
+        return f"{param.__module__}.{param.__name__}"
+
+    param_name = getattr(param, "__name__", None)
+
+    if param_name is None:
+        param_name = str(param)
+
+    return param_name
+
+
+def format_none(value):
+    """Formats None and NonType values."""
+    if value is None or value is type(None) or value == "None" or value == "NoneType":
+        return "None"
+    return value
+
+
+def format_value(value):
+    """Formats a value."""
+    if value is None:
+        return "None"
+    if isinstance(value, str):
+        return f'"{value}"'
+    return str(value)
+
+
+def get_parameter_docstring(docstring: str, parameter_name: str):
+    """Gets the docstring for a parameter."""
+    pattern = rf"\b{parameter_name}\b:[ \t]*(.*?)(?=\n|$)"
+
+    match = re.search(pattern, docstring, flags=re.DOTALL)
+    if match:
+        return match.group(1).strip()
+
+    return None
+
+
+def get_return_docstring(docstring: str):
+    """Gets the docstring for a return value."""
+    pattern = r"\bReturn(?:s){0,1}\b:[ \t\n]*(.*?)(?=\n|$)"
+
+    match = re.search(pattern, docstring, flags=re.DOTALL | re.IGNORECASE)
+    if match:
+        return match.group(1).strip()
+
+    return None
+
+
+def add_value(obj, key, value):
+    """Adds a value to a dictionary."""
+    type = "value" if key == "default" else "type"
+    obj[key] = format(value, type)
+
+    return obj
+
+
+def set_deep(dictionary, keys, value):
+    """Sets a value in a nested dictionary for a key path that may not exist"""
+    for key in keys[:-1]:
+        dictionary = dictionary.setdefault(key, {})
+    dictionary[keys[-1]] = value
+
+
+def get_deep(dictionary, keys):
+    """Gets a value from a nested dictionary without erroring if the key doesn't exist."""
+    try:
+        for key in keys:
+            dictionary = dictionary[key]
+        return dictionary
+    except KeyError:
+        return None
+
+
+def get_type_arguments(type_hint) -> tuple:
+    """Gets the type arguments for a type hint."""
+    if hasattr(type_hint, "__args__"):
+        return type_hint.__args__
+    elif hasattr(type_hint, "__extra__"):
+        return type_hint.__extra__.__args__
+    else:
+        return typing.get_args(type_hint)
+
+
+def get_container_name(arg):
+    """Gets a human readable name for a type."""
+
+    # This is a bit of a hack to get the generic type for python 3.8
+    generic_type = getattr(typing, "_GenericAlias", None)
+    generic_type_tuple = (
+        (types.GenericAlias,)
+        if generic_type is None
+        else (types.GenericAlias, generic_type)
+    )
+
+    if inspect.isclass(arg):
+        return arg.__name__
+    if isinstance(arg, (generic_type_tuple)):
+        return arg.__origin__.__name__
+    elif isinstance(arg, types.UnionType):
+        return "Union"
+    elif getattr(arg, "__origin__", None) is typing.Literal:
+        return "Literal"
+
+    else:
+        return str(arg)
+
+
+def format_type(_type: list[typing.Any], current=None):
+    """Pretty formats a possibly nested type hint."""
+    s = []
+    _current = None
+    for t in _type:
+        if isinstance(t, str):
+            _current = format_none(t)
+            continue
+
+        elif isinstance(t, list):
+            if len(t) == 0:
+                continue
+            s.append(f"{format_type(t, _current)}")
+        else:
+            s.append(t)
+    if len(s) == 0:
+        return _current
+    elif _current == "Literal" or _current == "Union":
+        return "| ".join(s)
+    else:
+        return f"{_current}[{','.join(s)}]"
+
+
+def get_type_hints(param, module, ignore=None):
+    """Gets the type hints for a parameter."""
+
+    def extract_args(
+        arg,
+        module_name_prefix,
+        additional_interfaces,
+        user_fn_refs,
+        append=True,
+        arg_of=None,
+    ):
+        """Recursively extracts the arguments from a type hint."""
+        arg_names = []
+        args = get_type_arguments(arg)
+
+        # These are local classes that are used in types
+        if inspect.isclass(arg) and arg.__module__.startswith(module_name_prefix):
+            # get sourcecode for the class
+
+            source_code = inspect.getsource(arg)
+
+            if arg_of is not None:
+                refs = get_deep(additional_interfaces, [arg_of, "refs"])
+
+                if refs is None:
+                    refs = [arg.__name__]
+                elif arg.__name__ not in refs:
+                    refs.append(arg.__name__)
+
+                set_deep(additional_interfaces, [arg_of, "refs"], refs)
+
+            if get_deep(additional_interfaces, [arg.__name__, "source"]) is None:
+                set_deep(additional_interfaces, [arg.__name__, "source"], source_code)
+
+            for field_type in typing.get_type_hints(arg).values():
+                # We want to recursively extract the source code for the fields but we don't want to add them to the list of arguments
+                new_args = extract_args(
+                    field_type,
+                    module_name_prefix,
+                    additional_interfaces,
+                    user_fn_refs,
+                    False,
+                    arg.__name__,
+                )
+
+                if len(new_args) > 0:
+                    arg_names.append(new_args)
+
+            if append:
+                arg_names.append(arg.__name__)
+                if arg.__name__ not in user_fn_refs:
+                    user_fn_refs.append(arg.__name__)
+        elif len(args) > 0:
+            if append:
+                arg_names.append(get_container_name(arg))
+            for inner_arg in list(args):
+                new_args = extract_args(
+                    inner_arg,
+                    module_name_prefix,
+                    additional_interfaces,
+                    user_fn_refs,
+                    True,
+                )
+
+                if len(new_args) > 0:
+                    arg_names.append(new_args)
+        else:
+            if append:
+                arg_names.append(get_param_name(arg))
+        return arg_names
+
+    module_name_prefix = module.__name__ + "."
+    additional_interfaces = {}
+    user_fn_refs = []
+
+    args = extract_args(
+        param,
+        module_name_prefix,
+        additional_interfaces,
+        user_fn_refs,
+    )
+
+    formatted_type = format_type(args)
+
+    return (formatted_type, additional_interfaces, user_fn_refs)
+
+
+def extract_docstrings(module):
+    docs = {}
+    for name, obj in inspect.getmembers(module):
+        # filter out the builtins etc
+        if name.startswith("_"):
+            continue
+        #  this could be expanded but i think is ok for now
+        if inspect.isfunction(obj) or inspect.isclass(obj):
+            docs[name] = {}
+
+            main_docstring = inspect.getdoc(obj) or ""
+            cleaned_docstring = str.join(
+                "\n",
+                [s for s in main_docstring.split("\n") if not re.match(r"^\S+:", s)],
+            )
+
+            docs[name]["description"] = cleaned_docstring
+            docs[name]["members"] = {}
+            docs["__meta__"] = {"additional_interfaces": {}}
+            for member_name, member in inspect.getmembers(obj):
+                if inspect.ismethod(member) or inspect.isfunction(member):
+                    # we are are only interested in these methods
+                    if (
+                        member_name != "__init__"
+                        and member_name != "preprocess"
+                        and member_name != "postprocess"
+                    ):
+                        continue
+
+                    docs[name]["members"][member_name] = {}
+
+                    member_docstring = inspect.getdoc(member) or ""
+                    hints = typing.get_type_hints(member)
path: gradio/cli/commands/components/_docs_utils.py
text: @user1:
I think we need to do `member.__annotations__` here. 

`get_type_hints` is failing for me on python 3.9 because of the use of `|` for unions.

<img width="609" alt="image" src="https://github.com/gradio-app/gradio/assets/41651716/fc7c08ab-f64c-487c-b305-a4bfa4c9f7f6">


@author:
Are these two separate issues? I'm not sure i'm understanding correctly.

If i change `hints = typing.get_type_hints(member)` to `hints = typing.get_type_hints(member.__annotations)` then it fails. Is there some specific issue with an earlier python version?

> get_type_hints is failing for me on python 3.9 because of the use of | for unions.

Is this unions in the docs code, in the component code or somewhere else?

I'll test on 3.9.

diff_hunk: @@ -0,0 +1,747 @@
+import inspect
+import json
+import re
+import types
+import typing
+from subprocess import PIPE, Popen
+
+
+def find_first_non_return_key(some_dict):
+    """Finds the first key in a dictionary that is not "return"."""
+    for key, value in some_dict.items():
+        if key != "return":
+            return value
+    return None
+
+
+def format(code: str, type: str):
+    """Formats code using ruff."""
+    if type == "value":
+        code = f"value = {code}"
+
+    ruff_args = ["ruff", "format", "-", "--line-length=60"]
+
+    process = Popen(
+        ruff_args,
+        stdin=PIPE,
+        stdout=PIPE,
+        stderr=PIPE,
+        universal_newlines=True,
+    )
+    formatted_code, err = process.communicate(input=code)
+
+    if type == "value":
+        formatted_code = re.sub(
+            r"^\s*value =\s*", "", formatted_code, flags=re.MULTILINE
+        )
+
+    stripped_source = re.search(r"^\s*\((.*)\)\s*$", formatted_code, re.DOTALL)
+
+    return (
+        stripped_source.group(1).strip() if stripped_source else formatted_code.strip()
+    )
+
+
+def get_param_name(param):
+    """Gets the name of a parameter."""
+
+    if isinstance(param, str):
+        return f'"{param}"'
+    if inspect.isclass(param) and param.__module__ == "builtins":
+        p = getattr(param, "__name__", None)
+        if p is None and inspect.isclass(param):
+            p = f"{param.__module__}.{param.__name__}"
+        return p
+
+    if inspect.isclass(param):
+        return f"{param.__module__}.{param.__name__}"
+
+    param_name = getattr(param, "__name__", None)
+
+    if param_name is None:
+        param_name = str(param)
+
+    return param_name
+
+
+def format_none(value):
+    """Formats None and NonType values."""
+    if value is None or value is type(None) or value == "None" or value == "NoneType":
+        return "None"
+    return value
+
+
+def format_value(value):
+    """Formats a value."""
+    if value is None:
+        return "None"
+    if isinstance(value, str):
+        return f'"{value}"'
+    return str(value)
+
+
+def get_parameter_docstring(docstring: str, parameter_name: str):
+    """Gets the docstring for a parameter."""
+    pattern = rf"\b{parameter_name}\b:[ \t]*(.*?)(?=\n|$)"
+
+    match = re.search(pattern, docstring, flags=re.DOTALL)
+    if match:
+        return match.group(1).strip()
+
+    return None
+
+
+def get_return_docstring(docstring: str):
+    """Gets the docstring for a return value."""
+    pattern = r"\bReturn(?:s){0,1}\b:[ \t\n]*(.*?)(?=\n|$)"
+
+    match = re.search(pattern, docstring, flags=re.DOTALL | re.IGNORECASE)
+    if match:
+        return match.group(1).strip()
+
+    return None
+
+
+def add_value(obj, key, value):
+    """Adds a value to a dictionary."""
+    type = "value" if key == "default" else "type"
+    obj[key] = format(value, type)
+
+    return obj
+
+
+def set_deep(dictionary, keys, value):
+    """Sets a value in a nested dictionary for a key path that may not exist"""
+    for key in keys[:-1]:
+        dictionary = dictionary.setdefault(key, {})
+    dictionary[keys[-1]] = value
+
+
+def get_deep(dictionary, keys):
+    """Gets a value from a nested dictionary without erroring if the key doesn't exist."""
+    try:
+        for key in keys:
+            dictionary = dictionary[key]
+        return dictionary
+    except KeyError:
+        return None
+
+
+def get_type_arguments(type_hint) -> tuple:
+    """Gets the type arguments for a type hint."""
+    if hasattr(type_hint, "__args__"):
+        return type_hint.__args__
+    elif hasattr(type_hint, "__extra__"):
+        return type_hint.__extra__.__args__
+    else:
+        return typing.get_args(type_hint)
+
+
+def get_container_name(arg):
+    """Gets a human readable name for a type."""
+
+    # This is a bit of a hack to get the generic type for python 3.8
+    generic_type = getattr(typing, "_GenericAlias", None)
+    generic_type_tuple = (
+        (types.GenericAlias,)
+        if generic_type is None
+        else (types.GenericAlias, generic_type)
+    )
+
+    if inspect.isclass(arg):
+        return arg.__name__
+    if isinstance(arg, (generic_type_tuple)):
+        return arg.__origin__.__name__
+    elif isinstance(arg, types.UnionType):
+        return "Union"
+    elif getattr(arg, "__origin__", None) is typing.Literal:
+        return "Literal"
+
+    else:
+        return str(arg)
+
+
+def format_type(_type: list[typing.Any], current=None):
+    """Pretty formats a possibly nested type hint."""
+    s = []
+    _current = None
+    for t in _type:
+        if isinstance(t, str):
+            _current = format_none(t)
+            continue
+
+        elif isinstance(t, list):
+            if len(t) == 0:
+                continue
+            s.append(f"{format_type(t, _current)}")
+        else:
+            s.append(t)
+    if len(s) == 0:
+        return _current
+    elif _current == "Literal" or _current == "Union":
+        return "| ".join(s)
+    else:
+        return f"{_current}[{','.join(s)}]"
+
+
+def get_type_hints(param, module, ignore=None):
+    """Gets the type hints for a parameter."""
+
+    def extract_args(
+        arg,
+        module_name_prefix,
+        additional_interfaces,
+        user_fn_refs,
+        append=True,
+        arg_of=None,
+    ):
+        """Recursively extracts the arguments from a type hint."""
+        arg_names = []
+        args = get_type_arguments(arg)
+
+        # These are local classes that are used in types
+        if inspect.isclass(arg) and arg.__module__.startswith(module_name_prefix):
+            # get sourcecode for the class
+
+            source_code = inspect.getsource(arg)
+
+            if arg_of is not None:
+                refs = get_deep(additional_interfaces, [arg_of, "refs"])
+
+                if refs is None:
+                    refs = [arg.__name__]
+                elif arg.__name__ not in refs:
+                    refs.append(arg.__name__)
+
+                set_deep(additional_interfaces, [arg_of, "refs"], refs)
+
+            if get_deep(additional_interfaces, [arg.__name__, "source"]) is None:
+                set_deep(additional_interfaces, [arg.__name__, "source"], source_code)
+
+            for field_type in typing.get_type_hints(arg).values():
+                # We want to recursively extract the source code for the fields but we don't want to add them to the list of arguments
+                new_args = extract_args(
+                    field_type,
+                    module_name_prefix,
+                    additional_interfaces,
+                    user_fn_refs,
+                    False,
+                    arg.__name__,
+                )
+
+                if len(new_args) > 0:
+                    arg_names.append(new_args)
+
+            if append:
+                arg_names.append(arg.__name__)
+                if arg.__name__ not in user_fn_refs:
+                    user_fn_refs.append(arg.__name__)
+        elif len(args) > 0:
+            if append:
+                arg_names.append(get_container_name(arg))
+            for inner_arg in list(args):
+                new_args = extract_args(
+                    inner_arg,
+                    module_name_prefix,
+                    additional_interfaces,
+                    user_fn_refs,
+                    True,
+                )
+
+                if len(new_args) > 0:
+                    arg_names.append(new_args)
+        else:
+            if append:
+                arg_names.append(get_param_name(arg))
+        return arg_names
+
+    module_name_prefix = module.__name__ + "."
+    additional_interfaces = {}
+    user_fn_refs = []
+
+    args = extract_args(
+        param,
+        module_name_prefix,
+        additional_interfaces,
+        user_fn_refs,
+    )
+
+    formatted_type = format_type(args)
+
+    return (formatted_type, additional_interfaces, user_fn_refs)
+
+
+def extract_docstrings(module):
+    docs = {}
+    for name, obj in inspect.getmembers(module):
+        # filter out the builtins etc
+        if name.startswith("_"):
+            continue
+        #  this could be expanded but i think is ok for now
+        if inspect.isfunction(obj) or inspect.isclass(obj):
+            docs[name] = {}
+
+            main_docstring = inspect.getdoc(obj) or ""
+            cleaned_docstring = str.join(
+                "\n",
+                [s for s in main_docstring.split("\n") if not re.match(r"^\S+:", s)],
+            )
+
+            docs[name]["description"] = cleaned_docstring
+            docs[name]["members"] = {}
+            docs["__meta__"] = {"additional_interfaces": {}}
+            for member_name, member in inspect.getmembers(obj):
+                if inspect.ismethod(member) or inspect.isfunction(member):
+                    # we are are only interested in these methods
+                    if (
+                        member_name != "__init__"
+                        and member_name != "preprocess"
+                        and member_name != "postprocess"
+                    ):
+                        continue
+
+                    docs[name]["members"][member_name] = {}
+
+                    member_docstring = inspect.getdoc(member) or ""
+                    hints = typing.get_type_hints(member)
+                    signature = inspect.signature(member)
+
+                    #  we iterate over the parameters and get the type information
+                    for param_name, param in hints.items():
+                        if (
+                            param_name == "return" and member_name == "postprocess"
+                        ) or (param_name != "return" and member_name == "preprocess"):
+                            continue
+                        _hints = get_type_hints(param, module)
+                        arg_names, additional_interfaces, user_fn_refs = _hints
+
+                        #  These interfaces belong to the whole module, so we add them 'globally' for later
+                        docs["__meta__"]["additional_interfaces"].update(
+                            additional_interfaces
+                        )
+
+                        docs[name]["members"][member_name][param_name] = {}
+
+                        if param_name == "return":
+                            docstring = get_return_docstring(member_docstring)
+                        else:
+                            docstring = get_parameter_docstring(
+                                member_docstring, param_name
+                            )
+
+                        add_value(
+                            docs[name]["members"][member_name][param_name],
+                            "type",
+                            arg_names,
+                        )
+
+                        if signature.parameters.get(param_name, None) is not None:
+                            default_value = signature.parameters[param_name].default
+
+                            add_value(
+                                docs[name]["members"][member_name][param_name],
+                                "default",
+                                format_value(default_value),
+                            )
+
+                        docs[name]["members"][member_name][param_name][
+                            "description"
+                        ] = docstring
+
+                        # We just want to normalise the arg name to 'value' for the preprocess and postprocess methods
+                        if member_name == "postprocess" or member_name == "preprocess":
+                            docs[name]["members"][member_name][
+                                "value"
+                            ] = find_first_non_return_key(
+                                docs[name]["members"][member_name]
+                            )
+                            additional_refs = get_deep(
+                                docs, ["__meta__", "user_fn_refs", name]
+                            )
+                            if additional_refs is None:
+                                set_deep(
+                                    docs,
+                                    ["__meta__", "user_fn_refs", name],
+                                    set(user_fn_refs),
+                                )
+                            else:
+                                additional_refs = set(additional_refs)
+                                additional_refs.update(user_fn_refs)
+                                set_deep(
+                                    docs,
+                                    ["__meta__", "user_fn_refs", name],
+                                    additional_refs,
+                                )
+                if member_name == "EVENTS":
+                    docs[name]["events"] = {}
+                    if isinstance(member, list):
+                        for event in member:
+                            docs[name]["events"][str(event)] = {
+                                "type": None,
+                                "default": None,
+                                "description": event.doc.replace(
+                                    "{{ component }}", name
+                                ),
+                            }
+        final_user_fn_refs = get_deep(docs, ["__meta__", "user_fn_refs", name])
+        if final_user_fn_refs is not None:
+            set_deep(docs, ["__meta__", "user_fn_refs", name], list(final_user_fn_refs))
+    with open("docs.json", "w") as f:
+        f.write(json.dumps(docs, indent=4))
+    return docs
+
+
+class AdditionalInterface(typing.TypedDict):
+    refs: list[str]
+    source: str
+
+
+def make_js(
+    interfaces: dict[str, AdditionalInterface],
+    user_fn_refs: dict[str, list[str]] | None = None,
+):
+    """Makes the javascript code for the additional interfaces."""
+    js_obj_interfaces = "{"
+    for interface_name, interface in interfaces.items():
+        js_obj_interfaces += f"""
+        {interface_name}: {interface.get("refs", None) or "[]"}, """
+    js_obj_interfaces += "}"
+
+    js_obj_user_fn_refs = "{"
+    if user_fn_refs is not None:
+        for class_name, refs in user_fn_refs.items():
+            js_obj_user_fn_refs += f"""
+          {class_name}: {refs}, """
+
+    js_obj_user_fn_refs += "}"
+
+    return rf"""function() {{
+    const refs = {js_obj_interfaces};
+    const user_fn_refs = {js_obj_user_fn_refs};
+    requestAnimationFrame(() => {{
+
+        Object.entries(user_fn_refs).forEach(([key, refs]) => {{
+            if (refs.length > 0) {{
+                const el = document.querySelector(`.${{key}}-user-fn`);
+                if (!el) return;
+                refs.forEach(ref => {{
+                    el.innerHTML = el.innerHTML.replace(
+                        new RegExp("\\b"+ref+"\\b", "g"),
+                        `<a href="#h-${{ref.toLowerCase()}}">${{ref}}</a>`
+                    );
+                }})
+            }}
+        }})
+        
+        Object.entries(refs).forEach(([key, refs]) => {{
+            if (refs.length > 0) {{
+                const el = document.querySelector(`.${{key}}`);
+                if (!el) return;
+                refs.forEach(ref => {{
+                    el.innerHTML = el.innerHTML.replace(
+                        new RegExp("\\b"+ref+"\\b", "g"),
+                        `<a href="#h-${{ref.toLowerCase()}}">${{ref}}</a>`
+                    );
+                }})
+            }}
+        }})
+    }})
+}}
+"""
+
+
+def render_additional_interfaces(interfaces):
+    """Renders additional helper classes or types that were extracted earlier."""
+
+    source = ""
+    for interface_name, interface in interfaces.items():
+        source += f"""
+    code_{interface_name} = gr.Markdown(\"\"\"
+## `{interface_name}`
+```python
+{interface["source"]}
+```\"\"\", elem_classes=["md-custom", "{interface_name}"], header_links=True)
+"""
+    return source
+
+
+def render_additional_interfaces_markdown(interfaces):
+    """Renders additional helper classes or types that were extracted earlier."""
+
+    source = ""
+    for interface_name, interface in interfaces.items():
+        source += f"""
+## `{interface_name}`
+```python
+{interface["source"]}
+```
+"""
+    return source
+
+
+def render_version_badge(pypi_exists, local_version, name):
+    """Renders a version badge for the package. PyPi badge if it exists, otherwise a static badge."""
+    if pypi_exists:
+        return f"""<a href="https://pypi.org/project/{name}/" target="_blank"><img alt="PyPI - Version" src="https://img.shields.io/pypi/v/{name}"></a>"""
+    else:
+        return f"""<img alt="Static Badge" src="https://img.shields.io/badge/version%20-%20{local_version}%20-%20orange">"""
+
+
+def render_github_badge(repo):
+    """Renders a github badge for the package if a repo is specified."""
+    if repo:
+        return f"""<a href="{repo}/issues" target="_blank"><img alt="Static Badge" src="https://img.shields.io/badge/Issues-white?logo=github&logoColor=black"></a>"""
+    else:
+        """"""
+
+
+def render_discuss_badge(space):
+    """Renders a discuss badge for the package if a space is specified."""
+    if space:
+        return f"""<a href="{space}/discussions" target="_blank"><img alt="Static Badge" src="https://img.shields.io/badge/%F0%9F%A4%97%20Discuss-%23097EFF?style=flat&logoColor=black"></a>"""
+    else:
+        """"""
+
+
+def render_class_events(events, name):
+    """Renders the events for a class."""
+    if events is not None:
+        return f"""
+    gr.Markdown("### Events")
+    gr.ParamViewer(value=_docs["{name}"]["events"], linkify={["Event"]})
+
+"""
+
+
+def render_class_events_markdown(events):
+    """Renders the events for a class."""
+    if events is None:
+        return ""
+
+    event_table = """
+### Events
+
+| name | description |
+|:-----|:------------|
+"""
+
+    for event_name, event in events.items():
+        event_table += f"| `{event_name}` | {event['description']} |\n"
+
+    return event_table
+
+
+def render_class_docs(exports, docs):
+    """Renders the class documentation for the package."""
+    docs_classes = ""
+    for class_name in exports:
+        docs_classes += f"""
+    gr.Markdown(\"\"\"
+## `{class_name}`
+
+### Initialization
+\"\"\", elem_classes=["md-custom"], header_links=True)
+
+    gr.ParamViewer(value=_docs["{class_name}"]["members"]["__init__"], linkify={["Parameter"]})
+
+{render_class_events(docs[class_name].get("events", None), class_name)}
+
+    gr.Markdown(\"\"\"
+
+### User function
+
+- **As output:** Is passed, {docs[class_name]["members"]["preprocess"]["return"]["description"]}.
+- **As input:** Should return, {docs[class_name]["members"]["postprocess"]["value"]["description"]}.
+
+```python
+def predict(
+    value: {docs[class_name]["members"]["preprocess"]["return"]["type"]}
+) -> {docs[class_name]["members"]["postprocess"]["value"]["type"]}:
+    return value 
+```
+\"\"\", elem_classes=["md-custom", "{class_name}-user-fn"], header_links=True)
+
+
+    """
+    return docs_classes
+
+
+html = """
+<table>
+<thead>
+<tr>
+<th align="left">name</th>
+<th align="left">type</th>
+<th align="left">default</th>
+<th align="left">description</th>
+</tr>
+</thead>
+<tbody><tr>
+<td align="left"><code>value</code></td>
+<td align="left"><code>list[Parameter] | None</code></td>
+<td align="left"><code>None</code></td>
+<td align="left">A list of dictionaries with keys "type", "description", and "default" for each parameter.</td>
+</tr>
+</tbody></table>
+"""
+
+
+def render_param_table(params):
+    """Renders the parameter table for the package."""
+    table = """<table>
+<thead>
+<tr>
+<th align="left">name</th>
+<th align="left" style="width: 25%;">type</th>
+<th align="left">default</th>
+<th align="left">description</th>
+</tr>
+</thead>
+<tbody>"""
+
+    # for class_name in exports:
+    #     docs_classes += f"""
+    #     """
+    for param_name, param in params.items():
+        table += f"""
+<tr>
+<td align="left"><code>{param_name}</code></td>
+<td align="left" style="width: 25%;">
+
+```python
+{param["type"]}
+```
+
+</td>
+<td align="left"><code>{param["default"]}</code></td>
+<td align="left">{param['description']}</td>
+</tr>
+"""
+    return table + "</tbody></table>"
+
+
+def render_class_docs_markdown(exports, docs):
+    """Renders the class documentation for the package."""
+    docs_classes = ""
+    for class_name in exports:
+        docs_classes += f"""
+## `{class_name}`
+
+### Initialization
+
+{render_param_table(docs[class_name]["members"]["__init__"])}
+
+{render_class_events_markdown(docs[class_name].get("events", None))}
+
+### User function
+
+- **As output:** Is passed, {docs[class_name]["members"]["preprocess"]["return"]["description"]}.
+- **As input:** Should return, {docs[class_name]["members"]["postprocess"]["value"]["description"]}.
+
+```python
+def predict(
+    value: {docs[class_name]["members"]["preprocess"]["return"]["type"]}
+) -> {docs[class_name]["members"]["postprocess"]["value"]["type"]}:
+    return value 
+```
+"""
+    return docs_classes
+
+
+def make_space(docs, name, description, local_version, demo, space, repo, pypi_exists):
+    filtered_keys = [key for key in docs if key != "__meta__"]
+
+    source = f"""
+import gradio as gr
+from app import demo as app
+from {name} import {",".join(filtered_keys)}
path: gradio/cli/commands/components/_docs_utils.py
text: @user1:
Are these imported classes actually used? If not we can remove

@author:
Ah no, they won't be used.

diff_hunk: @@ -0,0 +1,101 @@
+import importlib
+from pathlib import Path
+from typing import Optional
+
+import requests
+import toml
path: gradio/cli/commands/components/docs.py
text: @user1:
toml is only included in 3.10. We need to use `tomlkit` here for older versions. It's already installed and AKAIK `toml` is identical to `tomlkit`.

diff_hunk: @@ -0,0 +1,101 @@
+import importlib
path: gradio/cli/commands/components/docs.py
text: @user1:
We need to add `from __future__ import annotations` here to support 3.8/3.9.