Spaces:
Runtime error
Runtime error
Huggingface support (#28)
Browse files* huggingface support
* PR
- buster/docparser.py +30 -81
- buster/parser.py +152 -0
buster/docparser.py
CHANGED
|
@@ -1,41 +1,47 @@
|
|
| 1 |
import glob
|
| 2 |
-
import math
|
| 3 |
import os
|
| 4 |
|
| 5 |
-
import bs4
|
| 6 |
import numpy as np
|
| 7 |
import pandas as pd
|
| 8 |
import tiktoken
|
| 9 |
from bs4 import BeautifulSoup
|
| 10 |
from openai.embeddings_utils import get_embedding
|
| 11 |
|
|
|
|
|
|
|
| 12 |
EMBEDDING_MODEL = "text-embedding-ada-002"
|
| 13 |
EMBEDDING_ENCODING = "cl100k_base" # this the encoding for text-embedding-ada-002
|
| 14 |
|
| 15 |
|
| 16 |
-
BASE_URL_MILA = "https://docs.mila.quebec/"
|
| 17 |
-
BASE_URL_ORION = "https://orion.readthedocs.io/en/stable/"
|
| 18 |
-
BASE_URL_PYTORCH = "https://pytorch.org/docs/stable/"
|
| 19 |
-
|
| 20 |
-
|
| 21 |
PICKLE_EXTENSIONS = [".gz", ".bz2", ".zip", ".xz", ".zst", ".tar", ".tar.gz", ".tar.xz", ".tar.bz2"]
|
| 22 |
|
| 23 |
|
| 24 |
-
|
| 25 |
-
|
| 26 |
-
|
| 27 |
-
|
| 28 |
-
|
| 29 |
-
|
| 30 |
-
|
| 31 |
-
|
| 32 |
-
|
| 33 |
-
|
| 34 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 35 |
|
| 36 |
|
| 37 |
def get_all_documents(
|
| 38 |
-
root_dir: str, base_url: str, min_section_length: int = 100, max_section_length: int = 2000
|
| 39 |
) -> pd.DataFrame:
|
| 40 |
"""Parse all HTML files in `root_dir`, and extract all sections.
|
| 41 |
|
|
@@ -44,48 +50,6 @@ def get_all_documents(
|
|
| 44 |
"""
|
| 45 |
files = glob.glob("**/*.html", root_dir=root_dir, recursive=True)
|
| 46 |
|
| 47 |
-
def get_all_subsections(soup: BeautifulSoup) -> tuple[list[str], list[str], list[str]]:
|
| 48 |
-
found = soup.find_all("a", href=True, class_="headerlink")
|
| 49 |
-
|
| 50 |
-
sections = []
|
| 51 |
-
urls = []
|
| 52 |
-
names = []
|
| 53 |
-
for section_found in found:
|
| 54 |
-
section_soup = section_found.parent.parent
|
| 55 |
-
section_href = section_soup.find_all("a", href=True, class_="headerlink")
|
| 56 |
-
|
| 57 |
-
# If sections has subsections, keep only the part before the first subsection
|
| 58 |
-
if len(section_href) > 1 and section_soup.section is not None:
|
| 59 |
-
section_siblings = list(section_soup.section.previous_siblings)[::-1]
|
| 60 |
-
section = parse_section(section_siblings)
|
| 61 |
-
else:
|
| 62 |
-
section = parse_section(section_soup.children)
|
| 63 |
-
|
| 64 |
-
# Remove special characters, plus newlines in some url and section names.
|
| 65 |
-
section = section.strip()
|
| 66 |
-
url = section_found["href"].strip().replace("\n", "")
|
| 67 |
-
name = section_found.parent.text.strip()[:-1].replace("\n", "")
|
| 68 |
-
|
| 69 |
-
# If text is too long, split into chunks of equal sizes
|
| 70 |
-
if len(section) > max_section_length:
|
| 71 |
-
n_chunks = math.ceil(len(section) / float(max_section_length))
|
| 72 |
-
separator_index = math.floor(len(section) / n_chunks)
|
| 73 |
-
|
| 74 |
-
section_chunks = [section[separator_index * i : separator_index * (i + 1)] for i in range(n_chunks)]
|
| 75 |
-
url_chunks = [url] * n_chunks
|
| 76 |
-
name_chunks = [name] * n_chunks
|
| 77 |
-
|
| 78 |
-
sections.extend(section_chunks)
|
| 79 |
-
urls.extend(url_chunks)
|
| 80 |
-
names.extend(name_chunks)
|
| 81 |
-
# If text is not too short, add in 1 chunk
|
| 82 |
-
elif len(section) > min_section_length:
|
| 83 |
-
sections.append(section)
|
| 84 |
-
urls.append(url)
|
| 85 |
-
names.append(name)
|
| 86 |
-
|
| 87 |
-
return sections, urls, names
|
| 88 |
-
|
| 89 |
sections = []
|
| 90 |
urls = []
|
| 91 |
names = []
|
|
@@ -95,12 +59,11 @@ def get_all_documents(
|
|
| 95 |
source = f.read()
|
| 96 |
|
| 97 |
soup = BeautifulSoup(source, "html.parser")
|
| 98 |
-
|
| 99 |
-
|
| 100 |
|
| 101 |
-
|
| 102 |
urls.extend(urls_file)
|
| 103 |
-
|
| 104 |
names.extend(names_file)
|
| 105 |
|
| 106 |
documents_df = pd.DataFrame.from_dict({"name": names, "url": urls, "text": sections})
|
|
@@ -138,7 +101,8 @@ def read_documents(filepath: str) -> pd.DataFrame:
|
|
| 138 |
|
| 139 |
def compute_n_tokens(df: pd.DataFrame) -> pd.DataFrame:
|
| 140 |
encoding = tiktoken.get_encoding(EMBEDDING_ENCODING)
|
| 141 |
-
|
|
|
|
| 142 |
return df
|
| 143 |
|
| 144 |
|
|
@@ -154,18 +118,3 @@ def generate_embeddings(filepath: str, output_file: str) -> pd.DataFrame:
|
|
| 154 |
df = precompute_embeddings(df)
|
| 155 |
write_documents(output_file, df)
|
| 156 |
return df
|
| 157 |
-
|
| 158 |
-
|
| 159 |
-
if __name__ == "__main__":
|
| 160 |
-
root_dir = "/home/hadrien/perso/mila-docs/output/"
|
| 161 |
-
save_filepath = "data/documents.tar.gz"
|
| 162 |
-
|
| 163 |
-
# How to write
|
| 164 |
-
documents_df = get_all_documents(root_dir)
|
| 165 |
-
write_documents(save_filepath, documents_df)
|
| 166 |
-
|
| 167 |
-
# How to load
|
| 168 |
-
documents_df = read_documents(save_filepath)
|
| 169 |
-
|
| 170 |
-
# precompute the document embeddings
|
| 171 |
-
df = generate_embeddings(filepath=save_filepath, output_file="data/document_embeddings.tar.gz")
|
|
|
|
| 1 |
import glob
|
|
|
|
| 2 |
import os
|
| 3 |
|
|
|
|
| 4 |
import numpy as np
|
| 5 |
import pandas as pd
|
| 6 |
import tiktoken
|
| 7 |
from bs4 import BeautifulSoup
|
| 8 |
from openai.embeddings_utils import get_embedding
|
| 9 |
|
| 10 |
+
from buster.parser import HuggingfaceParser, Parser, SphinxParser
|
| 11 |
+
|
| 12 |
EMBEDDING_MODEL = "text-embedding-ada-002"
|
| 13 |
EMBEDDING_ENCODING = "cl100k_base" # this the encoding for text-embedding-ada-002
|
| 14 |
|
| 15 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 16 |
PICKLE_EXTENSIONS = [".gz", ".bz2", ".zip", ".xz", ".zst", ".tar", ".tar.gz", ".tar.xz", ".tar.bz2"]
|
| 17 |
|
| 18 |
|
| 19 |
+
supported_docs = {
|
| 20 |
+
"mila": {
|
| 21 |
+
"base_url": "https://docs.mila.quebec/",
|
| 22 |
+
"filename": "documents_mila.tar.gz",
|
| 23 |
+
"parser": SphinxParser,
|
| 24 |
+
},
|
| 25 |
+
"orion": {
|
| 26 |
+
"base_url": "https://orion.readthedocs.io/en/stable/",
|
| 27 |
+
"filename": "documents_orion.tar.gz",
|
| 28 |
+
"parser": SphinxParser,
|
| 29 |
+
},
|
| 30 |
+
"pytorch": {
|
| 31 |
+
"base_url": "https://pytorch.org/docs/stable/",
|
| 32 |
+
"filename": "documents_pytorch.tar.gz",
|
| 33 |
+
"parser": SphinxParser,
|
| 34 |
+
},
|
| 35 |
+
"huggingface": {
|
| 36 |
+
"base_url": "https://huggingface.co/docs/transformers/",
|
| 37 |
+
"filename": "documents_huggingface.tar.gz",
|
| 38 |
+
"parser": HuggingfaceParser,
|
| 39 |
+
},
|
| 40 |
+
}
|
| 41 |
|
| 42 |
|
| 43 |
def get_all_documents(
|
| 44 |
+
root_dir: str, base_url: str, parser: Parser, min_section_length: int = 100, max_section_length: int = 2000
|
| 45 |
) -> pd.DataFrame:
|
| 46 |
"""Parse all HTML files in `root_dir`, and extract all sections.
|
| 47 |
|
|
|
|
| 50 |
"""
|
| 51 |
files = glob.glob("**/*.html", root_dir=root_dir, recursive=True)
|
| 52 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 53 |
sections = []
|
| 54 |
urls = []
|
| 55 |
names = []
|
|
|
|
| 59 |
source = f.read()
|
| 60 |
|
| 61 |
soup = BeautifulSoup(source, "html.parser")
|
| 62 |
+
soup_parser = parser(soup, base_url, file, min_section_length, max_section_length)
|
| 63 |
+
sections_file, urls_file, names_file = soup_parser.parse()
|
| 64 |
|
| 65 |
+
sections.extend(sections_file)
|
| 66 |
urls.extend(urls_file)
|
|
|
|
| 67 |
names.extend(names_file)
|
| 68 |
|
| 69 |
documents_df = pd.DataFrame.from_dict({"name": names, "url": urls, "text": sections})
|
|
|
|
| 101 |
|
| 102 |
def compute_n_tokens(df: pd.DataFrame) -> pd.DataFrame:
|
| 103 |
encoding = tiktoken.get_encoding(EMBEDDING_ENCODING)
|
| 104 |
+
# TODO are there unexpected consequences of allowing endoftext?
|
| 105 |
+
df["n_tokens"] = df.text.apply(lambda x: len(encoding.encode(x, allowed_special={"<|endoftext|>"})))
|
| 106 |
return df
|
| 107 |
|
| 108 |
|
|
|
|
| 118 |
df = precompute_embeddings(df)
|
| 119 |
write_documents(output_file, df)
|
| 120 |
return df
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
buster/parser.py
ADDED
|
@@ -0,0 +1,152 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import math
|
| 2 |
+
import os
|
| 3 |
+
|
| 4 |
+
import bs4
|
| 5 |
+
import pandas as pd
|
| 6 |
+
from bs4 import BeautifulSoup
|
| 7 |
+
|
| 8 |
+
|
| 9 |
+
def parse_section(nodes: list[bs4.element.NavigableString]) -> str:
|
| 10 |
+
section = []
|
| 11 |
+
for node in nodes:
|
| 12 |
+
if node.name == "table":
|
| 13 |
+
node_text = pd.read_html(node.prettify())[0].to_markdown(index=False, tablefmt="github")
|
| 14 |
+
elif node.name == "script":
|
| 15 |
+
continue
|
| 16 |
+
else:
|
| 17 |
+
node_text = node.text
|
| 18 |
+
section.append(node_text)
|
| 19 |
+
section = "".join(section)
|
| 20 |
+
|
| 21 |
+
return section
|
| 22 |
+
|
| 23 |
+
|
| 24 |
+
class Parser:
|
| 25 |
+
def __init__(
|
| 26 |
+
self,
|
| 27 |
+
soup: BeautifulSoup,
|
| 28 |
+
base_url: str,
|
| 29 |
+
filename: str,
|
| 30 |
+
min_section_length: int = 100,
|
| 31 |
+
max_section_length: int = 2000,
|
| 32 |
+
):
|
| 33 |
+
self.soup = soup
|
| 34 |
+
self.base_url = base_url
|
| 35 |
+
self.filename = filename
|
| 36 |
+
self.min_section_length = min_section_length
|
| 37 |
+
self.max_section_length = max_section_length
|
| 38 |
+
|
| 39 |
+
def parse(self) -> tuple[list[str], list[str], list[str]]:
|
| 40 |
+
...
|
| 41 |
+
|
| 42 |
+
def find_sections(self) -> bs4.element.ResultSet:
|
| 43 |
+
...
|
| 44 |
+
|
| 45 |
+
def build_url(self, suffix: str) -> str:
|
| 46 |
+
...
|
| 47 |
+
|
| 48 |
+
|
| 49 |
+
class SphinxParser(Parser):
|
| 50 |
+
def parse(self) -> tuple[list[str], list[str], list[str]]:
|
| 51 |
+
found = self.find_sections()
|
| 52 |
+
|
| 53 |
+
sections = []
|
| 54 |
+
urls = []
|
| 55 |
+
names = []
|
| 56 |
+
for i in range(len(found)):
|
| 57 |
+
section_found = found[i]
|
| 58 |
+
|
| 59 |
+
section_soup = section_found.parent.parent
|
| 60 |
+
section_href = section_soup.find_all("a", href=True, class_="headerlink")
|
| 61 |
+
|
| 62 |
+
# If sections has subsections, keep only the part before the first subsection
|
| 63 |
+
if len(section_href) > 1 and section_soup.section is not None:
|
| 64 |
+
section_siblings = list(section_soup.section.previous_siblings)[::-1]
|
| 65 |
+
section = parse_section(section_siblings)
|
| 66 |
+
else:
|
| 67 |
+
section = parse_section(section_soup.children)
|
| 68 |
+
|
| 69 |
+
# Remove special characters, plus newlines in some url and section names.
|
| 70 |
+
section = section.strip()
|
| 71 |
+
url = section_found["href"].strip().replace("\n", "")
|
| 72 |
+
name = section_found.parent.text.strip()[:-1].replace("\n", "")
|
| 73 |
+
|
| 74 |
+
url = self.build_url(url)
|
| 75 |
+
|
| 76 |
+
# If text is too long, split into chunks of equal sizes
|
| 77 |
+
if len(section) > self.max_section_length:
|
| 78 |
+
n_chunks = math.ceil(len(section) / float(self.max_section_length))
|
| 79 |
+
separator_index = math.floor(len(section) / n_chunks)
|
| 80 |
+
|
| 81 |
+
section_chunks = [section[separator_index * i : separator_index * (i + 1)] for i in range(n_chunks)]
|
| 82 |
+
url_chunks = [url] * n_chunks
|
| 83 |
+
name_chunks = [name] * n_chunks
|
| 84 |
+
|
| 85 |
+
sections.extend(section_chunks)
|
| 86 |
+
urls.extend(url_chunks)
|
| 87 |
+
names.extend(name_chunks)
|
| 88 |
+
# If text is not too short, add in 1 chunk
|
| 89 |
+
elif len(section) > self.min_section_length:
|
| 90 |
+
sections.append(section)
|
| 91 |
+
urls.append(url)
|
| 92 |
+
names.append(name)
|
| 93 |
+
|
| 94 |
+
return sections, urls, names
|
| 95 |
+
|
| 96 |
+
def find_sections(self) -> bs4.element.ResultSet:
|
| 97 |
+
return self.soup.find_all("a", href=True, class_="headerlink")
|
| 98 |
+
|
| 99 |
+
def build_url(self, suffix: str) -> str:
|
| 100 |
+
return self.base_url + self.filename + suffix
|
| 101 |
+
|
| 102 |
+
|
| 103 |
+
class HuggingfaceParser(Parser):
|
| 104 |
+
def parse(self) -> tuple[list[str], list[str], list[str]]:
|
| 105 |
+
found = self.find_sections()
|
| 106 |
+
|
| 107 |
+
sections = []
|
| 108 |
+
urls = []
|
| 109 |
+
names = []
|
| 110 |
+
for i in range(len(found)):
|
| 111 |
+
section_href = found[i].find("a", href=True, class_="header-link")
|
| 112 |
+
|
| 113 |
+
section_nodes = []
|
| 114 |
+
for element in found[i].find_next_siblings():
|
| 115 |
+
if i + 1 < len(found) and element == found[i + 1]:
|
| 116 |
+
break
|
| 117 |
+
section_nodes.append(element)
|
| 118 |
+
section = parse_section(section_nodes)
|
| 119 |
+
|
| 120 |
+
# Remove special characters, plus newlines in some url and section names.
|
| 121 |
+
section = section.strip()
|
| 122 |
+
url = section_href["href"].strip().replace("\n", "")
|
| 123 |
+
name = found[i].text.strip().replace("\n", "")
|
| 124 |
+
|
| 125 |
+
url = self.build_url(url)
|
| 126 |
+
|
| 127 |
+
# If text is too long, split into chunks of equal sizes
|
| 128 |
+
if len(section) > self.max_section_length:
|
| 129 |
+
n_chunks = math.ceil(len(section) / float(self.max_section_length))
|
| 130 |
+
separator_index = math.floor(len(section) / n_chunks)
|
| 131 |
+
|
| 132 |
+
section_chunks = [section[separator_index * i : separator_index * (i + 1)] for i in range(n_chunks)]
|
| 133 |
+
url_chunks = [url] * n_chunks
|
| 134 |
+
name_chunks = [name] * n_chunks
|
| 135 |
+
|
| 136 |
+
sections.extend(section_chunks)
|
| 137 |
+
urls.extend(url_chunks)
|
| 138 |
+
names.extend(name_chunks)
|
| 139 |
+
# If text is not too short, add in 1 chunk
|
| 140 |
+
elif len(section) > self.min_section_length:
|
| 141 |
+
sections.append(section)
|
| 142 |
+
urls.append(url)
|
| 143 |
+
names.append(name)
|
| 144 |
+
|
| 145 |
+
return sections, urls, names
|
| 146 |
+
|
| 147 |
+
def find_sections(self) -> bs4.element.ResultSet:
|
| 148 |
+
return self.soup.find_all(["h1", "h2", "h3"], class_="relative group")
|
| 149 |
+
|
| 150 |
+
def build_url(self, suffix: str) -> str:
|
| 151 |
+
# The splitext is to remove the .html extension
|
| 152 |
+
return self.base_url + os.path.splitext(self.filename)[0] + suffix
|