You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Google Cloud Translate Basic API同语言翻译计费与脚本优化咨询

Google Cloud Translate Basic API 同语言翻译的计费与脚本优化

疑问解答

1. 源语言与目标语言一致时的API行为

当API检测到输入文本的源语言和目标语言一致时,会直接返回原文本,不会执行实际的翻译转换操作,但仍会完成语言检测的流程。

2. 同语言场景下的计费问题

会产生字符计费。Google Cloud Translate的计费规则是按提交给API的字符数计算,只要发起API请求并传递了文本内容,无论最终是否执行翻译,这些字符都会被计入计费额度(包括语言检测环节的字符处理)。

脚本优化方案

要避免同语言翻译的费用浪费,最直接的方式是在调用翻译API前,先对输入文本做语言检测,判断源语言是否与目标语言一致,一致则直接返回原文本,不一致再调用翻译接口。

修改后的脚本如下:

def translate_text(target: str, text: str) -> dict:
    """Translates text into the target language.
    Target must be an ISO 639-1 language code.
    """
    from google.cloud import translate_v2 as translate

    translate_client = translate.Client()

    if isinstance(text, bytes):
        text = text.decode("utf-8")
    
    # 先检测源语言
    detection_result = translate_client.detect_language(text)
    source_lang = detection_result["language"]
    
    # 如果源语言和目标语言一致,直接返回原文本结果
    if source_lang == target:
        result = {
            "input": text,
            "translatedText": text,
            "detectedSourceLanguage": source_lang
        }
        print("Text: {}".format(result["input"]))
        print("Translation: {}".format(result["translatedText"]))
        print("Detected source language: {}".format(result["detectedSourceLanguage"]))
        return result
    
    # 源语言与目标语言不同时,调用翻译接口
    result = translate_client.translate(text, target_language=target)

    print("Text: {}".format(result["input"]))
    print("Translation: {}".format(result["translatedText"]))
    print("Detected source language: {}".format(result["detectedSourceLanguage"]))

    return result

output = translate_text('en', 'text')

额外说明

  • 语言检测本身也会产生少量计费,但相比直接调用翻译接口,检测的字符计费成本更低,且能避免大量同语言场景下的无效翻译请求费用。
  • 如果业务场景中能提前确定部分文本的源语言,也可以直接传入source_language参数到translate方法中,进一步减少语言检测的开销。

内容的提问来源于stack exchange,提问作者hitesh goyal

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.15 19:57:46