發布日期:2024 年 9 月 24 日,上次更新日期:2025 年 5 月 20 日
將文字翻譯成另一種語言之前,您必須先判斷指定文字使用的語言。以往翻譯時,必須將文字上傳到雲端服務,在伺服器上執行翻譯,然後下載結果。
Language Detector API 在用戶端運作,因此可保護使用者隱私。雖然可以提供執行這項操作的特定程式庫,但需要額外資源才能下載。
語言偵測功能的使用時機
Language Detector API 主要適用於下列情境:
- 判斷輸入文字的語言,以便翻譯。
- 判斷輸入文字的語言,以便載入正確的模型,執行特定語言的工作,例如偵測惡意言論。
- 判斷輸入文字的語言,以便正確加上標籤,例如在線上社群網站中。
- 判斷輸入文字的語言,以便據此調整應用程式介面。例如,在比利時網站上,只向說法語的使用者顯示相關介面。
開始使用
Language Detector 和 Translator API 適用於電腦版 Chrome。這些 API 無法在行動裝置上運作。
執行功能偵測,確認瀏覽器是否支援 Language Detector API。
if ('LanguageDetector' in self) {
// The Language Detector API is available.
}
下載模型
語言偵測功能仰賴的模型,是專為偵測語言這項特定工作而微調。雖然 API 內建於瀏覽器中,但模型會在網站首次嘗試使用 API 時,隨選下載。在 Chrome 中,這個模型與其他模型相比非常小。由於其他 Chrome 功能也會使用這個模型,因此可能已經存在。
如要判斷模型是否可供使用,請呼叫非同步 LanguageDetector.availability() 函式。如果 availability() 的回應是 downloadable,請監聽下載進度並通知使用者,因為下載可能需要一些時間。
如要觸發下載並例項化語言偵測工具,請檢查使用者活動。然後呼叫非同步 LanguageDetector.create() 函式。
const detector = await LanguageDetector.create({
monitor(m) {
m.addEventListener('downloadprogress', (e) => {
console.log(`Downloaded ${e.loaded * 100}%`);
});
},
});
執行語言偵測工具
Language Detector API 會使用排名模型,判斷指定文字最可能使用的語言。排名是一種機器學習技術,目標是排序項目清單。在這種情況下,Language Detector API 會依機率由高到低排列語言。
detect() 函式可以傳回第一個結果、最可能的答案,或依據可信度逐一查看排名候選項目。系統會以 {detectedLanguage, confidence} 物件清單的形式傳回結果。confidence 程度會以介於 0.0 (最低可信度) 和 1.0 (最高可信度) 之間的值表示。
const someUserText = 'Hallo und herzlich willkommen!';
const results = await detector.detect(someUserText);
for (const result of results) {
// Show the full list of potential languages with their likelihood, ranked
// from most likely to least likely. In practice, one would pick the top
// language(s) that cross a high enough threshold.
console.log(result.detectedLanguage, result.confidence);
}
// (Output truncated):
// de 0.9993835687637329
// en 0.00038279531872831285
// nl 0.00010798392031574622
// ...
API 測試區
在 API Playground 中試用 Language Detector API。在文字區域中輸入不同語言的文字。
權限政策、iframe 和 Web Worker
根據預設,Language Detector API 僅適用於頂層視窗和同源 iframe。您可以使用權限政策 allow="" 屬性,將 API 存取權委派給跨源 iframe:
<!--
The hosting site at https://main.example.com can grant a cross-origin iframe
at https://cross-origin.example.com/ access to the Language Detector API by
setting the `allow="language-detector"` attribute.
-->
<iframe src="https://cross-origin.example.com/" allow="language-detector"></iframe>
Language Detector API 不適用於 Web Worker。這是因為要為每位 worker 建立負責的文件,以檢查權限政策審查狀態,相當複雜。
提供意見
我們想瞭解您使用 Language Detector API 建構的內容。歡迎在 X、YouTube 和 LinkedIn 與我們分享您的網站和網頁應用程式。
如果您對 Chrome 的實作方式有任何意見,請提交 Chromium 錯誤。
加入搶先體驗計畫,搶先瞭解新的內建 AI API,並加入我們的郵寄清單參與討論。