-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathtranslate-richtext.py
executable file
·3617 lines (2892 loc) · 149 KB
/
translate-richtext.py
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 python3
# FIXME translations_db_set is never called
# $ sqlite3 translations-cache.db "select count(1) from translations_cache"
# 0
# TODO export_lang must decode html entities to utf8
# TODO import_lang must encode html entities from utf8
# fixed: leading and trailing whitespace is lost when it should be part of text nodes
# this gives a different result than translate-richtext.js
# /~https://github.com/tree-sitter/tree-sitter-html/issues/87
# fixed in
# /~https://github.com/tree-sitter/tree-sitter-html/pull/89
import os
import sys
import re
import glob
import io
import json
import shutil
import hashlib
import subprocess
import html
import urllib.parse
import ast
import asyncio
import sqlite3
import tree_sitter_languages
# TODO? use aiohttp_chromium
from selenium_driverless import webdriver
from selenium_driverless.types.by import By
tree_sitter_html = tree_sitter_languages.get_parser("html")
"""
text = b"<b>asdf</b>"
tree = tree_sitter_html.parse(text)
print(tree.root_node.sexp())
sys.exit()
"""
#from format_error_context import formatErrorContext
show_debug = False
#show_debug = True
# limit of google, deepl
char_limit = 5000
translator_name = 'google'
preview_text_length = 500
debug_alignment = False
translate_comments = False
translate_title_attr = False
translate_meta_content = True
remove_regex_char_class = ''.join([
# ZERO WIDTH SPACE from google
# https://stackoverflow.com/questions/36744793
'\u200B',
])
artifacts_regex_char_class = ''.join([
remove_regex_char_class,
# space
' ',
])
code_num_regex_char_class = "0-9"
# "import" because this is used only in importLang
# where we have to deal with errors introduced by the translate service
code_num_regex_char_class_import = (
code_num_regex_char_class +
artifacts_regex_char_class
)
# https://stackoverflow.com/a/20372465/10440128
from inspect import currentframe
def __line__():
cf = currentframe()
return cf.f_back.f_lineno
def encode_num(num):
return "ref" + str(num)
def sha1sum(_bytes):
return hashlib.sha1(_bytes).hexdigest()
# NOTE xml processing instruction in xhtml gives a parse error
# <?xml version="1.0" encoding="UTF-8"?>
# /~https://github.com/tree-sitter/tree-sitter-html/issues/82
# but works with lezer-parser-html
# /~https://github.com/grantjenks/py-tree-sitter-languages/issues/59
# TODO better? get name-id mappings from parser binary?
with open(os.environ["TREE_SITTER_HTML_SRC"] + "/src/parser.c", "rb") as f:
parser_c_src = f.read()
tree_sitter_c = tree_sitter_languages.get_parser("c")
parser_c_tree = tree_sitter_c.parse(parser_c_src)
def walk_tree(tree):
cursor = tree.walk()
reached_root = False
while reached_root == False:
yield cursor.node
if cursor.goto_first_child():
continue
if cursor.goto_next_sibling():
continue
retracing = True
while retracing:
if not cursor.goto_parent():
retracing = False
reached_root = True
if cursor.goto_next_sibling():
retracing = False
if False:
# debug: print AST
node_idx = 0
max_len = 30
for node in walk_tree(parser_c_tree.root_node):
node_text = json_dumps(node_source)
if len(node_text) > max_len:
node_text = node_text[0:max_len] + "..."
#pfx = "# " if is_compound else " "
pfx = ""
print(pfx + f"node {node.kind_id:2d} = {node.type:25s} : {node_text:30s}")
node_idx += 1
#if node_idx > 100: break
sys.exit()
in_enum_ts_symbol_identifiers = False
in_char_ts_symbol_names = False
enum_name = None
current_identifier = None
enum_ts_symbol_identifiers = dict()
char_ts_symbol_names = dict()
for node in walk_tree(parser_c_tree.root_node):
node_source = node.text.decode("utf8")
if node.type == "type_identifier" and node.text == b"ts_symbol_identifiers":
in_enum_ts_symbol_identifiers = True
continue
if node.type == "pointer_declarator" and node.text == b"* const ts_symbol_names[]":
in_char_ts_symbol_names = True
continue
if in_enum_ts_symbol_identifiers:
if node.type == "identifier":
current_identifier = node_source
continue
if node.type == "number_literal":
enum_ts_symbol_identifiers[current_identifier] = (
int(node_source)
)
current_identifier = None
continue
if node.type == "}":
current_identifier = node_source
in_enum_ts_symbol_identifiers = False
continue
continue
if in_char_ts_symbol_names:
if node.type == "subscript_designator":
current_identifier = node_source[1:-1]
continue
if node.type == "string_literal":
char_ts_symbol_names[current_identifier] = (
ast.literal_eval(node_source)
)
current_identifier = None
continue
if node.type == "}":
current_identifier = node_source
in_char_ts_symbol_names = False
break
continue
#print("enum_ts_symbol_identifiers =", json_dumps(enum_ts_symbol_identifiers, indent=2))
#print("char_ts_symbol_names =", json_dumps(char_ts_symbol_names, indent=2))
# force user to use exact names from full_node_kind
# names can collide when grammars
# use the same names for different tokens...
# example: <!doctype html>
# both the full tag and the tag_name have the token name "doctype"
# sym_doctype = 26, // full doctype tag
# sym__doctype = 4, // tag_name of doctype tag
full_node_kind = enum_ts_symbol_identifiers
node_kind = dict()
for full_name, id in enum_ts_symbol_identifiers.items():
name = char_ts_symbol_names[full_name]
if len(list(filter(lambda n: n == name, char_ts_symbol_names.values()))) > 1:
# duplicate name
# force user to use full_name in full_node_kind
# also store full_name in node_kind
node_kind[full_name] = id
continue
node_kind[name] = id
# allow reverse lookup from id to name
node_name = [None] + list(node_kind.keys())
if show_debug:
#print("full_node_kind =", json_dumps(full_node_kind, indent=2))
print("node_kind =", json_dumps(node_kind, indent=2))
#print("node_kind document =", node_kind["document"])
# compound tags
# these are ignored when serializing the tree
compound_kind_id = set([
node_kind["document"],
#node_kind["doctype"],
full_node_kind["sym_doctype"], # full doctype tag
#full_node_kind["sym__doctype"], # tag_name of doctype tag
#node_kind["<!"],
#node_kind[">"],
node_kind["element"],
node_kind["script_element"],
node_kind["style_element"],
node_kind["sym_start_tag"],
node_kind["self_closing_tag"],
node_kind["end_tag"],
node_kind["attribute"],
#node_kind["quoted_attribute_value"], # keyerror
node_kind['"'], # double quote
node_kind["'"], # single quote
#node_kind["attribute_value"],
])
# /~https://github.com/tree-sitter/py-tree-sitter/issues/33
def walk_html_tree(tree, keep_compound_nodes=False):
global compound_kind_id
cursor = tree.walk()
reached_root = False
while reached_root == False:
is_compound = cursor.node.kind_id in compound_kind_id
# if filter_compound_nodes:
# if not is_compound:
# yield cursor.node
# #func(cursor.node) # slow?
# else:
# # dont filter
# #yield cursor.node
# func(cursor.node, is_compound)
#if not is_compound:
if keep_compound_nodes or not is_compound:
yield cursor.node
#func(cursor.node) # slow?
if cursor.goto_first_child():
continue
if cursor.goto_next_sibling():
continue
retracing = True
while retracing:
if not cursor.goto_parent():
retracing = False
reached_root = True
if cursor.goto_next_sibling():
retracing = False
# fs.writeFileSync
def write_file(file_path, content):
with open(file_path, 'w') as file:
file.write(content)
# JSON.stringify
def json_dumps(obj):
return json.dumps(obj, ensure_ascii=False, separators=(',', ':'))
# no: TypeError: Object of type RandomWriteList is not JSON serializable
#import collections
#class RandomWriteList(collections.UserList):
# https://stackoverflow.com/a/78147717/10440128
class RandomWriteList(list):
"list with random write access, like Array in javascript"
def __setitem__(self, idx, val):
try:
super().__setitem__(idx, val)
except IndexError:
self += [None] * (idx - len(self))
self.append(val)
# L = RandomWriteList()
# L[2] = "2"
# L[5] = "5"
# print("L", repr(L))
# assert L == [None, None, '2', None, None, '5']
class TranslationsDB():
def __init__(self, path):
self.path = path
self.con = sqlite3.connect(self.path)
self.cur = self.con.cursor()
self.create_table_source_text()
self.create_table_target_text()
def __del__(self):
self.con.commit()
self.con.close()
def create_table_source_text(self):
# populated by export_lang
table_name = "source_text"
sql_query = (
f"CREATE TABLE {table_name} (\n"
" id INTEGER PRIMARY KEY,\n"
#" key TEXT,\n" TODO? unique translation_key: source_lang + target_lang + source_text_hash
" source_lang TEXT,\n"
" source_text_hash TEXT,\n"
#" source_text_hash BLOB,\n"
" source_text TEXT,\n"
" UNIQUE (source_lang, source_text_hash)\n"
")"
)
try:
self.cur.execute(sql_query)
except sqlite3.OperationalError as exc:
if exc.args[0] != f"table {table_name} already exists":
raise
def create_table_target_text(self):
# populated by import_lang
table_name = "target_text"
sql_query = (
f"CREATE TABLE {table_name} (\n"
" id INTEGER PRIMARY KEY,\n"
" source_text_id INTEGER,\n"
# TODO with multiple translators, use separate tables for source_text and target_text
" target_lang TEXT,\n"
" translator_name TEXT,\n"
" target_text TEXT,\n"
" target_text_splitted TEXT,\n"
" UNIQUE (source_text_id, target_lang, translator_name)\n"
")"
)
try:
self.cur.execute(sql_query)
except sqlite3.OperationalError as exc:
if exc.args[0] != f"table {table_name} already exists":
raise
def add_source_text(self, source_lang, source_text_hash, source_text):
# note: this throws if xxx exists
sql_query = (
"INSERT INTO source_text ("
" source_lang, source_text_hash, source_text"
") VALUES ("
" ?, ?, ?"
")"
)
sql_args = (source_lang, source_text_hash, source_text)
try:
self.cur.execute(sql_query, sql_args)
#source_text_id = self.cur.lastrowid
#return source_text_id
except sqlite3.IntegrityError:
# UNIQUE constraint failed: source_text.source_lang, source_text.source_text_hash
pass
def get_source_text_id(self, source_lang, source_text_hash):
sql_query = (
"SELECT id FROM source_text WHERE "
"source_lang = ? AND source_text_hash = ? "
"LIMIT 1"
)
sql_args = (source_lang, source_text_hash)
row = self.cur.execute(sql_query, sql_args).fetchone()
if row == None:
return None
return row[0]
def add_target_text(self, source_lang, source_text_hash, target_lang, translator_name, target_text, target_text_splitted):
# note: this throws if xxx exists
source_text_id = self.get_source_text_id(source_lang, source_text_hash)
sql_query = (
"INSERT INTO target_text ("
" source_text_id, target_lang, translator_name, target_text, target_text_splitted"
") VALUES ("
" ?, ?, ?, ?, ?"
")"
)
sql_args = (source_text_id, target_lang, translator_name, target_text, target_text_splitted)
self.cur.execute(sql_query, sql_args)
#def has_target_text(self, source_lang, target_lang, source_text_hash):
def has_target_text(self, source_lang, source_text_hash, target_lang, translator_name=None):
source_text_id = self.get_source_text_id(source_lang, source_text_hash)
if source_text_id == None:
return False
sql_query = (
"SELECT 1 FROM target_text WHERE "
"source_text_id = ? AND target_lang = ? " +
("AND translator_name = ? " if translator_name else "") +
"LIMIT 1"
)
sql_args = [source_text_id, target_lang]
if translator_name:
sql_args.append(translator_name)
return self.cur.execute(sql_query, sql_args).fetchone() != None
#def get_target_text_list(self, source_lang, target_lang, source_text_hash):
def get_target_text(self, source_lang, source_text_hash, target_lang, translator_name):
"get target_text from one translator"
source_text_id = self.get_source_text_id(source_lang, source_text_hash)
if source_text_id == None:
return False
sql_query = (
"SELECT target_text, target_text_splitted FROM target_text WHERE "
"source_text_id = ? AND target_lang = ? AND translator_name = ? "
"LIMIT 1"
)
sql_args = (source_text_id, target_lang, translator_name)
return self.cur.execute(sql_query, sql_args).fetchone()
#def get_target_text_list(self, source_lang, target_lang, source_text_hash):
def get_target_text_list(self, source_lang, source_text_hash, target_lang):
"get target_text from all translators"
source_text_id = self.get_source_text_id(source_lang, source_text_hash)
if source_text_id == None:
return False
sql_query = (
"SELECT translator_name, target_text, target_text_splitted FROM target_text WHERE "
"source_text_id = ? AND target_lang = ? "
)
sql_args = (source_text_id, target_lang)
return self.cur.execute(sql_query, sql_args).fetchall()
# global state
translations_db = None
async def export_lang(input_path, target_lang, output_dir=""):
global translations_db
# tree-sitter expects binary string
#with open(input_path, 'r') as f:
with open(input_path, 'rb') as f:
input_html_bytes = f.read()
input_html_hash = 'sha1-' + hashlib.sha1(input_html_bytes).hexdigest()
# TODO rename input_path_frozen to output_base
#output_base = output_dir + f"{input_path}.{input_html_hash}"
#input_path_frozen = output_dir + input_path + '.' + input_html_hash
output_dir = os.path.join(os.path.dirname(input_path), output_dir)
input_path_frozen = output_dir + os.path.basename(input_path) + '.' + input_html_hash
print(f'writing {input_path_frozen}')
with open(input_path_frozen, 'wb') as f:
f.write(input_html_bytes)
if not translations_db:
translations_db = TranslationsDB(output_dir + "translations-cache.db")
# TODO use self.cur
# translations_database_html_path_glob = output_dir + 'translations-google-database-*-*.html'
# translations_database = {}
# # parse translation databases
# print("parsing translation databases")
# for translations_database_html_path in glob.glob(translations_database_html_path_glob):
# print(f'reading {translations_database_html_path}')
# with open(translations_database_html_path, 'r') as f:
# parse_translations_database(translations_database, f.read())
#html_parser = lezer_parser_html.configure()
html_parser = tree_sitter_html
# parse input html
print("parsing input html")
try:
html_tree = html_parser.parse(input_html_bytes)
except exception as error:
if str(error).startswith("No parse at "):
pos = int(str(error)[len("No parse at "):])
error_message = str(error) + '\n\n' + format_error_context(input_html_bytes, pos)
raise exception(error_message)
raise error
#root_node = html_tree.top_node # lezer-parser
root_node = html_tree.root_node
# debug: print the AST
debug_print_ast = False
#debug_print_ast = True
if debug_print_ast:
print("debug_print_ast")
last_node_to = 0
node_idx = -1
max_len = 30
for node in walk_html_tree(root_node, keep_compound_nodes=True):
is_compound = node.kind_id in compound_kind_id
node_text = json_dumps(node_source)
if len(node_text) > max_len:
node_text = node_text[0:max_len] + "..."
space_node_text = json_dumps(input_html_bytes[last_node_to:node.range.end_byte].decode("utf8"))
if len(space_node_text) > max_len:
space_node_text = space_node_text[0:max_len] + "..."
pfx = "# " if is_compound else " "
print(pfx + f"node {node.kind_id:2d} = {node.type:25s} : {node_text:30s} : {space_node_text}")
last_node_to = node.range.end_byte
node_idx += 1
#if node_idx > 20: raise 123
return
check_parser_lossless = False
#check_parser_lossless = True
if check_parser_lossless:
# test the tree walker
# this test run should return
# the exact same string as the input string
# = lossless noop
print("testing walk_html_tree")
# /~https://github.com/tree-sitter/py-tree-sitter/issues/202
# py-tree-sitter is 10x slower than lezer-parser
#walk_html_tree_test_result = b"" # slow!
walk_html_tree_test_result = io.BytesIO()
last_node_to = 0
node_idx = -1
for node in walk_html_tree(root_node):
# if is_compound:
# return
# node_source_bytes = input_html_bytes[last_node_to:node.range.end_byte]
# last_node_to = node.range.end_byte
# walk_html_tree_test_result += node_source_bytes
# return
# debug...
# if not input_html_bytes.startswith(walk_html_tree_test_result):
# print("is ok", False)
# print("writing walk_html_tree_test_result.html")
# with open("walk_html_tree_test_result.html", "wb") as f:
# f.write(walk_html_tree_test_result)
# raise 1234
node_source_bytes = input_html_bytes[last_node_to:node.range.end_byte]
last_node_to = node.range.end_byte
#walk_html_tree_test_result += node_source_bytes # slow!
walk_html_tree_test_result.write(node_source_bytes)
# s = repr(node_source)
# if len(s) > 50:
# s = s[0:50] + "..."
# node_source = node_source_bytes.decode("utf8")
# if len(node_source) > 50:
# node_source = node_source[0:50] + "..."
# print(f" node kind_id={node.kind_id:2d} type={node.type:10s} is_named={str(node.is_named):5s} {s:25s} {repr(node_source)}")
node_idx += 1
#if node_idx > 20: raise 123
# copy whitespace after last node
# fix: missing newline at end of file
node_source_bytes = input_html_bytes[last_node_to:]
#walk_html_tree_test_result += node_source_bytes # slow!
walk_html_tree_test_result.write(node_source_bytes)
walk_html_tree_test_result = walk_html_tree_test_result.getvalue()
if walk_html_tree_test_result != input_html_bytes:
print('error: the tree walker is not lossless')
input_path_frozen_error = output_dir + input_path + '.' + input_html_hash + '.error'
print(f'writing {input_path_frozen_error}')
with open(input_path_frozen_error, 'w') as f:
f.write(walk_html_tree_test_result)
print(f'TODO: diff -u {input_path_frozen} {input_path_frozen_error}')
print('TODO: fix the tree walker')
sys.exit(1)
print('ok. the tree walker is lossless')
walk_html_tree_test_result = None
class Tag:
def __init__(self):
self.open_space = None
self.open = None
self.name_space = None
self.name = None
self.attrs = []
self.class_list = []
self.parent = None
self.lang = None
self.ol = None # original language
self.notranslate = False
self.has_translation = False
# FIXME these are never set?
self._from = None
self.to = None
def new_tag():
return Tag()
last_node_to = 0
in_notranslate_block = False
current_tag = None
attr_name = None
attr_name_space = ""
attr_is = None
attr_is_space = ""
attr_value_quote = None
attr_value_quoted = None
attr_value = None
current_lang = None
text_to_translate_list = []
#output_template_html = "" # slow!
output_template_html = io.StringIO()
tag_path = []
in_start_tag = False
html_between_replacements_list = []
last_replacement_end = 0
in_doctype_node = False
def is_self_closing_tag_name(tag_name):
return tag_name in ('br', 'img', 'hr', 'meta', 'link', 'DOCTYPE', 'doctype')
def is_sentence_tag(current_tag):
if not current_tag:
return False
if show_debug:
print("current_tag.name", repr(current_tag.name))
return re.match(r"^(title|h[1-9]|div|li|td)$", current_tag.name) != None
# function nodeSourceIsEndOfSentence
def node_source_is_end_of_sentence(node_source):
return re.search(r'[.!?]["]?\s*$', node_source) != None
def should_translate_current_tag(current_tag, in_notranslate_block, current_lang, target_lang):
return (
not in_notranslate_block and
not current_tag.notranslate and
current_tag.lang != target_lang
)
def write_comment(*a):
return
s = " ".join(map(str, a))
# TODO escape "-->" in s
output_template_html.write(f"\n<!-- " + s + " -->\n")
def format_tag(t):
name = t.name or "(noname)"
lang = t.lang or "?"
translate = "N" if t.notranslate else "Y"
return f"{name}.{lang}.{translate}"
def format_tag_path(tag_path):
return "".join(map(lambda t: "/" + format_tag(t), tag_path))
#return "".join(map(lambda t: "/" + (t.name or "(noname)"), tag_path))
#print("walk_html_tree")
for node in walk_html_tree(root_node):
# nonlocal last_node_to
# nonlocal in_notranslate_block
# nonlocal current_tag
# nonlocal attr_name
# nonlocal attr_name_space
# nonlocal attr_is
# nonlocal attr_is_space
# nonlocal attr_value_quote
# nonlocal attr_value_quoted
# nonlocal attr_value
# nonlocal current_lang
# nonlocal text_to_translate_list
# nonlocal output_template_html
# nonlocal tag_path
# nonlocal in_start_tag
# nonlocal html_between_replacements_list
# nonlocal last_replacement_end
# nonlocal in_doctype_node
# off by one error?
# or how is ">" added?
# node_source = input_html_bytes[last_node_to:node.range.end_byte].decode("utf8")
# node_source_space_before = input_html_bytes[last_node_to:node.range.start_byte].decode("utf8")
node_type_id = node.kind_id
node_type_name = node.type
#node_source = input_html_bytes[node.range.start_byte:node.range.end_byte].decode("utf8")
node_source = node.text.decode("utf8")
#node_source_space_before = input_html_bytes[(last_node_to + 1):node.range.start_byte].decode("utf8")
node_source_space_before = input_html_bytes[(last_node_to):node.range.start_byte].decode("utf8")
if show_debug:
s = repr(node_source)
if len(s) > 500:
s = s[0:500] + "..."
print(__line__(), "node", format_tag_path(tag_path), node.kind_id, node_name[node.kind_id], repr(node_source_space_before), repr(s))
def write_node():
# copy this node with no changes
nonlocal last_node_to
output_template_html.write(
node_source_space_before + node_source
)
if show_debug:
print("output_template_html.write", __line__(), repr(
node_source_space_before + node_source
))
last_node_to = node.range.end_byte
# fix: node_source_space_before == 'html'
# workaround
# doctype: parse all child nodes
# /~https://github.com/tree-sitter/tree-sitter-html/issues/83
# node 1 = <!: '<!' -> '<!'
# node 4 = doctype: 'DOCTYPE' -> 'DOCTYPE'
# node 3 = >: '>' -> '>'
#if node_type_id == node_kind["<!"]:
if node_type_id == node_kind["<!"] or node_type_id == node_kind["sym__doctype"]:
in_doctype_node = True
#last_node_to = node.range.end_byte
write_node()
continue
elif node_type_id == node_kind[">"] and in_doctype_node == True:
in_doctype_node = False
#in_start_tag = False
write_node()
continue
if show_debug:
s2 = repr(node_source)
if len(s2) > 500:
s2 = s2[0:500] + "..."
print(f"node {node.kind_id} = {node.type}: {s} -> {s2}")
# validate node_source_space_before
if re.match(r"""^\s*$""", node_source_space_before) == None:
print("node_source_space_before", __line__(), repr(node_source_space_before))
print((
f'error: node_source_space_before must match the regex "\\s*". ' +
'hint: add "last_node_to = node.range.end_byte;" before "return;"'
), {
'lastNodeTo': last_node_to,
'nodeFrom': node.range.start_byte,
'nodeTo': node.range.end_byte,
'nodeSourceSpaceBefore': node_source_space_before,
'nodeSource': node_source,
# FIXME this can break utf8
'nodeSourceContext': input_html_bytes[node.range.start_byte - 100:node.range.end_byte + 100].decode("utf8"),
})
sys.exit(1)
if node_source == '<!-- <notranslate> -->':
in_notranslate_block = True
#output_template_html += (
output_template_html.write(
node_source_space_before + node_source
)
if show_debug:
print("output_template_html.write", __line__(), repr(
node_source_space_before + node_source
))
last_node_to = node.range.end_byte
#return
continue
elif node_source == '<!-- </notranslate> -->':
in_notranslate_block = False
#output_template_html += (
output_template_html.write(
node_source_space_before + node_source
)
if show_debug:
print("output_template_html.write", __line__(), repr(
node_source_space_before + node_source
))
last_node_to = node.range.end_byte
#return
continue
"""
node 5 < 1 '< ...'
node 17 tag_name 4 'head ...'
node 3 > 1 '> ...'
node 7 </ 2 '</ ...'
node 17 tag_name 5 'title ...'
node 3 > 1 '> ...'
"""
# start of open tag
# if node_type_name == "StartTag":
# node 1 '<!'
# node 5 '<'
if node_type_id == node_kind["<!"] or node_type_id == node_kind["<"]:
parent_tag = current_tag
# if True:
# write_comment(__line__(), f"current_tag = new_tag()")
current_tag = new_tag()
# if True:
# write_comment(__line__(), "current_tag =", repr(current_tag))
# if True:
# write_comment(__line__(), "current_tag.attrs =", repr(list(map(lambda a: "".join(a), current_tag.attrs))))
if parent_tag:
# inherit notranslate from parent
current_tag.notranslate = parent_tag.notranslate
current_tag.lang = parent_tag.lang
current_tag.parent = parent_tag
# no. notranslate blocks are outside of the html node tree
# if in_notranslate_block:
# current_tag.notranslate = True
tag_path.append(current_tag)
if show_debug:
#if True:
#write_comment(__line__(), f"tag_path += {current_tag.name} -> tag_path: " + format_tag_path(tag_path))
print(__line__(), f"tag_path += {current_tag.name} -> tag_path: " + format_tag_path(tag_path))
in_start_tag = True
#print(__line__(), f"node {node_type_id} -> in_start_tag=True")
current_tag.open_space = node_source_space_before
current_tag.open = node_source
# dont write. wait for end of start tag
last_node_to = node.range.end_byte
continue
# start of close tag
# "</"
# elif node_type_name == "StartCloseTag":
# TODO sym__start_tag_name
elif node_type_id == node_kind["</"]: # node 7 </ 2 '</ ...'
if show_debug:
print(f"tag_path: " + format_tag_path(tag_path))
if is_sentence_tag(current_tag):
if current_lang is None:
source_start = node_source[:100]
# TODO show "outerHTML". this is only the text node
raise ValueError(f"node has no lang attribute: {repr(source_start)}")
text_to_translate = [
len(text_to_translate_list), # textIdx
"", # nodeSourceTrimmedHash
current_lang,
".", # nodeSourceTrimmed
1, # todoRemoveEndOfSentence
0, # todoAddToTranslationsDatabase
]
text_to_translate_list.append(text_to_translate)
# htmlBetweenReplacementsList.push("");
html_between_replacements_list.append("")
if show_debug:
print("html_between_replacements_list[-1]", __line__(), repr(html_between_replacements_list[-1]))
# end of tag
# or
# end of self-closing tag
# lezer-parser-html
# 36: node 4 = EndTag: 1: ">"
# 23: node 4 = EndTag: 2: "/>"
# lezer-parser-html with dialect = selfClosing
# /~https://github.com/lezer-parser/html/issues/13
# 36: node 4 = EndTag: 1: ">"
# 23: node xxx = SelfClosingEndTag: 2: "/>"
# tree-sitter-html
# node 3 = >: ">"
# node 6 = />: "/>"
elif node_type_id == node_kind[">"] or node_type_id == node_kind["/>"]:
if show_debug:
print(f"node {node_type_id}: current_tag.name = {current_tag.name}")
print(f"node {node_type_id}: in_start_tag = {in_start_tag}")
print(f"node {node_type_id}: is_self_closing_tag = {is_self_closing_tag_name(current_tag.name)}")
if in_start_tag:
# end of start tag
if show_debug:
print(f"node {node_type_id}: end of start tag -> in_start_tag=False")
# process and write the start tag
write_comment(json.dumps({
"tag_path": format_tag_path(tag_path),
"current_tag.name": current_tag.name,
"current_tag.notranslate": current_tag.notranslate,
"current_tag.attrs": list(map(lambda a: "".join(a), current_tag.attrs)),
}, indent=2))
# write " <some_name"
output_template_html.write(
# " <"
current_tag.open_space + current_tag.open +
# "some_name"
current_tag.name_space + current_tag.name +
""
)
#if current_tag.notranslate or current_tag.lang == target_lang:
if not should_translate_current_tag(current_tag, in_notranslate_block, current_lang, target_lang):
# preserve attributes
for attr_item in current_tag.attrs:
output_template_html.write("".join(attr_item))
#if should_translate_current_tag(current_tag, in_notranslate_block, current_lang, target_lang):
else:
# modify attributes
for attr_item in current_tag.attrs:
(
attr_name_space,
attr_name,
attr_is_space,
attr_is,
attr_value_space,
attr_value_quote,