有没有办法在 Dash 仪表板上呈现 spaCy 的 NER 输出?

Is there a way to render spaCy's NER output on a Dash dashboard?

我正在尝试将 spaCy 的 NER 预训练模型合并到我的 Dash 仪表板中。我知道 Dash 目前无法渲染原始 html 所以我正在寻找解决方案。我已经在网上广泛搜索但没有找到解决方案。 目前,我有一个如下所示的仪表板:

[仪表板]

如果可能,我希望 SpaCy 的 NER 输出显示在下方。例如,请参见下图:

[NER 示例输出]

如果有人设法找到适用于 Dash 的解决方案,请告诉我。如果不可能,那么这不是世界末日。我知道它可以在 Flask 中完成,尽管在 HTML!

中编码更难

非常感谢!

不可能通过位移将其渲染成一行。但是,您应该能够通过 python 函数抽象出 html 并手动呈现结果。这是一个示例应用程序:

import dash
import dash_html_components as html

import spacy
from spacy.displacy.render import DEFAULT_LABEL_COLORS


# Initialize the application
app = dash.Dash(__name__)


def entname(name):
    return html.Span(name, style={
        "font-size": "0.8em",
        "font-weight": "bold",
        "line-height": "1",
        "border-radius": "0.35em",
        "text-transform": "uppercase",
        "vertical-align": "middle",
        "margin-left": "0.5rem"
    })


def entbox(children, color):
    return html.Mark(children, style={
        "background": color,
        "padding": "0.45em 0.6em",
        "margin": "0 0.25em",
        "line-height": "1",
        "border-radius": "0.35em",
    })


def entity(children, name):
    if type(children) is str:
        children = [children]

    children.append(entname(name))
    color = DEFAULT_LABEL_COLORS[name]
    return entbox(children, color)


def render(doc):
    children = []
    last_idx = 0
    for ent in doc.ents:
        children.append(doc.text[last_idx:ent.start_char])
        children.append(
            entity(doc.text[ent.start_char:ent.end_char], ent.label_))
        last_idx = ent.end_char
    children.append(doc.text[last_idx:])
    return children


text = "When Sebastian Thrun started working on self-driving cars at Google in 2007, few people outside of the company took him seriously."
nlp = spacy.load("en_core_web_sm")
doc = nlp(text)
print("Entities:", doc.ents)

# define de app
app.layout = html.Div(
    children=render(doc)
)

# Run the app
if __name__ == "__main__":
    app.run_server(debug=True)

这会产生以下结果:

在上面的示例中,entnameentbox 函数将分别生成一个 html.Spanhtml.Mark,其样式从输出 html 复制而来在 displacy。然后,函数entity将前面两个函数抽象出来,轻松生成一个实体框。最后,render 函数将获取 spacy 的 Doc 对象并将其转换为 Dash html 组件列表,可以在 Dash 布局中使用。