-
Notifications
You must be signed in to change notification settings - Fork 125
/
Copy pathcomparator.html
1193 lines (1064 loc) · 36.2 KB
/
comparator.html
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
<!DOCTYPE html>
<!-- 用于对比当前已有中文JSON和新版本的英文JSON,快速得到新版本英文JSON中增加的内容,这样就可以快速进行翻译 -->
<html lang="zh-CN">
<head>
<title>自动翻译脚本</title>
<!-- ====Meta==== -->
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<!-- ====Script Libraries==== -->
<script src="https://cdn.jsdelivr.net/npm/vue/dist/vue.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script>
<script src="https://cdn.bootcdn.net/ajax/libs/crypto-js/4.0.0/crypto-js.js"></script>
<script src="https://cdn.jsdelivr.net/npm/axios/dist/axios.min.js"></script>
<!-- ====Others Libraries==== -->
<link rel="icon" type="images/x-icon"
href="https://upload.wikimedia.org/wikipedia/commons/d/db/Google_Translate_Icon.png?20160129085523">
<!-- ====Style==== -->
<style>
body{
font-family: 'Arial', sans-serif;
}
li{
list-style: none;
}
fieldset{
padding: 0.5em;
margin: 1px;
}
button:hover{
cursor: pointer;
}
header{
height: 32px;
}
.header-anchor{
display: inline-block;
padding: 0;
margin: 0;
height: 100%;
}
.header-anchor-logo{
display: inline-block;
padding: 1px;
height: 30px;
}
.APIConfig{
display: flex;
flex-direction: column;
gap: 5px;
}
.input-group{
display: flex;
align-items: center;
}
.input-group label{
width: 200px;
margin-right: 10px;
}
.APIConfig button{
width: 200px;
}
.introduction{
background-color: #F5F5F5;
}
.introduction-list,
.introduction-list-li{
padding: 0;
margin: 0 0 0 4px;
list-style: decimal;
}
.operation{
min-height: 75vh;
display: grid;
grid-template-columns: 3fr 1fr;
}
.console{
display: grid;
grid-template-rows: 2em 2em 2em 2em 1fr auto;
gap: 4px;
}
.introduction{
padding-left: 15px;
}
.console-btns{
display: grid;
grid-template-columns: repeat(2, 1fr);
gap: 8px;
}
.console-btns2{
display: grid;
grid-template-columns: repeat(2, 1fr);
gap: 8px;
height: 2em;
}
.input-group{
display: flex;
align-items: center;
margin-bottom: 4px;
}
.input-group label{
width: 230px;
}
#sp{
margin-right: 6px;
}
#textJson{
width: 100%;
height: 95%;
overflow: auto;
margin-top: 10px;
resize: none;
padding: 4px;
box-sizing: border-box;
}
summary{
font-weight: bold;
cursor: pointer;
}
.diff-green{
color: green;
}
.diff-red{
color: red;
}
.diff-blue{
color: blue;
}
.error-message{
margin-left: 10px;
color: red;
font-weight: bold;
}
.save-message{
margin-left: 10px;
font-weight: bold;
}
.save-message.success{
color: green;
}
.save-message.error{
color: red;
}
@media (max-width: 1001px){
.operation{
display: grid;
grid-template-columns: 2fr 1fr;
}
}
</style>
</head>
<body>
<header class="header">
<a class="header-anchor" href="https://github.com/yk47g/gitkraken-chinese" target="_blank">
<img class="header-anchor-logo" src="https://github.githubassets.com/assets/GitHub-Mark-ea2971cee799.png"
alt="关于我们的GitHub项目">
</a>
</header>
<div id="app">
<form @submit.prevent="saveKeys">
<fieldset class="APIConfig">
<legend>API 配置</legend>
<!-- 下拉菜单选择API -->
<div class="input-group">
<label for="apiSelector">选择翻译 API:</label>
<select id="apiSelector" v-model="selectedApi">
<option value="openai">OpenAI</option>
<option value="deepseek">DeepSeek</option>
<option value="youdao">有道智云</option>
</select>
</div>
<!-- OpenAI API 配置 -->
<div v-if="selectedApi === 'openai'">
<div class="input-group">
<label for="openaiApiKey">OpenAI API 密钥:</label>
<input type="text" id="openaiApiKey" v-model="openai.apiKey" placeholder="以 sk- 开头">
</div>
<div class='input-group'>
<label for='modelSelector'>选择模型:</label>
<select id='modelSelector' v-model='openai.model'>
<option value='gpt-4o-mini'>4o-mini</option>
<option value='gpt-4o'>4o</option>
<option value='o1-mini'>o1-mini (不建议)</option>
</select>
</div>
</div>
<!-- DeepSeek API 配置 -->
<div v-if="selectedApi === 'deepseek'">
<div class="input-group">
<label for="deepseekApiKey">DeepSeek API 密钥:</label>
<input type="text" id="deepseekApiKey" v-model="deepseek.apiKey" placeholder="以 sk- 开头">
</div>
<div class='input-group'>
<label for='deepseekModel'>选择模型:</label>
<select id='deepseekModel' v-model='deepseek.model'>
<option value='deepseek-chat'>V3</option>
<option value='deepseek-reasoner'>R1</option>
</select>
</div>
</div>
<!-- 有道 API 配置 -->
<div v-if="selectedApi === 'youdao'">
<div class="input-group">
<label for="appKey">有道AppKey:</label>
<input type="text" id="appKey" v-model="youdao.appKey" placeholder="也就是应用ID">
</div>
<div class="input-group">
<label for="appSecret">有道AppSecret:</label>
<input type="text" id="appSecret" v-model="youdao.appSecret" placeholder="也就是应用秘钥">
</div>
</div>
<div class="input-group">
<button type="submit">保存</button>
<span v-if="saveMessage" :class="['save-message', saveMessageType]">
{{ saveMessage }}
</span>
</div>
</fieldset>
</form>
<div class="operation">
<fieldset class="console">
<legend>控制台</legend>
<div class="console-btns">
<button @click="compare">对比</button>
<button @click="autoTranslate">自动翻译</button>
</div>
<!-- 上传旧版英文文件 -->
<div class="input-group">
<label for="oldEnFile">上传旧版英文文件:</label>
<input type="file" id="oldEnFile" @change="loadFile('oldEN')">
<span v-if="showOldEnError" class="error-message">
需要上传旧版英文文件
</span>
</div>
<!-- 上传新版英文文件 -->
<div class="input-group">
<label for="newEnFile">上传新版英文文件:</label>
<input type="file" id="newEnFile" @change="loadFile('newEn')">
<span v-if="showNewEnError" class="error-message">
需要上传新版英文文件
</span>
</div>
<!-- 上传旧版中文文件 -->
<div class="input-group">
<label for="oldZhFile">上传旧版翻译文件:</label>
<input type="file" id="oldZhFile" @change="loadFile('oldZh')">
<span v-if="showOldZhError" class="error-message">
需要上传旧版翻译文件
</span>
</div>
<div class="console-textarea">
<label for="textJson"></label>
<textarea id="textJson"></textarea>
</div>
<div class="console-btns2">
<button @click="exportJson">导出JSON文件</button>
<button @click="copyToClipboard">复制到剪切板</button>
</div>
</fieldset>
<fieldset class="introduction">
<legend>使用说明</legend>
<b>对于有提供支持的API的用户:</b>
<ol class="introduction-list">
<li class="introduction-list-li">
填写API配置并保存
</li>
<li class="introduction-list-li">
上传旧版英文文件 (./原语言文件备份/strings.json), 新版英文文件 (具体位置见 ./README.md 中要替换的语言文件位置)
和旧版翻译文件 (./strings_x.x.x.json) 并点击 [对比] 按钮得到差异内容
</li>
<li class="introduction-list-li">
点击 [自动翻译] 按钮翻译并等待弹出"翻译完成"提示框
</li>
<li class="introduction-list-li">
导出并覆盖 strings.json 文件
</li>
<li class="introduction-list-li">
重启 GitKraken
</li>
</ol>
<b>对于没有API的用户</b>
<ol class="introduction-list">
<li class="introduction-list-li">
上传旧版英文文件 (./原语言文件备份/strings.json), 新版英文文件 (具体位置见 ./README.md 中要替换的语言文件位置)
和旧版翻译文件 (./strings_x.x.x.json) 并点击 [对比] 按钮得到差异内容
</li>
<li class="introduction-list-li">
复制并翻译文本框内的文件
</li>
<li class="introduction-list-li">
将翻译好的内容使用
<a href="https://www.bejson.com/" target="_blank">
格式化工具
</a>
整理
</li>
<li class="introduction-list-li">
重启 GitKraken
</li>
</ol>
<details>
<summary><b>可能出现的问题和解决建议</b></summary>
<a href="https://github.com/yk47g/gitkraken-chinese/issues">
报告问题
</a>
<ol class="introduction-list">
<li class="introduction-list-li">
使用API翻译后并没有插入新增内容
<ul>
<li style="list-style: circle">
确认使用了VS Code 的 Live Server 或类似的服务
</li>
<li style="list-style: circle">
检查API是否正确配置(有效性,模型访问权限)
</li>
</ul>
</li>
<li class="introduction-list-li">
按下[自动翻译]没反应
<ul>
<li style="list-style: circle">
在跳出任何错误弹窗前或控制台更新 JSON 翻译好的内容前, 都应该在正常运行,耐心等待即可
</li>
</ul>
</li>
<li class="introduction-list-li">
按下[自动翻译]后提示翻译失败
<ul>
<li style="list-style: circle">
检查 API 是否正确配置(有效性,模型访问权限)
</li>
<li style="list-style: circle">
如果选择的是 DeepSeek API, 可能是灯塔国又发力了. 请检查 DeepSeek 官网-产品-
<a href="https://status.deepseek.com/" target="_blank">服务状态</a>,
或稍后重试
</li>
<li style="list-style: circle">
如果还是不行, 可以尝试报告问题, 有可能是我的问题(因为我也没测试过, 新增该 API 时他们的 API 还在维护)
</li>
</ul>
</li>
</ol>
</details>
<details>
<summary><b>OpenAI API的申请步骤</b></summary>
<ol class="introduction-list">
<li class="introduction-list-li">
进入 <a href="https://platform.openai.com/api-keys" target="_blank">OpenAI 官方网站</a>
</li>
<li class="introduction-list-li">注册或登录</li>
<li class="introduction-list-li">
在顶栏左上角新建 Project (可选)或使用用户密钥(可选, 不推荐), 之后在顶栏右上角选择 "Dashboard", 随后侧边栏选择
"API Keys"
</li>
<li class="introduction-list-li">通过 "+ Create New secret key" 按照提示新建一个密钥</li>
<li class="introduction-list-li">
<b style="color: #F00">请保管好你的密钥, 平台将不会再次展示你的密钥,
忘记则意味着你需要重新创建密钥并删除旧的密钥</b>
</li>
<li class="introduction-list-li">
复制以 sk- 开头的API密钥到配置中, 建议使用 "gpt-4o-mini" 模型, 足以保证翻译效果, 且免费限额高还便宜
</li>
</ol>
<p class="hint">
<a href="https://platform.openai.com/docs/models/gpt-4o-mini" target="_blank">收费标准</a>
</p>
</details>
<details>
<summary><b>DeepSeek API的申请步骤</b></summary>
<ol class="introduction-list">
<li class="introduction-list-li">
访问 DeepSeek <a href="https://platform.deepseek.com/api_keys" target="_blank">API 开放平台</a>
</li>
<li class="introduction-list-li">注册/登录后进入API keys管理页面</li>
<li class="introduction-list-li">点击"创建 API key"生成新密钥</li>
<li class="introduction-list-li">
<b style="color: #F00">请保管好你的密钥, 平台将不会再次展示你的密钥,
忘记则意味着你需要重新创建密钥并删除旧的密钥</b>
</li>
<li class="introduction-list-li">复制以 sk- 开头的API密钥到配置中</li>
</ol>
<p class="hint">
<a href="https://api-docs.deepseek.com/zh-cn/quick_start/pricing/" target="_blank">收费标准</a>
</p>
</details>
<details>
<summary><b>有道API的申请步骤</b></summary>
<ol class="introduction-list">
<li class="introduction-list-li">
进入 <a href="https://ai.youdao.com/console/#/service-singleton/text-translation"
target="_blank">有道智云控制台</a>
</li>
<li class="introduction-list-li">注册或登录</li>
<li class="introduction-list-li">在侧边栏选择 "自然语言翻译服务/文本翻译"</li>
<li class="introduction-list-li">找到 "文本翻译/应用概览/创建应用"</li>
<li class="introduction-list-li">创建应用并复制 AppKey 和 AppSecret 到配置中</li>
</ol>
<p class="hint">
<a href="https://ai.youdao.com/price-center.s#servicename=fanyi-text" target="_blank">收费标准</a>
</p>
</details>
</fieldset>
</div>
<div id="sp">
<div>
<b>差异项 ({{diffItems.length}})
<span style="color: green">新增</span>
<span style="color: red"> 删减</span>
<span style="color: blue">改动</span>
</b>
</div>
<ul>
<li v-for="(diff, index) in diffItems" :key="index"
:class="{'diff-green': diff.color === 'green',
'diff-red': diff.color === 'red',
'diff-blue': diff.color === 'blue'}">
<!-- 改动时显示旧值->新值 -->
<span v-if="diff.type==='changed'">
{{index + 1}}. {{diff.key}} ({{diff.oldValue}} => {{diff.newValue}})
</span>
<!-- 新增/删减只显示key -->
<span v-else-if="diff.type==='added'">
{{index + 1}}. {{diff.key}}
</span>
<span v-else-if="diff.type==='removed'">
{{index + 1}}. {{diff.key}}
</span>
</li>
</ul>
</div>
</div>
</body>
</html>
<script>
const app = new Vue({
el: '#app',
data() {
return {
/**
* 文件内容解析(key/value)
*/
// 新版英文
menuStringsNewEn: [],
// 旧版中文
menuStringsOldZh: [],
// 旧版英文
menuStringsOldEn: [],
// 新版英文文件原始行内容(含空行/大括号/逗号)
newFileRawLines: [],
// 结果差异
diffItems: [],
// 提示
showOldEnError: false,
showNewEnError: false,
showOldZhError: false,
saveMessage: '',
saveMessageType: 'success',
/**
* API 配置
*/
// 默认 API
selectedApi: 'openai',
// OpenAI API 配置
openai: {
apiKey: '',
// 默认模型
model: 'gpt-4o-mini',
temperature: 0.7,
},
// DeepSeek API 配置
deepseek: {
apiKey: '',
// 默认模型
model: 'deepseek-chat',
temperature: 0.7,
},
// 有道 API 配置
youdao: {
appKey: '',
appSecret: '',
salt: (new Date).getTime(),
from: 'en',
to: 'zh-CHS',
},
// 固定翻译词汇
fixedTranslations: [
{term: "Cherry Pick", translation: "拣选"},
{term: "Email", translation: "邮箱"},
{term: "Email Address", translation: "邮箱"},
{term: "Filter", translation: "过滤器"},
{term: "Fork", translation: "分支"},
{term: "GitKraken Desktop", translation: "GitKraken 桌面版"},
{term: "Graph", translation: "图"},
{term: "Pull Request", translation: "拉取请求"},
{term: "Rebase", translation: "变基"},
{term: "Repo", translation: "仓库"},
{term: "Solo", translation: "单独显示"},
{term: "Stage", translation: "暂存"},
{term: "Stash", translation: "贮藏"}
],
// 需要保留的专有名词数组
keepTranslations: [
"Launchpad",
"WIP",
"Gitflow"
]
}
},
methods: {
/**
* 导出JSON文件
*/
exportJson() {
const content = document.getElementById("textJson").value;
if (!content.trim()) {
alert("没有可以导出的内容");
return;
}
const blob = new Blob([content], {type: "application/json"});
const link = document.createElement("a");
link.href = URL.createObjectURL(blob);
link.download = "strings.json";
link.click();
URL.revokeObjectURL(link.href);
},
/**
* 复制到剪切板
*
* @returns {Promise<void>} 标明方法类型,不用管
*/
async copyToClipboard() {
const content = document.getElementById("textJson").value;
if (!content.trim()) {
alert("没有可以复制的内容");
return;
}
try {
await navigator.clipboard.writeText(content);
} catch (e) {
alert("复制失败,请手动复制");
}
},
/**
* 读取文件
* @param type 'newEn' (新版英文) | 'oldZh' (旧版中文) | 'oldEN' (旧版英文)
*/
loadFile(type) {
this.showOldEnError = false;
let inputId;
switch (type) {
case 'newEn':
inputId = 'newEnFile';
break;
case 'oldZh':
inputId = 'oldZhFile';
break;
case 'oldEN':
inputId = 'oldEnFile';
break;
}
const fileInput = document.getElementById(inputId);
if (!fileInput.files[0]) {
alert("未选择文件");
return;
}
const reader = new FileReader();
reader.onload = e => {
const rawText = e.target.result;
try {
// 用 JSON.parse 获取 key-value
const jsonObj = JSON.parse(rawText);
if (type === 'newEn') {
this.menuStringsNewEn = [];
this.newFileRawLines = rawText.split(/\r?\n/);
this.processJsonKeys(jsonObj, 'newEn');
} else if (type === 'oldZh') {
this.menuStringsOldZh = [];
this.processJsonKeys(jsonObj, 'oldZh');
} else {
this.menuStringsOldEn = [];
this.processJsonKeys(jsonObj, 'oldEN');
}
} catch (e) {
alert("文件内容无效,无法解析为JSON");
}
};
reader.readAsText(fileInput.files[0]);
},
/**
* 将JSON里的 languageOption/menuStrings/strings 提取为数组
* @param json
* @param fileType
*/
processJsonKeys(json, fileType) {
["languageOption", "menuStrings", "strings"].forEach(scope => {
if (!json[scope]) return;
Object.keys(json[scope]).forEach(key => {
const item = {key, value: json[scope][key], scope};
if (fileType === 'newEn') {
this.menuStringsNewEn.push(item);
} else if (fileType === 'oldZh') {
this.menuStringsOldZh.push(item);
} else {
this.menuStringsOldEn.push(item);
}
});
});
},
/**
* 使用新英文对比旧英文
* 检测新增,删减,改动(key相同但值发生变化)
*/
compare() {
// 错误提示
this.showNewEnError = false;
this.showOldEnError = false;
this.showOldZhError = false;
if (!this.menuStringsNewEn.length) {
this.showNewEnError = true;
return;
}
if (!this.menuStringsOldEn.length) {
this.showOldEnError = true;
return;
}
if (!this.menuStringsOldZh.length) {
this.showOldZhError = true;
return;
}
this.diffItems = [];
// 新增
this.menuStringsNewEn.forEach(newItem => {
const oldItem = this.menuStringsOldEn.find(o => o.key === newItem.key && o.scope === newItem.scope);
if (!oldItem) {
this.diffItems.push({
key: newItem.key,
scope: newItem.scope,
color: 'green',
type: 'added',
newValue: newItem.value
});
}
});
// 删减
this.menuStringsOldEn.forEach(oldItem => {
const newItem = this.menuStringsNewEn.find(n => n.key === oldItem.key && n.scope === oldItem.scope);
if (!newItem) {
this.diffItems.push({
key: oldItem.key,
scope: oldItem.scope,
color: 'red',
type: 'removed',
oldValue: oldItem.value
});
}
});
// 改动
this.menuStringsNewEn.forEach(newItem => {
const oldItem = this.menuStringsOldEn.find(o => o.key === newItem.key && o.scope === newItem.scope);
if (oldItem) {
if (!this.isSameString(oldItem.value, newItem.value)) {
this.diffItems.push({
key: newItem.key,
scope: newItem.scope,
color: 'blue',
type: 'changed',
oldValue: oldItem.value,
newValue: newItem.value
});
}
}
});
if (!this.diffItems.length) {
alert("未发现差异");
}
this.autoGen();
},
isSameString(a, b) {
// 逻辑层面判断字符串是否相同
return a === b;
},
/**
* 转义 JSON 值
* @param str JSON 值
* @return {string} 转义后的值
*/
escapeJsonValue(str) {
if (typeof str !== 'string') {
str = String(str);
}
return JSON.stringify(str).slice(1, -1);
},
/**
* 自动生成JSON
* 基于旧版中文文件做合并,但行顺序和空行以新版英文文件为模板重构
* 差异项:
* -added:新增=>输出中文翻译或保留新版英文字符(若未翻译)
* -removed:删减
* -changed: 替换为新版英文(深度对比时)
* -未出现在diffItems的=>保留旧版中文翻译
*/
autoGen() {
// 1. 把旧版中文转为字典
const oldCnDict = {
languageOption: {},
menuStrings: {},
strings: {}
};
this.menuStringsOldZh.forEach(item => {
oldCnDict[item.scope][item.key] = item.value;
});
// 2. 把差异项变成 map
const diffMap = {};
this.diffItems.forEach(d => {
diffMap[d.scope + "\u0000" + d.key] = d;
});
let currentScope = null;
// 判断是不是在进入作用域
const scopePattern = /^\s*"?(languageOption|menuStrings|strings)"?\s*:\s*\{\s*$/;
// 判断是不是关闭了当前作用域
const scopeClosePattern = /^\s*\}\s*,?\s*$/;
// 匹配键值行
const keyValuePattern = /^(\s*)"((?:\\.|[^"\\])*)"\s*:\s*"((?:\\.|[^"\\])*)"\s*(,?)\s*$/;
const resultLines = [];
for (let i = 0; i < this.newFileRawLines.length; i++) {
const line = this.newFileRawLines[i];
// 判断有没有匹配到“进入作用域”
const scopeOpenMatch = line.match(scopePattern);
if (scopeOpenMatch) {
currentScope = scopeOpenMatch[1];
resultLines.push(line);
continue;
}
// 判断有没有匹配到“退出作用域”
const scopeCloseMatch = line.match(scopeClosePattern);
if (scopeCloseMatch) {
currentScope = null; // 退出当前作用域
resultLines.push(line);
continue;
}
const kvMatch = line.match(keyValuePattern);
if (!kvMatch) {
resultLines.push(line);
continue;
}
const leadingSpaces = kvMatch[1];
const rawKey = kvMatch[2];
const rawVal = kvMatch[3];
const trailingComma = kvMatch[4];
let parsedKey, parsedVal;
try {
parsedKey = JSON.parse(`"${rawKey}"`);
parsedVal = JSON.parse(`"${rawVal}"`);
} catch (e) {
resultLines.push(line);
continue;
}
let scopeName = currentScope || 'strings';
// 根据 diffMap 判断该 key 在当前作用域是否被增删改
const diffKey = scopeName + "\u0000" + parsedKey;
const diffInfo = diffMap[diffKey];
if (diffInfo) {
if (diffInfo.type === 'removed') {
// 不输出此行
} else if (diffInfo.type === 'added' || diffInfo.type === 'changed') {
// 如果存在翻译结果,则使用翻译结果,否则使用原始 newValue
const finalValue = diffInfo.translatedValue ? diffInfo.translatedValue : diffInfo.newValue;
const escapedVal = this.escapeJsonValue(finalValue);
const newLine = `${leadingSpaces}"${this.escapeJsonValue(parsedKey)}": "${escapedVal}"${trailingComma}`;
resultLines.push(newLine);
} else {
// 大概应该可能差不多不会跳到这里吧ww
}
} else {
// 无差异 => 保留旧版翻译
const oldVal = oldCnDict[scopeName][parsedKey];
const finalVal = (typeof oldVal === 'string') ? oldVal : parsedVal;
const escapedVal = this.escapeJsonValue(finalVal);
const newLine = `${leadingSpaces}"${this.escapeJsonValue(parsedKey)}": "${escapedVal}"${trailingComma}`;
resultLines.push(newLine);
}
}
document.getElementById('textJson').value = resultLines.join('\n');
},
/**
* 自动翻译
*/
async autoTranslate() {
this.showNewEnError = false;
this.showOldEnError = false;
this.showOldZhError = false;
// 验证API配置
if (this.selectedApi === 'openai') {
if (!this.openai.apiKey) {
alert("请填写OpenAI API密钥");
return;
}
} else if (this.selectedApi === 'deepseek') {
if (!this.deepseek.apiKey) {
alert("请填写DeepSeek API密钥");
return;
}
} else if (this.selectedApi === 'youdao') {
if (!this.youdao.appKey || !this.youdao.appSecret) {
alert("请填写有道AppKey和AppSecret");
return;
}
}
if (!this.diffItems.length) {
this.compare();
}
const toTranslate = this.diffItems.filter(d => (d.type === 'added' || d.type === 'changed'));
if (!toTranslate.length) {
alert("没有需要翻译的差异项");
return;
}
let translationSucceeded = false;
// 分批翻译
const batchSize = 20;
for (let i = 0; i < toTranslate.length; i += batchSize) {
const batch = toTranslate.slice(i, i + batchSize);
const query = batch.map(item => item.newValue).join('\n');
let translations = [];
if (this.selectedApi === 'openai') {
translations = await this.translateOpenAI(query);
} else if (this.selectedApi === 'deepseek') {
translations = await this.translateDeepSeek(query);
} else if (this.selectedApi === 'youdao') {
translations = await this.translateYoudao(query);
}
// 检查翻译结果是否有效
if (translations.length === 0 || translations.every(t => !t.trim())) {
alert("翻译失败: 未返回有效翻译结果。请检查API配置和网络连接");
continue;
} else {
translationSucceeded = true;
}
// 回写翻译
batch.forEach((item, index) => {
if (translations[index]) {
item.translatedValue = translations[index];
}
});
await this.sleep(1500);
}
if (translationSucceeded) {
this.autoGen();
alert('翻译并整理完成');
}
},
/**
* 将固定翻译词汇数组格式化为字符串
* @returns {string} 格式化后的字符串
*/
formatFixedTranslations() {
return this.fixedTranslations.map(item => `- ${item.term}: "${item.translation}"`).join("\n");
},
/**
* 将需要保留的专有名词数组格式化为字符串
* @returns {string} 格式化后的字符串
*/
formatKeepTranslations() {
return this.keepTranslations.map(term => `- ${term}`).join("\n");
},
/**
* 调用 OpenAI 翻译
*
* @param query 翻译内容
* @return {Promise<string[]|*[]>} 翻译结果
*/
async translateOpenAI(query) {
if (!this.openai.apiKey) {
console.error("OpenAI API 密钥未配置");
return [];
}
const messages = [
{
role: "system",
content: `You are a translation expert specializing in Git operation terminology. Please translate the following Git-related content from English to Chinese.
The following terms should be translated using fixed translations:
${this.formatFixedTranslations()}
The following terms should be kept in their original form without translation:
${this.formatKeepTranslations()}
Please note that you should only return the translated text, without engaging in conversation with the user or adding any additional content.`
},
{role: "user", content: query}
];
console.log(messages); // 这个最好是留着,方便以后新增词汇查看有没有问题
const data = {