-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathChinese_converter.js
2739 lines (2400 loc) · 111 KB
/
Chinese_converter.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
/*
TODO:
記錄各轉換的使用次數。
依照前後詞彙再建立 Map(),避免條件式串列過長。這可能得考慮如何合併詞性標註錯誤時的條件式。
+ "n*" PoS,放在 "n*:" 之下。
https://zhuanlan.zhihu.com/p/95358646
常用的关键词提取算法:TF-IDF算法、TextRank算法
https://blog.csdn.net/vivian_ll/article/details/106647666
利用jieba进行关键字提取时,有两种接口。一个基于TF-IDF算法,一个基于TextRank算法。
https://s.itho.me/techtalk/2017/%E4%B8%AD%E6%96%87%E6%96%B7%E8%A9%9E%EF%BC%9A%E6%96%B7%E5%8F%A5%E4%B8%8D%E8%A6%81%E6%82%B2%E5%8A%87.pdf
某個詞在⼀篇⽂章中出現的頻率⾼,且在其他⽂章中很少出現,則此詞語為具代表性的關鍵詞
*/
'use strict';
// modify from wikiapi.js
let CeL;
try {
// Load CeJS library.
CeL = require('cejs');
} catch (e) /* istanbul ignore next: Only for debugging locally */ {
// https://github.com/gotwarlost/istanbul/blob/master/ignoring-code-for-coverage.md
require('./_CeL.loader.nodejs.js');
CeL = globalThis.CeL;
}
// assert: typeof CeL === 'function'
// 在非 Windows 平台上避免 fatal 錯誤。
CeL.env.ignore_COM_error = true;
// Load modules.
CeL.run(['application.debug',
// 載入不同地區語言的功能 for wiki.work()。
'application.locale',
// Add color to console messages. 添加主控端報告的顏色。
'interact.console',
// CeL.data.Convert_Pairs.remove_comments()
'data.Convert_Pairs',
// for CeL_CN_to_TW()
'extension.zh_conversion',
//for CeL.get_URL()
'application.net.Ajax',
// for 'application.platform.nodejs': CeL.env.arg_hash, CeL.wiki.cache(),
// CeL.fs_mkdir(), CeL.wiki.read_dump()
'application.storage']);
/** {Number}未發現之index。 const: 基本上與程式碼設計合一,僅表示名義,不可更改。(=== -1) */
const NOT_FOUND = ''.indexOf('_');
/** {RegExp}沒中文字元,可跳過解析。 */
const PATTERN_non_Chinese_characters = /^[\u0000-\u00ff]*$/;
const module_base_path = CeL.append_path_separator(module.path);
const test_directory = CeL.append_path_separator(module_base_path + '_test suite');
// Cache default convertors without CeCC.
const CeL_CN_to_TW = CeL.zh_conversion.CN_to_TW, CeL_TW_to_CN = CeL.zh_conversion.TW_to_CN;
// ----------------------------------------------------------------------------
// default
const KEY_word = 'word', KEY_PoS_tag = 'tag', KEY_filter_name = 'filter_name';
const DEFAULT_TEST_FILE_EXTENSION = 'txt';
const dictionary_template = {
TW: 'CN_to_TW.%name.%type.txt',
CN: 'TW_to_CN.%name.%type.txt'
};
function get_dictionary_file_paths(type) {
if (!this.parser_name)
throw new Error('No parser name specified!');
const dictionary_file_paths = Object.create(null);
for (const language in dictionary_template) {
let path = dictionary_template[language]
.replace('%name', this.parser_name)
.replace('%type', type || 'PoS');
if (type === 'filters')
path = path.replace(/[^.]+$/, 'js');
dictionary_file_paths[language] = path;
}
if (!type)
this.dictionary_file_paths = dictionary_file_paths;
return dictionary_file_paths;
}
// CeCC
class Chinese_converter {
constructor(options) {
this.conversion_pairs = Object.create(null);
// this.tailored_conversion_pairs[work_title] = ((tailored conversion_pairs))
this.tailored_conversion_pairs = Object.create(null);
this.KEY_word = KEY_word;
this.KEY_PoS_tag = KEY_PoS_tag;
if (options?.LTP_URL) {
this.LTP_URL = options.LTP_URL;
options.using_LTP = options.using_LTP || true;
}
if (options?.using_LTP) {
// 最高正確率
this.KEY_word = 'text';
this.KEY_PoS_tag = 'pos';
this.TAG_punctuation = 'wp';
this.condition_filter = condition_filter_LTP;
this.parser_name = 'LTP';
this.filters = get_dictionary_file_paths.call(this, 'filters');
for (const language in this.filters) {
const dictionary_file_path = this.dictionaries_directory + this.filters[language];
this.filters[language] = require(dictionary_file_path);
}
this.generate_condition = generate_condition_LTP;
load_synonym_dictionary.call(this);
this.tag_paragraph = tag_paragraph_LTP;
// .batch_get_tag 批量查詢詞性標記之條件: 1.可接受批量{Array}。 2.單次查詢消耗太大。
this.batch_get_tag = !this.LTP_URL;
} else if (options?.CoreNLP_URL) {
// using Stanford CoreNLP
this.KEY_PoS_tag = 'pos';
this.CoreNLP_URL = new URL(options.CoreNLP_URL);
this.parser_name = 'CoreNLP';
// https://stanfordnlp.github.io/CoreNLP/corenlp-server.html
this.CoreNLP_URL_properties = {
annotators: 'tokenize,ssplit,pos,depparse',
};
this.tag_paragraph = tag_paragraph_via_CoreNLP;
} else {
// fallback to default: nodejieba
this.nodejieba_CN = require("nodejieba");
this.nodejieba_CN.load({ dict: this.dictionaries_directory + 'commons.txt' });
this.parser_name = 'jieba';
this.tag_paragraph = tag_paragraph_jieba;
}
get_dictionary_file_paths.call(this);
this.dictionary_file_path_loaded_Set = new Set;
for (const convert_to_language in this.dictionary_file_paths) {
const dictionary_file_path = this.dictionary_file_paths[convert_to_language]
= this.dictionaries_directory + this.dictionary_file_paths[convert_to_language];
load_dictionary.call(this, dictionary_file_path, { convert_to_language });
}
if (CeL.is_debug()) {
// 這些是比較耗時的轉換。
for (const [language, conversion_pairs] of Object.entries(this.conversion_pairs)) {
CeL.info({
// gettext_config:{"id":"conversion-pairs-of-$1"}
T: ['%1轉換對:', CeL.gettext.get_alias(language)]
});
function show_conversion_pairs(_pairs, tag = 'general') {
const size = _pairs.size;
if (size > 0) {
CeL.log(`\t${tag || 'general'}\t${size} conversion(s)${size < 9 ? '\t' + Array.from(_pairs.keys()).join('\t') : ''}`);
}
}
show_conversion_pairs(conversion_pairs.get(KEY_general_pattern_filter));
for (const [tag, _pairs] of Object.entries(conversion_pairs.get(KEY_tag_pattern_filter))) {
show_conversion_pairs(_pairs, tag);
}
}
}
this.load_default_text_to_check();
}
/**
* convert to TW
* @param {Array}paragraphs [{String}, {String}, ...]
* @param {Object}[options]
*/
async to_TW(paragraphs, options) {
return await convert_Chinese.call(this, await paragraphs, { convert_to_language: 'TW', ...options });
}
to_TW_sync(paragraphs, options) {
return convert_Chinese.call(this, paragraphs, { convert_to_language: 'TW', ...options });
}
/**
* convert to CN
* @param {Array}paragraphs [{String}, {String}, ...]
* @param {Object}[options]
*/
async to_CN(paragraphs, options) {
return await convert_Chinese.call(this, await paragraphs, { convert_to_language: 'CN', ...options });
}
to_CN_sync(paragraphs, options) {
return convert_Chinese.call(this, paragraphs, { convert_to_language: 'CN', ...options });
}
// 自動判斷句子、段落的語境(配合維基百科專有名詞轉換)
detect_domain(paragraphs, options) {
// TODO
}
static async has_LTP_server(options) {
if (typeof options === 'string') {
// treat options as LTP_URL
options = { LTP_URL: options };
} else {
options = { LTP_URL: 'http://localhost:5000/', ...options };
}
if (options.skip_server_test) {
// gettext_config:{"id":"force-the-use-of-the-ltp-server-and-skip-the-test-of-the-ltp-server-whether-it-works-properly-or-not.-use-this-option-only-if-you-are-prepared-to-use-the-cache-throughout"}
CeL.debug('強制使用 LTP server,跳過對 LTP server 的運作測試。請只在您準備全程使用 cache 的情況下才使用這個選項。', 1, Chinese_converter.has_LTP_server.name);
return options.LTP_URL;
}
try {
//console.trace(options);
// 注意: 測試 LTP server 不可包含空白或者英數字元!
const result = await tag_paragraph_LTP.call(options, '測試繁簡轉換伺服器是否正常運作');
//console.trace(result);
return Array.isArray(result) && options.LTP_URL;
} catch (e) {
//console.error(e);
}
}
//#parse_condition = parse_condition
}
// ----------------------------------------------------------------------------
function to_converted_file_path(convert_from_text__file_name) {
return convert_from_text__file_name.replace(/(\.\w+)$/, '.converted$1');
}
async function regenerate_converted(convert_from_text__file_path, convert_to_text__file_status, options) {
CeL.info([regenerate_converted.name + ': ', {
// gettext_config:{"id":"generate-the-answer-file-for-$1"}
T: ['生成 %1 的解答檔', options.convert_from_text__file_name || convert_from_text__file_path]
}]);
let converted_text = CeL.read_file(convert_from_text__file_path).toString();
//console.trace(options.convert_options);
converted_text = options.text_is_TW
? await this.to_CN(converted_text, options.convert_options || regenerate_converted.default_convert_options)
: await this.to_TW(converted_text, options.convert_options || regenerate_converted.default_convert_options)
;
//console.trace(converted_text.slice(0, 200));
CeL.write_file(convert_to_text__file_status
//.replace('.answer.', '.converted.')
, converted_text, { backup: { directory_name: 'backup' } });
}
regenerate_converted.default_convert_options = {
cache_directory: CeL.append_path_separator(test_directory + 'cache_data'),
cache_file_for_short_sentences: true,
// 超過此長度才創建個別的 cache 檔案,否則會放在 .cache_file_for_short_sentences。
min_cache_length: 40,
};
function get_convert_from_text__file_path(convert_from_text__file_name, options) {
let test_articles_directory = this.test_articles_directory;
let file_path = test_articles_directory + convert_from_text__file_name;
if (CeL.file_exists(file_path))
return file_path;
test_articles_directory += this.test_articles_archives_directory;
file_path = test_articles_directory + convert_from_text__file_name;
if (options?.check_file_exists && !CeL.file_exists(file_path))
return;
return file_path;
}
function get_convert_to_text__file_status(convert_from_text__file_name, options) {
options = CeL.setup_options(options);
let test_articles_directory = this.test_articles_directory;
const convert_from_text__file_path = options.is_file_path ? convert_from_text__file_name : get_convert_from_text__file_path.call(this, convert_from_text__file_name);
const convert_from_text__file_status = CeL.fso_status(convert_from_text__file_path);
const convert_to_text__file_path = options.convert_to_text__file_path
|| (options.convert_to_text__file_name ? test_articles_directory + options.convert_to_text__file_name : Chinese_converter.to_converted_file_path(convert_from_text__file_path));
const convert_to_text__file_status = CeL.fso_status(convert_to_text__file_path);
const need_to_generate_new_convert_to_text__file = options.regenerate_converted || !convert_to_text__file_status || convert_from_text__file_status.mtime - convert_to_text__file_status.mtime > 0;
return { convert_from_text__file_path, convert_from_text__file_status, convert_to_text__file_path, convert_to_text__file_status, need_to_generate_new_convert_to_text__file };
}
async function not_new_article_to_check(convert_from_text__file_name, options) {
options = CeL.setup_options(options);
const { convert_from_text__file_path, convert_from_text__file_status, convert_to_text__file_path, convert_to_text__file_status, need_to_generate_new_convert_to_text__file } = get_convert_to_text__file_status.call(this, convert_from_text__file_name, options);
if (need_to_generate_new_convert_to_text__file) {
//console.trace('重新生成 .converted.* 解答檔案。');
await this.regenerate_converted(convert_from_text__file_path, convert_to_text__file_path, { ...options, convert_from_text__file_name, });
}
if (options.recheck) {
// 既然要重新檢查,即便詞典檔是舊的,依然算作有新變化。
return;
}
// -----------------------------------
// 檢查上一次測試後,是否有尚未檢測通過的詞典檔。
const latest_test_result = options.latest_test_result && options.latest_test_result[options.test_name];
const latest_test_result_for_file = latest_test_result && latest_test_result.test_results && latest_test_result.test_results[convert_from_text__file_name];
const latest_test_result_date = latest_test_result_for_file?.error_count === 0 ? Date.parse(latest_test_result_for_file?.date)
// 檢查是否有比測試檔或 .converted.* 解答檔案更新的尚未檢測通過的詞典檔。
: convert_to_text__file_status ? Math.max(convert_from_text__file_status.mtime.getTime(), convert_to_text__file_status.mtime.getTime()) : convert_from_text__file_status.mtime.getTime();
//console.trace(this.dictionary_file_paths);
for (const dictionary_file_path of Object.values(this.dictionary_file_paths)) {
const dictionary_file_status = CeL.fso_status(dictionary_file_path);
//console.trace(dictionary_file_status);
//console.trace([dictionary_file_status.mtime - latest_test_result_date, convert_from_text__file_status && convert_from_text__file_status.mtime - dictionary_file_status.mtime]);
if (dictionary_file_status.mtime - latest_test_result_date > 0) {
CeL.info(`${not_new_article_to_check.name}: ${convert_from_text__file_name}: 自上次測試後,有新修改的辭典檔 ${dictionary_file_path}`);
if (latest_test_result)
delete latest_test_result[convert_from_text__file_name];
return;
}
}
// 檢查上一次測試是否比測試檔更新。
//console.trace(latest_test_result_date - convert_from_text__file_status.mtime);
if (latest_test_result_date - convert_from_text__file_status.mtime > 0) {
//console.trace(!convert_from_text__file_status || latest_test_result_date > convert_from_text__file_status.mtime);
return !convert_to_text__file_status || latest_test_result_date > convert_to_text__file_status.mtime;
}
}
// ----------------------------------------------------------------------------
/**
* 載入個別作品特設辭典。
* 單獨作品辭典檔案: 分割個別作品的辭典為特設辭典,簡化辭典複雜度。
*
* @param {Object}options 附加參數/設定選擇性/特殊功能與選項。
*/
function load_tailored_dictionary(options) {
if (!options.export) {
// e.g., { is_default: true }
return;
}
//console.trace(options);
const { work_title, original_work_title } = options.export;
const path_prefix = this.tailored_dictionaries_directory + work_title + '.';
const original_work_title__path_prefix = this.tailored_dictionaries_directory + original_work_title + '.';
//console.trace(path_prefix);
const _this = this;
function check_and_load(is_CeCC, to_TW, try_original_work_title) {
const using_title = try_original_work_title ? original_work_title : work_title;
let dictionary_file_path_to_load = (try_original_work_title ? original_work_title__path_prefix : path_prefix)
+ (is_CeCC ? get_dictionary_file_paths.call(_this, 'PoS')[to_TW ? 'TW' : 'CN']
: 'additional.' + (to_TW ? 'to_TW' : 'to_CN') + '.txt');
if (_this.dictionary_file_path_loaded_Set.has(dictionary_file_path_to_load)) {
return;
}
if (!CeL.file_exists(dictionary_file_path_to_load)) {
if (!try_original_work_title)
check_and_load(is_CeCC, to_TW, true);
return;
}
if (try_original_work_title) {
CeL.info(`${load_tailored_dictionary.name}: 無《${work_title}》之特設辭典,改採原標題《${original_work_title}》之特設辭典。`);
}
const contains = CeL.read_file(dictionary_file_path_to_load);
// @see extract_work_title_from_file_path()
const PATTERN_indicate_work_title = /(\n\/\/|@)\s*(《(?<work_title>[^.\n]+?)》)/g;
let matched;
while (matched = PATTERN_indicate_work_title.exec(contains)) {
//console.trace(matched);
if (!matched.groups.work_title.startsWith(using_title)) {
CeL.warn(`${load_tailored_dictionary.name}: 特設辭典可能混入了其他作品的設定? (${dictionary_file_path_to_load}) ${matched[0]}`);
}
}
// free
matched = null;
if (options.show_message)
CeL.info(`${load_tailored_dictionary.name}: ${is_CeCC ? '載入 CeCC' : '設定載入 zh_conversion'} 用作品特設辭典 ${dictionary_file_path_to_load}`);
if (is_CeCC) {
load_dictionary.call(_this, dictionary_file_path_to_load, {
convert_to_language: to_TW ? 'TW' : 'CN', priority: 0,
// TODO: 自定 conversion_pairs,tailored dictionary 放在個別 conversion_pairs 中以避免污染。
tailored_key: using_title,
});
} else {
_this.dictionary_file_path_loaded_Set.add(dictionary_file_path_to_load);
// 警告: .add_conversions({sort:}) 必須配合 Converter.options @ CeL.zh_conversion!
(to_TW ? CeL_CN_to_TW : CeL_TW_to_CN)[CeL.zh_conversion.KEY_converter].add_conversions({
file_path: dictionary_file_path_to_load, remove_comments: true, sort: '主要繁簡轉換', tailored_key: using_title,
});
}
}
// ----------------------------------------------------
check_and_load(false, true);
check_and_load(false, false);
// ----------------------------------------------------
check_and_load(true, true);
check_and_load(true, false);
}
// ----------------------------------------------------------------------------
const KEY_files_loaded = Symbol('files loaded');
/** {String}辭典修訂測試集檔名前綴。 */
const KEY_watch_target_file_name_prefix = 'watch_target.';
/** {Number}最短英文作品標題長度。 */
const MIN_English_WORK_TITLE_LENGTH = 3;
/** {Number}最短非英文作品名稱長度。 */
const MIN_NON_English_WORK_TITLE_LENGTH = 2;
/** {RegExp}辭典修訂測試集檔名模式。 */
const PATTERN_watch_target_file_name = new RegExp(CeL.to_RegExp_pattern(KEY_watch_target_file_name_prefix)
+ /(?<work_title>[^.\n]+)\.(?<to_language>TW|CN)\.\w+$/.source);
function extract_work_title_from_file_path(file_path) {
const matched = file_path.match(PATTERN_watch_target_file_name);
if (!matched)
return;
const work_title = matched.groups.work_title;
const MIN_WORK_TITLE_LENGTH = /^[\u0020-\u00ff]*$/.test(work_title) ? MIN_English_WORK_TITLE_LENGTH : MIN_NON_English_WORK_TITLE_LENGTH;
if (work_title.length < MIN_WORK_TITLE_LENGTH) {
CeL.error(`${extract_work_title_from_file_path.name}: 作品名稱長度起碼須有${MIN_WORK_TITLE_LENGTH}個字元!跳過字典檔: ${file_path}`);
return;
}
return work_title;
}
/**
* 載入個別作品辭典修訂測試集。
*
* @param {String|Object}should_be_text__file_name 欲載入的檔案
* @param {Object}options 附加參數/設定選擇性/特殊功能與選項。
*
* @returns {Promise} conditions
*/
function load_text_to_check(should_be_text__file_name, options) {
//console.trace(should_be_text__file_name, options);
if (CeL.is_Object(should_be_text__file_name)) {
if (should_be_text__file_name.all) {
function load_directory(directory_name) {
CeL.read_directory(directory_name).forEach(from_file_name => {
const work_title = extract_work_title_from_file_path(from_file_name);
if (work_title) {
this.load_text_to_check(from_file_name, {
export: { work_title }
});
}
});
}
load_directory(this.test_articles_directory);
load_directory(this.test_articles_directory + this.test_articles_archives_directory);
return;
}
if (should_be_text__file_name.work_title) {
options = CeL.setup_options(options);
if (!options.export) {
options.export = {
work_title: should_be_text__file_name.work_title,
original_work_title: should_be_text__file_name.original_work_title,
};
}
let first_file_name;
if (!['work_title', 'original_work_title'].some((key) => {
const work_title = should_be_text__file_name[key];
if (!work_title)
return;
// e.g., "watch_target.第一序列.TW.txt"
const file_name = `${KEY_watch_target_file_name_prefix}${work_title}.${should_be_text__file_name.convert_to_language}.${DEFAULT_TEST_FILE_EXTENSION}`;
if (get_convert_from_text__file_path.call(this, file_name, { check_file_exists: true })) {
should_be_text__file_name = file_name;
return true;
}
if (!first_file_name)
first_file_name = file_name;
})) {
// 找不到辭典檔,但仍繼續執行,由後面的程序處理。
should_be_text__file_name = first_file_name;
}
//console.trace(should_be_text__file_name);
} else {
throw new Error(`${load_text_to_check.name}: Invalid should_be_text__file_name: ${JSON.stringify(should_be_text__file_name)}`);
}
}
let check_language = should_be_text__file_name.match(/\.(TW|CN)\.\w+$/);
//console.trace([should_be_text__file_name, check_language]);
if (!check_language) {
CeL.error(`${load_text_to_check.name}: 無法判別檔案之語言: ${should_be_text__file_name}`);
return;
}
check_language = check_language[1];
options.show_message = true;
this.load_tailored_dictionary(options);
const convert_to_text__data = get_convert_to_text__file_status.call(this, should_be_text__file_name, options);
// assert: CeL.is_Object(convert_to_text__data)
const should_be_text__file_path = convert_to_text__data.convert_from_text__file_path;
if (!this.generate_condition_for_language
|| options?.reset && !this.generate_condition_for_language.only_default) {
//console.trace('初始化。');
this.generate_condition_for_language = { [KEY_files_loaded]: [], only_default: true };
if (!options?.is_default)
this.load_default_text_to_check();
}
if (this.generate_condition_for_language[KEY_files_loaded].includes(should_be_text__file_path)) {
CeL.log([load_text_to_check.name + ': ', {
// gettext_config:{"id":"skip-the-loaded-file-$1"}
T: ['跳過已載入的檔案:%1', should_be_text__file_path]
}]);
return;
}
if (!options?.is_default)
delete this.generate_condition_for_language.only_default;
this.generate_condition_for_language[KEY_files_loaded].push(should_be_text__file_path);
const should_be_texts = get_paragraphs_of_file(should_be_text__file_path, { with_configurations: true });
if (!should_be_texts)
return;
const source_text__file_path = convert_to_text__data.convert_to_text__file_path;
if (convert_to_text__data.need_to_generate_new_convert_to_text__file) {
//console.trace('重新生成 .converted.* 解答檔案。');
const base_cache_directory = regenerate_converted.default_convert_options.cache_directory;
CeL.create_directory(base_cache_directory);
return this.regenerate_converted(should_be_text__file_path, source_text__file_path, {
...options,
convert_from_text__file_name: should_be_text__file_name, text_is_TW: check_language === 'TW',
convert_options: {
...regenerate_converted.default_convert_options,
cache_directory: CeL.append_path_separator(base_cache_directory + should_be_text__file_name)
}
}).then(setup_generate_condition_for.bind(this));
} else {
return setup_generate_condition_for.call(this);
}
function setup_generate_condition_for() {
// should_be_text__file_path: .TW.* 為轉換之答案/標的,因此檢查的是相反語言。 .converted 才是原文!
const source_texts = get_paragraphs_of_file(source_text__file_path);
if (!source_texts)
return;
if (should_be_texts.length !== source_texts.length) {
CeL.error(`${should_be_text__file_name} 與 ${should_be_text__file_path} 含有不同數量之字串!此${CeL.gettext.get_alias(check_language)}之標的檔與欲測試之項目數不符,將不採用解答!若檔案為自動生成,您可以刪除舊檔後,重新生成轉換標的檔案。`);
return;
}
//console.log(this.generate_condition_for_language);
// this.generate_condition_for_language[convert_to_language] = { convert_from_text: should_convert_to_text, ... }
const generate_condition_for = this.generate_condition_for_language[check_language]
|| (this.generate_condition_for_language[check_language] = new Map);
const generate_condition_for__title = `${options?.export?.work_title ? `《${options.export.work_title}》` : '通用 '
}${CeL.gettext.get_alias(check_language === 'TW' ? 'CN' : 'TW')}→${CeL.gettext.get_alias(check_language)}`;
should_be_texts.forEach((should_convert_to_text, index) => {
const configuration = should_be_texts.configurations[should_convert_to_text];
//console.trace([should_convert_to_text, configuration]);
let text = source_texts[index];
if (false && configuration) {
console.trace([text, should_convert_to_text, configuration]);
}
if (configuration?.原文) {
if (configuration.原文 === text) {
CeL.info(`${setup_generate_condition_for.name}: 轉換前後文字相同,無需設定"原文" ${JSON.stringify(text)}: ${JSON.stringify(configuration)}`);
} else {
configuration.original_text_converted = text;
text = configuration.原文;
}
}
//console.trace([check_language === 'TW' ? CeL_CN_to_TW(text) : CeL_TW_to_CN(text), should_convert_to_text]);
if (generate_condition_for.has(text)) {
CeL.log(`${setup_generate_condition_for.name}: ${generate_condition_for__title}: 重複設定 ${JSON.stringify(text)}。先前於這個檔案設定: ${generate_condition_for.get(text).source_text__file_path}`);
}
generate_condition_for.set(text, {
should_convert_to_text,
source_text__file_path,
...options?.export, ...configuration
});
});
//console.trace(generate_condition_for);
const totle_count = generate_condition_for.size;
CeL.info(`${load_text_to_check.name}: 自動檢核 ${should_be_texts.length}個${generate_condition_for__title
} 之字串。${totle_count === should_be_texts.length ? '' : `總共檢核 ${totle_count}個。`} From ${should_be_text__file_path}`);
//console.trace(this.generate_condition_for_language);
return this.generate_condition_for_language;
}
}
// 會在每次轉換都測試是否有相符之文字。
function load_default_text_to_check() {
this.text_to_check_files.forEach(from_file_name => this.load_text_to_check(from_file_name, { is_default: true }));
}
// 顯示用函數。
function report_text_to_check(options) {
if (!this.generate_condition_for_language)
return;
const SGR_style = CeL.interact.console.SGR_style;
const normal_style = (new SGR_style('fg=green;bg=black')).toString(), NG_style = (new SGR_style('fg=red;bg=white')).toString(), reset_style = (new SGR_style({ reset: true })).toString();
const generate_condition_for = this.generate_condition_for_language[options.convert_to_language];
//console.trace(generate_condition_for);
// lost_texts: 用來記錄、顯示還有哪些尚未處理。
const lost_texts = [], multi_matched = Object.create(null);
let OK_count = 0, NG_count = 0;
for (const [convert_from, convert_data] of generate_condition_for.entries()) {
if (!convert_data.work_title) {
// e.g., 常出錯詞語 @ this.text_to_check_files
continue;
}
const { check_result } = convert_data;
if (!check_result) {
lost_texts.push(convert_data.should_convert_to_text);
continue;
}
if (check_result.NG.length > 0 || check_result.OK.length /* + check_result.NG.length */ > 1) {
multi_matched[convert_from] = check_result.OK.length;
if (check_result.NG.length > 0)
multi_matched[convert_from] += ` + ${NG_style}${check_result.NG.length} NG${normal_style}`;
}
if (check_result.NG.length > 0)
NG_count++;
else
OK_count++;
}
const message = `${report_text_to_check.name}: ${OK_count} OK, ${NG_count
} NG.${lost_texts.length > 0 ? ` ${lost_texts.length} lost:\n\t${lost_texts.join('\n\t')}` : ''}`;
if (NG_count > 0) {
CeL.error(message);
} else {
CeL.log(message);
}
const multi_matched_keys = Object.keys(multi_matched);
if (multi_matched_keys.length > 0) {
// 這裡可以計算某個值出現幾次。
CeL.log({
// gettext_config:{"id":"count-of-multiple-matches"}
T: '多次匹配的計數:'
});
CeL.log(`${normal_style
}${multi_matched_keys.map(convert_from => `\t${convert_from}: \t${multi_matched[convert_from]}`).join('\n')
}${/* 似乎沒用,仍可能在最後留一長長的一排背景色。 */reset_style}`);
}
return { lost_texts, OK_count, NG_count };
}
// ----------------------------------------------------------------------------
const condition_delimiter = '+';
/*
conditions will be split by `condition_delimiter`:
word
PoS:word
PoS:
// "~": 指示此 condition 為標的文字(is_target)
~PoS:word
// "!": 指示選出不符合此條件的(not_match)
!PoS:word
~!PoS:word
// 末尾的"?": 表示此條件可有可無、可以跳過(is_optional)
~!PoS:word?
// --------------------------
word:
文字
/search_pattern/flags
/search_pattern/replace_to/flags
// "~/改成了錯誤的繁體pattern/正確的繁體replace_to/flags$" 表示先進行繁簡轉換再執行此處的替代,僅僅適用於標的文字(is_target)
~/pattern/replace_to/flags
文字~/pattern/replace_to/flags
/search_pattern/flags~/pattern/replace_to/flags
文字<filter_name>filter_target
*/
// [ condition, is target, not match, tag (PoS), word / pattern, is optional / repeat range ]
const PATTERN_condition = /^(?<is_target>~)?(?<not_match>!)?(?:(?<tag>[^:+<>?\\\/]+):)?(?<word>.*?)(?<is_optional>\?)?$/;
// [ all, word, do_after_converting ]
const PATTERN_do_after_converting = new RegExp('^(?<word>.*?)~(?<do_after_converting>' + CeL.PATTERN_RegExp_replacement.source.slice(1, -1) + ')?$');
// JSON.stringify(): for "\n"
function stringify_condition(condition_text) {
// .replace(/\r/g, '\\r').replace(/\n/g, '\\n')
return JSON.stringify(condition_text).slice(1, -1).replace(/\\"/g, '"');
}
function word_data_to_condition(word_data, options) {
const tag = word_data[this.KEY_PoS_tag];
return (tag ? tag + ':' : '')
+ (options?.including_prefix_spaces && word_data[KEY_prefix_spaces] ? stringify_condition(word_data[KEY_prefix_spaces]) : '')
+ (typeof word_data[this.KEY_word] === 'string' &&
stringify_condition(word_data[this.KEY_word]) || word_data[this.KEY_word] || '');
}
// parse rule
// convert {String}full_condition_text to {Object}word_data or {Object}condition
function parse_condition(full_condition_text, options) {
let target_index;
function set_as_target(condition_data) {
condition_data.is_target = true;
condition_data.full_condition_text = full_condition_text;
if (options?.matched_condition)
condition_data.matched_condition = options.matched_condition;
}
const condition = [];
const full_condition_splitted = full_condition_text.split(condition_delimiter);
for (let index = 0, accumulated_target_index_diff = 0; index < full_condition_splitted.length; index++) {
let token = full_condition_splitted[index];
let matched = token.match(PATTERN_condition).groups;
if (/^\//.test(matched.tag) && /\(\?$/.test(matched.tag)) {
// e.g., "/^(?:a)$/"
matched.word = matched.tag + ':' + matched.word;
matched.tag = undefined;
//console.trace(matched);
}
const PATTERN_word_with_filter = /^(?<word>.*?)<(?<filter_name>[^<>\n*+?]+)>(?<filter_target>.*?)$/;
{
function test_if_is_regular(matched_group) {
let word_to_test = matched_group.word;
const filter = word_to_test.match(PATTERN_word_with_filter);
if (filter) {
word_to_test = filter.groups.filter_target;
}
if (!word_to_test.startsWith('/')) {
// not RegExp
return true;
}
//const PATTERN_unclosed_RegExp = /^\/(?:\\\/|[^\/])+$/;
//if (PATTERN_unclosed_RegExp.test(word_to_test)) return false;
return CeL.PATTERN_RegExp.test(word_to_test) || CeL.PATTERN_RegExp_replacement.test(word_to_test);
}
if (!test_if_is_regular(matched)) {
// 處理 RegExp pattern 中包含 condition_delimiter 的情況。
// e.g., ~里+/^许.+河$/ v:卷+m:/^[\\d〇一二三四五六七八九零十]+$/+~裡
const full_condition_splitted_expanded = Array.isArray(options.full_condition_splitted) ? full_condition_splitted.concat(options.full_condition_splitted.slice(options.index + 1)) : full_condition_splitted;
for (let combined_token = token, next_index = index; next_index < full_condition_splitted_expanded.length;) {
const next_token = full_condition_splitted_expanded[++next_index];
combined_token += condition_delimiter + next_token;
const _matched = combined_token.match(PATTERN_condition).groups;
if (test_if_is_regular(_matched)) {
token = combined_token;
matched = _matched;
accumulated_target_index_diff += next_index - index;
index = next_index;
//console.trace([token, matched]);
break;
}
}
if (index >= full_condition_splitted.length) {
// e.g., ~干<role.type:A1>/那.+何事$/
options.combined_token_count = index - full_condition_splitted.length + 1;
}
//console.log([full_condition_splitted_expanded, full_condition_splitted, options.full_condition_splitted?.slice(options.index + 1), options]);
//console.trace([index, target_index, accumulated_target_index_diff, token, matched]);
}
}
const condition_data = Object.create(null);
if (matched.is_target && !options?.no_target) {
set_as_target(condition_data);
if (target_index >= 0)
CeL.warn([parse_condition.name + ': ', {
// gettext_config:{"id":"there-are-multiple-conversion-targets-$1"}
T: ['有多個轉換標的:%1', full_condition_text]
}]);
else
target_index = index - accumulated_target_index_diff;
}
let do_after_converting = matched.word && matched.word.match(PATTERN_do_after_converting);
if (do_after_converting) {
do_after_converting = do_after_converting.groups;
matched.word = do_after_converting.word;
if (do_after_converting = do_after_converting.do_after_converting?.to_RegExp({ allow_replacement: true }))
condition_data.do_after_converting = do_after_converting;
}
if (matched.word) {
let filter = matched.word.match(PATTERN_word_with_filter);
if (filter) {
if (!this.condition_filter)
throw new Error('No .condition_filter set but set filter: ' + matched.word);
filter = filter.groups;
const _options = { no_target: true, full_condition_splitted, index };
Object.assign(condition_data, {
[this.KEY_word]: filter.word,
[KEY_filter_name]: filter.filter_name,
filter_target: parse_condition.call(this, filter.filter_target, _options)
});
//console.trace(condition_data);
if (_options.combined_token_count > 0) {
token = full_condition_splitted.slice(index, index + _options.combined_token_count + 1).join(condition_delimiter);
accumulated_target_index_diff += _options.combined_token_count;
index += _options.combined_token_count;
}
} else {
//const replace_pattern = matched.word.match();
condition_data[this.KEY_word] = CeL.PATTERN_RegExp.test(matched.word) || CeL.PATTERN_RegExp_replacement.test(matched.word)
? matched.word.to_RegExp({ allow_replacement: true })
// allow '\n', '\t' in filter.
: matched.word.replace(/\\\w/g, char => JSON.parse(`"${char}"`));
}
}
condition_data.condition_text = token;
if (matched.not_match) {
// !!: 採用字串作XOR運算,可能出現錯誤。 ('!'^true)===1
condition_data.not_match = !!matched.not_match;
//console.trace([matched, condition_data]);
}
if (matched.tag)
condition_data[this.KEY_PoS_tag] = matched.tag;
if (matched.is_optional)
condition_data.is_optional = true;
//console.trace(condition_data);
condition.push(condition_data);
}
if (!(target_index >= 0) && !options?.no_target) {
// 當僅僅只有單一 token 時,預設即為當前標的。
set_as_target(condition[0]);
}
if (condition.length === 1) {
return condition[0];
}
if (!options?.no_target) {
// default: set [0] as target.
condition.target_index = target_index || 0;
}
return condition;
}
// ------------------------------------------------------------------
// 顯示用函數。
const KEY_matched_condition = 'matched condition';
function print_correction_condition(correction_condition, {
work_title,
original_sentence_word_list,
tagged_convert_from_text,
zh_conversion_converted_pairs,
}) {
//console.trace(correction_condition);
const to_word_data = correction_condition.parsed[KEY_matched_condition];
let matched_condition_mark;
if (to_word_data) {
//console.log(correction_condition);
//console.log(correction_condition.parsed.parents);
//console.trace(to_word_data);
matched_condition_mark = ` 匹配的條件式: ${to_word_data.matched_condition ? `${to_word_data.matched_condition} → ` : ''}${to_word_data.full_condition_text}`;
CeL.warn(`Matched condition${matched_condition_mark}`);
}
//console.trace('自動提供可符合答案之候選條件式。');
CeL.info(`Candidate correction for ${JSON.stringify(correction_condition.parsed.text)}→${JSON.stringify(correction_condition.target)} (錯誤轉換為 ${JSON.stringify(correction_condition.error_converted_to)}):`);
if (tagged_convert_from_text) {
const list = correction_condition.slice(1).filter(correction => !correction.includes('<←'));
list.push(tagged_convert_from_text.join(condition_delimiter));
let zh_conversion_converted;
if (Array.isArray(zh_conversion_converted_pairs) && zh_conversion_converted_pairs.length > 0) {
const condition_text = correction_condition.parsed.text;
const pattern = new RegExp(`[${CeL.to_RegExp_pattern(condition_text).replace(/([-])/g, '\\$1')}]`);
//console.trace([condition_text, pattern]);
zh_conversion_converted = zh_conversion_converted_pairs.filter(
pair_text => pattern.test(pair_text.replace(/→.*$/, ''))
);
zh_conversion_converted = zh_conversion_converted.length > 0 ? ' 單純 zh_conversion 轉換過程: ' + zh_conversion_converted.unique().join(' ') : null;
}
CeL.info(`//${matched_condition_mark ? ' 解析錯誤 @' : ''}${work_title ? ` 《${work_title}》` : ''} ${stringify_condition(original_sentence_word_list)} (${list.join(' ')})${matched_condition_mark || ''}${zh_conversion_converted || ''}`);
}
CeL.info(correction_condition.join('\t'));
}
// 展示有問題的項目。
function print_section_report(configuration, options) {
const { tagged_word_list, condition_list, convert_from_text, convert_to_text, should_convert_to_text, show_tagged_word_list,
start_index, end_index, distance_token_header_to_metched } = configuration;
const { index_hash } = condition_list;
const SGR_style = CeL.interact.console.SGR_style;
const normal_style_tagged = (new SGR_style('fg=blue;bg=cyan')).toString(), marked_style_row = 'fg=red;bg=white', marked_style = (new SGR_style(marked_style_row)).toString(), reset_style = (new SGR_style({ reset: true })).toString();
const normal_style_convert_from_text_row = 'fg=green;bg=black';
const ansi_convert_from_text = new CeL.interact.console.SGR(convert_from_text);
let backward = 0, forward = 0;
const is_fragment = start_index >= 0 && should_convert_to_text.chars().length <= 4;
if (is_fragment) {
// 當截取的詞彙太短,自動擴張成一整句。
// assert: 0 <= start_index < end_index
let index = start_index;
// 向前找尋標點符號。
while (index > 0) {
const word_data = tagged_word_list[--index];
if (word_data[this.KEY_PoS_tag] === this.TAG_punctuation) {
// @see CeL.data.count_word()
if (index < start_index && /[、,;:。?!…]$/.test(word_data[this.KEY_word]))
index++;
break;
}
}
backward = start_index - index;
// assert: 0 <= backward <= start_index
// start from next tagged_word_list[], at least move 1 step.
// 向後找尋標點符號。
index = end_index;
while (index < tagged_word_list.length) {
const word_data = tagged_word_list[index++];
if (word_data[this.KEY_PoS_tag] === this.TAG_punctuation) {
break;
}
}
forward = index - end_index;
//console.trace([start_index, backward, end_index, forward]);
}
const tagged_word_list_pieces = start_index >= 0 ? tagged_word_list.slice(start_index - backward, end_index + forward) : tagged_word_list;
//console.trace(tagged_word_list_pieces);
let offset = convert_from_text.match(/^\s*/)[0].length, original_sentence_word_list = [];
const tagged_convert_from_text = [];
const matched_conditions = [];
//console.trace([convert_from_text, offset, distance_token_header_to_metched, start_index, backward]);
CeL.log(`${normal_style_tagged
}${CeL.gettext.get_alias(options.convert_to_language === 'TW' ? 'CN' : 'TW').slice(0, 1)
}\t${tagged_word_list_pieces.map((word_data, index) => {
const prefix_spaces = index > 0 && word_data[KEY_prefix_spaces] || '';
// condition filter 預設會排除 prefix spaces,因此將 prefix_spaces 另外列出。
// @see match_single_condition()
const text = stringify_condition(prefix_spaces) + word_data_to_condition.call(this, word_data);
tagged_convert_from_text.push(text);
original_sentence_word_list.push(prefix_spaces + word_data[this.KEY_word]);
const matched_condition_data = word_data[KEY_matched_condition];
if (matched_condition_data) {
//console.trace(matched_condition_data);
matched_conditions.push(matched_condition_data.matched_condition + ' → ' + matched_condition_data.condition_text);
}
if (backward && (index -= backward) < 0) {
return text;
}
if (prefix_spaces)
offset += prefix_spaces.length;
const start_offset = offset;
offset += word_data[this.KEY_word].length;
if (index === 0) {
// assert: convert_from_text.trimStart().startsWith(word_data_to_condition.call(this, word_data).slice(distance_token_header_to_metched));
if (distance_token_header_to_metched) {
//console.trace([distance_token_header_to_metched, prefix_spaces.length, word_data]);
// assert: distance_token_header_to_metched >= prefix_spaces.length
offset -= distance_token_header_to_metched - (word_data[KEY_prefix_spaces] || '').length;
}
}
if (!index_hash[start_index >= 0 ? start_index + index : index]) {
return text;
}