This repository was archived by the owner on Jan 7, 2026. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathtest_parser.py
More file actions
2215 lines (1819 loc) · 65.2 KB
/
test_parser.py
File metadata and controls
2215 lines (1819 loc) · 65.2 KB
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
import pytest
import os
from latex2json.parser import FRONTEND_STYLE_MAPPING, SECTION_LEVELS, PARAGRAPH_LEVELS
from latex2json.parser.tex_parser import LatexParser
from latex2json.utils.tex_utils import flatten_all_to_string
from tests.parser.latex_samples_data import TRAINING_SECTION_TEXT
# Replace setUp with fixtures
@pytest.fixture
def parser():
return LatexParser()
@pytest.fixture
def parsed_training_tokens(parser):
return parser.parse(TRAINING_SECTION_TEXT)
dir_path = os.path.dirname(os.path.abspath(__file__))
samples_dir_path = os.path.join(dir_path, "samples")
# Convert test classes to groups of functions
# TestParserText1 class becomes:
def get_title(token):
return flatten_all_to_string(token["title"])
def test_parse_sections(parsed_training_tokens):
sections = [token for token in parsed_training_tokens if token["type"] == "section"]
assert len(sections) == 5
start_level = SECTION_LEVELS["section"]
assert get_title(sections[0]) == "Training"
assert sections[0]["level"] == start_level
assert get_title(sections[1]) == "Training Data and Batching"
assert sections[1]["level"] == start_level + 1
assert get_title(sections[2]) == "Hardware and Schedule"
assert sections[2]["level"] == start_level + 1
regularization_section = None
for section in sections:
if get_title(section) == "Regularization":
regularization_section = section
break
assert regularization_section is not None
# check its label is there
assert regularization_section["labels"] == ["sec:reg"]
# check paragraphs
paragraphs = [
token for token in parsed_training_tokens if token["type"] == "paragraph"
]
assert len(paragraphs) == 2
assert get_title(paragraphs[0]) == "Residual Dropout"
assert paragraphs[0]["level"] == PARAGRAPH_LEVELS["paragraph"]
assert get_title(paragraphs[1]) == "Label Smoothing"
assert paragraphs[1]["level"] == PARAGRAPH_LEVELS["paragraph"]
def test_parse_subsections(parser):
text = r"""
\subsection{Training Data and Batching}
\subsubsection{Hardware and Schedule}
\paragraph{Regularization}
\subparagraph{Sub Regularization}
"""
parsed_tokens = parser.parse(text)
assert get_title(parsed_tokens[0]) == "Training Data and Batching"
assert parsed_tokens[0]["level"] == SECTION_LEVELS["section"] + 1
assert get_title(parsed_tokens[1]) == "Hardware and Schedule"
assert parsed_tokens[1]["level"] == SECTION_LEVELS["section"] + 2
assert get_title(parsed_tokens[2]) == "Regularization"
assert parsed_tokens[2]["level"] == PARAGRAPH_LEVELS["paragraph"]
assert get_title(parsed_tokens[3]) == "Sub Regularization"
assert parsed_tokens[3]["level"] == PARAGRAPH_LEVELS["subparagraph"]
def test_parse_equations(parsed_training_tokens):
equations = [
token for token in parsed_training_tokens if token["type"] == "equation"
]
# inline equations = 7
inline_equations = [token for token in equations if token.get("display") != "block"]
assert len(inline_equations) == 7
assert len(equations) == 8
def test_parse_citations(parsed_training_tokens):
# number of citations=5
citations = [
token for token in parsed_training_tokens if token["type"] == "citation"
]
assert len(citations) == 5
assert citations[0]["content"] == ["DBLP:journals/corr/BritzGLL17"]
def test_parse_refs(parser, parsed_training_tokens):
refs = [token for token in parsed_training_tokens if token["type"] == "ref"]
assert len(refs) == 1
assert refs[0]["content"] == ["tab:variations"]
labels = parser.labels
assert len(labels) == 1
assert "sec:reg" in labels
# TestParserEquations class becomes:
def test_math_mode_edge_cases(parser):
text = r"""
$a_1^2$ and $x_{i,j}^{2n}$ and $\frac{1}{2}$
$\left(\frac{1}{2}\right)$ and $\left[\frac{1}{2}\right]$
$\{x : x > 0\}$ and $|x|$ and $\|x\|$
$\sum_{i=1}^n$ and $\int_0^\infty$ and $\prod_{i=1}^n$
$\lim_{x \to \infty}$ and $\sup_{x \in X}$
"""
parsed_tokens = parser.parse(text)
equations = [t for t in parsed_tokens if t["type"] == "equation"]
assert len(equations) == 13
# TestParserNewCommands tests:
def test_command_definitions(parser):
text = r"""
\newcommand{\HH}{\mathbb{H}}
\newcommand{\I}{\mathbb{I}}
\newcommand{\E}{\mathbb{E}}
\renewcommand{\P}{\mathbb{P}}
\newcommand{\pow}[2][2]{#2^{#1}}
\newcommand{\dmodel}{d_{\text{model}}}
$\pow[5]{3}$ and $\HH$ and $\I$ and $\dmodel$
\newcommand*{\goodexample}[1]{#1}
\goodexample{Single line of text}
\newcommand{\myedit}[1]{#1 \newline(Edited by me)}
\myedit{First paragraph
Second paragraph}
"""
parsed_tokens = parser.parse(text)
equations = [token for token in parsed_tokens if token["type"] == "equation"]
commands = parser.commands
# Check if commands were stored correctly
assert "HH" in commands
assert "I" in commands
assert "E" in commands
assert "P" in commands
assert "pow" in commands
# Check command expansion in equations
assert equations[0]["content"].strip() == "3^{5}"
assert equations[1]["content"] == r"\mathbb{H}"
assert equations[2]["content"] == r"\mathbb{I}"
assert equations[3]["content"] == r"d_{\text{model}}"
last_token = parsed_tokens[-1]["content"]
split_content = [line.strip() for line in last_token.split("\n") if line.strip()]
assert len(split_content) == 4
assert split_content[0] == "Single line of text"
assert split_content[1] == "First paragraph"
assert split_content[2] == "Second paragraph"
assert split_content[3] == "(Edited by me)"
# command with required arg but if not given default to empty string
text = r"""
\newcommand{\ccc}[2]{arg1=#1, arg2=#2}
\ccc / \ccc{3} / \ccc{3}{4}
"""
parsed_tokens = parser.parse(text)
assert len(parsed_tokens) == 1
# split content
split_content = parsed_tokens[0]["content"].split("/")
assert len(split_content) == 3
assert split_content[0].strip() == "arg1=, arg2="
assert split_content[1].strip() == "arg1=3, arg2="
assert split_content[2].strip() == "arg1=3, arg2=4"
text = r"""
\newcommand{\successrate}{58.5\%}
\successrate{} success rate
"""
parsed_tokens = parser.parse(text)
assert parsed_tokens[0]["content"].strip() == r"58.5% success rate"
def test_recommand_definitions(parser):
text = r"""
\renewcommand{\outer}[2]{\inner{#1}{#2}}
\newcommand{\inner}[2]{(#1,#2)}
\outer{a}{b}
\renewcommand{\inner}[2]{[#1,#2]}
\outer{x}{y}
"""
parsed_tokens = parser.parse(text)
# Verify nested command expansion works correctly
text_content = []
for token in parsed_tokens:
ss = token["content"].split("\n")
for s in ss:
if s.strip():
text_content.append(s.strip())
assert text_content[0] == "(a,b)"
assert text_content[1] == "[x,y]"
def test_complex_math_command_definitions(parser):
text = r"""
% Command with 3 required arguments
\newcommand{\tensor}[3]{\mathbf{#1}_{#2}^{#3}}
% Command with 1 optional and 2 required arguments
\newcommand{\norm}[3][2]{\|#2\|_{#3}^{#1}}
\newcommand{\integral}[4][0]{\int_{#1}^{#2} #3 d#4}
% Command using other defined commands
\newcommand{\tensorNorm}[4]{\norm{\tensor{#1}{#2}{#3}}{#4}}
$\tensor{T}{i}{j}$ and $\norm[p]{x}{2}$ and $\norm{y}{1}$
$\integral{b}{f(x)}{x}$ and $\integral[a]{b}{g(x)}{x}$
$\tensorNorm{T}{i}{j}{\infty}$
"""
parsed_tokens = parser.parse(text)
equations = [token for token in parsed_tokens if token["type"] == "equation"]
# Check command storage
commands = parser.commands
assert "tensor" in commands
assert "norm" in commands
assert "integral" in commands
assert "tensorNorm" in commands
# Check expansions
expected_results = [
r"\mathbf{T}_{i}^{j}", # tensor expansion
r"\|x\|_{2}^{p}", # norm with optional arg
r"\|y\|_{1}^{2}", # norm with default optional arg
r"\int_{0}^{b}f(x)d{x}", # integral with defaults
r"\int_{a}^{b}g(x)d{x}", # integral with one optional
r"\|\mathbf{T}_{i}^{j}\|_{\infty}^{2}", # nested command
]
for eq, expected in zip(equations, expected_results):
c = eq["content"].replace(" ", "")
assert c == expected
parser.clear()
def test_newtoks(parser):
text = r"""
\newtoks\foo
\foo{hello}
After toks
"""
parsed_tokens = parser.parse(text)
assert parsed_tokens[0]["content"].strip() == "After toks"
assert "newtoks:foo" in parser.commands
parser.clear()
def test_command_with_environments(parser):
text = r"""
\newcommand{\Fma}{$F=ma$}
\newcommand{\myenv}[2]{
\begin {equation*}
#1 = #2
\Fma
\end{equation*}
}
\myenv{E}{mc^2}
"""
parsed_tokens = parser.parse(text)
# Check that we got one equation token
assert len(parsed_tokens) == 1
equation = parsed_tokens[0]
# Verify equation properties
assert equation["type"] == "equation"
assert equation["display"] == "block"
# Verify equation content includes both the substituted parameters
# and the expanded \Fma command
assert "E = mc^2" in equation["content"]
assert "F=ma" in equation["content"]
def test_alt_command_definitions(parser):
"""Test command definitions without braces"""
text = r"""
\newcommand\eps{\varepsilon}
$\eps$
"""
parsed_tokens = parser.parse(text)
equations = [token for token in parsed_tokens if token["type"] == "equation"]
# Check command storage
commands = parser.commands
assert "eps" in commands
# Check expansion
assert equations[0]["content"] == r"\varepsilon"
def test_newdef_definitions(parser):
text = r"""
\def\foo#1{bar #1}
\foo{hello}
"""
parsed_tokens = parser.parse(text)
assert parsed_tokens[0]["content"].strip() == "bar hello"
# test that \newcommand overrides \def
text = r"""
\def\foo#1{bar #1}
\newcommand\foo[1]{NOBAR #1}
\foo{hello}
"""
parsed_tokens = parser.parse(text)
assert parsed_tokens[0]["content"].strip() == "NOBAR hello"
text = r"""
\newcommand\addme[2]{#1+NONONO+#2}
\def\addme#1#2{
#1+#2
}
\begin{equation}
\addme{x}{y}
\end{equation}
"""
parsed_tokens = parser.parse(text)
assert parsed_tokens[0]["content"].strip() == "x+y"
# TestParserEnvironments tests:
def test_nested_environments(parser):
text = r"""
\begin{lemma}\label{tb} With probability $1-O(\eps)$, one has
\begin{equation}\label{t-bound}
\t = O_{\eps}(X^\delta).
\end{equation}
\end {lemma}
"""
parsed_tokens = parser.parse(text)
# Check environments
assert len(parsed_tokens) == 1
# Check lemma environment
lemma = parsed_tokens[0]
assert lemma["type"] == "math_env"
assert lemma["name"] == "lemma"
assert lemma["labels"] == ["tb"]
assert lemma["numbered"] is True
# Check equation environment
equation = lemma["content"][0]
for token in lemma["content"]:
if token["type"] == "equation" and "labels" in token:
equation = token
break
assert equation["labels"] == ["t-bound"]
def test_multiple_environments(parser):
text = r"""
\begin{theorem}
Statement
\begin{proof}
Proof details
\begin{subproof}
\item First point
\item Second point
\end{subproof}
\end{proof}
\end{theorem}
\begin{corollary}
\begin{equation}\label{nax}
\E \left|\sum_{j=1}^n \g(j)\right|^2 \leq C^2
\end{equation}
\label{COL}
\end{corollary}
"""
parsed_tokens = parser.parse(text)
theorem = parsed_tokens[0]
assert theorem["name"] == "theorem"
# check proof is nested inside theorem
proof = theorem["content"][1]
assert proof["name"] == "proof"
# check subproof is nested inside proof
assert proof["content"][0]["content"].strip() == "Proof details"
subproof = proof["content"][1]
assert subproof["name"] == "subproof"
corollary = parsed_tokens[1]
assert corollary["name"] == "corollary"
assert corollary["labels"] == ["COL"]
# check equation is nested inside corollary
equation = corollary["content"][0]
assert equation["content"] == r"\E \left|\sum_{j=1}^n \g(j)\right|^2 \leq C^2"
assert equation["labels"] == ["nax"]
def test_split_equation(parser):
text = r"""
\begin{equation}\label{jock}
\begin{split}
&\frac{1}{H} \sum_{H < H' \leq 2H} \sum_{a \in [1,\q^k], \hbox{ good}} \left|\sum_{m=1}^{H'} \tilde{\boldsymbol{\chi}}(a+m) \sum_{n = a+m \ (\q^k)} \frac{\h(n)}{n^{1+1/\log X}}\right|^2 \\
&\quad \ll_\eps \frac{\log^2 X}{\q^k} .
\end{split}
\end{equation}
"""
parsed_tokens = parser.parse(text)
equation = parsed_tokens[0]
assert equation["type"] == "equation"
assert equation["labels"] == ["jock"]
# check begin{split} is nested inside equation
split = equation["content"]
assert split.startswith(r"\begin{split}")
assert split.endswith(r"\end{split}")
def test_parse_equations_with_commands(parser):
text = r"""
\newcommand{\pow}[2][2]{#2^{#1}}
$$F=ma
E=mc^2
\pow{777}
$$
$\pow{x}$
\[
BLOCK ME
BRO
\pow[5]{A}
\]
\(XX, \pow[3]{B}\)
"""
parsed_tokens = parser.parse(text)
equations = [token for token in parsed_tokens if token["type"] == "equation"]
assert len(equations) == 4
block1 = equations[0]["content"]
block1 = block1.replace(" ", "")
# block1 contains F=ma, E=mc^2 and 777^{2}
assert "F=ma" in block1
assert "E=mc^2" in block1
assert "777^{2}" in block1
assert equations[0]["display"] == "block"
assert equations[1]["content"].replace(" ", "") == "x^{2}"
assert equations[1].get("display") != "block"
block2 = equations[2]["content"]
assert "BLOCK ME" in block2
assert "BRO" in block2
assert "A^{5}" in block2.replace(" ", "")
assert equations[2]["display"] == "block"
last_eqn = equations[3]["content"].replace(" ", "")
assert "B^{3}" in last_eqn
def test_align_block(parser):
text = r"""
\begin{align*}
\left(\E \left|\sum_{j=1}^n \g(jd)\right|^2\right)^{1/2} &= \left(\E \left| \sum_{i \geq 0: 3^i \leq n} \boldsymbol{\eps}_{i+l} \sum_{m \leq n/3^i} \chi_3(md') \right|^2\right)^{1/2} \\
&\leq \left(\sum_{i \geq 0: 3^i \leq n} 1\right)^{1/2}\\
&\ll \sqrt{\log n},
\end{align*}
"""
parsed_tokens = parser.parse(text)
align = parsed_tokens[0]
assert align["type"] == "equation"
assert align["display"] == "block"
content = align["content"]
assert content.startswith(r"\left(")
assert content.endswith(r"\sqrt{\log n},")
def test_parse_citations_with_titles(parser):
text = r"""
Regular citation \cite{DBLP:journals/corr/BritzGLL17}
Citation with title \cite[\textsc{Theorem} 2.1]{smith2023}
Multiple citations \cite{paper1,paper2}
"""
parsed_tokens = parser.parse(text)
citations = [token for token in parsed_tokens if token["type"] == "citation"]
# Test regular citation
assert citations[0]["content"] == ["DBLP:journals/corr/BritzGLL17"]
assert "title" not in citations[0]
# Test citation with title
assert citations[1]["title"] == [
{
"type": "text",
"content": "Theorem",
"styles": [FRONTEND_STYLE_MAPPING["textsc"]],
},
{"type": "text", "content": "2.1"},
]
assert citations[1]["content"] == ["smith2023"]
# Test multiple citations
assert citations[2]["content"] == ["paper1", "paper2"]
assert "title" not in citations[2]
def test_parse_citetext(parser):
text = r"""
\citetext{Smith et al. (2024) \citealt{smith2023}}
"""
parsed_tokens = parser.parse(text)
assert len(parsed_tokens) == 2
assert parsed_tokens[0]["type"] == "text"
assert parsed_tokens[0]["content"].strip() == "Smith et al. (2024)"
assert parsed_tokens[1]["type"] == "citation"
assert parsed_tokens[1]["content"] == ["smith2023"]
def test_parse_refs_and_urls(parser):
text = r"""
\url{https://www.tesla.com}
\href{https://www.google.com}{Google}
\hyperref[fig:modalnet]{ModalNet}
\ref{fig:modalnet}
"""
parsed_tokens = parser.parse(text)
refs = [token for token in parsed_tokens]
assert len(refs) == 4
assert refs[0]["type"] == "url"
assert refs[1]["type"] == "url"
assert refs[2]["type"] == "ref"
assert refs[3]["type"] == "ref"
assert "title" not in refs[0]
assert refs[0]["content"] == "https://www.tesla.com"
assert refs[1]["content"] == "https://www.google.com"
assert refs[1]["title"][0]["content"] == "Google"
assert refs[2]["title"][0]["content"] == "ModalNet"
assert refs[2]["content"] == ["fig:modalnet"]
assert "title" not in refs[3]
assert refs[3]["content"] == ["fig:modalnet"]
text = r"""
\newcommand{\cmd}{MY URL}
\href{\cmd}{MY LINK}
"""
parsed_tokens = parser.parse(text)
assert len(parsed_tokens) == 1
assert parsed_tokens[0]["type"] == "url"
assert parsed_tokens[0]["content"] == "MY URL"
def test_nested_items(parser):
text = r"""
\begin{enumerate}
\item Here is an item with a nested equation and a graphic:
\begin{minipage}{0.45\textwidth}
\begin{equation}
E = mc^2
\end{equation}
\begin{equation}
F = ma
\end{equation}
\end{minipage}%
\\
\begin{minipage}{0.45\textwidth}
\centering
\includegraphics[width=0.5\textwidth]{example-image}
\captionof{figure}{Example Image}
\end{minipage}
\item $asdasdsads$
\end{enumerate}
"""
parsed_tokens = parser.parse(text)
# Check the enumerate environment
assert len(parsed_tokens) == 1
enum_env = parsed_tokens[0]
assert enum_env["type"] == "list"
# Check items within enumerate
items = [token for token in enum_env["content"] if token["type"] == "item"]
assert len(items) == 2
# Check first item's nested content
first_item = items[0]
minipages = [
token
for token in first_item["content"]
if "name" in token and token["name"] == "minipage"
]
assert len(minipages) == 2
# Check equations in first minipage
first_minipage = minipages[0]
equations = [
token for token in first_minipage["content"] if token["type"] == "equation"
]
assert len(equations) == 2
assert equations[0]["content"] == "E = mc^2"
assert equations[1]["content"] == "F = ma"
# Check second minipage content
second_minipage = minipages[1]
graphics = [
token
for token in second_minipage["content"]
if token["type"] == "includegraphics"
]
assert len(graphics) == 1
assert graphics[0]["content"] == "example-image"
# Check second item's equation
second_item = items[1]
equations = [
token for token in second_item["content"] if token["type"] == "equation"
]
assert len(equations) == 1
assert equations[0]["content"] == "asdasdsads"
def test_item_with_label(parser):
text = r"""
\begin{itemize}
\label{label-top}
\item[*] First item with custom label
\item Second item
\item[+] \label{special-item} Third item with label % \begin{itemize}
\end{itemize}
"""
parsed_tokens = parser.parse(text)
itemize = parsed_tokens[0]
assert itemize["type"] == "list"
assert itemize["labels"] == ["label-top"]
items = [token for token in itemize["content"] if token["type"] == "item"]
assert len(items) == 3
# Check custom labels
assert items[0]["content"][0]["content"] == "First item with custom label"
assert items[1]["content"][0]["content"] == "Second item"
assert items[2]["content"][0]["content"] == "Third item with label"
# Check item with label
assert items[2]["labels"] == ["special-item"]
def test_algorithmic(parser):
text = r"""
\begin{algorithm}[H]
\caption{Sum of Array Elements \% Here is link \url{https://www.google.com}}
\label{alg:loop}
\begin{algorithmic}[1]
\Require{$A_{1} \dots A_{N}$}
\Ensure{$Sum$ (sum of values in the array)}
\Statex
\Function{Loop}{$A[\;]$}
\State {$Sum$ $\gets$ {$0$}}
\State {$N$ $\gets$ {$length(A)$}}
\For{$k \gets 1$ to $N$}
\State {$Sum$ $\gets$ {$Sum + A_{k}$}}
\EndFor
\State \Return {$Sum$}
\EndFunction
\end{algorithmic}
\end{algorithm}
"""
parsed_tokens = parser.parse(text)
algorithm = parsed_tokens[0]
assert algorithm["type"] == "algorithm"
assert len(algorithm["content"]) == 2
caption = algorithm["content"][0]
assert caption["type"] == "caption"
assert caption["labels"] == ["alg:loop"]
assert (
caption["content"][0]["content"].strip()
== "Sum of Array Elements % Here is link"
)
assert caption["content"][1]["type"] == "url"
assert caption["content"][1]["content"] == "https://www.google.com"
# algorithmic keep as literal?
algorithmic = algorithm["content"][1]
assert algorithmic["type"] == "algorithmic"
assert r"\Require{$A_{1} \dots A_{N}$}" in algorithmic["content"]
assert r"\Ensure{$Sum$ (sum of values in the array)}" in algorithmic["content"]
assert algorithmic["content"].strip().endswith(r"\EndFunction")
def test_figure(parser):
content = r"""
\begin{figure*}[h]
{\includegraphics[width=\textwidth, trim=0 0 0 36, clip]{./vis/making_more_difficult5_new.pdf}}
\caption{An example of the attention mechanism following long-distance dependencies in the encoder self-attention in layer 5 of 6. Many of the attention heads attend to a distant dependency of the verb `making', completing the phrase `making...more difficult'. Attentions here shown only for the word `making'. Different colors represent different heads. Best viewed in color.}
\end{figure*}
finish
""".strip()
tokens = parser.parse(content)
token = tokens[0]
assert token["type"] == "figure"
assert len(token["content"]) == 2
assert token["content"][0]["type"] == "includegraphics"
assert token["content"][1]["type"] == "caption"
def test_nested_figures(parser):
text = r"""
\begin{figure}[htbp]
\centering
\begin{subfigure}[b]{0.45\textwidth}
\centering
\includegraphics[width=\textwidth]{image.png}
\caption{First pendulum design}
\label{fig:pendulum-a}
\end{subfigure}
\hfill
\begin{subfigure}[b]{0.45\textwidth}
\centering
\includegraphics[width=\textwidth]{example-image-b}
\caption{Second pendulum design}
\label{fig:pendulum-b}
\end{subfigure}
\captionof{figure}{Different pendulum clock designs}
\label{fig:pendulum-designs}
\end{figure}
"""
parsed_tokens = parser.parse(text)
# Check main figure
assert len(parsed_tokens) == 1
figure = parsed_tokens[0]
assert figure["type"] == "figure"
# Check subfigures
subfigures = [token for token in figure["content"] if token["type"] == "subfigure"]
assert len(subfigures) == 2
# Check first subfigure
first_subfig = subfigures[0]
# Check first subfigure content
first_graphics = [
t for t in first_subfig["content"] if t["type"] == "includegraphics"
][0]
first_caption = [t for t in first_subfig["content"] if t["type"] == "caption"][0]
assert first_graphics["content"] == "image.png"
assert first_caption["content"][0]["content"] == "First pendulum design"
assert first_caption["labels"] == ["fig:pendulum-a"]
# Check second subfigure
second_subfig = subfigures[1]
# Check second subfigure content
second_graphics = [
t for t in second_subfig["content"] if t["type"] == "includegraphics"
][0]
second_caption = [t for t in second_subfig["content"] if t["type"] == "caption"][0]
assert second_graphics["content"] == "example-image-b"
assert second_caption["content"][0]["content"] == "Second pendulum design"
assert second_caption["labels"] == ["fig:pendulum-b"]
# Check main caption
main_caption = [t for t in figure["content"] if t["type"] == "caption"][0]
assert main_caption["content"][0]["content"] == "Different pendulum clock designs"
def test_complex_table(parser):
text = r"""
\newcommand{\HELLO}[1]{HELLO #1}
\begin{table}[htbp]
\centering
\begin {tabular}{|c|c|c|c|}
\hline
\multicolumn{2}{|c|}{\multirow{2}{*}{Region}} & \multicolumn{2}{c|}{Sales} \\
\cline{3-4}
\multicolumn{2}{|c|}{} & 2022 & 2023 \\
\hline
\multirow{2}{*}{North} & Urban & $x^2 + y^2 = z^2$ & 180 \\
& Rural & 100 & 120 \\
\hline
\multirow{2}{*}{\textbf{South} and \texttt{Texas}} & Urban & 200 & \begin{align} \label{eq:1} E = mc^2 \\ $F = ma$ \end{align} \\
& & 130 & 160 \\
Thing with \cite{elon_musk} & SpaceX & Tesla & Neuralink \\
\H{o} & \HELLO{WORLD} & \textyen\textdollar & \unknown \\
\hline
AA \& BB\newline CC & DD & EE &
\end{tabular}
\caption{Regional Sales Distribution}
\label{tab:sales}
\end{table}
"""
parsed_tokens = parser.parse(text)
table = parsed_tokens[0]
# Check table properties
assert table["type"] == "table"
assert table["numbered"] == True
# Check tabular content
tabular = table["content"][0]
assert tabular["type"] == "tabular"
assert tabular["column_spec"] == "|c|c|c|c|"
# Check specific cells
cells = tabular["content"]
# Check header cell with multicolumn and multirow
assert cells[0][0]["content"] == "Region"
assert cells[0][0]["rowspan"] == 2
assert cells[0][0]["colspan"] == 2
assert cells[1][0]["content"] == None
assert cells[1][0]["colspan"] == 2
assert cells[1][0]["rowspan"] == 1
assert cells[1][1:] == ["2022", "2023"]
assert cells[2][0]["content"] == "North"
assert cells[2][0]["rowspan"] == 2
assert cells[2][0]["colspan"] == 1
# Check equation cell
equation_cell = cells[2][2][0]
assert equation_cell["type"] == "equation"
assert equation_cell["content"] == "x^2 + y^2 = z^2"
assert equation_cell.get("display") != "block"
assert cells[3] == [None, "Rural", "100", "120"]
assert cells[4][0]["rowspan"] == 2
cell4_0 = cells[4][0]["content"]
assert cell4_0[0]["content"] == "South"
assert cell4_0[0]["styles"] == [FRONTEND_STYLE_MAPPING["textbf"]]
assert cell4_0[1]["content"].strip() == "and"
assert cell4_0[2]["content"] == "Texas"
assert cell4_0[2]["styles"] == [FRONTEND_STYLE_MAPPING["texttt"]]
# Check align environment cell
align_cell = cells[4][3][0]
assert align_cell["type"] == "equation"
assert align_cell["display"] == "block"
assert align_cell["labels"] == ["eq:1"]
assert cells[5] == [None, None, "130", "160"]
assert cells[6][1:] == ["SpaceX", "Tesla", "Neuralink"]
assert cells[6][0] == [
{"type": "text", "content": "Thing with "},
{"type": "citation", "content": ["elon_musk"]},
]
assert cells[7] == [
"ő",
"HELLO WORLD",
"¥$",
[{"type": "command", "command": "\\unknown"}],
]
assert cells[8] == ["AA & BB\n CC", "DD", "EE", None]
# Check caption
caption = table["content"][1]
assert caption["type"] == "caption"
assert caption["content"][0]["content"] == "Regional Sales Distribution"
assert caption["labels"] == ["tab:sales"]
def test_tabular_with_escaped_delimiters(parser):
text = r"""
\begin{tabular}{cc}
ssss \& 23333
\end{tabular}
"""
parsed_tokens = parser.parse(text)
assert parsed_tokens[0]["type"] == "tabular"
assert parsed_tokens[0]["content"] == [[r"ssss & 23333"]]
def test_nested_newcommands(parser):
text = r"""
\newcommand{\pow}[2][2]{#2^{#1}}
\newcommand{\uno}{1}
$\pow[5]{\uno}$
"""
parsed_tokens = parser.parse(text)
assert parsed_tokens[0]["content"] == "1^{5}"
parser.clear()
text = r"""
\newcommand{\imageat}{\tocat}
\newcommand{\tocat}{~[at]~}
\imageat{}math.ucla.edu
"""
tokens = parser.parse(text)
assert len(tokens) == 1
assert tokens[0]["content"].strip() == "~[at]~math.ucla.edu"
def test_newcommand_and_grouping(parser):
text = r"""
\newcommand\pow[2]{#1^{#2}}
{
\begin{figure}[h]
inside $\pow{3}{2}$
\end{figure}
}
"""
parsed_tokens = parser.parse(text)
# # Check total number of tokens
# assert len(parsed_tokens) == 7
# Check figure environment
figure = parsed_tokens[0]
assert figure["type"] == "figure"
assert figure["numbered"] == True
assert len(figure["content"]) == 2
# Check equation inside figure
equation = figure["content"][1]
assert equation["type"] == "equation"
assert equation["content"].replace(" ", "") == "3^{2}"
def test_comments(parser):
text = r"""
% Single line comment
Text % Comment after text
$E=mc^2$ % Comment after equation
\begin{equation} % Comment after environment start
F=ma % Comment in equation
\end{equation} % Comment after environment end
"""
parsed_tokens = parser.parse(text)
# Verify comments are stripped appropriately
equations = [t for t in parsed_tokens if t["type"] == "equation"]
assert equations[0]["content"].strip() == "E=mc^2"
assert "F=ma" in equations[1]["content"]
def test_footnote_with_environments(parser):
text = r"""
\newcommand{\Fma}{$F=ma$}
\footnote{
Here's a list: \Fma
\begin{itemize}
\item First point
\item Second point
\end{itemize}
}
"""