/
FullTextParser.java
executable file
·2414 lines (2158 loc) · 104 KB
/
FullTextParser.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.collect.Iterables;
import org.apache.commons.collections4.CollectionUtils;
import org.apache.commons.lang3.tuple.Pair;
import org.apache.commons.io.FileUtils;
import java.nio.charset.StandardCharsets;
import org.grobid.core.GrobidModels;
import org.grobid.core.data.BibDataSet;
import org.grobid.core.data.BiblioItem;
import org.grobid.core.data.Figure;
import org.grobid.core.data.Table;
import org.grobid.core.data.Equation;
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.citations.LabeledReferenceResult;
import org.grobid.core.engines.citations.ReferenceSegmenter;
import org.grobid.core.engines.config.GrobidAnalysisConfig;
import org.grobid.core.engines.counters.CitationParserCounters;
import org.grobid.core.engines.label.SegmentationLabels;
import org.grobid.core.engines.label.TaggingLabels;
import org.grobid.core.engines.label.TaggingLabel;
import org.grobid.core.engines.tagging.GenericTaggerUtils;
import org.grobid.core.exceptions.GrobidException;
import org.grobid.core.exceptions.GrobidResourceException;
import org.grobid.core.features.FeatureFactory;
import org.grobid.core.features.FeaturesVectorFulltext;
import org.grobid.core.lang.Language;
import org.grobid.core.layout.*;
import org.grobid.core.tokenization.TaggingTokenCluster;
import org.grobid.core.tokenization.TaggingTokenClusteror;
import org.grobid.core.utilities.LanguageUtilities;
import org.grobid.core.utilities.TextUtilities;
import org.grobid.core.utilities.KeyGen;
import org.grobid.core.utilities.LayoutTokensUtil;
import org.grobid.core.utilities.GrobidProperties;
import org.grobid.core.utilities.Consolidation;
import org.grobid.core.utilities.matching.ReferenceMarkerMatcher;
import org.grobid.core.utilities.matching.EntityMatcherException;
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.Arrays;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.SortedSet;
import java.util.StringTokenizer;
import java.util.TreeSet;
import java.util.regex.Matcher;
import static org.apache.commons.lang3.StringUtils.*;
/**
* @author Patrice Lopez
*/
public class FullTextParser extends AbstractParser {
private static final Logger LOGGER = LoggerFactory.getLogger(FullTextParser.class);
//private LanguageUtilities languageUtilities = LanguageUtilities.getInstance();
// private String tmpPathName = null;
// private Document doc = null;
protected File tmpPath = null;
// private String pathXML = null;
// private BiblioItem resHeader = null;
// default bins for relative position
private static final int NBBINS_POSITION = 12;
// default bins for inter-block spacing
private static final int NBBINS_SPACE = 5;
// default bins for block character density
private static final int NBBINS_DENSITY = 5;
// projection scale for line length
private static final int LINESCALE = 10;
protected EngineParsers parsers;
/**
* TODO some documentation...
*/
public FullTextParser(EngineParsers parsers) {
super(GrobidModels.FULLTEXT);
this.parsers = parsers;
tmpPath = GrobidProperties.getTempPath();
}
public Document processing(File inputPdf,
GrobidAnalysisConfig config) throws Exception {
DocumentSource documentSource =
DocumentSource.fromPdf(inputPdf, config.getStartPage(), config.getEndPage(),
config.getPdfAssetPath() != null, true, false);
return processing(documentSource, config);
}
/**
* Machine-learning recognition of the complete full text structures.
*
* @param documentSource input
* @param config config
* @return the document object with built TEI
*/
public Document processing(DocumentSource documentSource,
GrobidAnalysisConfig config) {
if (tmpPath == null) {
throw new GrobidResourceException("Cannot process pdf file, because temp path is null.");
}
if (!tmpPath.exists()) {
throw new GrobidResourceException("Cannot process pdf file, because temp path '" +
tmpPath.getAbsolutePath() + "' does not exists.");
}
try {
// general segmentation
Document doc = parsers.getSegmentationParser().processing(documentSource, config);
SortedSet<DocumentPiece> documentBodyParts = doc.getDocumentPart(SegmentationLabels.BODY);
// header processing
BiblioItem resHeader = new BiblioItem();
Pair<String, LayoutTokenization> featSeg = null;
// using the segmentation model to identify the header zones
parsers.getHeaderParser().processingHeaderSection(config, doc, resHeader, false);
// The commented part below makes use of the PDF embedded metadata (the so-called XMP) if available
// as fall back to set author and title if they have not been found.
// However tests on PMC set 1942 did not improve recognition. This will have to be re-evaluated with
// another, more diverse, testing set and with further updates of the header model.
// ---> DO NOT DELETE !
/*if (isBlank(resHeader.getTitle()) || isBlank(resHeader.getAuthors()) || CollectionUtils.isEmpty(resHeader.getFullAuthors())) {
// try to exploit PDF embedded metadata (the so-called XMP) if we are still without title/authors
// this is risky as those metadata are highly unreliable, but as last chance, why not :)
Metadata metadata = doc.getMetadata();
if (metadata != null) {
boolean titleUpdated = false;
boolean authorsUpdated = false;
if (isNotBlank(metadata.getTitle()) && isBlank(resHeader.getTitle())) {
if (!endsWithAny(lowerCase(metadata.getTitle()), ".doc", ".pdf", ".tex", ".dvi", ".docx", ".odf", ".odt", ".txt")) {
resHeader.setTitle(metadata.getTitle());
titleUpdated = true;
}
}
if (isNotBlank(metadata.getAuthor())
&& (isBlank(resHeader.getAuthors()) || CollectionUtils.isEmpty(resHeader.getFullAuthors()))) {
resHeader.setAuthors(metadata.getAuthor());
resHeader.setOriginalAuthors(metadata.getAuthor());
authorsUpdated = true;
List<Person> localAuthors = parsers.getAuthorParser().processingHeader(metadata.getAuthor());
if (localAuthors != null) {
for (Person pers : localAuthors) {
resHeader.addFullAuthor(pers);
}
}
}
// if title and author have been updated with embedded PDF metadata, we try to consolidate
// again as required
if ( titleUpdated || authorsUpdated ) {
parsers.getHeaderParser().consolidateHeader(resHeader, config.getConsolidateHeader());
}
}
}*/
// structure the abstract using the fulltext model
if (isNotBlank(resHeader.getAbstract())) {
//List<LayoutToken> abstractTokens = resHeader.getLayoutTokens(TaggingLabels.HEADER_ABSTRACT);
List<LayoutToken> abstractTokens = resHeader.getAbstractTokensWorkingCopy();
if (CollectionUtils.isNotEmpty(abstractTokens)) {
abstractTokens = BiblioItem.cleanAbstractLayoutTokens(abstractTokens);
Pair<String, List<LayoutToken>> abstractProcessed = processShort(abstractTokens, doc);
if (abstractProcessed != null) {
// neutralize figure and table annotations (will be considered as paragraphs)
String labeledAbstract = abstractProcessed.getLeft();
labeledAbstract = postProcessLabeledAbstract(labeledAbstract);
resHeader.setLabeledAbstract(labeledAbstract);
resHeader.setLayoutTokensForLabel(abstractProcessed.getRight(), TaggingLabels.HEADER_ABSTRACT);
}
}
}
// citation processing
// consolidation, if selected, is not done individually for each citation but
// in a second stage for all citations which is much faster
List<BibDataSet> resCitations = parsers.getCitationParser().
processingReferenceSection(doc, parsers.getReferenceSegmenterParser(), 0);
// consolidate the set
if (config.getConsolidateCitations() != 0 && resCitations != null) {
Consolidation consolidator = Consolidation.getInstance();
if (consolidator.getCntManager() == null)
consolidator.setCntManager(Engine.getCntManager());
try {
Map<Integer,BiblioItem> resConsolidation = consolidator.consolidate(resCitations);
for(int i=0; i<resCitations.size(); i++) {
BiblioItem resCitation = resCitations.get(i).getResBib();
BiblioItem bibo = resConsolidation.get(i);
if (bibo != null) {
if (config.getConsolidateCitations() == 1)
BiblioItem.correct(resCitation, bibo);
else if (config.getConsolidateCitations() == 2)
BiblioItem.injectIdentifiers(resCitation, bibo);
}
}
} catch(Exception e) {
throw new GrobidException(
"An exception occured while running consolidation on bibliographical references.", e);
}
}
doc.setBibDataSets(resCitations);
// full text processing
featSeg = getBodyTextFeatured(doc, documentBodyParts);
String resultBody = null;
LayoutTokenization layoutTokenization = null;
List<Figure> figures = null;
List<Table> tables = null;
List<Equation> equations = null;
if (featSeg != null && isNotBlank(featSeg.getLeft())) {
// if featSeg is null, it usually means that no body segment is found in the
// document segmentation
String bodytext = featSeg.getLeft();
layoutTokenization = featSeg.getRight();
//tokenizationsBody = featSeg.getB().getTokenization();
//layoutTokensBody = featSeg.getB().getLayoutTokens();
resultBody = label(bodytext);
// we apply now the figure and table models based on the fulltext labeled output
figures = processFigures(resultBody, layoutTokenization.getTokenization(), doc);
// further parse the caption
for(Figure figure : figures) {
if (CollectionUtils.isNotEmpty(figure.getCaptionLayoutTokens()) ) {
Pair<String, List<LayoutToken>> captionProcess = processShort(figure.getCaptionLayoutTokens(), doc);
figure.setLabeledCaption(captionProcess.getLeft());
figure.setCaptionLayoutTokens(captionProcess.getRight());
}
}
tables = processTables(resultBody, layoutTokenization.getTokenization(), doc);
// further parse the caption
for(Table table : tables) {
if ( CollectionUtils.isNotEmpty(table.getCaptionLayoutTokens()) ) {
Pair<String, List<LayoutToken>> captionProcess = processShort(table.getCaptionLayoutTokens(), doc);
table.setLabeledCaption(captionProcess.getLeft());
table.setCaptionLayoutTokens(captionProcess.getRight());
}
if ( CollectionUtils.isNotEmpty(table.getNoteLayoutTokens())) {
Pair<String, List<LayoutToken>> noteProcess = processShort(table.getNoteLayoutTokens(), doc);
table.setLabeledNote(noteProcess.getLeft());
table.setNoteLayoutTokens(noteProcess.getRight());
}
}
equations = processEquations(resultBody, layoutTokenization.getTokenization(), doc);
} else {
LOGGER.debug("Fulltext model: The featured body is empty");
}
// possible annexes (view as a piece of full text similar to the body)
documentBodyParts = doc.getDocumentPart(SegmentationLabels.ANNEX);
featSeg = getBodyTextFeatured(doc, documentBodyParts);
String resultAnnex = null;
List<LayoutToken> tokenizationsBody2 = null;
if (featSeg != null && isNotEmpty(trim(featSeg.getLeft()))) {
// if featSeg is null, it usually means that no body segment is found in the
// document segmentation
String bodytext = featSeg.getLeft();
tokenizationsBody2 = featSeg.getRight().getTokenization();
resultAnnex = label(bodytext);
//System.out.println(rese);
}
// final combination
toTEI(doc, // document
resultBody, resultAnnex, // labeled data for body and annex
layoutTokenization, tokenizationsBody2, // tokenization for body and annex
resHeader, // header
figures, tables, equations,
config);
return doc;
} catch (GrobidException e) {
throw e;
} catch (Exception e) {
throw new GrobidException("An exception occurred while running Grobid.", e);
}
}
/**
* Process a simple segment of layout tokens with the full text model.
* Return null if provided Layout Tokens is empty or if structuring failed.
*/
public Pair<String, List<LayoutToken>> processShortNew(List<LayoutToken> tokens, Document doc) {
if (CollectionUtils.isEmpty(tokens))
return null;
SortedSet<DocumentPiece> documentParts = new TreeSet<DocumentPiece>();
// identify continuous sequence of layout tokens in the abstract
int posStartPiece = -1;
int currentOffset = -1;
int startBlockPtr = -1;
LayoutToken previousToken = null;
for(LayoutToken token : tokens) {
if (currentOffset == -1) {
posStartPiece = getDocIndexToken(doc, token);
startBlockPtr = token.getBlockPtr();
} else if (token.getOffset() != currentOffset + previousToken.getText().length()) {
// new DocumentPiece to be added
DocumentPointer dp1 = new DocumentPointer(doc, startBlockPtr, posStartPiece);
DocumentPointer dp2 = new DocumentPointer(doc,
previousToken.getBlockPtr(),
getDocIndexToken(doc, previousToken));
DocumentPiece piece = new DocumentPiece(dp1, dp2);
documentParts.add(piece);
// set index for the next DocumentPiece
posStartPiece = getDocIndexToken(doc, token);
startBlockPtr = token.getBlockPtr();
}
currentOffset = token.getOffset();
previousToken = token;
}
// we still need to add the last document piece
// conditional below should always be true because abstract is not null if we reach this part, but paranoia is good when programming
if (posStartPiece != -1) {
DocumentPointer dp1 = new DocumentPointer(doc, startBlockPtr, posStartPiece);
DocumentPointer dp2 = new DocumentPointer(doc,
previousToken.getBlockPtr(),
getDocIndexToken(doc, previousToken));
DocumentPiece piece = new DocumentPiece(dp1, dp2);
documentParts.add(piece);
}
Pair<String, LayoutTokenization> featSeg = getBodyTextFeatured(doc, documentParts);
String res = "";
List<LayoutToken> layoutTokenization = new ArrayList<>();
if (featSeg != null) {
String featuredText = featSeg.getLeft();
LayoutTokenization layouts = featSeg.getRight();
if (layouts != null)
layoutTokenization = layouts.getTokenization();
if (isNotBlank(featuredText)) {
res = label(featuredText);
}
} else
return null;
return Pair.of(res, layoutTokenization);
}
public Pair<String, List<LayoutToken>> processShort(List<LayoutToken> tokens, Document doc) {
if (CollectionUtils.isEmpty(tokens))
return null;
SortedSet<DocumentPiece> documentParts = new TreeSet<>();
// we need to identify all the continuous chunks of tokens, and ignore the others
List<List<LayoutToken>> tokenChunks = new ArrayList<>();
List<LayoutToken> currentChunk = new ArrayList<>();
int currentPos = 0;
for(LayoutToken token : tokens) {
if (currentChunk.size() != 0) {
int tokenPos = token.getOffset();
if (currentPos != tokenPos) {
// new chunk
tokenChunks.add(currentChunk);
currentChunk = new ArrayList<LayoutToken>();
}
}
currentChunk.add(token);
currentPos = token.getOffset() + token.getText().length();
}
// add last chunk
tokenChunks.add(currentChunk);
for(List<LayoutToken> chunk : tokenChunks) {
int endInd = chunk.size()-1;
int posStartAbstract = getDocIndexToken(doc, chunk.get(0));
int posEndAbstract = getDocIndexToken(doc, chunk.get(endInd));
DocumentPointer dp1 = new DocumentPointer(doc, chunk.get(0).getBlockPtr(), posStartAbstract);
DocumentPointer dp2 = new DocumentPointer(doc, chunk.get(endInd).getBlockPtr(), posEndAbstract);
DocumentPiece piece = new DocumentPiece(dp1, dp2);
documentParts.add(piece);
}
Pair<String, LayoutTokenization> featSeg = getBodyTextFeatured(doc, documentParts);
String res = null;
List<LayoutToken> layoutTokenization = null;
if (featSeg != null) {
String featuredText = featSeg.getLeft();
LayoutTokenization layouts = featSeg.getRight();
if (layouts != null)
layoutTokenization = layouts.getTokenization();
if ( (featuredText != null) && (featuredText.trim().length() > 0) ) {
res = label(featuredText);
}
}
return Pair.of(res, layoutTokenization);
}
static protected String postProcessLabeledAbstract(String labeledAbstract) {
if (labeledAbstract == null)
return null;
StringBuilder result = new StringBuilder();
String[] lines = labeledAbstract.split("\n");
String previousLabel = null;
for(int i=0; i<lines.length; i++) {
String line = lines[i];
if (line == null || line.trim().length() == 0)
continue;
String[] pieces = line.split("\t");
String label = pieces[pieces.length-1];
if (label.equals("I-"+TaggingLabels.FIGURE.getLabel()) || label.equals("I-"+TaggingLabels.TABLE.getLabel())) {
if (previousLabel == null || !previousLabel.endsWith(TaggingLabels.PARAGRAPH.getLabel())) {
pieces[pieces.length-1] = "I-"+TaggingLabels.PARAGRAPH.getLabel();
} else {
pieces[pieces.length-1] = TaggingLabels.PARAGRAPH.getLabel();
}
} else if (label.equals(TaggingLabels.FIGURE.getLabel()) || label.equals(TaggingLabels.TABLE.getLabel())) {
pieces[pieces.length-1] = TaggingLabels.PARAGRAPH.getLabel();
}
for(int j=0; j<pieces.length; j++) {
if (j != 0)
result.append("\t");
result.append(pieces[j]);
}
previousLabel = label;
result.append("\n");
}
return result.toString();
}
static public Pair<String, LayoutTokenization> getBodyTextFeatured(Document doc,
SortedSet<DocumentPiece> documentBodyParts) {
if ((documentBodyParts == null) || (documentBodyParts.size() == 0)) {
return null;
}
FeatureFactory featureFactory = FeatureFactory.getInstance();
StringBuilder fulltext = new StringBuilder();
String currentFont = null;
int currentFontSize = -1;
List<Block> blocks = doc.getBlocks();
if ( (blocks == null) || blocks.size() == 0) {
return null;
}
// vector for features
FeaturesVectorFulltext features;
FeaturesVectorFulltext previousFeatures = null;
ReferenceMarkerMatcher referenceMarkerMatcher = null;
// if bibliographical references are available from the bibliographical reference section, we look if we have
// a numbering associated to the bibliographical references (bib. ref. callout will likely be numerical then)
String bibRefCalloutType = "UNKNOWN";
List<BibDataSet> bibDataSets = doc.getBibDataSets();
if (bibDataSets != null) {
try {
referenceMarkerMatcher = doc.getReferenceMarkerMatcher();
// we look at the exising extracted labels in the bibliographical section (if available and if any) and set
// the value based on the majority of labels
int nbNumbType = 0;
int nbAuthorType = 0;
for(BibDataSet bibDataSet : bibDataSets) {
if ((bibDataSet == null) || (bibDataSet.getRefSymbol() == null))
continue;
boolean isNumb = referenceMarkerMatcher.isNumberedCitationReference(bibDataSet.getRefSymbol());
if (isNumb) {
nbNumbType++;
continue;
}
boolean isAuthor = referenceMarkerMatcher.isAuthorCitationStyle(bibDataSet.getRefSymbol());
if (isAuthor)
nbAuthorType++;
}
if (nbNumbType > (bibDataSets.size() / 2))
bibRefCalloutType = "NUMBER";
else if (nbAuthorType > (bibDataSets.size() / 2))
bibRefCalloutType = "AUTHOR";
} catch(EntityMatcherException e) {
LOGGER.info("Could not build the bibliographical matcher", e);
}
}
boolean endblock;
boolean endPage = true;
boolean newPage = true;
//boolean start = true;
int mm = 0; // page position
int nn = 0; // document position
double lineStartX = Double.NaN;
boolean indented = false;
int fulltextLength = 0;
int pageLength = 0; // length of the current page
double lowestPos = 0.0;
double spacingPreviousBlock = 0.0;
int currentPage = 0;
List<LayoutToken> layoutTokens = new ArrayList<LayoutToken>();
fulltextLength = getFulltextLength(doc, documentBodyParts, fulltextLength);
//System.out.println("fulltextLength: " + fulltextLength);
for(DocumentPiece docPiece : documentBodyParts) {
DocumentPointer dp1 = docPiece.getLeft();
DocumentPointer dp2 = docPiece.getRight();
//int blockPos = dp1.getBlockPtr();
for(int blockIndex = dp1.getBlockPtr(); blockIndex <= dp2.getBlockPtr(); blockIndex++) {
//System.out.println("blockIndex: " + blockIndex);
boolean graphicVector = false;
boolean graphicBitmap = false;
Block block = blocks.get(blockIndex);
// length of the page where the current block is
double pageHeight = block.getPage().getHeight();
int localPage = block.getPage().getNumber();
if (localPage != currentPage) {
newPage = true;
currentPage = localPage;
mm = 0;
lowestPos = 0.0;
spacingPreviousBlock = 0.0;
}
/*if (start) {
newPage = true;
start = false;
}*/
boolean newline;
boolean previousNewline = false;
endblock = false;
/*if (endPage) {
newPage = true;
mm = 0;
lowestPos = 0.0;
}*/
if (lowestPos > block.getY()) {
// we have a vertical shift, which can be due to a change of column or other particular layout formatting
spacingPreviousBlock = doc.getMaxBlockSpacing() / 5.0; // default
}
else
spacingPreviousBlock = block.getY() - lowestPos;
String localText = block.getText();
if (TextUtilities.filterLine(localText)) {
continue;
}
/*if (localText != null) {
if (localText.contains("@PAGE")) {
mm = 0;
// pageLength = 0;
endPage = true;
newPage = false;
} else {
endPage = false;
}
}*/
// character density of the block
double density = 0.0;
if ( (block.getHeight() != 0.0) && (block.getWidth() != 0.0) &&
(localText != null) && (!localText.contains("@PAGE")) &&
(!localText.contains("@IMAGE")) )
density = (double)localText.length() / (block.getHeight() * block.getWidth());
// check if we have a graphical object connected to the current block
List<GraphicObject> localImages = Document.getConnectedGraphics(block, doc);
if (localImages != null) {
for(GraphicObject localImage : localImages) {
if (localImage.getType() == GraphicObjectType.BITMAP)
graphicVector = true;
if (localImage.getType() == GraphicObjectType.VECTOR)
graphicBitmap = true;
}
}
List<LayoutToken> tokens = block.getTokens();
if (tokens == null) {
continue;
}
int n = 0;// token position in current block
if (blockIndex == dp1.getBlockPtr()) {
// n = dp1.getTokenDocPos() - block.getStartToken();
n = dp1.getTokenBlockPos();
}
int lastPos = tokens.size();
// if it's a last block from a document piece, it may end earlier
if (blockIndex == dp2.getBlockPtr()) {
lastPos = dp2.getTokenBlockPos()+1;
if (lastPos > tokens.size()) {
LOGGER.error("DocumentPointer for block " + blockIndex + " points to " +
dp2.getTokenBlockPos() + " token, but block token size is " +
tokens.size());
lastPos = tokens.size();
}
}
while (n < lastPos) {
if (blockIndex == dp2.getBlockPtr()) {
//if (n > block.getEndToken()) {
if (n > dp2.getTokenDocPos() - block.getStartToken()) {
break;
}
}
LayoutToken token = tokens.get(n);
layoutTokens.add(token);
features = new FeaturesVectorFulltext();
features.token = token;
double coordinateLineY = token.getY();
String text = token.getText();
if ( (text == null) || (text.length() == 0)) {
n++;
//mm++;
//nn++;
continue;
}
//text = text.replaceAll("\\s+", "");
text = text.replace(" ", "");
if (text.length() == 0) {
n++;
mm++;
nn++;
continue;
}
if (text.equals("\n")) {
newline = true;
previousNewline = true;
n++;
mm++;
nn++;
continue;
} else
newline = false;
// final sanitisation and filtering
text = text.replaceAll("[ \n]", "");
if (TextUtilities.filterLine(text)) {
n++;
continue;
}
if (previousNewline) {
newline = true;
previousNewline = false;
if ((token != null) && (previousFeatures != null)) {
double previousLineStartX = lineStartX;
lineStartX = token.getX();
double characterWidth = token.width / text.length();
if (!Double.isNaN(previousLineStartX)) {
if (previousLineStartX - lineStartX > characterWidth)
indented = false;
else if (lineStartX - previousLineStartX > characterWidth)
indented = true;
// Indentation ends if line start is > 1 character width to the left of previous line start
// Indentation starts if line start is > 1 character width to the right of previous line start
// Otherwise indentation is unchanged
}
}
}
features.string = text;
if (graphicBitmap) {
features.bitmapAround = true;
}
if (graphicVector) {
features.vectorAround = true;
}
if (newline) {
features.lineStatus = "LINESTART";
if (token != null)
lineStartX = token.getX();
// be sure that previous token is closing a line, except if it's a starting line
if (previousFeatures != null) {
if (!previousFeatures.lineStatus.equals("LINESTART"))
previousFeatures.lineStatus = "LINEEND";
}
}
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 (indented) {
features.alignmentStatus = "LINEINDENT";
}
else {
features.alignmentStatus = "ALIGNEDLEFT";
}
if (n == 0) {
features.lineStatus = "LINESTART";
// be sure that previous token is closing a line, except if it's a starting line
if (previousFeatures != null) {
if (!previousFeatures.lineStatus.equals("LINESTART"))
previousFeatures.lineStatus = "LINEEND";
}
if (token != null)
lineStartX = token.getX();
features.blockStatus = "BLOCKSTART";
} else if (n == tokens.size() - 1) {
features.lineStatus = "LINEEND";
previousNewline = true;
features.blockStatus = "BLOCKEND";
endblock = true;
} else {
// look ahead...
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")) {
endline = true;
endloop = true;
} else {
if ((toto.length() != 0)
&& (!(toto.startsWith("@IMAGE")))
&& (!(toto.startsWith("@PAGE")))
&& (!text.contains(".pbm"))
&& (!text.contains(".svg"))
&& (!text.contains(".png"))
&& (!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";
//endblock = true;
}
}
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";
}
Matcher m = featureFactory.isDigit.matcher(text);
if (m.find()) {
features.digit = "ALLDIGIT";
}
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 (features.capitalisation == null)
features.capitalisation = "NOCAPS";
if (features.digit == null)
features.digit = "NODIGIT";
if (features.punctType == null)
features.punctType = "NOPUNCT";
features.relativeDocumentPosition = featureFactory
.linearScaling(nn, fulltextLength, NBBINS_POSITION);
// System.out.println(mm + " / " + pageLength);
features.relativePagePositionChar = featureFactory
.linearScaling(mm, pageLength, NBBINS_POSITION);
int pagePos = featureFactory
.linearScaling(coordinateLineY, pageHeight, NBBINS_POSITION);
if (pagePos > NBBINS_POSITION)
pagePos = NBBINS_POSITION;
features.relativePagePosition = pagePos;
//System.out.println((coordinateLineY) + " " + (pageHeight) + " " + NBBINS_POSITION + " " + pagePos);
if (spacingPreviousBlock != 0.0) {
features.spacingWithPreviousBlock = featureFactory
.linearScaling(spacingPreviousBlock - doc.getMinBlockSpacing(),
doc.getMaxBlockSpacing() - doc.getMinBlockSpacing(), NBBINS_SPACE);
}
if (density != -1.0) {
features.characterDensity = featureFactory
.linearScaling(density - doc.getMinCharacterDensity(), doc.getMaxCharacterDensity() - doc.getMinCharacterDensity(), NBBINS_DENSITY);
//System.out.println((density-doc.getMinCharacterDensity()) + " " + (doc.getMaxCharacterDensity()-doc.getMinCharacterDensity()) + " " + NBBINS_DENSITY + " " + features.characterDensity);
}
features.calloutType = bibRefCalloutType;
// check of the token is a known bib ref label
if ((referenceMarkerMatcher != null) && ( referenceMarkerMatcher.isKnownLabel(text) || referenceMarkerMatcher.isKnownFirstAuthor(text) ))
features.calloutKnown = true;
if (token.isSuperscript()) {
features.superscript = true;
}
// fulltext.append(features.printVector());
if (previousFeatures != null) {
if (features.blockStatus.equals("BLOCKSTART") &&
previousFeatures.blockStatus.equals("BLOCKIN")) {
// this is a post-correction due to the fact that the last character of a block
// can be a space or EOL character
previousFeatures.blockStatus = "BLOCKEND";
previousFeatures.lineStatus = "LINEEND";
}
fulltext.append(previousFeatures.printVector());
}
n++;
mm += text.length();
nn += text.length();
previousFeatures = features;
}
// lowest position of the block
lowestPos = block.getY() + block.getHeight();
//blockPos++;
}
}
if (previousFeatures != null) {
fulltext.append(previousFeatures.printVector());
}
return Pair.of(fulltext.toString(),
new LayoutTokenization(layoutTokens));
}
/**
* Evaluate the length of the fulltext
*/
private static int getFulltextLength(Document doc, SortedSet<DocumentPiece> documentBodyParts, int fulltextLength) {
for(DocumentPiece docPiece : documentBodyParts) {
DocumentPointer dp1 = docPiece.getLeft();
DocumentPointer dp2 = docPiece.getRight();
int tokenStart = dp1.getTokenDocPos();
int tokenEnd = dp2.getTokenDocPos();
for (int i = tokenStart; i <= tokenEnd && i < doc.getTokenizations().size(); i++) {
//tokenizationsBody.add(tokenizations.get(i));
fulltextLength += doc.getTokenizations().get(i).getText().length();
}
}
return fulltextLength;
}
/**
* Return the index of a token in a document tokenization
*/
private static int getDocIndexToken(Document doc, LayoutToken token) {
int blockPtr = token.getBlockPtr();
Block block = doc.getBlocks().get(blockPtr);
int startTokenBlockPos = block.getStartToken();
List<LayoutToken> tokens = doc.getTokenizations();
int i = startTokenBlockPos;
for(; i < tokens.size(); i++) {
int offset = tokens.get(i).getOffset();
if (offset >= token.getOffset())
break;
}
return i;
}
/**
* Process the specified pdf and format the result as training data for all the models.
*
* @param inputFile input file
* @param pathFullText path to fulltext
* @param pathTEI path to TEI
* @param id id
*/
public Document createTraining(File inputFile,
String pathFullText,
String pathTEI,
int id) {
if (tmpPath == null)
throw new GrobidResourceException("Cannot process pdf file, because temp path is null.");
if (!tmpPath.exists()) {
throw new GrobidResourceException("Cannot process pdf file, because temp path '" +
tmpPath.getAbsolutePath() + "' does not exists.");
}
DocumentSource documentSource = null;
try {
if (!inputFile.exists()) {
throw new GrobidResourceException("Cannot train for fulltext, becuase file '" +
inputFile.getAbsolutePath() + "' does not exists.");
}
String pdfFileName = inputFile.getName();
// SEGMENTATION MODEL
documentSource = DocumentSource.fromPdf(inputFile, -1, -1, false, true, true);
Document doc = new Document(documentSource);
doc.addTokenizedDocument(GrobidAnalysisConfig.defaultInstance());
if (doc.getBlocks() == null) {
throw new Exception("PDF parsing resulted in empty content");
}
doc.produceStatistics();