-
Notifications
You must be signed in to change notification settings - Fork 431
/
HeaderParser.java
executable file
·1669 lines (1517 loc) · 75.7 KB
/
HeaderParser.java
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
package org.grobid.core.engines;
import com.google.common.base.Splitter;
import org.apache.commons.lang3.tuple.ImmutablePair;
import org.apache.commons.lang3.tuple.Pair;
import org.grobid.core.GrobidModels;
import org.grobid.core.data.BiblioItem;
import org.grobid.core.data.Date;
import org.grobid.core.data.Keyword;
import org.grobid.core.data.Person;
import org.grobid.core.document.Document;
import org.grobid.core.document.DocumentPiece;
import org.grobid.core.document.DocumentPointer;
import org.grobid.core.document.DocumentSource;
import org.grobid.core.document.TEIFormatter;
import org.grobid.core.engines.config.GrobidAnalysisConfig;
import org.grobid.core.engines.label.SegmentationLabels;
import org.grobid.core.engines.label.TaggingLabels;
import org.grobid.core.exceptions.GrobidException;
import org.grobid.core.exceptions.GrobidExceptionStatus;
import org.grobid.core.features.FeatureFactory;
import org.grobid.core.features.FeaturesVectorHeader;
import org.grobid.core.lang.Language;
import org.grobid.core.layout.Block;
import org.grobid.core.layout.LayoutToken;
import org.grobid.core.utilities.Consolidation;
import org.grobid.core.utilities.GrobidProperties;
import org.grobid.core.utilities.LanguageUtilities;
import org.grobid.core.utilities.LayoutTokensUtil;
import org.grobid.core.utilities.TextUtilities;
import org.grobid.core.utilities.counters.CntManager;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.OutputStreamWriter;
import java.io.Writer;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
import java.util.SortedSet;
import java.util.StringTokenizer;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
/**
* @author Patrice Lopez
*/
public class HeaderParser extends AbstractParser {
private static final Logger LOGGER = LoggerFactory.getLogger(HeaderParser.class);
private LanguageUtilities languageUtilities = LanguageUtilities.getInstance();
private EngineParsers parsers;
public HeaderParser(EngineParsers parsers, CntManager cntManager) {
super(GrobidModels.HEADER, cntManager);
this.parsers = parsers;
GrobidProperties.getInstance();
}
public HeaderParser(EngineParsers parsers) {
super(GrobidModels.HEADER);
this.parsers = parsers;
GrobidProperties.getInstance();
}
/**
* Processing with application of the segmentation model
*/
public Pair<String, Document> processing(File input, BiblioItem resHeader, GrobidAnalysisConfig config) {
DocumentSource documentSource = null;
try {
documentSource = DocumentSource.fromPdf(input, config.getStartPage(), config.getEndPage());
Document doc = parsers.getSegmentationParser().processing(documentSource, config);
String tei = processingHeaderSection(config.isConsolidateHeader(), doc, resHeader);
return new ImmutablePair<String, Document>(tei, doc);
} finally {
if (documentSource != null) {
documentSource.close(true, true, true);
}
}
}
/**
* Processing without application of the segmentation model, regex are used to identify the header
* zone.
*/
public Pair<String, Document> processing2(String pdfInput, BiblioItem resHeader, GrobidAnalysisConfig config) {
DocumentSource documentSource = null;
try {
documentSource = DocumentSource.fromPdf(new File(pdfInput), config.getStartPage(), config.getEndPage());
Document doc = new Document(documentSource);
doc.addTokenizedDocument(config);
if (doc.getBlocks() == null) {
throw new GrobidException("PDF parsing resulted in empty content");
}
String tei = processingHeaderBlock(config.isConsolidateHeader(), doc, resHeader);
return Pair.of(tei, doc);
} catch (Exception e) {
throw new GrobidException(e, GrobidExceptionStatus.GENERAL);
} finally {
if (documentSource != null) {
documentSource.close(true, true, true);
}
}
}
/**
* Header processing after identification of the header blocks with heuristics (old approach)
*/
public String processingHeaderBlock(boolean consolidate, Document doc, BiblioItem resHeader) throws Exception {
String header;
//if (doc.getBlockDocumentHeaders() == null) {
header = doc.getHeaderFeatured(true, true);
/*} else {
header = doc.getHeaderFeatured(false, true);
}*/
List<LayoutToken> tokenizations = doc.getTokenizationsHeader();
//System.out.println(tokenizations.toString());
if ((header != null) && (header.trim().length() > 0)) {
String res = label(header);
resHeader = resultExtraction(res, true, tokenizations, resHeader);
// language identification
String contentSample = "";
if (resHeader.getTitle() != null)
contentSample += resHeader.getTitle();
if (resHeader.getAbstract() != null)
contentSample += "\n" + resHeader.getAbstract();
if (resHeader.getKeywords() != null)
contentSample += "\n" + resHeader.getKeywords();
if (contentSample.length() < 200) {
// we need more textual content to ensure that the language identification will be
// correct
contentSample += doc.getBody();
}
Language langu = languageUtilities.runLanguageId(contentSample);
if (langu != null) {
String lang = langu.getLang();
doc.setLanguage(lang);
resHeader.setLanguage(lang);
}
if (resHeader != null) {
if (resHeader.getAbstract() != null) {
resHeader.setAbstract(TextUtilities.dehyphenizeHard(resHeader.getAbstract()));
//resHeader.setAbstract(TextUtilities.dehyphenize(resHeader.getAbstract()));
}
BiblioItem.cleanTitles(resHeader);
if (resHeader.getTitle() != null) {
// String temp =
// utilities.dehyphenizeHard(resHeader.getTitle());
String temp = TextUtilities.dehyphenize(resHeader.getTitle());
temp = temp.trim();
if (temp.length() > 1) {
if (temp.startsWith("1"))
temp = temp.substring(1, temp.length());
temp = temp.trim();
}
resHeader.setTitle(temp);
}
if (resHeader.getBookTitle() != null) {
resHeader.setBookTitle(TextUtilities.dehyphenize(resHeader.getBookTitle()));
}
resHeader.setOriginalAuthors(resHeader.getAuthors());
boolean fragmentedAuthors = false;
boolean hasMarker = false;
List<Integer> authorsBlocks = new ArrayList<Integer>();
String[] authorSegments;
if (resHeader.getAuthors() != null) {
ArrayList<String> auts;
authorSegments = resHeader.getAuthors().split("\n");
List<List<LayoutToken>> tokenAuthorSegments = LayoutTokensUtil.split(resHeader.getAuthorsTokens(), Pattern.compile("\n"), false);
if (authorSegments.length > 1) {
fragmentedAuthors = true;
}
for (int k = 0; k < authorSegments.length; k++) {
auts = new ArrayList<String>();
auts.add(authorSegments[k]);
// List<Person> localAuthors = parsers.getAuthorParser().processingHeader(auts);
List<Person> localAuthors = parsers.getAuthorParser().processingHeaderWithLayoutTokens(tokenAuthorSegments.get(k));
if (localAuthors != null) {
for (Person pers : localAuthors) {
resHeader.addFullAuthor(pers);
if (pers.getMarkers() != null) {
hasMarker = true;
}
authorsBlocks.add(k);
}
}
}
resHeader.setFullAffiliations(
parsers.getAffiliationAddressParser().processReflow(res, tokenizations));
resHeader.attachEmails();
boolean attached = false;
if (fragmentedAuthors && !hasMarker) {
if (resHeader.getFullAffiliations() != null) {
if (authorSegments != null) {
if (resHeader.getFullAffiliations().size() == authorSegments.length) {
int k = 0;
List<Person> persons = resHeader.getFullAuthors();
if (persons != null) {
for (Person pers : persons) {
if (k < authorsBlocks.size()) {
int indd = authorsBlocks.get(k);
if (indd < resHeader.getFullAffiliations().size()) {
pers.addAffiliation(resHeader.getFullAffiliations().get(indd));
}
}
k++;
}
}
attached = true;
resHeader.setFullAffiliations(null);
resHeader.setAffiliation(null);
}
}
}
}
if (!attached) {
resHeader.attachAffiliations();
}
if (resHeader.getEditors() != null) {
// ArrayList<String> edits = new ArrayList<String>();
// edits.add(resHeader.getEditors());
resHeader.setFullEditors(parsers.getAuthorParser().processingHeader(resHeader.getEditors()));
// resHeader.setFullEditors(authorParser.processingCitation(edits));
}
if (resHeader.getReference() != null) {
BiblioItem refer = parsers.getCitationParser().processing(resHeader.getReference(), false);
if (refer != null)
BiblioItem.correct(resHeader, refer);
}
}
// keyword post-processing
if (resHeader.getKeyword() != null) {
String keywords = TextUtilities.dehyphenize(resHeader.getKeyword());
keywords = BiblioItem.cleanKeywords(keywords);
resHeader.setKeyword(keywords.replace("\n", " ").replace(" ", " "));
List<Keyword> keywordsSegmented = BiblioItem.segmentKeywords(keywords);
if ((keywordsSegmented != null) && (keywordsSegmented.size() > 0))
resHeader.setKeywords(keywordsSegmented);
}
// DOI pass
List<String> dois = doc.getDOIMatches();
if (dois != null) {
if ((dois.size() == 1) && (resHeader != null)) {
resHeader.setDOI(dois.get(0));
}
}
if (consolidate || (resHeader.getDOI() != null)) {
resHeader = consolidateHeader(resHeader);
}
// normalization of dates
if (resHeader != null) {
if (resHeader.getPublicationDate() != null) {
List<Date> dates = parsers.getDateParser().processing(resHeader.getPublicationDate());
// most basic heuristic, we take the first date - to be
// revised...
if (dates != null) {
if (dates.size() > 0) {
resHeader.setNormalizedPublicationDate(dates.get(0));
}
}
}
if (resHeader.getSubmissionDate() != null) {
List<Date> dates = parsers.getDateParser().processing(resHeader.getSubmissionDate());
if (dates != null) {
if (dates.size() > 0) {
resHeader.setNormalizedSubmissionDate(dates.get(0));
}
}
}
}
}
} else {
LOGGER.debug("WARNING: header is empty.");
}
doc.setResHeader(resHeader);
TEIFormatter teiFormatter = new TEIFormatter(doc);
StringBuilder tei = teiFormatter.toTEIHeader(resHeader, null, GrobidAnalysisConfig.builder().consolidateHeader(consolidate).build());
tei.append("\t</text>\n");
tei.append("</TEI>\n");
//LOGGER.debug(tei.toString());
return tei.toString();
}
/**
* Header processing after application of the segmentation model (new approach)
*/
public String processingHeaderSection(boolean consolidate, Document doc, BiblioItem resHeader) {
try {
SortedSet<DocumentPiece> documentHeaderParts = doc.getDocumentPart(SegmentationLabels.HEADER);
List<LayoutToken> tokenizations = doc.getTokenizations();
if (documentHeaderParts != null) {
List<LayoutToken> tokenizationsHeader = new ArrayList<LayoutToken>();
for (DocumentPiece docPiece : documentHeaderParts) {
DocumentPointer dp1 = docPiece.a;
DocumentPointer dp2 = docPiece.b;
int tokens = dp1.getTokenDocPos();
int tokene = dp2.getTokenDocPos();
for (int i = tokens; i < tokene; i++) {
tokenizationsHeader.add(tokenizations.get(i));
}
}
String header = getSectionHeaderFeatured(doc, documentHeaderParts, true);
String res = null;
if ((header != null) && (header.trim().length() > 0)) {
res = label(header);
resHeader = resultExtraction(res, true, tokenizations, resHeader);
}
// language identification
String contentSample = "";
if (resHeader.getTitle() != null)
contentSample += resHeader.getTitle();
if (resHeader.getAbstract() != null)
contentSample += "\n" + resHeader.getAbstract();
if (contentSample.length() < 200) {
// we need more textual content to ensure that the language identification will be
// correct
SortedSet<DocumentPiece> documentBodyParts = doc.getDocumentPart(SegmentationLabels.BODY);
StringBuilder contentBuffer = new StringBuilder();
for (DocumentPiece docPiece : documentBodyParts) {
DocumentPointer dp1 = docPiece.a;
DocumentPointer dp2 = docPiece.b;
int tokens = dp1.getTokenDocPos();
int tokene = dp2.getTokenDocPos();
for (int i = tokens; i < tokene; i++) {
contentBuffer.append(tokenizations.get(i));
contentBuffer.append(" ");
}
}
contentSample += " " + contentBuffer.toString();
}
Language langu = languageUtilities.runLanguageId(contentSample);
if (langu != null) {
String lang = langu.getLang();
doc.setLanguage(lang);
resHeader.setLanguage(lang);
}
if (resHeader != null) {
if (resHeader.getAbstract() != null) {
resHeader.setAbstract(TextUtilities.dehyphenizeHard(resHeader.getAbstract()));
//resHeader.setAbstract(TextUtilities.dehyphenize(resHeader.getAbstract()));
}
BiblioItem.cleanTitles(resHeader);
if (resHeader.getTitle() != null) {
// String temp =
// utilities.dehyphenizeHard(resHeader.getTitle());
String temp = TextUtilities.dehyphenize(resHeader.getTitle());
temp = temp.trim();
if (temp.length() > 1) {
if (temp.startsWith("1"))
temp = temp.substring(1, temp.length());
temp = temp.trim();
}
resHeader.setTitle(temp);
}
if (resHeader.getBookTitle() != null) {
resHeader.setBookTitle(TextUtilities.dehyphenize(resHeader.getBookTitle()));
}
resHeader.setOriginalAuthors(resHeader.getAuthors());
boolean fragmentedAuthors = false;
boolean hasMarker = false;
List<Integer> authorsBlocks = new ArrayList<Integer>();
String[] authorSegments = null;
if (resHeader.getAuthors() != null) {
// List<String> auts;
authorSegments = resHeader.getAuthors().split("\n");
if (authorSegments.length > 1) {
fragmentedAuthors = true;
}
for (int k = 0; k < authorSegments.length; k++) {
// auts = new ArrayList<String>();
// auts.add(authorSegments[k]);
// List<Person> localAuthors = parsers.getAuthorParser().processingHeader(auts);
List<Person> localAuthors = parsers.getAuthorParser().processingHeader(authorSegments[k]);
if (localAuthors != null) {
for (Person pers : localAuthors) {
resHeader.addFullAuthor(pers);
if (pers.getMarkers() != null) {
hasMarker = true;
}
authorsBlocks.add(k);
}
}
}
}
resHeader.setFullAffiliations(
parsers.getAffiliationAddressParser().processReflow(res, tokenizations));
resHeader.attachEmails();
boolean attached = false;
if (fragmentedAuthors && !hasMarker) {
if (resHeader.getFullAffiliations() != null) {
if (authorSegments != null) {
if (resHeader.getFullAffiliations().size() == authorSegments.length) {
int k = 0;
List<Person> persons = resHeader.getFullAuthors();
for (Person pers : persons) {
if (k < authorsBlocks.size()) {
int indd = authorsBlocks.get(k);
if (indd < resHeader.getFullAffiliations().size()) {
pers.addAffiliation(resHeader.getFullAffiliations().get(indd));
}
}
k++;
}
attached = true;
resHeader.setFullAffiliations(null);
resHeader.setAffiliation(null);
}
}
}
}
if (!attached) {
resHeader.attachAffiliations();
}
if (resHeader.getEditors() != null) {
// List<String> edits = new ArrayList<String>();
// edits.add(resHeader.getEditors());
resHeader.setFullEditors(parsers.getAuthorParser().processingHeader(resHeader.getEditors()));
// resHeader.setFullEditors(parsers.getAuthorParser().processingHeader(edits));
// resHeader.setFullEditors(authorParser.processingCitation(edits));
}
if (resHeader.getReference() != null) {
BiblioItem refer = parsers.getCitationParser().processing(resHeader.getReference(), false);
BiblioItem.correct(resHeader, refer);
}
}
// keyword post-processing
if (resHeader.getKeyword() != null) {
String keywords = TextUtilities.dehyphenize(resHeader.getKeyword());
keywords = BiblioItem.cleanKeywords(keywords);
resHeader.setKeyword(keywords.replace("\n", " ").replace(" ", " "));
List<Keyword> keywordsSegmented = BiblioItem.segmentKeywords(keywords);
if ((keywordsSegmented != null) && (keywordsSegmented.size() > 0))
resHeader.setKeywords(keywordsSegmented);
}
// DOI pass
List<String> dois = doc.getDOIMatches();
if (dois != null) {
if ((dois.size() == 1) && (resHeader != null)) {
resHeader.setDOI(dois.get(0));
}
}
if (consolidate || (resHeader.getDOI() != null)) {
resHeader = consolidateHeader(resHeader);
}
// normalization of dates
if (resHeader != null) {
if (resHeader.getPublicationDate() != null) {
List<Date> dates = parsers.getDateParser().processing(resHeader.getPublicationDate());
// most basic heuristic, we take the first date - to be
// revised...
if (dates != null) {
if (dates.size() > 0) {
resHeader.setNormalizedPublicationDate(dates.get(0));
}
}
}
if (resHeader.getSubmissionDate() != null) {
List<Date> dates = parsers.getDateParser().processing(resHeader.getSubmissionDate());
if (dates != null) {
if (dates.size() > 0) {
resHeader.setNormalizedSubmissionDate(dates.get(0));
}
}
}
}
TEIFormatter teiFormatter = new TEIFormatter(doc);
StringBuilder tei = teiFormatter.toTEIHeader(resHeader, null, GrobidAnalysisConfig.defaultInstance());
tei.append("\t</text>\n");
tei.append("</TEI>\n");
return tei.toString();
}
} catch (Exception e) {
throw new GrobidException("An exception occurred while running Grobid.", e);
}
return null;
}
/**
* Return the header section with features to be processed by the CRF model
*/
public String getSectionHeaderFeatured(Document doc,
SortedSet<DocumentPiece> documentHeaderParts,
boolean withRotation) {
FeatureFactory featureFactory = FeatureFactory.getInstance();
StringBuilder header = new StringBuilder();
String currentFont = null;
int currentFontSize = -1;
// vector for features
FeaturesVectorHeader features;
boolean endblock;
//for (Integer blocknum : blockDocumentHeaders) {
List<Block> blocks = doc.getBlocks();
if ((blocks == null) || blocks.size() == 0) {
return null;
}
for (DocumentPiece docPiece : documentHeaderParts) {
DocumentPointer dp1 = docPiece.a;
DocumentPointer dp2 = docPiece.b;
for (int blockIndex = dp1.getBlockPtr(); blockIndex <= dp2.getBlockPtr(); blockIndex++) {
Block block = blocks.get(blockIndex);
boolean newline;
boolean previousNewline = false;
endblock = false;
List<LayoutToken> tokens = block.getTokens();
if (tokens == null)
continue;
int n = 0;
if (blockIndex == dp1.getBlockPtr()) {
//n = block.getStartToken();
n = dp1.getTokenDocPos() - block.getStartToken();
}
while (n < tokens.size()) {
if (blockIndex == dp2.getBlockPtr()) {
if (n > dp2.getTokenDocPos() - block.getStartToken()) {
break;
}
}
LayoutToken token = tokens.get(n);
features = new FeaturesVectorHeader();
features.token = token;
String text = token.getText();
if (text == null) {
n++;
continue;
}
//text = text.trim();
//text = text.replace(" ", "").replace("\t", "").replace("\u00A0", "");
text = text.replace(" ", "");
if (text.length() == 0) {
n++;
continue;
}
//if (text.equals("\n") || text.equals("\r")) {
if (text.equals("\n")) {
newline = true;
previousNewline = true;
n++;
continue;
} else
newline = false;
if (previousNewline) {
newline = true;
previousNewline = false;
}
// final sanitisation and filtering
text = text.replaceAll("[ \n]", "");
if (TextUtilities.filterLine(text)) {
n++;
continue;
}
features.string = text;
if (newline)
features.lineStatus = "LINESTART";
Matcher m0 = featureFactory.isPunct.matcher(text);
if (m0.find()) {
features.punctType = "PUNCT";
}
if (text.equals("(") || text.equals("[")) {
features.punctType = "OPENBRACKET";
} else if (text.equals(")") || text.equals("]")) {
features.punctType = "ENDBRACKET";
} else if (text.equals(".")) {
features.punctType = "DOT";
} else if (text.equals(",")) {
features.punctType = "COMMA";
} else if (text.equals("-")) {
features.punctType = "HYPHEN";
} else if (text.equals("\"") || text.equals("\'") || text.equals("`")) {
features.punctType = "QUOTE";
}
if (n == 0) {
// beginning of block
features.lineStatus = "LINESTART";
features.blockStatus = "BLOCKSTART";
} else if (n == tokens.size() - 1) {
// end of block
features.lineStatus = "LINEEND";
previousNewline = true;
features.blockStatus = "BLOCKEND";
endblock = true;
} else {
// look ahead to see if we are at the end of a line within the block
boolean endline = false;
int ii = 1;
boolean endloop = false;
while ((n + ii < tokens.size()) && (!endloop)) {
LayoutToken tok = tokens.get(n + ii);
if (tok != null) {
String toto = tok.getText();
if (toto != null) {
if (toto.equals("\n") || text.equals("\r")) {
endline = true;
endloop = true;
} else {
if ((toto.trim().length() != 0)
&& (!text.equals("\u00A0"))
&& (!(toto.contains("@IMAGE")))
&& (!(toto.contains("@PAGE")))
&& (!text.contains(".pbm"))
&& (!text.contains(".ppm"))
&& (!text.contains(".png"))
&& (!text.contains(".vec"))
&& (!text.contains(".jpg"))) {
endloop = true;
}
}
}
}
if (n + ii == tokens.size() - 1) {
endblock = true;
endline = true;
}
ii++;
}
if ((!endline) && !(newline)) {
features.lineStatus = "LINEIN";
} else if (!newline) {
features.lineStatus = "LINEEND";
previousNewline = true;
}
if ((!endblock) && (features.blockStatus == null))
features.blockStatus = "BLOCKIN";
else if (features.blockStatus == null)
features.blockStatus = "BLOCKEND";
}
if (text.length() == 1) {
features.singleChar = true;
}
if (Character.isUpperCase(text.charAt(0))) {
features.capitalisation = "INITCAP";
}
if (featureFactory.test_all_capital(text)) {
features.capitalisation = "ALLCAP";
}
if (featureFactory.test_digit(text)) {
features.digit = "CONTAINSDIGITS";
}
if (featureFactory.test_common(text)) {
features.commonName = true;
}
if (featureFactory.test_names(text)) {
features.properName = true;
}
if (featureFactory.test_month(text)) {
features.month = true;
}
if (text.contains("-")) {
features.containDash = true;
}
Matcher m = featureFactory.isDigit.matcher(text);
if (m.find()) {
features.digit = "ALLDIGIT";
}
Matcher m2 = featureFactory.year.matcher(text);
if (m2.find()) {
features.year = true;
}
Matcher m3 = featureFactory.email.matcher(text);
if (m3.find()) {
features.email = true;
}
Matcher m4 = featureFactory.http.matcher(text);
if (m4.find()) {
features.http = true;
}
if (currentFont == null) {
currentFont = token.getFont();
features.fontStatus = "NEWFONT";
} else if (!currentFont.equals(token.getFont())) {
currentFont = token.getFont();
features.fontStatus = "NEWFONT";
} else
features.fontStatus = "SAMEFONT";
int newFontSize = (int) token.getFontSize();
if (currentFontSize == -1) {
currentFontSize = newFontSize;
features.fontSize = "HIGHERFONT";
} else if (currentFontSize == newFontSize) {
features.fontSize = "SAMEFONTSIZE";
} else if (currentFontSize < newFontSize) {
features.fontSize = "HIGHERFONT";
currentFontSize = newFontSize;
} else if (currentFontSize > newFontSize) {
features.fontSize = "LOWERFONT";
currentFontSize = newFontSize;
}
if (token.getBold())
features.bold = true;
if (token.getItalic())
features.italic = true;
if (token.getRotation())
features.rotation = true;
// CENTERED
// LEFTAJUSTED
if (features.capitalisation == null)
features.capitalisation = "NOCAPS";
if (features.digit == null)
features.digit = "NODIGIT";
if (features.punctType == null)
features.punctType = "NOPUNCT";
header.append(features.printVector(withRotation));
n++;
}
}
}
return header.toString();
}
/**
* Process the header of the specified pdf and format the result as training
* data.
*
* @param inputFile path to input file
* @param pathHeader path to header
* @param pathTEI path to TEI
*/
public Document createTrainingHeader(String inputFile, String pathHeader, String pathTEI) {
DocumentSource documentSource = null;
try {
File file = new File(inputFile);
String pdfFileName = file.getName();
//Document doc = parsers.getSegmentationParser().processing(file, GrobidAnalysisConfig.defaultInstance());
documentSource = DocumentSource.fromPdf(file);
Document doc = parsers.getSegmentationParser().processing(documentSource, GrobidAnalysisConfig.defaultInstance());
//documentSource = DocumentSource.fromPdf(file);
//Document doc = new Document(documentSource);
//doc.addTokenizedDocument();
/*if (doc.getBlocks() == null) {
throw new GrobidException("PDF parsing resulted in empty content");
}*/
SortedSet<DocumentPiece> documentHeaderParts = doc.getDocumentPart(SegmentationLabels.HEADER);
List<LayoutToken> tokenizationsFull = doc.getTokenizations();
if (documentHeaderParts != null) {
List<LayoutToken> tokenizations = new ArrayList<LayoutToken>();
for (DocumentPiece docPiece : documentHeaderParts) {
DocumentPointer dp1 = docPiece.a;
DocumentPointer dp2 = docPiece.b;
int tokens = dp1.getTokenDocPos();
int tokene = dp2.getTokenDocPos();
for (int i = tokens; i < tokene; i++) {
tokenizations.add(tokenizationsFull.get(i));
}
}
String header = getSectionHeaderFeatured(doc, documentHeaderParts, true);
String rese = null;
if ((header != null) && (header.trim().length() > 0)) {
rese = label(header);
//String header = doc.getHeaderFeatured(true, true);
//List<LayoutToken> tokenizations = doc.getTokenizationsHeader();
// we write the header untagged
String outPathHeader = pathHeader + File.separator + pdfFileName.replace(".pdf", ".header");
Writer writer = new OutputStreamWriter(new FileOutputStream(new File(outPathHeader), false), "UTF-8");
writer.write(header + "\n");
writer.close();
// buffer for the header block
StringBuilder bufferHeader = trainingExtraction(rese, true, tokenizations);
Language lang = languageUtilities.runLanguageId(bufferHeader.toString());
if (lang != null) {
doc.setLanguage(lang.getLang());
}
// buffer for the affiliation+address block
StringBuilder bufferAffiliation =
parsers.getAffiliationAddressParser().trainingExtraction(rese, tokenizations);
// buffer for the date block
StringBuilder bufferDate = null;
// we need to rebuild the found date string as it appears
String input = "";
int q = 0;
StringTokenizer st = new StringTokenizer(rese, "\n");
while (st.hasMoreTokens() && (q < tokenizations.size())) {
String line = st.nextToken();
String theTotalTok = tokenizations.get(q).getText();
String theTok = tokenizations.get(q).getText();
while (theTok.equals(" ") || theTok.equals("\t") || theTok.equals("\n") || theTok.equals("\r")) {
q++;
if ((q > 0) && (q < tokenizations.size())) {
theTok = tokenizations.get(q).getText();
theTotalTok += theTok;
}
}
if (line.endsWith("<date>")) {
input += theTotalTok;
}
q++;
}
if (input.trim().length() > 1) {
List<String> inputs = new ArrayList<String>();
inputs.add(input.trim());
bufferDate = parsers.getDateParser().trainingExtraction(inputs);
}
// buffer for the name block
StringBuilder bufferName = null;
// we need to rebuild the found author string as it appears
input = "";
q = 0;
st = new StringTokenizer(rese, "\n");
while (st.hasMoreTokens() && (q < tokenizations.size())) {
String line = st.nextToken();
String theTotalTok = tokenizations.get(q).getText();
String theTok = tokenizations.get(q).getText();
while (theTok.equals(" ") || theTok.equals("\t") || theTok.equals("\n") || theTok.equals("\r")) {
q++;
if ((q > 0) && (q < tokenizations.size())) {
theTok = tokenizations.get(q).getText();
theTotalTok += theTok;
}
}
if (line.endsWith("<author>")) {
input += theTotalTok;
}
q++;
}
if (input.length() > 1) {
//List<String> inputs = new ArrayList<String>();
//inputs.add(input.trim());
bufferName = parsers.getAuthorParser().trainingExtraction(input.trim(), true);
}
// buffer for the reference block
StringBuilder bufferReference = null;
// we need to rebuild the found citation string as it appears
input = "";
q = 0;
st = new StringTokenizer(rese, "\n");
while (st.hasMoreTokens() && (q < tokenizations.size())) {
String line = st.nextToken();
String theTotalTok = tokenizations.get(q).getText();
String theTok = tokenizations.get(q).getText();
while (theTok.equals(" ") || theTok.equals("\t") || theTok.equals("\n") || theTok.equals("\r")) {
q++;
if ((q > 0) && (q < tokenizations.size())) {
theTok = tokenizations.get(q).getText();
theTotalTok += theTok;
}
}
if (line.endsWith("<reference>")) {
input += theTotalTok;
}
q++;
}
if (input.length() > 1) {
List<String> inputs = new ArrayList<String>();
inputs.add(input.trim());
bufferReference = parsers.getCitationParser().trainingExtraction(inputs);
}
// write the TEI file to reflect the extract layout of the text as
// extracted from the pdf
writer = new OutputStreamWriter(new FileOutputStream(new File(pathTEI + File.separator
+ pdfFileName.replace(".pdf", GrobidProperties.FILE_ENDING_TEI_HEADER)), false), "UTF-8");
writer.write("<?xml version=\"1.0\" ?>\n<tei>\n\t<teiHeader>\n\t\t<fileDesc xml:id=\""
+ pdfFileName.replace(".pdf", "")
+ "\"/>\n\t</teiHeader>\n\t<text");
if (lang != null) {
// TODO: why English (Slava)
writer.write(" xml:lang=\"en\"");
}
writer.write(">\n\t\t<front>\n");
writer.write(bufferHeader.toString());
writer.write("\n\t\t</front>\n\t</text>\n</tei>\n");
writer.close();
if (bufferAffiliation != null) {
if (bufferAffiliation.length() > 0) {
Writer writerAffiliation = new OutputStreamWriter(new FileOutputStream(new File(pathTEI +
File.separator
+ pdfFileName.replace(".pdf", ".affiliation.tei.xml")), false), "UTF-8");
writerAffiliation.write("<?xml version=\"1.0\" encoding=\"UTF-8\"?>");
writerAffiliation.write("\n<tei xmlns=\"http://www.tei-c.org/ns/1.0\""
+ " xmlns:xlink=\"http://www.w3.org/1999/xlink\" " + "xmlns:mml=\"http://www.w3.org/1998/Math/MathML\">");
writerAffiliation.write("\n\t<teiHeader>\n\t\t<fileDesc>\n\t\t\t<sourceDesc>");
writerAffiliation.write("\n\t\t\t\t<biblStruct>\n\t\t\t\t\t<analytic>\n\t\t\t\t\t\t<author>\n\n");
writerAffiliation.write(bufferAffiliation.toString());
writerAffiliation.write("\n\t\t\t\t\t\t</author>\n\t\t\t\t\t</analytic>");
writerAffiliation.write("\n\t\t\t\t</biblStruct>\n\t\t\t</sourceDesc>\n\t\t</fileDesc>");
writerAffiliation.write("\n\t</teiHeader>\n</tei>\n");
writerAffiliation.close();
}
}
if (bufferDate != null) {
if (bufferDate.length() > 0) {
Writer writerDate = new OutputStreamWriter(new FileOutputStream(new File(pathTEI +
File.separator
+ pdfFileName.replace(".pdf", ".date.xml")), false), "UTF-8");
writerDate.write("<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n");
writerDate.write("<dates>\n");
writerDate.write(bufferDate.toString());
writerDate.write("</dates>\n");
writerDate.close();
}
}
if (bufferName != null) {