File size: 8,289 Bytes
e94100d
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
#!/usr/bin/python3
# -*- coding: utf-8 -*-
import argparse
import os
from pathlib import Path
import re
import shutil
import tempfile
import uuid

from markdownify import markdownify as md
from selenium import webdriver
from selenium.webdriver.chrome.service import Service
from webdriver_manager.chrome import ChromeDriverManager, DriverCacheManager
from bs4 import BeautifulSoup

from project_settings import project_path
from toolbox.to_markdown.base_to_markdown import BaseToMarkdown


def get_args():
    parser = argparse.ArgumentParser()
    parser.add_argument(
        "--filename",
        # default=(project_path / "data/files/html/nxlink.html").as_posix(),
        default=(project_path / "data/files/html/nxcloud.html").as_posix(),
        type=str
    )
    args = parser.parse_args()
    return args


class HtmlPreprocess(object):
    @staticmethod
    def remove_comment(html_doc: str):
        pattern = "<!--.*?-->"
        html_doc = re.sub(pattern, "", html_doc, flags=re.DOTALL)
        return html_doc

    @staticmethod
    def remove_img(html_doc: str):
        pattern = "<img.*?>"
        html_doc = re.sub(pattern, "", html_doc, flags=re.DOTALL)
        return html_doc

    @staticmethod
    def remove_multiple_newlines(html_doc: str):
        html_doc = re.sub(r"(\n\s*\n)+", "\n", html_doc, flags=re.DOTALL)
        return html_doc

    @staticmethod
    def remove_no_script(html_doc: str):
        pattern = "<noscript>.*?</noscript>"
        html_doc = re.sub(pattern, "", html_doc, flags=re.DOTALL)
        return html_doc

    @staticmethod
    def remove_script(html_doc: str):
        pattern = "<script.*?</script>"
        html_doc = re.sub(pattern, "", html_doc, flags=re.DOTALL)
        return html_doc

    @staticmethod
    def remove_style(html_doc: str):
        remove_script_pattern = "<style.*?</style>"
        html_doc = re.sub(remove_script_pattern, "", html_doc, flags=re.DOTALL)
        return html_doc

    @staticmethod
    def remove_class_property(html_doc: str):
        pattern = " class=\".+?\""
        html_doc = re.sub(pattern, "", html_doc, flags=re.DOTALL)
        return html_doc

    @staticmethod
    def remove_id_property(html_doc: str):
        pattern = " id=\".+?\""
        html_doc = re.sub(pattern, "", html_doc, flags=re.DOTALL)
        return html_doc

    @staticmethod
    def remove_onclick_property(html_doc: str):
        pattern = " onclick=\".+?\""
        html_doc = re.sub(pattern, "", html_doc, flags=re.DOTALL)
        return html_doc

    @staticmethod
    def remove_style_property(html_doc: str):
        pattern = " style=\".+?\""
        html_doc = re.sub(pattern, "", html_doc, flags=re.DOTALL)
        pattern = " style='.+?'"
        html_doc = re.sub(pattern, "", html_doc, flags=re.DOTALL)
        return html_doc

    @staticmethod
    def replace_a(html_doc: str):
        pattern = r"<a\b[^>]*>(.*?)</a>"
        html_doc = re.sub(pattern, r"\1", html_doc, flags=re.DOTALL)
        return html_doc

    @staticmethod
    def replace_br(html_doc: str):
        pattern = r"(<br>|<br/>|<br />)"
        html_doc = re.sub(pattern, "\n", html_doc, flags=re.DOTALL)
        return html_doc

    @staticmethod
    def replace_div(html_doc: str):
        pattern = r"<div\b[^>]*>(.*?)</div>"
        html_doc = re.sub(pattern, r"\1", html_doc, flags=re.DOTALL)
        return html_doc


@BaseToMarkdown.register("html_markdownify")
class HtmlToMarkdown(BaseToMarkdown, HtmlPreprocess):
    def __init__(self, filename: str):
        super().__init__(filename)
        with open(self.filename, "r", encoding="utf-8") as f:
            html_doc = f.read()
        soup = BeautifulSoup(html_doc, "html.parser")
        self.html_doc = soup.prettify()

    def get_md_text(self) -> str:
        options = {
            "strip": ["script"],
            "autolinks": False,
        }

        html_doc = self.html_doc
        html_doc = html_doc.replace("&lt;", "<")
        html_doc = html_doc.replace("&gt;", ">")

        html_doc = self.remove_comment(html_doc)
        html_doc = self.remove_img(html_doc)
        html_doc = self.remove_no_script(html_doc)
        html_doc = self.remove_script(html_doc)
        html_doc = self.remove_style(html_doc)

        html_doc = self.remove_class_property(html_doc)
        html_doc = self.remove_id_property(html_doc)
        html_doc = self.remove_onclick_property(html_doc)
        html_doc = self.remove_style_property(html_doc)

        html_doc = self.replace_a(html_doc)
        html_doc = self.replace_br(html_doc)
        html_doc = self.replace_div(html_doc)

        html_doc = self.remove_multiple_newlines(html_doc)
        md_text = md(html_doc, **options)
        md_text = self.remove_multiple_newlines(md_text)

        return md_text

    def save_to_zip(self, output_dir: str):
        basename = str(uuid.uuid4())

        temp_dir = Path(tempfile.gettempdir()) / basename
        temp_dir.mkdir(parents=True, exist_ok=False)

        md_file = temp_dir / f"{basename}.md"
        md_text = self.get_md_text()
        with open(md_file.as_posix(), "w", encoding="utf-8") as f:
            f.write(md_text)
        output_zip_file = os.path.join(output_dir, f"{basename}.zip")

        # zip
        self.zip_directory(temp_dir, output_zip_file)
        shutil.rmtree(temp_dir)
        return output_zip_file


class UrlToMarkdown(BaseToMarkdown, HtmlPreprocess):
    def __init__(self, url: str):
        super().__init__(url)
        self.url = url
        html_doc = self.get_url_content(url)
        soup = BeautifulSoup(html_doc, "html.parser")
        self.html_doc = soup.prettify()

    def get_url_content(self, url: str):
        chrome_driver_manager = ChromeDriverManager(
            cache_manager=DriverCacheManager(
                root_dir=(project_path / "data").as_posix()
            )
        )
        driver_path = chrome_driver_manager.install()
        print(f"driver_path: {driver_path}")

        driver = webdriver.Chrome(
            service=Service(driver_path=driver_path),
        )

        driver.get(url)
        driver.execute_script('window.scrollTo(0, document.body.scrollHeight)')

        html_doc = driver.page_source
        driver.quit()
        return html_doc

    def get_md_text(self) -> str:
        options = {
            "strip": ["script"],
            "autolinks": False,
        }

        html_doc = self.html_doc
        html_doc = html_doc.replace("&lt;", "<")
        html_doc = html_doc.replace("&gt;", ">")

        html_doc = self.remove_comment(html_doc)
        html_doc = self.remove_img(html_doc)
        html_doc = self.remove_no_script(html_doc)
        html_doc = self.remove_script(html_doc)
        html_doc = self.remove_style(html_doc)

        html_doc = self.remove_class_property(html_doc)
        html_doc = self.remove_id_property(html_doc)
        html_doc = self.remove_onclick_property(html_doc)
        html_doc = self.remove_style_property(html_doc)

        html_doc = self.replace_a(html_doc)
        html_doc = self.replace_br(html_doc)
        html_doc = self.replace_div(html_doc)

        html_doc = self.remove_multiple_newlines(html_doc)
        md_text = md(html_doc, **options)
        md_text = self.remove_multiple_newlines(md_text)

        return md_text

    def save_to_zip(self, output_dir: str):
        basename = str(uuid.uuid4())

        temp_dir = Path(tempfile.gettempdir()) / basename
        temp_dir.mkdir(parents=True, exist_ok=False)

        md_file = temp_dir / f"{basename}.md"
        md_text = self.get_md_text()
        with open(md_file.as_posix(), "w", encoding="utf-8") as f:
            f.write(md_text)
        output_zip_file = os.path.join(output_dir, f"{basename}.zip")

        # zip
        self.zip_directory(temp_dir, output_zip_file)
        shutil.rmtree(temp_dir)
        return output_zip_file


def main():
    args = get_args()

    h2m = HtmlToMarkdown(args.filename)

    output_zip_file = h2m.save_to_zip(output_dir=".")
    print(output_zip_file)
    return


def main2():
    args = get_args()

    h2m = UrlToMarkdown("https://www.baidu.com/")

    output_zip_file = h2m.save_to_zip(output_dir=".")
    print(output_zip_file)
    return


if __name__ == "__main__":
    # main()
    main2()