-
-
Notifications
You must be signed in to change notification settings - Fork 2
/
Copy pathPageXML.cc
5617 lines (5016 loc) · 192 KB
/
PageXML.cc
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
/**
* Class for input, output and processing of Page XML files and referenced image.
*
* @version $Version: 2025.04.24$
* @copyright Copyright (c) 2016-present, Mauricio Villegas <[email protected]>
* @license MIT License
*/
#include "PageXML.h"
#include <stdio.h>
#include <unistd.h>
#include <string.h>
#include <math.h>
#include <stdexcept>
#include <regex>
#include <iomanip>
#include <unordered_set>
#include <cassert>
#include <fstream>
#include <set>
#include <map>
#ifdef __PAGEXML_SLIM__
#include "mock_cv.h"
#else
#include <opencv2/opencv.hpp>
#endif
#include <libxml/xpathInternals.h>
#include <libxslt/xsltconfig.h>
using namespace std;
#ifdef __PAGEXML_MAGICK__
Magick::Color transparent("rgba(0,0,0,0)");
Magick::Color opaque("rgba(0,0,0,100%)");
Magick::Color colorWhite("white");
#endif
regex reXheight(".*x-height: *([0-9.]+) *px;.*");
regex reRotation(".*readingOrientation: *([0-9.]+) *;.*");
regex reDirection(".*readingDirection: *([lrt]t[rlb]) *;.*");
regex reFileExt("\\.[^.]+$");
regex reInvalidBaseChars(" ");
regex reImagePageNum("^(.*)\\[([0-9]+)\\]$");
regex reIsPdf(".+\\.pdf(\\[[0-9]+\\]){0,1}$",std::regex::icase);
regex reIsTiff(".+\\.tif{1,2}(\\[[0-9]+\\]){0,1}$",std::regex::icase);
xsltStylesheetPtr sortattr = xsltParseStylesheetDoc( xmlParseDoc( (xmlChar*)"<xsl:stylesheet xmlns:xsl=\"http://www.w3.org/1999/XSL/Transform\" version=\"1.0\"><xsl:output method=\"xml\" indent=\"yes\" encoding=\"utf-8\" omit-xml-declaration=\"no\"/><xsl:template match=\"*\"><xsl:copy><xsl:apply-templates select=\"@*\"><xsl:sort select=\"name()\"/></xsl:apply-templates><xsl:apply-templates/></xsl:copy></xsl:template><xsl:template match=\"@*|comment()|processing-instruction()\"><xsl:copy/></xsl:template></xsl:stylesheet>" ) );
xsltStylesheetPtr sortelem = xsltParseStylesheetDoc( xmlParseDoc( (xmlChar*)"<xsl:stylesheet xmlns:xsl=\"http://www.w3.org/1999/XSL/Transform\" version=\"1.0\"><xsl:output method=\"xml\" indent=\"yes\" encoding=\"utf-8\" omit-xml-declaration=\"no\"/><xsl:strip-space elements=\"*\"/><xsl:template match=\"@* | node()\"><xsl:copy><xsl:apply-templates select=\"@* | node()\"/></xsl:copy></xsl:template><xsl:template match=\"*[local-name()='PcGts']\"><xsl:copy><xsl:apply-templates select=\"@*\"/><xsl:apply-templates select=\"*[local-name()='Metadata']\"/><xsl:apply-templates select=\"*[local-name()='Property']\"/><xsl:apply-templates select=\"*[local-name()='Page']\"/><xsl:apply-templates select=\"node()[not(contains(' Metadata Property Page ',concat(' ',local-name(),' ')))]\"/></xsl:copy></xsl:template><xsl:template match=\"*[*[local-name()='Coords' or local-name()='Baseline' or local-name()='TextEquiv']] | *[local-name()='Page']\"><xsl:copy><xsl:apply-templates select=\"@*\"/><xsl:apply-templates select=\"*[local-name()='ImageOrientation']\"/><xsl:apply-templates select=\"*[local-name()='Property']\"/><xsl:apply-templates select=\"*[local-name()='Coords']\"/><xsl:apply-templates select=\"*[local-name()='Baseline']\"/><xsl:apply-templates select=\"*[local-name()='TextLine' or local-name()='Word' or local-name()='Glyph']\"/><xsl:apply-templates select=\"*[local-name()='TextEquiv']\"/><xsl:apply-templates select=\"node()[not(contains(' ImageOrientation Property Coords Baseline TextLine Word Glyph TextEquiv ',concat(' ',local-name(),' ')))]\"/></xsl:copy></xsl:template></xsl:stylesheet>" ) );
bool validation_enabled = true;
/////////////////////
/// Class version ///
/////////////////////
static char class_version[] = "Version: 2022.08.15";
/**
* Returns the class version.
*/
char* PageXML::version() {
return class_version+9;
}
/**
* Prints the version of the PageXML library and its main dependencies.
*
* @param file Stream where to print the versions.
*/
void PageXML::printVersions( FILE* file ) {
fprintf( file, "compiled against PageXML %s\n", class_version+9 );
fprintf( file, "compiled against libxml2 %s, linked with %s\n", LIBXML_DOTTED_VERSION, xmlParserVersion );
fprintf( file, "compiled against libxslt %s, linked with %s\n", LIBXSLT_DOTTED_VERSION, xsltEngineVersion );
#ifndef __PAGEXML_SLIM__
fprintf( file, "compiled against opencv %s\n", CV_VERSION );
#endif
}
/////////////////////////
/// Resources release ///
/////////////////////////
/**
* Releases all reserved resources of PageXML instance.
*/
void PageXML::release() {
freeXML();
freeSchema();
}
/**
* Releases XML related resources.
*/
void PageXML::freeXML() {
if( xml == NULL )
return;
if( xml != NULL )
xmlFreeDoc(xml);
xml = NULL;
if( context != NULL )
xmlXPathFreeContext(context);
context = NULL;
imgDir = string("");
xmlPath = string("");
#if defined (__PAGEXML_LEPT__) || defined (__PAGEXML_IMG_MAGICK__) || defined (__PAGEXML_IMG_CV__)
releaseImages();
pagesImage = std::vector<PageImage>();
#endif
pagesImageFilename = std::vector<std::string>();
pagesImageBase = std::vector<std::string>();
process_running = NULL;
}
/**
* PageXML object destructor.
*/
PageXML::~PageXML() {
release();
}
////////////////////
/// Constructors ///
////////////////////
/**
* PageXML constructor that receives a file name to load.
*
* @param pagexml_path Path to the XML file to read.
* @param schema_path Path to the XSD file to read.
*/
PageXML::PageXML( const char* pagexml_path, const char* schema_path ) {
if( schema_path != NULL )
loadSchema( schema_path );
if( pagexml_path != NULL )
loadXml( pagexml_path );
}
PageXML PageXML::clone() {
PageXML pxml;
pxml.loadXmlString( toString().c_str(), false );
pxml.setImagesBaseDir( std::string(imgDir) );
pxml.setXmlFilePath( std::string(xmlPath) );
return pxml;
}
void PageXML::setImagesBaseDir( std::string imgBaseDir ) {
imgDir = imgBaseDir;
}
void PageXML::setXmlFilePath( std::string xmlFilePath ) {
xmlPath = xmlFilePath;
}
std::string PageXML::getImagesBaseDir() {
return imgDir;
}
std::string PageXML::getXmlFilePath() {
return xmlPath;
}
/////////////////////////
/// Schema validation ///
/////////////////////////
static void validationErrorFunc( void* ctx __attribute__((unused)), const char *msg, ... ) {
static char buffer[5000];
va_list argp;
va_start( argp, msg );
vsprintf( buffer, msg, argp );
va_end( argp );
fprintf( stderr, "error: %s\n", buffer );
}
static void validationWarningFunc( void* ctx __attribute__((unused)), const char *msg, ... ) {
static char buffer[5000];
va_list argp;
va_start( argp, msg );
vsprintf( buffer, msg, argp );
va_end( argp );
fprintf( stderr, "warning: %s\n", buffer );
}
/**
* Releases schema related resources.
*/
void PageXML::freeSchema() {
schema_namespace = std::string("");
if( valid_context ) {
xmlSchemaFreeValidCtxt(valid_context);
valid_context = NULL;
}
if( valid_schema ) {
xmlSchemaFree(valid_schema);
valid_schema = NULL;
}
if( valid_parser ) {
xmlSchemaFreeParserCtxt(valid_parser);
valid_parser = NULL;
}
if( valid_doc ) {
xmlFreeDoc(valid_doc);
valid_doc = NULL;
}
}
/**
* Gets the default namespace of a document.
*
* @param doc The XML document pointer.
* @return The default namespace string.
*/
std::string getDefaultNamespace( xmlDocPtr doc ) {
xmlXPathContextPtr ctxt = xmlXPathNewContext(doc);
xmlXPathObjectPtr xsel = xmlXPathEvalExpression( (xmlChar*)"//namespace::*[name()='']", ctxt );
if ( xsel == NULL || xmlXPathNodeSetIsEmpty(xsel->nodesetval) || xsel->nodesetval->nodeNr < 1 )
throw_runtime_error( "getDefaultNamespace: problems retrieving default namespace" );
xmlChar* cnamespace = xmlNodeGetContent(xsel->nodesetval->nodeTab[0]);
std::string snamespace((char*)cnamespace);
xmlFree(cnamespace);
xmlXPathFreeObject(xsel);
if ( snamespace == std::string("http://www.w3.org/2001/XMLSchema") ) {
xmlXPathObjectPtr xsel = xmlXPathEvalExpression( (xmlChar*)"//namespace::*[name()='pc']", ctxt );
if ( xsel == NULL || xmlXPathNodeSetIsEmpty(xsel->nodesetval) || xsel->nodesetval->nodeNr < 1 )
throw_runtime_error( "getDefaultNamespace: problems retrieving pc namespace" );
cnamespace = xmlNodeGetContent(xsel->nodesetval->nodeTab[0]);
snamespace = std::string((char*)cnamespace);
xmlFree(cnamespace);
xmlXPathFreeObject(xsel);
}
xmlXPathFreeContext(ctxt);
return snamespace;
}
/**
* Loads a schema for xml validation.
*
* @param schema_path File name of the XSD file to read.
*/
void PageXML::loadSchema( const char *schema_path ) {
if( schema_path == NULL )
return;
freeSchema();
if( ! (valid_doc = xmlReadFile(schema_path, NULL, XML_PARSE_NONET)) )
throw_runtime_error( "PageXML.loadSchema: problems reading schema: %s", schema_path );
if( ! (valid_parser = xmlSchemaNewDocParserCtxt(valid_doc)) )
throw_runtime_error( "PageXML.loadSchema: problems creating schema parser: %s", schema_path );
if( ! (valid_schema = xmlSchemaParse(valid_parser)) )
throw_runtime_error( "PageXML.loadSchema: problems parsing schema: %s", schema_path );
if( ! (valid_context = xmlSchemaNewValidCtxt(valid_schema)) )
throw_runtime_error( "PageXML.loadSchema: problems creating validation context: %s", schema_path );
xmlSchemaSetValidErrors( valid_context, &validationErrorFunc, &validationWarningFunc, NULL );
schema_namespace = getDefaultNamespace(valid_doc);
}
/**
* Validates the currently loaded XML.
*
* @param xml_to_validate Pointer to the loaded XML to validate.
* @return Whether XML validates or not.
*/
bool PageXML::isValid( xmlDocPtr xml_to_validate ) {
if( xml_to_validate == NULL )
xml_to_validate = xml;
if( xml_to_validate == NULL || valid_context == NULL || ! validation_enabled )
return true;
std::string xml_namespace = getDefaultNamespace(xml_to_validate);
if ( xml_namespace != schema_namespace ) {
std::string conv_str = std::string("<xsl:stylesheet\n")
+ " xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\"\n"
+ " xmlns:xsl=\"http://www.w3.org/1999/XSL/Transform\"\n"
+ " xmlns:_=\"" + xml_namespace + "\"\n"
+ " xmlns=\"" + schema_namespace + "\"\n"
+ " extension-element-prefixes=\"xsi _\"\n"
+ " version=\"1.0\">\n"
+ " <xsl:output method=\"xml\" indent=\"no\" encoding=\"utf-8\" omit-xml-declaration=\"no\"/>\n"
+ " <xsl:strip-space elements=\"*\"/>\n"
+ " <xsl:template match=\"@xsi:schemaLocation\"/>\n"
+ " <xsl:template match=\"@* | node()\">\n"
+ " <xsl:copy>\n"
+ " <xsl:apply-templates select=\"@* | node()\"/>\n"
+ " </xsl:copy>\n"
+ " </xsl:template>\n"
+ " <xsl:template match=\"_:*\">\n"
+ " <xsl:element name=\"{local-name()}\">\n"
+ " <xsl:apply-templates select=\"@* | node()\"/>\n"
+ " </xsl:element>\n"
+ " </xsl:template>\n"
+ "</xsl:stylesheet>\n";
xsltStylesheetPtr conv_xslt = xsltParseStylesheetDoc( xmlParseDoc( (xmlChar*)conv_str.c_str() ) );
xml_to_validate = xmlCopyDoc(xml_to_validate, true); // Avoids weird issue
xmlDocPtr conv_xml = xsltApplyStylesheet( conv_xslt, xml_to_validate, NULL );
bool is_valid = xmlSchemaValidateDoc(valid_context, conv_xml) ? false : true;
xmlFreeDoc(conv_xml);
xmlFreeDoc(xml_to_validate);
xsltFreeStylesheet(conv_xslt);
return is_valid;
}
return xmlSchemaValidateDoc(valid_context, xml_to_validate) ? false : true;
}
/**
* Enables/disables schema validation.
*
* @param val Whether schema validation should be enabled.
*/
void PageXML::setValidationEnabled( bool val ) {
validation_enabled = val;
}
//////////////
/// Output ///
//////////////
/**
* Writes the current state of the XML to a file using utf-8 encoding.
*
* @param fname File name of where the XML file will be written.
* @param indent Whether to indent the XML.
* @param validate Whether the Page XML should be validated before writing.
* @return Number of bytes written.
*/
int PageXML::write( const char* fname, bool indent, bool validate ) {
if ( ! xml )
throw_runtime_error( "PageXML.write: no Page XML loaded" );
if ( process_running )
processEnd();
xmlDocPtr tmpxml = xmlCopyDoc(xml, true); // Avoids weird issue
xmlDocPtr sortedElemXml = xsltApplyStylesheet( sortelem, tmpxml, NULL );
xmlDocPtr sortedXml = xsltApplyStylesheet( sortattr, sortedElemXml, NULL );
xmlFreeDoc(sortedElemXml);
xmlFreeDoc(tmpxml);
if( validate && ! isValid(sortedXml) ) {
xmlFreeDoc(sortedXml);
throw_runtime_error( "PageXML.write: aborted write of invalid PageXML" );
}
int bytes = xmlSaveFormatFileEnc( fname, sortedXml, "utf-8", indent );
xmlFreeDoc(sortedXml);
if ( strcmp("-",fname) )
setXmlFilePath(std::string(fname));
return bytes;
}
/**
* Creates a string representation of the Page XML.
*
* @param indent Whether to indent the XML.
* @param validate Whether the Page XML should be validated before writing.
* @return The Page XML string.
*/
string PageXML::toString( bool indent, bool validate ) {
if ( ! xml )
throw_runtime_error( "PageXML.toString: no Page XML loaded" );
if ( process_running )
processEnd();
string sxml;
xmlChar *cxml;
int size;
xmlDocPtr tmpxml = xmlCopyDoc(xml, true); // Avoids weird issue
xmlDocPtr sortedElemXml = xsltApplyStylesheet( sortelem, tmpxml, NULL );
xmlDocPtr sortedXml = xsltApplyStylesheet( sortattr, sortedElemXml, NULL );
xmlFreeDoc(sortedElemXml);
xmlFreeDoc(tmpxml);
if( validate && ! isValid(sortedXml) ) {
xmlFreeDoc(sortedXml);
throw_runtime_error( "PageXML.toString: aborted conversion to string of invalid PageXML" );
}
xmlDocDumpFormatMemoryEnc(sortedXml, &cxml, &size, "utf-8", indent);
xmlFreeDoc(sortedXml);
if ( cxml == NULL ) {
throw_runtime_error( "PageXML.toString: problem dumping to memory" );
return sxml;
}
sxml = string((char*)cxml);
xmlFree(cxml);
return sxml;
}
///////////////
/// Loaders ///
///////////////
/**
* Creates a new Page XML.
*
* @param creator Info about tool creating the XML.
* @param image Path to the image file.
* @param imgW Width of image.
* @param imgH Height of image.
* @param pagens The page xml namespace string to use.
* @return Pointer to the Page node.
*/
xmlNodePt PageXML::newXml( const char* creator, const char* image, const int imgW, const int imgH, const char* pagens ) {
if ( schema_namespace.length() == 0 && pagens == NULL ) {
throw_runtime_error( "PageXML.newXml: either a schema should be loaded or pagens provided" );
return NULL;
}
freeXML();
time_t now;
time(&now);
char tstamp[sizeof "YYYY-MM-DDTHH:MM:SSZ"];
strftime(tstamp, sizeof tstamp, "%FT%TZ", gmtime(&now));
std::string spagens = schema_namespace;
if ( pagens != NULL )
spagens = std::string(pagens);
std::string libver = std::string("PageXML ") + (class_version+9);
std::string str = std::string("<?xml version=\"1.0\" encoding=\"utf-8\"?>\n")
+ "<PcGts xmlns=\"" + spagens + "\">\n"
+ " <Metadata>\n"
+ " <Creator>" + (creator == NULL ? libver : std::string(creator)+" ("+libver+")" ) + "</Creator>\n"
+ " <Created>" + tstamp + "</Created>\n"
+ " <LastChange>" + tstamp + "</LastChange>\n"
+ " </Metadata>\n"
+ " <Page imageFilename=\"" + image +"\" imageHeight=\"" + to_string(imgH) + "\" imageWidth=\"" + to_string(imgW) + "\"/>\n"
+ "</PcGts>\n";
xmlKeepBlanksDefault(0);
xml = xmlParseDoc( (xmlChar*)str.c_str() );
setupXml();
if( imgW <= 0 || imgH <= 0 ) {
#if defined (__PAGEXML_LEPT__) || defined (__PAGEXML_IMG_MAGICK__) || defined (__PAGEXML_IMG_CV__)
loadImage( 0, NULL, false );
#if defined (__PAGEXML_LEPT__)
int width = pixGetWidth(pagesImage[0]);
int height = pixGetHeight(pagesImage[0]);
#elif defined (__PAGEXML_IMG_MAGICK__)
int width = pagesImage[0].columns();
int height = pagesImage[0].rows();
#elif defined (__PAGEXML_IMG_CV__)
int width = pagesImage[0].size().width;
int height = pagesImage[0].size().height;
#endif
setAttr( "//_:Page", "imageWidth", to_string(width).c_str() );
setAttr( "//_:Page", "imageHeight", to_string(height).c_str() );
#else
throw_runtime_error( "PageXML.newXml: invalid image size" );
freeXML();
return NULL;
#endif
}
return selectNth( "//_:Page", 0 );
}
/**
* Loads a Page XML from a file.
*
* @param fname File name of the XML file to read.
* @param validate Whether to validate against XSD schema.
*/
void PageXML::loadXml( const char* fname, bool validate ) {
freeXML();
if ( ! strcmp(fname,"-") ) {
loadXml( STDIN_FILENO, false, validate );
return;
}
size_t slash_pos = string(fname).find_last_of("/");
imgDir = slash_pos == string::npos ?
string(""):
string(fname).substr(0,slash_pos);
FILE *file;
if ( (file=fopen(fname,"rb")) == NULL ) {
throw_runtime_error( "PageXML.loadXml: unable to open file: %s", fname );
return;
}
loadXml( fileno(file), false, validate );
setXmlFilePath(std::string(fname));
fclose(file);
}
/**
* Loads a Page XML from an input stream.
*
* @param fnum File number from where to read the XML file.
* @param prevfree Whether to release resources before loading.
* @param validate Whether to validate against XSD schema.
*/
void PageXML::loadXml( int fnum, bool prevfree, bool validate ) {
if ( prevfree )
freeXML();
xmlKeepBlanksDefault(0);
xml = xmlReadFd( fnum, NULL, NULL, XML_PARSE_NONET );
if ( ! xml ) {
throw_runtime_error( "PageXML.loadXml: problems reading file" );
return;
}
setupXml();
if( validate && ! isValid() ) {
freeXML();
throw_runtime_error( "PageXML.loadXml: aborted load of invalid Page XML" );
}
}
/**
* Loads a Page XML from a string.
*
* @param xml_string The XML content.
* @param validate Whether to validate against XSD schema.
*/
void PageXML::loadXmlString( const char* xml_string, bool validate ) {
freeXML();
xmlKeepBlanksDefault(0);
xml = xmlParseDoc( (xmlChar*)xml_string );
if ( ! xml ) {
throw_runtime_error( "PageXML.loadXmlString: problems reading XML from string" );
return;
}
setupXml();
if( validate && ! isValid() ) {
freeXML();
throw_runtime_error( "PageXML.loadXml: aborted load of invalid Page XML" );
}
}
/**
* Populates the imageFilename and pagesImageBase arrays for the given page number.
*
* @param pagenum The page number (0-based).
*/
void PageXML::parsePageImage( int pagenum ) {
xmlNodePt page = selectNth( "//_:Page", pagenum );
string imageFilename = getAttr( page, "imageFilename" );
if( imageFilename.empty() ) {
throw_runtime_error( "PageXML.parsePageImage: problems retrieving image filename from xml" );
return;
}
pagesImageFilename[pagenum] = imageFilename;
string imageBase = regex_replace( imageFilename, reFileExt, "" );
imageBase = regex_replace( imageBase, reInvalidBaseChars, "_" );
pagesImageBase[pagenum] = imageBase;
}
/**
* Setups internal variables related to the loaded Page XML.
*/
void PageXML::setupXml() {
context = xmlXPathNewContext(xml);
if( context == NULL ) {
throw_runtime_error( "PageXML.setupXml: unable create xpath context" );
return;
}
std::string pagens = getDefaultNamespace(xml);
if( xmlXPathRegisterNs( context, (xmlChar*)"_", (xmlChar*)pagens.c_str() ) != 0 ) {
throw_runtime_error( "PageXML.setupXml: unable to register namespace" );
return;
}
rootnode = xmlDocGetRootElement(xml);
rpagens = xmlSearchNsByHref(xml,rootnode,(xmlChar*)pagens.c_str());
vector<xmlNodePt> elem_page = select( "//_:Page" );
if( elem_page.size() == 0 ) {
throw_runtime_error( "PageXML.setupXml: unable to find Page element(s)" );
return;
}
#if defined (__PAGEXML_LEPT__) || defined (__PAGEXML_IMG_MAGICK__) || defined (__PAGEXML_IMG_CV__)
pagesImage = std::vector<PageImage>(elem_page.size());
#endif
pagesImageFilename = std::vector<std::string>(elem_page.size());
pagesImageBase = std::vector<std::string>(elem_page.size());
for( int n=0; n<(int)elem_page.size(); n++ )
parsePageImage(n);
if( imgDir.empty() )
imgDir = string(".");
}
//#ifdef __PAGEXML_PDF__
/**
* Function that creates a temporal file using the mktemp command.
*
* @param tempbase The mktemp template to use, including at least 3 consecutive X.
* @param tempname Pointer where to store the temporal filename created.
*/
void mktemp( const char* tempbase, char *tempname ) {
char cmd[FILENAME_MAX];
sprintf( cmd, "mktemp --tmpdir %s", tempbase );
FILE *p = popen( cmd, "r" );
if( p != NULL ) {
sprintf( cmd, "%%%ds\n", FILENAME_MAX-1 );
if( fscanf( p, cmd, tempname ) != 1 )
tempname[0] = '\0';
pclose(p);
}
}
int execute_command( std::string command, std::string caller ) {
char buffer[128];
std::string result = "";
FILE* pipe = popen(command.c_str(), "r");
if( ! pipe ) {
throw_runtime_error( "%s: error: unable to run command :: %s", caller.c_str(), command.c_str() );
}
while (!feof(pipe)) {
if (fgets(buffer, sizeof buffer, pipe) != nullptr)
result += buffer;
}
return pclose(pipe);
}
/**
* Function that uses libgs to get pdf page sizes.
*
* @param pdf_path Path to pdf file to process.
*/
std::vector< std::pair<double,double> > gsGetPdfPageSizes( std::string pdf_path ) {
char outfile_temp[FILENAME_MAX];
mktemp( "tmp_gsGetPdfPageSizes_XXXXXXXX.txt", outfile_temp );
std::string outfile_arg = std::string("-sOutputFile=")+outfile_temp;
std::string infile_arg = std::string("-sInputFile=")+pdf_path;
int n=0, gsargc = 10;
const char * gsargv[gsargc];
gsargv[n++] = "pdf_page_sizes";
gsargv[n++] = "-dNOPAUSE";
gsargv[n++] = "-dBATCH";
gsargv[n++] = "-dQUIET";
gsargv[n++] = "-dNODISPLAY";
gsargv[n++] = "-dNOSAFER";
gsargv[n++] = outfile_arg.c_str();
gsargv[n++] = infile_arg.c_str();
gsargv[n++] = "-c";
gsargv[n++] = "/outfile OutputFile (w) file def\n\
InputFile (r) file runpdfbegin\n\
1 1 pdfpagecount {\n\
pdfgetpage\n\
outfile (Rotate=) writestring\n\
dup /Rotate pget { =string cvs outfile exch writestring } if\n\
outfile (\tMediaBox=) writestring\n\
dup /MediaBox pget { { outfile ( ) writestring =string cvs outfile exch writestring } forall } if\n\
outfile (\tCropBox=) writestring\n\
dup /CropBox pget { { outfile ( ) writestring =string cvs outfile exch writestring } forall } if\n\
outfile (\n) writestring\n\
} for\n\
outfile closefile";
int code;
#if defined (__PAGEXML_GS__)
int code1;
void *minst;
code = gsapi_new_instance(&minst, NULL);
if( code == 0 ) {
code = gsapi_set_arg_encoding(minst, GS_ARG_ENCODING_UTF8);
if( code == 0 )
code = gsapi_init_with_args(minst, gsargc, const_cast<char **>(gsargv));
code1 = gsapi_exit(minst);
if( (code == 0) || (code == gs_error_Quit) )
code = code1;
gsapi_delete_instance(minst);
}
#else
std::string command("gs");
for( int n=1; n<gsargc; n++ ) {
const char * quote = (n == gsargc-1) ? "\"" : "";
command += std::string(" ") + quote + gsargv[n] + quote;
}
code = execute_command(command+" 2>&1", std::string("gsGetPdfPageSizes"));
#endif
std::vector< std::pair<double,double> > pdf_pages;
if( code == 0 ) {
//fprintf(stderr, "outfile_temp: %s\n", outfile_temp);
//fprintf(stderr,"InputFile: %s\n",gsargv[6]);
//fprintf(stderr,"PS: %s\n",gsargv[8]);
std::regex parseLine("^Rotate=([-.0-9]*)\tMediaBox= ([-.0-9]+) ([-.0-9]+) ([-.0-9]+) ([-.0-9]+)\tCropBox=(.*)$");
std::regex parseCropBox("^ ([-.0-9]+) ([-.0-9]+) ([-.0-9]+) ([-.0-9]+)$");
std::ifstream infile(outfile_temp);
std::string line;
while( std::getline(infile, line) ) {
//fprintf(stderr, " %s\n", line.c_str());
std::cmatch base_match;
if( std::regex_match(line.c_str(), base_match, parseLine) ) {
double rot = base_match[1].str().empty() ? 0.0 : stof(base_match[1].str());
double x0 = stof(base_match[2].str());
double y0 = stof(base_match[3].str());
double x1 = stof(base_match[4].str());
double y1 = stof(base_match[5].str());
std::string cropbox = base_match[6].str();
if( ! cropbox.empty() ) {
if( std::regex_match(cropbox.c_str(), base_match, parseCropBox) ) {
x0 = stof(base_match[1].str());
y0 = stof(base_match[2].str());
x1 = stof(base_match[3].str());
y1 = stof(base_match[4].str());
}
else {
unlink(outfile_temp);
throw_runtime_error( "gsGetPdfPageSizes: error: failed to parse CropBox '%s' for pdf file: %s\n", cropbox.c_str(), pdf_path.c_str() );
}
}
if( rot != 0 && rot != 90 && rot != 180 && rot != 270 ) {
unlink(outfile_temp);
throw_runtime_error( "gsGetPdfPageSizes: error: unexpected page rotation '%g' for pdf file: %s\n", rot, pdf_path.c_str() );
}
double width = (rot == 0 || rot == 180) ? x1-x0 : y1-y0;
double height = (rot == 0 || rot == 180) ? y1-y0 : x1-x0;
pdf_pages.push_back( std::make_pair(width,height) );
//fprintf( stderr, "R=%s M=%s,%s,%s,%s C=%s\n", base_match[1].str().c_str(), base_match[2].str().c_str(), base_match[3].str().c_str(), base_match[4].str().c_str(), base_match[5].str().c_str(), base_match[6].str().c_str() );
//fprintf( stderr, "R=%g M=%g,%g,%g,%g C=%s\n", rot, x0, y0, x1, y1, cropbox.c_str() );
}
else {
unlink(outfile_temp);
throw_runtime_error( "gsGetPdfPageSizes: error: failed to parse line '%s' for pdf file: %s\n", line.c_str(), pdf_path.c_str() );
}
}
}
unlink(outfile_temp);
if( code != 0 )
throw_runtime_error( "gsGetPdfPageSizes: error: failed to get pdf page sizes for pdf file: %s", pdf_path.c_str() );
return code == 0 ? pdf_pages : std::vector< std::pair<double,double> >();
}
/**
* Function that uses libgs to render a pdf page to a png file.
*
* @param pdf_path Path to pdf file to process.
*/
void gsRenderPdfPageToPng( std::string pdf_path, int page_num, std::string png_path, int density ) {
std::string first_page_arg = std::string("-dFirstPage=")+std::to_string(page_num);
std::string last_page_arg = std::string("-dLastPage=")+std::to_string(page_num);
std::string outfile_arg = std::string("-sOutputFile=")+png_path;
std::string density_arg = std::string("-r")+std::to_string(density);
int n=0, gsargc = 13;
const char * gsargv[gsargc];
gsargv[n++] = "pdf_to_png";
gsargv[n++] = "-dNOPAUSE";
gsargv[n++] = "-dBATCH";
gsargv[n++] = "-dQUIET";
gsargv[n++] = "-dUseCropBox";
gsargv[n++] = "-sDEVICE=png16m";
gsargv[n++] = "-dTextAlphaBits=4";
gsargv[n++] = "-dGraphicsAlphaBits=4";
gsargv[n++] = first_page_arg.c_str();
gsargv[n++] = last_page_arg.c_str();
gsargv[n++] = density_arg.c_str();
gsargv[n++] = outfile_arg.c_str();
gsargv[n++] = pdf_path.c_str();
int code;
#if defined (__PAGEXML_GS__)
int code1;
void *minst;
code = gsapi_new_instance(&minst, NULL);
if( code == 0 ) {
code = gsapi_set_arg_encoding(minst, GS_ARG_ENCODING_UTF8);
if( code == 0 )
code = gsapi_init_with_args(minst, gsargc, const_cast<char **>(gsargv));
code1 = gsapi_exit(minst);
if( (code == 0) || (code == gs_error_Quit) )
code = code1;
gsapi_delete_instance(minst);
}
#else
std::string command("gs");
for( int n=1; n<gsargc; n++ ) {
command += std::string(" ") + gsargv[n];
}
code = execute_command(command+" 2>&1", std::string("gsRenderPdfPageToPng"));
#endif
if( code != 0 ) {
unlink(png_path.c_str());
throw_runtime_error( "gsRenderPdfPageToPng: error: failed to convert to png page %d of pdf file: %s", page_num, pdf_path.c_str() );
}
}
//#endif
#if defined (__PAGEXML_LEPT__) || defined (__PAGEXML_IMG_MAGICK__) || defined (__PAGEXML_IMG_CV__)
#if defined (__PAGEXML_MAGICK__)
/**
* Removes alpha channel, setting all transparent regions to the background color.
*
* @param image Image to process.
* @param color Color for the background.
* @return Whether flattening was performed.
*/
bool listFlattenImage( Magick::Image& image, const Magick::Color* color = NULL ) {
if( ! image.matte() )
return false;
image.backgroundColor( color == NULL ? colorWhite : *color );
list<Magick::Image> flattenList = { image };
Magick::Image flat;
flattenImages( &flat, flattenList.begin(), flattenList.end() );
image = flat;
return true;
}
#endif
#if defined (__PAGEXML_LEPT__) || defined (__PAGEXML_IMG_MAGICK__) || defined (__PAGEXML_IMG_CV__)
/**
* Releases an already loaded image.
*
* @param pagenum The number of the page for which to release the image (0-based).
*/
void PageXML::releaseImage( int pagenum ) {
if( pagenum < 0 || pagenum >= (int)pagesImageFilename.size() )
throw_runtime_error( "PageXML.releaseImage: invalid page number: %d", pagenum );
#if defined (__PAGEXML_LEPT__)
if ( pagesImage[pagenum] != NULL ) {
pixDestroy(&(pagesImage[pagenum]));
pagesImage[pagenum] = NULL;
}
#elif defined (__PAGEXML_IMG_MAGICK__)
pagesImage[pagenum] = Magick::Image();
#elif defined (__PAGEXML_IMG_CV__)
pagesImage[pagenum] = cv::Mat();
#endif
}
void PageXML::releaseImage( xmlNodePt node ) {
return releaseImage( getPageNumber(node) );
}
void PageXML::releaseImages() {
for( int n=(int)pagesImageFilename.size()-1; n>=0; n-- )
releaseImage( n );
}
#if defined (__PAGEXML_LEPT__) && defined (__PAGEXML_MAGICK__)
/**
* Loads an image for a Page in the XML.
*
* @param pagenum The number of the page for which to load the image (0-based).
* @param fname File name of the image to read, overriding the one in the XML.
* @param resize_coords If image size differs, resize page XML coordinates.
* @param density Load the image at the given density, resizing the page coordinates if required.
*/
void PageXML::loadImage( int pagenum, const char* fname, const bool resize_coords, const int density ) {
#else
/**
* Loads an image for a Page in the XML.
*
* @param pagenum The number of the page for which to load the image (0-based).
* @param fname File name of the image to read, overriding the one in the XML.
* @param resize_coords If image size differs, resize page XML coordinates.
* @param density Load the image at the given density, resizing the page coordinates if required.
*/
void PageXML::loadImage( int pagenum, const char* fname, const bool resize_coords, const int density __attribute__((unused)) ) {
#endif
if( pagenum < 0 || pagenum >= (int)pagesImageFilename.size() )
throw_runtime_error( "PageXML.loadImage: invalid page number: %d", pagenum );
string aux;
string aux2;
string fbase;
if( fname == NULL ) {
aux = pagesImageFilename[pagenum].at(0) == '/' ? pagesImageFilename[pagenum] : (imgDir+'/'+pagesImageFilename[pagenum]);
fname = aux.c_str();
}
// Get image number for multipage files //
int imgnum = 0;
fbase = string(fname);
cmatch base_match;
if( std::regex_match(fname,base_match,reImagePageNum) ) {
imgnum = stoi(base_match[2].str());
aux2 = std::string(base_match[1].str().c_str()) + "[" + std::to_string(imgnum) + "]";
fname = aux2.c_str();
fbase = std::string(base_match[1].str().c_str());
}
int ldensity = density;
bool lresize_coords = resize_coords;
if( default_density ) {
ldensity = default_density;
lresize_coords = true;
}
releaseImage(pagenum);
try {
#if defined (__PAGEXML_LEPT__)
// Leptonica load pdf page //
#if defined (__PAGEXML_GS__)
if( std::regex_match(fname, reIsPdf) ) {
if( ! ldensity ) {
if( lresize_coords )
throw_runtime_error( "PageXML.loadImage: density is required when reading pdf with resize_coords option" );
std::vector< std::pair<double,double> > page_sizes = gsGetPdfPageSizes( std::string(fname) );
double Dw = 72.0*getPageWidth(pagenum)/page_sizes[pagenum].first;
double Dh = 72.0*getPageHeight(pagenum)/page_sizes[pagenum].second;
ldensity = std::round(0.5*(Dw+Dh));
}
char tmpfname[FILENAME_MAX];
std::string tmpbase = std::string("tmp_PageXML_pdf_")+std::to_string(pagenum)+"_XXXXXXXX.png";
mktemp( tmpbase.c_str(), tmpfname );
gsRenderPdfPageToPng( fbase, imgnum+1, std::string(tmpfname), ldensity );
pagesImage[pagenum] = pixRead(tmpfname);
unlink(tmpfname);
}
#elif defined (__PAGEXML_MAGICK__)
if( std::regex_match(fname, reIsPdf) ) {
if( ! ldensity ) {
if( lresize_coords )
throw_runtime_error( "PageXML.loadImage: density is required when reading pdf with resize_coords option" );
Magick::Image ptmp;
ptmp.ping(fname);
double Dw = 72.0*getPageWidth(pagenum)/ptmp.columns();
double Dh = 72.0*getPageHeight(pagenum)/ptmp.rows();
ldensity = std::round(0.5*(Dw+Dh));
}
Magick::Image tmp;
tmp.density(std::to_string(ldensity).c_str());
tmp.read(fname);
listFlattenImage(tmp);
char tmpfname[FILENAME_MAX];
std::string tmpbase = std::string("tmp_PageXML_pdf_")+std::to_string(pagenum)+"_XXXXXXXX.png";
mktemp( tmpbase.c_str(), tmpfname );
tmp.resolutionUnits(MagickCore::ResolutionType::PixelsPerInchResolution);
tmp.write( (std::string("png24:")+tmpfname).c_str() );
pagesImage[pagenum] = pixRead(tmpfname);
unlink(tmpfname);
}
#endif
if( pagesImage[pagenum] == NULL ) {
// Leptonica load tiff page //
if( std::regex_match(fname, reIsTiff) ) {
PIXA* tiffimage = pixaReadMultipageTiff( fbase.c_str() );
if( tiffimage == NULL || tiffimage->n == 0 )
throw_runtime_error( "PageXML.loadImage: problems reading tiff image: %s", fbase.c_str() );
if( imgnum >= tiffimage->n )
throw_runtime_error( "PageXML.loadImage: requested page %d but tiff image only has %d pages: %s", imgnum+1, tiffimage->n, fbase.c_str() );
pagesImage[pagenum] = pixClone(tiffimage->pix[imgnum]);
pixaDestroy(&tiffimage);
}
// Leptonica load other image formats //
else
pagesImage[pagenum] = pixRead(fname);
}
if( pagesImage[pagenum] == NULL ) {
throw_runtime_error( "PageXML.loadImage: problems reading image: %s", fname );
return;
}
#elif defined (__PAGEXML_IMG_MAGICK__)
// ImageMagick load image //
try {
if( ldensity )
pagesImage[pagenum].density(std::to_string(ldensity).c_str());
pagesImage[pagenum].read(fname);
if( std::regex_match(fname, reIsPdf) )
listFlattenImage( pagesImage[pagenum] );
pagesImage[pagenum].page( Magick::Geometry(0,0,0,0) );
}
catch( exception& e ) {
throw_runtime_error( "PageXML.loadImage: problems reading image: %s", e.what() );
return;
}
#elif defined (__PAGEXML_IMG_CV__)
// OpenCV load pdf page //
#if defined (__PAGEXML_GS__)
if( std::regex_match(fname, reIsPdf) ) {
if( ! ldensity ) {
if( lresize_coords )
throw_runtime_error( "PageXML.loadImage: density is required when reading pdf with resize_coords option" );
std::vector< std::pair<double,double> > page_sizes = gsGetPdfPageSizes( fbase );
double Dw = 72.0*getPageWidth(pagenum)/page_sizes[pagenum].first;
double Dh = 72.0*getPageHeight(pagenum)/page_sizes[pagenum].second;
ldensity = std::round(0.5*(Dw+Dh));
}
char tmpfname[FILENAME_MAX];
std::string tmpbase = std::string("tmp_PageXML_pdf_")+std::to_string(pagenum)+"_XXXXXXXX.png";