跳到内容

HTML 转 Markdown

pipeline pipeline

HTML 到 Markdown 管道将 HTML 转换为 Markdown。

Markdown 格式应用于标题、块引用、列表、代码、表格和文本。视觉格式(粗体、斜体等)也包含在内。

此管道会搜索包含相关文本的最佳节点,通常使用 articlemainbody 标签找到。

HTML 转 Markdown 管道需要安装 BeautifulSoup4 库。

示例

下面是使用此管道的一个简单示例。

from txtai.pipeline import HTMLToMarkdown

# Create and run pipeline
md = HTMLToMarkdown()
md("<html><body>This is a test</body></html>")

配置驱动示例

管道通过 Python 或配置运行。管道可以在 配置 中使用管道的小写名称实例化。配置驱动的管道通过 工作流API 运行。

config.yml

# Create pipeline using lower case class name
htmltomarkdown:

# Run pipeline with workflow
workflow:
  markdown:
    tasks:
      - action: htmltomarkdown

使用工作流运行

from txtai import Application

# Create and run pipeline with workflow
app = Application("config.yml")
list(app.workflow("markdown", ["<html><body>This is a test</body></html>"]))

使用 API 运行

CONFIG=config.yml uvicorn "txtai.api:app" &

curl \
  -X POST "http://localhost:8000/workflow" \
  -H "Content-Type: application/json" \
  -d '{"name":"markdown", "elements":["<html><body>This is a test</body></html>"]}'

方法

管道的 Python 文档。

__init__(paragraphs=False, sections=False)

创建一个新的 Extract 实例。

参数

名称 类型 描述 默认值
paragraphs

如果启用段落解析则为 True,否则为 False

False
sections

如果启用章节解析则为 True,否则为 False

False
源代码位于 txtai/pipeline/data/htmltomd.py
28
29
30
31
32
33
34
35
36
37
38
39
40
41
def __init__(self, paragraphs=False, sections=False):
    """
    Create a new Extract instance.

    Args:
        paragraphs: True if paragraph parsing enabled, False otherwise
        sections: True if section parsing enabled, False otherwise
    """

    if not SOUP:
        raise ImportError('HTMLToMarkdown pipeline is not available - install "pipeline" extra to enable')

    self.paragraphs = paragraphs
    self.sections = sections

__call__(html)

将输入的 HTML 转换为 Markdown 格式的文本。

参数

名称 类型 描述 默认值
html

输入 HTML

必需

返回

类型 描述

Markdown 格式的文本

源代码位于 txtai/pipeline/data/htmltomd.py
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
def __call__(self, html):
    """
    Transforms input HTML into Markdown formatted text.

    Args:
        html: input html

    Returns:
        markdown formatted text
    """

    # HTML Parser
    soup = BeautifulSoup(html, features="html.parser")

    # Ignore script and style tags
    for script in soup.find_all(["script", "style"]):
        script.decompose()

    # Check for article sections
    article = next((x for x in ["article", "main"] if soup.find(x)), None)

    # Extract text from each section element
    nodes = []
    for node in soup.find_all(article if article else "body"):
        # Skip article sections without at least 1 paragraph
        if not article or node.find("p"):
            nodes.append(self.process(node, article))

    # Return extracted text, fallback to default text extraction if no nodes found
    return "\n".join(self.metadata(soup) + nodes) if nodes else self.default(soup)