-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathtranslate-richtext.js
executable file
·4116 lines (3429 loc) · 153 KB
/
translate-richtext.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
#!/usr/bin/env node
// FIXME nodeTypeId is not stable
// https://github.com/tree-sitter/py-tree-sitter/issues/202
// py-tree-sitter is 10x slower than lezer-parser
//throw new Error("TODO update node ids of @lezer/html from version 1.3.6 to 1.3.9")
// based on src/alchi-book/scripts/translate.js
// TODO in exportLang, remove lang="en" from outputTemplateHtml
// when targetLang == "en"
// only keep <html lang="en">
// also remove (lang="en") from comments: <!--(lang="en") ... -->
// TODO add lang="de" to untranslated parts
// example:
// <span class="note">predictions<span style="display:none">
// TODO 16personalities macht Vorhersagen zur Kompatibilität
// </span></span>
// the annotation was not translated
// it had no explicit lang="de" attribute
// but it inherited lang from <html lang="de">
// FIXME to get the "joined" translations
// we have to send full sentences to the translator
// so we cannot remove "already translated" parts of sentences
// example:
// This is some sentence with <b>some already translated words</b>, you see?
// if the part "some already translated words" has already been translated
// and is already stored in the the translations database
// then we can only remove it from the source text for the "splitted" translation
// but not from the source text for the "joined" translation
/*
TODO remove empty <span> tags that were used only for lang="..."
<div lang="en" class="para">
Fuck the system! <span lang="de">Aber diesmal richtig.</span>
</div>
*/
// FIXME keep lang="..." of notranslate tags if sourceLang != targetLang
/*
<span lang="latin" class="notranslate">Si vis pacem, para bellum.</span>
<span lang="fr" class="notranslate">Laisse faire, la nature.</span>
*/
// TODO update existing translated documents
// TODO render a side-by-side view of source and translated text
// with aligned text parts
// TODO add "translation based on ..." info to the output html
// something like
// <meta name="translation-based-on-file-name" value="input.html" class="notranslate">
// <meta name="translation-based-on-git-blob" value="6183d1520516dfeb3ec3c77ec8248a7599d3e67d" class="notranslate">
// then the original file can be produced with
// git cat-file blob 6183d1520516dfeb3ec3c77ec8248a7599d3e67d
// TODO add "translated license" to non-english translations
// https://github.com/milahu/mit-license
// TODO autofix: "i.e." -> "in effect,"
// TODO autofix: "cannot" -> "can not"
// TODO test the "v2 beta" version of argos-translate
/*
cd ~/src/milahu/nur-packages
nix-build . -A python3Packages.argostranslate_2
PYTHONPATH=$PYTHONPATH:/nix/store/jinijfbh62d55bzzy9476wrgnglgr571-python3.10-argostranslate-2.alpha/lib/python3.10/site-packages
*/
// warning: this code is a horrible mess
// ideally i would do a rewrite from scratch
// but i dont have the time...
// write errors to stdout to keep stdout and stderr in sync
console.error = console.log;
const debugAlignment = false;
const translateComments = false;
const translateTitleAttr = false;
const translateMetaContent = true;
//const sleepBetweenTranslationRequests = 10 * 1000;
/*
// https://stackoverflow.com/a/39914235/10440128
function sleep(ms) {
return new Promise(resolve => setTimeout(resolve, ms));
}
*/
// see also
// https://webapps.stackexchange.com/questions/52668/prohibit-the-translation-of-pieces-of-text-in-google-translate/154694#154694
// https://github.com/ssut/py-googletrans/issues/99#issuecomment-848714972
// alternatives
// https://github.com/Frully/html-google-translate
// based on https://github.com/Frully/google-translate-open-api
// Free and unlimited
// (translate.google.com uses a token to authorize the requests.
// If you are not Google, you do not have this token
// and will have to pay $20 per 1 million characters of text)
// TODO translate svg files
// TODO refactor src/pages/*.html to use <lang.de> instead of <de> etc. -> make tags unambiguous
// e.g. <tr> can be turkish or table row
// TODO avoid double inserts
// TODO verify: all text-fragments are inserted
// TODO auto-detect sourceLangList from files in src/pages/*.html
// TODO post-process old and manual translations
// -> add/update rev="en#xxxxxxxx" (revision ID) to keep translations in sync
// use different encoding than base64? base32 or base16 (hex) -> better for filenames
// -> easier to build a content-addressable store to cache old versions
// con: text fragments are small -> use one large database file, e.g. jsonlines format
// collision safety? git uses short IDs of only 7 chars in base16
// FIXME [-{_>] can be translated to [-{_}]
// example: translations-store/de-en-sha1-7f77643ee85951e4b66d0b9656afaa78061d9898.translation.txt.broken-code
// input: input.html.sha1-6b994e5f12c80d8ffcb4a9722cd51460a39a1f96.groups.json
// for now, im manually fixing the translation.txt file
// based on the sequence of codes in the input files
// TODO maybe automate this fixing
// see "wild guess: the translator translated our code"
// TODO show context of the broken code: source versus translation
// TODO use unicode symbols instead of ascii codes?
// these should be non-text symbols, so they are not translated
// FIXME [_-_{] can be translated to [_-_-]
// translations-store/de-en-sha1-5d2fca6fd68c766edca573ca3abedcc6e23abab6.translation.txt.broken-code
// FIXME [</^<] can be translated to [</^ ^<]
// translations-store/de-en-sha1-01144fcc0bfa61f74471d152eed40852e072c780.translation.txt.broken-code
// FIXME ['-'^}] can be translated to ['-'^] ... }]
// es sind ja im Internet sämtliche ['-'^/] ['-'^_] Lehrpläne ['-'^{] ['-'^}] zugänglich
// there are all ['-'^/] ['-'^_] curricula ['-'^{] ['-'^] on the Internet }] accessible
// FIXME ['-</}] can be translated to ['-</{}]
// Bevor sie mich holten, wusste ich, sie würden kommen, ['-</}] jetzt sitze ich im Knast und werd jeden Tag vernommen.
// Before they took me, I knew they were coming, ['-</{}] now I'm in jail and being questioned every day.
// 12 safe symbols: []^'*-/_{}<>
// ascii codes
/*
const codeNumKey = "^'*-/_{}<>"; // 10 digits -> base 10 code
const codeNumRegexCharClass = "\\^'*-/_{}<>"; // escape ^ for regex character class
*/
// unicode codes
// also unicode codes are broken by google translate
// [☢☥] is replaced with [☢☤]
// error: duplicate replaceId 8740
// { _replacement: '[☢☤]', idxStr: '☢☤', replaceId: 8740, rest: '' }
// couldn't remember anything at all, [☢☡] except for the [☢☢] [☢☣] veracity of his claims [☢☤] [☢☤] [ ☢☥] . [☢☦] [☢☧] I stood there rigid many a time. [☢☨] [☢☩] You didn't know what to admire more, [☢☪] her eloquence or her art of [☢☫] [☢☬] lying [☢☭] [☢☮] .
// bewiesene [☢☢] [☢☣] Richtigkeit seiner Behauptungen [☢☤] [☢☥] . [☢☦] [☢☧] Ich stand manches Mal starr da. [☢☨] [☢☩] Man wußte nicht, was man mehr best
// TODO use single char unicode codes
// -> no, is also broken
// also broken: verbose ascii code `ref${num}`;
// [\"ref2663\"] also wenn sein Subtyp stabilere Bindungen zum gleichen Geschlecht hat, [\"ref2664\"] dann hat dieser Mensch auch \"heterosexuelle\" Bindungen (zum anderen Geschlecht), [\"ref2665\"] aber diese Bindungen sind eher labil (weniger stabil, seltener).
// ["ref2663"] i.e. if his subtype has more stable ties to the same sex, ["ref2664"] then this person also has "heterosexual" ties (to the opposite sex), ["ref2662"] "ref2665"] but these bonds are rather unstable (less stable, less common). ["ref2666"]
// translator can remove sentences
// missing refs: ref8383 ref8384 ref8385
// removed sentence: Die Missgeburt vom Jugendamt wird sich eine Kugel fangen
// but the translator works on this small text:
/*
Ich rasiere mein Äffchen und lass es anschaffen, [\"ref8380\"]
tret so lange auf dein Kopf, bis vier und drei acht machen. [\"ref8381\"] [\"ref8382\"]
Die Missgeburt vom Jugendamt wird sich eine Kugel fangen [\"ref8383\"] [\"ref8384\"] , [\"ref8385\"]
meine Eltern sind seit neun Jahren im Urlaub, Mann. [\"ref8386\"]
*/
/*
I'll shave my little monkey and have it done, ["ref8380"]
step on your head until four and three make eight.
My parents have been on vacation for nine years, man. ["ref8386"]
*/
// so... was the sentence removed because the translator is stupid or evil?
//const codeNumRegexCharClass = "\\u2600-\\u26FF";
// verbose ascii code `ref${num}`;
// "ref" as in "reference". this should look like a footnote-reference
const codeNumRegexCharClass = "0-9";
// FIXME translator removes unicode codes
// [⚪] [⚫] Ob und wie die Diagonal-Paare funktionieren, [⚬] weiss ich noch nicht. Diagonal-Paare: MS-FL und FS-ML. [⚭] [⚮]
// [⚪] [⚫] I don't yet know whether and how the diagonal pairs work. Diagonal pairs: MS-FL and FS-ML. [⚭] [⚮]
// warning: unsteady replaceIdRaw: 171 -> 173 = code: ⚫ -> ⚭
// -> [⚬] was removed, this is bad...
// we need codes that are ALWAYS preserved by the translator
// this looks better:
// [⚪] [⚫] ["ref6"] Ob ["ref7"] und ["ref8"] wie ["ref9"] die ["ref10"] Diagonal-Paare ["ref11"] funktionieren ["ref12"], ["ref1"] weiss ["ref2"] ich ["ref3"] noch ["ref4"] nicht ["ref5"]. ["ref13"] Diagonal-Paare ["ref14"]: MS-FL und FS-ML. ["ref15"] [⚭] [⚮]
// [⚪] [⚫] ["ref6"] Whether ["ref7"] and ["ref8"] work like ["ref9"] the ["ref10"] diagonal pairs ["ref11"] ["ref12"], ["ref1"] don't know ["ref2"] I ["ref3"] nor ["ref4"] ["ref5"]. ["ref13"] Diagonal pairs ["ref14"]: MS-FL and FS-ML. ["ref15"] [⚭] [⚮]
const removeRegexCharClass = [
'\u200B', // ZERO WIDTH SPACE from google https://stackoverflow.com/questions/36744793
].join('');
const artifactsRegexCharClass = removeRegexCharClass + [
' ', // space
// this is valid source text: […] = [...]
//'…', // 8230
].join('');
// "import" because this is used only in importLang
// where we have to deal with errors introduced by the translate service
const codeNumRegexCharClassImport = codeNumRegexCharClass + artifactsRegexCharClass;
// no. valid replacementId are all integers >= 0
// expected range: 9728 to 9983
/*
function isValidReplacementId(num) {
return (9728 <= num && num <= 9983);
}
*/
// ascii codes
//const encodeNumTable = Object.fromEntries(codeNumKey.split('').map((c, i) => [i, c]));
function encodeNum(num) {
// verbose ascii code `ref${num}`;
return `ref${num}`;
// ascii codes
//return num.toString().split('').map(i => encodeNumTable[i]).join('');
// unicode codes
// https://stackoverflow.com/questions/12746278/generate-a-list-of-unicode-characters-in-a-for-loop
// String.fromCharCode(9728)
// String.fromCharCode(9983)
// https://stackoverflow.com/questions/43150498/how-to-get-all-unicode-characters-from-specific-categories
// https://stackoverflow.com/questions/1337419/how-do-you-convert-numbers-between-different-bases-in-javascript
// https://en.wikipedia.org/wiki/Miscellaneous_Symbols
// 9728 = https://unicode-explorer.com/c/2600
// 9728 + 255 = https://unicode-explorer.com/c/26FF
// FIXME some codes are not translated @ single char unicode codes
// expected range: 9728 to 9983
// [♑] = 9809
// [♳] = 9843
// [☯]
// [♎]
// [♹]
// [☧]
// single char unicode codes
const outputBase = 256;
const digit = num % outputBase;
return String.fromCharCode(9728 + digit);
// convert base 10 to base 256
/*
const outputBase = 256;
let result = [];
do {
const digit = num % outputBase;
//const char = keys[digit];
const char = String.fromCharCode(9728 + digit);
result.push(char);
num = Math.trunc(num / outputBase);
} while (num != 0);
return result.reverse().join("");
*/
//return String.fromCharCode(9728 + (num % 256));
}
let decodeNumOffest = 0;
let decodeNumLastResult = 0;
// ascii codes
//const decodeNumTable = Object.fromEntries(codeNumKey.split('').map((c, i) => [c, i]));
function decodeNum(str) {
//const numStr = str.replace(/\s+/sg, '').split('').map(c => decodeNumTable[c]).join('');
// TODO also remove unicode spaces
let numStr = str.replace(/\s+/sg, '');
// verbose ascii code `ref${num}`;
if (!numStr.match(/^ref[0-9]+$/)) {
throw new Error(`decodeNum: invalid str: ${JSON.stringify(str)}`);
}
numStr = numStr.slice(4, -1);
return parseInt(numStr);
// unicode codes
/*
const inputBase = 256;
//if (!numStr.match(/^[0-9]+$/)) {
if (!numStr.match(/^[\u2600-\u26ff]+$/)) {
throw new Error(`decodeNum: invalid str: ${JSON.stringify(str)}`);
}
const chars = numStr.split('');
if (chars.length != 1) {
throw new Error(`decodeNum: invalid str length: ${JSON.stringify(str)}`);
}
const char = chars[0];
// 0 <= digit <= 255
const digit = char.charCodeAt(0) - 9728;
let result = decodeNumOffest + digit;
if (result < (decodeNumLastResult - inputBase/2)) {
// overflow
result += inputBase;
decodeNumOffest += inputBase;
}
decodeNumLastResult = result;
return result;
*/
}
/*
// unicode
function decodeNumRaw(str) {
const numStr = str.replace(/\s+/sg, '');
if (!numStr.match(/^[\u2600-\u26ff]+$/u)) {
throw new Error(`decodeNum: invalid str: ${JSON.stringify(str)}`);
}
const chars = numStr.split('');
if (chars.length != 1) {
throw new Error(`decodeNum: invalid str length: ${JSON.stringify(str)}`);
}
const char = chars[0];
// 0 <= digit <= 255
const digit = char.charCodeAt(0) - 9728;
return digit;
}
*/
/*
// ok
// test
console.log(`testing encodeNum and decodeNum ...`)
// reset state of decodeNum
decodeNumOffest = 0;
decodeNumLastResult = 0;
for (let num = 0; num < 255*255*10; num++) {
const code = encodeNum(num);
const numActual = decodeNum(code);
if (num != numActual) {
console.error(`encodeNum or decodeNum failed: num=${num} code=${JSON.stringify(code)} numActual=${numActual}`)
process.exit(1);
}
}
// ok
console.log(`testing encodeNum and decodeNum done`)
// reset state of decodeNum
decodeNumOffest = 0;
decodeNumLastResult = 0;
for (const num of [0, 256-1, 256, 2*256-1, 2*256, 3*256-1, 3*256, 4*256-1, 4*256]) {
const code = encodeNum(num);
const numActual = decodeNum(code);
console.log(`encodeNum(${num}) == ${JSON.stringify(code)} decodeNum(${JSON.stringify(code)}) == ${numActual}`)
}
// reset state of decodeNum
decodeNumOffest = 0;
decodeNumLastResult = 0;
process.exit(0);
*/
const dryRunExport = 0;
const dryRunImport = 0;
const showDebug = 0;
//const showDebug = 1;
const charLimit = 5000; // limit of google, deepl
//const charLimit = 1000; // good page size for manual translations or debugging
//const charLimit = 1500; // deepl without login
// deepl rate limit: 4 requests, each 5000 chars
// Want to keep translating? Try DeepL Pro for free.
// You’ve reached your free usage limit.
// You can use the free version of DeepL again in 24 hours
// or try DeepL Pro to translate now and get premium features.
let useXml = false;
let translatorName = 'google';
//let translatorName = 'deepl';
const previewTextLength = 500;
/*
const fs = require('fs');
const path = require('path');
//const appRoot = require('app-root-path').path;
const glob = require('fast-glob');
// https://github.com/taoqf/node-html-parser
// https://github.com/taoqf/node-html-parser/pull/253
const { parse: parseHtml } = require('node-html-parser');
const htmlEntities = require('he');
// TODO
// google translate client
// https://github.com/thedaviddelta/lingva-scraper
const LingvaScraper = require('lingva-scraper');
// https://github.com/chge/tasty-treewalker
// https://stackoverflow.com/questions/39309351/dom-tree-walker-as-an-exercisejs
const tastyTreewalker = require('tasty-treewalker');
const crypto = require("crypto");
*/
import fs from 'fs';
import path from 'path';
import crypto from 'crypto';
import child_process from 'child_process';
//import { parse as parseHtml } from 'node-html-parser'; // TODO remove
//import * as htmlparser2 from "htmlparser2";
// concrete syntax tree parser for html
// https://github.com/lezer-parser/html
import { parser as lezerParserHtml } from '@lezer/html';
// https://github.com/milahu/nix-eval-js
// https://github.com/milahu/lezer-parser-nix
import { formatErrorContext } from './format-error-context.js';
import glob from 'fast-glob';
import htmlEntities from 'he';
//import LingvaScraper from 'lingva-scraper';
import { todo } from 'node:test'; // TODO what?
//console.log("htmlEntities.encode", htmlEntities.encode("&<>'\"")); process.exit()
// no, this is a polyfill for the browser
//import tastyTreewalker from 'tasty-treewalker';
// no. broken
//import HTMLtoDOCX from "html-to-docx";
//const elevConf = require(appRoot + '/config/eleventy.config.js')();
//process.chdir(appRoot);
//const scriptPath = path.relative(appRoot, process.argv[1]);
//const inputDir = elevConf.dir.input;
//const infilesGlob = inputDir + '/pages/'+'*.html';
//const infilesGlob = 'input.html';
const infilesGlob = '';
//const sourceLangList = ['de', 'en']; // TODO get from 11ty metadata
async function main() {
const argv = process.argv.slice(1); // argv[0] is node
const langMap = {
zh: 'zh-CN', // simplified chinese
};
function getLang(str) {
if (str && str in langMap) return langMap[str];
return str;
}
// run this script from alchi/src/whoaremyfriends/
//const inputPath = 'input.html';
const inputPath = argv[1];
const targetLang = getLang(argv[2]);
const translationsPathList = argv.slice(3);
if (!inputPath || !targetLang) {
console.error(`error: missing arguments`);
console.error(`usage:`);
console.error(`# step 1: export text parts to a html file with links to translator`);
console.error(`node translate-richtext.js input.html en`);
console.error(`# step 2: import the translated text parts from a text file`);
console.error(`node translate-richtext.js input.html en translations.txt`);
return 1;
}
if (translationsPathList.length > 0) {
return await importLang(inputPath, targetLang, translationsPathList);
}
else {
return await exportLang(inputPath, targetLang);
}
}
async function exportLang(inputPath, targetLang) {
const inputHtml = fs.readFileSync(inputPath, 'utf8');
// no. HTMLtoDOCX is broken: TypeError: Cannot read properties of undefined (reading 'colSpan')
/*
const headerHTMLString = null;
const footerHTMLString = null;
const documentOptions = {
table: { row: { cantSplit: true } },
footer: false,
pageNumber: false,
};
const docxBuffer = await HTMLtoDOCX(inputHtml, headerHTMLString, documentOptions, footerHTMLString);
const docxPath = inputPath + ".src.docx";
fs.writeFileSync(docxPath, docxBuffer);
console.log(`done ${docxPath}`);
return 0;
*/
// .slice(0, 50*1000);
//const inputHtml = "<?xml a=\"b\"?><!doctype html><div id=\"asdf\" lang='foo'><a href=\"#\"><!-- my comment --></a></div>";
// debug...
// parse error
// - <a class="nofootnote" href="https://www.youtube.com/watch?v=Cm_O97phbec&t=4566"
// + <a class="nofootnote" href="https://www.youtube.com/watch?v=Cm_O97phbec&t=4566"t=4566"
// fixed by ignoring InvalidEntity
/*
const inputHtml = `
<div>
— Ken Jebsen im
<a class="nofootnote" href="https://www.youtube.com/watch?v=Cm_O97phbec&t=4566"
>100% Realtalk Podcast #72</a>
</div>
`
*/
/*
const inputHtml = `
<div>
— Ken Jebsen im
<a class="nofootnote" href="https://www.youtube.com/watch?v=Cm_O97phbec&t=4566&foo"
>100% Realtalk Podcast #72</a>
</div>
`
*/
/*
const inputHtml = `
<html lang="de">
<head>
<title>asdf</title>
<meta name="description" content="what">
<meta name="author" content="who">
</head>
</html>
`
*/
// fixed in https://github.com/lezer-parser/html/pull/11
/*
console.error(`debug: position 50119+-5:\n-------------------------\n` + inputHtml.slice(50119 - 5, 50119 + 5) + '\n-------------------------')
console.error(`debug: position 50119+-10:\n-------------------------\n` + inputHtml.slice(50119 - 10, 50119 + 10) + '\n-------------------------')
console.error(`debug: position 50119+-20:\n-------------------------\n` + inputHtml.slice(50119 - 20, 50119 + 20) + '\n-------------------------')
console.error(`debug: position 50119+-50:\n-------------------------\n` + inputHtml.slice(50119 - 50, 50119 + 50) + '\n-------------------------')
//console.error(`debug: position 50119+-100:\n-------------------------\n` + inputHtml.slice(50119 - 100, 50119 + 100) + '\n-------------------------')
*/
// node 5 = SelfClosingEndTag : "/>" : "/>"
//const inputHtml = "<img><br/>";
// freeze the input for later
const inputHtmlHash = 'sha1-' + sha1sum(inputHtml);
const inputPathFrozen = inputPath + '.' + inputHtmlHash;
console.error(`writing ${inputPathFrozen}`);
fs.writeFileSync(inputPathFrozen, inputHtml, 'utf8');
//const translationsDatabaseJsonPath = 'translations-database.json';
// TODO add sourceLang and targetLang to the file name
//const translationsDatabaseHtmlPath = 'translations-database.html';
// TODO add other translators: argos translate, deepl translator
//const translationsDatabaseHtmlPathGlob = 'translations-database-*.html';
const translationsDatabaseHtmlPathGlob = 'translations-google-database-*-*.html';
const translationsDatabase = {};
// parse translation databases
for (const translationsDatabaseHtmlPath of glob.sync(translationsDatabaseHtmlPathGlob)) {
console.log(`reading ${translationsDatabaseHtmlPath}`)
const sizeBefore = Object.keys(translationsDatabase).length;
parseTranslationsDatabase(translationsDatabase, fs.readFileSync(translationsDatabaseHtmlPath, 'utf8'));
const sizeAfter = Object.keys(translationsDatabase).length;
console.log(`loaded ${sizeAfter - sizeBefore} translations from ${translationsDatabaseHtmlPath}`)
}
// debug
/*
for (const key of Object.keys(translationsDatabase).slice(0, 10)) {
console.log(`1010: translationsDatabase[${key}] = ${translationsDatabase[key]}`);
}
*/
// note: lezer-parser is a CONCRETE syntax tree parser == CST parser
const htmlParser = lezerParserHtml.configure({
// https://lezer.codemirror.net/docs/ref/#lr.ParserConfig
// https://github.com/lezer-parser/html/blob/main/src/html.grammar
// FIXME strict lezer-parser fails on large inputs. SyntaxError: No parse at 50119
// TODO what is position 50119?
//strict: true, // throw on parse error
// fixed. dialect selfClosing is not working - parse error at SelfClosingEndTag
// https://github.com/lezer-parser/html/issues/13
// parse "/>" as SelfClosingEndTag
// parse ">" as EndTag
//dialect: "selfClosing",
// TODO? dialect noMatch
});
let htmlTree;
// parse input html
try {
htmlTree = htmlParser.parse(inputHtml);
}
catch (error) {
// https://github.com/lezer-parser/lr/blob/main/src/parse.ts#L300
if (error.message.startsWith("No parse at ")) {
// note: pos is the character position, not the byte position
const pos = parseInt(error.message.slice("No parse at ".length));
error.message += '\n\n' + formatErrorContext(inputHtml, pos);
}
throw error;
}
const rootNode = htmlTree.topNode;
//console.log(tree);
// https://codereview.stackexchange.com/a/97886/205605
// based on nix-eval-js/src/lezer-parser-nix/src/nix-format.js
/** @param {Tree | TreeNode} tree */
function walkHtmlTree(tree, func) {
const cursor = tree.cursor();
//if (!cursor) return '';
if (!cursor) return;
let depth = 0;
while (true) {
// NLR: Node, Left, Right
// Node
// NOTE InvalidEntity breaks the parser
// <a t="a&b&c">a&b&c</a>
// -> require valid input, throw on parse error
const cursorTypeId = cursor.type.id;
if (
//true || // debug: dont filter
!(
cursorTypeId == 15 || // Document
cursorTypeId == 20 || // Element
cursorTypeId == 23 || // Attribute
cursorTypeId == 21 || // OpenTag <script>
cursorTypeId == 30 || // OpenTag <style>
cursorTypeId == 36 || // OpenTag
cursorTypeId == 32 || // CloseTag </style>
cursorTypeId == 29 || // CloseTag </script>
cursorTypeId == 37 || // CloseTag
cursorTypeId == 38 || // SelfClosingTag
// note: this is inconsistent in the parser
// InvalidEntity is child node
// EntityReference is separate node (sibling of other text nodes)
cursorTypeId == 19 || // InvalidEntity: <a href="?a=1&b=2" -> "&" is parsed as InvalidEntity
//cursorTypeId == 17 || // EntityReference: "&" or "—" is parsed as EntityReference
false
)
) {
func(cursor)
}
// Left
if (cursor.firstChild()) {
// moved down
depth++;
continue;
}
// Right
if (depth > 0 && cursor.nextSibling()) {
// moved right
continue;
}
let continueMainLoop = false;
let firstUp = true;
while (cursor.parent()) {
// moved up
depth--;
if (depth <= 0) {
// when tree is a node, stop at the end of node
// == dont visit sibling or parent nodes
return;
}
if (cursor.nextSibling()) {
// moved up + right
continueMainLoop = true;
break;
}
firstUp = false;
}
if (continueMainLoop) continue;
break;
}
}
// note: always set this to zero before calling walkHtmlTree
let lastNodeTo = 0;
const debugPrintAst = false;
//const debugPrintAst = true;
// debug: print the AST
if (debugPrintAst) {
lastNodeTo = 0;
const maxLen = 30;
walkHtmlTree(rootNode, (node) => {
//const nodeSource = inputHtml.slice(lastNodeTo, node.to);
let nodeSource = JSON.stringify(inputHtml.slice(node.from, node.to));
let spaceNodeSource = JSON.stringify(inputHtml.slice(lastNodeTo, node.to));
if (nodeSource.length > maxLen) {
nodeSource = nodeSource.slice(0, maxLen);
}
if (spaceNodeSource.length > maxLen) {
spaceNodeSource = spaceNodeSource.slice(0, maxLen);
}
//console.log(`${node.from}: node ${node.type.id} = ${node.type.name}: ${nodeSource.length}: ${nodeSource.slice(0, 100)}...`)
//console.log(`${node.from}: node ${node.type.id} = ${node.type.name}: ${nodeSource.length}: ${JSON.stringify(nodeSource)}`)
//console.log(`${node.from}: node ${node.type.id} = ${node.type.name}: ${JSON.stringify(nodeSource)}`)
//console.log(`node ${node.type.id} = ${node.type.name}: ${JSON.stringify(nodeSource)}`)
// TODO better. wrap string in single quotes
// similar to python repr(...)
//const s = "'" + JSON.stringify(nodeSource).slice(1, -1).replace(/\\"/g, '"') + "'";
//const s = JSON.stringify(nodeSource).slice(0, 100);
console.log(`node ${String(node.type.id).padStart(2)} = ${node.type.name.padEnd(25)} : ${nodeSource.padEnd(maxLen)} : ${spaceNodeSource}`);
lastNodeTo = node.to;
});
return;
}
const checkParserLossless = false;
//const checkParserLossless = true;
if (checkParserLossless) {
// test the tree walker
// this test run should return
// the exact same string as the input string
// = lossless noop
let walkHtmlTreeTestResult = "";
lastNodeTo = 0;
walkHtmlTree(rootNode, (node) => {
const nodeSource = inputHtml.slice(lastNodeTo, node.to);
walkHtmlTreeTestResult += nodeSource;
lastNodeTo = node.to;
// debug: print the AST
//const s = JSON.stringify(nodeSource).slice(0, 100);
//console.log(`node ${node.type.id} = ${node.type.name}: ${s}`);
});
if (walkHtmlTreeTestResult != inputHtml) {
console.error('error: the tree walker is not lossless');
const inputPathFrozenError = inputPath + '.' + inputHtmlHash + '.error';
console.error(`writing ${inputPathFrozenError}`);
fs.writeFileSync(inputPathFrozenError, walkHtmlTreeTestResult, 'utf8');
console.error(`TODO: diff -u ${inputPathFrozen} ${inputPathFrozenError}`);
console.error(`TODO: fix the tree walker`);
process.exit(1);
}
console.error(`ok. the tree walker is lossless`);
walkHtmlTreeTestResult = "";
//return;
}
/*
let currentTagName = undefined;
*/
//function newTag(parent) {
function newTag() {
const tag = {
openSpace: null,
open: null,
nameSpace: null,
name: null,
attrs: [],
classList: [],
parent: null,
lang: null,
ol: null, // original language
// this tag (or a parent tag) has one of these attributes:
// class="... notranslate ..."
// style="... display:none ..."
notranslate: false,
hasTranslation: false, // tag has attribute: src-lang-id="en:some-id"
};
return tag;
}
lastNodeTo = 0;
let inNotranslateBlock = false;
let currentTag = undefined;
let attrName = undefined;
let attrNameSpace = "";
let attrIs = undefined;
let attrIsSpace = "";
let attrValueQuoted = undefined;
let attrValue = undefined;
let currentLang = undefined;
const textToTranslateList = [];
let outputTemplateHtml = "";
let tagPath = [];
let inStartTag = false;
let startTagNodes = [];
const htmlBetweenReplacementsList = [];
let lastReplacementEnd = 0;
let inAttributeValue = false;
// https://html.spec.whatwg.org/multipage/syntax.html#void-elements
const selfClosingTagNameSet = new Set([
"area", "base", "br", "col", "embed", "hr", "img",
"input", "link", "meta", "source", "track", "wbr"
]);
function isSelfClosingTagName(tagName) {
// note: this is case sensitive
// ideally this would use tagName.toLowerCase()
return selfClosingTagNameSet.has(tagName);
}
function trimNodeSource(str) {
return str.replace(/\s+/g, " ").trim();
}
function isSentenceTag(currentTag) {
// TODO nested tags? <li><a>asdf</a></li> should become "asdf."
return currentTag.name.match(/^(title|h[1-9]|div|li|td)$/) != null;
}
function nodeSourceIsEndOfSentence(nodeSource) {
return nodeSource.match(/[.!?]["]?\s*$/s) != null;
}
function shouldTranslateCurrentTag(currentTag, inNotranslateBlock, currentLang, targetLang) {
return (
inNotranslateBlock == false &&
currentTag.notranslate != true &&
// TODO remove. moved to currentTag.notranslate
//currentTag.hasTranslation == false &&
currentTag.lang != targetLang
// TODO remove. lang inheritance moved to newTag()
//currentLang != targetLang
);
}
function writeComment(...a) {
return;
const s = a.map(String).join(" ");
outputTemplateHtml += "\n<!-- " + s + " -->\n";
}
// walkHtmlTree rootNode
walkHtmlTree(rootNode, (node) => {
//console.log(node);
//console.log("node", node);
//console.log("node.name", node.type.name);
//console.log("node.type.name", node.type.name);
//console.log("node.type.id", node.type.id);
//console.log("node.from + to", node.from, node.to);
//console.log("node.rawTagName", node.rawTagName);
//console.log("node.toString", node.toString());
//const nodeSource = inputHtml.slice(node.from, node.to);
let nodeSource = inputHtml.slice(node.from, node.to);
let nodeSourceSpaceBefore = inputHtml.slice(lastNodeTo, node.from);
//console.log("nodeSource", nodeSource);
//console.log("nodeSource:", { lastNodeTo, nodeFrom: node.from, nodeTo: node.to, nodeSourceSpaceBefore, nodeSource });
// debug
false && console.log("node:", {
typeId: node.type.id,
typeName: node.type.name,
lastNodeTo,
nodeFrom: node.from,
nodeTo: node.to,
nodeSourceSpaceBefore,
nodeSource,
});
// validate nodeSourceSpaceBefore
if (nodeSourceSpaceBefore.match(/^\s*$/) == null) {
console.error((
`error: nodeSourceSpaceBefore must match the regex "\\s*". ` +
`hint: add "lastNodeTo = node.to;" before "return;"`
), {
lastNodeTo,
nodeFrom: node.from,
nodeTo: node.to,
nodeSourceSpaceBefore,
nodeSource,
nodeSourceContext: inputHtml.slice(node.from - 100, node.to + 100),
})
process.exit(1);
}
if (nodeSource == '<!-- <notranslate> -->') {
inNotranslateBlock = true;
outputTemplateHtml += `${nodeSourceSpaceBefore}${nodeSource}`;
lastNodeTo = node.to;
return;
}
else if (nodeSource == '<!-- </notranslate> -->') {
inNotranslateBlock = false;
outputTemplateHtml += `${nodeSourceSpaceBefore}${nodeSource}`;
lastNodeTo = node.to;
return;
}
const nodeTypeId = node.type.id;
const nodeTypeName = node.type.name;
/*
6 = StartTag: <
22 = TagName: html
24 = AttributeName: lang
25 = Is: =
26 = AttributeValue: "de"
4 = EndTag: >
*/
// start of open tag
// "<"
if (
nodeTypeName == "StartTag"
/*
nodeTypeId == 6 ||
nodeTypeId == 7 || // <script>
nodeTypeId == 10 || // <link>
false
*/
) {
if (
!(
nodeTypeId == 6 ||
nodeTypeId == 7 || // <script>
nodeTypeId == 8 || // <style>
nodeTypeId == 10 || // <link>
false
)