集成:DeepL
在 Haystack 中使用 DeepL 翻译服务
目录
概述
DeepL 是一个强大的翻译服务提供商,提供高质量的多语言翻译。此集成允许您在 Haystack 中使用 DeepL 的翻译服务。
安装
pip install deepl-haystack
使用
组件
DeepL Haystack 集成引入了两个组件,可用于通过 DeepL API 获取翻译。
DeepLTextTranslator用于翻译纯文本(Python 字符串)。DeepLDocumentTranslator用于翻译 Haystack 的Document对象。
API 密钥
要使用 DeepL Haystack 集成,您需要提供 DeepL API 密钥。您可以通过在 DeepL API 网站注册来获取。
获取密钥后,请务必在运行以下示例之前将其作为名为 DEEPL_API_KEY 的环境变量导出到您的工作环境中。DeepLTextTranslator 和 DeepLDocumentTranslator 组件的构造函数都将期望此变量已设置。
提供 API 密钥的另一种方法(但不推荐)是通过组件构造函数的 api_key 参数传递,使用 Haystack 的 Secret 工具。
示例
独立运行
以下示例演示了如何翻译一个简单文本
from deepl_haystack import DeepLTextTranslator
translator = DeepLTextTranslator(source_lang="EN", target_lang="ES")
translated_text = translator.run("Hello, world!")
print(translated_text)
# {'translation': '¡Hola, mundo!', 'meta': {'source_lang': 'EN', 'target_lang': 'ES'}}
在这里,我们展示了如何翻译一组 Document 对象
from haystack.dataclasses import Document
from deepl_haystack import DeepLDocumentTranslator
translator = DeepLDocumentTranslator(source_lang="EN", target_lang="ES")
documents_to_translate = [
Document(content="Hello, world!"),
Document(content="Goodbye, Joe!", meta={"name": "Joe"}),
]
translated_documents = translator.run(documents_to_translate)
print(
"\n".join(
[f"{doc.content}, {doc.meta}" for doc in translated_documents["documents"]]
)
)
# ¡Hola, mundo!, {'source_lang': 'EN', 'target_lang': 'ES'}
# ¡Adiós, Joe!, {'name': 'Joe', 'source_lang': 'EN', 'target_lang': 'ES'}
管道
要在 Haystack 管道中使用 DeepL 组件,您可以像使用其他 Haystack 组件一样使用它们。
from haystack import Pipeline
from haystack.components.converters import TextFileToDocument
from haystack.components.writers import DocumentWriter
from haystack.dataclasses.byte_stream import ByteStream
from haystack.document_stores.in_memory import InMemoryDocumentStore
from deepl_haystack import DeepLDocumentTranslator
document_store = InMemoryDocumentStore()
pipeline = Pipeline()
pipeline.add_component(instance=TextFileToDocument(), name="converter")
pipeline.add_component(
instance=DeepLDocumentTranslator(target_lang="ES"),
name="translator",
)
pipeline.add_component(
instance=DocumentWriter(document_store=document_store), name="document_store"
)
pipeline.connect("converter", "translator")
pipeline.connect("translator", "document_store")
pipeline.run({"converter": {"sources": [ByteStream.from_string("Hello world!")]}})
print(document_store.filter_documents())
# [Document(id=..., content: '¡Hola, mundo!', meta: {'source_lang': 'EN', 'language': 'ES'})]
许可证
deepl-haystack 根据 MIT 许可的条款分发。
