forked from Bistutu/FluentRead
-
Notifications
You must be signed in to change notification settings - Fork 0
/
userscripts.js
2061 lines (1866 loc) · 84.6 KB
/
userscripts.js
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
// ==UserScript==
// @name 流畅阅读
// @license GPL-3.0 license
// @namespace https://fr.unmeta.cn/
// @version 1.31
// @description 基于上下文语境的人工智能翻译引擎,为部分网站提供精准翻译,让所有人都能够拥有基于母语般的阅读体验。程序Github开源:https://github.com/Bistutu/FluentRead,欢迎 star。
// @author ThinkStu
// @match *://*/*
// @icon data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAMgAAADICAYAAACtWK6eAAAAAXNSR0IArs4c6QAADn5JREFUeF7tnT+OJUkRxrsPgLQYYK+QcEBrrbF402Nwgx0kcDjCHmFmjjB7AYSDg4E4wfZ4uxJYaHEQs9iMgcEBHuTrl7PZr6sqIr78n/E9aaSZeZlZlV/ELyMiq17V7Q0/VIAK7CpwS22oABXYV4CA0DuowIECBITuQQUICH2ACmAKMIJgurGXEwUIiBNDc5qYAgQE0429nChAQJwYmtPEFCAgmG7s5UQBAuLE0JwmpgABwXRjLycKEBAnhuY0MQUICKYbezlRgIA4MTSniSlAQDDd2MuJAgTEiaE5TUwBAoLpxl5OFCAgTgzNaWIKEBBMN/ZyogABcWJoThNTgIBgurGXEwUIiBNDc5qYAgQE0429nChAQJwYmtPEFCAgmG7s5UQBAuLE0JwmpgABwXRjLycKEBAnhuY0MQUICKYbezlRgIA4MTSniSlAQDDd2MuJAgTEiaE5TUwBAoLpxl5OFCAgTgzNaWIKEBBMN/ZyogABcWJoThNTgIBgurGXEwUIiBNDc5qYAgQE0429nChAQJwYmtPEFCAgmG7aXndJw/j3ZwedY5v7nTZvr/4/tNtrqz1HtjtQgICUcY/o2C8vw6VglDmCbpQAS4SI8Og0O2xFQOwiBucPf0Ik6AWC9awjOITGqBwBkQULEPSODPJZ2lqkkeaVrauv1gTkqb3TdGmWCJHrtREYwnKlJAF5EMQjFHtQMR1LlPEMyIy1RG6kQPq//n8nt5HFIyCxpmiaPt394kePnPPusx9/+Pezq+/CF2+/fv+o/f03/37876vvEc839gmghI8rW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QEpBUpc2ULoL/ZwtgxnGqFrfFlPOBfxFW8HJzxVOrU1jxUAKZF2XdcqHmEpBUXcnRrqgh+66qwCSBpNwt+1z7o90s38cGjUCB37xegQ9MqJFHEK00eMFYp0jT9ZHwotjRlhiavjrKlYCkRu+pRqthwYcXKrRZBrRy8NyrVTvL38x4gpWS0YXIDhBZDUmMj9XVJkuf4+jTTq93ZYD7LRPn0q/LNC6ZKUfi5RY0jarx5BtuZfM6pITpV+H6NPmr9f90/rguD46adEzSD5h6tosSWGR0BaRxWLE47WNvuFPaNNyHo+3gGJeoXVON3mtOq4Unv3UKTGJCBPXTvC0iKXHwUsQrFjCQIiu2isWVYCJgUiKDDrtrVsvcwWBMQu4IzAMELY7XzuQUBA4TZ2lOKuUs9IE0EIO2Tx74wOGTYmIBniKbpev7U2dLnerg3/t7dlu+fcKQBMkRSGQJsQEFQ59nOhAAFxYWZOElWAgKDKsZ8LBQiICzNzkqgCBARVjv1cKEBAXJiZk0QVICCocuznQgEC4sLMnCSqAAFBlWM/FwoQEBdm5iRRBQgIqhz7uVCAgLgwMyeJKkBAUOXYz4UCBMSFmTlJVAECgirHfi4UICAuzMxJogoQEFQ59nOhAAFxYWZOElWAgKDKsZ8LBQiICzNzkqgCBARVjv1cKEBAXJiZk0QVICCocuznQgEC4sLMnCSqAAFBlWM/FwoQEBdm5iRRBQgIqhz7uVCAgLgwMyeJKkBAUOXYz4UCBMSFmTlJVAECgirHfi4UICAuzMxJogoQEFQ59nOhAAFxYWZOElWAgKDKsZ8LBQiICzNzkqgCBARVjv1cKEBAXJiZk0QVICCocuznQgEC4sLMnCSqAAFBlWM/Fwr8D7iSywVmHVPHAAAAAElFTkSuQmCC
// @grant GM_setValue
// @grant GM_getValue
// @grant GM_listValues
// @grant GM_deleteValue
// @grant GM_xmlhttpRequest
// @grant GM_addStyle
// @grant GM_registerMenuCommand
// @grant GM_getResourceText
// @connect fr.unmeta.cn
// @connect 127.0.0.1
// @connect localhost
// @connect edge.microsoft.com
// @connect api-edge.cognitive.microsofttranslator.com
// @connect aip.baidubce.com
// @connect dashscope.aliyuncs.com
// @connect open.bigmodel.cn
// @connect api.openai.com
// @connect api.moonshot.cn
// @connect fanyi.baidu.com
// @connect gateway.ai.cloudflare.com
// @connect api.chatanywhere.com.cn
// @connect generativelanguage.googleapis.com
// @connect api-free.deepl.com
// @run-at document-end
// @downloadURL https://update.greasyfork.org/scripts/482986/%E6%B5%81%E7%95%85%E9%98%85%E8%AF%BB.user.js
// @updateURL https://update.greasyfork.org/scripts/482986/%E6%B5%81%E7%95%85%E9%98%85%E8%AF%BB.meta.js
// @require https://cdnjs.cloudflare.com/ajax/libs/crypto-js/4.0.0/crypto-js.min.js
// @require https://registry.npmmirror.com/sweetalert2/10.16.6/files/dist/sweetalert2.min.js
// @resource swalStyle https://registry.npmmirror.com/sweetalert2/10.16.6/files/dist/sweetalert2.min.css
// ==/UserScript==
// TODO 油猴脚本
// region 变量
// URL 相关
const POST = "POST";
const url = new URL(location.href.split('?')[0]);
// cacheKey 与 时间
const checkKey = "fluent_read_check";
const expiringTime = 86400000 / 4;
// 服务请求地址
// const source = "http://127.0.0.1"
const source = "https://fr.unmeta.cn"
const read = "%s/read".replace("%s", source), preread = "%s/preread".replace("%s", source);
// icon
const icon = {
retryIcon: createRetrySvgIcon(),
warnIcon: createWarnSvgIcon()
}
// 预编译正则表达式
const regex = {
timeRegex: /^(a|an|\d+)\s+(minute|hour|day|month|year)(s)?\s+ago$/, // "2 days ago"
paginationRegex: /^(\d+)\s*-\s*(\d+)\s+of\s+([\d,]+)$/, // "10 - 20 of 300"
lastReleaseRegex: /Last Release on (Jan|Feb|Mar|Apr|May|Jun|Jul|Aug|Sep|Oct|Nov|Dec)\s(\d{1,2}),\s(\d{4})/, // "Last Release on Jul 4, 2022"
dependencyRegex: /(Test|Provided|Compile) Dependencies \((\d+)\)/, // "Compile Dependencies (5)"
rankRegex: /#(\d+) in\s*(.*)/, // "#3 in Algorithms"
artifactsRegex: /^([\d,]+)\s+artifacts$/, // "1,024 artifacts"
vulnerabilityRegex: /^(\d+)\s+vulnerabilit(y|ies)$/, // "3 vulnerabilities"
repositoriesRegex: /Indexed (Repositories|Artifacts) \(([\d.]+)M?\)/, // Indexed Repositories (100)
packagesRegex: /([\d,]+) indexed packages/, // 12,795,152 indexed packages
joinedRegex: /Joined ((Jan|Feb|Mar|Apr|May|Jun|Jul|Aug|Sep|Oct|Nov|Dec).*\s\d{1,2},?\s\d{4}$)/, // Joined March 27, 2022
moreRegex: /\+(\d+) more\.\.\./, // More 100
commentsRegex: /(\d+)\sComments/, // 数字 Comments
gamesRegex: /(\d{1,3}(?:,\d{3})*)( games| Collections)/,
combinedDateRegex: /^(Jan|Feb|Mar|Apr|May|Jun|Jul|Aug|Sep|Oct|Nov|Dec).*\s\d{1,2},?\s\d{4}$|^\d{1,2}\s(Jan|Feb|Mar|Apr|May|Jun|Jul|Aug|Sep|Oct|Nov|Dec).*,?\s\d{4}$|^\d{1,2}\/\d{1,2}\/\d{4}$/i,
emailRegex: /^Receive feedback emails \((.*)\)$/,
verifyDomain: /To verify ownership of (.*), navigate to your DNS provider and add a TXT record with this value:/,
autoSavedRegex: /Auto-saved (\d{2}):(\d{2}):(\d{2})/,
// 辅助变量
typeMap: {'Test': '测试', 'Provided': '提供', 'Compile': '编译'},
}
// 精确翻译特例适配
const exceptionMap = {
maven: "mvnrepository.com",
docker: "hub.docker.com",
nexusmods: "www.nexusmods.com",
openai_web: "openai.com",
chatGPT: "chat.openai.com",
coze: "www.coze.com",
}
// 兼容
const compatFn = {
"www.youtube.com": youtube,
}
// 文本类型
const textType = {
textContent: 0,
placeholder: 1,
inputValue: 2,
ariaLabel: 3,
}
// 适配器与剪枝、预处理 map
let adapterFnMap = new (Map);
let skipStringMap = new Map();
let pruneSet = new Set(); // 剪枝 set
let outerHTMLSet = new Set(); // outerHTML set prune
// DOM 防抖,单位毫秒
let throttleObserveDOM = throttle(observeDOM, 3000);
// 鼠标位置
let mouseX = 0, mouseY = 0;
const transModelFn = new Map() // 翻译模型 map
// 翻译模型
const transModel = { // 翻译模型枚举
// --- LLM翻译 ---
openai: "openai",
gemini: "gemini",
yiyan: "yiyan",
tongyi: "tongyi",
zhipu: "zhipu",
moonshot: "moonshot",
// --- 机器翻译 ---
microsoft: "microsoft",
deepL: "deepL",
// --- 本地大模型 ---
ollama: "ollama",
}
const LLM = new Set(
[
transModel.openai, transModel.yiyan, transModel.tongyi,
transModel.zhipu, transModel.moonshot, transModel.gemini,
transModel.ollama,
]
)
// 翻译模型名称
const transModelName = {
['machine']: '---【机器翻译】---',
[transModel.microsoft]: '微软翻译(推荐)',
[transModel.deepL]: 'DeepL翻译(需令牌)',
['llm']: '---【AI翻译】---',
[transModel.moonshot]: 'Moonshot',
[transModel.zhipu]: '智谱清言',
[transModel.tongyi]: '通义千问',
[transModel.yiyan]: '文心一言',
[transModel.openai]: 'ChatGPT',
[transModel.gemini]: 'Gemini',
['native']: '---【本地大模型】---',
[transModel.ollama]: 'ollama',
}
// 错误类型
const errorManager = {
unknownError: "未知错误",
netError: "网络超时,请稍后重试",
authFailed: "认证失败,请检查 token 是否正确",
quota: "每分钟翻译次数已达上限,请稍后再试",
}
// 模型类型
const optionsManager = {
openai: {
"gpt-3.5-turbo": "gpt-3.5-turbo",
"gpt-4": "gpt-4",
"gpt-4-turbo-preview": "gpt-4-turbo-preview",
},
gemini: {
"gemini-pro": "gemini-pro",
},
yiyan: { // url 后缀
"ERNIE-Bot 4.0": "completions_pro",
"ERNIE-Bot-8K": "ernie_bot_8k",
"ERNIE-Bot": "completions",
},
tongyi: {
"qwen-turbo": "qwen-turbo",
"qwen-plus": "qwen-plus",
"qwen-max": "qwen-max",
"qwen-max-longcontext": "qwen-max-longcontext",
},
zhipu: {
"glm-4": "glm-4",
"glm-4v": "glm-4v",
"glm-3-turbo": "glm-3-turbo",
},
moonshot: {
"moonshot-v1-8k": "moonshot-v1-8k",
},
// 获取 option key
getOption(model) {
return GM_getValue("model_" + model) || '';
},
setOption(model, value) {
// LLM 才有 option 选项
if (LLM.has(model)) GM_setValue("model_" + model, value);
},
// 获取 option value
getOptionName(model) {
return this[model][this.getOption(model)];
},
getCustomOption(model) {
return GM_getValue("model_" + model) || '';
}
}
let LLMFormat = {
getStdHeader(token) {
return {
'Content-Type': 'application/json',
'Authorization': 'Bearer ' + token
}
},
getStdData(origin, option) {
return JSON.stringify({
'model': option,
"temperature": 0.3,
'messages': [
{'role': 'system', 'content': chatMgs.getSystemMsg()},
{'role': 'user', 'content': chatMgs.getUserMsg('hello')},
{'role': "assistant", 'content': '你好'},
{'role': 'user', 'content': origin}
]
})
},
getOllamaData(origin, option) {
return JSON.stringify({
'model': option,
"stream": false,
"temperature": 0.1,
'messages': [
{'role': 'system', 'content': chatMgs.getSystemMsg()},
{'role': 'user', 'content': chatMgs.getUserMsg(origin)},
]
})
}
}
// token 管理器
const tokenManager = {
setToken: (model, value) => {
if (transModel[model]) GM_setValue("token_" + model, value)
},
getToken: model => {
return GM_getValue("token_" + model, '');
},
removeToken(model) {
GM_deleteValue("token_" + model)
}
};
// sessionStorage
const localStorageManager = {
// 同时缓存原文和译文
setTransCache(origin, result) {
let model = util.getValue('model');
let option = optionsManager.getOption(model);
// key: 模型_文本,value: 文本
localStorage.setItem(model + "_" + option + "_" + origin, result)
localStorage.setItem(model + "_" + option + "_" + result, origin)
},
getTransCache(key) {
let model = util.getValue('model');
let option = optionsManager.getOption(model);
return localStorage.getItem(model + "_" + option + "_" + key)
},
removeSession(key) {
localStorage.removeItem(util.getValue('model') + "_" + key)
},
// 清空相关域下的 LocalStorage
clearLocalStorageIfNewSession() {
const lastSessionTimestamp = localStorage.getItem('lastSessionTimestamp');
const currentTime = new Date().getTime();
// 超过 24 小时清空 localStorage
if (!lastSessionTimestamp || currentTime - parseInt(lastSessionTimestamp) > 24 * 3600000) {
// if (!lastSessionTimestamp || currentTime - parseInt(lastSessionTimestamp) > 20000) {
localStorage.clear();
}
// 更新时间戳
localStorage.setItem('lastSessionTimestamp', currentTime.toString());
}
}
const util = {
getValue(name) {
return GM_getValue(name, '');
},
setValue(name, value) {
GM_setValue(name, value);
},
// 获取元素值
getElementValue(id) {
return document.getElementById(id).value || '';
},
}
// trustHTML
let safeFluentRead;
if (window.trustedTypes && window.trustedTypes.createPolicy) {
safeFluentRead = window.trustedTypes.createPolicy("safeFluentRead", {
createHTML: (string) => string
});
}
// endregion
// region 菜单
// toast 样式定义
const toastClass = {
container: 'translate-d-container',
popup: 'translate-d-popup',
};
// toast 实例
const toast = Swal.mixin({
toast: true,
position: 'top',
showConfirmButton: false,
timerProgressBar: false,
didOpen: toast => {
toast.addEventListener('mouseenter', Swal.stopTimer);
toast.addEventListener('mouseleave', Swal.resumeTimer);
}
});
// 多语言管理对象
const langManager = {
auto: '自动检测', // 自动检测
zh: 'zh-Hans', // 简体中文
cht: 'zh-Hant', // 繁体中文
en: 'en', // 英语
jp: 'ja', // 日语
kor: 'ko', // 韩语
fra: 'fr', // 法语
spa: 'es', // 西班牙语
ru: 'ru', // 俄语
de: 'de', // 德语
it: 'it', // 意大利语
tr: 'tr', // 土耳其语
pt: 'pt', // 葡萄牙语
vie: 'vi', // 越南语
id: 'id', // 印度尼西亚语
th: 'th', // 泰语
ar: 'ar', // 阿拉伯语
hi: 'hi', // 印地语
per: 'fa', // 波斯语
// from、to 源语言、目标语言
from: {auto: '自动检测'},
to: {'zh-Hans': '简体中文', 'en': '英语',},
// 解析语言种类
parseLanguage(language) {
return langManager[language] || language || 'en';
},
// set
setFromTo(from, to) {
GM_setValue('from', from);
GM_setValue('to', to);
},
getFrom() {
return GM_getValue('from', 'auto')
},
getTo() {
return GM_getValue('to', 'zh-Hans')
}
}
// 快捷键
const shortcutManager = {
currentShortcut: null,
hotkeyOptions: {Control: 'Control', Alt: 'Alt', Shift: 'Shift', '`': '反引号键'},
hotkeyPressed: false,
}
// 自定义 GPT地址
const customGPT = {
openai: "https://api.openai.com/v1/chat/completions",
setGPTUrl(model, url) {
url = url.trim(); // 去除首尾空格
// 解析 url,确保为 cloudflare 代理或 openai 官方地址
let cloudflareReg = /https:\/\/gateway.ai.cloudflare.com\/v1\/\w+\/\w+\/openai\/chat\/completions/;
if (url === this.openai
|| url === "https://api.chatanywhere.com.cn/v1/chat/completions"
|| cloudflareReg.test(url)
// 是 127.0.0.1 或 localhost
|| url.indexOf("127.0.0.1") !== -1
|| url.indexOf("localhost") !== -1
) {
GM_setValue(model + '_url', url)
return true
}
return false
},
getGPTUrl(model) {
if (!model) model = util.getValue('model');
return GM_getValue(model + '_url', this.openai)
}
}
// 鼠标悬停计时器
let hoverTimer;
const settingManager = {
generateOptions(options, selectedValue) {
return Object.entries(options).map(([key, value]) => {
// 检查是否为需要禁用的选项
const isDisabled = ['---【机器翻译】---', '---【AI翻译】---', '---【本地大模型】---'].includes(value);
return `<option value="${key}" ${selectedValue === key ? 'selected' : ''} ${isDisabled ? 'disabled' : ''}>${value}</option>`;
}).join('');
},
// 设置中心界面
setSetting() {
// 页面 dom
const dom = `
<div style="font-size: 1em;" xmlns="http://www.w3.org/1999/html">
<label class="instant-setting-label">快捷键<select id="fluent-read-hotkey" class="instant-setting-common">${this.generateOptions(shortcutManager.hotkeyOptions, util.getValue('hotkey'))}</select></label>
<label class="instant-setting-label">翻译源语言<select id="fluent-read-from" class="instant-setting-common">${this.generateOptions(langManager.from, langManager.getFrom())}</select></label>
<label class="instant-setting-label">翻译目标语言<select id="fluent-read-to" class="instant-setting-common">${this.generateOptions(langManager.to, langManager.getTo())}</select></label>
<label class="instant-setting-label">翻译服务<select id="fluent-read-model" class="instant-setting-select">${this.generateOptions(transModelName, util.getValue('model'))}</select></label>
<!--支持 ollama 等自定义模型名称-->
<label class="instant-setting-label" id="fluent-read-custom-type-label" style="display: none;">
<span class="fluent-read-tooltip">自定义模型类型
<span class="fluent-read-tooltiptext">
请填写模型类型全称,如:gemma:7b、llama2:7b
</span>
</span>
<input type="text" class="instant-setting-input" id="fluent-read-custom-type" value="${optionsManager.getOption(util.getValue('model'))}" ></label>
<label class="instant-setting-label" id="fluent-read-option-label" style="display: none;">模型类型<select id="fluent-read-option" class="instant-setting-select"></select></label>
<!-- custom 输入框-->
<label class="instant-setting-label" id="fluent-read-custom-label" style="display: none;">
<span class="fluent-read-tooltip">自定义 GPT 地址
<span class="fluent-read-tooltiptext">
1、支持 OpenAI 官方地址,如:https://api.openai.com/v1/chat/completions
</br>
2、支持 Cloudflare 代理,如:https://gateway.ai.cloudflare.com/.../openai/chat/completions
</br>
3、支持国内开源代理,如:https://api.chatanywhere.com.cn/v1/chat/completions
</br>
4、支持本地代理,如:http://localhost:11434/v1/chat/completions
</br>
5、由于浏览器安全限制,如需支持其他代理,请于 GitHub 提 issue.
</span>
</span>
<input type="text" class="instant-setting-input" id="fluent-read-custom" value="${customGPT.getGPTUrl()}" >
</label>
<!-- 令牌区域 -->
<label class="instant-setting-label" id="fluent-read-token-label" style="display: none;">token令牌<input type="text" class="instant-setting-input" id="fluent-read-token" value="" ></label>
<label class="instant-setting-label" id="fluent-read-ak-label" style="display: none;">ak令牌<input type="text" class="instant-setting-input" id="fluent-read-ak" value="" ></label>
<label class="instant-setting-label" id="fluent-read-sk-label" style="display: none;">sk令牌<input type="text" class="instant-setting-input" id="fluent-read-sk" value="" ></label>
<!-- 添加的输入区域 -->
<label class="instant-setting-label" id="fluent-read-system-label" style="display: none;">
<span class="fluent-read-tooltip">system角色设定<span class="fluent-read-tooltiptext">模型角色设定,如:你是一名专业的翻译家</span></span>
<textarea class="instant-setting-textarea" id="fluent-read-system-message">${chatMgs.getSystemMsg()}</textarea>
</label>
<label class="instant-setting-label" id="fluent-read-user-label" style="display: none;">
<span class="fluent-read-tooltip">user消息模板<span class="fluent-read-tooltiptext">用户对话内容,如:请你翻译 Hello</br>注意:{{text}} 是你需要翻译的原文,不可缺少。</span></span>
<textarea class="instant-setting-textarea" id="fluent-read-user-message">${chatMgs.getOriginUserMsg()}</textarea>
</label>
</div>`;
Swal.fire({
title: '设置中心',
html: dom,
showCancelButton: true,
confirmButtonText: '保存并刷新页面',
cancelButtonText: '取消',
customClass: toastClass
},
).then(async (result) => {
if (result.isConfirmed) {
let model = util.getElementValue('fluent-read-model');
// 0、设置自定义 GPT 地址
if ([transModel.openai, transModel.ollama].includes(model)) {
let ok = customGPT.setGPTUrl(model, util.getElementValue('fluent-read-custom'));
if (!ok) {
toast.fire({
icon: 'error',
title: '自定义地址不合法,请检查后重试!'
});
return
}
}
// 1、设置语言
util.setValue('from', util.getElementValue('fluent-read-from'));
util.setValue('to', util.getElementValue('fluent-read-to'));
// 2、设置快捷键
util.setValue('hotkey', util.getElementValue('fluent-read-hotkey'));
// 3、设置翻译服务
util.setValue('model', model);
// 4、设置模型类型
if (model === transModel.ollama) {
optionsManager.setOption(model, util.getElementValue('fluent-read-custom-type'));
} else {
optionsManager.setOption(model, util.getElementValue('fluent-read-option'));
}
// 5、存储 token
let token = util.getElementValue('fluent-read-token');
let ak = util.getElementValue('fluent-read-ak');
let sk = util.getElementValue('fluent-read-sk');
switch (model) {
case transModel.yiyan:
tokenManager.setToken(model, {ak: ak, sk: sk});
break;
case transModel.zhipu:
tokenManager.setToken(model, {apikey: token});
break;
default:
tokenManager.setToken(model, token);
}
// 6、设置 chatGPT 消息模板
chatMgs.setSystemMsg(util.getElementValue('fluent-read-system-message'));
chatMgs.setUserMsg(util.getElementValue('fluent-read-user-message'));
toast.fire({icon: 'success', title: '设置成功!'});
history.go(0); // 刷新页面
}
}
)
// 设置中心打开时需判断是否展示 token 选项
let model = util.getElementValue('fluent-read-model');
if (LLM.has(model) || model === transModel.deepL) {
this.showHidden(model);
}
// 监听“翻译服务”选择框
document.getElementById('fluent-read-model').addEventListener('change', e => {
const model = e.currentTarget.value;
this.showHidden(model);
});
},
showHidden(model) {
// label 是最外层的标签
const tokenLabel = document.getElementById('fluent-read-token-label');
const akLabel = document.getElementById('fluent-read-ak-label');
const skLabel = document.getElementById('fluent-read-sk-label');
const token = document.getElementById('fluent-read-token');
const ak = document.getElementById('fluent-read-ak');
const sk = document.getElementById('fluent-read-sk');
// 获取存储的 token 对象
const tokenObject = tokenManager.getToken(model)
switch (model) {
case transModel.yiyan:
ak.value = tokenObject ? tokenObject.ak : '';
sk.value = tokenObject ? tokenObject.sk : '';
this.setDisplayStyle([akLabel, skLabel], [tokenLabel]);
break;
case transModel.zhipu:
token.value = tokenObject.apikey || '';
this.setDisplayStyle([tokenLabel], [akLabel, skLabel]);
break;
default:
if ([transModel.openai, transModel.moonshot, transModel.tongyi, transModel.gemini, transModel.deepL, transModel.ollama].includes(model)) {
token.value = tokenObject;
this.setDisplayStyle([tokenLabel], [akLabel, skLabel]);
} else {
this.setDisplayStyle([], [tokenLabel, akLabel, skLabel]);
}
}
},
// 批量设置元素的 display 样式
setDisplayStyle(flex, none) {
// 消息模版
const systemMsgLabel = document.getElementById('fluent-read-system-label');
const userMsgLabel = document.getElementById('fluent-read-user-label');
// 自定义 GPT 地址框
const customLabel = document.getElementById('fluent-read-custom-label');
const optionLabel = document.getElementById('fluent-read-option-label');
const customTypeLabel = document.getElementById('fluent-read-custom-type-label');
// 1、如果 flex 为空,则设置所有元素的 display 为 none,返回 / 如果是 DeepL
let model = util.getElementValue('fluent-read-model');
if (flex.length === 0 || model === transModel.deepL) {
optionLabel.style.display = "none";
systemMsgLabel.style.display = "none";
userMsgLabel.style.display = "none";
customLabel.style.display = "none";
none.forEach(element => element.style.display = "none");
flex.forEach(element => element.style.display = "flex");
return
}
// 2、正常逻辑,更新选项、按需要显示元素
customLabel.style.display = [transModel.openai, transModel.ollama].includes(model) ? "flex" : "none"; // 判断是否显示自定义 GPT 地址输入框
document.getElementById('fluent-read-custom').value = customGPT.getGPTUrl(model); // 设置自定义 GPT 地址
flex.forEach(element => element.style.display = "flex");
none.forEach(element => element.style.display = "none");
systemMsgLabel.style.display = "flex";
userMsgLabel.style.display = "flex";
// 更新下拉框选项
if (model === transModel.ollama) {
optionLabel.style.display = "none"
customTypeLabel.style.display = "flex"
flex.forEach(element => element.style.display = "none");
document.getElementById('fluent-read-custom-type').value = optionsManager.getCustomOption(model);
} else {
const optionSelect = document.getElementById('fluent-read-option');
optionSelect.innerHTML = settingManager.generateOptions(optionsManager[model], optionsManager.getOption(model));
optionLabel.style.display = "flex"
customTypeLabel.style.display = "none"
}
}
,
setHotkey() {
Swal.fire({
title: '快捷键设置',
text: '请选择鼠标快捷键',
input: 'select',
inputValue: util.getValue('hotkey'),
inputOptions: shortcutManager.hotkeyOptions,
confirmButtonText: '保存并刷新页面',
cancelButtonText: '取消',
showCancelButton: true,
customClass: toastClass,
}).then(async (result) => {
if (result.isConfirmed) {
util.setValue('hotkey', result.value);
setShortcut(result.value);
toast.fire({icon: 'success', title: '快捷键设置成功!'});
history.go(0); // 刷新页面
}
});
}
,
setLanguage(lang) {
let args = lang === 'from' ? {
notion: "源",
inputValue: langManager.getFrom(),
inputOptions: langManager.from,
} : {
notion: "目标",
inputValue: langManager.getTo(),
inputOptions: langManager.to,
}
Swal.fire({
title: args.notion + '语言设置',
text: '请选择翻译' + args.notion + '语言',
input: 'select',
inputValue: args.inputValue,
inputOptions: args.inputOptions,
confirmButtonText: '保存并刷新页面',
cancelButtonText: '取消',
showCancelButton: true,
customClass: toastClass,
}).then(async (result) => {
if (result.isConfirmed) {
langManager.setFromTo(langManager.getFrom(), result.value);
toast.fire({icon: 'success', title: args.notion + '语言设置成功!'});
history.go(0); // 刷新页面
}
});
}
,
update() {
// 跳转页面
window.open('https://greasyfork.org/zh-CN/scripts/482986-%E6%B5%81%E7%95%85%E9%98%85%E8%AF%BB');
}
,
about() {
// 跳转页面
window.open('https://github.com/Bistutu/FluentRead');
}
};
// endregion
// region 主函数
(function () {
'use strict';
initApplication()
// 触屏监听事件:三指触摸触发翻译事件
document.body.addEventListener('touchstart', event => {
// 检查是否有三个触摸点以及其中心位置
if (event.touches.length === 3) {
let centerX = (event.touches[0].clientX + event.touches[1].clientX + event.touches[2].clientX) / 3;
let centerY = (event.touches[0].clientY + event.touches[1].clientY + event.touches[2].clientY) / 3;
// 调用翻译处理函数
handler(centerX, centerY, 0, false);
}
});
// 当浏览器或标签页失去焦点时,重置 ctrlPressed
window.addEventListener('blur', () => shortcutManager.hotkeyPressed = false)
// 鼠标、键盘监听事件,悬停翻译
window.addEventListener('keydown', event => handler(mouseX, mouseY, 10))
document.body.addEventListener('mousemove', event => {
// 更新鼠标位置
mouseX = event.clientX;
mouseY = event.clientY;
handler(mouseX, mouseY, 25);
});
// 检查是否需要拉取数据
checkRun(shouldRun => {
// 如果 host 包含在 preread 中,shouldRun 为 true,则开始解析 DOM 树并设置监听器
if (!shouldRun) return
// 1、添加监听器,使用 MutationObserver 监听 DOM 变化
const observer = new MutationObserver(function (mutations, obs) {
mutations.forEach(mutation => {
if (isEmpty(mutation.target)) return;
// console.log("原先变更记录:", mutation.target);
// 如果不包含下面节点,则处理
if (!["img", "noscript"].includes(mutation.target.tagName.toLowerCase())) {
handleDOMUpdate(mutation.target);
}
});
});
observer.observe(document.body, {childList: true, subtree: true});
// 2、手动开启一次解析 DOM 树
handleDOMUpdate(document.body);
});
document.addEventListener('keydown', function (event) {
// F2 清空当前页面所有翻译缓存
if (event.key === 'F2') {
localStorage.clear()
// toast.fire({icon: 'success', title: '当前页面翻译缓存清空成功!'});
console.log('当前页面翻译缓存清空成功!')
}
// 快捷键 F1,清空所有缓存
// if (event.key === 'F1') {
// let listValues = GM_listValues();
// listValues.forEach(e => GM_deleteValue(e))
// console.log('Cache cleared!');
// }
// 鼠标选中事件,暂未开放
// if (event.key === 'F3') {
// translateSelectedText();
// }
});
})();
// 监听事件处理器,参数:鼠标坐标、计时器
function handler(mouseX, mouseY, time, noSkip = true) {
if (noSkip && !shortcutManager.hotkeyPressed) return;
clearTimeout(hoverTimer); // 清除计时器
hoverTimer = setTimeout(() => {
let node = getTransNode(document.elementFromPoint(mouseX, mouseY)); // 获取最终需要翻译的节点
if (!node) return; // 如果不需要翻译,则跳过
if (hasLoadingSpinner(node)) { // 如果已经在翻译,则跳过
// console.log('正在翻译中...跳过');
return;
// }else {
// console.log('翻译节点:', node);
}
// 去重判断
let outerHTMLTemp = node.outerHTML;
if (outerHTMLSet.has(outerHTMLTemp)) {
// console.log('重复节点', node);
return;
}
outerHTMLSet.add(outerHTMLTemp);
// 检测缓存 cache
let outerHTMLCache = localStorageManager.getTransCache(node.outerHTML);
if (outerHTMLCache) {
// console.log("缓存命中:", outerHTMLCache);
let spinner = createLoadingSpinner(node, true);
setTimeout(() => { // 延迟 remove 转圈动画与替换文本
spinner.remove();
outerHTMLSet.delete(outerHTMLTemp);
let fn = compatFn[url.host]; // 兼容函数
if (fn) {
fn(node, outerHTMLCache); // 兼容函数
} else {
node.outerHTML = safeFluentRead ? safeFluentRead.createHTML(outerHTMLCache) : outerHTMLCache;
}
delayRemoveCache(outerHTMLCache);
}, 250);
return;
}
translate(node);
}, time);
}
const getTransNodeSet = new Set(['span']);
// 特例集合
const specialSet = new Set([
'h1', 'h2', 'h3', 'h4', 'h5', 'h6', // 标题
'p', // 段落(p 标签通常代表一句完整的话)
"li", // 列表
'yt-formatted-string', // youtube 评论
]);
// 特例适配
const getTransNodeCompat = new Map([
["mvnrepository.com", node => {
if (node.tagName.toLowerCase() === 'div' && node.classList.contains('im-description')) return true
},
"www.aozora.gr.jp", node => {
if (node.tagName.toLowerCase() === 'div' && node.classList.contains('main_text')) return true
},
],
]);
// 返回最终应该翻译的父节点或 false
function getTransNode(node) {
let model = util.getValue('model')
// 1、全局节点与空节点、文字过多的节点、class="notranslate" 的节点不翻译
if (!node || [document.documentElement, document.body].includes(node)
|| node.tagName.toLowerCase() === "iframe" || node.classList.contains('notranslate')
|| node.textContent.length > 8192
) return false;
// 2、特例适配标签,遇到这些标签则直接返回节点
if (specialSet.has(node.tagName.toLowerCase())) return node;
// 3、特例适配函数,根据 host 适配、且支持匹配 class
let fn = getTransNodeCompat.get(url.host);
if (fn && fn(node)) return node;
// 4、检测当前节点是否满足翻译条件
if (getTransNodeSet.has(node.tagName.toLowerCase()) || detectChildMeta(node)) {
return getTransNode(node.parentNode) || node; // 如果当前节点满足翻译条件,则向上寻找最终符合的父节点
}
// 5、如果节点是div并且不符合一般翻译条件,可翻译首行文本
if (node.tagName.toLowerCase() === 'div') {
// 遍历子节点,寻找首个文本节点或 a 标签节点
let child = node.firstChild;
while (child) {
if (child.nodeType === Node.TEXT_NODE && child.textContent.trim() !== '') {
transModelFn[model](child.textContent).then(text => {
child.textContent = text;
})
return false; // 只翻译首行文本
}
child = child.nextSibling;
}
}
// 6、翻译文本节点
if (node.nodeType === Node.TEXT_NODE && node.textContent.trim() !== '') {
transModelFn[model](node.textContent).then(text => {
node.textContent = text;
})
return false; // 只翻译文本节点
}
// console.log('不翻译节点:', node);
return false
}
// node 的 parentNode 只含有这些标签时,会向上翻译 parentNode
const detectChildMetaSet = new Set([
'a', 'b', 'strong', 'span', 'p', 'img',
'br', 'em', 'u', 'small', 'sub', 'sup', 'i',
'font', 'big', 'strike', 's', 'del', 'ins',
'mark', 'cite', 'q', 'abbr', 'acronym', 'dfn',
'code', 'samp', 'kbd', 'var', 'pre', 'address',
'time', 'ruby', 'rb', 'rt', 'rp', 'bdi', 'bdo', 'wbr',
'details', 'summary', 'menuitem', 'menu', 'dialog',
'slot', 'template', 'shadow', 'content', 'element',
]);
// 检测子元素中是否包含指定标签以外的元素
function detectChildMeta(parent) {
let child = parent.firstChild;
while (child) {
if (child.nodeType === Node.ELEMENT_NODE && !detectChildMetaSet.has(child.nodeName.toLowerCase())) {
return false;
}
child = child.nextSibling;
}
return true;
}
// endregion
// region 通用翻译处理模块
const chatMgs = {
system: `You are a professional, authentic translation engine, only returns translations.`,
user_pre: `Please translate them into {{to}}, `, // 隐藏前半部分(语言选择),显示用户自定义的后半部分
user_post: `please do not explain my original text.:
{{origin}}`,
setSystemMsg(msg) {
GM_setValue('systemMsg', msg);
},
setUserMsg(msg) {
GM_setValue('userMsg', this.user_pre + msg);
},
getOriginUserMsg() {
let userMsg = GM_getValue('userMsg', this.user_pre + this.user_post);
return userMsg.substring(userMsg.indexOf(',') + 2, userMsg.length);
},
getSystemMsg() {
return GM_getValue('systemMsg', this.system);
},
getUserMsg(origin) {
let userMsg = GM_getValue('userMsg', this.user_pre + this.user_post);
return userMsg.replace('{{origin}}', origin).replace('{{to}}', langManager.getTo());
}
}
function translate(node) {
let model = util.getValue('model')
if (!node.innerText.trim()) return; // 空文本,跳过
// 检测语言类型,如果是中文则不翻译
baiduDetectLang(node.innerText).then(lang => {
if (lang === langManager.getTo()) return; // 与目标语言相同,不翻译
// 如果是机器翻译,则翻译 outerHTML,否则递归获取文本
let origin = isMachineTrans(model) ? node.outerHTML : getTextWithNode(node);
let spinner = createLoadingSpinner(node); // 插入转圈动画
let timeout = setTimeout(() => {
createFailedTip(node, new Error(errorManager.netError).toString(), spinner);
}, 60000);
// 调用翻译服务
transModelFn[model](origin).then(text => {
clearTimeout(timeout) // 取消超时
spinner.remove() // 移除 spinner
// console.log("翻译前的句子:", origin);
// console.log("翻译后的句子:", text);
if (!text || origin === text) return;
let oldOuterHtml = node.outerHTML // 保存旧的 outerHTML
let newOuterHtml = text
if (isMachineTrans(model)) {
// 机器翻译
if (!node.parentNode) return;
let fn = compatFn[url.host];
if (fn) {
oldOuterHtml = node.outerHTML;
fn(node, text);
newOuterHtml = node.outerHTML;
} else {
node.outerHTML = safeFluentRead ? safeFluentRead.createHTML(text) : text;
}
} else {
// LLM 翻译
node.innerHTML = safeFluentRead ? safeFluentRead.createHTML(text) : text;
newOuterHtml = node.outerHTML;
}
localStorageManager.setTransCache(oldOuterHtml, newOuterHtml); // 设置缓存
// 延迟 newOuterHtml,删除 oldOuterHtml
delayRemoveCache(newOuterHtml);
outerHTMLSet.delete(oldOuterHtml);
}).catch(e => {
console.log(e)
clearTimeout(timeout);
createFailedTip(node, e.toString() || errorManager.unknownError, spinner);
})
}).catch(e => {
console.log(e)
createFailedTip(node, e.toString() || errorManager.unknownError)
})
}
const getTextWithNodeSet = new Set([
'div', 'br',
'code', 'a', 'strong', 'b', 'em', 'i', 'u', 's', 'del',
'ins', 'mark', 'small', 'sub', 'sup', 'big', 'font',
'abbr', 'acronym', 'cite', 'dfn', 'kbd', 'samp', 'var',
'pre', 'q', 'blockquote', 'address', 'time', 'ruby', 'rt',
'rp', 'bdi', 'bdo', 'wbr', 'details', 'summary', 'menuitem',
'menu', 'dialog', 'slot', 'template', 'shadow', 'content', 'element',
])
// LLM 模式获取翻译文本
function getTextWithNode(node) {
let text = "";
// 遍历所有子节点
node.childNodes.forEach(child => {
if (child.nodeType === Node.TEXT_NODE) {
// 文本节点:直接添加其文本
text += child.nodeValue;
} else if (child.nodeType === Node.ELEMENT_NODE) {
// 检查是否为特定节点