Repository navigation
Expand file tree
/
Copy pathDicConversion.pm
More file actions
3004 lines (2866 loc) · 155 KB
/
Copy pathDicConversion.pm
File metadata and controls
3004 lines (2866 loc) · 155 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
#!/usr/bin/perl
package DicConversion;
use strict;
use utf8;
use open IO => ':utf8';
use open ':std', ':utf8';
use feature 'unicode_strings'; # You get funky results with the sub convertNumberedSequencesToChar without this.
use lib '/home/mark/git/PocketBookDic/';
use DicGlobals;
use Dic2Screen;
use Exporter;
use DicFileUtils;
use DicHelpUtils;
use DicManualCuts;
if( $isTestingOn ){ use warnings; }
our @ISA = ('Exporter');
our @EXPORT = (
'convertABBYY2XDXF',
'$isABBYYAllCleared',
'$isABBYConverted',
'$isABBYYConverterReuse',
'$isABBYYWordlistNeeded',
'@ABBYYConverterAllowedKeys',
'@ABBYYConverterPauseFor',
'@ABBYY_CSS',
'convertCVStoXDXF',
'convertHTML2XDXF',
'$DebugKeyWordConvertHTML2XDXF',
'$isConvertDiv2SpaninHTML2DXDF',
'$isConvertFont2Small',
'$isConvertFont2Span',
'$isConvertMMCFullText2Span',
'convertImage2Base64',
'$isConvertGIF2PNG',
'%ReplacementImageStrings',
'$ReplacementImageStringsHashFileName',
'convertIMG2Text',
'$isConvertImagesUsingOCR',
'$isManualValidation',
'$isRemoveUnSubstitutedImageString',
'$isRemoveUnSourcedImageStrings',
'%OCRedImages',
'%ValidatedOCRedImages',
'$ValidatedOCRedImagesHashFileName',
'convertParsed2XDXF',
'convertRAWML2XDXF',
'convertRAWMLUsingManualCuts',
'convertStardictXMLtoXDXF',
'convertXDXFtoStardictXML',
'convertXML2Binary',
'generateXDXFTagBased',
'$HigherFrequencyTags',
'$isDeleteLowerFrequencyTagsinFilterTagsHash',
'$isExcludeImgTags',
'$isgatherSetsVerbose',
'$isRemoveMpbAndBodyTags',
'@KnownStylingTags',
'$LowFrequencyCriterium',
'$isSkipKnownStylingTags',
'$MinimumSetPercentage',
'$MinimumNodes',
'$useStoredCatches',
'$isParsedTreeReused',
);
# Because this control variable is used both in convertIMG2Text and convertHTML2XDXF it has poll position.
our $isConvertImagesUsingOCR = 1; # Try to identify images as symbols whenever possible.
our $MinimumNodes = 10; #Minimum number of nodes
our $useStoredCatches = 1;
our $isParsedTreeReused = 1;
our $isParsedConverterReuse = 1; # Controls the check for already generated xdxf-file
our $isPrintRecurseTree = 1;
our $isParsedConverted = 0; # Global variable that gets set to 1 if convertParsed2XDXF returns an xdxf-array.
our $isRemoveTextLess = 0;
sub convertParsed2XDXF{
# Usage: @xdxf = convertParsed2XDXF( $html );
my $html = shift;
info ( "Entering convertParsed2XDXF.");
if( $isTestingOn ){
info("Testing is on.");
$isParsedConverterReuse = 0;
$isParsedTreeReused = 1;
$useStoredCatches = 1;
}
info ( "\$isParsedConverterReuse is '$isParsedConverterReuse'");
info ( "\$isParsedTreeReused is '$isParsedTreeReused'");
info ( "\$useStoredCatches is '$useStoredCatches'");
sub changeMBPTags{
my $html = shift;
$html =~ s~<mbp:pagebreak\s*/>~<div style="page-break-after: always;"></div>~g;
$html =~ s~<mbp:frameset>~<div class="frameset">~g;
$html =~ s~</mbp:frameset>~</div>~g;
if( $html =~ m~(<mbp:[^>]*>)~ ){ die "Found another mbp-tag: $1."; }
return $html;
}
# This displays the contents of $node and any children it may
# have. The variable $depth is the indentation used.
sub recurse{
my ($node, $depth, $size_of_parent_contents, $maxdepth, $Parent_with_maximum_children, $Maximum_number_of_children, $print) = @_;
printGreen( "." ) unless $print;
if( $depth > $maxdepth){ return; }
# Print indentation according to the level of recursion.
print " " x $depth if $print;
# If $node is a reference, then it is an HTML::Element.
if (ref $node) {
# Print the tag associated with $node, for example "html" or
# "li".
my $parent_node = $node->parent();
my @parent_children = () ;
if( ref $parent_node ){ @parent_children = $parent_node->content_list; }
# $node->content_list () returns a list of child nodes of
# $node, which we store in @children.
my @children = $node->content_list();
printGreen( $node->tag (), "\t") if $print;
print("brethern: ") if $print;
print scalar @parent_children if $print;
print(" children: ") if $print;
print scalar @children," ","\n" if $print;
my @children = $node->content_list();
my $number_of_children = scalar @children;
# shortcut for rather large containers.
if ( $number_of_children > 1000){ return $node; }
if( $number_of_children > $Maximum_number_of_children ){
$Maximum_number_of_children = $number_of_children;
$Parent_with_maximum_children = $node;
}
for my $child_node (@children) {
$Parent_with_maximum_children = recurse ($child_node, $depth + 1, scalar @children, $maxdepth, $Parent_with_maximum_children, $Maximum_number_of_children, $print );
}
}
else {
# If $node is not a reference, then it is just a piece of text
# from the HTML file.
printItalics( $node, "\n" ) if $print;
}
return($Parent_with_maximum_children);
}
if( $isParsedConverterReuse ){
my $XDXFFileName = $FileName;
$XDXFFileName =~ s~\.\w+$~~;
$XDXFFileName .= ".xdxf";
if( -e $XDXFFileName ){
info("Reusing xdxf data.");
$isParsedConverted = 1;
return ( file2Array( $XDXFFileName ) );
}
}
else{ info("Not reusing converted data."); }
use HTML::TreeBuilder 5 -weak;
my $tree = HTML::TreeBuilder->new;
if( $isParsedTreeReused and -e $FileName.'.tree' ){
$tree = retrieve ( $FileName.'.tree' );
info( "Retrieved tree from '".$FileName.".tree'"); }
else{
$html = changeMBPTags( $html );
$html = convertNonBreakableSpacetoNumberedSequence4Strings( $html );
$html = convertNumberedSequencesToChar4Strings( $html );
# $html = mergeConsecutiveIdenticallyAttributedSpans( $html );
# $html = mergeConsecutiveBoldSpans( $html );
# $tree->p_strict(1); # https://metacpan.org/pod/HTML::TreeBuilder#p_strict
# $tree->parse_file($FileName);
$tree->no_space_compacting(1);
$tree->ignore_unknown(0);
$tree->parse_content( $html );
debugV( "tree '$tree'");
# tree 'HTML::TreeBuilder=HASH(0x562d600afcf0)'
unless( $tree =~ m~HTML::TreeBuilder=HASH~ ){
unlink $FileName . '.tree';
die2("\$tree not a HTML::TreeBuilder hash. \$tree='$tree'\n Deleted old tree-file. Rerun script.");
}
store( $tree, $FileName.'.tree' );
$tree->elementify();
debugV( "tree '$tree'");
info("End parsing");
}
my $root = $tree->root;
my @contents = $root->content_list;
debug("root tag: ", $root->tag);
my @Catch = ();
if( -e $FileName.'.catched' and $useStoredCatches){
@Catch = @{retrieve ( $FileName.'.catched' )};
info( "Retrieved \@Catch from '".$FileName.".catched'"); }
else{
my $number_of_children_root = $root->content_list;
# First one gives numbers without dealing with pruning.
my $Parent_with_maximum_children = '';
while( $root ne $Parent_with_maximum_children){
$Parent_with_maximum_children = recurse(
$root, # node from which you start recursing
0, # starting depth
$number_of_children_root,
99, # maximum depth
$root, # Parent_with_maximum_children
0, # Maximum_number_of_children
$isPrintRecurseTree); # Print or not print
debug( $Parent_with_maximum_children );
debug( $Parent_with_maximum_children->tag() );
debug( scalar $Parent_with_maximum_children->content_list );
$Parent_with_maximum_children->detach();
push @Catch, $Parent_with_maximum_children;
}
store( \@Catch, $FileName.'.catched' ) || die "Can't store to $FileName.catches" ;
}
info("Analyzing catches");
my $MaxChildren=0;
foreach my $c(@Catch){
info_t( $c->tag()," seen ", scalar $c->content_list, " times.");
if( scalar $c->content_list > $MaxChildren ){
$MaxChildren = $c->content_list;
}
}
my $Significance = 40;
my %Catch;
sub registerPair{
my ( $Key, $Definition ) = @_;
if( ref $Key ){ $Key = $Key->as_text(); }
$Key =~ s~^\s+~~;
$Key =~ s~\s+$~~;
my $tag= tagNode($Definition);
if( ref $Definition ){ $Definition = $Definition->as_HTML('&<>'); }
$Definition =~ s~\<$tag[^>]*\>~~;
if( defined( $Definition ) ){ $Definition = escapeHTMLString($Definition); }
if( $Key ne '' and $Definition ne ''){
$Catch{ $Key } = $Definition;
info("Found key '$Key'");
}
}
sub tagNode{
my $Node = shift;
if( ref $Node and $Node->tag() !~ m~b|i|font~ ){ return $Node->tag(); }
else{ return "txt";}
}
foreach my $Catch( @Catch ){
debug( $Catch->tag() );
debug( scalar $Catch->content_list );
if( ( scalar $Catch->content_list < $MinimumNodes) or
(scalar $Catch->content_list < ($MaxChildren / $Significance))
){
info("Skipped '".$Catch->tag()."', because it containes less than $MinimumNodes nodes or has less 1/$Significance of the maximum number.");
next;
}
my @Contents = $Catch->content_list;
my @Nodes;
my %AlreadySaid;
foreach my $Content( @Contents ){
if( !(ref $Content) or (ref $Content and ( $Content->as_text =~ m~\w|[*!@#$%^&(){}|+-=]~ or $Content->as_HTML eq '<br />') ) ){
push @Nodes, $Content;
}
else{
my $String = $Content->as_HTML(',.&');
unless( $AlreadySaid{$String} ){ info( "Omitted: '",$String, "'"); $AlreadySaid{$String} = 1;}
}
}
info( "Reduced size of contents from ", scalar $Catch->content_list," to ", scalar @Nodes );
# Are there separator nodes?
# Are there tag patterns?
# div 635 1
# h2 1 0
# dt 635 1
# Aba
# dd 635 1
# A loose, usually black robe worn by Fremen women and Bene Gesserit sisters.
# hr 635 0
# div 635 1
# h2 1 0
# dt 635 1
# Abomination
# dd 635 1
# Bene Gesserit term for one who is pre-born and thus susceptible to being taken over by the ancestral personalities in Other Memory.
# hr 635 0
# div 635 1
# h2 1 0
# dt 635 1
# Ajidamal
# dd 635 1
## Generate patterns
my ( @Patterns_from_start, @Patterns_from_end );
foreach my $Node(@Nodes){ $Patterns_from_start[0] .= tagNode($Node); }
while( $Patterns_from_start[0] =~ s~txttxt~txt~g ){;}
$Patterns_from_end[0] = $Patterns_from_start[0];
my $MaxPatLength = 10;
for( my $pattern_length = 1; $pattern_length <= $MaxPatLength; $pattern_length++ ){
for( my $i = 0; $i < $pattern_length; $i++){
$Patterns_from_start[$pattern_length] .= tagNode($Nodes[$i]);
my $j = - $i - 1;
$Patterns_from_end[$pattern_length] = tagNode($Nodes[$j]) . $Patterns_from_end[$pattern_length];
}
}
info_t("\@Patterns from start");
foreach( @Patterns_from_start ){ info_t($_); }
info_t("\@Patterns from end");
foreach( @Patterns_from_end ){ info_t($_); }
## Match Patterns
my @CheckResults;
for( my $start_length = 1; $start_length <= $MaxPatLength; $start_length++ ){
my $Check = $Patterns_from_start[0];
my $Start = $Patterns_from_start[$start_length];
my $End;
my $end_length = 0;
my $from_start_matches = 0;
my $from_end_matches = 0;
my $combination_matches = 0;
while( $Check =~ s~^($Start)~~ ){ $from_start_matches++; }
if( length($Check) == 0 ){ push @CheckResults, { "start" => $Start, "start_length" => $start_length, "end" => $End, "end_length" => $end_length, "from_start_matches" => $from_start_matches, "from_end_matches" => $from_end_matches, "combination_matches" => $combination_matches }; next; }
for( $end_length = 1; $end_length <= $MaxPatLength; $end_length++ ){
my $Check2 = $Check;
$End = $Patterns_from_end[$end_length];
while( $Check2 =~ s~^($End)~~ ){ $from_end_matches++; }
if( length($Check2) == 0 ){ push @CheckResults, { "start" => $Start, "start_length" => $start_length, "end" => $End, "end_length" => $end_length, "from_start_matches" => $from_start_matches, "from_end_matches" => $from_end_matches, "combination_matches" => $combination_matches }; next; }
my $Combination ='';
if( $from_start_matches != 0 ){ $Combination .= $Start x $from_start_matches; }
if( $from_end_matches != 0 ){ $Combination .= $End x $from_end_matches;}
while( $Combination ne '' and $Check2 =~ s~^$Combination~~ ){ $combination_matches++; }
if( length($Check2) == 0 ){ push @CheckResults, { "start" => $Start, "start_length" => $start_length, "end" => $End, "end_length" => $end_length, "from_start_matches" => $from_start_matches, "from_end_matches" => $from_end_matches, "combination_matches" => $combination_matches }; next; }
}
}
## Analyze found patterns
unless( scalar @CheckResults ){
warn "Current Catch doesn't hold patterns that are indicative for key-definition pairs. ";
next;
}
print( Dumper( @CheckResults ) );
my $MostMatches = 0;
my $IndexWithMostMatches = 0;
for( my $i = 0; $i <= $#CheckResults; $i++ ){
my %Result = %{ $CheckResults[$i] };
if( $Result{"combination_matches"} > $MostMatches ){
$MostMatches = $Result{"combination_matches"};
$IndexWithMostMatches = $i;
}
elsif ( ($Result{"combination_matches"}) == $MostMatches ){
$IndexWithMostMatches = $IndexWithMostMatches . "," . $i;
}
}
if( $IndexWithMostMatches =~ m~,~ ){
# multiple combination_matches
my @BestIndexes = split( /,/, $IndexWithMostMatches );
my @FilteredResults;
foreach( @BestIndexes ){ push @FilteredResults, $CheckResults[$_]; }
my $MostMatchesFiltered = 0;
my $IndexWithMostMatchesFiltered = 0;
for( my $i = 0; $i <= $#FilteredResults; $i++ ){
my %Result = %{ $FilteredResults[$i] };
if( ($Result{"from_end_matches"}+$Result{"from_start_matches"}) > $MostMatchesFiltered ){
$MostMatchesFiltered = $Result{"from_end_matches"}+$Result{"from_start_matches"};
$IndexWithMostMatchesFiltered = $i;
}
}
$IndexWithMostMatches = $IndexWithMostMatchesFiltered;
}
my %Best = %{$CheckResults[$IndexWithMostMatches]};
info("Found best match to be:");
print( Dumper( %Best ) );
info("The list of contents can be seen as:");
foreach( keys %Best ){
unless(defined $Best{$_}){$Best{$_} ="''"; }
}
info("( ",$Best{"start"}," x ",$Best{"from_start_matches"}," ",$Best{"end"}," x ",$Best{"from_end_matches"}," ) x ", $Best{"combination_matches"} + 1 );
if( $Best{"start_length"} == 1 and $Best{"end_length"} == 1){
# $Nodes[0]->tag() followed by $Nodes[-1] found as pattern.
if( ((ref $Nodes[0] and $Nodes[0]->as_text =~ m~\w~) or !(ref $Nodes[0])) and
((ref $Nodes[-1] and $Nodes[-1]->as_text =~ m~\w~ ) or !(ref $Nodes[-1])) ){
# And both have letters in it.
while(@Nodes){
my $Key = shift @Nodes;
my $Definition = shift @Nodes;
registerPair( $Key, $Definition );
}
}
elsif( $Best{"end"} eq "txt" ){
while( @Nodes ){
my $Key = shift @Nodes;
my $Definition = '';
while( tagNode($Nodes[0]) eq "txt" and @Nodes){
my $DefPart = shift @Nodes;
debug( $DefPart ) if $isDebugVerbose;
if( ref $DefPart ){ $DefPart = $DefPart->as_HTML('&<>'); }
$Definition .= $DefPart;
printGreen($DefPart,"\n") if $isDebugVerbose;
}
registerPair( $Key, $Definition );
}
}
else{ die "No pattern interpretation available"; }
}
elsif( $Best{"start_length"} == 1 and $Best{"start_length"} > (1000 x $Best{"end_length"}) ){
# $Nodes[0]->tag() found as pattern.
foreach my $Node(@Nodes){
if ( $Node->tag() eq $Best{"start"} ){
my @Children = $Node->content_list;
my $warning = 1;
while( @Children ){
my $Child = shift @Children;
# test if there is text for key or skip
if( ( ref $Child and
$Child->as_text() =~ m~\w~ and
$Child = $Child->as_text() ) or
!(ref $Child) ){
# Current child has text, rest forms definition
my $Key = $Child;
my $Definition = '';
foreach my $DefParts (@Children){
if( ref $DefParts ){ $DefParts = $DefParts->as_HTML('&<>'); }
$Definition .= $DefParts;
}
registerPair( $Key, $Definition );
$warning = 0;
last;
}
}
if( $warning ){ die "No key/definition interpretation for this node."; }
}
else{ info("Omitting node with tag ", $Node->tag()); }
}
}
else{ die "No pattern interpretation available"; }
}
my @xdxf;
unless( scalar keys %Catch == 0 ){ @xdxf = convertHASHtoXDXF( \%Catch ); }
else{ @xdxf = convertRAWML2XDXF ( split(/^/, $html )); }
my $XDXFFileName = $FileName;
$XDXFFileName =~ s~\.\w+$~~;
$XDXFFileName .= ".xdxf";
array2File( $XDXFFileName, @xdxf );
$isParsedConverted = 1;
return( @xdxf);}
sub convertHASHtoXDXF{
my %Hash = %{ $_[0] };
my @xdxf = @xdxf_start;
foreach(sort keys %Hash){
if( $_ eq ''){next; }
push @xdxf, "<ar><head><k>$_</k></head><def>$Hash{$_}</def></ar>\n";
}
push @xdxf, $lastline_xdxf;
if( $isTestingOn ){ array2File( "test_HASHConversion".__LINE__.".xdxf", @xdxf ); }
return(@xdxf);}
sub convertCVStoXDXF{
my @cvs = @_;
my @xdxf = @xdxf_start;
my $number= 0;
my $Max_debuglines = 3;
info("\$CVSDeliminator is \'$CVSDeliminator\'.") if $number<$Max_debuglines;
foreach(@cvs){
$number++;
info("CVS line is: $_") if $number<$Max_debuglines;
m~\Q$CVSDeliminator\E~s;
my $key = $`; # Special variable $PREMATCH
my $def = $'; # Special variable $POSTMATCH
info("key found: '$key'") if $number<$Max_debuglines;
info("def found: '$def'") if $number<$Max_debuglines;
unless( defined $key and defined $def and $key ne '' and $def ne ''){
warn "key and/or definition are undefined.";
debug("CVSDeliminator is '$CVSDeliminator'");
debug("CVS line is '$_'");
die2("Array index is $number");
}
# Remove whitespaces at the beginning of the definition and EOL at the end.
$def =~ s~^\s+~~;
$def =~ s~\s+$~~;
push @xdxf, "<ar><head><k>$key</k></head><def>$def</def></ar>\n";
debug("Pushed <ar><head><k>$key</k></head><def>$def</def></ar>") if $number<10;
}
push @xdxf, $lastline_xdxf;
if( $isTestingOn ){ array2File( "test_CVSConversion".__LINE__.".xdxf", @xdxf ); }
return(@xdxf);}
# Controls for convertHTML2XDXF
our $DebugKeyWordConvertHTML2XDXF = "Gewirr"; # In convertHTML2XDXF only debug messages from this entry are shown. E.g. "Gewirr"
our $isConvertDiv2SpaninHTML2DXDF = 0 ;
our $isConvertFont2Small = 0 ;
our $isConvertFont2Span = 0 ;
our $isConvertMMCFullText2Span = 1 ;
sub convertHTML2XDXF{
# Converts html generated by KindleUnpack to xdxf
my $encoding = shift;
my $html = join('',@_);
my @xdxf = @xdxf_start;
# Content excerpt Duden 7. Auflage 2011:
# <idx:entry scriptable="yes"><idx:orth value="a"></idx:orth><div height="4"><a id="filepos242708" /><a id="filepos242708" /><a id="filepos242708" /><div><sub> </sub><sup> </sup><b>a, </b><b>A </b><img hspace="0" align="middle" hisrc="Images/image15902.gif"/>das; - (UGS.: -s), - (UGS.: -s) [mhd., ahd. a]: <b>1.</b> erster Buchstabe des Alphabets: <i>ein kleines a, ein gro\xDFes A; </i> <i>eine Brosch\xFCre mit praktischen Hinweisen von A bis Z (unter alphabetisch angeordneten Stichw\xF6rtern); </i> <b>R </b>wer A sagt, muss auch B sagen (wer etwas beginnt, muss es fortsetzen u. auch unangenehme Folgen auf sich nehmen); <sup>*</sup><b>das A und O, </b>(SELTENER:) <b>das A und das O </b>(die Hauptsache, Quintessenz, das Wesentliche, Wichtigste, der Kernpunkt; urspr. = der Anfang und das Ende, nach dem ersten [Alpha] und dem letzten [Omega] Buchstaben des griech. Alphabets); <sup>*</sup><b>von A bis Z </b>(UGS.; von Anfang bis Ende, ganz und gar, ohne Ausnahme; nach dem ersten u. dem letzten Buchstaben des dt. Alphabets). <b>2.</b> ‹das; -, -› (MUSIK) sechster Ton der C-Dur-Tonleiter: <i>der Kammerton a, A.</i> </div></div></idx:entry><div height="10" align="center"><img hspace="0" vspace="0" align="middle" losrc="Images/image15903.gif" hisrc="Images/image15904.gif" src="Images/image15905.gif"/></div> <idx:entry scriptable="yes"><idx:orth value="\xE4"></idx:orth><div height="4"><div><b>\xE4, </b><b>\xC4 </b><img hspace="0" align="middle" hisrc="Images/image15906.gif"/>das; - (ugs.: -s), - (ugs.: -s) [mhd. \xE6]: Buchstabe, der f\xFCr den Umlaut aus a steht.</div></div></idx:entry><div height="10" align="center"><img hspace="0" vspace="0" align="middle" losrc="Images/image15903.gif" hisrc="Images/image15904.gif" src="Images/image15905.gif"/></div> <idx:entry scriptable="yes"><idx:orth value="a"></idx:orth><div height="4"><div><sup><font size="2">1‌</font></sup><b>a</b><b> </b>= a-Moll; Ar.</div></div></idx:entry><div height="10" align="center"><img hspace="0" vspace="0" align="middle" losrc="Images/image15903.gif" hisrc="Images/image15904.gif" src="Images/image15905.gif"/></div>
# (The /xE6 was due to Perl output encoding set to UTF-8.)
# Prettified:
# <idx:entry scriptable="yes">
# <idx:orth value="a"></idx:orth>
# <div height="4"><a id="filepos242708" /><a id="filepos242708" /><a id="filepos242708" />
# <div><sub> </sub><sup> </sup><b>a, </b><b>A </b><img hspace="0" align="middle" hisrc="Images/image15902.gif" />das; - (UGS.: -s), - (UGS.: -s) [mhd., ahd. a]: <b>1.</b> erster Buchstabe des Alphabets: <i>ein kleines a, ein gro\xDFes A; </i> <i>eine Brosch\xFCre mit praktischen Hinweisen von A bis Z (unter alphabetisch angeordneten Stichw\xF6rtern); </i> <b>R </b>wer A sagt, muss auch B sagen (wer etwas beginnt, muss es fortsetzen u. auch unangenehme Folgen auf sich nehmen); <sup>*</sup><b>das A und O, </b>(SELTENER:) <b>das A und das O </b>(die Hauptsache, Quintessenz, das Wesentliche, Wichtigste, der Kernpunkt; urspr. = der Anfang und das Ende, nach dem ersten [Alpha] und dem letzten [Omega] Buchstaben des griech. Alphabets); <sup>*</sup><b>von A bis Z </b>(UGS.; von Anfang bis Ende, ganz und gar, ohne Ausnahme; nach dem ersten u. dem letzten Buchstaben des dt. Alphabets). <b>2.</b> ‹das; -, -› (MUSIK) sechster Ton der C-Dur-Tonleiter: <i>der Kammerton a, A.</i> </div>
# </div>
# </idx:entry>
# <div height="10" align="center"><img hspace="0" vspace="0" align="middle" losrc="Images/image15903.gif" hisrc="Images/image15904.gif" src="Images/image15905.gif" /></div>
# <idx:entry scriptable="yes">
# <idx:orth value="\xE4"></idx:orth>
# <div height="4">
# <div><b>\xE4, </b><b>\xC4 </b><img hspace="0" align="middle" hisrc="Images/image15906.gif" />das; - (ugs.: -s), - (ugs.: -s) [mhd. \xE6]: Buchstabe, der f\xFCr den Umlaut aus a steht.</div>
# </div>
# </idx:entry>
# <div height="10" align="center"><img hspace="0" vspace="0" align="middle" losrc="Images/image15903.gif" hisrc="Images/image15904.gif" src="Images/image15905.gif" /></div>
# <idx:entry scriptable="yes">
# <idx:orth value="a"></idx:orth>
# <div height="4">
# <div><sup>
# <font size="2">1‌</font>
# </sup><b>a</b><b> </b>= a-Moll; Ar.</div>
# </div>
# </idx:entry>
# <div height="10" align="center"><img hspace="0" vspace="0" align="middle" losrc="Images/image15903.gif" hisrc="Images/image15904.gif" src="Images/image15905.gif" /></div>
# Content excerpt Prettified:
# <idx:entry>
# <idx:orth value="A">
# </idx:entry>
# <b>A N M</b>
# <blockquote>Aulus (Roman praenomen); (abb. A./Au.); [Absolvo, Antiquo => free, reject];</blockquote>
# <hr />
# <idx:entry>
# <idx:orth value="Abba">
# </idx:entry>
# <b>Abba, undeclined N M</b>
# <blockquote>Father; (Aramaic); bishop of Syriac/Coptic church; (false read obba/decanter);</blockquote>
# <hr />
# <idx:entry>
# <idx:orth value="Academia">
# <idx:infl>
# <idx:iform name="" value="Academia" />
# <idx:iform name="" value="Academiabus" />
# <idx:iform name="" value="Academiad" />
# <idx:iform name="" value="Academiae" />
# <idx:iform name="" value="Academiai" />
# <idx:iform name="" value="Academiam" />
# <idx:iform name="" value="Academiarum" />
# <idx:iform name="" value="Academias" />
# <idx:iform name="" value="Academiis" />
# <idx:iform name="" value="Academium" />
# </idx:infl>
# <idx:infl>
# <idx:iform name="" value="Academiaque" />
# <idx:iform name="" value="Academiabusque" />
# <idx:iform name="" value="Academiadque" />
# <idx:iform name="" value="Academiaeque" />
# <idx:iform name="" value="Academiaique" />
# <idx:iform name="" value="Academiamque" />
# <idx:iform name="" value="Academiarumque" />
# <idx:iform name="" value="Academiasque" />
# <idx:iform name="" value="Academiisque" />
# <idx:iform name="" value="Academiumque" />
# </idx:infl>
# </idx:entry>
# <b>Academia, Academiae N F</b>
# <blockquote>academy, university; gymnasium where Plato taught; school built by Cicero;</blockquote>
# <hr />
# <idx:entry>
# Duden entry around "früh"
# <idx:entry scriptable="yes">
# <idx:orth value="früh"></idx:orth>
# <div height="4"><a id="filepos17894522" /><a id="filepos17894522" />
# <div><sub> </sub><sup> </sup><sup>
# <font size="2">1‌</font>
# </sup><b>fr</b><u><b><b>ü</b></b></u><b>h</b><b> </b>
# <mmc:no-fulltext>‹Adj.› [mhd. vrüe(je), ahd. fruoji, zu: fruo, </mmc:no-fulltext>
# <mmc:fulltext-word value="‹Adj.› mhd. vrüeje, ahd. fruoji, zu: fruo, " /><a href="#filepos17896263">
# <font size="+1"><b><img hspace="0" align="middle" hisrc="Images/image15907.gif" /></b></font> <sup>
# <font size="-1">2</font>
# </sup>früh
# </a>]: <b>1.</b> in der Zeit noch nicht weit fortgeschritten, am Anfang liegend, zeitig: <i>am -en Morgen; </i> <i>
# <mmc:no-fulltext>in -er, -[e]ster Kindheit; </mmc:no-fulltext>
# <mmc:fulltext-word value="in -er, -ester Kindheit; " />
# </i> <i>es ist noch f. am Tage; </i> <i>f. blühende Tulpen; </i> Ü <i>der -e (junge) Nietzsche; </i> Ü <i>die -esten (ältesten) Kulturen; </i> <sup>*</sup><b>von f. auf </b>(von früher Kindheit, Jugend an: <i>sie ist von f. auf an Selbstständigkeit gewöhnt). </i> <b>2.</b> früher als erwartet, als normalerweise geschehend, eintretend; frühzeitig, vorzeitig: <i>ein -er Winter; </i> <i>ein -er Tod; </i> <i>eine -e (früh reifende) Sorte Äpfel; </i> <i>wir nehmen einen -eren Zug; </i> <i>Ostern ist, fällt dieses Jahr f.; </i> <i>er kam -er als erwartet; </i> <i>sie ist zu f., noch f. genug gekommen; </i> <i>ihre f. (in jungen Jahren) verstorbene Mutter; </i> <i>ein f. vollendeter (in seiner Kunst schon in jungen Jahren zu absoluter Meisterschaft gelangter [u. jung verstorbener]) Maler; </i> <i>sie hat f. geheiratet; </i> <i>-er oder später (zwangsläufig irgendwann einmal) wird sie doch umziehen müssen.</i>
# </div>
# </div>
# </idx:entry>
# <div height="10" align="center"><img hspace="0" vspace="0" align="middle" losrc="Images/image15903.gif" hisrc="Images/image15904.gif" src="Images/image15905.gif" /><br /></div>
# <idx:entry scriptable="yes">
# <idx:orth value="früh"></idx:orth>
# <div height="4"><a id="filepos17896263" />
# <div><sup>
# <font size="2">2‌</font>
# </sup><b>fr</b><u><b><b>ü</b></b></u><b>h</b><b> </b>‹Adv.› [mhd. vruo, ahd. fruo, eigtl. = (zeitlich) vorn, voran]: morgens, am Morgen: <i>heute f., [am] Dienstag f.; </i> <i>kommst du morgen f.?; </i> <i>er arbeitet von f. bis spät [in die Nacht] (den ganzen Tag).</i> </div>
# </div>
# </idx:entry>
# <div height="10" align="center"><img hspace="0" vspace="0" align="middle" losrc="Images/image15903.gif" hisrc="Images/image15904.gif" src="Images/image15905.gif" /><br /></div>
# Clean images out of the html
if( $html =~ m~<img[^>]+>~s and $isConvertImagesUsingOCR ){
$html = convertIMG2Text( $html );
if( $isTestingOn ){
my $ConvertedIMG2TextHTML = $FileName;
$ConvertedIMG2TextHTML =~ m~/([^/]+)$~;
$ConvertedIMG2TextHTML = $1;
debug_t( "Filename at ".__LINE__." is '$FileName'" );
unless( $ConvertedIMG2TextHTML =~ s~(xdxf|html)$~test.html~ ){ die2("Regex for filename for test.html does not match."); }
string2File( $BaseDir."/".$ConvertedIMG2TextHTML, $html );
}
}
# my @indexentries = $html=~m~<idx:entry scriptable="yes">((?:(?!</idx:entry>).)+)</idx:entry>~gs; # Only works for Duden
my @indexentries = $html=~m~<idx:entry[^>]*>((?:(?!<idx:entry).)+)~gs; # Collect from the start until the next starts.
if( scalar @indexentries == 0 ){
if ($html =~ m~<meta name="generator" content="ABBYY FineReader 15">~s){
warn "Found meta content to be ABBYY FineReader 15. Trying convertABBYY2XDXF";
return( convertABBYY2XDXF( $html ) );
}
else{
warn "No idx-entry tags found in html. Trying convertParsed2XDXF";
return convertParsed2XDXF( $html );
}
}
if($isTestingOn){ array2File("test_html_indexentries.html",map(qq/$_\n/,@indexentries) ) ; }
waitForIt("Converting indexentries from HTML to XDXF.");
my $number = 0;
my $lastkey = "";
my $lastInflectionEntries="";
my %ConversionDebugStrings;
my ($TotalRemovalTime,$TotalImageConversion,$TotalEncodingConversionTime,$TotalConversion2SpanTime,$TotalArticleExtraction) = (0,0,0,0,0);
foreach (@indexentries){
my $TotalTime = 0;
$number++;
my $isLoopDebugging = 0;
if(m~<idx:orth value="\Q$DebugKeyWordConvertHTML2XDXF\E"~ and $isTestingOn){ $isLoopDebugging = 1; }
debug($_) if $isLoopDebugging;
# Removal of tags
my $start = time;
# Remove <a />, </a>, </idx:entry>, <br/>, <hr />, <betonung/>, <mmc:fulltext-word ../> tags
s~</?a[^>]*>|<betonung\s*/>|</idx:entry>|<br\s*/>|<hr\s*/>|<mmc:fulltext-word[^>]+>~~sg;
# Remove empty tag-pairs
$_ = removeEmptyTagPairs( $_ );
$TotalRemovalTime += time - $start;
# Convert or remove <img...>, e.g. <img hspace="0" align="middle" hisrc="Images/image15907.gif" />
$start = time;
if( $isConvertImagesUsingOCR and m~<img[^>]+>~s ){ $_ = convertIMG2Text( $_ ); }
if( $isCodeImageBase64 and m~<img[^>]+>~s ){ $_ = convertImage2Base64( $_ ); }
else{ s~<img[^>]+>~~sg; } # No images-resources are used in xdxf.
$TotalImageConversion += time - $start;
# Include encoding conversion
$start = time;
while( $encoding eq "cp1252" and m~\&\#(\d+);~s ){
my $encoded = $1;
my $decoded = decode( $encoding, pack("N", $encoded) );
# The decode step generates four hex values: a triplet of <0x00> followed by the one that's wanted. This goes awry if there are multiple non-zero octets.
while( ord( substr( $decoded, 0, 1) ) == 0 ){
$decoded = substr( $decoded, 1 );
}
# Skip character because it cannot be handled by code and is most probably the same in cp1252 and unicode.
if( length($decoded)>1 ){
# Convert to hexadecimal value so that the while-loop doesn't become endless.
my $hex = sprintf("%X", $encoded);
$decoded = "&#x$hex;";
}
# If character is NL, than replacement should be \n
elsif( ord($decoded) == 12 ){ $decoded = "\n";}
my $DebugString = "Encoding is $encoding. Encoded is $encoded. Decoded is \'$decoded\' of length ".length($decoded).", numbered ".ord($decoded);
$ConversionDebugStrings{$encoded} = $DebugString;
s~\&\#$encoded;~$decoded~sg;
}
$TotalEncodingConversionTime += time - $start;
# Change div-blocks to spans
if( $isConvertDiv2SpaninHTML2DXDF ){ s~(</?)div[^>]*>~$1span>~sg; }
my $round = 0;
# Change font- to spanblocks
$start = time;
while( $isConvertFont2Small and s~<font size="(?:2|-1)">((?:(?!</font).)+)</font>~<small>$1</small>~sg ){
$round++;
debug("font-blocks substituted with small-blocks in round $round.") if m~<idx:orth value="$DebugKeyWordConvertHTML2XDXF"~;
}
$round = 0;
while( $isConvertFont2Span and s~<font(?<fontstyling>[^>]*)>(?<content>(?:(?!</font).)*)</font>~<span$+{"fontstyling"}>$+{"content"}</span>~sg ){
$round++;
debug("font-blocks substituted with span-blocks in round $round.") if m~<idx:orth value="$DebugKeyWordConvertHTML2XDXF"~;
}
# Change <mmc:no-fulltext> to <span>
$round = 0;
while( $isConvertMMCFullText2Span and s~<mmc:no-fulltext>((?:(?!</mmc:no-fulltext).)+)</mmc:no-fulltext>~<span> $1</span>~sg ){
$round++;
debug("<mmc:no-fulltext>-blocks substituted with spans in round $round.") if $number<3;
}
$TotalConversion2SpanTime = time - $start;
# Create key&definition strings.
$start = time;
# m~^<idx:orth value="(?<key>[^"]+)"></idx:orth>(?<def>.+)$~s; # Works only for Duden
s~<idx:orth value="(?<key>[^"]+)">~~s; # Remove idx-orth value.
my $key = $+{key};
if( defined $key and $key ne "" ){ debug("Found \$key $key.") if $isLoopDebugging; }
else{ debug("No key found! Dumping and Quitting:\n\n$_"); die;}
s~</idx:orth>~~sg; # Remove closing tag if present.
#Handle inflections block
# Remove inflections category tags
s~</?idx:infl>~~sg;
# <idx:iform name="" value="Academia" />
my @inflections = m~<idx:iform name="" value="(\w*)"/>~sg;
s~<idx:iform[^>]*>~~sg;
my $InflectionEntries="";
foreach my $inflection(@inflections){
# Create string to append after main definition.
if( defined $inflection and $inflection ne $key and $inflection ne "" ){
my $ExtraEntry = "<ar><head><k>$inflection</k></head><def><blockquote>↑".pack("U", 0x2009)."<i>$key</i></blockquote></def></ar>\n";
$InflectionEntries = $InflectionEntries.$ExtraEntry;
}
}
# Remove leftover empty lines.
s~ ~ ~sg;
s~\t\t~\t~sg;
s~\n\n~\n~sg;
# Remove trailing and leading spaces and line endings
s~^\s+~~sg;
s~\s+$~~sg;
# Assign remaining entry to $def.
my $def = "<blockquote>".$_."</blockquote>";
debugV("key found: $key") if $number<5;
debugV("def found: $def") if $number<5;
# Remove whitespaces at the beginning of the definition and EOL at the end.
$def =~ s~^\s+~~;
$def =~ s~\n$~~;
# Switch position sup/span/small blocks
# <sup><small>1‌</small></sup>
# $html =~ s~<sup><small>([^<]*)</small>~<sup>$1~sg;
$def =~ s~<sup><small>([^<]*)</small></sup>~<small><sup>$1</sup></small>~sg;
# $html =~ s~<sup><span>([^<]*)</span>~<sup>$1~sg;
$def =~ s~<sup><span>([^<]*)</span></sup>~<span><sup>$1</sup></span>~sg;
$def =~ s~<sub><small>([^<]*)</small></sub>~<small><sub>$1</sub></small>~sg;
$def =~ s~<sub><span>([^<]*)</span></sub>~<span><sub>$1</sub></span>~sg;
# Put space in front of ‹, e.g. ‹Adj.›, if it's lacking
$def =~ s~([^\s])‹~$1 ‹~sg;
if( $key eq $lastkey){
# Change the last entry to append current definition
$xdxf[-1] =~ s~</def></ar>\n~\n$def</def></ar>\n~s;
debug("Added to the last definition. It's now:\n$xdxf[-1]") if $isLoopDebugging;
}
else{
# Because I want the inflections to follow in the index on the full definition.
if( $lastInflectionEntries ne "" ){
$xdxf[-1] =~ s~\n$~\n$lastInflectionEntries~s;
$lastInflectionEntries = "";
}
push @xdxf, "<ar><head><k>$key</k></head><def>$def</def></ar>\n";
debug("Pushed <ar><head><k>$key</k></head><def>$def</def></ar>") if $isLoopDebugging;
}
# To allow appending definitions of identical keys
$lastkey = $key;
# To allow inflection entries after the main entry
$lastInflectionEntries = $lastInflectionEntries.$InflectionEntries;
$TotalArticleExtraction += time - $start;
my @Names = ("TotalRemovalTime","TotalImageConversion","TotalEncodingConversionTime","TotalConversion2SpanTime","TotalArticleExtraction");
foreach($TotalRemovalTime,$TotalImageConversion,$TotalEncodingConversionTime,$TotalConversion2SpanTime,$TotalArticleExtraction){
my $Name = shift @Names;
infoVV("$Name: $_");
$TotalTime += $_;
}
infoVV("Total time in loop: $TotalTime");
}
foreach( sort keys %ConversionDebugStrings){ debug($ConversionDebugStrings{$_}); }
doneWaiting();
push @xdxf, $lastline_xdxf;
return(@xdxf);}
our $isConvertGIF2PNG = 0; # Creates a dependency on Imagemagick "convert".
our (%ReplacementImageStrings, $ReplacementImageStringsHashFileName);
sub convertImage2Base64{
$_ = shift;
my @imagestrings = m~(<img[^>]+>)~sg;
debug("Number of imagestrings found is ", scalar @imagestrings) if m~<idx:orth value="$DebugKeyWordConvertHTML2XDXF"~;
my $replacement;
foreach my $imagestring(@imagestrings){
# debug('$ReplacementImageStrings{$imagestring}: ',$ReplacementImageStrings{$imagestring});
if ( exists $ReplacementImageStrings{$imagestring} ){
$replacement = $ReplacementImageStrings{$imagestring}
}
else{
# <img hspace="0" align="middle" hisrc="Images/image15907.gif"/>
$imagestring =~ m~hisrc="(?<image>[^"]*?\.(?<ext>gif|jpg|png|bmp))"~si;
debug("Found image named $+{image} with extension $+{ext}.") if m~<idx:orth value="$DebugKeyWordConvertHTML2XDXF"~;
my $imageName = $+{image};
my $imageformat = $+{ext};
if( -e "$FullPath/$imageName"){
if ( $isConvertGIF2PNG and $imageformat =~ m~gif~i){
# Convert gif to png
my $Command="convert \"$FullPath/$imageName\" \"$FullPath/$imageName.png\"";
debug("Executing command: $Command") if m~<idx:orth value="$DebugKeyWordConvertHTML2XDXF"~;
`$Command`;
$imageName = "$imageName.png";
$imageformat = "png";
}
my $image = join('', file2Array("$FullPath/$imageName", "raw", "quiet") );
my $encoded = encode_base64($image);
$encoded =~ s~\n~~sg;
$replacement = '<img src="data:image/'.$imageformat.';base64,'.$encoded.'" alt="'.$imageName.'"/>';
$replacement =~ s~\\\"~"~sg;
debug($replacement) if m~<idx:orth value="$DebugKeyWordConvertHTML2XDXF"~;
$ReplacementImageStrings{$imagestring} = $replacement;
}
else{
$replacement = "";
die2("Can't find $FullPath/$imageName. Quitting.");
}
}
s~\Q$imagestring\E~$replacement~;
}
return $_;}
our $isManualValidation = 1; # Default value
our $isRemoveUnSubstitutedImageString = 1;
our $isRemoveUnSourcedImageStrings = 1;
our (%OCRedImages, %ValidatedOCRedImages, $ValidatedOCRedImagesHashFileName);
sub convertIMG2Text{
if( $isConvertImagesUsingOCR ){
use Image::OCR::Tesseract 'get_ocr';
$Image::OCR::Tesseract::DEBUG = 0;
$ValidatedOCRedImagesHashFileName = $BaseDir."/".join('', $FileName=~m~^(.+?\.)[^.]+$~)."validation.hash";
debug_t( "ValidatedOCRedImagesHashFileName is '$ValidatedOCRedImagesHashFileName'");
if( -e $ValidatedOCRedImagesHashFileName ){ %ValidatedOCRedImages = %{ retrieveHash($ValidatedOCRedImagesHashFileName)}; }
else{ debug("No previously validated images found."); }
%OCRedImages = %ValidatedOCRedImages;
info("Number of imagestrings OCRed is ".scalar keys %ValidatedOCRedImages);
unless( storeHash(\%ValidatedOCRedImages, $ValidatedOCRedImagesHashFileName) ){ die2("Cannot store hash ValidatedOCRedImages.");} # To check whether filename is storable.
if( scalar keys %ValidatedOCRedImages == 0 ){ unlink $ValidatedOCRedImagesHashFileName; }
else{ info("Mistakes in the validated values can be manually corrected by editing '$ValidatedOCRedImagesHashFileName'"); }
}
else{ return shift; }
my $String = shift;
info_t("Entering convertIMG2Text");
debugVV( $String."\n");
# Get absolute ImagePath
my $CurrentDir = `pwd`; chomp $CurrentDir;
unless( $CurrentDir eq $BaseDir){ warn "'$CurrentDir' is another than '$BaseDir'"; }
else{ infoV("Working from '$BaseDir'"); }
infoV("$FileName");
unless( $FileName =~ m~(?<localpath>.+?)[^/]+$~ ){ die2("Regex didn't match for local path"); }
my $ImagePath = $BaseDir . "/" . $+{localpath};
info( "Imagepath is '$ImagePath'");
# Collect ImageStrings;
my @ImageStrings = $String =~ m~(<img[^>]+>)~sg;
unless( scalar @ImageStrings ){ warn "No imagestrings found in convertIMG2Text. Why is the sub called?"; return $String; }
my $counter = 0;
my %ImageStringsHandled;
IMAGESTRING: foreach my $ImageString( @ImageStrings){
# Deal with already handled imagestrings in $String.
if( $ImageStringsHandled{ $ImageString } ){ next; }
# Unhandled imagestring.
$counter++;
if( $ImageString =~ m~alt="x([0-9A-Fa-f]+)"~ ){
infoV("Alternative expression for image is U+$1.");
# my $smiley_from_code_point = "\N{U+263a}";
my $Alt = chr( hex($1) );
if( $String =~ s~\Q$ImageString\E~$Alt~sg ){
infoV("Substituted imagestring '$ImageString' with '$Alt'");
$ImageStringsHandled{ $ImageString } = 1;
next IMAGESTRING;
}
else{ die2("Regex substitution alternative expression doesn't work."); }
}
my @Sources = $ImageString =~ m~(\w*src="[^"]+")~sg;
unless( scalar @Sources ){
warn "No sources found in imagestring:\n'$ImageString'";
$ImageStringsHandled{ $ImageString } = 1;
if( $isRemoveUnSourcedImageStrings ){
unless( $String =~ s~\Q$ImageString\E~~sg){ die2("Couldn't remove unsourced imagestring"); }
next IMAGESTRING;
}
}
our %Sources;
foreach( @Sources ){
unless( m~(?<type>\w*src)="(?<imagename>[^"]+)"~s ){ die2("Regex sources doesn't work."); }
$Sources{ $+{"imagename"} } = $+{"type"};
}
our %SourceQuality = { "src" => 1, "hisrc" => 2, "lowsrc" => 0 };
sub sourceQuality{
# Filename to src/hisrc/losrc to 1/2/0
# Descending sort so $a and $b are swapped.
$SourceQuality{ $Sources{ $b } } <=> $SourceQuality { $Sources { $a } }
}
SOURCE: foreach my $Source ( sort sourceQuality keys %Sources ){
# Change to absolute path
my $SourceInfo = "Quality of '$Source' is '$Sources{ $Source }'";
$Source = $ImagePath . $Source;
# If the source has been validated, act upon it.
if( exists $ValidatedOCRedImages{ $Source } ){
if( defined $ValidatedOCRedImages{ $Source } and $ValidatedOCRedImages{ $Source } ne "VALIDATED AS INCORRECT" ){
unless ( $String =~ s~\Q$ImageString\E~$ValidatedOCRedImages{ $Source }~sg ){
die2("ImageString '$ImageString' not matched for substitution with '$ValidatedOCRedImages{ $Source }'.");
}
else{
infoV("ImageString '$ImageString' substituted with '$ValidatedOCRedImages{ $Source }'.");
}
$ImageStringsHandled{ $ImageString } = 1;
next IMAGESTRING;
}
else{ next SOURCE; }
}
# No validated recognition of source image available.
elsif( $isManualValidation ){
unless( -e $Source ){ warn "Image file '$Source' not found."; next SOURCE; }
# No use in running the OCR twice.
unless( exists $OCRedImages{ $Source } ){
my $text = get_ocr( $Source, undef, "eng+equ --psm 10" );
chomp $text;
info_t( "Imagestring =\n'".$ImageString."'");
info_t( $SourceInfo );
info( "Tesseract identified image '$Source' as '$text'");
$OCRedImages{ $Source } = $text;
}
if( $OCRedImages{ $Source } eq '' ){ debug("No result from OCR."); }
# Validate OCRedImages manually and store them or quit.
my $substitution = 0;
system("feh --borderless --auto-zoom --image-bg white --geometry 300x300 \"$Source\"&");
printGreen("\n\n--------->Is the image '$Source' correctly recognized as '".$OCRedImages{$Source}."'?\nPress enter to keep or provide a correction or quit manual validation [Enter|Provide correction|No|quit]");
my $input = <STDIN>;
system( "killall feh 2>/dev/null");
chomp $input;
if( $input =~ m~quit~i ){
$isManualValidation = 0;
next SOURCE;
}
elsif( $input eq ''){
$ValidatedOCRedImages{ $Source } = $OCRedImages{ $Source };
$substitution = 1;
}
elsif( $input =~ m~no~i ){
$ValidatedOCRedImages{ $Source } = "VALIDATED AS INCORRECT";
$substitution = 0;
}
else{
$ValidatedOCRedImages{ $Source } = $input;
$substitution = 1;
}
storeHash(\%ValidatedOCRedImages, $ValidatedOCRedImagesHashFileName);
if( $substitution ){
unless ( $String =~ s~\Q$ImageString\E~$ValidatedOCRedImages{ $Source }~sg ){
die2("ImageString '$ImageString' not matched for substitution with '$ValidatedOCRedImages{ $Source }'");
}
$ImageStringsHandled{ $ImageString } = 1;
next IMAGESTRING;
}
}
}
# End SOURCE-loop. If the code is here, than no substitution has been made for the imagestring.
if( $isRemoveUnSubstitutedImageString ){
unless( $String =~ s~\Q$ImageString\E~~sg ){ die2("Image-tag '$ImageString' could not be removed"); }
$ImageStringsHandled{ $ImageString } = 1;
}
}
infoV("Leaving convertIMG2Text");
return $String;}
sub convertRAWML2XDXF{
# Converts html generated by KindleUnpack to xdxf
my $rawml = join('',@_);
my $xdxfCuts = convertRAWMLUsingManualCuts( $rawml );
if( defined $xdxfCuts ){ return @{ $xdxfCuts }; }
my $xdxf_try = generateXDXFTagBased( $rawml );
if( $xdxf_try ){ return (@{ $xdxf_try }); }