File size: 5,402 Bytes
f5ec40e
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
import math
import os

import bs4
import pandas as pd
from bs4 import BeautifulSoup


def parse_section(nodes: list[bs4.element.NavigableString]) -> str:
    section = []
    for node in nodes:
        if node.name == "table":
            node_text = pd.read_html(node.prettify())[0].to_markdown(index=False, tablefmt="github")
        elif node.name == "script":
            continue
        else:
            node_text = node.text
        section.append(node_text)
    section = "".join(section)

    return section


class Parser:
    def __init__(
        self,
        soup: BeautifulSoup,
        base_url: str,
        filename: str,
        min_section_length: int = 100,
        max_section_length: int = 2000,
    ):
        self.soup = soup
        self.base_url = base_url
        self.filename = filename
        self.min_section_length = min_section_length
        self.max_section_length = max_section_length

    def parse(self) -> tuple[list[str], list[str], list[str]]:
        ...

    def find_sections(self) -> bs4.element.ResultSet:
        ...

    def build_url(self, suffix: str) -> str:
        ...


class SphinxParser(Parser):
    def parse(self) -> tuple[list[str], list[str], list[str]]:
        found = self.find_sections()

        sections = []
        urls = []
        names = []
        for i in range(len(found)):
            section_found = found[i]

            section_soup = section_found.parent.parent
            section_href = section_soup.find_all("a", href=True, class_="headerlink")

            # If sections has subsections, keep only the part before the first subsection
            if len(section_href) > 1 and section_soup.section is not None:
                section_siblings = list(section_soup.section.previous_siblings)[::-1]
                section = parse_section(section_siblings)
            else:
                section = parse_section(section_soup.children)

            # Remove special characters, plus newlines in some url and section names.
            section = section.strip()
            url = section_found["href"].strip().replace("\n", "")
            name = section_found.parent.text.strip()[:-1].replace("\n", "")

            url = self.build_url(url)

            # If text is too long, split into chunks of equal sizes
            if len(section) > self.max_section_length:
                n_chunks = math.ceil(len(section) / float(self.max_section_length))
                separator_index = math.floor(len(section) / n_chunks)

                section_chunks = [section[separator_index * i : separator_index * (i + 1)] for i in range(n_chunks)]
                url_chunks = [url] * n_chunks
                name_chunks = [name] * n_chunks

                sections.extend(section_chunks)
                urls.extend(url_chunks)
                names.extend(name_chunks)
            # If text is not too short, add in 1 chunk
            elif len(section) > self.min_section_length:
                sections.append(section)
                urls.append(url)
                names.append(name)

        return sections, urls, names

    def find_sections(self) -> bs4.element.ResultSet:
        return self.soup.find_all("a", href=True, class_="headerlink")

    def build_url(self, suffix: str) -> str:
        return self.base_url + self.filename + suffix


class HuggingfaceParser(Parser):
    def parse(self) -> tuple[list[str], list[str], list[str]]:
        found = self.find_sections()

        sections = []
        urls = []
        names = []
        for i in range(len(found)):
            section_href = found[i].find("a", href=True, class_="header-link")

            section_nodes = []
            for element in found[i].find_next_siblings():
                if i + 1 < len(found) and element == found[i + 1]:
                    break
                section_nodes.append(element)
            section = parse_section(section_nodes)

            # Remove special characters, plus newlines in some url and section names.
            section = section.strip()
            url = section_href["href"].strip().replace("\n", "")
            name = found[i].text.strip().replace("\n", "")

            url = self.build_url(url)

            # If text is too long, split into chunks of equal sizes
            if len(section) > self.max_section_length:
                n_chunks = math.ceil(len(section) / float(self.max_section_length))
                separator_index = math.floor(len(section) / n_chunks)

                section_chunks = [section[separator_index * i : separator_index * (i + 1)] for i in range(n_chunks)]
                url_chunks = [url] * n_chunks
                name_chunks = [name] * n_chunks

                sections.extend(section_chunks)
                urls.extend(url_chunks)
                names.extend(name_chunks)
            # If text is not too short, add in 1 chunk
            elif len(section) > self.min_section_length:
                sections.append(section)
                urls.append(url)
                names.append(name)

        return sections, urls, names

    def find_sections(self) -> bs4.element.ResultSet:
        return self.soup.find_all(["h1", "h2", "h3"], class_="relative group")

    def build_url(self, suffix: str) -> str:
        # The splitext is to remove the .html extension
        return self.base_url + os.path.splitext(self.filename)[0] + suffix