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| 5 |
+
# "beautifulsoup4",
|
| 6 |
+
# "llms-txt-rs",
|
| 7 |
+
# "tqdm"
|
| 8 |
+
# ]
|
| 9 |
+
# ///
|
| 10 |
+
|
| 11 |
+
from dataclasses import dataclass
|
| 12 |
+
from urllib.parse import urlparse
|
| 13 |
+
|
| 14 |
+
import asyncio
|
| 15 |
+
import aiohttp
|
| 16 |
+
from bs4 import BeautifulSoup
|
| 17 |
+
from llms_txt_rs import parse_llms_txt
|
| 18 |
+
from datasets import Dataset
|
| 19 |
+
from tqdm.asyncio import tqdm_asyncio
|
| 20 |
+
import json
|
| 21 |
+
|
| 22 |
+
# Type alias
|
| 23 |
+
ParsedTxt = dict[str, str | None | dict[str, list[dict[str, str | None]]]]
|
| 24 |
+
|
| 25 |
+
|
| 26 |
+
@dataclass
|
| 27 |
+
class Page:
|
| 28 |
+
name: str
|
| 29 |
+
url: str | None
|
| 30 |
+
url_full: str | None
|
| 31 |
+
# Data added to the Page object once downloaded
|
| 32 |
+
llms_txt: str | None = None
|
| 33 |
+
llms_txt_parsed: ParsedTxt | None = None
|
| 34 |
+
llms_txt_full: str | None = None
|
| 35 |
+
|
| 36 |
+
@property
|
| 37 |
+
def base_url(self) -> str:
|
| 38 |
+
parsed = urlparse(self.url)
|
| 39 |
+
return f"{parsed.scheme}://{parsed.netloc}"
|
| 40 |
+
|
| 41 |
+
def add_text(self, txt: str, parsed_txt: ParsedTxt, is_full: bool = False, url: str | None = None) -> None:
|
| 42 |
+
if url and not url.startswith(self.base_url):
|
| 43 |
+
return
|
| 44 |
+
if not is_full:
|
| 45 |
+
self.llms_txt = txt
|
| 46 |
+
self.llms_txt_parsed = parsed_txt
|
| 47 |
+
else:
|
| 48 |
+
self.llms_txt_full = txt
|
| 49 |
+
|
| 50 |
+
def record(self) -> dict:
|
| 51 |
+
# This is necessary to ensure the 'llms_txt_parsed' field is saved appropriately,
|
| 52 |
+
# otherwise datasets will mix the fields to make the field homogeneus across the different
|
| 53 |
+
# pages.
|
| 54 |
+
return {
|
| 55 |
+
"name": self.name,
|
| 56 |
+
"url": self.url,
|
| 57 |
+
"url_full": self.url_full,
|
| 58 |
+
"llms_txt": self.llms_txt,
|
| 59 |
+
"llms_txt_parsed": json.dumps(self.llms_txt_parsed),
|
| 60 |
+
"llms_txt_full": self.llms_txt_full,
|
| 61 |
+
}
|
| 62 |
+
|
| 63 |
+
|
| 64 |
+
async def download_directory_llmstxt(url: str = "https://directory.llmstxt.cloud/") -> list[Page]:
|
| 65 |
+
async with aiohttp.ClientSession() as session:
|
| 66 |
+
async with session.get(url) as response:
|
| 67 |
+
content = await response.read()
|
| 68 |
+
soup = BeautifulSoup(content, 'html.parser')
|
| 69 |
+
|
| 70 |
+
pages = [parse_row(row) for row in soup.find_all('li')]
|
| 71 |
+
|
| 72 |
+
return pages
|
| 73 |
+
|
| 74 |
+
|
| 75 |
+
# Extracts the pages from the html
|
| 76 |
+
def parse_row(row: list[str]) -> Page:
|
| 77 |
+
a_elems = row.find_all("a")
|
| 78 |
+
name = a_elems[0].find("h3").text
|
| 79 |
+
url_full = None
|
| 80 |
+
if len(a_elems) > 2: # contains both url llms.txt and llms-full.txt
|
| 81 |
+
for elem in a_elems[1:]:
|
| 82 |
+
url = elem.get("href")
|
| 83 |
+
if "llms-full.txt" in url:
|
| 84 |
+
url_full = url
|
| 85 |
+
else:
|
| 86 |
+
url = a_elems[1].get("href")
|
| 87 |
+
|
| 88 |
+
return Page(
|
| 89 |
+
name=name,
|
| 90 |
+
url=url,
|
| 91 |
+
url_full=url_full
|
| 92 |
+
)
|
| 93 |
+
|
| 94 |
+
|
| 95 |
+
async def download_url(session: aiohttp.ClientSession, page: Page, url: str) -> Page:
|
| 96 |
+
try:
|
| 97 |
+
async with session.get(url) as response:
|
| 98 |
+
if response.status == 200:
|
| 99 |
+
txt = await response.text()
|
| 100 |
+
try:
|
| 101 |
+
parsed = parse_llms_txt(txt)
|
| 102 |
+
if "llms.txt" in url:
|
| 103 |
+
page.add_text(txt, parsed, is_full=False, url=url)
|
| 104 |
+
elif "llms-full.txt" in url:
|
| 105 |
+
page.add_text(txt, None, is_full=True, url=url)
|
| 106 |
+
else:
|
| 107 |
+
print(f"Unexpected url downloaded from the directory: {url}")
|
| 108 |
+
return page
|
| 109 |
+
|
| 110 |
+
except Exception as e:
|
| 111 |
+
# No need to do anything, the fields will remain None
|
| 112 |
+
print(f"Error parsing '{url}': {e}")
|
| 113 |
+
|
| 114 |
+
except Exception as e:
|
| 115 |
+
print(f"Error downloading url '{url}': {e}")
|
| 116 |
+
|
| 117 |
+
return page
|
| 118 |
+
|
| 119 |
+
|
| 120 |
+
async def process_page(session: aiohttp.ClientSession, page: Page) -> list[Page]:
|
| 121 |
+
if url := page.url:
|
| 122 |
+
page = await download_url(session, page, url)
|
| 123 |
+
if url := page.url_full:
|
| 124 |
+
page = await download_url(session, page, url)
|
| 125 |
+
|
| 126 |
+
return page
|
| 127 |
+
|
| 128 |
+
|
| 129 |
+
async def download_pages(pages: list[Page]) -> list[Page]:
|
| 130 |
+
async with aiohttp.ClientSession() as session:
|
| 131 |
+
tasks = [process_page(session, page) for page in pages]
|
| 132 |
+
return await tqdm_asyncio.gather(*tasks, total=len(pages))
|
| 133 |
+
|
| 134 |
+
|
| 135 |
+
async def main():
|
| 136 |
+
print("Downloading directory...")
|
| 137 |
+
pages = await download_directory_llmstxt()
|
| 138 |
+
|
| 139 |
+
print("Downloading pages...")
|
| 140 |
+
pages = await download_pages(pages)
|
| 141 |
+
|
| 142 |
+
print("Preparing dataset...")
|
| 143 |
+
ds = Dataset.from_list([page.record() for page in pages])
|
| 144 |
+
|
| 145 |
+
ds.push_to_hub("plaguss/llms-txt", commit_message="Initial commit")
|
| 146 |
+
|
| 147 |
+
|
| 148 |
+
if __name__ == "__main__":
|
| 149 |
+
asyncio.run(main())
|