|
| 1 | +from __future__ import annotations as _annotations |
| 2 | + |
| 3 | +import os |
| 4 | + |
| 5 | +from bs4 import BeautifulSoup |
| 6 | +from markdownify import MarkdownConverter |
| 7 | +from mkdocs.config.defaults import MkDocsConfig |
| 8 | +from mkdocs.structure.files import Files |
| 9 | +from mkdocs.structure.pages import Page |
| 10 | + |
| 11 | + |
| 12 | +def on_config(config: MkDocsConfig): |
| 13 | + os.mkdir(config.site_dir) |
| 14 | + llms_path = os.path.join(config.site_dir, 'llms.txt') |
| 15 | + with open(llms_path, 'w') as f: |
| 16 | + f.write('') |
| 17 | + |
| 18 | + |
| 19 | +def on_page_content(html: str, page: Page, config: MkDocsConfig, files: Files) -> str: |
| 20 | + soup = BeautifulSoup(html, 'html.parser') |
| 21 | + |
| 22 | + # Clean up presentational and UI elements |
| 23 | + for element in soup.find_all( |
| 24 | + ['a', 'div', 'img'], attrs={'class': ['headerlink', 'tabbed-labels', 'twemoji lg middle', 'twemoji']} |
| 25 | + ): |
| 26 | + element.decompose() |
| 27 | + |
| 28 | + # The API reference generates HTML tables with line numbers, this strips the line numbers cell and goes back to a code block |
| 29 | + for extra in soup.find_all('table', attrs={'class': 'highlighttable'}): |
| 30 | + extra.replace_with(BeautifulSoup(f'<pre>{extra.find('code').get_text()}</pre>', 'html.parser')) |
| 31 | + |
| 32 | + with open(os.path.join(config.site_dir, 'llms.txt'), 'a', encoding='utf-8') as f: |
| 33 | + f.write(MarkdownConverter().convert_soup(soup)) # type: ignore[reportUnknownMemberType] |
| 34 | + |
| 35 | + return html |
0 commit comments