code: def inject_weight_metadata(app, what, name, obj, options, lines):
      """This hook is used to generate docs for the models weights.
  
      Objects like ResNet18_Weights are enums with fields, where each field is a Weight object.
      Enums aren't easily documented in Python so the solution we're going for is to:
  
      - add an autoclass directive in the model's builder docstring, e.g.
  
      ```
      .. autoclass:: torchvision.models.ResNet34_Weights
          :members:
      ```
  
      (see resnet.py for an example)
      - then this hook is called automatically when building the docs, and it generates the text that gets
        used within the autoclass directive.
      """
  
      if getattr(obj, "__name__", "").endswith(
          ("_Weights", "_QuantizedWeights")
      ):
          if len(obj) == 0:
              lines[:] = ["There are no available pre-trained weights."]
              return
  
          lines[:] = [
              "The model builder above accepts the following values as the ``weights`` parameter.",
              f"``{obj.__name__}.DEFAULT`` is equivalent to ``{obj.DEFAULT}``. You can also use strings, e.g. "
              f"``weights='DEFAULT'`` or ``weights='{str(list(obj)[0]).split('.')[1]}'``.",
          ]
  
          if obj.__doc__ != "An enumeration.":
              # We only show the custom enum doc if it was overridden. The default one from Python is "An enumeration"
              lines.append("")
              lines.append(obj.__doc__)
  
          lines.append("")
  
          for field in obj:
              meta = copy(field.meta)
  
              lines += [f"**{str(field)}**:", ""]
              lines += [meta.pop("_docs")]
  
              if field == obj.DEFAULT:
                  lines += [
                      f"Also available as ``{obj.__name__}.DEFAULT``."
                  ]
              lines += [""]
  
              table = []
              metrics = meta.pop("_metrics")
              for dataset, dataset_metrics in metrics.items():
                  for (
                      metric_name,
                      metric_value,
                  ) in dataset_metrics.items():
                      table.append(
                          (
                              f"{metric_name} (on {dataset})",
                              str(metric_value),
                          )
                      )
  
              for k, v in meta.items():
                  if k in {"recipe", "license"}:
                      v = f"`link <{v}>`__"
                  elif k == "min_size":
                      v = f"height={v[0]}, width={v[1]}"
                  elif k in {
                      "categories",
                      "keypoint_names",
                  } and isinstance(v, list):
                      max_visible = 3
                      v_sample = ", ".join(v[:max_visible])
                      v = (
                          f"{v_sample}, ... ({len(v)-max_visible} omitted)"
                          if len(v) > max_visible
                          else v_sample
                      )
                  elif k == "_ops":
                      v = f"{v:.2f}"
                      k = (
                          "GIPS"
                          if obj.__name__.endswith("_QuantizedWeights")
                          else "GFLOPS"
                      )
                  elif k == "_file_size":
                      k = "File size"
                      v = f"{v:.1f} MB"
  
                  table.append((str(k), str(v)))
              table = tabulate(table, tablefmt="rst")
              lines += [
                  ".. rst-class:: table-weights"
              ]  # Custom CSS class, see custom_torchvision.css
              lines += [".. table::", ""]
              lines += textwrap.indent(table, " " * 4).split("\n")
              lines.append("")
              lines.append(
                  f"The inference transforms are available at ``{str(field)}.transforms`` and "
                  f"perform the following preprocessing operations: {field.transforms().describe()}"
              )
              lines.append("")
  
imports: import os
  import sys
  import textwrap
  from copy import copy
  from pathlib import Path
  import pytorch_sphinx_theme
  import torchvision
  import torchvision.models
  from sphinx_gallery.sorting import ExplicitOrder
  from tabulate import tabulate
  from sphinx_gallery import gen_rst
  from docutils import nodes
  from sphinx import addnodes
  from sphinx.util.docfields import TypedField
label_desc: Use image node_id 3 for calling a global function with example usage: inject_weight_metadata(app, what, name, obj, options, lines) without return types