---
tags: note, google
---
# Google Translate API
[官方簡介](https://cloud.google.com/translate?hl=zh-tw)
## 功能與計價方式
這應該是評估要不要使用的兩大考量點。
[官方比較表](https://cloud.google.com/translate?hl=zh-tw#section-6)
### TL;DR
看影片最快
[What is the Translation API?](https://www.youtube.com/watch?v=A3knNbGfXh4)
[What is AutoML Translation?](https://www.youtube.com/watch?v=yzZiRrKcwD8)
[How to automatically transcribe your video or audio into text](https://www.youtube.com/watch?v=RyVWUMAMIDk)
### 文字說明
1. Translation API Basic
使用google自己的model翻譯,每月`前50萬個`字元免費。
所以如果只是要[Google translate](https://translate.google.com.tw/)一樣的翻譯品質,而且量不大的話,那用這個方案會是很足夠的。
2. Translation API Advanced
主要有幾個需求是basic版本做不到的:
- 有特殊的名詞需要特別進行翻譯 -> Glossary
- 使用自己訓練的model翻譯 -> AutoML Translation
- 文件翻譯
- 批次翻譯
以翻譯字元量及批次翻譯量計價。
其中glossary和文件翻譯會用到google cloud storage,有可能會需要額外收費(看用量)。
3. AutoML Translation
訓練自己的model,必須配合上面第二項使用。
以訓練時間和翻譯字元量計價,提供的訓練資料越龐大,訓練時間就越久、費用越高囉。
5. Media Translation API
串流翻譯,比以前的翻譯方式更簡單、快速、高品質。
已用量(分鐘)計價
## Translation API Basic
### API Key
> Project > API和服務 > 憑證 > API金鑰
金鑰可以另外設定使用限制:
- 呼叫的來源
- 可呼叫的API(不限制的話可以呼叫所有google cloud 服務)
```javascript=
// 翻譯文字範例
$.post({
url: 'https://translation.googleapis.com/language/translate/v2',
data: {
"q": val,
"target": target, // 目標語言
"key": key
},
success: function (res) {
let translations = res.data.translations;
// 回傳是一個list
for (t of translations) {
let translated = t.translatedText;
console.log(translated)
}
}
});
```
### Client Libraries
#### 1. 權限設定 service account & private key
#### 2. private key放在執行環境理
```console
export GOOGLE_APPLICATION_CREDENTIALS="KEY_PATH"
```
KEY_PATH會是JSON檔案路徑。
#### 3. 安裝client libraries
```console
# Basic
pip install google-cloud-translate==2.0.1
```
```console
# Advanced
pip install --upgrade google-cloud-translate
```
#### 4. 範例
```python=
# Django function 翻譯文字範例
import six
from google.cloud import translate_v2 as translate
def get_translate(request):
post_param = request.POST
text = post_param.get('text', None) # 欲翻譯文字
target = post_param.get('target', None) # 目標語言
if text:
translate_client = translate.Client()
if isinstance(text, six.binary_type):
text - text.decode('utf-8')
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 HttpResponse(result['translatedText'])
```
## Translation API Advanced
### Glossary
#### 1. Google Cloud Bucket
### File Translation
#### 1. Google Cloud Bucket
### Batch Translation
#### 1. Google Cloud Bucket
## AutoML Translation