Skip to content

Commit

Permalink
feat: cloud translation
Browse files Browse the repository at this point in the history
  • Loading branch information
zdm committed Feb 13, 2024
1 parent 9db9f41 commit dc19542
Showing 1 changed file with 52 additions and 10 deletions.
62 changes: 52 additions & 10 deletions lib/package/localization.js
Original file line number Diff line number Diff line change
Expand Up @@ -7,13 +7,21 @@ 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`
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 )
);
Expand All @@ -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(),

Expand Down Expand Up @@ -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, [

Expand All @@ -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 }
` );
}
}
}
}
Expand All @@ -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,
] );
}
}

0 comments on commit dc19542

Please sign in to comment.