/
lakhnawi.py
2199 lines (1840 loc) · 66.9 KB
/
lakhnawi.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
"""Lakhnawi pdf reverse engineering.
This is an effort to make the Lakhnawi PDF readable.
It is a text-based PDF, no images are used to represent text.
Yet the text is not easily extracted, due to:
* the use of private-use unicode characters that refer to heavily customised fonts;
* some fonts have some glyphs with dual unicode points;
* the drawing order of characters does not reflect the reading order;
* horizontal whitespace is hard to detect due to oversized bounding boxes of many
private-use characters.
We used the top-notch Python PDF library
[PyMUPDF](https://pymupdf.readthedocs.io/en/latest/index.html), also know as *fitz*.
```
pip3 install PyMuPDF
```
But even this library could not solve the above issues.
Here is how we solved the issues
# Private use characters
We used font analysis software from PdfLib:
[FontReporter](https://www.pdflib.com/download/free-software/fontreporter/)
to generate a
[report of character and font usage in the Lakhnawi PDF](https://github.com/among/fusus/blob/master/ur/Lakhnawi/FontReport-Lakhnawi.pdf).
Based on visual inspection of this font report and the occurrences of the private use tables
we compiled a translation table mapping dirty strings (with private use characters) to
clean strings (without private use characters).
# Dual code points
In case of dual code points, we ignore the highest code points.
Often the two code points refer to a normal Arabic code point and to a ligature or special form
of the character.
The unicode algorithm is very good nowadays to generate the special forms from the ordinary forms
based on immediate context.
# Reading order
We ordered the characters ourselves, based on the coordinates.
This required considerable subtlety, because we had to deal with diacritics above and below the lines.
See `clusterVert`.
# Horizontal whitespace
This is the most tricky point, because the information we retain from the PDF is, strictly speaking,
insufficient to determine word boundaries.
Word boundaries are partly in the eyes of the beholder, if the beholder knows Arabic.
The objective part is in the amount of whitespace between characters and the form of the characters
(initial, final, isolated).
But the rules of Arabic orthography allow initial characters inside words, and there are the enclitic
words.
So we only reached an approximate solution for this problem.
"""
import sys
import os
import collections
import re
from itertools import chain
from IPython.display import display, HTML, Image
import fitz
from tf.core.helpers import setFromSpec
from .parameters import SOURCE_DIR, UR_DIR, ALL_PAGES
from .lib import pprint
from .char import (
UChar,
getSetFromDef,
isAlefFinal,
isArDigit,
isEuDigit,
isMeemOrYeh,
isWaw,
normalizeC,
normalizeD,
uName,
)
NAME = "Lakhnawi"
SOURCE = f"{SOURCE_DIR}/{NAME}/{NAME.lower()}.pdf"
FONT = f"{UR_DIR}/{NAME}/FontReport-{NAME}.pdf"
DEST = f"{SOURCE_DIR}/{NAME}/{NAME.lower()}.txt"
CSS = """
<style>
*,
*:before,
*:after {
box-sizing: border-box;
}
@page {
size: A4;
margin: 2cm;
}
div.window {
display: flex;
flex-flow: row nowrap;
justify-content: flex-start;
align-items: flex-start;
min-width: 1000pt;
height: 99vh;
}
div.sidebar {
flex: 1 1 300pt;
display: flex;
flex-flow: row nowrap;
border-right: 1pt solid var(--fog-rim);
padding-left: 8px;
padding-right: 12px;
height: 99vh;
overflow: auto;
-webkit-overflow-scrolling: touch;
}
div.toc {
flex: 1 1 50pt;
}
div.pages {
flex: 0 0 700pt;
}
div.pages.bypage {
height: 99vh;
overflow: auto;
-webkit-overflow-scrolling: touch;
}
div.page {
margin-right: 1cm;
padding-left: 0.5cm;
max-width: 600pt;
min-width: 600pt;
width: 600pt;
}
div.pagec {
margin-right: 1cm;
padding-right: 10%;
width: 90%;
text-align: center;
}
div.phead {
color: #777777;
font-size: small;
text-align: right;
width: 1cm;
margin-right: -1cm;
float: right;
}
.r {
font-family: normal, sans-serif;
font-size: 22pt;
direction: rtl;
unicode-bidi: isolate-override;
}
.rc, .lc {
font-family: normal, sans-serif;
font-size: 22pt;
background-color: white;
border: 2pt solid #ffcccc;
}
.rc {
direction: rtl;
unicode-bidi: isolate-override;
}
.lc {
direction: ltr;
unicode-bidi: isolate-override;
}
p {
text-align: left;
direction: ltr;
unicode-bidi: isolate-override;
}
p.r {
text-align: right;
direction: rtl;
unicode-bidi: isolate-override;
}
.l {
font-family: normal, sans-serif;
font-size: x-large;
direction: ltr;
unicode-bidi: isolate-override;
}
.c {
font-family: monospace;
font-size: x-small;
direction: ltr;
unicode-bidi: isolate-override;
}
.p {
font-family: monospace;
font-size: medium;
font-weight: bold;
background-color: yellow;
direction: ltr;
unicode-bidi: isolate-override;
}
.lrg {
font-size: 22pt;
font-weight: bold;
}
span.sp {
background-color: #00ff00;
}
td.al {
text-align: left ! important;
}
div.cn {
text-align: center
}
div.ch.p {
background-color: #ffeedd;
text-align: center
}
span.cni {
background-color: #eeeeee;
padding-top: 4pt;
padding-bottom: 4pt;
padding-left: 8pt;
padding-right: 8pt;
border: 2pt solid #66aaaa;
display: inline-block;
}
div.ch,div.cht,div.chs {
border: 2pt solid #cccccc;
display: inline-flex;
flex-flow: column nowrap;
max-width: 10em;
}
div.ch {
background-color: #ddffff;
}
div.chs {
background-color: #ccffcc;
}
div.cht {
background-color: #44ff44;
}
div.sr {
display: flex;
flex-flow: row wrap;
direction: rtl;
unicode-bidi: isolate-override;
}
table.linecols {
max-width: 100%;
min-width: 100%;
width: 100%;
direction: rtl;
unicode-bidi: isolate-override;
}
td.cols {
padding-left: 0.5em;
padding-right: 0.5em;
text-align: right;
}
td.cols2 {
max-width: 50%;
min-width: 50%;
width: 500%;
}
td.cols3 {
max-width: 33%;
min-width: 33%;
width: 33%;
}
td.cols4 {
max-width: 25%;
min-width: 25%;
width: 25%;
}
td.cols4 {
max-width: 20%;
min-width: 20%;
width: 20%;
}
:root {
--fog-rim: hsla( 0, 0%, 60%, 0.5 );
}
</style>
"""
POST_HTML = """
</body>
</html>
"""
def preHtml(pageNum):
return f"""\
<html>
<head>
<meta name="viewport" content="width=device-width, initial-scale=1.0"/>
<meta charset="utf-8"/>
<title>Lakhnawi {pageNum}</title>
{CSS}
</head>
<body>
"""
def getToc(pageNums):
limit = 60
html = []
html.append("""<div class="toc">""")
j = 0
for (i, pageNum) in enumerate(pageNums):
if j == limit:
j = 0
html.append("""</div>\n<div class="toc">""")
html.append(f"""<a href="#p{pageNum:>03}">p {pageNum}</a><br>""")
j += 1
html.append("""</div>""")
return "\n".join(html)
PRIVATE_SPACE = "\uea75"
PRIVATE_LETTERS_DEF = """
e800
e806
e807
e808
e809
e80a
e80e
e898
e8d4
e8e9
e915
e917
ea79
"""
PRIVATE_DIAS_DEF = """
e812
e814
e815
e816
e817
e818
e81d
e821
e823
e824
e825
e826
e827
e828
e829
e82b
e82e
e82f
e830
e831
e832
e833
e834
e835
e837
e838
e839
e83a
e83f
e840
e845
e846
e849
e84d
e85b
e85c
e863
e864
e86d
e87f
e880
e887
e888
e8de
e8df
e8e6
e8e7
e8e8
e8e9
e8ea
e8eb
e8ee
e8f4
e8f5
e8f6
e8f8
e8fb
e8fe
"""
REPLACE_DEF = """
# see https://www.unicode.org/versions/Unicode13.0.0/ch09.pdf
# see https://www.compart.com/en/unicode/U+FE8E
# see https://r12a.github.io/scripts/arabic/block
e821 => : (ignore short tatweel)
e825 => 064e : FATHA
e849 => 064e : FATHA
e86d => 064e : FATHA
e87f => 064e : FATHA
e8e8 => 064e : FATHA
e823 => 064b : FATHATAN
e8e6 => 064b : FATHATAN
e826 => 064f : DAMMA
e8e9 => 064f : DAMMA
e824 => 064c : DAMMATAN
e8e7 => 064c : DAMMATAN
e840 => 0650 : KASRA
e864 => 0650 : KASRA
e888 => 0650 : KASRA
e8df => 0650 : KASRA
e83f => 064d : KASRATAN
e863 => 064d : KASRATAN
e887 => 064d : KASRATAN
e8de => 064d : KASRATAN
e827 => 0651 : SHADDA
e8ea => 0651 : SHADDA
e828 => 0652 : SUKUN
e8eb => 0652 : SUKUN
e829 => 0653 : MADDA
e84d => 0653 : MADDA
e82b => 0670 : ALEF(super)
e8ee => 0670 : ALEF(super)
e830 => 064e+0651 : SHADDA+FATHA
e8f4 => 064e+0651 : SHADDA+FATHA
e8f6 => 064e+0651 : SHADDA+FATHA
e831 => 064f+0651 : SHADDA+DAMMA
e8f5 => 064f+0651 : SHADDA+DAMMA
e82e => 064c+0651 : SHADDA+DAMMATAN
e832 => 0650+0651 : SHADDA+KASRA
e82f => 064d+0651 : SHADDA+KASRATAN [2]
e834 => 064d+0651 : SHADDA+KASRATAN [2]
e812 => 064d+0651 : SHADDA+KASRATAN [2]
e8f8 => 064d+0651 : SHADDA+KASRATAN [2]
e818 => 0653+0670 : MADDA+ALEF(super) [4]
e83a => 0653+0670 : MADDA+ALEF(super) [4]
e8fe => 0653+0670 : MADDA+ALEF(super) [4]
e81d => 0640+0650+0651 : TATWEEL+KASRA+SHADDA
e898 => 0647 : HEH
e806 => 0627 : ALEF
e807 => 0627 : ALEF
e808 => 0671 : ALEF(wasla)
e809 => 0671 : ALEF(wasla)
e800 => 0622 : ALEF/MADDA
0627+e815 => 0623+064e : ALEF/HAMZA+FATHA
0627+e85b => 0623+064e : ALEF/HAMZA+FATHA
fe8e+e815 => 0623+064e : ALEF/HAMZA+FATHA
fe8e+e821+e815 => 0623+064e : ALEF/HAMZA+FATHA
e806+e85b => 0623+064e : ALEF/HAMZA+FATHA
0627+e85c => 0623+064f : ALEF/HAMZA+DAMMA
0627+e816 => 0623+064f : ALEF/HAMZA+DAMMA
e806+e85c => 0623+064f : ALEF/HAMZA+DAMMA
fe8e+e816 => 0623+064f : ALEF/HAMZA+DAMMA
fe8e+e821+e816 => 0623+064f : ALEF/HAMZA+DAMMA
0627+e814 => 0623+064c : ALEF/HAMZA+DAMMATAN
0627+e846 => 0625+064d : ALEF/HAMZA(low)+KASHRATAN
fe8e+e821+e846 => 0625+064d : ALEF/HAMZA(low)+KASRATAN
fe8e+e817 => 0623+0652 : ALEF/HAMZA+SUKUN [7]
e835 => 0654+064b : HAMZA+FATHATAN [3]
e837 => 0654+064e : HAMZA+FATHA [3]
e8fb => 0654+064e : HAMZA+FATHA [3]
e838 => 0654+064f : HAMZA+DAMMA [3]
e880 => 0654+064f : HAMZA+DAMMA [3]
e839 => 0654+0652 : HAMZA+SUKUN [3]
e845 => 0655+0650 : HAMZA(low)+KASRA
0648+e838 => 0624+064f : WAW/HAMZA+DAMMA
e80a => 0644 : LAM
e80e => 0644 : LAM
e821+e8d4+e821+e830 => 0644 : LAM [10]
e821+e8d4+e82b+e821 => 0644 : LAM [10]
e8d4+e830 => 0644 : LAM [10]
e8d4+e833 => 0644 : LAM [10]
e8d4+e821 => 0644 : LAM [10]
e8d4+e821+e827 => 0644 : LAM [10]
e8d4+e821+e833 => 0644 : LAM [10]
e8d4+e821+e821+e833 => 0644 : LAM [10]
e8d4+fc63 => 0644 : LAM [10]
e8d4+e827 => 0644 : LAM [10]
e8d4 => 0644 : LAM [10]
e8d4+064e+e82b => 0644 : LAM [11]
fefb+e85b => 0644+623+064e : LAM+ALEF/HAMZA+FATHA
fefb+e85c => 0644+0623+064f : LAM/ALEF/HAMZA+DAMMA
fefc+e87f => 0644+0623+064e : LAM/ALEF/HAMZA+FATHA
fef4+e917 => 064a+0649+0670 : YEH+ALEF(super)
ea75+e828+ea79 => 062d+0652+0645 : HAH+SUKUN+MEEM
fe92+0650+e915 => 0628+0650+064a : BEH+KASRA+YEH
fec3+0652+e821+e80e+064e+e807 => 0637+0652+e821+e80e+064e+e807 : [9]
fffd => : replacement character
# [1] it should be a LAM/ALEF ligature with wasla, but there is no such unicode char
# See https://savannah.gnu.org/bugs/?52454
# [2] it looks like shadda+fathatan, but there is no shadda+fathatan.
# Instead, it is shadda+kashratan, where the kashratan is placed high.
# [3] not a perfect solution. After fbe9 (alef maksura) the high hamza is not
# a recommended combination.
# [4] the result combination of madda and alef superscript does not render nicely
# [5] the hamza ends up on the left part of the ligature and combines
# there with the fatha/damma, the d should be positioned on the rightmost part
# of the ligature, but this does not happen
# [6] The shadda/kasra should render low, but it does render high.
# On page 185 line 4 is a yeh that has both this one and the shadda/fatha,
# where in the original the one is rendered below, and the other above the letter.
# In Unicode they end up both in a high position.
# [7] In the original, the sukun tops the alef and the hamza tops the sukun.
# In Unicode, it's the otherway round: the hamza tops the alif and the sukun is
# at the top.
# [9] Singular case on page 45 line 9 char 90 : a final tah inside a word
# [10] as in Allah. The shadda and alef superscript are filled in by the unicode
# algorithm.
# [11] as in Allah, but with fatha instead of shadda. Probaly a typo in a note,
# page 12 second last line.
"""
def tweakSpace(c):
# return c.strip() if ISOLATED in dc else (" " + c.strip()) if INITIAL in dc else c
# return c
return c.strip()
# return c.strip() + (" " if FINAL in dc else "")
# return (c.strip(), " " if FINAL in dc else "")
def ptRepD(p):
return "?" if p is None else int(round(p * 10))
def ptRep(p):
return "?" if p is None else int(round(p))
REPLACE_RE = re.compile(r"""^([0-9a-z+]+)\s*=>\s*([0-9a-z+]*)\s*:\s*(.*)$""", re.I)
LETTER_CODE_DEF = dict(
c=(2, "letter"),
d=(1, "diacritic"),
)
LETTER_CODE = {cd: info[0] for (cd, info) in LETTER_CODE_DEF.items()}
CODE_LETTER = {info[0]: cd for (cd, info) in LETTER_CODE_DEF.items()}
LETTER_KIND = {info[0]: info[1] for info in LETTER_CODE_DEF.values()}
def getDictFromDef(defs):
rules = []
rn = 0
good = True
for (i, line) in enumerate(defs.strip().split("\n")):
parts = line.split("#", maxsplit=1)
if len(parts) > 1:
line = parts[0]
line = line.strip()
if not line:
continue
match = REPLACE_RE.match(line)
if not match:
print(f"MALFORMED REPLACE DEF @{i}: {line}")
good = False
continue
rn += 1
(valStr, replStr, comment) = match.group(1, 2, 3)
vals = []
d = None
for (i, val) in enumerate(valStr.split("+")):
if val in {"c", "d"}:
if d is not None:
print(f"MULTIPLE d in RULE @{i}: rule {rn}: {line}")
good = False
d = i
vals.append(LETTER_CODE[val])
else:
vals.append(chr(int(val, base=16)))
repls = []
e = None
if replStr:
for (i, repl) in enumerate(replStr.split("+")):
if repl in {"c", "d"}:
if e is not None:
print(f"MULTIPLE d in RULE @{i}: rule {rn}: {line}")
good = False
e = i
repls.append(LETTER_CODE[repl])
else:
repls.append(chr(int(repl, base=16)))
if d is None and e is not None:
print(f"d in REPLACEMENT but not in MATCH @[i]: rule {rn}: {line}")
good = False
rules.append((rn, tuple(vals), d, tuple(repls), e))
if not good:
return None
result = {}
ruleIndex = {}
for (rn, vals, d, repls, e) in sorted(rules, key=lambda x: (-len(x[1]), str(x[1]))):
result.setdefault(vals[0], []).append((rn, vals, d, repls, e))
ruleIndex[rn] = (vals, d, repls, e)
return (result, ruleIndex)
def parseNums(numSpec):
return (
None
if not numSpec
else [numSpec]
if type(numSpec) is int
else setFromSpec(numSpec)
if type(numSpec) is str
else list(numSpec)
)
U_LINE_RE = re.compile(r"""^U\+([0-9a-f]{4})([0-9a-f ]*)$""", re.I)
HEX_RE = re.compile(r"""^[0-9a-f]{4}$""", re.I)
PUA_RE = re.compile(r"""⌊([^⌋]*)⌋""")
RECT = "rect"
COLOR = "color"
FNRULE_WIDTH = 60
SPACE_THRESHOLD = 25
class Lakhnawi(UChar):
def __init__(self):
super().__init__()
self.getCharConfig()
self.doc = fitz.open(SOURCE)
self.lines = {}
self.text = {}
self.fnRules = {}
self.spaces = {}
self.columns = {}
self.good = True
def close(self):
self.doc.close()
def setStyle(self):
display(HTML(CSS))
def getCharConfig(self):
self.privateInfo()
self.setupRules()
self.getCharInfo()
def privateInfo(self):
self.privateLetters = getSetFromDef(PRIVATE_LETTERS_DEF)
self.privateDias = getSetFromDef(PRIVATE_DIAS_DEF)
self.privateSpace = PRIVATE_SPACE
self.nospacings |= self.privateDias
self.diacritics |= self.privateDias
self.diacriticLike |= self.privateDias
self.arabicLetters = self.arabic - self.privateDias
self.rls |= self.puas
def setupRules(self):
(self.replace, self.ruleIndex) = getDictFromDef(REPLACE_DEF)
if self.replace is None:
self.replace = {}
self.good = False
self.rulesApplied = collections.defaultdict(collections.Counter)
for rn in self.ruleIndex:
self.rulesApplied[rn] = collections.Counter()
def getCharInfo(self):
self.doubles = {}
self.privates = set()
doubles = self.doubles
privates = self.privates
puas = self.puas
doc = fitz.open(FONT)
for page in doc:
textPage = page.getTextPage()
data = textPage.extractText()
for (ln, line) in enumerate(data.split("\n")):
if line.startswith("U+"):
match = U_LINE_RE.match(line)
if not match:
continue
(main, rest) = match.group(1, 2)
main = main.lower()
nMain = int(main, base=16)
cMain = chr(nMain)
if cMain in puas:
privates.add(cMain)
continue
if cMain == chr(0):
continue
second = None
rest = rest.replace(" ", "")
if rest:
if HEX_RE.match(rest):
second = rest.lower()
if second:
nSecond = int(second, base=16)
cSecond = chr(nSecond)
if nSecond > nMain:
doubles[cMain] = cSecond
else:
doubles[cSecond] = cMain
def showChar(self, c):
if c in {1, 2}:
return f"""
<div class="ch p">
<div class="cn">{LETTER_KIND[c]}</div>
</div>
"""
if c == "":
extra = ""
ccode = ""
crep = "\u00a0"
cname = "EMPTY"
else:
puas = self.puas
rls = self.rls
ccode = (
f"""<span class="{"p" if c in puas else "c"}">{ord(c):>04x}</span>"""
)
crep = (
"??"
if c in puas
else f"""<span class="{"rc" if c in rls else "lc"}">{c}"""
)
cname = "" if c in puas else f"""<span class="c">{uName(c)}</span>"""
extra = "t" if c == "\t" else "s" if c == " " else ""
return f"""
<div class="ch{extra}">
<div class="cn">{ccode}</div>
<div class="cn"><span class="cni">{crep}</span></div>
<div class="cn">{cname}</div>
</div>
"""
def plainChar(self, c):
if c == "":
return "⌊⌋"
if c in {1, 2}:
return CODE_LETTER[c]
return f"⌊{ord(c):>04x}⌋"
def showString(self, s, asString=False):
shtml = f"""<span class="r">{s}</span>"""
html = """<div class="sr">""" + (
"".join(self.showChar(c) for c in s) + "</div>"
)
if asString:
return f"""<span>{shtml}</span>{html}"""
display(HTML(f"""<p>{shtml}</p>{html}"""))
def plainString(self, s):
return " ".join(self.plainChar(c) for c in s)
def showReplacements(self, rule=None, isApplied=False):
ruleIndex = self.ruleIndex
rulesApplied = self.rulesApplied
ruleNums = parseNums(rule)
ruleNums = (
set(ruleIndex)
if ruleNums is None
else sorted(r for r in ruleNums if r in ruleIndex)
)
html = []
totalRules = len(ruleIndex)
totalApplications = sum(sum(x.values()) for x in rulesApplied.values())
totalPages = len(set(chain.from_iterable(rulesApplied.values())))
ruleRep = "rule" + ("" if totalRules == 1 else "s")
appRep = "application" + ("" if totalApplications == 1 else "s")
pageRep = "page" + ("" if totalPages == 1 else "s")
html.append(
f"""
<p><b>{totalRules} {ruleRep} with
{totalApplications} {appRep} on {totalPages} {pageRep}</b></p>
<table>
"""
)
for (rn, applied) in sorted(
rulesApplied.items(), key=lambda x: (-sum(x[1].values()), x[0])
):
if rn not in ruleNums:
continue
(vals, d, repls, e) = ruleIndex[rn]
valRep = "".join(self.showChar(c) for c in vals)
replRep = "".join(self.showChar(c) for c in repls)
total = sum(applied.values())
if isApplied and not applied:
continue
if applied:
examplePageNum = sorted(applied, key=lambda p: -applied[p])[0]
nExamples = applied[examplePageNum]
appliedEx = f"e.g. page {examplePageNum} with {nExamples} applications"
else:
appliedEx = ""
appliedRep = f"<b>{total}</b> x applied on <i>{len(applied)}</i> pages"
html.append(
f"""
<tr>
<th>rule {rn}</th>
<td class="al">{appliedRep}</td>
<td class="al">{appliedEx}</td>
<td class="al">{valRep}</td>
<td class="al"><span class="lrg">⇒</span></td>
<td class="al">{replRep}</td>
</tr>
"""
)
html.append("<table>")
display(HTML("".join(html)))
def parsePageNums(self, pageNumSpec):
doc = self.doc
pageNums = (
list(range(1, len(doc) + 1))
if not pageNumSpec
else [pageNumSpec]
if type(pageNumSpec) is int
else setFromSpec(pageNumSpec)
if type(pageNumSpec) is str
else list(pageNumSpec)
)
return [i for i in sorted(pageNums) if 0 < i <= len(doc)]
def drawPages(self, pageNumSpec, clip=None):
doc = self.doc
for pageNum in self.parsePageNums(pageNumSpec):
page = doc[pageNum - 1]
if clip is not None:
clip = (0, clip[0], page.rect.width, clip[1])
pix = page.getPixmap(matrix=fitz.Matrix(4, 4), clip=clip, alpha=False)
display(HTML(f"""<p><b>page {pageNum}</b></p>"""))
display(Image(data=pix.getPNGData(), format="png"))
def getPages(
self,
pageNumSpec,
refreshConfig=False,
doRules=True,
doFilter=True,
onlyFnRules=False,
):
if not self.good:
print("SKIPPING because of config errors")
return
fnRules = self.fnRules
spaces = self.spaces
columns = self.columns
self.doRules = doRules
self.doFilter = doFilter
ruleIndex = self.ruleIndex
rulesApplied = self.rulesApplied
if refreshConfig:
self.getCharConfig()
for rn in ruleIndex:
rulesApplied[rn] = collections.Counter()
for (i, pageNum) in enumerate(self.parsePageNums(pageNumSpec)):
self.pageNum = pageNum
rep = (
f"{i + 1:>4} (page {pageNum:>4})"
if pageNum != i + 1
else (f"{i + 1:>4}" + " " * 12)
)
sys.stdout.write(f"\r\t{rep}")
sys.stdout.flush()
doc = self.doc
page = doc[pageNum - 1]
theseFnRules = set()
for fnRule in page.getDrawings():
if RECT in fnRule and fnRule.get(COLOR, None):
rect = fnRule[RECT]
width = rect.x1 - rect.x0
if width > FNRULE_WIDTH:
theseFnRules.add(int(round(rect.y0)))
fnRules[pageNum] = tuple(sorted(theseFnRules))
spaces[pageNum] = {}
columns[pageNum] = {}
if onlyFnRules:
continue
textPage = page.getTextPage()
data = textPage.extractRAWDICT()
self.collectPage(data)
def getPageRaw(self, pageNum):
self.pageNum = pageNum
rep = f"page {pageNum:>4}"
sys.stdout.write(f"{rep}")
sys.stdout.flush()
doc = self.doc
page = doc[pageNum - 1]
textPage = page.getTextPage()
data = textPage.extractRAWDICT()
pprint(data)
def getPageObj(self, pageNum):
self.pageNum = pageNum
doc = self.doc
return doc[pageNum - 1]
def plainPages(self, pageNumSpec):
text = self.text
for pageNum in self.parsePageNums(pageNumSpec):
lines = text.get(pageNum, [])
for (i, line) in enumerate(lines):
print(self.plainLine(line))
def tsvPages(self, pageNumSpec):
text = self.text
destDir = f"{UR_DIR}/{NAME}"
pageNums = self.parsePageNums(pageNumSpec)
if not os.path.exists(destDir):
os.makedirs(destDir, exist_ok=True)
pageNumRep = ALL_PAGES if pageNumSpec is None else str(pageNumSpec)
filePath = f"{destDir}/{pageNumRep}.tsv"
fh = open(filePath, "w")
fh.write(self.tsvHeadLine())
for pageNum in pageNums:
lines = text.get(pageNum, [])
for (ln, line) in enumerate(lines):
fh.write(self.tsvLine(line, pageNum, ln + 1))