在使用 Anvil.works 部署 spaCy 应用时,可能会遇到 displacy.render 函数将可视化结果输出到 Jupyter Notebook 代码单元,而不是返回到 Anvil 应用中的问题。这是因为 displacy.render 默认会检测当前是否在 Jupyter 环境中运行,如果是,则直接在 Notebook 中渲染结果。为了解决这个问题,我们需要显式地告诉 displacy.render 函数不要进行 Jupyter 环境的自动检测。
在你的代码中,找到调用 displacy.render 函数的地方,并添加 jupyter=False 参数。修改后的代码如下所示:
def visualize_entities_in_sentences(self, doc_id): """Visualize entities in the sentences of a document. :param doc_id: the id of the document to visualize :type doc_id: str """ doc = self.get_document(doc_id) sentences = list(doc.sents) labels = displacy.render(sentences, style="ent", page=False, minify=True, jupyter=False) return labels
通过添加 jupyter=False 参数,我们强制 displacy.render 函数忽略 Jupyter 环境的检测,并将渲染结果作为字符串返回。
下面是一个完整的代码示例,展示了如何在 Anvil 应用中使用 spaCy 和 displacy 显示实体:
import spacy from spacy import displacy import anvil.server # 加载 spaCy 模型 nlp = spacy.load("en_core_web_sm") class Corpus: def __init__(self): self.documents = {} def add_document(self, doc_id, text): self.documents[doc_id] = nlp(text) def get_document(self, doc_id): return self.documents[doc_id] def visualize_entities_in_sentences(self, doc_id): """Visualize entities in the sentences of a document. :param doc_id: the id of the document to visualize :type doc_id: str """ doc = self.get_document(doc_id) sentences = list(doc.sents) labels = displacy.render(sentences, style="ent", page=False, minify=True, jupyter=False) return labels # 创建 Corpus 实例 my_corpus = Corpus() # 添加示例文档 my_corpus.add_document("doc1", "Apple is looking at buying U.K. startup for $1 billion") @anvil.server.callable def get_visualize_entities_in_sentences(doc_id): """"Get the document markdown for a document in my_corpus with entity labels visualized. :param doc_id: a document id :type doc_id: str :returns: markdown :rtype: str """ return my_corpus.visualize_entities_in_sentences(doc_id) # 启动 Anvil 服务器 # anvil.server.connect("YOUR_ANVIL_KEY") # 替换为你的 Anvil API 密钥 # anvil.server.wait_forever()
通过在 displacy.render 函数调用中添加 jupyter=False 参数,可以有效地解决在使用 Anvil.works 服务器时,spaCy displacy 将可视化结果输出到 Jupyter Notebook 代码单元的问题。这使得你可以在 Anvil 应用中轻松地显示实体可视化结果,从而提升应用的交互性和用户体验。
以上就是在 Anvil.works 中使用 spaCy displacy 显示实体的详细内容,更多请关注php中文网其它相关文章!
每个人都需要一台速度更快、更稳定的 PC。随着时间的推移,垃圾文件、旧注册表数据和不必要的后台进程会占用资源并降低性能。幸运的是,许多工具可以让 Windows 保持平稳运行。
Copyright 2014-2025 //m.sbmmt.com/ All Rights Reserved | php.cn | 湘ICP备2023035733号