Microsoft Azure Ai Translation Text Python客户端库
项目描述
Azure Text Translation Python客户端库
文本翻译是翻译服务的一个基于云的REST API功能,它使用神经机器翻译技术,可以在所有支持的语言中实现快速、准确的目标文本翻译。
使用Python的文本翻译客户端库:
-
返回支持翻译、转写和字典操作的语言列表。
-
通过单个请求将单个源语言文本渲染为多个目标语言文本。
-
将源语言的文本转换为不同脚本中的字母。
-
返回源术语在目标语言中的等效词。
-
返回源术语和目标术语对的语法结构和上下文示例。
源代码 | 包(PyPI) | API参考文档 | 产品文档 | 示例
入门
先决条件
- 使用此软件包需要Python 3.7或更高版本。
- 现有的翻译服务或认知服务资源。
安装包
使用 pip 安装 Azure Text Translation Python 客户端库
pip install azure-ai-translation-text
创建翻译服务资源
您可以按照创建翻译资源的说明来创建翻译资源。
客户端认证
使用客户端库与服务的交互从创建一个TextTranslationClient类的实例开始。您需要一个 API密钥 或 TokenCredential
来实例化客户端对象。有关使用认知服务进行认证的更多信息,请参阅认证对翻译服务的请求。
获取API密钥
您可以从Azure门户中的认知服务资源或翻译服务资源信息中获取endpoint
、API密钥
和区域
。
或者,使用以下Azure CLI片段从翻译服务资源获取API密钥。
az cognitiveservices account keys list --resource-group <your-resource-group-name> --name <your-resource-name>
使用API密钥和区域凭据创建TextTranslationClient
一旦您有了API密钥和区域值,创建一个AzureKeyCredential
。这将允许您在不创建新客户端的情况下更新API密钥。
有了endpoint
、credential
和region
的值,您可以创建TextTranslationClient
credential = AzureKeyCredential(apikey)
text_translator = TextTranslationClient(credential=credential, region=region)
关键概念
TextTranslationClient
TextTranslationClient
是开发人员使用文本翻译客户端库的主要接口。它提供了同步和异步操作,以访问特定的文本翻译用法,例如获取支持的语言检测或文本翻译。
输入
文本元素(string
)是单个输入单元,将被翻译服务的翻译模型处理。对TextTranslationClient
的操作可能接受单个文本元素或文本元素的集合。有关文本元素长度限制、最大请求大小和受支持文本编码的信息,请参阅此处。
示例
以下部分提供了使用上面创建的client
的一些代码片段,并涵盖了此客户端库中存在的主要功能。尽管以下大多数代码片段都使用了同步服务调用,但请注意,Python的文本翻译库支持同步和异步API。
获取支持的语言
获取翻译的其他操作当前支持的语言集。
try:
response = text_translator.get_supported_languages()
print(
f"Number of supported languages for translate operation: {len(response.translation) if response.translation is not None else 0}"
)
print(
f"Number of supported languages for transliterate operation: {len(response.transliteration) if response.transliteration is not None else 0}"
)
print(
f"Number of supported languages for dictionary operations: {len(response.dictionary) if response.dictionary is not None else 0}"
)
if response.translation is not None:
print("Translation Languages:")
for key, value in response.translation.items():
print(f"{key} -- name: {value.name} ({value.native_name})")
if response.transliteration is not None:
print("Transliteration Languages:")
for key, value in response.transliteration.items():
print(f"{key} -- name: {value.name}, supported script count: {len(value.scripts)}")
if response.dictionary is not None:
print("Dictionary Languages:")
for key, value in response.dictionary.items():
print(f"{key} -- name: {value.name}, supported target languages count: {len(value.translations)}")
except HttpResponseError as exception:
if exception.error is not None:
print(f"Error Code: {exception.error.code}")
print(f"Message: {exception.error.message}")
raise
有关使用languages
端点的示例,请参阅更多示例此处。
请参阅服务文档,了解语言的概念性讨论。
翻译
使用单个请求将源语言文本渲染为多个目标语言文本。
try:
to_language = ["cs", "es", "de"]
input_text_elements = ["This is a test"]
response = text_translator.translate(body=input_text_elements, to_language=to_language)
translation = response[0] if response else None
if translation:
detected_language = translation.detected_language
if detected_language:
print(
f"Detected languages of the input text: {detected_language.language} with score: {detected_language.score}."
)
for translated_text in translation.translations:
print(f"Text was translated to: '{translated_text.to}' and the result is: '{translated_text.text}'.")
except HttpResponseError as exception:
if exception.error is not None:
print(f"Error Code: {exception.error.code}")
print(f"Message: {exception.error.message}")
有关使用translate
端点的示例,请参阅更多示例此处。
请参阅服务文档,了解翻译的概念性讨论。
转写
将源语言中的字符或字母转换为对应的目标语言中的字符或字母。
try:
language = "zh-Hans"
from_script = "Hans"
to_script = "Latn"
input_text_elements = ["这是个测试。"]
response = text_translator.transliterate(
body=input_text_elements,
language=language,
from_script=from_script,
to_script=to_script,
)
transliteration = response[0] if response else None
if transliteration:
print(
f"Input text was transliterated to '{transliteration.script}' script. Transliterated text: '{transliteration.text}'."
)
except HttpResponseError as exception:
if exception.error is not None:
print(f"Error Code: {exception.error.code}")
print(f"Message: {exception.error.message}")
raise
有关使用transliterate
端点的示例,请参阅更多示例此处。
请参阅服务文档,了解对转写的概念性讨论。
句子分割
标识文本中句子边界的定位。
try:
include_sentence_length = True
to_language = ["cs"]
input_text_elements = ["The answer lies in machine translation. This is a test."]
response = text_translator.translate(
body=input_text_elements, to_language=to_language, include_sentence_length=include_sentence_length
)
translation = response[0] if response else None
if translation:
detected_language = translation.detected_language
if detected_language:
print(
f"Detected languages of the input text: {detected_language.language} with score: {detected_language.score}."
)
for translated_text in translation.translations:
print(f"Text was translated to: '{translated_text.to}' and the result is: '{translated_text.text}'.")
if translated_text.sent_len:
print(f"Source Sentence length: {translated_text.sent_len.src_sent_len}")
print(f"Translated Sentence length: {translated_text.sent_len.trans_sent_len}")
except HttpResponseError as exception:
if exception.error is not None:
print(f"Error Code: {exception.error.code}")
print(f"Message: {exception.error.message}")
有关使用句子分割
端点的示例,请参阅更多示例此处。
请参阅服务文档,了解对句子分割的概念性讨论。
词典查询
返回目标语言中对源术语的等效单词。
try:
from_language = "en"
to_language = "es"
input_text_elements = ["fly"]
response = text_translator.lookup_dictionary_entries(
body=input_text_elements, from_language=from_language, to_language=to_language
)
dictionary_entry = response[0] if response else None
if dictionary_entry:
print(f"For the given input {len(dictionary_entry.translations)} entries were found in the dictionary.")
print(
f"First entry: '{dictionary_entry.translations[0].display_target}', confidence: {dictionary_entry.translations[0].confidence}."
)
except HttpResponseError as exception:
if exception.error is not None:
print(f"Error Code: {exception.error.code}")
print(f"Message: {exception.error.message}")
raise
有关使用词典查询
端点的示例,请参阅更多示例此处。
请参阅服务文档,了解对词典查询的概念性讨论。
词典示例
返回源术语和目标术语对的语法结构和上下文示例。
try:
from_language = "en"
to_language = "es"
input_text_elements = [DictionaryExampleTextItem(text="fly", translation="volar")]
response = text_translator.lookup_dictionary_examples(
body=input_text_elements, from_language=from_language, to_language=to_language
)
dictionary_entry = response[0] if response else None
if dictionary_entry:
print(f"For the given input {len(dictionary_entry.examples)} entries were found in the dictionary.")
print(
f"First example: '{dictionary_entry.examples[0].target_prefix}{dictionary_entry.examples[0].target_term}{dictionary_entry.examples[0].target_suffix}'."
)
except HttpResponseError as exception:
if exception.error is not None:
print(f"Error Code: {exception.error.code}")
print(f"Message: {exception.error.message}")
raise
有关使用词典示例
端点的示例,请参阅更多示例此处。
请参阅服务文档,了解对词典示例的概念性讨论。
故障排除
当您使用TextTranslator客户端库与翻译服务交互时,翻译服务返回的错误与REST API请求返回的相同HTTP状态码相对应。
例如,如果您在没有目标翻译语言的情况下提交翻译请求,则返回一个400
错误,表示“无效请求”。
您可以在服务文档中找到服务返回的不同错误代码。
提供反馈
如果您遇到任何错误或有建议,请在项目的问题部分提交问题。
下一步
更多示例可以在示例目录下找到。
贡献
此项目欢迎贡献和建议。大多数贡献都需要您同意一份贡献者许可协议(CLA),声明您有权利,并且实际上确实授予我们使用您贡献的权利。有关详细信息,请访问cla.microsoft.com。
当您提交拉取请求时,CLA-bot会自动确定您是否需要提供CLA,并相应地装饰PR(例如,标签、注释)。只需遵循机器人提供的说明即可。您只需在整个使用我们CLA的存储库中进行一次此操作。
此项目已采用Microsoft开源行为准则。有关更多信息,请参阅行为准则FAQ或通过opencode@microsoft.com联系以获取任何额外的问题或评论。
项目详情
下载文件
下载适合您平台的文件。如果您不确定选择哪个,请了解有关安装包的更多信息。
源分布
构建版本
azure-ai-translation-text-1.0.1.tar.gz的哈希值
算法 | 哈希摘要 | |
---|---|---|
SHA256 | 8fff37f7ea4f82f25ad6328374859d6bad022d2f30fde9b30b5ee4cf1f7c1769 |
|
MD5 | bc25f7c21591cba2cef6bc9cb0045475 |
|
BLAKE2b-256 | 04db4b9ea0a86c994a7355868a7cc1604ceec5963b94c38dc39bdf9205ebbe30 |
azure_ai_translation_text-1.0.1-py3-none-any.whl的哈希值
算法 | 哈希摘要 | |
---|---|---|
SHA256 | 2c60d1adcda68809dd9f431ec0b8ac1b1977a69037d10751a39c233bc6bc42d8 |
|
MD5 | 2cf088e32bbe05bc10883b3ec82c9e23 |
|
BLAKE2b-256 | 8101d3efa3e5383744fce4d5ca6f05e749928f5fc4aa62b0399c8027ada189f5 |