/
core.py
2099 lines (1927 loc) · 84.4 KB
/
core.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
# Definition of the processing context for Wikitext processing, and code for
# expanding templates, parser functions, and Lua macros.
#
# Copyright (c) 2020-2022, 2024 Tatu Ylonen. See file LICENSE and https://ylonen.org
import json
import logging
import re
import sqlite3
import sys
import tempfile
import urllib.parse
from collections import defaultdict, deque
from collections.abc import Sequence, Set
from dataclasses import dataclass
from functools import lru_cache
if sys.version_info < (3, 10):
from importlib_resources import files
else:
from importlib.resources import files
from pathlib import Path
from types import TracebackType
from typing import (
TYPE_CHECKING,
Callable,
Iterator,
Optional,
TypedDict,
Union,
)
from .common import (
MAGIC_FIRST,
MAGIC_LBRACKET_CHAR,
MAGIC_NOWIKI_CHAR,
MAGIC_RBRACKET_CHAR,
MAGIC_RE_PATTERN,
MAX_MAGICS,
URL_STARTS,
add_newline_to_expansion,
nowiki_quote,
)
from .luaexec import call_lua_sandbox
from .node_expand import NodeHandlerFnCallable, to_html, to_text, to_wikitext
from .parser import (
KIND_TO_LEVEL,
GeneralNode,
WikiNode,
parse_encoded,
set_html_tag_data,
set_inside_html_tags_re,
)
from .parserfns import PARSER_FUNCTIONS, call_parser_function
from .wikihtml import ALLOWED_HTML_TAGS, HTMLTagData
if TYPE_CHECKING:
from lupa.lua51 import LuaNumber, LuaRuntime, _LuaTable
NamespaceDataEntry = TypedDict(
"NamespaceDataEntry",
{
"aliases": list[str],
"content": bool,
"id": int,
"issubject": bool,
"istalk": bool,
"name": str,
},
total=True, # fields are obligatory
)
JsonValues = Union[str, int, float, list, dict, bool, None]
# Can't specify _LuaTable contents further, so no use specifying the Dict either
ParentData = tuple[str, Union["_LuaTable", dict[Union[int, str], str]]]
TemplateArgs = Union[dict[Union[int, str], str]]
TemplateFnCallable = Callable[
[
str, # name
TemplateArgs, # arguments
],
Optional[str], # expanded output
]
PostTemplateFnCallable = Callable[
[
str, # name
TemplateArgs, # arguments
str, # previously expanded from templatefn
],
Optional[str], # finalized expanded output
]
class ErrorMessageData(TypedDict):
msg: str
trace: str
title: str
section: str
subsection: str
called_from: str
path: tuple[str, ...]
class CollatedErrorReturnData(TypedDict):
errors: list[ErrorMessageData]
warnings: list[ErrorMessageData]
debugs: list[ErrorMessageData]
CookieData = tuple[str, Sequence[str], bool]
CookieChar = str
EMPTY_NAMESPACEDATA: NamespaceDataEntry = {
"id": -1,
"name": "NAMESPACE_DATA_ERROR",
"aliases": [],
"content": False,
"istalk": False,
"issubject": False,
}
@dataclass
class Page:
title: str
namespace_id: int
redirect_to: Optional[str] = None
need_pre_expand: bool = False
body: Optional[str] = None
model: Optional[str] = None
class BegLineDisableManager:
"""A 'context manager'-style object to use with `with` that increments
and decrements a counter used as a flag to see whether the parser
should care about tokens at the beginning of a line, used in magic_fn
to disable parsing when just looping through arguments"""
def __init__(self, ctx: "Wtp") -> None:
self.ctx = ctx
def __enter__(self) -> None:
self.ctx.begline_disable_counter += 1
self.ctx.begline_enabled = False
def __exit__(
self,
exc_type: type[BaseException],
exc_value: BaseException,
trace: TracebackType,
) -> None:
self.ctx.begline_disable_counter -= 1
if self.ctx.begline_disable_counter < 1:
self.ctx.begline_enabled = True
LINKS = (
# `[[something<abcd>]]`
# XXX this regex seems to be too complex,
# could you replace it with just [^][{}]*?
r"(?<!\[)"
+ r"\["
+ MAGIC_NOWIKI_CHAR
+ r"?\[("
+ r"(((?!\]\])[^[\|\n])*((?!\[\[)[^]\n])+)"
+ r"(\|(((?!\]\])[^[])*((?!\[\[)[^]])+))?" # after pipe no newlines, optnl.
+ r")\]"
+ MAGIC_NOWIKI_CHAR
+ r"?\]"
)
# (?<!\[) # negative lookbehind,
# # [[[ breaks the link completely,
# # the whole thing is not parsed as a link or url
# \[MAGIC_NOWIKI?\[ # start brackets
# (, optnl.
# (
# (?!\]\]) # negative lookahead, no ]] allowed
# [^[\n]
# )* # no [ or newlines allowed
# (
# (?!\[\[) # no [[ allowed
# [^]\n] # no ] or newlines
# )+
# )
# (\| # after a |, newlines are allowed, the below is the same as above
# (((?!\]\])[^[])*((?!\[\[)[^]])+)
# )?
# \]MAGIC_NOWIKI?\]
LINKS_RE = re.compile(LINKS)
# Encode external links: [something]
EXTERNAL_LINKS = r"\[([^][{}<>|\n]+)\]"
EXTERNAL_LINKS_RE = re.compile(EXTERNAL_LINKS)
# Encode template arguments: {{{arg}}}, {{{..{|..|}..}}}
TEMPLATE_ARGUMENTS = (
r"\{"
+ MAGIC_NOWIKI_CHAR
+ r"?\{"
+ MAGIC_NOWIKI_CHAR
+ r"?\{(("
+ r"[^{}]|" # No curly brackets (except inside cookies)
+ r"\{\|[^{}]*\|\}" # Outermost table brackets accepted?
+ r")*?)\}"
+ MAGIC_NOWIKI_CHAR
+ r"?\}"
+ MAGIC_NOWIKI_CHAR
+ r"?\}"
)
TEMPLATE_ARGUMENTS_RE = re.compile(TEMPLATE_ARGUMENTS)
TEMPLATES = (
r"\{" + MAGIC_NOWIKI_CHAR + r"?\{((?:"
r"[^{}]{?|" # lone possible { and also default "any"
r"}(?=[^{}])|" # lone `}`, (?=...) is not consumed (lookahead)
r"-{}-|" # GitHub issue #59 Chinese wiktionary special `-{}-`
r"}{|" # latex argument: "<math>\frac{1}{2}</math>"
r")+?)\}" + MAGIC_NOWIKI_CHAR + r"?\}"
)
TEMPLATES_RE = re.compile(TEMPLATES)
ALL_BRACKETS_RE = re.compile(
r"("
+ r"|".join((LINKS, EXTERNAL_LINKS, TEMPLATE_ARGUMENTS, TEMPLATES))
+ r")"
)
class Wtp:
"""Context used for processing wikitext and for expanding templates,
parser functions and Lua macros. The intended usage pattern is to
initialize this context once (this holds template and module definitions),
and then using the context for processing many pages."""
__slots__ = (
"db_path", # Database path
"db_conn", # Database connection
"cookies", # Mapping from magic cookie -> expansion data
"debugs", # List of debug messages (cleared for each new page)
"errors", # List of error messages (cleared for each new page)
"fullpage", # The unprocessed text of the current page (or None)
"lua", # Lua runtime or None if not yet initialized
"lua_invoke", # Lua function used to invoke a Lua module
"lua_reset_env", # Lua function to reset Lua environment
"lua_clear_loaddata_cache", # Lua function to clear mw.loadData() cache
"lua_path", # Path to Lua modules
"rev_ht", # Mapping from text to magic cookie
"expand_stack", # Saved stack before calling Lua function
"title", # current page title
"warnings", # List of warning messages (cleared for each new page)
# Data for parsing
"beginning_of_line", # Parser at beginning of line
"wsp_beginning_of_line", # Parser at beginning of line + whitespace
"begline_enabled", # in magic_fn, beginning_of_line = False
"begline_disable_counter",
"begline_disabled", # context-managerish thing for begline_en..
"linenum", # Current line number
"pre_parse", # XXX is pre-parsing still needed?
"parser_stack", # Parser stack
"section", # Section within page, for error messages
"subsection", # Subsection within page, for error messages
"suppress_special", # XXX never set to True???
"data_folder",
"NAMESPACE_DATA",
"LOCAL_NS_NAME_BY_ID", # Local namespace names dictionary
"NS_ID_BY_LOCAL_NAME",
"lang_code",
# Python functions for overriding template expanded text
"template_override_funcs",
"lua_env_stack",
"lua_frame_stack",
"project", # "wiktionary" or "wikipedia"
"strip_marker_cache",
"allowed_html_tags",
"html_permitted_parents",
"paired_html_tags",
"inside_html_tags_re",
"invoke_aliases",
)
def __init__(
self,
db_path: Optional[Union[str, Path]] = None,
lang_code="en",
template_override_funcs: dict[str, Callable[[Sequence[str]], str]] = {},
project: str = "wiktionary",
extension_tags: Optional[dict[str, HTMLTagData]] = None,
invoke_aliases: Optional[set[str]] = None,
file_aliases: Optional[set[str]] = None,
):
if isinstance(db_path, str):
self.db_path: Optional[Path] = Path(db_path)
else:
self.db_path = db_path
self.cookies: list[CookieData] = []
self.errors: list[ErrorMessageData] = []
self.warnings: list[ErrorMessageData] = []
self.debugs: list[ErrorMessageData] = []
self.section: Optional[str] = None
self.subsection: Optional[str] = None
self.lua: Optional["LuaRuntime"] = None
self.lua_invoke: Optional[
Callable[
[str, str, "_LuaTable", str, Optional[LuaNumber]],
tuple[bool, str],
]
] = None
self.lua_reset_env: Optional[Callable[[], "_LuaTable"]] = None
self.lua_clear_loaddata_cache: Optional[Callable[[], None]] = None
self.rev_ht: dict[CookieData, str] = {}
self.expand_stack: list[str] = [] # XXX: this has a confusing name
self.parser_stack: list["WikiNode"] = []
self.lang_code = lang_code # dump file language code
self.data_folder = files("wikitextprocessor") / "data" / lang_code
self.init_namespace_data()
self.create_db()
self.template_override_funcs = template_override_funcs
self.beginning_of_line = False
self.begline_enabled = True
self.begline_disable_counter = 0
self.begline_disabled = BegLineDisableManager(self)
self.wsp_beginning_of_line = False
self.title: Optional[str] = None
self.section = None
self.subsection = None
self.linenum = 1
self.pre_parse = False
self.suppress_special = False
self.lua_env_stack: deque["_LuaTable"] = deque()
self.lua_frame_stack: deque["_LuaTable"] = deque()
self.project = project
self.strip_marker_cache: defaultdict[str, int] = defaultdict(int)
self.allowed_html_tags: dict[str, HTMLTagData] = ALLOWED_HTML_TAGS
if extension_tags is not None:
self.allowed_html_tags.update(extension_tags)
# Set of HTML tags that need an explicit end tag.
self.paired_html_tags: set[str] = set(
k
for k, v in self.allowed_html_tags.items()
if not v.get("no-end-tag")
)
self.html_permitted_parents: dict[str, set[str]] = set_html_tag_data(
self
)
self.inside_html_tags_re: re.Pattern = set_inside_html_tags_re(self)
self.invoke_aliases = {"#invoke"}
if invoke_aliases is not None:
self.invoke_aliases |= invoke_aliases
def create_db(self) -> None:
from .wikidata import init_wikidata_cache
if self.db_path is None:
temp_file = tempfile.NamedTemporaryFile(
prefix="wikitextprocessor_tempdb", delete=False
)
self.db_path = Path(temp_file.name)
temp_file.close()
if self.backup_db_path.exists():
self.db_path.unlink(True)
self.backup_db_path.rename(self.db_path)
self.db_conn = sqlite3.connect(self.db_path, check_same_thread=False)
self.db_conn.executescript(
"""
CREATE TABLE IF NOT EXISTS pages (
title TEXT,
namespace_id INTEGER,
redirect_to TEXT,
need_pre_expand INTEGER,
body TEXT,
model TEXT,
PRIMARY KEY(title, namespace_id));
PRAGMA journal_mode = WAL;
"""
)
init_wikidata_cache(self)
@property
def backup_db_path(self) -> Path:
assert self.db_path
return self.db_path.with_stem(self.db_path.stem + "_backup")
def backup_db(self) -> None:
self.backup_db_path.unlink(True)
self.db_conn.commit()
backup_conn = sqlite3.connect(self.backup_db_path)
with backup_conn:
self.db_conn.backup(backup_conn)
backup_conn.close()
def close_db_conn(self) -> None:
assert self.db_path
self.db_conn.close()
if self.db_path.parent.samefile(Path(tempfile.gettempdir())):
for path in self.db_path.parent.glob(self.db_path.name + "*"):
# also remove SQLite -wal and -shm file
path.unlink(True)
def has_analyzed_templates(self) -> bool:
for (result,) in self.db_conn.execute(
"SELECT count(*) > 0 FROM pages WHERE need_pre_expand = 1"
):
return result == 1
return False
def build_sql_where_query(
self,
namespace_ids: Optional[list[int]] = None,
include_redirects: bool = True,
model: Optional[str] = None,
search_pattern: Optional[str] = None,
) -> tuple[str, tuple[Union[str, int], ...]]:
and_strs = []
where_str = ""
query_values: list[Union[int, str]] = []
if namespace_ids is not None:
and_strs.append(
f"namespace_id IN ({','.join('?' * len(namespace_ids))})"
)
query_values.extend(namespace_ids)
if not include_redirects:
and_strs.append("redirect_to IS NULL")
if search_pattern:
and_strs.append("body LIKE ?")
query_values.append(search_pattern)
if model is not None:
and_strs.append("model = ?")
query_values.append(model)
if len(and_strs) > 0:
where_str = " WHERE " + " AND ".join(and_strs)
return where_str, tuple(query_values)
def saved_page_nums(
self,
namespace_ids: Optional[list[int]] = None,
include_redirects: bool = True,
model: Optional[str] = None,
search_pattern: Optional[str] = None,
) -> int:
query_str = "SELECT count(*) FROM pages"
where_str, query_values = self.build_sql_where_query(
namespace_ids,
include_redirects,
model,
search_pattern,
)
query_str += where_str
for result in self.db_conn.execute(query_str, query_values):
return result[0]
return 0 # Mainly to satisfy the type checker
def init_namespace_data(self) -> None:
with self.data_folder.joinpath("namespaces.json").open(
encoding="utf-8"
) as f:
self.NAMESPACE_DATA: dict[str, NamespaceDataEntry] = json.load(f)
self.LOCAL_NS_NAME_BY_ID: dict[int, str] = {
data["id"]: data["name"]
for data in self.NAMESPACE_DATA.values()
}
self.NS_ID_BY_LOCAL_NAME: dict[str, int] = {
data["name"]: data["id"]
for data in self.NAMESPACE_DATA.values()
}
def _fmt_errmsg(self, kind: str, msg: str, trace: Optional[str]) -> None:
assert isinstance(kind, str)
assert isinstance(msg, str)
assert isinstance(trace, (str, type(None)))
loc = self.title or "ERROR_TITLE"
if self.section is not None:
loc += "/" + self.section
if self.subsection is not None:
loc += "/" + self.subsection
if self.expand_stack:
msg += " at {}".format(self.expand_stack)
if self.parser_stack:
titles: list[str] = []
for node in self.parser_stack:
if node.kind in KIND_TO_LEVEL:
if not node.largs:
continue
lst = (
x if isinstance(x, str) else "???"
for x in node.largs[0]
)
title = "".join(lst)
titles.append(title.strip())
msg += " parsing " + "/".join(titles)
if trace:
msg += "\n" + trace
print("{}: {}: {}".format(loc, kind, msg))
sys.stdout.flush()
def error(
self, msg: str, trace: Optional[str] = None, sortid="XYZunsorted"
) -> None:
"""Prints an error message to stdout. The error is also saved in
self.errors."""
assert isinstance(msg, str)
assert isinstance(trace, (str, type(None)))
assert isinstance(sortid, str)
# sortid should be a static string only used to sort
# error messages into buckets based on where they
# have been called. There was previously some code for
# inspecting the stack trace here that did the same
# thing, but it was a bit costly.
self.errors.append(
{
"msg": msg,
"trace": trace or "",
"title": self.title or "ERROR_TITLE",
"section": self.section or "",
"subsection": self.subsection or "",
"called_from": sortid,
"path": tuple(self.expand_stack),
}
)
self._fmt_errmsg("ERROR", msg, trace)
def warning(
self, msg: str, trace: Optional[str] = None, sortid="XYZunsorted"
) -> None:
"""Prints a warning message to stdout. The error is also saved in
self.warnings."""
assert isinstance(msg, str)
assert isinstance(trace, (str, type(None)))
assert isinstance(sortid, str)
self.warnings.append(
{
"msg": msg,
"trace": trace or "",
"title": self.title or "ERROR_TITLE",
"section": self.section or "",
"subsection": self.subsection or "",
"called_from": sortid,
"path": tuple(self.expand_stack),
}
)
self._fmt_errmsg("WARNING", msg, trace)
def debug(
self, msg: str, trace: Optional[str] = None, sortid="XYZunsorted"
) -> None:
"""Prints a debug message to stdout. The error is also saved in
self.debug."""
assert isinstance(msg, str)
assert isinstance(trace, (str, type(None)))
assert isinstance(sortid, str)
self.debugs.append(
{
"msg": msg,
"trace": trace or "",
"title": self.title or "ERROR_TITLE",
"section": self.section or "",
"subsection": self.subsection or "",
"called_from": sortid,
"path": tuple(self.expand_stack),
}
)
self._fmt_errmsg("DEBUG", msg, trace)
def to_return(self) -> CollatedErrorReturnData:
"""Returns a dictionary with errors, warnings, and debug messages
from the context. Note that the values are reset whenever starting
processing a new word. The value returned by this function is
JSON-compatible and can easily be returned by a parallel process."""
return {
"errors": self.errors,
"warnings": self.warnings,
"debugs": self.debugs,
}
def _canonicalize_parserfn_name(self, name: str) -> str:
"""Canonicalizes a parser function name by replacing underscores by
spaces and sequences of whitespace by a single whitespace."""
name = re.sub(r"[\s_]+", " ", name)
if name not in PARSER_FUNCTIONS:
name = name.lower() # Parser function names are case-insensitive
return name
def _save_value(
self, kind: str, args: Sequence[str], nowiki: bool
) -> CookieChar:
"""Saves a value of a particular kind and returns a unique magic
cookie character for it."""
assert kind in (
"T", # Template {{ ... }}
"A", # Template argument {{{ ... }}}
"L", # link
"E", # external link
"N", # nowiki text
)
assert isinstance(args, (list, tuple))
assert nowiki in (True, False)
# print("save_value", kind, args, nowiki)
args = tuple(args)
v: CookieData = (kind, args, nowiki)
if v in self.rev_ht:
return self.rev_ht[v]
idx = len(self.cookies)
if idx >= MAX_MAGICS:
self.error(
"too many templates, arguments, or parser function calls",
sortid="core/372",
)
return ""
self.cookies.append(v)
ch = chr(MAGIC_FIRST + idx)
self.rev_ht[v] = ch
return ch
def _encode(self, text: str) -> str:
"""Encode all templates, template arguments, and parser function calls
in the text, from innermost to outermost."""
def vbar_split(v: str) -> list[str]:
args = list(
m.group(1)
for m in re.finditer(
# re.X = ignore whitespace and comments, re.I = ignore case
r"""(?xi)\|(
(
<([-a-zA-Z0-9]+)\b[^>]*(?<!/)> # html start tag
[^][{}]*? # element contents
# (including `|`'s)
</\3\s*> # end tag
| [^|] # everything else
)*
)""",
"|" + v, # first/only argument needs a vbar
)
)
return args
def repl_arg(m: re.Match) -> CookieChar:
"""Replacement function for template arguments."""
nowiki = MAGIC_NOWIKI_CHAR in m.group(0)
orig = m.group(1)
args = vbar_split(orig)
return self._save_value("A", args, nowiki)
# def repl_arg_err(m):
# """Replacement function for template arguments, with error."""
# nowiki = MAGIC_NOWIKI_CHAR in m.group(0)
# prefix = m.group(1)
# orig = m.group(2)
# args = vbar_split(orig)
# self.debug(
# "heuristically added missing }} to template arg {}"
# # a single "}" needs to be escaped as "}}" with .format
# .format(args[0].strip()),
# sortid="core/405",
# )
# return prefix + self._save_value("A", args, nowiki)
def repl_templ(m: re.Match) -> Union[CookieChar, str]:
# I know CookieChar == str, this is just for documentation.
"""Replacement function for templates {{name|...}} and parser
functions."""
whole_match = m.group(0)
nowiki = False
if whole_match.startswith(
"{" + MAGIC_NOWIKI_CHAR
) or whole_match.endswith(MAGIC_NOWIKI_CHAR + "}"):
nowiki = True # <nowiki/> inside `{{` or `}}`
args = vbar_split(m.group(1))
if len(args) == 0 or args[0] == "":
# Templates without a first argument (template name)
# are just rendered as text in wikimedia stuff.
return (
"{{"
+ "|".join(args)
+ "}}"
)
first_arg = args[0].strip()
if not first_arg.startswith("#") and MAGIC_NOWIKI_CHAR in args[0]:
nowiki = True # <nowiki/> before first pipe
if (
first_arg.startswith("#")
and ":" in first_arg
and MAGIC_NOWIKI_CHAR in first_arg[: first_arg.index(":")]
):
nowiki = True # <nowiki/> before parser function name
# print("REPL_TEMPL: args={}".format(args))
return self._save_value("T", args, nowiki)
# def repl_templ_err(m):
# """Replacement function for templates {{name|...}} and parser
# functions, with error."""
# nowiki = MAGIC_NOWIKI_CHAR in m.group(0)
# prefix = m.group(1)
# v = m.group(2)
# args = vbar_split(v)
# self.debug(
# "heuristically added missing }} to template {}"
# # a single "}" needs to be escaped as "}}" with .format
# .format(args[0].strip()),
# sortid="core/427",
# )
# return prefix + self._save_value("T", args, nowiki)
def repl_link(m: re.Match) -> CookieChar:
"""Replacement function for links [[...]]."""
m2 = ALL_BRACKETS_RE.search(
# check to see if link contains something that should be
# handled first
m.group(0)[2:-2],
)
if m2:
# print(f"{m.group(0)=}, {m.group(0)=}")
return m.group(0)
nowiki = MAGIC_NOWIKI_CHAR in m.group(0)
orig = m.group(1)
if MAGIC_NOWIKI_CHAR in orig:
# check if nowiki tag is direct child
root = parse_encoded(self, orig)
nowiki = False
for child in root.children:
if isinstance(child, str) and "<nowiki />" in child:
nowiki = True
break
args = vbar_split(orig)
# print("REPL_LINK: orig={!r}".format(orig))
if not any(s.strip() for s in args):
# empty [[ ]] links should really be rendered as
# [[#Language]], where language is the section we're in,
# but if something relies on this behavior I will eat my
# chocolate hat. Let's just return escaped brackets.
return "[[" + m.group(0)[2:-2] + "]]"
return self._save_value("L", args, nowiki)
def repl_extlink(m: re.Match) -> CookieChar:
"""Replacement function for external links [...]. This is also
used to replace bracketed sections, such as [...]."""
nowiki = MAGIC_NOWIKI_CHAR in m.group(0)
orig = m.group(1)
if not orig.startswith(URL_STARTS):
return MAGIC_LBRACKET_CHAR + orig + MAGIC_RBRACKET_CHAR
args = [orig]
return self._save_value("E", args, nowiki)
# Main loop of encoding. We encode repeatedly, always the innermost
# template, argument, or parser function call first. We also encode
# links as they affect the interpretation of templates.
# As a preprocessing step, remove comments from the text.
text = re.sub(r"(?s)<!--.*?-->", "", text)
while True:
prev = text
# Encode template arguments. We repeat this until there are
# no more matches, because otherwise we could encode the two
# innermost braces as a template transclusion.
# KJ: This inside-out parsing seems to work because wikitext
# can't parse ambiguous stuff either:
# {{ {{NAMESPACE}}}} <- parses "correctly" as a broken template
# {{{{NAMESPACE}}}} <- parses incorrectly as `{{{{NAMESPACE}}}}`
while True:
prev2 = text
# Encode links.
while True:
text = LINKS_RE.sub(repl_link, text)
if text == prev2:
break
prev2 = text
# Encode external links: [something]
text = EXTERNAL_LINKS_RE.sub(repl_extlink, text)
# Encode template arguments: {{{arg}}}, {{{..{|..|}..}}}
text = TEMPLATE_ARGUMENTS_RE.sub(repl_arg, text)
if text == prev2:
# When everything else has been done, see if we can find
# template arguments that have one missing closing bracket.
# This is so common in Wiktionary that I'm suspecting it
# might be allowed by the MediaWiki parser.
# This needs to be done before processing templates, as
# otherwise the argument with a missing closing brace would
# be interpreted as a template.
# Note: we don't want to do this for {{{!}}, as that is
# sometimes used inside {{#if|...}} for table start/end.
# XXX rejecting all possibly erroneous arguments because
# they contain a ! anywhere is not ideal.
# text = re.sub(
# r"([^{]){" # {{{{{1... is incorrect in wikitext
# + MAGIC_NOWIKI_CHAR
# + r"?{"
# + MAGIC_NOWIKI_CHAR
# + r"?{([^{}!]*?)}"
# + MAGIC_NOWIKI_CHAR
# + r"?}",
# repl_arg_err,
# text,
# )
# if text != prev2:
# continue
break
# Replace template invocation
text = TEMPLATES_RE.sub(repl_templ, text)
# We keep looping until there is no change during the iteration
if text == prev:
# When everything else has been done, see if we can find
# template calls that have one missing closing bracket.
# This is so common in Wiktionary that I'm suspecting it
# might be allowed by the MediaWiki parser. We must allow
# tables {| ... |} inside these.
# text = re.sub(
# r"([^{])\{" # Leave a space between ambiguous brackets
# + MAGIC_NOWIKI_CHAR
# + r"?{(("
# + r"[^{}]|"
# + r"{\|[^{}]*?\|}|" # Table brackets
# + r"}[^{}])+?)}", # Missing bracket
# repl_templ_err,
# text,
# )
# if text != prev:
# continue
break
prev = text
# Replace any remaining braces etc by corresponding character entities
# text = re.sub(r"\{([&|])", r"{\1", text)
# text = re.sub(r"\{([&|])", r"{\1", text)
# text = re.sub(r"[^|]\}", r"\1}", text)
# text = re.sub(r"[^|]\}", r"\1}", text)
# text = re.sub(r"\|", "|", text)
text = text.replace(MAGIC_LBRACKET_CHAR, "[")
text = text.replace(MAGIC_RBRACKET_CHAR, "]")
return text
def _template_to_body(self, title: str, text: Optional[str]) -> str:
"""Extracts the portion to be transcluded from a template body."""
assert isinstance(title, str)
assert isinstance(text, str), (
f"{text=!r} was passed " "into _template_to_body"
)
# Remove all comments
text = re.sub(r"(?s)<!--.*?-->", "", text)
# Remove all text inside <noinclude> ... </noinclude>
text = re.sub(r"(?is)<noinclude\s*>.*?</noinclude\s*>", "", text)
# Handle <noinclude> without matching </noinclude> by removing the
# rest of the file. <noinclude/> is handled specially elsewhere, as
# it appears to be used as a kludge to prevent normal interpretation
# of e.g. [[ ... ]] by placing it between the brackets.
text = re.sub(r"(?is)<noinclude\s*>.*", "", text)
# Apparently unclosed <!-- at the end of a template body is ignored
text = re.sub(r"(?s)<!--.*", "", text)
# <onlyinclude> tags, if present, include the only text that will be
# transcluded. All other text is ignored.
onlys = list(
re.finditer(
r"(?is)<onlyinclude\s*>(.*?)"
r"</onlyinclude\s*>|"
r"<onlyinclude\s*/>",
text,
)
)
if onlys:
text = "".join(m.group(1) or "" for m in onlys)
# Remove <includeonly>. They mark text that is not visible on the page
# itself but is included in transclusion. Also text outside these tags
# is included in transclusion.
text = re.sub(r"(?is)<\s*(/\s*)?includeonly\s*(/\s*)?>", "", text)
return text
def add_page(
self,
title: str,
namespace_id: Optional[int],
body: Optional[str] = None,
redirect_to: Optional[str] = None,
need_pre_expand: bool = False,
model: Optional[str] = "wikitext",
) -> None:
"""Collects information about the page and save page text to a
SQLite database file."""
if model is None:
model = "wikitext"
if namespace_id:
ns_prefix = self.LOCAL_NS_NAME_BY_ID.get(namespace_id, "") + ":"
else:
ns_prefix = ""
if namespace_id != 0 and not title.startswith(ns_prefix):
title = ns_prefix + title
if title.startswith("Main:"):
title = title[5:]
if (
namespace_id
== self.NAMESPACE_DATA.get("Template", {"id": None}).get("id")
and redirect_to is None
):
body = self._template_to_body(title, body)
self.db_conn.execute(
"""INSERT INTO pages (title, namespace_id, body,
redirect_to, need_pre_expand, model) VALUES (?, ?, ?, ?, ?, ?)
ON CONFLICT(title, namespace_id) DO UPDATE SET
body=excluded.body, redirect_to=excluded.redirect_to,
need_pre_expand=excluded.need_pre_expand, model=excluded.model""",
(title, namespace_id, body, redirect_to, need_pre_expand, model),
)
def _analyze_template(self, name: str, body: str) -> tuple[set[str], bool]:
"""Analyzes a template body and returns a set of the canonicalized
names of all other templates it calls and a boolean that is True
if it should be pre-expanded before final parsing and False if it
need not be pre-expanded. The pre-expanded flag is determined
based on that body only; the caller should propagate it to
templates that include the given template. This does not work for
template and template function calls where the name is generated by
other expansions."""
included_templates: set[str] = set()
pre_expand = False
# Determine if the template starts with a list item
# XXX should we expand other templates that produce list items???
contains_list = body.startswith(("#", "*", ";", ":"))
# Remove paired tables.
# What is left is unpaired tables, which is an indication that a
# template somewhere should be generating those table eventually,
# and thus needs to be pre-expanded.
table_start_pos = []
table_end_pos = []
# `[[wikt:/|}]]` in Template:Mon standard keyboard
# and `{{l|mul|} }}` in Template:punctuation are not end of table token
# but `|}]]` in Template:Lithuania map is a table
m: Union[re.Match, None]
for m in re.finditer(
r"""
(?<!{){\| # `{|` not after `{`, like `{{{|}}}`
|
\|}(?!\s*}) # `|}` not before ` }`
""",
body,
re.VERBOSE,
):
if m.group() == "{|":
table_start_pos.append(m.start())
else:
table_end_pos.append(m.end())
num_table_start = len(table_start_pos)
num_table_end = len(table_end_pos)
contains_unpaired_table = num_table_start != num_table_end
table_start = len(body)
table_end = table_start
if num_table_start > num_table_end and num_table_end > 0:
table_start = table_start_pos[num_table_start - num_table_end - 1]
table_end = table_end_pos[-1]
elif num_table_start < num_table_end and num_table_start > 0:
table_start = table_start_pos[0]
table_end = table_end_pos[num_table_start]
elif num_table_start > 0 and num_table_end > 0:
table_start = table_start_pos[0]
table_end = table_end_pos[-1]
unpaired_text = body[:table_start] + body[table_end:]
# Determine if the template contains table element tokens
# outside paired table start/end. We only try to look for
# these outside templates, as it is common to write each
# template argument on its own line starting with a "|".
outside = unpaired_text
while True:
# print("=== OUTSIDE ITER")
prev = outside
# handle {{{ }}} parameters without templates inside them
while True:
newt = re.sub(
# re.X, ignore white space and comments
r"""(?sx)\{\{\{ # {{{
( [^{}] # no {} except...
| \}[^}] # no }} unless...
| \}\}[^}] # they're definitely not }}}
)*?
\}\}\} # }}}
""",
"",
prev,
)
if newt == prev: