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_docs.py 11 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
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
  1. # Ultralytics YOLO 🚀, AGPL-3.0 license
  2. """
  3. Automates the building and post-processing of MkDocs documentation, particularly for projects with multilingual content.
  4. It streamlines the workflow for generating localized versions of the documentation and updating HTML links to ensure
  5. they are correctly formatted.
  6. Key Features:
  7. - Automated building of MkDocs documentation: The script compiles both the main documentation and
  8. any localized versions specified in separate MkDocs configuration files.
  9. - Post-processing of generated HTML files: After the documentation is built, the script updates all
  10. HTML files to remove the '.md' extension from internal links. This ensures that links in the built
  11. HTML documentation correctly point to other HTML pages rather than Markdown files, which is crucial
  12. for proper navigation within the web-based documentation.
  13. Usage:
  14. - Run the script from the root directory of your MkDocs project.
  15. - Ensure that MkDocs is installed and that all MkDocs configuration files (main and localized versions)
  16. are present in the project directory.
  17. - The script first builds the documentation using MkDocs, then scans the generated HTML files in the 'site'
  18. directory to update the internal links.
  19. - It's ideal for projects where the documentation is written in Markdown and needs to be served as a static website.
  20. Note:
  21. - This script is built to be run in an environment where Python and MkDocs are installed and properly configured.
  22. """
  23. import os
  24. import re
  25. import shutil
  26. import subprocess
  27. from pathlib import Path
  28. from bs4 import BeautifulSoup
  29. from tqdm import tqdm
  30. os.environ["JUPYTER_PLATFORM_DIRS"] = "1" # fix DeprecationWarning: Jupyter is migrating to use standard platformdirs
  31. DOCS = Path(__file__).parent.resolve()
  32. SITE = DOCS.parent / "site"
  33. def prepare_docs_markdown(clone_repos=True):
  34. """Build docs using mkdocs."""
  35. if SITE.exists():
  36. print(f"Removing existing {SITE}")
  37. shutil.rmtree(SITE)
  38. # Get hub-sdk repo
  39. if clone_repos:
  40. repo = "https://github.com/ultralytics/hub-sdk"
  41. local_dir = DOCS.parent / Path(repo).name
  42. if not local_dir.exists():
  43. os.system(f"git clone {repo} {local_dir}")
  44. os.system(f"git -C {local_dir} pull") # update repo
  45. shutil.rmtree(DOCS / "en/hub/sdk", ignore_errors=True) # delete if exists
  46. shutil.copytree(local_dir / "docs", DOCS / "en/hub/sdk") # for docs
  47. shutil.rmtree(DOCS.parent / "hub_sdk", ignore_errors=True) # delete if exists
  48. shutil.copytree(local_dir / "hub_sdk", DOCS.parent / "hub_sdk") # for mkdocstrings
  49. print(f"Cloned/Updated {repo} in {local_dir}")
  50. # Add frontmatter
  51. for file in tqdm((DOCS / "en").rglob("*.md"), desc="Adding frontmatter"):
  52. update_markdown_files(file)
  53. def update_page_title(file_path: Path, new_title: str):
  54. """Update the title of an HTML file."""
  55. # Read the content of the file
  56. with open(file_path, encoding="utf-8") as file:
  57. content = file.read()
  58. # Replace the existing title with the new title
  59. updated_content = re.sub(r"<title>.*?</title>", f"<title>{new_title}</title>", content)
  60. # Write the updated content back to the file
  61. with open(file_path, "w", encoding="utf-8") as file:
  62. file.write(updated_content)
  63. def update_html_head(script=""):
  64. """Update the HTML head section of each file."""
  65. html_files = Path(SITE).rglob("*.html")
  66. for html_file in tqdm(html_files, desc="Processing HTML files"):
  67. with html_file.open("r", encoding="utf-8") as file:
  68. html_content = file.read()
  69. if script in html_content: # script already in HTML file
  70. return
  71. head_end_index = html_content.lower().rfind("</head>")
  72. if head_end_index != -1:
  73. # Add the specified JavaScript to the HTML file just before the end of the head tag.
  74. new_html_content = html_content[:head_end_index] + script + html_content[head_end_index:]
  75. with html_file.open("w", encoding="utf-8") as file:
  76. file.write(new_html_content)
  77. def update_subdir_edit_links(subdir="", docs_url=""):
  78. """Update the HTML head section of each file."""
  79. if str(subdir[0]) == "/":
  80. subdir = str(subdir[0])[1:]
  81. html_files = (SITE / subdir).rglob("*.html")
  82. for html_file in tqdm(html_files, desc="Processing subdir files"):
  83. with html_file.open("r", encoding="utf-8") as file:
  84. soup = BeautifulSoup(file, "html.parser")
  85. # Find the anchor tag and update its href attribute
  86. a_tag = soup.find("a", {"class": "md-content__button md-icon"})
  87. if a_tag and a_tag["title"] == "Edit this page":
  88. a_tag["href"] = f"{docs_url}{a_tag['href'].split(subdir)[-1]}"
  89. # Write the updated HTML back to the file
  90. with open(html_file, "w", encoding="utf-8") as file:
  91. file.write(str(soup))
  92. def update_markdown_files(md_filepath: Path):
  93. """Creates or updates a Markdown file, ensuring frontmatter is present."""
  94. if md_filepath.exists():
  95. content = md_filepath.read_text().strip()
  96. # Replace apostrophes
  97. content = content.replace("‘", "'").replace("’", "'")
  98. # Add frontmatter if missing
  99. if not content.strip().startswith("---\n") and "macros" not in md_filepath.parts: # skip macros directory
  100. header = "---\ncomments: true\ndescription: TODO ADD DESCRIPTION\nkeywords: TODO ADD KEYWORDS\n---\n\n"
  101. content = header + content
  102. # Ensure MkDocs admonitions "=== " lines are preceded and followed by empty newlines
  103. lines = content.split("\n")
  104. new_lines = []
  105. for i, line in enumerate(lines):
  106. stripped_line = line.strip()
  107. if stripped_line.startswith("=== "):
  108. if i > 0 and new_lines[-1] != "":
  109. new_lines.append("")
  110. new_lines.append(line)
  111. if i < len(lines) - 1 and lines[i + 1].strip() != "":
  112. new_lines.append("")
  113. else:
  114. new_lines.append(line)
  115. content = "\n".join(new_lines)
  116. # Add EOF newline if missing
  117. if not content.endswith("\n"):
  118. content += "\n"
  119. # Save page
  120. md_filepath.write_text(content)
  121. return
  122. def update_docs_html():
  123. """Updates titles, edit links, head sections, and converts plaintext links in HTML documentation."""
  124. # Update 404 titles
  125. update_page_title(SITE / "404.html", new_title="Ultralytics Docs - Not Found")
  126. # Update edit links
  127. update_subdir_edit_links(
  128. subdir="hub/sdk/", # do not use leading slash
  129. docs_url="https://github.com/ultralytics/hub-sdk/tree/main/docs/",
  130. )
  131. # Convert plaintext links to HTML hyperlinks
  132. files_modified = 0
  133. for html_file in tqdm(SITE.rglob("*.html"), desc="Converting plaintext links"):
  134. with open(html_file, encoding="utf-8") as file:
  135. content = file.read()
  136. updated_content = convert_plaintext_links_to_html(content)
  137. if updated_content != content:
  138. with open(html_file, "w", encoding="utf-8") as file:
  139. file.write(updated_content)
  140. files_modified += 1
  141. print(f"Modified plaintext links in {files_modified} files.")
  142. # Update HTML file head section
  143. script = ""
  144. if any(script):
  145. update_html_head(script)
  146. # Delete the /macros directory from the built site
  147. macros_dir = SITE / "macros"
  148. if macros_dir.exists():
  149. print(f"Removing /macros directory from site: {macros_dir}")
  150. shutil.rmtree(macros_dir)
  151. def convert_plaintext_links_to_html(content):
  152. """Convert plaintext links to HTML hyperlinks in the main content area only."""
  153. soup = BeautifulSoup(content, "html.parser")
  154. # Find the main content area (adjust this selector based on your HTML structure)
  155. main_content = soup.find("main") or soup.find("div", class_="md-content")
  156. if not main_content:
  157. return content # Return original content if main content area not found
  158. modified = False
  159. for paragraph in main_content.find_all(["p", "li"]): # Focus on paragraphs and list items
  160. for text_node in paragraph.find_all(string=True, recursive=False):
  161. if text_node.parent.name not in {"a", "code"}: # Ignore links and code blocks
  162. new_text = re.sub(
  163. r"(https?://[^\s()<>]*[^\s()<>.,:;!?\'\"])",
  164. r'<a href="\1">\1</a>',
  165. str(text_node),
  166. )
  167. if "<a href=" in new_text:
  168. # Parse the new text with BeautifulSoup to handle HTML properly
  169. new_soup = BeautifulSoup(new_text, "html.parser")
  170. text_node.replace_with(new_soup)
  171. modified = True
  172. return str(soup) if modified else content
  173. def remove_macros():
  174. """Removes the /macros directory and related entries in sitemap.xml from the built site."""
  175. shutil.rmtree(SITE / "macros", ignore_errors=True)
  176. (SITE / "sitemap.xml.gz").unlink(missing_ok=True)
  177. # Process sitemap.xml
  178. sitemap = SITE / "sitemap.xml"
  179. lines = sitemap.read_text(encoding="utf-8").splitlines(keepends=True)
  180. # Find indices of '/macros/' lines
  181. macros_indices = [i for i, line in enumerate(lines) if "/macros/" in line]
  182. # Create a set of indices to remove (including lines before and after)
  183. indices_to_remove = set()
  184. for i in macros_indices:
  185. indices_to_remove.update(range(i - 1, i + 3)) # i-1, i, i+1, i+2, i+3
  186. # Create new list of lines, excluding the ones to remove
  187. new_lines = [line for i, line in enumerate(lines) if i not in indices_to_remove]
  188. # Write the cleaned content back to the file
  189. sitemap.write_text("".join(new_lines), encoding="utf-8")
  190. print(f"Removed {len(macros_indices)} URLs containing '/macros/' from {sitemap}")
  191. def minify_html_files():
  192. """Minifies all HTML files in the site directory and prints reduction stats."""
  193. try:
  194. from minify_html import minify # pip install minify-html
  195. except ImportError:
  196. return
  197. total_original_size = 0
  198. total_minified_size = 0
  199. for html_file in tqdm(SITE.rglob("*.html"), desc="Minifying HTML files"):
  200. with open(html_file, encoding="utf-8") as f:
  201. content = f.read()
  202. original_size = len(content)
  203. minified_content = minify(content)
  204. minified_size = len(minified_content)
  205. total_original_size += original_size
  206. total_minified_size += minified_size
  207. with open(html_file, "w", encoding="utf-8") as f:
  208. f.write(minified_content)
  209. total_reduction = total_original_size - total_minified_size
  210. total_percent_reduction = (total_reduction / total_original_size) * 100
  211. print(f"Minify HTML reduction: {total_percent_reduction:.2f}% " f"({total_reduction / 1024:.2f} KB saved)")
  212. def main():
  213. """Builds docs, updates titles and edit links, minifies HTML, and prints local server command."""
  214. prepare_docs_markdown()
  215. # Build the main documentation
  216. print(f"Building docs from {DOCS}")
  217. subprocess.run(f"mkdocs build -f {DOCS.parent}/mkdocs.yml --strict", check=True, shell=True)
  218. remove_macros()
  219. print(f"Site built at {SITE}")
  220. # Update docs HTML pages
  221. update_docs_html()
  222. # Minify HTML files
  223. minify_html_files()
  224. # Show command to serve built website
  225. print('Docs built correctly ✅\nServe site at http://localhost:8000 with "python -m http.server --directory site"')
  226. if __name__ == "__main__":
  227. main()
Tip!

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

Comments

Loading...