如何导出具有多个组件的 SpaCy 模型

How to export SpaCy model with multiple components

我正在尝试使用多个组件构建 SpaCy 管道。我当前的管道目前只有两个组件,一个实体标尺和另一个自定义组件。

我的搭建方式是这样的:

class EntityLookupComponent:
    def __call__(self, doc: Doc) -> Doc:
        print("Just testing")
        return doc

@Language.factory("entity_lookup_component")
def my_component(nlp, name):
    return EntityLookupComponent(nlp)

def main(patterns_path: Path, output_path: Path):
    """Build the spaCy model and output it to disk"""

    # Ensure output_path directory exists
    if not Path(os.path.dirname(output_path)).is_dir():
        os.makedirs(os.path.dirname(output_path))

    nlp = English()
    nlp.add_pipe("entity_ruler").from_disk(patterns_path)
    nlp.add_pipe("entity_lookup_component", name="entity_lookup", last=True)

    print(nlp.pipe_names)

    nlp.to_disk('./test')

    with open(output_path, "wb") as output_file:
        pickle.dump(nlp, output_file)

输出 pipe_names 得到:['entity_ruler', 'entity_lookup'].

但是,当我尝试加载模型并进行测试时,通过执行以下操作:

nlp = spacy.load("en_core_web_lg", disable=["ner"])
nlp.add_pipe("entity_ruler", source=spacy.load("./test"))

它立即抛出以下错误:

ValueError: [E002] Can't find factory for 'entity_lookup_component' for language English (en). This usually happens when spaCy calls `nlp.create_pipe` with a custom component name that's not registered on the current language class. If you're using a Transformer, make sure to install 'spacy-transformers'. If you're using a custom component, make sure you've added the decorator `@Language.component` (for function components) or `@Language.factory` (for class components).

只有在我添加 entity_lookup_component 之后才会出现这种情况。此组件应该使用查找 table,以将一些元数据添加到现有实体。

在加载模型的地方,您需要访问定义自定义组件的代码。因此,如果您定义自定义组件的文件是 custom.py,您可以将 import custom 放在您正在加载管道的文件顶部,它应该可以工作。

另请参阅 the docs 保存和加载自定义组件。