Register
Login
Resources
Docs Blog Datasets Glossary Case Studies Tutorials & Webinars
Product
Data Engine LLMs Platform Enterprise
Pricing Explore
Connect to our Discord channel

build_reference.py 5.0 KB

You have to be logged in to leave a comment. Sign In
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
  1. # Ultralytics YOLO 🚀, AGPL-3.0 license
  2. """
  3. Helper file to build Ultralytics Docs reference section. Recursively walks through ultralytics dir and builds an MkDocs
  4. reference section of *.md files composed of classes and functions, and also creates a nav menu for use in mkdocs.yaml.
  5. Note: Must be run from repository root directory. Do not run from docs directory.
  6. """
  7. import re
  8. from collections import defaultdict
  9. from pathlib import Path
  10. from ultralytics.utils import ROOT
  11. NEW_YAML_DIR = ROOT.parent
  12. CODE_DIR = ROOT
  13. REFERENCE_DIR = ROOT.parent / 'docs/en/reference'
  14. def extract_classes_and_functions(filepath: Path) -> tuple:
  15. """Extracts class and function names from a given Python file."""
  16. content = filepath.read_text()
  17. class_pattern = r'(?:^|\n)class\s(\w+)(?:\(|:)'
  18. func_pattern = r'(?:^|\n)def\s(\w+)\('
  19. classes = re.findall(class_pattern, content)
  20. functions = re.findall(func_pattern, content)
  21. return classes, functions
  22. def create_markdown(py_filepath: Path, module_path: str, classes: list, functions: list):
  23. """Creates a Markdown file containing the API reference for the given Python module."""
  24. md_filepath = py_filepath.with_suffix('.md')
  25. # Read existing content and keep header content between first two ---
  26. header_content = ''
  27. if md_filepath.exists():
  28. existing_content = md_filepath.read_text()
  29. header_parts = existing_content.split('---')
  30. for part in header_parts:
  31. if 'description:' in part or 'comments:' in part:
  32. header_content += f'---{part}---\n\n'
  33. module_name = module_path.replace('.__init__', '')
  34. module_path = module_path.replace('.', '/')
  35. url = f'https://github.com/ultralytics/ultralytics/blob/main/{module_path}.py'
  36. edit = f'https://github.com/ultralytics/ultralytics/edit/main/{module_path}.py'
  37. title_content = (
  38. f'# Reference for `{module_path}.py`\n\n'
  39. f'!!! Note\n\n'
  40. f' This file is available at [{url}]({url}). If you spot a problem please help fix it by [contributing](https://docs.ultralytics.com/help/contributing/) a [Pull Request]({edit}) 🛠️. Thank you 🙏!\n\n'
  41. )
  42. md_content = ['<br><br>\n'] + [f'## ::: {module_name}.{class_name}\n\n<br><br>\n' for class_name in classes]
  43. md_content.extend(f'## ::: {module_name}.{func_name}\n\n<br><br>\n' for func_name in functions)
  44. md_content = header_content + title_content + '\n'.join(md_content)
  45. if not md_content.endswith('\n'):
  46. md_content += '\n'
  47. md_filepath.parent.mkdir(parents=True, exist_ok=True)
  48. md_filepath.write_text(md_content)
  49. return md_filepath.relative_to(NEW_YAML_DIR)
  50. def nested_dict() -> defaultdict:
  51. """Creates and returns a nested defaultdict."""
  52. return defaultdict(nested_dict)
  53. def sort_nested_dict(d: dict) -> dict:
  54. """Sorts a nested dictionary recursively."""
  55. return {key: sort_nested_dict(value) if isinstance(value, dict) else value for key, value in sorted(d.items())}
  56. def create_nav_menu_yaml(nav_items: list):
  57. """Creates a YAML file for the navigation menu based on the provided list of items."""
  58. nav_tree = nested_dict()
  59. for item_str in nav_items:
  60. item = Path(item_str)
  61. parts = item.parts
  62. current_level = nav_tree['reference']
  63. for part in parts[2:-1]: # skip the first two parts (docs and reference) and the last part (filename)
  64. current_level = current_level[part]
  65. md_file_name = parts[-1].replace('.md', '')
  66. current_level[md_file_name] = item
  67. nav_tree_sorted = sort_nested_dict(nav_tree)
  68. def _dict_to_yaml(d, level=0):
  69. """Converts a nested dictionary to a YAML-formatted string with indentation."""
  70. yaml_str = ''
  71. indent = ' ' * level
  72. for k, v in d.items():
  73. if isinstance(v, dict):
  74. yaml_str += f'{indent}- {k}:\n{_dict_to_yaml(v, level + 1)}'
  75. else:
  76. yaml_str += f"{indent}- {k}: {str(v).replace('docs/en/', '')}\n"
  77. return yaml_str
  78. # Print updated YAML reference section
  79. print('Scan complete, new mkdocs.yaml reference section is:\n\n', _dict_to_yaml(nav_tree_sorted))
  80. # Save new YAML reference section
  81. # (NEW_YAML_DIR / 'nav_menu_updated.yml').write_text(_dict_to_yaml(nav_tree_sorted))
  82. def main():
  83. """Main function to extract class and function names, create Markdown files, and generate a YAML navigation menu."""
  84. nav_items = []
  85. for py_filepath in CODE_DIR.rglob('*.py'):
  86. classes, functions = extract_classes_and_functions(py_filepath)
  87. if classes or functions:
  88. py_filepath_rel = py_filepath.relative_to(CODE_DIR)
  89. md_filepath = REFERENCE_DIR / py_filepath_rel
  90. module_path = f"ultralytics.{py_filepath_rel.with_suffix('').as_posix().replace('/', '.')}"
  91. md_rel_filepath = create_markdown(md_filepath, module_path, classes, functions)
  92. nav_items.append(str(md_rel_filepath))
  93. create_nav_menu_yaml(nav_items)
  94. if __name__ == '__main__':
  95. main()
Tip!

Press p or to see the previous file or, n or to see the next file

Comments

Loading...