File size: 1,959 Bytes
d93fd32
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
from collections.abc import Callable
import typing

from bs4 import BeautifulSoup
from html2markdown import WikiConverter


class MediaWikiSoup:
    def __init__(self) -> None:
        self.soup_filters = []
        self.md_filters = []
        self.converter = WikiConverter()

    def soup_filter(self, content: str, meta:dict={}):
        soup = BeautifulSoup(content, "lxml")
        soup, meta = self.soup_filters[0](soup, meta)
        if len(self.soup_filters) <= 1:
            return soup, meta
        for idx, filter in enumerate(self.soup_filters[1:]):
            try:
                soup, meta = filter(soup, meta)
            except Exception as e:
                print("Previous filter", self.soup_filters[idx])
                print("Current filter", filter)
                print(e)
                raise e
            if meta.get("_drop"):
                return None
        return soup, meta
    
    def add_markdown_filter(
        self,
        func: Callable[
            [str, typing.Dict[typing.Any, typing.Any]],
            typing.Tuple[str, typing.Dict[typing.Any, typing.Any]],
        ],
    ):
        self.md_filters.append(func)
    
    def markdown_filter(self, soup:BeautifulSoup | str, meta:dict={}):
        if isinstance(soup, str):
            markdown = soup
        else:
            markdown = self.converter.convert_soup(soup)
        markdown, meta = self.md_filters[0](markdown, meta)
        if len(self.md_filters) <= 1:
            return markdown, meta
        for filter in self.md_filters[1:]:
            markdown, meta = filter(markdown, meta)
            if meta.get("_drop"):
                return None
        return markdown, meta

    def add_soup_filter(
        self,
        func: Callable[
            [BeautifulSoup, typing.Dict[typing.Any, typing.Any]],
            typing.Tuple[BeautifulSoup, typing.Dict[typing.Any, typing.Any]],
        ],
    ):
        self.soup_filters.append(func)