|
| 1 | +# SPDX-FileCopyrightText: Copyright (c) 2024 NVIDIA CORPORATION & AFFILIATES. All rights reserved. |
| 2 | +# SPDX-License-Identifier: Apache-2.0 |
| 3 | +# |
| 4 | +# Licensed under the Apache License, Version 2.0 (the "License"); |
| 5 | +# you may not use this file except in compliance with the License. |
| 6 | +# You may obtain a copy of the License at |
| 7 | +# |
| 8 | +# http://www.apache.org/licenses/LICENSE-2.0 |
| 9 | +# |
| 10 | +# Unless required by applicable law or agreed to in writing, software |
| 11 | +# distributed under the License is distributed on an "AS IS" BASIS, |
| 12 | +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. |
| 13 | +# See the License for the specific language governing permissions and |
| 14 | +# limitations under the License. |
| 15 | + |
| 16 | +"""A small extension on top of the autodoc_pydantic extension to show default configs.""" |
| 17 | + |
| 18 | +import json |
| 19 | +import types |
| 20 | +from contextlib import contextmanager, nullcontext |
| 21 | +from typing import Any, Callable |
| 22 | + |
| 23 | +from sphinx.application import Sphinx |
| 24 | +from sphinxcontrib.autodoc_pydantic import __version__ |
| 25 | +from sphinxcontrib.autodoc_pydantic.directives.autodocumenters import ( |
| 26 | + PydanticFieldDocumenter, |
| 27 | + PydanticModelDocumenter, |
| 28 | +) |
| 29 | +from sphinxcontrib.autodoc_pydantic.directives.templates import to_collapsable |
| 30 | + |
| 31 | + |
| 32 | +def _wrap_into_collabsable(summary: str): |
| 33 | + """Decorator to wrap the lines written by the function into a collapsable block.""" |
| 34 | + |
| 35 | + # patch self.add_line to intercept the lines instead of writing them to the output |
| 36 | + def add_line_intercepted( |
| 37 | + self: "ModeloptPydanticModelDocumenter", line: str, source: str, *lineno: int |
| 38 | + ): |
| 39 | + if self._source_intercepted is None: |
| 40 | + self._source_intercepted = source |
| 41 | + else: |
| 42 | + assert self._source_intercepted == source, "Only one source supported!" |
| 43 | + assert not lineno, "No optional lineno argument supported!" |
| 44 | + self._lines_intercepted.append(line) |
| 45 | + |
| 46 | + def decorator(func: Callable) -> Callable: |
| 47 | + def func_with_collabsable(self: "ModeloptPydanticModelDocumenter", *args, **kwargs) -> Any: |
| 48 | + # patch the add_line method |
| 49 | + self._lines_intercepted = [] |
| 50 | + self._source_intercepted = None |
| 51 | + self.add_line_unpatched = self.add_line.__func__ |
| 52 | + self.add_line = types.MethodType(add_line_intercepted, self) |
| 53 | + |
| 54 | + # run method |
| 55 | + ret = func(self, *args, **kwargs) |
| 56 | + |
| 57 | + # clean up |
| 58 | + lines = self._lines_intercepted |
| 59 | + source = self._source_intercepted |
| 60 | + self.add_line = types.MethodType(self.add_line_unpatched, self) |
| 61 | + del self._lines_intercepted |
| 62 | + del self._source_intercepted |
| 63 | + del self.add_line_unpatched |
| 64 | + |
| 65 | + # check if we have any lines to wrap |
| 66 | + if lines: |
| 67 | + lines = to_collapsable(lines, summary, "autodoc_pydantic_collapsable_json") |
| 68 | + for line in lines: |
| 69 | + self.add_line(line, source) |
| 70 | + |
| 71 | + # return the original return value |
| 72 | + return ret |
| 73 | + |
| 74 | + return func_with_collabsable |
| 75 | + |
| 76 | + return decorator |
| 77 | + |
| 78 | + |
| 79 | +def _skip_lines(func: Callable) -> Callable: |
| 80 | + def func_with_skip_lines(self: "ModeloptPydanticModelDocumenter", *args, **kwargs) -> Any: |
| 81 | + # patch the add_line method |
| 82 | + self.add_line_unpatched = self.add_line.__func__ |
| 83 | + self.add_line = types.MethodType(lambda self, *args, **kwargs: None, self) |
| 84 | + |
| 85 | + # run method |
| 86 | + ret = func(self, *args, **kwargs) |
| 87 | + |
| 88 | + # clean up |
| 89 | + self.add_line = types.MethodType(self.add_line_unpatched, self) |
| 90 | + del self.add_line_unpatched |
| 91 | + |
| 92 | + # return the original return value |
| 93 | + return ret |
| 94 | + |
| 95 | + return func_with_skip_lines |
| 96 | + |
| 97 | + |
| 98 | +class ModeloptPydanticModelDocumenter(PydanticModelDocumenter): |
| 99 | + """We add the option to print defaults.""" |
| 100 | + |
| 101 | + def __init__(self, *args: Any) -> None: |
| 102 | + super().__init__(*args) |
| 103 | + exclude_members = self.options["exclude-members"] |
| 104 | + exclude_members.add("model_computed_fields") |
| 105 | + |
| 106 | + @_wrap_into_collabsable("Show default config as JSON") |
| 107 | + def add_default_dict(self) -> None: |
| 108 | + # we use sanitized schema which means errors in the schema are ignored |
| 109 | + schema = self.pydantic.inspect.schema.sanitized |
| 110 | + config = {k: v.get("default") for k, v in schema["properties"].items()} |
| 111 | + |
| 112 | + # create valid rst lines from the config |
| 113 | + config_json = json.dumps(config, default=str, indent=3) |
| 114 | + lines = [f" {line}" for line in config_json.split("\n")] |
| 115 | + lines = [":Default config (JSON):", "", ".. code-block:: json", ""] + lines + [""] |
| 116 | + |
| 117 | + # add lines to autodoc |
| 118 | + source_name = self.get_sourcename() |
| 119 | + for line in lines: |
| 120 | + self.add_line(line, source_name) |
| 121 | + |
| 122 | + def add_collapsable_schema(self): |
| 123 | + if self.pydantic.options.is_true("modelopt-show-default-dict", True): |
| 124 | + self.add_default_dict() |
| 125 | + with ( |
| 126 | + nullcontext() |
| 127 | + if self.pydantic.options.is_true("modelopt-show-json-schema", True) |
| 128 | + else self._skip_lines() |
| 129 | + ): |
| 130 | + super().add_collapsable_schema() |
| 131 | + |
| 132 | + @_wrap_into_collabsable("Show field summary") |
| 133 | + def add_field_summary(self): |
| 134 | + return super().add_field_summary() |
| 135 | + |
| 136 | + @contextmanager |
| 137 | + def _skip_lines(self): |
| 138 | + self.add_line_unpatched = self.add_line.__func__ |
| 139 | + self.add_line = types.MethodType(lambda self, *args, **kwargs: None, self) |
| 140 | + yield |
| 141 | + self.add_line = types.MethodType(self.add_line_unpatched, self) |
| 142 | + del self.add_line_unpatched |
| 143 | + |
| 144 | + |
| 145 | +class ModeloptPydanticFieldDocumenter(PydanticFieldDocumenter): |
| 146 | + """Collabsing field doc string by default and only showing summary.""" |
| 147 | + |
| 148 | + @_wrap_into_collabsable("Show details") |
| 149 | + def add_description(self): |
| 150 | + super().add_description() |
| 151 | + |
| 152 | + |
| 153 | +def setup(app: Sphinx) -> dict[str, Any]: |
| 154 | + """Setup the extension.""" |
| 155 | + # we have one new option that we enable |
| 156 | + app.add_config_value("autodoc_pydantic_model_modelopt_show_default_dict", True, True, bool) |
| 157 | + app.add_config_value("autodoc_pydantic_model_modelopt_show_json_schema", True, True, bool) |
| 158 | + |
| 159 | + # we require this extension to be loaded first |
| 160 | + app.setup_extension("sphinx.ext.autodoc") |
| 161 | + app.setup_extension("sphinxcontrib.autodoc_pydantic") |
| 162 | + |
| 163 | + # we modify the model and field documenter on top of autodoch_pydantic |
| 164 | + app.add_autodocumenter(ModeloptPydanticModelDocumenter, override=True) |
| 165 | + app.add_autodocumenter(ModeloptPydanticFieldDocumenter, override=True) |
| 166 | + |
| 167 | + return { |
| 168 | + "version": __version__, |
| 169 | + "parallel_read_safe": True, |
| 170 | + "parallel_write_safe": True, |
| 171 | + } |
0 commit comments