|
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) |
|
|