Skip to content

Commit a02b87c

Browse files
author
Stepan Kamenik
committed
feat(FgForrest#3): add google translator
1 parent e2b495d commit a02b87c

File tree

7 files changed

+83
-29
lines changed

7 files changed

+83
-29
lines changed

pom.xml

+18
Original file line numberDiff line numberDiff line change
@@ -69,7 +69,25 @@
6969
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
7070
</properties>
7171

72+
<dependencyManagement>
73+
<dependencies>
74+
<dependency>
75+
<groupId>com.google.cloud</groupId>
76+
<artifactId>libraries-bom</artifactId>
77+
<version>4.3.0</version>
78+
<type>pom</type>
79+
<scope>import</scope>
80+
</dependency>
81+
</dependencies>
82+
</dependencyManagement>
83+
7284
<dependencies>
85+
86+
<dependency>
87+
<groupId>com.google.cloud</groupId>
88+
<artifactId>google-cloud-translate</artifactId>
89+
</dependency>
90+
7391
<dependency>
7492
<groupId>com.deepl.api</groupId>
7593
<artifactId>deepl-java</artifactId>

src/main/java/one/edee/babylon/MainService.java

+2-2
Original file line numberDiff line numberDiff line change
@@ -29,7 +29,7 @@ public MainService(Exporter exporter,
2929
this.importProcessor = importProcessor;
3030
}
3131

32-
public void startTranslation(Action action, TranslationConfiguration configuration, String spreadsheetId, boolean combineSheets, String deeplApiKey) throws IOException, GeneralSecurityException, InterruptedException {
32+
public void startTranslation(Action action, TranslationConfiguration configuration, String spreadsheetId, boolean combineSheets, String translatorApiKey) throws IOException, GeneralSecurityException, InterruptedException {
3333
long stTime = System.currentTimeMillis();
3434
switch (action) {
3535
case EXPORT:
@@ -41,7 +41,7 @@ public void startTranslation(Action action, TranslationConfiguration configurati
4141
configuration.getSnapshotPath(),
4242
configuration.getLockedCellEditors(),
4343
combineSheets,
44-
deeplApiKey,
44+
translatorApiKey,
4545
configuration.getDefaultLang());
4646
break;
4747
case IMPORT:

src/main/java/one/edee/babylon/SpringBootConsoleApplication.java

+5-5
Original file line numberDiff line numberDiff line change
@@ -44,7 +44,7 @@ public void run(String... args) {
4444
try {
4545
log.info("Loading config file: '" + arguments.getConfigFileName() + "'");
4646
TranslationConfiguration configuration = configurationReader.readAndCheckConfiguration(arguments.getConfigFileName());
47-
mainService.startTranslation(arguments.getAction(), configuration, arguments.getGoogleSheetId(), arguments.isCombineSheets(), arguments.getDeeplApiKey());
47+
mainService.startTranslation(arguments.getAction(), configuration, arguments.getGoogleSheetId(), arguments.isCombineSheets(), arguments.getTranslatorApiKey());
4848
} catch (Exception e) {
4949
log.error("BABYLON ERROR: ", e);
5050
System.exit(-1);
@@ -75,7 +75,7 @@ public static Arguments parseArguments(String... args) {
7575
arguments.setConfigFileName(args[1]);
7676
arguments.setGoogleSheetId(args[2]);
7777
if (args.length > 3){
78-
arguments.setDeeplApiKey(args[3]);
78+
arguments.setTranslatorApiKey(args[3]);
7979
if (args.length > 4){
8080
arguments.setCombineSheets(Boolean.parseBoolean(args[4]));
8181
}
@@ -87,7 +87,7 @@ private static void printRequiredArguments() {
8787
log.info("1 - expected action (import, export)");
8888
log.info("2 - path to translator-config.json file");
8989
log.info("3 - ID of the google sheet (e.g. 1xhnBAOpy8-9KWhl8NP0ZIy6mhlgXKnKcLJwKcIeyjPc)");
90-
log.info("4 - arg to specify deepl api key");
90+
log.info("4 - arg to specify translator api key");
9191
log.info("5 - arg to specify combineSheets mode");
9292
}
9393

@@ -120,9 +120,9 @@ public static class Arguments {
120120
private boolean combineSheets = false;
121121

122122
/**
123-
* Deepl api key.
123+
* Translator api key (Google/Deepl).
124124
*/
125-
private String deeplApiKey;
125+
private String translatorApiKey;
126126
}
127127

128128
}

src/main/java/one/edee/babylon/config/TranslationConfiguration.java

+6
Original file line numberDiff line numberDiff line change
@@ -49,6 +49,12 @@ public class TranslationConfiguration implements Serializable {
4949
@NonNull
5050
private String defaultLang;
5151

52+
/**
53+
* Default language of project properties.
54+
*/
55+
@NonNull
56+
private String translatorApiKey;
57+
5258
@JsonIgnore
5359
public Path getSnapshotPath() {
5460
return Paths.get(dataFileName);

src/main/java/one/edee/babylon/export/Exporter.java

+42-13
Original file line numberDiff line numberDiff line change
@@ -1,7 +1,10 @@
11
package one.edee.babylon.export;
22

3-
import com.deepl.api.TextResult;
3+
import com.deepl.api.DeepLException;
44
import com.deepl.api.Translator;
5+
import com.google.api.client.http.HttpRequestInitializer;
6+
import com.google.cloud.translate.Translate;
7+
import com.google.cloud.translate.TranslateOptions;
58
import lombok.extern.apachecommons.CommonsLog;
69
import one.edee.babylon.db.SnapshotUtils;
710
import one.edee.babylon.export.dto.ExportResult;
@@ -11,6 +14,7 @@
1114
import one.edee.babylon.snapshot.TranslationSnapshotWriteContract;
1215
import one.edee.babylon.util.AntPathResourceLoader;
1316
import one.edee.babylon.util.PathUtils;
17+
import org.jetbrains.annotations.NotNull;
1418
import org.springframework.util.StringUtils;
1519

1620
import java.io.File;
@@ -21,6 +25,9 @@
2125
import java.util.function.Function;
2226
import java.util.stream.Collectors;
2327

28+
import static com.google.cloud.translate.Translate.TranslateOption.sourceLanguage;
29+
import static com.google.cloud.translate.Translate.TranslateOption.targetLanguage;
30+
2431
/**
2532
* Performs the export phase that generates translation sheets.
2633
*/
@@ -56,8 +63,8 @@ public void walkPathsAndWriteSheets(List<String> patternPaths,
5663
String spreadsheetId,
5764
Path snapshotPath,
5865
boolean combineSheets,
59-
String deeplApiKey) {
60-
walkPathsAndWriteSheets(patternPaths, translationLangs, spreadsheetId, snapshotPath, Collections.emptyList(), combineSheets, deeplApiKey, null);
66+
String translatorApiKey) {
67+
walkPathsAndWriteSheets(patternPaths, translationLangs, spreadsheetId, snapshotPath, Collections.emptyList(), combineSheets, translatorApiKey, null);
6168
}
6269

6370
/**
@@ -68,15 +75,15 @@ public void walkPathsAndWriteSheets(List<String> patternPaths,
6875
* @param spreadsheetId id of GSheets spreadsheet, must be empty
6976
* @param snapshotPath path to the translation snapshot file
7077
* @param lockedCellEditors list of Google account emails, these account will have the permission to edit locked cells
71-
* @param deeplApiKey
78+
* @param translatorApiKey
7279
*/
7380
public void walkPathsAndWriteSheets(List<String> patternPaths,
7481
List<String> translationLangs,
7582
String spreadsheetId,
7683
Path snapshotPath,
7784
List<String> lockedCellEditors,
7885
boolean combineSheets,
79-
String deeplApiKey,
86+
String translatorApiKey,
8087
String defaultLang) {
8188
warnDuplicatePaths(patternPaths);
8289

@@ -109,11 +116,25 @@ public void walkPathsAndWriteSheets(List<String> patternPaths,
109116
original.add(new TranslationSheet(COMBINING_SHEET_NAME,combine));
110117
}
111118

119+
Map<String, List<String>> changed = translateTextsByExternalTool(translatorApiKey, defaultLang, result);
120+
121+
uploadTranslations(result, spreadsheetId, lockedCellEditors, changed);
122+
123+
updateSnapshotAndWriteToDisk(this.snapshot, result, snapshotPath);
124+
125+
List<Integer> prevSheetIds = prevSheets.stream().map(ASheet::getId).collect(Collectors.toList());
126+
deleteOldSheets(prevSheetIds, spreadsheetId);
127+
}
128+
129+
@NotNull
130+
private static Map<String, List<String>> translateTextsByExternalTool(String translatorApiKey, String defaultLang, ExportResult result) {
112131
Map<String, List<String>> changed = new HashMap<>();
113132

114-
if (deeplApiKey != null) {
133+
if (translatorApiKey != null) {
115134
try {
116-
Translator translator = new Translator(deeplApiKey);
135+
// Translator translator = new Translator(translatorApiKey);
136+
//noinspection deprecation
137+
Translate translate = TranslateOptions.newBuilder().setApiKey(translatorApiKey).build().getService();
117138
for (TranslationSheet sheet : result.getSheets()) {
118139
log.info("Translating sheet " + sheet.getSheetName());
119140

@@ -136,8 +157,8 @@ public void walkPathsAndWriteSheets(List<String> patternPaths,
136157
}
137158

138159
if (StringUtils.hasText(original)) {
139-
TextResult translatedText = translator.translateText(original, defaultLang, lang);
140-
toChange.put(l, translatedText.getText());
160+
String translatedText = getTranslatedTextByGoogle(defaultLang, translate, original, lang);
161+
toChange.put(l, translatedText);
141162

142163
changed
143164
.computeIfAbsent(sheet.getSheetName(), key -> new LinkedList<>())
@@ -157,15 +178,23 @@ public void walkPathsAndWriteSheets(List<String> patternPaths,
157178
log.error(e.getMessage(), e);
158179
}
159180
}
181+
return changed;
182+
}
160183

161-
uploadTranslations(result, spreadsheetId, lockedCellEditors, changed);
184+
private static String getTranslatedTextByDeepl(String defaultLang, Translator translator, String original, String lang) throws DeepLException, InterruptedException {
185+
return translator.translateText(original, defaultLang, lang).getText();
186+
}
162187

163-
updateSnapshotAndWriteToDisk(this.snapshot, result, snapshotPath);
188+
private static String getTranslatedTextByGoogle(String defaultLang, Translate translate, String original, String lang) {
164189

165-
List<Integer> prevSheetIds = prevSheets.stream().map(ASheet::getId).collect(Collectors.toList());
166-
deleteOldSheets(prevSheetIds, spreadsheetId);
190+
return translate.translate(
191+
original,
192+
sourceLanguage(defaultLang),
193+
targetLanguage(lang))
194+
.getTranslatedText();
167195
}
168196

197+
169198
private void warnDuplicatePaths(List<String> patternPaths) {
170199
List<String> duplicatePaths = detectDuplicatePatternPaths(patternPaths);
171200
if (!duplicatePaths.isEmpty()) {

src/main/java/one/edee/babylon/maven/BabylonExpImpBaseMojo.java

+5-5
Original file line numberDiff line numberDiff line change
@@ -14,7 +14,7 @@ public abstract class BabylonExpImpBaseMojo extends AbstractMojo {
1414
public static final String CONFIG_FILE_PARAM = "config.file";
1515
public static final String GOOGLE_SHEET_ID_PARAM = "google.sheet.id";
1616
public static final String COMBINE_SHEET_PARAM = "combine.sheets";
17-
public static final String DEEPL_API_KEY_PARAM = "deepl.api.key";
17+
public static final String TRANSLATOR_API_KEY_PARAM = "translator.api.key";
1818

1919
/**
2020
* File name and relative path to the Json configuration file.
@@ -35,10 +35,10 @@ public abstract class BabylonExpImpBaseMojo extends AbstractMojo {
3535
private Boolean combineSheets;
3636

3737
/**
38-
* Deepl api key.
38+
* Translator api key (Google/Deepl).
3939
*/
40-
@Parameter(property = DEEPL_API_KEY_PARAM)
41-
private String deeplApiKey;
40+
@Parameter(property = TRANSLATOR_API_KEY_PARAM)
41+
private String translatorApiKey;
4242

4343
@Override
4444
public void execute() {
@@ -50,7 +50,7 @@ private String[] getArguments() {
5050
arg[0] = getAction().name();
5151
arg[1] = this.configFileName;
5252
arg[2] = this.googleSheetId;
53-
arg[3] = this.deeplApiKey;
53+
arg[3] = this.translatorApiKey;
5454
arg[4] = String.valueOf(this.combineSheets);
5555

5656
return arg;

src/main/java/one/edee/babylon/properties/TsFileActiveRecord.java

+5-4
Original file line numberDiff line numberDiff line change
@@ -21,7 +21,7 @@
2121
*/
2222
public class TsFileActiveRecord extends FileActiveRecord {
2323

24-
private static final String DEFAULT_LANG_DEF_IMPORT = "import type { LangDef } from '@edeeone/i18n/LangDef';";
24+
private static final String DEFAULT_LANG_DEF_IMPORT = "import type { LangDef } from '@edeeone/juan-core/i18n/LangDef';";
2525

2626
/**
2727
* Loads properties from file by specified reader.
@@ -75,7 +75,8 @@ public void save(Writer writer, String primaryPropFilePath, String mutation) thr
7575
}
7676

7777
bufferedWriter.newLine();
78-
bufferedWriter.write("const " + propertyListDefName + firstLetterToUppercase(mutation) + " : LangDef<typeof " + propertyListDefName + "> = {");
78+
String finalLocalizationName = firstLetterToUppercase(mutation);
79+
bufferedWriter.write("const " + propertyListDefName + finalLocalizationName + ": LangDef<typeof " + propertyListDefName + "> = {");
7980
bufferedWriter.newLine();
8081

8182
synchronized (this) {
@@ -84,14 +85,14 @@ public void save(Writer writer, String primaryPropFilePath, String mutation) thr
8485
AbstractProperty value = entry.getValue();
8586
String keyDelimiter = key.matches("\\[.*]") ? "" : "'";
8687

87-
bufferedWriter.write(" " + keyDelimiter + key + keyDelimiter +": "+ value.getQuotedValue() + ",");
88+
bufferedWriter.write(" " + keyDelimiter + key + keyDelimiter +": "+ value.getQuotedValue() + ",");
8889
bufferedWriter.newLine();
8990
}
9091
}
9192

9293
bufferedWriter.write("};");
9394
bufferedWriter.newLine();
94-
bufferedWriter.write("export default "+baseName+";");
95+
bufferedWriter.write("export default "+finalLocalizationName+";");
9596

9697
bufferedWriter.flush();
9798
}

0 commit comments

Comments
 (0)