From dc195428dd96807fad1a4caa710109b594373a2d Mon Sep 17 00:00:00 2001 From: zdm Date: Tue, 13 Feb 2024 05:38:22 +0200 Subject: [PATCH] feat: cloud translation --- lib/package/localization.js | 62 +++++++++++++++++++++++++++++++------ 1 file changed, 52 insertions(+), 10 deletions(-) diff --git a/lib/package/localization.js b/lib/package/localization.js index 0c0080a5..33fb155d 100644 --- a/lib/package/localization.js +++ b/lib/package/localization.js @@ -7,6 +7,13 @@ import GetText from "#lib/get-text"; import sql from "#core/sql"; import env from "#core/env"; import url from "node:url"; +import CloudTranslationApi from "#core/api/google/cloud/translation"; + +env.loadUserEnv(); + +if ( process.env.GCLOUD_TRANSLATION_API_KEY ) { + var cloudTranslationApi = new CloudTranslationApi( process.env.GCLOUD_TRANSLATION_API_KEY ); +} const SQL = { "schema": sql` @@ -14,6 +21,7 @@ create table if not exists translation ( language text noy null, msgid text not null, msgid_plural text not null, + fuzzy bool NOT NULL, translations json not null, primary key ( language, msgid, msgid_plural ) ); @@ -25,11 +33,13 @@ INSERT INTO translation language, msgid, msgid_plural, + fuzzy, translations ) VALUES - ( ?, ?, ?, ? ) + ( ?, ?, ?, ?, ? ) ON CONFLICT ( language, msgid, msgid_plural ) DO UPDATE SET + fuzzy = EXCLUDED.fuzzy, translations = EXCLUDED.translations `.prepare(), @@ -149,18 +159,14 @@ export default class { for ( const message of Object.values( poFile.messages ) ) { if ( message.isDisabled ) continue; - if ( message.isDisFuzzy ) continue; - + // message is fully translated if ( message.isTranslated ) { - this.#dbh.do( SQL.updateTranslations, [ + if ( message.isDisFuzzy ) continue; - // - poFile.language, - message.id, - message.pluralId || "", - message.translations, - ] ); + this.#storeMessage( poFile.language, message ); } + + // message is not translated else { const res = this.#dbh.selectRow( SQL.getTranslations, [ @@ -174,6 +180,30 @@ export default class { message.isFuzzy = true; message.setTranslations( res.data.translations ); } + else if ( cloudTranslationApi ) { + if ( message.pluralId ) continue; + + const res = await cloudTranslationApi.translate( poFile.language, [ message.id ] ); + + // error + if ( !res.ok ) { + console.warn( `Cloud translation API error:`, res + "" ); + + continue; + } + + // not translated + if ( !res.data ) continue; + + message.isFuzzy = true; + message.setTranslations( [ res.data ] ); + + console.log( `Auto translated: +${ message.id } +${ res.data } + +` ); + } } } } @@ -198,4 +228,16 @@ export default class { this.#dbh.exec( SQL.schema ); } + + #storeMessage ( language, message ) { + this.#dbh.do( SQL.updateTranslations, [ + + // + language, + message.id, + message.pluralId || "", + message.isDisFuzzy, + message.translations, + ] ); + } }