Spaces:
Runtime error
Runtime error
Merge pull request #50 from marondeau/parsing
Browse files- buster/docparser.py +12 -7
- buster/parser.py +94 -122
buster/docparser.py
CHANGED
@@ -1,5 +1,6 @@
|
|
1 |
import glob
|
2 |
import os
|
|
|
3 |
|
4 |
import numpy as np
|
5 |
import pandas as pd
|
@@ -42,7 +43,11 @@ supported_docs = {
|
|
42 |
|
43 |
|
44 |
def get_all_documents(
|
45 |
-
root_dir: str,
|
|
|
|
|
|
|
|
|
46 |
) -> pd.DataFrame:
|
47 |
"""Parse all HTML files in `root_dir`, and extract all sections.
|
48 |
|
@@ -60,12 +65,12 @@ def get_all_documents(
|
|
60 |
source = f.read()
|
61 |
|
62 |
soup = BeautifulSoup(source, "html.parser")
|
63 |
-
|
64 |
-
sections_file, urls_file, names_file =
|
65 |
-
|
66 |
-
|
67 |
-
|
68 |
-
|
69 |
|
70 |
documents_df = pd.DataFrame.from_dict({"title": names, "url": urls, "content": sections})
|
71 |
|
|
|
1 |
import glob
|
2 |
import os
|
3 |
+
from typing import Type
|
4 |
|
5 |
import numpy as np
|
6 |
import pandas as pd
|
|
|
43 |
|
44 |
|
45 |
def get_all_documents(
|
46 |
+
root_dir: str,
|
47 |
+
base_url: str,
|
48 |
+
parser_cls: Type[Parser],
|
49 |
+
min_section_length: int = 100,
|
50 |
+
max_section_length: int = 2000,
|
51 |
) -> pd.DataFrame:
|
52 |
"""Parse all HTML files in `root_dir`, and extract all sections.
|
53 |
|
|
|
65 |
source = f.read()
|
66 |
|
67 |
soup = BeautifulSoup(source, "html.parser")
|
68 |
+
parser = parser_cls(soup, base_url, file, min_section_length, max_section_length)
|
69 |
+
# sections_file, urls_file, names_file =
|
70 |
+
for section in parser.parse():
|
71 |
+
sections.append(section.text)
|
72 |
+
urls.append(section.url)
|
73 |
+
names.append(section.name)
|
74 |
|
75 |
documents_df = pd.DataFrame.from_dict({"title": names, "url": urls, "content": sections})
|
76 |
|
buster/parser.py
CHANGED
@@ -1,151 +1,123 @@
|
|
1 |
import math
|
2 |
import os
|
|
|
|
|
|
|
|
|
3 |
|
4 |
import bs4
|
5 |
import pandas as pd
|
6 |
from bs4 import BeautifulSoup
|
7 |
|
8 |
|
9 |
-
|
10 |
-
|
11 |
-
|
12 |
-
|
13 |
-
|
14 |
-
|
15 |
-
|
16 |
-
|
17 |
-
|
18 |
-
|
19 |
-
|
20 |
-
|
21 |
-
|
22 |
-
|
23 |
-
|
24 |
-
|
25 |
-
|
26 |
-
self
|
27 |
-
|
28 |
-
|
29 |
-
|
30 |
-
|
31 |
-
|
32 |
-
):
|
33 |
-
|
34 |
-
|
35 |
-
|
36 |
-
|
37 |
-
|
38 |
-
|
39 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
40 |
...
|
41 |
|
42 |
-
|
|
|
43 |
...
|
44 |
|
45 |
-
def
|
46 |
-
|
|
|
|
|
|
|
|
|
47 |
|
48 |
|
49 |
class SphinxParser(Parser):
|
50 |
-
def
|
51 |
-
|
52 |
-
|
53 |
-
|
54 |
-
urls = []
|
55 |
-
names = []
|
56 |
-
for i in range(len(found)):
|
57 |
-
section_found = found[i]
|
58 |
|
59 |
-
|
60 |
-
|
61 |
|
62 |
# If sections has subsections, keep only the part before the first subsection
|
63 |
-
if len(section_href) > 1 and
|
64 |
-
|
65 |
-
section =
|
66 |
else:
|
67 |
-
section =
|
68 |
-
|
69 |
-
|
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
|
105 |
-
|
|
|
|
|
|
|
106 |
|
107 |
-
|
108 |
-
|
109 |
-
|
110 |
-
|
111 |
-
|
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
|
|
|
1 |
import math
|
2 |
import os
|
3 |
+
from abc import ABC, abstractmethod
|
4 |
+
from dataclasses import InitVar, dataclass, field
|
5 |
+
from itertools import takewhile, zip_longest
|
6 |
+
from typing import Iterator
|
7 |
|
8 |
import bs4
|
9 |
import pandas as pd
|
10 |
from bs4 import BeautifulSoup
|
11 |
|
12 |
|
13 |
+
@dataclass
|
14 |
+
class Section:
|
15 |
+
url: str
|
16 |
+
name: str
|
17 |
+
nodes: InitVar[list[bs4.element.NavigableString]]
|
18 |
+
text: str = field(init=False)
|
19 |
+
|
20 |
+
def __post_init__(self, nodes: list[bs4.element.NavigableString]):
|
21 |
+
section = []
|
22 |
+
for node in nodes:
|
23 |
+
if node.name == "table":
|
24 |
+
node_text = pd.read_html(node.prettify())[0].to_markdown(index=False, tablefmt="github")
|
25 |
+
elif node.name == "script":
|
26 |
+
continue
|
27 |
+
else:
|
28 |
+
node_text = node.text
|
29 |
+
section.append(node_text)
|
30 |
+
self.text = "".join(section).strip()
|
31 |
+
|
32 |
+
def __len__(self) -> int:
|
33 |
+
return len(self.text)
|
34 |
+
|
35 |
+
@classmethod
|
36 |
+
def from_text(cls, text: str, url: str, name: str) -> "Section":
|
37 |
+
"""Alternate constructor, without parsing."""
|
38 |
+
section = cls.__new__(cls) # Allocate memory, does not call __init__
|
39 |
+
# Does the init here.
|
40 |
+
section.text = text
|
41 |
+
section.url = url
|
42 |
+
section.name = name
|
43 |
+
|
44 |
+
return section
|
45 |
+
|
46 |
+
def get_chunks(self, min_length: int, max_length: int) -> Iterator["Section"]:
|
47 |
+
"""Split a section into chunks."""
|
48 |
+
if len(self) > max_length:
|
49 |
+
# Get the number of chunk, by dividing and rounding up.
|
50 |
+
# Then, split the section into equal lenght chunks.
|
51 |
+
# This could results in chunks below the minimum length,
|
52 |
+
# and will truncate the end of the section.
|
53 |
+
n_chunks = (len(self) + max_length - 1) // max_length
|
54 |
+
length = len(self) // n_chunks
|
55 |
+
for chunk in range(n_chunks):
|
56 |
+
start = chunk * length
|
57 |
+
yield Section.from_text(self.text[start : start + length], self.url, self.name)
|
58 |
+
elif len(self) > min_length:
|
59 |
+
yield self
|
60 |
+
return
|
61 |
+
|
62 |
+
|
63 |
+
@dataclass
|
64 |
+
class Parser(ABC):
|
65 |
+
soup: BeautifulSoup
|
66 |
+
base_url: str
|
67 |
+
filename: str
|
68 |
+
min_section_length: int = 100
|
69 |
+
max_section_length: int = 2000
|
70 |
+
|
71 |
+
@abstractmethod
|
72 |
+
def build_url(self, suffix: str) -> str:
|
73 |
...
|
74 |
|
75 |
+
@abstractmethod
|
76 |
+
def find_sections(self) -> Iterator[Section]:
|
77 |
...
|
78 |
|
79 |
+
def parse(self) -> list[Section]:
|
80 |
+
"""Parse the documents into sections, respecting the lenght constraints."""
|
81 |
+
sections = []
|
82 |
+
for section in self.find_sections():
|
83 |
+
sections.extend(section.get_chunks(self.min_section_length, self.max_section_length))
|
84 |
+
return sections
|
85 |
|
86 |
|
87 |
class SphinxParser(Parser):
|
88 |
+
def find_sections(self) -> Iterator[Section]:
|
89 |
+
for section in self.soup.find_all("a", href=True, class_="headerlink"):
|
90 |
+
container = section.parent.parent
|
91 |
+
section_href = container.find_all("a", href=True, class_="headerlink")
|
|
|
|
|
|
|
|
|
92 |
|
93 |
+
url = self.build_url(section["href"].strip().replace("\n", ""))
|
94 |
+
name = section.parent.text
|
95 |
|
96 |
# If sections has subsections, keep only the part before the first subsection
|
97 |
+
if len(section_href) > 1 and container.section is not None:
|
98 |
+
siblings = list(container.section.previous_siblings)[::-1]
|
99 |
+
section = Section(url, name, siblings)
|
100 |
else:
|
101 |
+
section = Section(url, name, container.children)
|
102 |
+
yield section
|
103 |
+
return
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
104 |
|
105 |
def build_url(self, suffix: str) -> str:
|
106 |
return self.base_url + self.filename + suffix
|
107 |
|
108 |
|
109 |
class HuggingfaceParser(Parser):
|
110 |
+
def find_sections(self) -> Iterator[Section]:
|
111 |
+
sections = self.soup.find_all(["h1", "h2", "h3"], class_="relative group")
|
112 |
+
for section, next_section in zip_longest(sections, sections[1:]):
|
113 |
+
href = section.find("a", href=True, class_="header-link")
|
114 |
+
nodes = list(takewhile(lambda sibling: sibling != next_section, section.find_next_siblings()))
|
115 |
|
116 |
+
url = self.build_url(href["href"].strip().replace("\n", ""))
|
117 |
+
name = section.text.strip().replace("\n", "")
|
118 |
+
yield Section(url, name, nodes)
|
119 |
+
|
120 |
+
return
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
121 |
|
122 |
def build_url(self, suffix: str) -> str:
|
123 |
# The splitext is to remove the .html extension
|