repo
stringlengths
1
191
file
stringlengths
23
351
code
stringlengths
0
5.32M
file_length
int64
0
5.32M
avg_line_length
float64
0
2.9k
max_line_length
int64
0
288k
extension_type
stringclasses
1 value
CERMINE
CERMINE-master/cermine-impl/src/main/java/pl/edu/icm/cermine/structure/readingorder/TreeToListConverter.java
/** * This file is part of CERMINE project. * Copyright (c) 2011-2018 ICM-UW * * CERMINE is free software: you can redistribute it and/or modify * it under the terms of the GNU Affero General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * CERMINE is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU Affero General Public License for more details. * * You should have received a copy of the GNU Affero General Public License * along with CERMINE. If not, see <http://www.gnu.org/licenses/>. */ package pl.edu.icm.cermine.structure.readingorder; import java.util.ArrayList; import java.util.List; import pl.edu.icm.cermine.structure.model.BxZone; /** * @author Pawel Szostek */ public class TreeToListConverter { public List<BxZone> convertToList(BxZoneGroup obj) { List<BxZone> ret = new ArrayList<BxZone>(); if (obj.getLeftChild() instanceof BxZone) { BxZone zone = (BxZone) obj.getLeftChild(); ret.add(zone); } else { // obj.getLeftChild() instanceof BxZoneGroup ret.addAll(convertToList((BxZoneGroup) obj.getLeftChild())); } if (obj.getRightChild() instanceof BxZone) { BxZone zone = (BxZone) obj.getRightChild(); ret.add(zone); } else { // obj.getRightChild() instanceof BxZoneGroup ret.addAll(convertToList((BxZoneGroup) obj.getRightChild())); } return ret; } }
1,660
33.604167
78
java
CERMINE
CERMINE-master/cermine-impl/src/main/java/pl/edu/icm/cermine/structure/readingorder/DistElem.java
/** * This file is part of CERMINE project. * Copyright (c) 2011-2018 ICM-UW * * CERMINE is free software: you can redistribute it and/or modify * it under the terms of the GNU Affero General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * CERMINE is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU Affero General Public License for more details. * * You should have received a copy of the GNU Affero General Public License * along with CERMINE. If not, see <http://www.gnu.org/licenses/>. */ package pl.edu.icm.cermine.structure.readingorder; import pl.edu.icm.cermine.tools.Utils; /** * Tuple containing magic value c, object1, object2 and distance between them. * * @author Pawel Szostek * @param <E> element type */ public class DistElem<E> implements Comparable<DistElem<E>> { @Override public int hashCode() { final int prime = 31; int result = 1; result = prime * result + (c ? 1231 : 1237); long temp; temp = Double.doubleToLongBits(dist); result = prime * result + (int) (temp ^ (temp >>> 32)); result = prime * result + ((obj1 == null) ? 0 : obj1.hashCode()); result = prime * result + ((obj2 == null) ? 0 : obj2.hashCode()); return result; } @Override public boolean equals(Object obj) { if (this == obj) { return true; } if (obj == null) { return false; } if (getClass() != obj.getClass()) { return false; } DistElem other = (DistElem) obj; if (c != other.c) { return false; } if (Double.doubleToLongBits(dist) != Double .doubleToLongBits(other.dist)) { return false; } if (obj1 == null) { if (other.obj1 != null) { return false; } } else if (!obj1.equals(other.obj1)) { return false; } if (obj2 == null) { if (other.obj2 != null) { return false; } } else if (!obj2.equals(other.obj2)) { return false; } return true; } boolean c; double dist; E obj1; E obj2; public boolean isC() { return c; } public void setC(boolean c) { this.c = c; } public double getDist() { return dist; } public void setDist(double dist) { this.dist = dist; } public E getObj1() { return obj1; } public void setObj1(E obj1) { this.obj1 = obj1; } public E getObj2() { return obj2; } public void setObj2(E obj2) { this.obj2 = obj2; } public DistElem(boolean c, double dist, E obj1, E obj2) { this.c = c; this.dist = dist; this.obj1 = obj1; this.obj2 = obj2; } @Override public int compareTo(DistElem<E> compareObject) { double eps = 1E-3; if (c == compareObject.c) { return Utils.compareDouble(dist, compareObject.dist, eps); } else { return c ? -1 : 1; } } }
3,380
24.231343
78
java
CERMINE
CERMINE-master/cermine-impl/src/main/java/pl/edu/icm/cermine/structure/model/Indexable.java
/** * This file is part of CERMINE project. * Copyright (c) 2011-2018 ICM-UW * * CERMINE is free software: you can redistribute it and/or modify * it under the terms of the GNU Affero General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * CERMINE is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU Affero General Public License for more details. * * You should have received a copy of the GNU Affero General Public License * along with CERMINE. If not, see <http://www.gnu.org/licenses/>. */ package pl.edu.icm.cermine.structure.model; /** * @author Pawel Szostek * @param <A> indexable object class */ public interface Indexable<A> { /** * Getter for the value based on TrueViz XxxID field * @return id */ String getId(); /** * Getter for the value based on TrueViz XxxNext field * @return next id */ String getNextId(); /** * Setter for the value based on TrueViz XxxID field * @param id id */ void setId(String id); /** * Setter for the value based on TrueViz XxxNext field * @param nextId next id */ void setNextId(String nextId); /** * Get next linked list element * @return next object */ A getNext(); /** * Set next linked list element * @param elem next object */ void setNext(A elem); boolean hasNext(); A getPrev(); void setPrev(A elem); boolean hasPrev(); }
1,682
22.704225
78
java
CERMINE
CERMINE-master/cermine-impl/src/main/java/pl/edu/icm/cermine/structure/model/BxChunk.java
/** * This file is part of CERMINE project. * Copyright (c) 2011-2018 ICM-UW * * CERMINE is free software: you can redistribute it and/or modify * it under the terms of the GNU Affero General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * CERMINE is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU Affero General Public License for more details. * * You should have received a copy of the GNU Affero General Public License * along with CERMINE. If not, see <http://www.gnu.org/licenses/>. */ package pl.edu.icm.cermine.structure.model; import com.google.common.collect.Sets; import java.util.ArrayList; import java.util.Iterator; import java.util.List; import java.util.Set; /** * Immutable representation of a chunk of glyphs. * * @author Lukasz Bolikowski (bolo@icm.edu.pl) */ public final class BxChunk extends BxObject<Character, BxChunk, BxWord> { private static final long serialVersionUID = -6911268485662874663L; private String fontName; public BxChunk(BxBounds bounds, String text) { this.setBounds(bounds); this.setText(text); } public BxChunk withBounds(BxBounds bounds) { return new BxChunk(bounds, this.getText()); } public BxChunk withText(String text) { return new BxChunk(getBounds(), text); } public String getFontName() { return fontName; } public void setFontName(String fontName) { this.fontName = fontName; } @Override public String toText() { return this.getText(); } @Override public String getMostPopularFontName() { return fontName; } @Override public Set<String> getFontNames() { return Sets.newHashSet(fontName); } @Override public Iterator<Character> iterator() { List<Character> characters = new ArrayList<Character>(); for (char ch: getText().toCharArray()) { characters.add(ch); } return characters.listIterator(); } @Override public int childrenCount() { return toText().length(); } @Override public Character getChild(int index) { if (index < 0 || index >= toText().length()) { throw new IndexOutOfBoundsException(); } return toText().charAt(index); } }
2,537
25.4375
78
java
CERMINE
CERMINE-master/cermine-impl/src/main/java/pl/edu/icm/cermine/structure/model/BxZone.java
/** * This file is part of CERMINE project. * Copyright (c) 2011-2018 ICM-UW * * CERMINE is free software: you can redistribute it and/or modify * it under the terms of the GNU Affero General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * CERMINE is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU Affero General Public License for more details. * * You should have received a copy of the GNU Affero General Public License * along with CERMINE. If not, see <http://www.gnu.org/licenses/>. */ package pl.edu.icm.cermine.structure.model; import java.util.*; import pl.edu.icm.cermine.tools.CountMap; import pl.edu.icm.cermine.tools.timeout.TimeoutRegister; /** * Models a single zone of a page. A zone contains either lines of text * or a list of chunks, that haven't been grouped into lines yet. * * @author Dominika Tkaczyk (d.tkaczyk@icm.edu.pl) */ public final class BxZone extends BxObject<BxLine, BxZone, BxPage> { private static final long serialVersionUID = -7331944901471939127L; /** zone's label */ private BxZoneLabel label; /** list of zone's lines (if the zone is segmented) */ private final List<BxLine> lines = new ArrayList<BxLine>(); /** list of zone's text chunks (if the zone is not segmented) */ private final List<BxChunk> chunks = new ArrayList<BxChunk>(); public BxZoneLabel getLabel() { return label; } public BxZone setLabel(BxZoneLabel label) { this.label = label; return this; } public BxZone setLines(Collection<BxLine> lines) { resetText(); if (lines != null) { this.lines.clear(); for (BxLine line : lines) { addLine(line); } } return this; } public BxZone addLine(BxLine line) { resetText(); if (line != null) { this.lines.add(line); line.setParent(this); } return this; } public List<BxChunk> getChunks() { return chunks; } public BxZone setChunks(Collection<BxChunk> chunks) { resetText(); if (chunks != null) { this.chunks.clear(); this.chunks.addAll(chunks); } return this; } public BxZone addChunk(BxChunk chunk) { resetText(); if (chunk != null) { this.chunks.add(chunk); } return this; } @Override public String getMostPopularFontName() { CountMap<String> map = new CountMap<String>(); for (BxLine line : lines) { for (BxWord word : line) { for (BxChunk chunk : word) { if (chunk.getFontName() != null) { map.add(chunk.getFontName()); } } } } return map.getMaxCountObject(); } @Override public Set<String> getFontNames() { Set<String> names = new HashSet<String>(); for (BxLine line : lines) { names.addAll(line.getFontNames()); TimeoutRegister.get().check(); } return names; } @Override public String toText() { if (getText() == null) { StringBuilder sb = new StringBuilder(); boolean first = true; for (BxLine w : lines) { if (!first) { sb.append("\n"); } first = false; sb.append(w.toText()); } setText(sb.toString()); } return getText(); } @Override public Iterator<BxLine> iterator() { return lines.listIterator(); } @Override public int childrenCount() { return lines.size(); } @Override public BxLine getChild(int index) { if (index < 0 || index >= lines.size()) { throw new IndexOutOfBoundsException(); } return lines.get(index); } }
4,217
26.38961
78
java
CERMINE
CERMINE-master/cermine-impl/src/main/java/pl/edu/icm/cermine/structure/model/BxZoneLabel.java
/** * This file is part of CERMINE project. * Copyright (c) 2011-2018 ICM-UW * * CERMINE is free software: you can redistribute it and/or modify * it under the terms of the GNU Affero General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * CERMINE is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU Affero General Public License for more details. * * You should have received a copy of the GNU Affero General Public License * along with CERMINE. If not, see <http://www.gnu.org/licenses/>. */ package pl.edu.icm.cermine.structure.model; import java.util.ArrayList; import java.util.EnumMap; import java.util.List; import java.util.Map; /** * Represents a zone's function on a page. * * @author Lukasz Bolikowski (bolo@icm.edu.pl) */ public enum BxZoneLabel { /** * General zones */ /** * Document's metadata - 0 */ GEN_METADATA(BxZoneLabelCategory.CAT_GENERAL), /** * Document's body - 1 */ GEN_BODY(BxZoneLabelCategory.CAT_GENERAL), /** * Document's references - 2 */ GEN_REFERENCES(BxZoneLabelCategory.CAT_GENERAL), /** * Other stuff left in the document - 3 */ GEN_OTHER(BxZoneLabelCategory.CAT_GENERAL), /** * Metadata zones */ /** * Document's abstract - 4 */ MET_ABSTRACT(BxZoneLabelCategory.CAT_METADATA), /** * Authors' Affiliations - 5 */ MET_AFFILIATION(BxZoneLabelCategory.CAT_METADATA), /** * Document's access info - 6 */ MET_ACCESS_DATA(BxZoneLabelCategory.CAT_METADATA), /** * Authors' biographies - 7 */ MET_BIOGRAPHY(BxZoneLabelCategory.CAT_METADATA), /** * Authors' names. - 8 */ MET_AUTHOR(BxZoneLabelCategory.CAT_METADATA), /** * Bibliographic information, such as journal, volume, year, doi, etc. - 9 */ MET_BIB_INFO(BxZoneLabelCategory.CAT_METADATA), /** * Authors' correspondence information - 10 */ MET_CORRESPONDENCE(BxZoneLabelCategory.CAT_METADATA), /** * When the document was received/revised/accepted/etc. - 11 */ MET_DATES(BxZoneLabelCategory.CAT_METADATA), /** * Document's editor - 12 */ MET_EDITOR(BxZoneLabelCategory.CAT_METADATA), /** * Keywords - 13 */ MET_KEYWORDS(BxZoneLabelCategory.CAT_METADATA), /** * Document's title - 14 */ MET_TITLE(BxZoneLabelCategory.CAT_METADATA), /** * Document's type - 15 */ MET_TYPE(BxZoneLabelCategory.CAT_METADATA), /** * Document's copyright - 16 */ MET_COPYRIGHT(BxZoneLabelCategory.CAT_METADATA), /** * Body zones */ /** * Document's body - 17 */ BODY_CONTENT(BxZoneLabelCategory.CAT_BODY), /** * Glossary - 18 */ BODY_GLOSSARY(BxZoneLabelCategory.CAT_BODY), /** * Equation - 19 */ BODY_EQUATION(BxZoneLabelCategory.CAT_BODY), /** * Equation's label - 20 */ BODY_EQUATION_LABEL(BxZoneLabelCategory.CAT_BODY), /** * Figure - 21 */ BODY_FIGURE(BxZoneLabelCategory.CAT_BODY), /** * Figure's caption - 22 */ BODY_FIGURE_CAPTION(BxZoneLabelCategory.CAT_BODY), /** * Content header - 23 */ BODY_HEADING(BxZoneLabelCategory.CAT_BODY), /** * General label for tables, figures and equations - 24 */ BODY_JUNK(BxZoneLabelCategory.CAT_BODY), /** * Table - 25 */ BODY_TABLE(BxZoneLabelCategory.CAT_BODY), /** * Table's caption - 26 */ BODY_TABLE_CAPTION(BxZoneLabelCategory.CAT_BODY), /** * Acknowledgments - 27 */ BODY_ACKNOWLEDGMENT(BxZoneLabelCategory.CAT_BODY), /** * Author's contributions - 28 */ BODY_CONTRIBUTION(BxZoneLabelCategory.CAT_BODY), /** * Conflict statements - 29 */ BODY_CONFLICT_STMT(BxZoneLabelCategory.CAT_BODY), /** * Attachments - 30 */ BODY_ATTACHMENT(BxZoneLabelCategory.CAT_BODY), /** * Other zones */ /** * Page number - 31 */ OTH_PAGE_NUMBER(BxZoneLabelCategory.CAT_OTHER), /** * Undetermined zone - 32 */ OTH_UNKNOWN(BxZoneLabelCategory.CAT_OTHER), /** * References zones */ /** * References - 33 */ REFERENCES(BxZoneLabelCategory.CAT_REFERENCES), /** * Document's title with authors - 34 */ MET_TITLE_AUTHOR(BxZoneLabelCategory.CAT_METADATA), /** * 35 */ MET_CATEGORY(BxZoneLabelCategory.CAT_METADATA), /** * 36 */ MET_TERMS(BxZoneLabelCategory.CAT_METADATA); private final BxZoneLabelCategory category; private static final Map<BxZoneLabelCategory, BxZoneLabel> CATEGORY_TO_GENERAL = new EnumMap<BxZoneLabelCategory, BxZoneLabel>(BxZoneLabelCategory.class); static { CATEGORY_TO_GENERAL.put(BxZoneLabelCategory.CAT_BODY, GEN_BODY); CATEGORY_TO_GENERAL.put(BxZoneLabelCategory.CAT_METADATA, GEN_METADATA); CATEGORY_TO_GENERAL.put(BxZoneLabelCategory.CAT_OTHER, GEN_OTHER); CATEGORY_TO_GENERAL.put(BxZoneLabelCategory.CAT_REFERENCES, GEN_REFERENCES); } private static final Map<BxZoneLabel, BxZoneLabelCategory> GENERAL_TO_CATEGORY = new EnumMap<BxZoneLabel, BxZoneLabelCategory>(BxZoneLabel.class); static { GENERAL_TO_CATEGORY.put(GEN_BODY, BxZoneLabelCategory.CAT_BODY); GENERAL_TO_CATEGORY.put(GEN_METADATA, BxZoneLabelCategory.CAT_METADATA); GENERAL_TO_CATEGORY.put(GEN_OTHER, BxZoneLabelCategory.CAT_OTHER); GENERAL_TO_CATEGORY.put(GEN_REFERENCES, BxZoneLabelCategory.CAT_REFERENCES); } private static final Map<BxZoneLabel, BxZoneLabel> LABEL_TO_GENERAL = new EnumMap<BxZoneLabel, BxZoneLabel>(BxZoneLabel.class); static { for (BxZoneLabel label : BxZoneLabel.values()) { if (CATEGORY_TO_GENERAL.get(label.category) != null) { LABEL_TO_GENERAL.put(label, CATEGORY_TO_GENERAL.get(label.category)); } else { LABEL_TO_GENERAL.put(label, label); } } } private static final Map<BxZoneLabel, BxZoneLabelCategory> LABEL_TO_CATEGORY = new EnumMap<BxZoneLabel, BxZoneLabelCategory>(BxZoneLabel.class); static { for (BxZoneLabel label : BxZoneLabel.values()) { LABEL_TO_CATEGORY.put(label, label.category); } } BxZoneLabel(BxZoneLabelCategory category) { this.category = category; } public BxZoneLabelCategory getCategory() { return category; } public BxZoneLabel getGeneralLabel() { return LABEL_TO_GENERAL.get(this); } public boolean isOfCategory(BxZoneLabelCategory category) { return category.equals(this.getCategory()); } public boolean isOfCategoryOrGeneral(BxZoneLabelCategory category) { return category.equals(this.getCategory()) || this.equals(CATEGORY_TO_GENERAL.get(category)); } public static List<BxZoneLabel> valuesOfCategory(BxZoneLabelCategory category) { List<BxZoneLabel> values = new ArrayList<BxZoneLabel>(); for (BxZoneLabel label : BxZoneLabel.values()) { if (category.equals(label.getCategory())) { values.add(label); } } return values; } public static Map<BxZoneLabel, BxZoneLabel> getLabelToGeneralMap() { return LABEL_TO_GENERAL; } public static Map<BxZoneLabel, BxZoneLabel> getIdentityMap() { Map<BxZoneLabel, BxZoneLabel> ret = new EnumMap<BxZoneLabel, BxZoneLabel>(BxZoneLabel.class); for (BxZoneLabel label : BxZoneLabel.values()) { ret.put(label, label); } return ret; } }
8,005
27.289753
101
java
CERMINE
CERMINE-master/cermine-impl/src/main/java/pl/edu/icm/cermine/structure/model/BxBounds.java
/** * This file is part of CERMINE project. * Copyright (c) 2011-2018 ICM-UW * * CERMINE is free software: you can redistribute it and/or modify * it under the terms of the GNU Affero General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * CERMINE is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU Affero General Public License for more details. * * You should have received a copy of the GNU Affero General Public License * along with CERMINE. If not, see <http://www.gnu.org/licenses/>. */ package pl.edu.icm.cermine.structure.model; import java.io.Serializable; /** * Bounding box of an object. Immutable. * * @author Lukasz Bolikowski (bolo@icm.edu.pl) */ public final class BxBounds implements Serializable { private static final long serialVersionUID = 5062840871474513495L; /** X coordinate of the bounding box' position on the page */ private final double x; /** Y coordinate of the bounding box' position on the page */ private final double y; /** width of the bounding box */ private final double width; /** height of the bounding box */ private final double height; /** * Default constructor returning a unit box at the origin of the coordinate * system. */ public BxBounds() { this.x = 0.0; this.y = 0.0; this.width = 1.0; this.height = 1.0; } public BxBounds(double x, double y, double width, double height) { this.x = x; this.y = y; this.width = width; this.height = height; } public double getX() { return x; } public BxBounds withX(double x) { return new BxBounds(x, y, width, height); } public double getY() { return y; } public BxBounds withY(double y) { return new BxBounds(x, y, width, height); } public double getWidth() { return width; } public BxBounds withWidth(double width) { return new BxBounds(x, y, width, height); } public double getHeight() { return height; } public BxBounds withHeight(double height) { return new BxBounds(x, y, width, height); } public boolean isSimilarTo(BxBounds bounds, double tolerance) { double diffX1 = Math.abs(x - bounds.getX()); double diffX2 = Math.abs(x + width - bounds.getX() - bounds.getWidth()); double diffY1 = Math.abs(y - bounds.getY()); double diffY2 = Math.abs(y + height - bounds.getY() - bounds.getHeight()); return ((diffX1 <= tolerance) && (diffX2 <= tolerance) && (diffY1 <= tolerance) && (diffY2 <= tolerance)); } }
2,881
26.711538
114
java
CERMINE
CERMINE-master/cermine-impl/src/main/java/pl/edu/icm/cermine/structure/model/BxDocument.java
/** * This file is part of CERMINE project. * Copyright (c) 2011-2018 ICM-UW * * CERMINE is free software: you can redistribute it and/or modify * it under the terms of the GNU Affero General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * CERMINE is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU Affero General Public License for more details. * * You should have received a copy of the GNU Affero General Public License * along with CERMINE. If not, see <http://www.gnu.org/licenses/>. */ package pl.edu.icm.cermine.structure.model; import java.util.*; import pl.edu.icm.cermine.tools.CountMap; /** * Models a document containing pages. * * @author Dominika Tkaczyk (d.tkaczyk@icm.edu.pl) */ public final class BxDocument extends BxObject<BxPage, BxDocument, Object> { private static final long serialVersionUID = -4826783896245709986L; /** list of document's pages */ private final List<BxPage> pages = new ArrayList<BxPage>(); private String filename = null; private int curPageNumber = 0; public String getFilename() { return filename; } public void setFilename(String filename) { this.filename = filename; } public BxDocument setPages(Collection<BxPage> pages) { if (pages != null) { this.pages.clear(); curPageNumber = 0; for (BxPage page : pages) { addPage(page); } } return this; } public BxDocument addPage(BxPage page) { if (page != null) { page.setId(Integer.toString(this.curPageNumber++)); page.setParent(this); this.pages.add(page); } return this; } @Override public String toText() { StringBuilder sb = new StringBuilder(); boolean first = true; for (Printable w : pages) { if (!first) { sb.append("\n"); } first = false; sb.append(w.toText()); } return sb.toString(); } /** * * @return a list of constituent pages. The list keeps the order used in the original file */ public Iterable<BxPage> asPages() { return new Iterable<BxPage>() { @Override public Iterator<BxPage> iterator() { return pages.listIterator(); } }; } /** * * @return a list of constituent zones. The list holds the logical reading-order if * a ReadingOrderResolver was run on the original document. */ public Iterable<BxZone> asZones() { return new Iterable<BxZone>() { @Override public Iterator<BxZone> iterator() { List<BxZone> zones = new ArrayList<BxZone>(); for (BxPage page : asPages()) { for (BxZone zone : page) { zones.add(zone); } } return zones.listIterator(); } }; } /** * * @return a list of constituent text lines. The list holds the logical reading-order if * a ReadingOrderResolver was run on the original document. */ public Iterable<BxLine> asLines() { return new Iterable<BxLine>() { @Override public Iterator<BxLine> iterator() { List<BxLine> lines = new ArrayList<BxLine>(); for (BxZone zone : asZones()) { for (BxLine line : zone) { lines.add(line); } } return lines.listIterator(); } }; } /** * * @return a list of constituent words. The list holds the logical reading-order if * a ReadingOrderResolver was run on the original document. */ public Iterable<BxWord> asWords() { return new Iterable<BxWord>() { @Override public Iterator<BxWord> iterator() { List<BxWord> words = new ArrayList<BxWord>(); for (BxLine line : asLines()) { for (BxWord word : line) { words.add(word); } } return words.listIterator(); } }; } /** * * @return a list of constituent letters. The list holds the logical reading-order if * a ReadingOrderResolver was run on the original document. */ public Iterable<BxChunk> asChunks() { return new Iterable<BxChunk>() { @Override public Iterator<BxChunk> iterator() { List<BxChunk> chunks = new ArrayList<BxChunk>(); for (BxWord word : asWords()) { for (BxChunk chunk : word) { chunks.add(chunk); } } return chunks.listIterator(); } }; } public Iterable<BxImage> asImages() { return new Iterable<BxImage>() { @Override public Iterator<BxImage> iterator() { List<BxImage> images = new ArrayList<BxImage>(); for (BxPage page : asPages()) { images.addAll(page.getImages()); } return images.listIterator(); } }; } @Override public String getMostPopularFontName() { CountMap<String> map = new CountMap<String>(); for (BxChunk chunk : asChunks()) { if (chunk.getFontName() != null) { map.add(chunk.getFontName()); } } return map.getMaxCountObject(); } @Override public Set<String> getFontNames() { Set<String> names = new HashSet<String>(); for (BxPage page : pages) { names.addAll(page.getFontNames()); } return names; } @Override public Iterator<BxPage> iterator() { return pages.listIterator(); } @Override public int childrenCount() { return pages.size(); } @Override public BxPage getChild(int index) { if (index < 0 || index >= pages.size()) { throw new IndexOutOfBoundsException(); } return pages.get(index); } }
6,670
27.630901
94
java
CERMINE
CERMINE-master/cermine-impl/src/main/java/pl/edu/icm/cermine/structure/model/BxZoneLabelCategory.java
/** * This file is part of CERMINE project. * Copyright (c) 2011-2018 ICM-UW * * CERMINE is free software: you can redistribute it and/or modify * it under the terms of the GNU Affero General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * CERMINE is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU Affero General Public License for more details. * * You should have received a copy of the GNU Affero General Public License * along with CERMINE. If not, see <http://www.gnu.org/licenses/>. */ package pl.edu.icm.cermine.structure.model; /** * Zone label category. * * @author Dominika Tkaczyk (d.tkaczyk@icm.edu.pl) */ public enum BxZoneLabelCategory { /** * Category including all categories - for filtering purposes */ CAT_ALL, /** * General labels. */ CAT_GENERAL, /** * Document's metadata. */ CAT_METADATA, /** * Document's body. */ CAT_BODY, /** * Document's references. */ CAT_REFERENCES, /** * Other stuff left in the document. */ CAT_OTHER, CAT_UNKNOWN, }
1,325
24.5
78
java
CERMINE
CERMINE-master/cermine-impl/src/main/java/pl/edu/icm/cermine/structure/model/BxWord.java
/** * This file is part of CERMINE project. * Copyright (c) 2011-2018 ICM-UW * * CERMINE is free software: you can redistribute it and/or modify * it under the terms of the GNU Affero General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * CERMINE is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU Affero General Public License for more details. * * You should have received a copy of the GNU Affero General Public License * along with CERMINE. If not, see <http://www.gnu.org/licenses/>. */ package pl.edu.icm.cermine.structure.model; import java.util.*; import pl.edu.icm.cermine.tools.CountMap; /** * Models a word containing text chunks. * * @author Dominika Tkaczyk (d.tkaczyk@icm.edu.pl) */ public class BxWord extends BxObject<BxChunk, BxWord, BxLine> { private static final long serialVersionUID = 2704689342968933369L; /** list of word's chunks */ private final List<BxChunk> chunks = new ArrayList<BxChunk>(); public BxWord setChunks(Collection<BxChunk> chunks) { resetText(); if (chunks != null) { this.chunks.clear(); for (BxChunk chunk : chunks) { addChunk(chunk); } } return this; } public BxWord addChunk(BxChunk chunk) { resetText(); if (chunks != null) { this.chunks.add(chunk); chunk.setParent(this); } return this; } @Override public String getMostPopularFontName() { CountMap<String> map = new CountMap<String>(); for (BxChunk chunk : chunks) { if (chunk.getFontName() != null) { map.add(chunk.getFontName()); } } return map.getMaxCountObject(); } @Override public Set<String> getFontNames() { Set<String> names = new HashSet<String>(); for (BxChunk chunk : chunks) { if (chunk.getFontName() != null) { names.add(chunk.getFontName()); } } return names; } @Override public String toText() { if (getText() == null) { StringBuilder sb = new StringBuilder(); for (BxChunk ch : chunks) { sb.append(ch.getText()); } setText(sb.toString()); } return getText(); } @Override public Iterator<BxChunk> iterator() { return chunks.listIterator(); } @Override public int childrenCount() { return chunks.size(); } @Override public BxChunk getChild(int index) { if (index < 0 || index >= chunks.size()) { throw new IndexOutOfBoundsException(); } return chunks.get(index); } }
2,975
26.302752
78
java
CERMINE
CERMINE-master/cermine-impl/src/main/java/pl/edu/icm/cermine/structure/model/BxImage.java
/** * This file is part of CERMINE project. * Copyright (c) 2011-2018 ICM-UW * * CERMINE is free software: you can redistribute it and/or modify * it under the terms of the GNU Affero General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * CERMINE is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU Affero General Public License for more details. * * You should have received a copy of the GNU Affero General Public License * along with CERMINE. If not, see <http://www.gnu.org/licenses/>. */ package pl.edu.icm.cermine.structure.model; import java.awt.image.BufferedImage; import java.nio.file.Paths; /** * Models an image. * * @author Dominika Tkaczyk (d.tkaczyk@icm.edu.pl) */ public class BxImage { private String prefix; private final String filename; private final BufferedImage image; private final float x; private final float y; public BxImage(String filename, BufferedImage image, float x, float y) { this.filename = filename; this.image = image; this.x = x; this.y = y; } public BufferedImage getImage() { return image; } public String getFilename() { return filename; } public String getPath() { if (prefix == null) { return filename; } return Paths.get(prefix, filename).toString(); } public void setPrefix(String prefix) { this.prefix = prefix; } public float getX() { return x; } public float getY() { return y; } }
1,791
22.578947
78
java
CERMINE
CERMINE-master/cermine-impl/src/main/java/pl/edu/icm/cermine/structure/model/BxPage.java
/** * This file is part of CERMINE project. * Copyright (c) 2011-2018 ICM-UW * * CERMINE is free software: you can redistribute it and/or modify * it under the terms of the GNU Affero General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * CERMINE is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU Affero General Public License for more details. * * You should have received a copy of the GNU Affero General Public License * along with CERMINE. If not, see <http://www.gnu.org/licenses/>. */ package pl.edu.icm.cermine.structure.model; import java.util.*; import pl.edu.icm.cermine.tools.CountMap; /** * Models a single page of a document. A page is either segmented (divided into zones) * or not segmented (containing a list of chunks that haven't been grouped into zones yet). * * @author Dominika Tkaczyk (d.tkaczyk@icm.edu.pl) */ public final class BxPage extends BxObject<BxZone, BxPage, BxDocument> { private static final long serialVersionUID = 8981043716257046347L; /** list of page's zones (if the page is segmented) */ private final List<BxZone> zones = new ArrayList<BxZone>(); /** list of page's text chunks (if the page is not segmented) */ private final List<BxChunk> chunks = new ArrayList<BxChunk>(); private final List<BxImage> images = new ArrayList<BxImage>(); public BxPage setZones(Collection<BxZone> zones) { resetText(); if (zones != null) { this.zones.clear(); for (BxZone zone : zones) { addZone(zone); } } return this; } public BxPage addZone(BxZone zone) { resetText(); if (zone != null) { this.zones.add(zone); zone.setParent(this); } return this; } public Iterator<BxChunk> getChunks() { return chunks.listIterator(); } public BxPage setChunks(Collection<BxChunk> chunks) { resetText(); if (chunks != null) { this.chunks.clear(); this.chunks.addAll(chunks); } return this; } public BxPage addChunk(BxChunk chunk) { resetText(); if (chunk != null) { this.chunks.add(chunk); } return this; } public BxPage addImage(BxImage image) { images.add(image); return this; } public BxPage addImages(Collection<BxImage> image) { images.addAll(image); return this; } public List<BxImage> getImages() { return images; } @Override public String getMostPopularFontName() { CountMap<String> map = new CountMap<String>(); for (BxZone zone : zones) { for (BxLine line : zone) { for (BxWord word : line) { for (BxChunk chunk : word) { if (chunk.getFontName() != null) { map.add(chunk.getFontName()); } } } } } return map.getMaxCountObject(); } @Override public Set<String> getFontNames() { Set<String> names = new HashSet<String>(); for (BxZone zone : zones) { names.addAll(zone.getFontNames()); } return names; } @Override public String toText() { if (getText() == null) { StringBuilder sb = new StringBuilder(); boolean first = true; for (BxZone w : zones) { if (!first) { sb.append("\n"); } first = false; sb.append(w.toText()); } setText(sb.toString()); } return getText(); } @Override public Iterator<BxZone> iterator() { return zones.listIterator(); } @Override public int childrenCount() { return zones.size(); } @Override public BxZone getChild(int index) { if (index < 0 || index >= zones.size()) { throw new IndexOutOfBoundsException(); } return zones.get(index); } }
4,400
26.679245
91
java
CERMINE
CERMINE-master/cermine-impl/src/main/java/pl/edu/icm/cermine/structure/model/BxLine.java
/** * This file is part of CERMINE project. * Copyright (c) 2011-2018 ICM-UW * * CERMINE is free software: you can redistribute it and/or modify * it under the terms of the GNU Affero General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * CERMINE is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU Affero General Public License for more details. * * You should have received a copy of the GNU Affero General Public License * along with CERMINE. If not, see <http://www.gnu.org/licenses/>. */ package pl.edu.icm.cermine.structure.model; import java.util.*; import pl.edu.icm.cermine.tools.CountMap; /** * Models a single line of text containing words. * * @author Dominika Tkaczyk (d.tkaczyk@icm.edu.pl) */ public class BxLine extends BxObject<BxWord, BxLine, BxZone> { private static final long serialVersionUID = 917352034911588106L; /** list of line's words */ private final List<BxWord> words = new ArrayList<BxWord>(); @Override public BxLine setBounds(BxBounds bounds) { super.setBounds(bounds); return this; } public BxLine setWords(Collection<BxWord> words) { resetText(); if (words != null) { this.words.clear(); for (BxWord word : words) { addWord(word); } } return this; } public BxLine addWord(BxWord word) { resetText(); if (word != null) { this.words.add(word); word.setParent(this); } return this; } @Override public String getMostPopularFontName() { CountMap<String> map = new CountMap<String>(); for (BxWord word : words) { for (BxChunk chunk : word) { if (chunk.getFontName() != null) { map.add(chunk.getFontName()); } } } return map.getMaxCountObject(); } @Override public Set<String> getFontNames() { Set<String> names = new HashSet<String>(); for (BxWord word : words) { names.addAll(word.getFontNames()); } return names; } @Override public String toText() { if (getText() == null) { StringBuilder sb = new StringBuilder(); boolean first = true; for (BxWord w : words) { if (!first) { sb.append(" "); } first = false; sb.append(w.toText()); } setText(sb.toString()); } return getText(); } @Override public Iterator<BxWord> iterator() { return words.listIterator(); } @Override public int childrenCount() { return words.size(); } @Override public BxWord getChild(int index) { if (index < 0 || index >= words.size()) { throw new IndexOutOfBoundsException(); } return words.get(index); } }
3,212
26
78
java
CERMINE
CERMINE-master/cermine-impl/src/main/java/pl/edu/icm/cermine/structure/model/BxObject.java
/** * This file is part of CERMINE project. * Copyright (c) 2011-2018 ICM-UW * * CERMINE is free software: you can redistribute it and/or modify * it under the terms of the GNU Affero General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * CERMINE is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU Affero General Public License for more details. * * You should have received a copy of the GNU Affero General Public License * along with CERMINE. If not, see <http://www.gnu.org/licenses/>. */ package pl.edu.icm.cermine.structure.model; import java.io.Serializable; import java.util.Iterator; import java.util.Set; /** * Common class for all Bx* classes having physical properties (this is to say * BxBounds). * * @param <C> child type * @param <T> the actual type * @param <P> parent type (e.g. BxPage for BxZone) * * @author Dominika Tkaczyk (d.tkaczyk@icm.edu.pl) * @author Pawel Szostek */ public abstract class BxObject <C, T, P> implements Indexable<T>, Iterable<C>, Printable, Serializable { /** zone's bounding box */ private BxBounds bounds; /** page number in the document */ private String objId; /** number of the next page from the sequence */ private String nextObjId; /** next page in the linked list of pages. Stored in the logical reading order */ private T nextObj; private T prevObj; private P parent; private String text; public void setParent(P parent) { this.parent = parent; } public P getParent() { return parent; } @Override public abstract Iterator<C> iterator(); public boolean hasChildren() { return iterator().hasNext(); } public abstract int childrenCount(); public C getFirstChild() { Iterator<C> it = iterator(); return it.hasNext() ? it.next() : null; } public abstract C getChild(int index); @Override public void setId(String objId) { this.objId = objId; } @Override public String getId() { return this.objId; } @Override public void setNextId(String nextObjId) { this.nextObjId = nextObjId; } @Override public String getNextId() { return this.nextObjId; } @Override public void setNext(T nextObj) { this.nextObj = nextObj; } @Override public T getNext() { return this.nextObj; } @Override public boolean hasNext() { return getNext() != null; } @Override public void setPrev(T prevObj) { this.prevObj = prevObj; } @Override public T getPrev() { return this.prevObj; } @Override public boolean hasPrev() { return getPrev() != null; } public double getArea() { return (bounds.getHeight() * bounds.getWidth()); } public BxBounds getBounds() { return bounds; } public T setBounds(BxBounds bounds) { this.bounds = bounds; return (T)this; } public double getX() { return bounds.getX(); } public double getY() { return bounds.getY(); } public double getWidth() { return bounds.getWidth(); } public double getHeight() { return bounds.getHeight(); } protected String getText() { return text; } protected void setText(String text) { this.text = text; } public void resetText() { this.text = null; } public abstract String getMostPopularFontName(); public abstract Set<String> getFontNames(); }
3,832
20.655367
104
java
CERMINE
CERMINE-master/cermine-impl/src/main/java/pl/edu/icm/cermine/structure/model/Printable.java
/** * This file is part of CERMINE project. * Copyright (c) 2011-2018 ICM-UW * * CERMINE is free software: you can redistribute it and/or modify * it under the terms of the GNU Affero General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * CERMINE is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU Affero General Public License for more details. * * You should have received a copy of the GNU Affero General Public License * along with CERMINE. If not, see <http://www.gnu.org/licenses/>. */ package pl.edu.icm.cermine.structure.model; /** * @author Pawel Szostek */ public interface Printable { String toText(); }
868
30.035714
78
java
CERMINE
CERMINE-master/cermine-impl/src/main/java/pl/edu/icm/cermine/structure/transformers/TrueVizToBxDocumentReader.java
/** * This file is part of CERMINE project. * Copyright (c) 2011-2018 ICM-UW * * CERMINE is free software: you can redistribute it and/or modify * it under the terms of the GNU Affero General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * CERMINE is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU Affero General Public License for more details. * * You should have received a copy of the GNU Affero General Public License * along with CERMINE. If not, see <http://www.gnu.org/licenses/>. */ package pl.edu.icm.cermine.structure.transformers; import com.google.common.collect.Lists; import java.io.IOException; import java.io.Reader; import java.io.StringReader; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.Locale; import java.util.Map; import javax.xml.parsers.ParserConfigurationException; import org.w3c.dom.Document; import org.w3c.dom.Element; import org.w3c.dom.Node; import org.w3c.dom.NodeList; import org.xml.sax.InputSource; import org.xml.sax.SAXException; import pl.edu.icm.cermine.exception.TransformationException; import pl.edu.icm.cermine.structure.model.*; import pl.edu.icm.cermine.structure.tools.BxBoundsBuilder; import pl.edu.icm.cermine.structure.tools.BxModelUtils; /** * Reads BxDocument model pages from TrueViz format. * * @author Kuba Jurkiewicz * @author Krzysztof Rusek * @author Pawel Szostek */ public class TrueVizToBxDocumentReader { //set while parsing xml private boolean areIdsSet; public static final Map<String, BxZoneLabel> ZONE_LABEL_MAP = new HashMap<String, BxZoneLabel>(); static { ZONE_LABEL_MAP.put("abstract", BxZoneLabel.MET_ABSTRACT); ZONE_LABEL_MAP.put("access_data", BxZoneLabel.MET_ACCESS_DATA); ZONE_LABEL_MAP.put("acknowledgment", BxZoneLabel.BODY_ACKNOWLEDGMENT); ZONE_LABEL_MAP.put("affiliation", BxZoneLabel.MET_AFFILIATION); ZONE_LABEL_MAP.put("attachment", BxZoneLabel.BODY_ATTACHMENT); ZONE_LABEL_MAP.put("author", BxZoneLabel.MET_AUTHOR); ZONE_LABEL_MAP.put("author_title", BxZoneLabel.MET_TITLE); ZONE_LABEL_MAP.put("bib_info", BxZoneLabel.MET_BIB_INFO); ZONE_LABEL_MAP.put("biography", BxZoneLabel.MET_BIOGRAPHY); ZONE_LABEL_MAP.put("body", BxZoneLabel.BODY_CONTENT); ZONE_LABEL_MAP.put("body_content", BxZoneLabel.BODY_CONTENT); ZONE_LABEL_MAP.put("category", BxZoneLabel.MET_CATEGORY); ZONE_LABEL_MAP.put("contribution", BxZoneLabel.BODY_CONTRIBUTION); ZONE_LABEL_MAP.put("conflict_statement", BxZoneLabel.BODY_CONFLICT_STMT); ZONE_LABEL_MAP.put("copyright", BxZoneLabel.MET_COPYRIGHT); ZONE_LABEL_MAP.put("correspondence", BxZoneLabel.MET_CORRESPONDENCE); ZONE_LABEL_MAP.put("dates", BxZoneLabel.MET_DATES); ZONE_LABEL_MAP.put("editor", BxZoneLabel.MET_EDITOR); ZONE_LABEL_MAP.put("equation", BxZoneLabel.BODY_EQUATION); ZONE_LABEL_MAP.put("equation_label", BxZoneLabel.BODY_EQUATION_LABEL); ZONE_LABEL_MAP.put("figure", BxZoneLabel.BODY_FIGURE); ZONE_LABEL_MAP.put("figure_caption", BxZoneLabel.BODY_FIGURE_CAPTION); ZONE_LABEL_MAP.put("glossary", BxZoneLabel.BODY_GLOSSARY); ZONE_LABEL_MAP.put("junk", BxZoneLabel.BODY_JUNK); ZONE_LABEL_MAP.put("heading", BxZoneLabel.BODY_HEADING); ZONE_LABEL_MAP.put("keywords", BxZoneLabel.MET_KEYWORDS); ZONE_LABEL_MAP.put("page_number", BxZoneLabel.OTH_PAGE_NUMBER); ZONE_LABEL_MAP.put("references", BxZoneLabel.REFERENCES); ZONE_LABEL_MAP.put("table", BxZoneLabel.BODY_TABLE); ZONE_LABEL_MAP.put("table_caption", BxZoneLabel.BODY_TABLE_CAPTION); ZONE_LABEL_MAP.put("terms", BxZoneLabel.MET_TERMS); ZONE_LABEL_MAP.put("title", BxZoneLabel.MET_TITLE); ZONE_LABEL_MAP.put("type", BxZoneLabel.MET_TYPE); ZONE_LABEL_MAP.put("unknown", BxZoneLabel.OTH_UNKNOWN); } public List<BxPage> read(String string, Object... hints) throws TransformationException { return read(new StringReader(string), hints); } public List<BxPage> read(Reader reader, Object... hints) throws TransformationException { try { areIdsSet = true; Document doc = TrueVizUtils.newDocumentBuilder().parse(new InputSource(reader)); List<BxPage> pages = new ArrayList<BxPage>(); if ("Page".equalsIgnoreCase(doc.getDocumentElement().getTagName())) { pages.add(parsePageNode(doc.getDocumentElement())); } else if ("Document".equalsIgnoreCase(doc.getDocumentElement().getTagName())) { for (Element pageElement : getChildren("Page", doc.getDocumentElement())) { BxPage page = parsePageNode(pageElement); pages.add(page); } } setIdsAndLinkPages(pages); if (areIdsSet) { linkAndReorderOtherElements(pages); } for (BxPage page : pages) { BxModelUtils.setParents(page); } return pages; } catch (IOException ex) { System.err.println(ex.getMessage()); throw new TransformationException(ex); } catch (ParserConfigurationException ex) { System.err.println(ex.getMessage()); throw new TransformationException(ex); } catch (SAXException ex) { System.err.println(ex.getMessage()); throw new TransformationException(ex); } } protected <A extends Indexable<A>> List<A> reorderList(List<A> list) { if (list.isEmpty()) { return list; } Map<String, A> elems = new HashMap<String, A>(); List<A> ordered = new ArrayList<A>(list.size()); for (A elem : list) { elems.put(elem.getId(), elem); } A start = null; for (A elem : list) { if (elem.getPrev() == null) {//first element at all start = elem; break; } } //maybe we are somewhere in the middle of the document if(start == null) { for(A elem : list) { if (!elems.keySet().contains(elem.getPrev().getId())) { start = elem; break; } } } //there is not previous element.. if (start == null) { for(A elem : list) { System.out.println(elem.getPrev()); } throw new IllegalStateException("Start element not found"); } do { ordered.add(start); if (!start.hasNext()) { //last element at all break; } start = start.getNext(); } while (elems.keySet().contains(start.getId())); if (ordered.size() != list.size()) { throw new IllegalStateException("Output list size doesn't match the input one: " + ordered.size() + " " + list.size()); } return ordered; } /** * A generic function for linking objects together (setting *Next and *Prev) It is a assumed, that all Id's and * NextId's are set before. * * @param list is a list of elements to be connected */ private <A extends Indexable<A>> void linkGenericImpl(List<A> list) { Map<String, A> indicesMap = new HashMap<String, A>(); for (A elem : list) { indicesMap.put(elem.getId(), elem); } for (A elem : list) { String nextId = elem.getNextId(); if (nextId.equals("-1") || list.indexOf(elem) == list.size()-1) { /* * there is no next element */ elem.setNext(null); } else { A next = indicesMap.get(nextId); if (next == null) { throw new RuntimeException("No matching element found for \"" + nextId + "\""); } //link with the next element elem.setNext(next); //link with the previous element next.setPrev(elem); } } } /* * assumes that nextIds are set for all objects */ private void linkAndReorderOtherElements(List<BxPage> pages) { BxDocument temp = new BxDocument(); temp.setPages(pages); linkGenericImpl(Lists.newArrayList(temp.asZones())); linkGenericImpl(Lists.newArrayList(temp.asLines())); linkGenericImpl(Lists.newArrayList(temp.asWords())); linkGenericImpl(Lists.newArrayList(temp.asChunks())); for (BxPage page : pages) { for (BxZone zone : page) { for (BxLine line : zone) { for (BxWord word : line) { word.setChunks(reorderList(Lists.newArrayList(word))); } line.setWords(reorderList(Lists.newArrayList(line))); } zone.setLines(reorderList(Lists.newArrayList(zone))); } page.setZones(reorderList(Lists.newArrayList(page))); } } private void setIdsAndLinkPages(List<BxPage> pages) { if (pages.isEmpty()) { return; } if (pages.size() == 1) { BxPage page = pages.get(0); page.setId("0"); page.setNextId("-1"); page.setNext(null); page.setPrev(null); return; } boolean arePageIdsSet = true; for (BxPage page : pages) { if (page.getNextId() == null || page.getId() == null) { arePageIdsSet = false; break; } } if (arePageIdsSet) { /* * Page IDs were set in the input file */ linkGenericImpl(pages); } else { /* * Page IDs were not set. We have to do it on our own */ Integer idx; for (idx = 0; idx < pages.size() - 1; ++idx) { pages.get(idx).setId(Integer.toString(idx)); pages.get(idx).setNextId(Integer.toString(idx + 1)); } pages.get(pages.size() - 1).setId(Integer.toString(idx)); pages.get(pages.size() - 1).setNextId("-1"); linkGenericImpl(pages); } } private List<Element> getChildren(String name, Element el) { ArrayList<Element> list = new ArrayList<Element>(); NodeList nl = el.getChildNodes(); for (int i = 0; i < nl.getLength(); i++) { Node n = nl.item(i); if (n instanceof Element) { Element e = (Element) n; if (e.getTagName().equalsIgnoreCase(name)) { list.add(e); } } } return list; } /** * Function for obtaining value for optional children (that can appear in the XML, but doesn't have to). * * @param name is a name of the node * @param el is the root node for the child * @return value of the child, if present and not empty. Otherwise equals to null */ private String getOptionalChildValue(String name, Element el) { List<Element> children = getChildren(name, el); if (!children.isEmpty()) { String val = children.get(0).getAttribute("Value"); if (val.equals("")) { return null; } else { return val; } } else { return null; } } private BxBounds parseElementContainingVertexes(Element el) { List<Element> vs = getChildren("Vertex", el); BxBoundsBuilder builder = new BxBoundsBuilder(); for (Element v : vs) { double x = Double.parseDouble(v.getAttribute("x")); double y = Double.parseDouble(v.getAttribute("y")); builder.expand(x, y); } return builder.getBounds(); } private BxChunk parseCharacterElement(Element charE) { BxBounds bou = null; String text = null; if (!getChildren("CharacterCorners", charE).isEmpty()) { bou = (parseElementContainingVertexes(getChildren("CharacterCorners", charE).get(0))); } if (!(getChildren("GT_Text", charE).isEmpty())) { text = getChildren("GT_Text", charE).get(0).getAttribute("Value"); } BxChunk chunk = new BxChunk(bou, text); chunk.setId(getOptionalChildValue("CharacterId", charE)); chunk.setNextId(getOptionalChildValue("CharacterNext", charE)); List<Element> fonts = getChildren("Font", charE); if (!fonts.isEmpty()) { chunk.setFontName(fonts.get(0).getAttribute("Type")); } if (areIdsSet && (chunk.getId() == null || chunk.getNextId() == null)) { areIdsSet = false; } return chunk; } private BxWord parseWordElement(Element wordE) { BxWord word = new BxWord(); if (!(getChildren("WordCorners", wordE).isEmpty())) { word.setBounds(parseElementContainingVertexes(getChildren("WordCorners", wordE).get(0))); } word.setId(getOptionalChildValue("WordId", wordE)); word.setNextId(getOptionalChildValue("WordNext", wordE)); if (areIdsSet && (word.getId() == null || word.getNextId() == null)) { areIdsSet = false; } List<Element> e = getChildren("Character", wordE); for (Element caE : e) { BxChunk ch = parseCharacterElement(caE); ch.setParent(word); word.addChunk(ch); } return word; } private BxLine parseLineElement(Element lineE) { BxLine line = new BxLine(); if (!(getChildren("LineCorners", lineE).isEmpty())) { line.setBounds(parseElementContainingVertexes(getChildren("LineCorners", lineE).get(0))); } line.setId(getOptionalChildValue("LineId", lineE)); line.setNextId(getOptionalChildValue("LineNext", lineE)); if (areIdsSet && (line.getId() == null || line.getNextId() == null)) { areIdsSet = false; } List<Element> e = getChildren("Word", lineE); for (Element we : e) { BxWord wo = parseWordElement(we); wo.setParent(line); line.addWord(wo); } return line; } private BxZoneLabel parseClassification(Element elClassicfication) throws TransformationException { List<Element> eli = getChildren("Category", elClassicfication); Element catEl = eli.isEmpty() ? null : eli.get(0); if (catEl == null) { eli = getChildren("Type", elClassicfication); catEl = eli.isEmpty() ? null : eli.get(0); } if (catEl == null) { return null; } String val = catEl.getAttribute("Value"); if (val.isEmpty()) { return null; } if (val.isEmpty()) { return BxZoneLabel.OTH_UNKNOWN; } if (ZONE_LABEL_MAP.containsKey(val.toLowerCase(Locale.ENGLISH))) { return ZONE_LABEL_MAP.get(val.toLowerCase(Locale.ENGLISH)); } else { return BxZoneLabel.valueOf(val.toUpperCase(Locale.ENGLISH)); } } private BxZone parseZoneNode(Element zoneE) throws TransformationException { BxZone zone = new BxZone(); zone.setLabel(BxZoneLabel.OTH_UNKNOWN); if (!getChildren("Classification", zoneE).isEmpty()) { zone.setLabel(parseClassification(getChildren("Classification", zoneE).get(0))); } if (!getChildren("ZoneCorners", zoneE).isEmpty()) { zone.setBounds(parseElementContainingVertexes(getChildren("ZoneCorners", zoneE).get(0))); } zone.setId(getOptionalChildValue("ZoneId", zoneE)); zone.setNextId(getOptionalChildValue("ZoneNext", zoneE)); if (areIdsSet && (zone.getId() == null || zone.getNextId() == null)) { areIdsSet = false; } List<Element> e = getChildren("Line", zoneE); for (Element lin : e) { BxLine li = parseLineElement(lin); li.setParent(zone); zone.addLine(li); } return zone; } private BxPage parsePageNode(Element elem) throws TransformationException { BxPage page = new BxPage(); page.setId(getOptionalChildValue("PageId", elem)); page.setNextId(getOptionalChildValue("PageNext", elem)); if (areIdsSet && (page.getId() == null || page.getNextId() == null)) { areIdsSet = false; } List<Element> e = getChildren("Zone", elem); for (Element zo : e) { BxZone zon = parseZoneNode(zo); zon.setParent(page); page.addZone(zon); } BxBoundsBuilder.setBounds(page); return page; } }
17,187
36.528384
131
java
CERMINE
CERMINE-master/cermine-impl/src/main/java/pl/edu/icm/cermine/structure/transformers/BxDocumentToTrueVizWriter.java
/** * This file is part of CERMINE project. * Copyright (c) 2011-2018 ICM-UW * * CERMINE is free software: you can redistribute it and/or modify * it under the terms of the GNU Affero General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * CERMINE is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU Affero General Public License for more details. * * You should have received a copy of the GNU Affero General Public License * along with CERMINE. If not, see <http://www.gnu.org/licenses/>. */ package pl.edu.icm.cermine.structure.transformers; import java.io.StringWriter; import java.io.Writer; import java.text.DecimalFormat; import java.text.DecimalFormatSymbols; import java.util.*; import javax.xml.parsers.ParserConfigurationException; import javax.xml.transform.OutputKeys; import javax.xml.transform.Transformer; import javax.xml.transform.TransformerException; import javax.xml.transform.TransformerFactory; import javax.xml.transform.dom.DOMSource; import javax.xml.transform.stream.StreamResult; import org.w3c.dom.Document; import org.w3c.dom.Element; import pl.edu.icm.cermine.exception.TransformationException; import pl.edu.icm.cermine.structure.model.*; /** * Writes BxDocument model pages to TrueViz format. * * @author Krzysztof Rusek */ public class BxDocumentToTrueVizWriter { public static final String MINIMAL_OUTPUT_SIZE = "MINIMAL_OUTPUT_SIZE"; private static final Properties OUTPUT_PROPERTIES = new Properties(); static { OUTPUT_PROPERTIES.setProperty(OutputKeys.DOCTYPE_SYSTEM, "Trueviz.dtd"); OUTPUT_PROPERTIES.setProperty(OutputKeys.INDENT, "yes"); } public static final Map<BxZoneLabel, String> ZONE_LABEL_MAP = new EnumMap<BxZoneLabel, String>(BxZoneLabel.class); static { ZONE_LABEL_MAP.put(BxZoneLabel.GEN_METADATA, "gen_metadata"); ZONE_LABEL_MAP.put(BxZoneLabel.GEN_BODY, "gen_body"); ZONE_LABEL_MAP.put(BxZoneLabel.GEN_REFERENCES, "gen_references"); ZONE_LABEL_MAP.put(BxZoneLabel.GEN_OTHER, "gen_other"); ZONE_LABEL_MAP.put(BxZoneLabel.MET_ABSTRACT, "abstract"); ZONE_LABEL_MAP.put(BxZoneLabel.MET_AFFILIATION, "affiliation"); ZONE_LABEL_MAP.put(BxZoneLabel.MET_AUTHOR, "author"); ZONE_LABEL_MAP.put(BxZoneLabel.MET_TITLE_AUTHOR, "author_title"); ZONE_LABEL_MAP.put(BxZoneLabel.MET_BIB_INFO, "bib_info"); ZONE_LABEL_MAP.put(BxZoneLabel.MET_BIOGRAPHY, "biography"); ZONE_LABEL_MAP.put(BxZoneLabel.MET_CATEGORY, "category"); ZONE_LABEL_MAP.put(BxZoneLabel.MET_TERMS, "terms"); ZONE_LABEL_MAP.put(BxZoneLabel.MET_CORRESPONDENCE, "correspondence"); ZONE_LABEL_MAP.put(BxZoneLabel.MET_ACCESS_DATA, "access_data"); ZONE_LABEL_MAP.put(BxZoneLabel.MET_DATES, "dates"); ZONE_LABEL_MAP.put(BxZoneLabel.MET_EDITOR, "editor"); ZONE_LABEL_MAP.put(BxZoneLabel.MET_KEYWORDS, "keywords"); ZONE_LABEL_MAP.put(BxZoneLabel.MET_TITLE, "title"); ZONE_LABEL_MAP.put(BxZoneLabel.MET_TYPE, "type"); ZONE_LABEL_MAP.put(BxZoneLabel.MET_COPYRIGHT, "copyright"); ZONE_LABEL_MAP.put(BxZoneLabel.BODY_CONTRIBUTION, "contribution"); ZONE_LABEL_MAP.put(BxZoneLabel.BODY_ATTACHMENT, "attachment"); ZONE_LABEL_MAP.put(BxZoneLabel.BODY_ACKNOWLEDGMENT, "acknowledgment"); ZONE_LABEL_MAP.put(BxZoneLabel.BODY_GLOSSARY, "glossary"); ZONE_LABEL_MAP.put(BxZoneLabel.BODY_CONFLICT_STMT, "conflict_statement"); ZONE_LABEL_MAP.put(BxZoneLabel.BODY_CONTENT, "body_content"); ZONE_LABEL_MAP.put(BxZoneLabel.BODY_HEADING, "heading"); ZONE_LABEL_MAP.put(BxZoneLabel.BODY_EQUATION, "equation"); ZONE_LABEL_MAP.put(BxZoneLabel.BODY_EQUATION_LABEL, "equation_label"); ZONE_LABEL_MAP.put(BxZoneLabel.BODY_FIGURE, "figure"); ZONE_LABEL_MAP.put(BxZoneLabel.BODY_FIGURE_CAPTION, "figure_caption"); ZONE_LABEL_MAP.put(BxZoneLabel.BODY_TABLE, "table"); ZONE_LABEL_MAP.put(BxZoneLabel.BODY_TABLE_CAPTION, "table_caption"); ZONE_LABEL_MAP.put(BxZoneLabel.BODY_ATTACHMENT, "attachment"); ZONE_LABEL_MAP.put(BxZoneLabel.BODY_JUNK, "junk"); ZONE_LABEL_MAP.put(BxZoneLabel.OTH_PAGE_NUMBER, "page_number"); ZONE_LABEL_MAP.put(BxZoneLabel.OTH_UNKNOWN , "unknown"); ZONE_LABEL_MAP.put(BxZoneLabel.REFERENCES, "references"); } private void appendProperty(Document doc, Element parent, String name, String value) { Element node = doc.createElement(name); node.setAttribute("Value", value); parent.appendChild(node); } private void appendPropertyIfNotNull(Document doc, Element parent, String name, String value) { if(value == null) { appendProperty(doc, parent, name, ""); } else { appendProperty(doc, parent, name, value); } } private void appendVertex(Document doc, Element parent, double x, double y, Object... hints) { DecimalFormat format = new DecimalFormat("0.000", new DecimalFormatSymbols(Locale.US)); if (Arrays.asList(hints).contains(MINIMAL_OUTPUT_SIZE)) { format = new DecimalFormat("0.0", new DecimalFormatSymbols(Locale.US)); } Element node = doc.createElement("Vertex"); node.setAttribute("x", format.format(x)); node.setAttribute("y", format.format(y)); parent.appendChild(node); } private void appendBounds(Document doc, Element parent, String name, BxBounds bounds, Object... hints) { if (bounds == null) { bounds = new BxBounds(); } Element node = doc.createElement(name); appendVertex(doc, node, bounds.getX(), bounds.getY(), hints); if (!Arrays.asList(hints).contains(MINIMAL_OUTPUT_SIZE)) { appendVertex(doc, node, bounds.getX() + bounds.getWidth(), bounds.getY(), hints); } appendVertex(doc, node, bounds.getX() + bounds.getWidth(), bounds.getY() + bounds.getHeight(), hints); if (!Arrays.asList(hints).contains(MINIMAL_OUTPUT_SIZE)) { appendVertex(doc, node, bounds.getX(), bounds.getY() + bounds.getHeight(), hints); } parent.appendChild(node); } private void appendCharacter(Document doc, Element parent, BxChunk chunk, Object... hints) { Element node = doc.createElement("Character"); appendPropertyIfNotNull(doc, node, "CharacterID", chunk.getId()); appendBounds(doc, node, "CharacterCorners", chunk.getBounds(), hints); appendPropertyIfNotNull(doc, node, "CharacterNext", chunk.getNextId()); Element font = doc.createElement("Font"); font.setAttribute("Size", ""); font.setAttribute("Spacing", ""); font.setAttribute("Style", ""); font.setAttribute("Type", chunk.getFontName()); node.appendChild(font); appendProperty(doc, node, "GT_Text", chunk.toText()); parent.appendChild(node); } private void appendWord(Document doc, Element parent, BxWord word, Object... hints) { Element node = doc.createElement("Word"); appendPropertyIfNotNull(doc, node, "WordID", word.getId()); appendBounds(doc, node, "WordCorners", word.getBounds(), hints); appendPropertyIfNotNull(doc, node, "WordNext", word.getNextId()); appendProperty(doc, node, "WordNumChars", ""); for (BxChunk chunk : word) { appendCharacter(doc, node, chunk, hints); } parent.appendChild(node); } private void appendLine(Document doc, Element parent, BxLine line, Object... hints) { Element node = doc.createElement("Line"); appendPropertyIfNotNull(doc, node, "LineID", line.getId()); appendBounds(doc, node, "LineCorners", line.getBounds(), hints); appendPropertyIfNotNull(doc, node, "LineNext", line.getNextId()); appendProperty(doc, node, "LineNumChars", ""); for (BxWord word : line) { appendWord(doc, node, word, hints); } parent.appendChild(node); } private void appendClassification(Document doc, Element parent, String category, String type) { Element node = doc.createElement("Classification"); appendProperty(doc, node, "Category", category); appendProperty(doc, node, "Type", type); parent.appendChild(node); } private void appendZone(Document doc, Element parent, BxZone zone, Object... hints) throws TransformationException { Element node = doc.createElement("Zone"); appendPropertyIfNotNull(doc, node, "ZoneID", zone.getId()); appendBounds(doc, node, "ZoneCorners", zone.getBounds(), hints); appendPropertyIfNotNull(doc, node, "ZoneNext", zone.getNextId()); Element insetsNode = doc.createElement("ZoneInsets"); insetsNode.setAttribute("Top", ""); insetsNode.setAttribute("Bottom", ""); insetsNode.setAttribute("Left", ""); insetsNode.setAttribute("Right", ""); node.appendChild(insetsNode); appendProperty(doc, node, "ZoneLines", ""); if (zone.getLabel() != null) { if (ZONE_LABEL_MAP.get(zone.getLabel()) != null && !ZONE_LABEL_MAP.get(zone.getLabel()).isEmpty()) { appendClassification(doc, node, ZONE_LABEL_MAP.get(zone.getLabel()).toUpperCase(Locale.ENGLISH), ""); } else { throw new TransformationException("Writing down an unknown zone label: " + zone.getLabel()); } } for (BxLine line : zone) { appendLine(doc, node, line, hints); } parent.appendChild(node); } private void appendPage(Document doc, Element parent, BxPage page, Object... hints) throws TransformationException { Element node = doc.createElement("Page"); appendPropertyIfNotNull(doc, node, "PageID", page.getId()); appendProperty(doc, node, "PageType", ""); appendProperty(doc, node, "PageNumber", ""); appendProperty(doc, node, "PageColumns", ""); appendPropertyIfNotNull(doc, node, "PageNext", page.getNextId()); appendProperty(doc, node, "PageZones", ""); for (BxZone zone : page) { appendZone(doc, node, zone, hints); } parent.appendChild(node); } private void appendLanguage(Document doc, Element parent, String type, String script, String codeset) { Element node = doc.createElement("Language"); node.setAttribute("Type", type); node.setAttribute("Script", script); node.setAttribute("Codeset", codeset); parent.appendChild(node); } private void appendFont(Document doc, Element parent, String type, String style, String spacing, String size) { Element node = doc.createElement("Font"); node.setAttribute("Type", type); node.setAttribute("Style", style); node.setAttribute("Spacing", spacing); node.setAttribute("Size", size); parent.appendChild(node); } private Document createDocument(List<BxPage> pages, Object... hints) throws ParserConfigurationException, TransformationException { Document doc = TrueVizUtils.newDocumentBuilder().newDocument(); Element root = doc.createElement("Document"); appendProperty(doc, root, "DocID", ""); appendProperty(doc, root, "DocTitle", ""); appendProperty(doc, root, "DocPubName", ""); appendProperty(doc, root, "DocVolNum", ""); appendProperty(doc, root, "DocIssueNum", ""); appendProperty(doc, root, "DocMargins", ""); appendProperty(doc, root, "DocDate", ""); appendProperty(doc, root, "DocPages", ""); Element imageNode = doc.createElement("DocImage"); appendProperty(doc, imageNode, "Name", ""); appendProperty(doc, imageNode, "Format", ""); appendProperty(doc, imageNode, "Depth", ""); appendProperty(doc, imageNode, "Compression", ""); appendProperty(doc, imageNode, "Capture", ""); appendProperty(doc, imageNode, "Quality", ""); root.appendChild(imageNode); appendLanguage(doc, root, "", "", ""); appendFont(doc, root, "", "", "", ""); appendProperty(doc, root, "ReadingDir", ""); appendProperty(doc, root, "CharOrient", ""); appendClassification(doc, root, "", ""); appendProperty(doc, root, "GT_Text", ""); for (BxPage page: pages) { appendPage(doc, root, page, hints); } doc.appendChild(root); return doc; } public String write(List<BxPage> objects, Object... hints) throws TransformationException { StringWriter sw = new StringWriter(); write(sw, objects, hints); sw.flush(); return sw.toString(); } public void write(Writer writer, List<BxPage> objects, Object... hints) throws TransformationException { try { Document doc = createDocument(objects, hints); Transformer t = TransformerFactory.newInstance().newTransformer(); t.setOutputProperties(OUTPUT_PROPERTIES); t.transform(new DOMSource(doc), new StreamResult(writer)); } catch (TransformerException ex) { throw new TransformationException(ex); } catch (ParserConfigurationException ex) { throw new TransformationException(ex); } } }
13,921
46.515358
135
java
CERMINE
CERMINE-master/cermine-impl/src/main/java/pl/edu/icm/cermine/structure/transformers/TrueVizUtils.java
/** * This file is part of CERMINE project. * Copyright (c) 2011-2018 ICM-UW * * CERMINE is free software: you can redistribute it and/or modify * it under the terms of the GNU Affero General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * CERMINE is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU Affero General Public License for more details. * * You should have received a copy of the GNU Affero General Public License * along with CERMINE. If not, see <http://www.gnu.org/licenses/>. */ package pl.edu.icm.cermine.structure.transformers; import javax.xml.parsers.DocumentBuilder; import javax.xml.parsers.DocumentBuilderFactory; import javax.xml.parsers.ParserConfigurationException; import org.xml.sax.EntityResolver; import org.xml.sax.InputSource; import org.xml.sax.SAXException; /** * Contains utility methods/formats for manipulating TrueViz/Marg documents. * * @author Krzysztof Rusek */ public final class TrueVizUtils { private static final String TRUEVIZ_DTD = "pl/edu/icm/cermine/structure/imports/Trueviz.dtd"; /** * Returns new document builder for creating/parsing TrueViz/Marg documents. * @return DocumentBuilder * @throws ParserConfigurationException ParserConfigurationException */ public static DocumentBuilder newDocumentBuilder() throws ParserConfigurationException { return newDocumentBuilder(false); } /** * Returns new document builder for creating/parsing TrueViz/Marg documents. * @param validating true if the builder produced will validate documents * as they are parsed; false otherwise * @return DocumentBuilder * @throws ParserConfigurationException ParserConfigurationException */ public static DocumentBuilder newDocumentBuilder(boolean validating) throws ParserConfigurationException { DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance(); factory.setValidating(validating); DocumentBuilder builder = factory.newDocumentBuilder(); builder.setEntityResolver(new EntityResolver() { @Override public InputSource resolveEntity(String publicID, String systemID) throws SAXException { if (systemID != null && systemID.endsWith("/Trueviz.dtd")) { return new InputSource(TrueVizUtils.class.getClassLoader().getResourceAsStream(TRUEVIZ_DTD)); } // If no match, returning null makes process continue normally return null; } }); return builder; } private TrueVizUtils() {} }
2,839
37.378378
113
java
CERMINE
CERMINE-master/cermine-impl/src/main/java/pl/edu/icm/cermine/exception/TransformationException.java
/** * This file is part of CERMINE project. * Copyright (c) 2011-2018 ICM-UW * * CERMINE is free software: you can redistribute it and/or modify * it under the terms of the GNU Affero General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * CERMINE is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU Affero General Public License for more details. * * You should have received a copy of the GNU Affero General Public License * along with CERMINE. If not, see <http://www.gnu.org/licenses/>. */ package pl.edu.icm.cermine.exception; /** * Thrown when an unrecoverable problem occurs during transformations. * * @author Dominika Tkaczyk (d.tkaczyk@icm.edu.pl) */ public class TransformationException extends Exception { private static final long serialVersionUID = -4871017514024156616L; public TransformationException() { super(); } public TransformationException(String message, Throwable cause) { super(message, cause); } public TransformationException(String message) { super(message); } public TransformationException(Throwable cause) { super(cause); } }
1,378
29.644444
78
java
CERMINE
CERMINE-master/cermine-impl/src/main/java/pl/edu/icm/cermine/exception/AnalysisException.java
/** * This file is part of CERMINE project. * Copyright (c) 2011-2018 ICM-UW * * CERMINE is free software: you can redistribute it and/or modify * it under the terms of the GNU Affero General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * CERMINE is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU Affero General Public License for more details. * * You should have received a copy of the GNU Affero General Public License * along with CERMINE. If not, see <http://www.gnu.org/licenses/>. */ package pl.edu.icm.cermine.exception; /** * Thrown when an unrecoverable problem occurs during analysis. * * @author Lukasz Bolikowski (bolo@icm.edu.pl) */ public class AnalysisException extends Exception { private static final long serialVersionUID = 4601197315845837554L; public AnalysisException() { super(); } public AnalysisException(String message, Throwable cause) { super(message, cause); } public AnalysisException(String message) { super(message); } public AnalysisException(Throwable cause) { super(cause); } }
1,336
28.711111
78
java
CERMINE
CERMINE-master/cermine-impl/src/main/java/pl/edu/icm/cermine/parsing/tools/TextTokenizer.java
/** * This file is part of CERMINE project. * Copyright (c) 2011-2018 ICM-UW * * CERMINE is free software: you can redistribute it and/or modify * it under the terms of the GNU Affero General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * CERMINE is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU Affero General Public License for more details. * * You should have received a copy of the GNU Affero General Public License * along with CERMINE. If not, see <http://www.gnu.org/licenses/>. */ package pl.edu.icm.cermine.parsing.tools; import java.util.List; import pl.edu.icm.cermine.parsing.model.Token; /** * Text tokenizer. * * @author Bartosz Tarnawski * @param <T> token type */ public interface TextTokenizer<T extends Token<?>> { /** * @param text text * @return list of tokens, a sequence of atomic parts of the text */ List<T> tokenize(String text); }
1,135
29.702703
78
java
CERMINE
CERMINE-master/cermine-impl/src/main/java/pl/edu/icm/cermine/parsing/tools/FeatureExtractor.java
/** * This file is part of CERMINE project. * Copyright (c) 2011-2018 ICM-UW * * CERMINE is free software: you can redistribute it and/or modify * it under the terms of the GNU Affero General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * CERMINE is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU Affero General Public License for more details. * * You should have received a copy of the GNU Affero General Public License * along with CERMINE. If not, see <http://www.gnu.org/licenses/>. */ package pl.edu.icm.cermine.parsing.tools; import pl.edu.icm.cermine.parsing.model.ParsableString; /** * Finds features of tokens in a tokenized parsable string. * * @author Bartosz Tarnawski * @param <PS> type of the parsable string to process */ public interface FeatureExtractor<PS extends ParsableString<?>> { /** * Adds appropriate strings representing features to the tokens of the * parsable string. * * @param parsableString the tokenized parsable string to be processed */ void calculateFeatures(PS parsableString); }
1,303
33.315789
78
java
CERMINE
CERMINE-master/cermine-impl/src/main/java/pl/edu/icm/cermine/parsing/tools/NLMParsableStringExtractor.java
/** * This file is part of CERMINE project. * Copyright (c) 2011-2018 ICM-UW * * CERMINE is free software: you can redistribute it and/or modify * it under the terms of the GNU Affero General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * CERMINE is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU Affero General Public License for more details. * * You should have received a copy of the GNU Affero General Public License * along with CERMINE. If not, see <http://www.gnu.org/licenses/>. */ package pl.edu.icm.cermine.parsing.tools; import java.io.IOException; import java.util.ArrayList; import java.util.Iterator; import java.util.List; import java.util.Map; import org.jdom.Document; import org.jdom.Element; import org.jdom.JDOMException; import org.jdom.Text; import org.jdom.filter.Filter; import org.jdom.input.SAXBuilder; import org.xml.sax.InputSource; import pl.edu.icm.cermine.parsing.model.ParsableString; import pl.edu.icm.cermine.parsing.model.Token; /** * Generic extractor, which transform NLM XML's into the parsable string * representation. * * @author Dominika Tkaczyk (d.tkaczyk@icm.edu.pl) * @author Bartosz Tarnawski * * @param <L> label type * @param <T> token type * @param <P> parsable string type */ public abstract class NLMParsableStringExtractor<L, T extends Token<L>, P extends ParsableString<T>> { protected abstract List<String> getTags(); protected abstract String getKeyText(); protected abstract Map<String, L> getTagLabelMap(); protected abstract P createParsableString(); protected abstract P createParsableString(String text); /** * @param source the InputSoruce representing the XML document * @return parsable string representing the source * @throws JDOMException JDOMException * @throws IOException IOException */ public List<P> extractStrings(InputSource source) throws JDOMException, IOException { SAXBuilder builder = new SAXBuilder("org.apache.xerces.parsers.SAXParser"); builder.setValidation(false); builder.setFeature("http://xml.org/sax/features/validation", false); builder.setFeature("http://apache.org/xml/features/nonvalidating/load-dtd-grammar", false); builder.setFeature("http://apache.org/xml/features/nonvalidating/load-external-dtd", false); Document doc = builder.build(source); @SuppressWarnings("serial") Iterator<?> mixedStrings = doc.getDescendants(new Filter() { @Override public boolean matches(Object object) { return object instanceof Element && getTags().contains(((Element) object).getName()); } }); List<P> stringSet = new ArrayList<P>(); while (mixedStrings.hasNext()) { P instance = createParsableString(); readElement((Element) mixedStrings.next(), instance); stringSet.add(instance); } return stringSet; } private void readElement(Element element, P instance) { for (Object content : element.getContent()) { if (content instanceof Text) { String contentText = ((Text) content).getText(); if (!contentText.matches("^[\\s]*$")) { for (T token : createParsableString(contentText).getTokens()) { token.setStartIndex(token.getStartIndex() + instance.getRawText().length()); token.setEndIndex(token.getEndIndex() + instance.getRawText().length()); token.setLabel(getTagLabelMap().get(getKeyText())); instance.addToken(token); } instance.appendText(contentText); } else { instance.appendText(" "); } } else if (content instanceof Element) { Element contentElement = (Element) content; String contentElementName = contentElement.getName(); if (getTagLabelMap().containsKey(contentElementName)) { for (T token : createParsableString(contentElement.getValue()).getTokens()) { token.setStartIndex(token.getStartIndex() + instance.getRawText().length()); token.setEndIndex(token.getEndIndex() + instance.getRawText().length()); token.setLabel(getTagLabelMap().get(contentElementName)); instance.addToken(token); } instance.appendText(contentElement.getValue()); } else { readElement(contentElement, instance); } } } instance.clean(); } }
4,982
39.185484
102
java
CERMINE
CERMINE-master/cermine-impl/src/main/java/pl/edu/icm/cermine/parsing/tools/GrmmUtils.java
/** * This file is part of CERMINE project. * Copyright (c) 2011-2018 ICM-UW * * CERMINE is free software: you can redistribute it and/or modify * it under the terms of the GNU Affero General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * CERMINE is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU Affero General Public License for more details. * * You should have received a copy of the GNU Affero General Public License * along with CERMINE. If not, see <http://www.gnu.org/licenses/>. */ package pl.edu.icm.cermine.parsing.tools; import java.util.ArrayList; import java.util.List; import pl.edu.icm.cermine.parsing.model.Token; /** * Utility class for exporting feature lists to GRMM input. * * @author Bartosz Tarnawski */ public class GrmmUtils { private static final String LABEL_SEPARATOR = " ---- "; private static final String SEPARATOR = " "; private static final String START_LABEL = "Start"; private static final String END_LABEL = "End"; private static final String CONNECTOR = "@"; /** * @param label label * @param features features * @return GRMM 'timestep' representing a token with the label and the * features */ public static String toGrmmInput(String label, List<String> features) { StringBuilder builder = new StringBuilder(); builder.append(label); builder.append(LABEL_SEPARATOR); for (int i = 0; i < features.size(); i++) { builder.append(features.get(i)); if (i + 1 < features.size()) { builder.append(SEPARATOR); } } return builder.toString(); } private static <T extends Token<?>> List<String> neighborFeatures(int current, int offset, List<T> tokens) { List<String> features = new ArrayList<String>(); String suffix = ""; if (offset != 0) { suffix = CONNECTOR + offset; } int neighbor = current + offset; if (neighbor < 0) { features.add(START_LABEL + suffix); } else if (neighbor >= tokens.size()) { features.add(END_LABEL + suffix); } else { for (String feature : tokens.get(neighbor).getFeatures()) { features.add(feature + suffix); } } return features; } /** * @param <T> token type * @param tokens the tokens whose feature lists should be exported * @param neighborInfluenceThreshold the maximum distance of token's * neighbor whose local features will be added to the token's feature list * @return GRMM input string representing the token sequence */ public static <T extends Token<?>> String toGrmmInput(List<T> tokens, int neighborInfluenceThreshold) { StringBuilder grmmInputBuilder = new StringBuilder(); for (int i = 0; i < tokens.size(); i++) { List<String> features = new ArrayList<String>(); String label = tokens.get(i).getLabel().toString(); // For better readability, we write the own features of a token first. features.addAll(neighborFeatures(i, 0, tokens)); for (int j = -neighborInfluenceThreshold; j <= neighborInfluenceThreshold; j++) { if (j != 0) { features.addAll(neighborFeatures(i, j, tokens)); } } grmmInputBuilder.append(GrmmUtils.toGrmmInput(label, features)); grmmInputBuilder.append("\n"); } return grmmInputBuilder.toString(); } }
3,820
35.390476
93
java
CERMINE
CERMINE-master/cermine-impl/src/main/java/pl/edu/icm/cermine/parsing/tools/TokenClassifier.java
/** * This file is part of CERMINE project. * Copyright (c) 2011-2018 ICM-UW * * CERMINE is free software: you can redistribute it and/or modify * it under the terms of the GNU Affero General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * CERMINE is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU Affero General Public License for more details. * * You should have received a copy of the GNU Affero General Public License * along with CERMINE. If not, see <http://www.gnu.org/licenses/>. */ package pl.edu.icm.cermine.parsing.tools; import java.util.List; import pl.edu.icm.cermine.exception.AnalysisException; import pl.edu.icm.cermine.parsing.model.Token; /** * Class for predicting token labels. * * @author Bartosz Tarnawski * @param <T> token type */ public interface TokenClassifier<T extends Token<?>> { /** * Predicts and sets a label for each of the tokens. The tokens are assumed * to hold appropriate lists of features. * * @param tokens tokens * @throws AnalysisException AnalysisException */ void classify(List<T> tokens) throws AnalysisException; }
1,354
32.04878
79
java
CERMINE
CERMINE-master/cermine-impl/src/main/java/pl/edu/icm/cermine/parsing/tools/ParsableStringParser.java
/** * This file is part of CERMINE project. * Copyright (c) 2011-2018 ICM-UW * * CERMINE is free software: you can redistribute it and/or modify * it under the terms of the GNU Affero General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * CERMINE is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU Affero General Public License for more details. * * You should have received a copy of the GNU Affero General Public License * along with CERMINE. If not, see <http://www.gnu.org/licenses/>. */ package pl.edu.icm.cermine.parsing.tools; import org.jdom.Element; import pl.edu.icm.cermine.exception.AnalysisException; import pl.edu.icm.cermine.exception.TransformationException; import pl.edu.icm.cermine.parsing.model.ParsableString; /** * Generic parser, processes an instance of ParsableString by generating and * tagging its tokens. * * @author Bartosz Tarnawski * * @param <PS> parsable string type */ public interface ParsableStringParser<PS extends ParsableString<?>> { /** * Sets the token list of the parsable string so that their labels determine * the tagging of its text content. * * @param text the parsable string instance to parse * @throws AnalysisException AnalysisException */ void parse(PS text) throws AnalysisException; /** * @param text string to parse * @return XML Element with the tagged text in NLM format * @throws TransformationException TransformationException * @throws AnalysisException AnalysisException */ Element parse(String text) throws AnalysisException, TransformationException; }
1,841
34.423077
81
java
CERMINE
CERMINE-master/cermine-impl/src/main/java/pl/edu/icm/cermine/parsing/features/IsAllLowerCaseFeature.java
/** * This file is part of CERMINE project. * Copyright (c) 2011-2018 ICM-UW * * CERMINE is free software: you can redistribute it and/or modify * it under the terms of the GNU Affero General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * CERMINE is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU Affero General Public License for more details. * * You should have received a copy of the GNU Affero General Public License * along with CERMINE. If not, see <http://www.gnu.org/licenses/>. */ package pl.edu.icm.cermine.parsing.features; import pl.edu.icm.cermine.parsing.model.ParsableString; import pl.edu.icm.cermine.parsing.model.Token; import pl.edu.icm.cermine.tools.TextUtils; /** * @author Bartosz Tarnawski */ public class IsAllLowerCaseFeature extends BinaryTokenFeatureCalculator { @Override public boolean calculateFeaturePredicate(Token<?> token, ParsableString<?> context) { return TextUtils.isAllLowerCase(token.getText()); } }
1,212
33.657143
89
java
CERMINE
CERMINE-master/cermine-impl/src/main/java/pl/edu/icm/cermine/parsing/features/IsAllUpperCaseFeature.java
/** * This file is part of CERMINE project. * Copyright (c) 2011-2018 ICM-UW * * CERMINE is free software: you can redistribute it and/or modify * it under the terms of the GNU Affero General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * CERMINE is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU Affero General Public License for more details. * * You should have received a copy of the GNU Affero General Public License * along with CERMINE. If not, see <http://www.gnu.org/licenses/>. */ package pl.edu.icm.cermine.parsing.features; import pl.edu.icm.cermine.parsing.model.ParsableString; import pl.edu.icm.cermine.parsing.model.Token; import pl.edu.icm.cermine.tools.TextUtils; /** * @author Bartosz Tarnawski */ public class IsAllUpperCaseFeature extends BinaryTokenFeatureCalculator { @Override public boolean calculateFeaturePredicate(Token<?> token, ParsableString<?> context) { return TextUtils.isAllUpperCase(token.getText()); } }
1,212
33.657143
89
java
CERMINE
CERMINE-master/cermine-impl/src/main/java/pl/edu/icm/cermine/parsing/features/WordFeatureCalculator.java
/** * This file is part of CERMINE project. * Copyright (c) 2011-2018 ICM-UW * * CERMINE is free software: you can redistribute it and/or modify * it under the terms of the GNU Affero General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * CERMINE is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU Affero General Public License for more details. * * You should have received a copy of the GNU Affero General Public License * along with CERMINE. If not, see <http://www.gnu.org/licenses/>. */ package pl.edu.icm.cermine.parsing.features; import java.util.List; import java.util.Locale; import pl.edu.icm.cermine.parsing.model.ParsableString; import pl.edu.icm.cermine.parsing.model.Token; /** * A 'word feature' of a token is a binary feature identifying the token's text. * * @author Bartosz Tarnawski */ public class WordFeatureCalculator { private final List<BinaryTokenFeatureCalculator> blockingFeatures; private final boolean toLowerCase; // This is a GRMM convention, see: https://dl.dropboxusercontent.com/u/55174954/grmm.htm private static final String PREFIX = "W="; /** * @param blockingFeatures the word feature will not be produced if the * given token has any of these features * @param toLowerCase whether the word feature should be converted to lower * case */ public WordFeatureCalculator(List<BinaryTokenFeatureCalculator> blockingFeatures, boolean toLowerCase) { this.blockingFeatures = blockingFeatures; this.toLowerCase = toLowerCase; } /** * @param token token * @param context context * @return the word represented by the token in an appropriate format or * null if the token has a blocking feature */ public String calculateFeatureValue(Token<?> token, ParsableString<?> context) { for (BinaryTokenFeatureCalculator feature : blockingFeatures) { if (feature.calculateFeaturePredicate(token, context)) { return null; } } if (toLowerCase) { return PREFIX + token.getText().toLowerCase(Locale.ENGLISH); } else { return PREFIX + token.getText(); } } }
2,447
35
92
java
CERMINE
CERMINE-master/cermine-impl/src/main/java/pl/edu/icm/cermine/parsing/features/IsWordFeature.java
/** * This file is part of CERMINE project. * Copyright (c) 2011-2018 ICM-UW * * CERMINE is free software: you can redistribute it and/or modify * it under the terms of the GNU Affero General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * CERMINE is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU Affero General Public License for more details. * * You should have received a copy of the GNU Affero General Public License * along with CERMINE. If not, see <http://www.gnu.org/licenses/>. */ package pl.edu.icm.cermine.parsing.features; import pl.edu.icm.cermine.parsing.model.ParsableString; import pl.edu.icm.cermine.parsing.model.Token; import pl.edu.icm.cermine.tools.TextUtils; /** * @author Bartosz Tarnawski */ public class IsWordFeature extends BinaryTokenFeatureCalculator { @Override public boolean calculateFeaturePredicate(Token<?> token, ParsableString<?> context) { return TextUtils.isWord(token.getText()); } }
1,196
33.2
89
java
CERMINE
CERMINE-master/cermine-impl/src/main/java/pl/edu/icm/cermine/parsing/features/IsRareFeature.java
/** * This file is part of CERMINE project. * Copyright (c) 2011-2018 ICM-UW * * CERMINE is free software: you can redistribute it and/or modify * it under the terms of the GNU Affero General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * CERMINE is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU Affero General Public License for more details. * * You should have received a copy of the GNU Affero General Public License * along with CERMINE. If not, see <http://www.gnu.org/licenses/>. */ package pl.edu.icm.cermine.parsing.features; import java.util.HashSet; import java.util.List; import java.util.Locale; import java.util.Set; import pl.edu.icm.cermine.parsing.model.ParsableString; import pl.edu.icm.cermine.parsing.model.Token; import pl.edu.icm.cermine.tools.TextUtils; /** * A token is considered as rare if it is word that does not belong to the set * of common words. * * @author Bartosz Tarnawski */ public class IsRareFeature extends BinaryTokenFeatureCalculator { private final Set<String> commonWords; private final boolean caseSensitive; /** * @param commonWordsList the words that are not considered as rare * @param caseSensitive whether the lookups should be case-sensitive */ public IsRareFeature(List<String> commonWordsList, boolean caseSensitive) { this.commonWords = new HashSet<String>(); this.caseSensitive = caseSensitive; for (String commonWord : commonWordsList) { if (caseSensitive) { commonWords.add(commonWord); } else { commonWords.add(commonWord.toLowerCase(Locale.ENGLISH)); } } } @Override public boolean calculateFeaturePredicate(Token<?> token, ParsableString<?> context) { String text = token.getText(); if (!TextUtils.isWord(text)) { return false; } if (!caseSensitive) { text = text.toLowerCase(Locale.ENGLISH); } return !commonWords.contains(text); } }
2,271
31.927536
89
java
CERMINE
CERMINE-master/cermine-impl/src/main/java/pl/edu/icm/cermine/parsing/features/IsSeparatorFeature.java
/** * This file is part of CERMINE project. * Copyright (c) 2011-2018 ICM-UW * * CERMINE is free software: you can redistribute it and/or modify * it under the terms of the GNU Affero General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * CERMINE is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU Affero General Public License for more details. * * You should have received a copy of the GNU Affero General Public License * along with CERMINE. If not, see <http://www.gnu.org/licenses/>. */ package pl.edu.icm.cermine.parsing.features; import pl.edu.icm.cermine.parsing.model.ParsableString; import pl.edu.icm.cermine.parsing.model.Token; import pl.edu.icm.cermine.tools.TextUtils; /** * @author Bartosz Tarnawski */ public class IsSeparatorFeature extends BinaryTokenFeatureCalculator { @Override public boolean calculateFeaturePredicate(Token<?> token, ParsableString<?> context) { return TextUtils.isSeparator(token.getText()); } }
1,206
33.485714
89
java
CERMINE
CERMINE-master/cermine-impl/src/main/java/pl/edu/icm/cermine/parsing/features/IsNumberFeature.java
/** * This file is part of CERMINE project. * Copyright (c) 2011-2018 ICM-UW * * CERMINE is free software: you can redistribute it and/or modify * it under the terms of the GNU Affero General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * CERMINE is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU Affero General Public License for more details. * * You should have received a copy of the GNU Affero General Public License * along with CERMINE. If not, see <http://www.gnu.org/licenses/>. */ package pl.edu.icm.cermine.parsing.features; import pl.edu.icm.cermine.parsing.model.ParsableString; import pl.edu.icm.cermine.parsing.model.Token; import pl.edu.icm.cermine.tools.TextUtils; /** * @author Bartosz Tarnawski */ public class IsNumberFeature extends BinaryTokenFeatureCalculator { @Override public boolean calculateFeaturePredicate(Token<?> token, ParsableString<?> context) { return TextUtils.isNumber(token.getText()); } }
1,200
33.314286
89
java
CERMINE
CERMINE-master/cermine-impl/src/main/java/pl/edu/icm/cermine/parsing/features/IsUpperCaseFeature.java
/** * This file is part of CERMINE project. * Copyright (c) 2011-2018 ICM-UW * * CERMINE is free software: you can redistribute it and/or modify * it under the terms of the GNU Affero General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * CERMINE is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU Affero General Public License for more details. * * You should have received a copy of the GNU Affero General Public License * along with CERMINE. If not, see <http://www.gnu.org/licenses/>. */ package pl.edu.icm.cermine.parsing.features; import pl.edu.icm.cermine.parsing.model.ParsableString; import pl.edu.icm.cermine.parsing.model.Token; import pl.edu.icm.cermine.tools.TextUtils; /** * @author Bartosz Tarnawski */ public class IsUpperCaseFeature extends BinaryTokenFeatureCalculator { @Override public boolean calculateFeaturePredicate(Token<?> token, ParsableString<?> context) { return TextUtils.isOnlyFirstUpperCase(token.getText()); } }
1,215
33.742857
89
java
CERMINE
CERMINE-master/cermine-impl/src/main/java/pl/edu/icm/cermine/parsing/features/IsNonAlphanumFeature.java
/** * This file is part of CERMINE project. * Copyright (c) 2011-2018 ICM-UW * * CERMINE is free software: you can redistribute it and/or modify * it under the terms of the GNU Affero General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * CERMINE is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU Affero General Public License for more details. * * You should have received a copy of the GNU Affero General Public License * along with CERMINE. If not, see <http://www.gnu.org/licenses/>. */ package pl.edu.icm.cermine.parsing.features; import pl.edu.icm.cermine.parsing.model.ParsableString; import pl.edu.icm.cermine.parsing.model.Token; import pl.edu.icm.cermine.tools.TextUtils; /** * @author Bartosz Tarnawski */ public class IsNonAlphanumFeature extends BinaryTokenFeatureCalculator { @Override public boolean calculateFeaturePredicate(Token<?> token, ParsableString<?> context) { return TextUtils.isNonAlphanumSep(token.getText()); } }
1,212
34.676471
89
java
CERMINE
CERMINE-master/cermine-impl/src/main/java/pl/edu/icm/cermine/parsing/features/BinaryTokenFeatureCalculator.java
/** * This file is part of CERMINE project. * Copyright (c) 2011-2018 ICM-UW * * CERMINE is free software: you can redistribute it and/or modify * it under the terms of the GNU Affero General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * CERMINE is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU Affero General Public License for more details. * * You should have received a copy of the GNU Affero General Public License * along with CERMINE. If not, see <http://www.gnu.org/licenses/>. */ package pl.edu.icm.cermine.parsing.features; import pl.edu.icm.cermine.parsing.model.ParsableString; import pl.edu.icm.cermine.parsing.model.Token; import pl.edu.icm.cermine.tools.classification.general.FeatureCalculator; /** * Feature calculator which checks whether a token (representing a word) has a * given feature. * * @author Bartosz Tarnawski */ public abstract class BinaryTokenFeatureCalculator extends FeatureCalculator<Token<?>, ParsableString<?>> { /** * @param token token * @param context context * @return whether the token in the context has the feature represented by * the class */ public abstract boolean calculateFeaturePredicate(Token<?> token, ParsableString<?> context); @Override public double calculateFeatureValue(Token<?> token, ParsableString<?> context) { return calculateFeaturePredicate(token, context) ? 1 : 0; } }
1,655
34.234043
97
java
CERMINE
CERMINE-master/cermine-impl/src/main/java/pl/edu/icm/cermine/parsing/features/KeywordFeatureCalculator.java
/** * This file is part of CERMINE project. * Copyright (c) 2011-2018 ICM-UW * * CERMINE is free software: you can redistribute it and/or modify * it under the terms of the GNU Affero General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * CERMINE is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU Affero General Public License for more details. * * You should have received a copy of the GNU Affero General Public License * along with CERMINE. If not, see <http://www.gnu.org/licenses/>. */ package pl.edu.icm.cermine.parsing.features; import java.io.BufferedReader; import java.io.IOException; import java.io.InputStream; import java.io.InputStreamReader; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.Locale; import java.util.Map; import pl.edu.icm.cermine.exception.AnalysisException; import pl.edu.icm.cermine.metadata.tools.MetadataTools; import pl.edu.icm.cermine.parsing.model.Token; import pl.edu.icm.cermine.parsing.tools.TextTokenizer; /** * Class for calculating keyword features. It finds all occurrences of a keyword * string in a list of tokens and adds the appropriate feature string to the * corresponding tokens * * @author Bartosz Tarnawski * @param <T> type of tokens */ public class KeywordFeatureCalculator<T extends Token<?>> { // Stores keyword sequences of tokens. A token is considered to be a keyword if together // with its neighbors it forms a keyword sequence. // // For example: // The token "Great" is considered to be a country keyword when it is followed // by "Britain" but not when it is followed by "Gatsby". private final List<List<T>> entries; // Maps a token to the list of indices of keyword sequences in the 'entries' list which // start with this token. // // For example: // if entries.get(4) == ["United", "States"] and entries.get(7) == ["United", "Kingdom"], then // dictionary.get("United") will contain 4 and 7 private final Map<String, List<Integer>> dictionary; private final TextTokenizer<T> textTokenizer; private final String featureString; private final boolean caseSensitive; /** * @param FeatureString the string which will be added to the matching * tokens' features lists * @param dictionaryFileName the name of the dictionary to be used (must be * a package resource) * @param caseSensitive whether dictionary lookups should be case sensitive * @param tokenizer used for dictionary entries splitting * @throws AnalysisException AnalysisException */ public KeywordFeatureCalculator(String FeatureString, String dictionaryFileName, boolean caseSensitive, TextTokenizer<T> tokenizer) throws AnalysisException { this.entries = new ArrayList<List<T>>(); this.dictionary = new HashMap<String, List<Integer>>(); this.textTokenizer = tokenizer; this.featureString = FeatureString; this.caseSensitive = caseSensitive; loadDictionary(dictionaryFileName); } private void addLine(String line, int number) { String normalizedLine = MetadataTools.cleanAndNormalize(line); List<T> tokens = textTokenizer.tokenize(normalizedLine); if (tokens.isEmpty()) { System.err.println("Line (" + number + ") with no ASCII characters: " + line); return; } entries.add(tokens); int entryId = entries.size() - 1; String tokenString = tokens.get(0).getText(); if (!caseSensitive) { tokenString = tokenString.toLowerCase(Locale.ENGLISH); } if (!dictionary.containsKey(tokenString)) { dictionary.put(tokenString, new ArrayList<Integer>()); } dictionary.get(tokenString).add(entryId); } private void loadDictionary(String dictionaryFileName) throws AnalysisException { InputStream is = KeywordFeatureCalculator.class.getResourceAsStream(dictionaryFileName); if (is == null) { throw new AnalysisException("Resource not found: " + dictionaryFileName); } BufferedReader in = null; try { in = new BufferedReader(new InputStreamReader(is, "UTF-8")); String line; int lineNumber = 1; while ((line = in.readLine()) != null) { addLine(line, lineNumber++); } } catch (IOException readException) { throw new AnalysisException("An exception occured when the dictionary " + dictionaryFileName + " was being read: " + readException); } finally { try { if (in != null) { in.close(); } } catch (IOException closeException) { throw new AnalysisException("An exception occured when the " + dictionaryFileName + "dictionary reader was being closed: " + closeException); } } } /** * Finds all occurrences of the keywords in the text formed by the sequence * of the tokens and marks the corresponding tokens by adding an appropriate * string to their feature lists. * * @param tokens tokens */ public void calculateDictionaryFeatures(List<T> tokens) { boolean marked[] = new boolean[tokens.size()]; for (int i = 0; i < marked.length; i++) { marked[i] = false; } for (int l = 0; l < tokens.size(); l++) { T token = tokens.get(l); String tokenString = token.getText(); if (!caseSensitive) { tokenString = tokenString.toLowerCase(Locale.ENGLISH); } // candidateIds are indices of keyword sequences in the 'entries' list // which start with the 'tokenString'. List<Integer> candidateIds = dictionary.get(tokenString); if (candidateIds != null) { for (int candidateId : candidateIds) { List<T> entry = entries.get(candidateId); int r = l + entry.size(); if (r <= tokens.size() && Token.sequenceTextEquals(entry, tokens.subList(l, r), caseSensitive)) { for (int i = l; i < r; i++) { marked[i] = true; } } } } } for (int i = 0; i < marked.length; i++) { if (marked[i]) { tokens.get(i).addFeature(featureString); } } } }
6,879
37.435754
99
java
CERMINE
CERMINE-master/cermine-impl/src/main/java/pl/edu/icm/cermine/parsing/model/ParsableString.java
/** * This file is part of CERMINE project. * Copyright (c) 2011-2018 ICM-UW * * CERMINE is free software: you can redistribute it and/or modify * it under the terms of the GNU Affero General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * CERMINE is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU Affero General Public License for more details. * * You should have received a copy of the GNU Affero General Public License * along with CERMINE. If not, see <http://www.gnu.org/licenses/>. */ package pl.edu.icm.cermine.parsing.model; import java.util.List; /** * Representation of a parsable string. Such a string may be tokenized i.e. * split into smaller parts (for example words). Each token may have a label * corresponding to the type of its text content. The parsing process consists * of tokenization followed by token classification. * * @author Bartosz Tarnawski * @param <T> type of the tokens */ public interface ParsableString<T extends Token<?>> { /** * @return tokens corresponding to the text content */ List<T> getTokens(); /** * @param tokens the tokens corresponding to the text content of the * parsable string */ void setTokens(List<T> tokens); /** * @return the text content */ String getRawText(); /** * @param token token to the end of the token list */ void addToken(T token); /** * Appends the text to the text content * * @param text text */ void appendText(String text); /** * Cleans the text content */ void clean(); }
1,830
26.742424
78
java
CERMINE
CERMINE-master/cermine-impl/src/main/java/pl/edu/icm/cermine/parsing/model/Token.java
/** * This file is part of CERMINE project. * Copyright (c) 2011-2018 ICM-UW * * CERMINE is free software: you can redistribute it and/or modify * it under the terms of the GNU Affero General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * CERMINE is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU Affero General Public License for more details. * * You should have received a copy of the GNU Affero General Public License * along with CERMINE. If not, see <http://www.gnu.org/licenses/>. */ package pl.edu.icm.cermine.parsing.model; import java.util.ArrayList; import java.util.List; import java.util.Locale; import org.apache.commons.lang.builder.EqualsBuilder; /** * Representation of a token, an atomic part of a string. Used for string * parsing. * * @author Bartosz Tarnawski * @param <L> type of label used for token classifying */ public class Token<L> { protected String text; protected int startIndex; protected int endIndex; protected L label; protected List<String> features; public String getText() { return text; } public void setText(String text) { this.text = text; } public int getStartIndex() { return startIndex; } public void setStartIndex(int startIndex) { this.startIndex = startIndex; } public int getEndIndex() { return endIndex; } public void setEndIndex(int endIndex) { this.endIndex = endIndex; } public L getLabel() { return label; } public void setLabel(L label) { this.label = label; } public List<String> getFeatures() { return features; } public void setFeatures(List<String> features) { this.features = features; } public void addFeature(String feature) { features.add(feature); } /** * @param text the normalized string corresponding to the * substring(startIndex, endIndex) of the parsable string the token belongs * to * @param startIndex start index * @param endIndex end index * @param label may be null if the token is not classified yet */ public Token(String text, int startIndex, int endIndex, L label) { this.text = text; this.startIndex = startIndex; this.endIndex = endIndex; this.label = label; this.features = new ArrayList<String>(); } /** * @param text the normalized string corresponding to the * substring(startIndex, endIndex) of the parsable string the token belongs * to * @param startIndex start index * @param endIndex end index */ public Token(String text, int startIndex, int endIndex) { this(text, startIndex, endIndex, null); } public Token(String text) { this(text, 0, 0); } public Token() { this(""); } // For testing purposes only @Override public boolean equals(Object obj) { if (!(obj instanceof Token)) { return false; } if (obj == this) { return true; } @SuppressWarnings("rawtypes") Token rhs = (Token) obj; return new EqualsBuilder(). append(text, rhs.text). append(startIndex, rhs.startIndex). append(endIndex, rhs.endIndex). append(label, rhs.label). isEquals(); } @Override public int hashCode() { int hash = 3; hash = 23 * hash + (this.text != null ? this.text.hashCode() : 0); hash = 23 * hash + this.startIndex; hash = 23 * hash + this.endIndex; hash = 23 * hash + (this.label != null ? this.label.hashCode() : 0); return hash; } /** * Compares text strings represented by sequences of tokens * * @param <T> token type * @param lhs token sequence * @param rhs token sequence * @param caseSensitive whether case sensitive * @return whether the corresponding strings are equal */ @SuppressWarnings("rawtypes") public static <T extends Token> boolean sequenceTextEquals(List<T> lhs, List<T> rhs, boolean caseSensitive) { if (lhs.size() != rhs.size()) { return false; } for (int i = 0; i < lhs.size(); i++) { String lhsString = lhs.get(i).getText(); String rhsString = rhs.get(i).getText(); if (!caseSensitive) { lhsString = lhsString.toLowerCase(Locale.ENGLISH); rhsString = rhsString.toLowerCase(Locale.ENGLISH); } if (!lhsString.equals(rhsString)) { return false; } } return true; } @Override public String toString() { return "Token{" + "text=" + text + ", startIndex=" + startIndex + ", endIndex=" + endIndex + ", label=" + label + '}'; } }
5,154
26.715054
126
java
CERMINE
CERMINE-master/cermine-impl/src/main/java/pl/edu/icm/cermine/content/RawTextWithLabelsExtractor.java
/** * This file is part of CERMINE project. * Copyright (c) 2011-2018 ICM-UW * * CERMINE is free software: you can redistribute it and/or modify * it under the terms of the GNU Affero General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * CERMINE is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU Affero General Public License for more details. * * You should have received a copy of the GNU Affero General Public License * along with CERMINE. If not, see <http://www.gnu.org/licenses/>. */ package pl.edu.icm.cermine.content; import java.util.HashSet; import java.util.Set; import org.jdom.Element; import pl.edu.icm.cermine.content.cleaning.ContentCleaner; import pl.edu.icm.cermine.content.model.BxContentStructure; import pl.edu.icm.cermine.content.model.BxContentStructure.BxDocContentPart; import pl.edu.icm.cermine.exception.AnalysisException; import pl.edu.icm.cermine.structure.model.BxDocument; import pl.edu.icm.cermine.structure.model.BxLine; import pl.edu.icm.cermine.structure.model.BxZoneLabel; import pl.edu.icm.cermine.structure.model.BxZoneLabelCategory; import pl.edu.icm.cermine.tools.XMLTools; /** * @author Dominika Tkaczyk (d.tkaczyk@icm.edu.pl) */ public class RawTextWithLabelsExtractor { public Element extractRawTextWithLabels(BxDocument document, BxContentStructure structure) throws AnalysisException { Set<BxLine> headerLines = new HashSet<BxLine>(); for (BxDocContentPart contentPart : structure.getParts()) { headerLines.addAll(contentPart.getHeaderLines()); } Element root = new Element("document"); if (!document.asLines().iterator().hasNext()) { return root; } BxZoneLabel actLabel = document.asLines().iterator().next().getParent().getLabel(); StringBuilder sb = new StringBuilder(); for (BxLine line : document.asLines()) { BxZoneLabel label = line.getParent().getLabel(); if (headerLines.contains(line)) { if (actLabel.equals(BxZoneLabel.BODY_HEADING)) { sb.append(line.toText()); sb.append("\n"); } else { addZone(root, actLabel, sb.toString()); sb = new StringBuilder(); sb.append(line.toText()); sb.append("\n"); actLabel = BxZoneLabel.BODY_HEADING; } } else if (label.isOfCategoryOrGeneral(BxZoneLabelCategory.CAT_BODY)) { if (actLabel.equals(BxZoneLabel.BODY_CONTENT)) { sb.append(line.toText()); sb.append("\n"); } else { addZone(root, actLabel, sb.toString()); sb = new StringBuilder(); sb.append(line.toText()); sb.append("\n"); actLabel = BxZoneLabel.BODY_CONTENT; } } else { if (actLabel.equals(label)) { sb.append(line.toText()); sb.append("\n"); } else { addZone(root, actLabel, sb.toString()); sb = new StringBuilder(); sb.append(line.toText()); sb.append("\n"); actLabel = label; } } } Element z = new Element("zone"); z.setAttribute("label", actLabel.toString()); z.addContent(ContentCleaner.cleanAll(sb.toString())); root.addContent(z); return root; } private void addZone(Element root, BxZoneLabel label, String rawText) { Element z = new Element("zone"); z.setAttribute("label", label.toString()); z.addContent(ContentCleaner.cleanAll(XMLTools.removeInvalidXMLChars(rawText))); root.addContent(z); } }
4,192
38.186916
95
java
CERMINE
CERMINE-master/cermine-impl/src/main/java/pl/edu/icm/cermine/content/LogicalStructureExtractor.java
/** * This file is part of CERMINE project. * Copyright (c) 2011-2018 ICM-UW * * CERMINE is free software: you can redistribute it and/or modify * it under the terms of the GNU Affero General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * CERMINE is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU Affero General Public License for more details. * * You should have received a copy of the GNU Affero General Public License * along with CERMINE. If not, see <http://www.gnu.org/licenses/>. */ package pl.edu.icm.cermine.content; import pl.edu.icm.cermine.content.cleaning.ContentCleaner; import pl.edu.icm.cermine.content.filtering.ContentFilter; import pl.edu.icm.cermine.content.headers.ContentHeadersExtractor; import pl.edu.icm.cermine.content.model.BxContentStructure; import pl.edu.icm.cermine.content.model.ContentStructure; import pl.edu.icm.cermine.content.transformers.BxContentToDocContentConverter; import pl.edu.icm.cermine.exception.AnalysisException; import pl.edu.icm.cermine.exception.TransformationException; import pl.edu.icm.cermine.structure.model.BxDocument; /** * @author Dominika Tkaczyk (d.tkaczyk@icm.edu.pl) */ public abstract class LogicalStructureExtractor { private ContentFilter contentFilter; private ContentHeadersExtractor headerExtractor; private ContentCleaner contentCleaner; private BxContentToDocContentConverter converter; public LogicalStructureExtractor() { } public LogicalStructureExtractor(ContentFilter contentFilter, ContentHeadersExtractor headerExtractor, ContentCleaner contentCleaner, BxContentToDocContentConverter converter) { this.contentFilter = contentFilter; this.headerExtractor = headerExtractor; this.contentCleaner = contentCleaner; this.converter = converter; } public ContentStructure extractStructure(BxDocument document) throws AnalysisException { try { BxDocument doc = contentFilter.filter(document); BxContentStructure tmpContentStructure = headerExtractor.extractHeaders(doc); contentCleaner.cleanupContent(tmpContentStructure); return converter.convert(tmpContentStructure); } catch (TransformationException ex) { throw new AnalysisException("Cannot extract logical structure!", ex); } } public ContentCleaner getContentCleaner() { return contentCleaner; } public void setContentCleaner(ContentCleaner contentCleaner) { this.contentCleaner = contentCleaner; } public ContentFilter getContentFilter() { return contentFilter; } public void setContentFilter(ContentFilter contentFilter) { this.contentFilter = contentFilter; } public BxContentToDocContentConverter getConverter() { return converter; } public void setConverter(BxContentToDocContentConverter converter) { this.converter = converter; } public ContentHeadersExtractor getHeaderExtractor() { return headerExtractor; } public void setHeaderExtractor(ContentHeadersExtractor headerExtractor) { this.headerExtractor = headerExtractor; } }
3,460
33.61
107
java
CERMINE
CERMINE-master/cermine-impl/src/main/java/pl/edu/icm/cermine/content/SVMLogicalStructureExtractor.java
/** * This file is part of CERMINE project. * Copyright (c) 2011-2018 ICM-UW * * CERMINE is free software: you can redistribute it and/or modify * it under the terms of the GNU Affero General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * CERMINE is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU Affero General Public License for more details. * * You should have received a copy of the GNU Affero General Public License * along with CERMINE. If not, see <http://www.gnu.org/licenses/>. */ package pl.edu.icm.cermine.content; import java.io.BufferedReader; import pl.edu.icm.cermine.content.cleaning.ContentCleaner; import pl.edu.icm.cermine.content.filtering.SVMContentFilter; import pl.edu.icm.cermine.content.headers.SVMContentHeadersExtractor; import pl.edu.icm.cermine.content.transformers.BxContentToDocContentConverter; import pl.edu.icm.cermine.exception.AnalysisException; /** * @author Dominika Tkaczyk (d.tkaczyk@icm.edu.pl) */ public class SVMLogicalStructureExtractor extends LogicalStructureExtractor { public SVMLogicalStructureExtractor(BufferedReader filterModelFile, BufferedReader filterRangeFile) throws AnalysisException { this.setContentFilter(new SVMContentFilter(filterModelFile, filterRangeFile)); this.setHeaderExtractor(new SVMContentHeadersExtractor()); this.setContentCleaner(new ContentCleaner()); this.setConverter(new BxContentToDocContentConverter()); } public SVMLogicalStructureExtractor(BufferedReader filterModelFile, BufferedReader filterRangeFile, BufferedReader headerModelFile, BufferedReader headerRangeFile) throws AnalysisException { super(new SVMContentFilter(filterModelFile, filterRangeFile), new SVMContentHeadersExtractor(headerModelFile, headerRangeFile), new ContentCleaner(), new BxContentToDocContentConverter()); } }
2,149
42.877551
130
java
CERMINE
CERMINE-master/cermine-impl/src/main/java/pl/edu/icm/cermine/content/cleaning/ContentCleaner.java
/** * This file is part of CERMINE project. * Copyright (c) 2011-2018 ICM-UW * * CERMINE is free software: you can redistribute it and/or modify * it under the terms of the GNU Affero General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * CERMINE is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU Affero General Public License for more details. * * You should have received a copy of the GNU Affero General Public License * along with CERMINE. If not, see <http://www.gnu.org/licenses/>. */ package pl.edu.icm.cermine.content.cleaning; import java.util.ArrayList; import java.util.List; import pl.edu.icm.cermine.content.model.BxContentStructure; import pl.edu.icm.cermine.content.model.BxContentStructure.BxDocContentPart; import pl.edu.icm.cermine.structure.model.BxLine; /** * @author Dominika Tkaczyk (d.tkaczyk@icm.edu.pl) */ public class ContentCleaner { public static final double DEFAULT_PAR_LINE_MULT = 0.5; public static final double DEFAULT_MIN_PAR_IND = 5; public static final double DEFAULT_LAST_PAR_LINE_MULT = 0.8; public static final double DEFAULT_FIRST_PAR_LINE_SCORE = 3; private double paragraphLineIndentMultiplier = DEFAULT_PAR_LINE_MULT; private double minParagraphIndent = DEFAULT_MIN_PAR_IND; private double lastParagraphLineLengthMult = DEFAULT_LAST_PAR_LINE_MULT; private double firstParagraphLineMinScore = DEFAULT_FIRST_PAR_LINE_SCORE; public void cleanupContent(BxContentStructure contentStructure) { for (BxDocContentPart contentPart : contentStructure.getParts()) { List<BxLine> headerLines = contentPart.getHeaderLines(); StringBuilder sb = new StringBuilder(); for (BxLine headerLine : headerLines) { String lineText = headerLine.toText(); if (lineText.endsWith("-")) { lineText = lineText.substring(0, lineText.length()-1); if (lineText.lastIndexOf(' ') < 0) { sb.append(lineText); } else { sb.append(lineText.substring(0, lineText.lastIndexOf(' '))); sb.append(" "); sb.append(lineText.substring(lineText.lastIndexOf(' ')+1)); } } else { sb.append(lineText); sb.append(" "); } } contentPart.setCleanHeaderText(cleanLigatures(sb.toString().trim())); List<BxLine> contentLines = contentPart.getContentLines(); List<String> contentTexts = new ArrayList<String>(); double maxLen = Double.NEGATIVE_INFINITY; for (BxLine line : contentLines) { if (line.getWidth() > maxLen) { maxLen = line.getWidth(); } } String contentText = ""; for (BxLine line : contentLines) { int score = 0; BxLine prev = line.getPrev(); BxLine next = line.getNext(); if (line.toText().matches("^[A-Z].*$")) { score++; } if (prev != null) { if (line.getX() > prev.getX() && line.getX() - prev.getX() < paragraphLineIndentMultiplier * maxLen && line.getX() - prev.getX() > minParagraphIndent) { score++; } if (prev.getWidth() < lastParagraphLineLengthMult * maxLen) { score++; } if (prev.toText().endsWith(".")) { score++; } } if (next != null && line.getX() > next.getX() && line.getX() - next.getX() < paragraphLineIndentMultiplier * maxLen && line.getX() - next.getX() > minParagraphIndent) { score++; } if (score >= firstParagraphLineMinScore) { if (!contentText.isEmpty()) { contentTexts.add(cleanLigatures(contentText.trim())); } contentText = ""; } String lineText = line.toText(); if (lineText.endsWith("-")) { lineText = lineText.substring(0, lineText.length()-1); if (lineText.lastIndexOf(' ') < 0) { contentText += lineText; } else { contentText += lineText.substring(0, lineText.lastIndexOf(' ')); contentText += "\n"; contentText += lineText.substring(lineText.lastIndexOf(' ')+1); } } else { contentText += lineText; contentText += "\n"; } } if (!contentText.isEmpty()) { contentTexts.add(cleanLigatures(contentText.trim())); } contentPart.setCleanContentTexts(contentTexts); } } public static String cleanOther(String str) { if (str == null) { return null; } return str.replaceAll("[’‘]", "'") .replaceAll("[–]", "-") // EN DASH \u2013 .replaceAll("[—]", "-"); // EM DASH \u2014 } public static String cleanLigatures(String str) { if (str == null) { return null; } return str.replaceAll("\uFB00", "ff") .replaceAll("\uFB01", "fi") .replaceAll("\uFB02", "fl") .replaceAll("\uFB03", "ffi") .replaceAll("\uFB04", "ffl") .replaceAll("\uFB05", "ft") .replaceAll("\uFB06", "st") .replaceAll("\u00E6", "ae") .replaceAll("\u0153", "oe"); } public static String clean(String str) { if (str == null) { return null; } return cleanOther(cleanLigatures(str)); } public static String cleanHyphenationAndBreaks(String str) { if (str == null) { return null; } return cleanHyphenation(str).replaceAll("\n", " "); } public static String cleanHyphenation(String str) { if (str == null) { return null; } str = str.replaceAll(" +", " ").replaceAll("^ +", "").replaceAll(" +$", ""); String hyphenList = "\u002D\u00AD\u2010\u2011\u2012\u2013\u2014\u2015\u207B\u208B\u2212-"; String[] lines = str.split("\n"); for (int i = 0; i < lines.length; i++) { lines[i] = lines[i].replaceAll("^ +", "").replaceAll(" +$", ""); } StringBuilder sb = new StringBuilder(); int i = 0; while (i < lines.length) { String line = lines[i]; if (i + 1 == lines.length) { sb.append(line); break; } String next = lines[i+1]; if (line.matches("^.*["+hyphenList+"]$")) { line = line.substring(0, line.length()-1); sb.append(line); int idx = next.indexOf(' '); if (idx < 0) { sb.append(next); i++; } else { sb.append(next.substring(0, idx)); lines[i+1] = next.substring(idx+1); } } else { sb.append(line); } sb.append("\n"); i++; } return sb.toString().trim(); } public static String cleanAll(String str) { if (str == null) { return null; } return clean(cleanHyphenation(str)); } public static String cleanAllAndBreaks(String str) { if (str == null) { return null; } return clean(cleanHyphenationAndBreaks(str)); } public void setFirstParagraphLineMinScore(double firstParagraphLineMinScore) { this.firstParagraphLineMinScore = firstParagraphLineMinScore; } public void setLastParagraphLineLengthMult(double lastParagraphLineLengthMult) { this.lastParagraphLineLengthMult = lastParagraphLineLengthMult; } public void setMinParagraphIndent(double minParagraphIndent) { this.minParagraphIndent = minParagraphIndent; } public void setParagraphLineIndentMultiplier(double paragraphLineIndentMultiplier) { this.paragraphLineIndentMultiplier = paragraphLineIndentMultiplier; } }
9,086
36.241803
132
java
CERMINE
CERMINE-master/cermine-impl/src/main/java/pl/edu/icm/cermine/content/model/BxContentStructure.java
/** * This file is part of CERMINE project. * Copyright (c) 2011-2018 ICM-UW * * CERMINE is free software: you can redistribute it and/or modify * it under the terms of the GNU Affero General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * CERMINE is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU Affero General Public License for more details. * * You should have received a copy of the GNU Affero General Public License * along with CERMINE. If not, see <http://www.gnu.org/licenses/>. */ package pl.edu.icm.cermine.content.model; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.Map; import pl.edu.icm.cermine.structure.model.BxLine; import pl.edu.icm.cermine.structure.model.BxPage; import pl.edu.icm.cermine.tools.classification.general.FeatureVector; import pl.edu.icm.cermine.tools.classification.general.FeatureVectorBuilder; /** * @author Dominika Tkaczyk (d.tkaczyk@icm.edu.pl) */ public class BxContentStructure { private final List<BxLine> firstHeaderLines = new ArrayList<BxLine>(); private final Map<BxLine, BxDocContentPart> parts = new HashMap<BxLine, BxDocContentPart>(); public void addFirstHeaderLine(BxPage page, BxLine headerLine) { firstHeaderLines.add(headerLine); parts.put(headerLine, new BxDocContentPart(page, headerLine)); } public void addContentLine(BxLine headerLine, BxLine contentLine) { if (parts.get(headerLine) != null) { parts.get(headerLine).addContentLine(contentLine); } } public FeatureVector[] getFirstHeaderFeatureVectors(FeatureVectorBuilder builder) { FeatureVector[] fvs = new FeatureVector[parts.size()]; int i = 0; for (BxLine header : firstHeaderLines) { fvs[i] = parts.get(header).getFirstHeaderFeatureVector(builder); i++; } return fvs; } public void setHeaderLevelIds(int[] ids) { int i = 0; for (BxLine header : firstHeaderLines) { parts.get(header).setLevelId(ids[i]); i++; } } public List<BxLine> getFirstHeaderLines() { return firstHeaderLines; } public boolean containsFirstHeaderLine(BxLine headerLine) { return firstHeaderLines.contains(headerLine); } public void addAdditionalHeaderLine(BxLine headerLine, BxLine additionalLine) { parts.get(headerLine).markLineAsHeader(additionalLine); } public List<BxDocContentPart> getParts() { List<BxDocContentPart> sortedParts = new ArrayList<BxDocContentPart>(); for (BxLine header : firstHeaderLines) { sortedParts.add(parts.get(header)); } return sortedParts; } public int getTopHeaderLevelId() { if (firstHeaderLines == null || firstHeaderLines.isEmpty()) { return -1; } return parts.get(firstHeaderLines.get(0)).getLevelId(); } public static class BxDocContentPart { private int levelId; private final BxPage page; private BxLine firstHeaderLine; private List<BxLine> headerLines = new ArrayList<BxLine>(); private String cleanHeaderText; private List<BxLine> contentLines = new ArrayList<BxLine>(); private List<String> cleanContentTexts = new ArrayList<String>(); public BxDocContentPart(BxPage page, BxLine firstHeaderLine) { this.page = page; this.firstHeaderLine = firstHeaderLine; this.headerLines.add(firstHeaderLine); } public int getLevelId() { return levelId; } public void setLevelId(int levelId) { this.levelId = levelId; } public BxLine getFirstHeaderLine() { return firstHeaderLine; } public void setFirstHeaderLine(BxLine firstHeaderLine) { this.firstHeaderLine = firstHeaderLine; } public FeatureVector getFirstHeaderFeatureVector(FeatureVectorBuilder builder) { return builder.getFeatureVector(firstHeaderLine, page); } public List<String> getCleanContentTexts() { return cleanContentTexts; } public void setCleanContentTexts(List<String> cleanContentTexts) { this.cleanContentTexts = cleanContentTexts; } public String getCleanHeaderText() { return cleanHeaderText; } public void setCleanHeaderText(String cleanHeaderText) { this.cleanHeaderText = cleanHeaderText; } public List<BxLine> getContentLines() { return contentLines; } public void setContentLines(List<BxLine> contentLines) { this.contentLines = contentLines; } public List<BxLine> getHeaderLines() { return headerLines; } public void setHeaderLines(List<BxLine> headerLines) { this.headerLines = headerLines; } private void addContentLine(BxLine line) { contentLines.add(line); } private void markLineAsHeader(BxLine headerLine) { headerLines.add(headerLine); contentLines.remove(headerLine); } } }
5,529
30.067416
96
java
CERMINE
CERMINE-master/cermine-impl/src/main/java/pl/edu/icm/cermine/content/model/ContentStructure.java
/** * This file is part of CERMINE project. * Copyright (c) 2011-2018 ICM-UW * * CERMINE is free software: you can redistribute it and/or modify * it under the terms of the GNU Affero General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * CERMINE is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU Affero General Public License for more details. * * You should have received a copy of the GNU Affero General Public License * along with CERMINE. If not, see <http://www.gnu.org/licenses/>. */ package pl.edu.icm.cermine.content.model; import java.util.ArrayList; import java.util.List; /** * @author Dominika Tkaczyk (d.tkaczyk@icm.edu.pl) */ public class ContentStructure { private List<DocumentSection> sections = new ArrayList<DocumentSection>(); public List<DocumentSection> getSections() { return getSections(false); } public List<DocumentSection> getSections(boolean recursive) { if (!recursive) { return sections; } List<DocumentSection> secs = new ArrayList<DocumentSection>(); for (DocumentSection sec : sections) { secs.add(sec); secs.addAll(sec.getSubsections(true)); } return secs; } public void setSections(List<DocumentSection> sections) { this.sections = sections; } public void addSection(DocumentSection section) { sections.add(section); } }
1,665
28.75
78
java
CERMINE
CERMINE-master/cermine-impl/src/main/java/pl/edu/icm/cermine/content/model/DocumentSection.java
/** * This file is part of CERMINE project. * Copyright (c) 2011-2018 ICM-UW * * CERMINE is free software: you can redistribute it and/or modify * it under the terms of the GNU Affero General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * CERMINE is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU Affero General Public License for more details. * * You should have received a copy of the GNU Affero General Public License * along with CERMINE. If not, see <http://www.gnu.org/licenses/>. */ package pl.edu.icm.cermine.content.model; import java.util.ArrayList; import java.util.List; /** * @author Dominika Tkaczyk (d.tkaczyk@icm.edu.pl) */ public class DocumentSection { private int level; private String title; private final List<String> paragraphs = new ArrayList<String>(); private final List<DocumentSection> subsections = new ArrayList<DocumentSection>(); public List<DocumentSection> getSubsections() { return getSubsections(false); } public List<DocumentSection> getSubsections(boolean recursive) { if (!recursive) { return subsections; } List<DocumentSection> secs = new ArrayList<DocumentSection>(); for (DocumentSection sec : subsections) { secs.add(sec); secs.addAll(sec.getSubsections(true)); } return secs; } public void addSection(DocumentSection part) { subsections.add(part); } public List<String> getParagraphs() { return paragraphs; } public void addParagraph(String paragraph) { paragraphs.add(paragraph); } public int getLevel() { return level; } public void setLevel(int level) { this.level = level; } public String getTitle() { return title; } public void setTitle(String title) { this.title = title; } }
2,148
25.207317
87
java
CERMINE
CERMINE-master/cermine-impl/src/main/java/pl/edu/icm/cermine/content/transformers/DocContentStructToNLMElementConverter.java
/** * This file is part of CERMINE project. * Copyright (c) 2011-2018 ICM-UW * * CERMINE is free software: you can redistribute it and/or modify * it under the terms of the GNU Affero General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * CERMINE is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU Affero General Public License for more details. * * You should have received a copy of the GNU Affero General Public License * along with CERMINE. If not, see <http://www.gnu.org/licenses/>. */ package pl.edu.icm.cermine.content.transformers; import java.util.ArrayList; import java.util.Collections; import java.util.Comparator; import java.util.List; import org.apache.commons.lang.StringUtils; import org.jdom.Element; import pl.edu.icm.cermine.content.citations.CitationPosition; import pl.edu.icm.cermine.content.citations.ContentStructureCitationPositions; import pl.edu.icm.cermine.content.model.ContentStructure; import pl.edu.icm.cermine.content.model.DocumentSection; import pl.edu.icm.cermine.exception.TransformationException; import pl.edu.icm.cermine.structure.model.BxImage; import pl.edu.icm.cermine.tools.Pair; import pl.edu.icm.cermine.tools.XMLTools; import pl.edu.icm.cermine.tools.transformers.ModelToModelConverter; /** * Writes DocumentContentStructure model to NLM format. * * @author Dominika Tkaczyk (d.tkaczyk@icm.edu.pl) */ public class DocContentStructToNLMElementConverter implements ModelToModelConverter<ContentStructure, Element> { @Override public Element convert(ContentStructure source, Object... hints) throws TransformationException { Element body = new Element("body"); body.addNamespaceDeclaration(XMLTools.NS_XLINK); ContentStructureCitationPositions positions = null; List<BxImage> images = new ArrayList<BxImage>(); for (Object hint : hints) { if (hint instanceof ContentStructureCitationPositions) { positions = (ContentStructureCitationPositions) hint; } if (hint instanceof List) { images = (List<BxImage>) hint; } } body.addContent(toHTML(source, positions, images)); addSectionIds(body); return body; } private List<Element> toHTML(ContentStructure dcs, ContentStructureCitationPositions positions, List<BxImage> images) { List<Element> elements = new ArrayList<Element>(); for (BxImage image : images) { elements.add(toHTML(image)); } for (DocumentSection part : dcs.getSections()) { elements.addAll(toHTML(part, positions)); } return elements; } private Element toHTML(BxImage image) { Element fig = new Element("fig"); Element graphic = new Element("graphic"); graphic.setAttribute("href", image.getPath(), XMLTools.NS_XLINK); fig.addContent(graphic); return fig; } private List<Element> toHTML(DocumentSection part, ContentStructureCitationPositions positions) { List<Element> elements = new ArrayList<Element>(); Element element = new Element("sec"); element.addContent(toHTMLTitle(part.getTitle())); for (int i = 0; i < part.getParagraphs().size(); i++) { String paragraph = part.getParagraphs().get(i); List<Pair<Integer, CitationPosition>> positionList = new ArrayList<Pair<Integer, CitationPosition>>(); if (positions != null) { positionList = positions.getPositions(part, i); Collections.sort(positionList, new Comparator<Pair<Integer, CitationPosition>>() { @Override public int compare(Pair<Integer, CitationPosition> t1, Pair<Integer, CitationPosition> t2) { if (t1.getSecond().getStartRefPosition() != t2.getSecond().getStartRefPosition()) { return Integer.valueOf(t1.getSecond().getStartRefPosition()).compareTo(t2.getSecond().getStartRefPosition()); } return Integer.valueOf(t1.getSecond().getEndRefPosition()).compareTo(t2.getSecond().getEndRefPosition()); } }); } element.addContent(toHTMLParagraph(paragraph, positionList)); } for (DocumentSection subpart : part.getSubsections()) { element.addContent(toHTML(subpart, positions)); } elements.add(element); return elements; } public Element toHTMLTitle(String header) { Element element = new Element("title"); element.setText(XMLTools.removeInvalidXMLChars(header+"\n")); return element; } public Element toHTMLParagraph(String paragraph, List<Pair<Integer, CitationPosition>> positions) { Element element = new Element("p"); int lastParIndex = 0; int posIndex = 0; while (posIndex < positions.size()) { CitationPosition position = positions.get(posIndex).getSecond(); int start = position.getStartRefPosition(); int end = position.getEndRefPosition(); List<Integer> citationIndices = new ArrayList<Integer>(); citationIndices.add(positions.get(posIndex).getFirst()+1); while (++posIndex < positions.size() && positions.get(posIndex).getSecond().getStartRefPosition() == start) { citationIndices.add(positions.get(posIndex).getFirst()+1); } element.addContent(XMLTools.removeInvalidXMLChars(paragraph.substring(lastParIndex, start))); Element ref = new Element("xref"); ref.setAttribute("ref-type", "bibr"); List<String> rids = new ArrayList<String>(); for (Integer ind : citationIndices) { rids.add("ref"+ind); } Collections.sort(rids); ref.setAttribute("rid", StringUtils.join(rids, " ")); ref.setText(XMLTools.removeInvalidXMLChars(paragraph.substring(start, end))); element.addContent(ref); lastParIndex = end; } element.addContent(XMLTools.removeInvalidXMLChars(paragraph.substring(lastParIndex))); return element; } private void addSectionIds(Element element) { List<Element> sections = element.getChildren("sec"); int index = 1; for (Element section : sections) { addSectionIds(section, "", index++); } } private void addSectionIds(Element element, String prefix, int index) { if (!prefix.isEmpty()) { prefix += "-"; } String id = prefix + index; element.setAttribute("id", "sec-" + id); List<Element> sections = element.getChildren("sec"); int i = 1; for (Element section : sections) { addSectionIds(section, id, i++); } } @Override public List<Element> convertAll(List<ContentStructure> source, Object... hints) throws TransformationException { throw new UnsupportedOperationException("Not supported yet."); } }
7,400
41.291429
137
java
CERMINE
CERMINE-master/cermine-impl/src/main/java/pl/edu/icm/cermine/content/transformers/NLMToHTMLWriter.java
/** * This file is part of CERMINE project. * Copyright (c) 2011-2018 ICM-UW * * CERMINE is free software: you can redistribute it and/or modify * it under the terms of the GNU Affero General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * CERMINE is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU Affero General Public License for more details. * * You should have received a copy of the GNU Affero General Public License * along with CERMINE. If not, see <http://www.gnu.org/licenses/>. */ package pl.edu.icm.cermine.content.transformers; import java.io.IOException; import java.io.StringWriter; import java.io.Writer; import java.util.ArrayList; import java.util.List; import org.jdom.Element; import org.jdom.output.Format; import org.jdom.output.XMLOutputter; import pl.edu.icm.cermine.exception.TransformationException; import pl.edu.icm.cermine.tools.transformers.ModelToFormatWriter; /** * Writes DocumentContentStructure model to NLM format. * * @author Dominika Tkaczyk (d.tkaczyk@icm.edu.pl) */ public class NLMToHTMLWriter implements ModelToFormatWriter<Element> { @Override public String write(Element object, Object... hints) throws TransformationException { StringWriter sw = new StringWriter(); write(sw, object, hints); return sw.toString(); } @Override public void write(Writer writer, Element object, Object... hints) throws TransformationException { Element html = new Element("html"); Element body = object.getChild("body"); if (body != null) { List<Element> sections = body.getChildren("sec"); for (Element section : sections) { for (Element el : toHTML(section, 1)) { html.addContent(el); } } } XMLOutputter outputter = new XMLOutputter(Format.getPrettyFormat()); try { outputter.output(html, writer); } catch (IOException ex) { throw new TransformationException("", ex); } } private List<Element> toHTML(Element section, int level) { List<Element> elements = new ArrayList<Element>(); List<Element> children = section.getChildren(); for (Element child : children) { if ("title".equals(child.getName())) { Element element = new Element("H"+level); element.setText(child.getText()); elements.add(element); } else if ("p".equals(child.getName())) { Element el = new Element("p"); el.setText(child.getText()); elements.add(el); } else if ("sec".equals(child.getName())) { elements.addAll(toHTML(child, level+1)); } } return elements; } @Override public String writeAll(List<Element> objects, Object... hints) throws TransformationException { throw new UnsupportedOperationException("Not supported yet."); } @Override public void writeAll(Writer writer, List<Element> objects, Object... hints) throws TransformationException { throw new UnsupportedOperationException("Not supported yet."); } }
3,450
34.947917
112
java
CERMINE
CERMINE-master/cermine-impl/src/main/java/pl/edu/icm/cermine/content/transformers/BxContentToDocContentConverter.java
/** * This file is part of CERMINE project. * Copyright (c) 2011-2018 ICM-UW * * CERMINE is free software: you can redistribute it and/or modify * it under the terms of the GNU Affero General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * CERMINE is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU Affero General Public License for more details. * * You should have received a copy of the GNU Affero General Public License * along with CERMINE. If not, see <http://www.gnu.org/licenses/>. */ package pl.edu.icm.cermine.content.transformers; import java.util.ArrayList; import java.util.List; import pl.edu.icm.cermine.content.model.BxContentStructure; import pl.edu.icm.cermine.content.model.BxContentStructure.BxDocContentPart; import pl.edu.icm.cermine.content.model.ContentStructure; import pl.edu.icm.cermine.content.model.DocumentSection; import pl.edu.icm.cermine.exception.TransformationException; import pl.edu.icm.cermine.tools.transformers.ModelToModelConverter; /** * @author Dominika Tkaczyk (d.tkaczyk@icm.edu.pl) */ public class BxContentToDocContentConverter implements ModelToModelConverter<BxContentStructure, ContentStructure> { @Override public ContentStructure convert(BxContentStructure contentStructure, Object... hints) throws TransformationException { ContentStructure dcs = new ContentStructure(); List<BxDocContentPart> sectionContentParts = new ArrayList<BxDocContentPart>(); if (contentStructure.getParts().isEmpty()) { return dcs; } int topClusterNum = contentStructure.getParts().get(0).getLevelId(); for (BxDocContentPart contentPart : contentStructure.getParts()) { if (contentPart.getLevelId() == topClusterNum && !sectionContentParts.isEmpty()) { DocumentSection dcp = convertContentPart(sectionContentParts, 1); dcs.addSection(dcp); sectionContentParts.clear(); } sectionContentParts.add(contentPart); } if (!sectionContentParts.isEmpty()) { DocumentSection dcp = convertContentPart(sectionContentParts, 1); dcs.addSection(dcp); } return dcs; } private DocumentSection convertContentPart(List<BxDocContentPart> contentParts, int level) { DocumentSection section = new DocumentSection(); if (contentParts.isEmpty()) { return section; } section.setLevel(level); section.setTitle(contentParts.get(0).getCleanHeaderText()); for (String contentText : contentParts.get(0).getCleanContentTexts()) { section.addParagraph(contentText); } contentParts.remove(0); if (contentParts.isEmpty()) { return section; } int topClusterNum = contentParts.get(0).getLevelId(); List<BxDocContentPart> sectionContentParts = new ArrayList<BxDocContentPart>(); for (BxDocContentPart contentPart : contentParts) { if (contentPart.getLevelId() == topClusterNum && !sectionContentParts.isEmpty()) { DocumentSection dcp = convertContentPart(sectionContentParts, level + 1); section.addSection(dcp); sectionContentParts.clear(); } sectionContentParts.add(contentPart); } if (!sectionContentParts.isEmpty()) { DocumentSection dcp = convertContentPart(sectionContentParts, level + 1); section.addSection(dcp); } return section; } @Override public List<ContentStructure> convertAll(List<BxContentStructure> source, Object... hints) throws TransformationException { throw new UnsupportedOperationException("Not supported yet."); } }
4,050
38.330097
127
java
CERMINE
CERMINE-master/cermine-impl/src/main/java/pl/edu/icm/cermine/content/transformers/DocContentToHTMLWriter.java
/** * This file is part of CERMINE project. * Copyright (c) 2011-2018 ICM-UW * * CERMINE is free software: you can redistribute it and/or modify * it under the terms of the GNU Affero General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * CERMINE is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU Affero General Public License for more details. * * You should have received a copy of the GNU Affero General Public License * along with CERMINE. If not, see <http://www.gnu.org/licenses/>. */ package pl.edu.icm.cermine.content.transformers; import java.io.IOException; import java.io.StringWriter; import java.io.Writer; import java.util.ArrayList; import java.util.List; import org.jdom.Element; import org.jdom.output.Format; import org.jdom.output.XMLOutputter; import pl.edu.icm.cermine.content.model.ContentStructure; import pl.edu.icm.cermine.content.model.DocumentSection; import pl.edu.icm.cermine.exception.TransformationException; import pl.edu.icm.cermine.tools.XMLTools; import pl.edu.icm.cermine.tools.transformers.ModelToFormatWriter; /** * Writes DocumentContentStructure model to HTML format. * * @author Dominika Tkaczyk (d.tkaczyk@icm.edu.pl) */ public class DocContentToHTMLWriter implements ModelToFormatWriter<ContentStructure> { @Override public String write(ContentStructure object, Object... hints) throws TransformationException { StringWriter sw = new StringWriter(); write(sw, object, hints); return sw.toString(); } @Override public void write(Writer writer, ContentStructure object, Object... hints) throws TransformationException { try { Element element = toHTML(object); XMLOutputter outputter = new XMLOutputter(Format.getPrettyFormat()); outputter.output(element, writer); } catch (IOException ex) { throw new TransformationException(ex); } } private Element toHTML(ContentStructure dcs) { Element element = new Element("html"); for (DocumentSection part : dcs.getSections()) { element.addContent(toHTML(part)); } return element; } private List<Element> toHTML(DocumentSection part) { List<Element> elements = new ArrayList<Element>(); elements.add(toHTML(part.getLevel(), part.getTitle())); for (String paragraph : part.getParagraphs()) { elements.add(toHTML(paragraph)); } for (DocumentSection subpart : part.getSubsections()) { elements.addAll(toHTML(subpart)); } return elements; } public Element toHTML(int level, String header) { Element element = new Element("H" + level); element.setText(XMLTools.removeInvalidXMLChars(header)); return element; } public Element toHTML(String paragraph) { Element element = new Element("p"); element.setText(XMLTools.removeInvalidXMLChars(paragraph)); return element; } @Override public String writeAll(List<ContentStructure> objects, Object... hints) throws TransformationException { throw new UnsupportedOperationException("Not supported yet."); } @Override public void writeAll(Writer writer, List<ContentStructure> objects, Object... hints) throws TransformationException { throw new UnsupportedOperationException("Not supported yet."); } }
3,654
34.833333
121
java
CERMINE
CERMINE-master/cermine-impl/src/main/java/pl/edu/icm/cermine/content/transformers/HTMLToDocContentReader.java
/** * This file is part of CERMINE project. * Copyright (c) 2011-2018 ICM-UW * * CERMINE is free software: you can redistribute it and/or modify * it under the terms of the GNU Affero General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * CERMINE is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU Affero General Public License for more details. * * You should have received a copy of the GNU Affero General Public License * along with CERMINE. If not, see <http://www.gnu.org/licenses/>. */ package pl.edu.icm.cermine.content.transformers; import java.io.IOException; import java.io.Reader; import java.io.StringReader; import java.util.ArrayList; import java.util.List; import java.util.Locale; import org.jdom.Element; import org.jdom.JDOMException; import org.jdom.input.SAXBuilder; import pl.edu.icm.cermine.content.model.ContentStructure; import pl.edu.icm.cermine.content.model.DocumentSection; import pl.edu.icm.cermine.exception.TransformationException; import pl.edu.icm.cermine.tools.transformers.FormatToModelReader; /** * Reads DocumentContentStructure model from HTML format. * * @author Dominika Tkaczyk (d.tkaczyk@icm.edu.pl) */ public class HTMLToDocContentReader implements FormatToModelReader<ContentStructure> { @Override public ContentStructure read(String string, Object... hints) throws TransformationException { return read(new StringReader(string), hints); } @Override public ContentStructure read(Reader reader, Object... hints) throws TransformationException { try { Element root = getRoot(reader); ContentStructure dcs = new ContentStructure(); List<Element> elements = root.getChildren(); if (elements.isEmpty()) { return dcs; } int index = 0; Element current = elements.get(0); while (current != null && isParagraph(current)) { current = getNext(++index, elements); } if (current == null) { return dcs; } int nextLevel = getHeaderLevel(current); List<Element> els = new ArrayList<Element>(); while (current != null) { if (isHeader(current) && nextLevel == getHeaderLevel(current) && !els.isEmpty()) { DocumentSection n = createPart(els, 1); dcs.addSection(n); els.clear(); } els.add(current); current = getNext(++index, elements); } if (!els.isEmpty()) { DocumentSection n = createPart(els, 1); dcs.addSection(n); } return dcs; } catch (JDOMException ex) { throw new TransformationException(ex); } catch (IOException ex) { throw new TransformationException(ex); } } private Element getRoot(Reader reader) throws JDOMException, IOException { SAXBuilder saxBuilder = new SAXBuilder("org.apache.xerces.parsers.SAXParser"); org.jdom.Document dom = saxBuilder.build(reader); return dom.getRootElement(); } private DocumentSection createPart(List<Element> elements, int level) { DocumentSection section = new DocumentSection(); if (elements.isEmpty()) { return section; } int index = 0; Element current = elements.get(0); section.setLevel(level); section.setTitle(current.getValue()); current = getNext(++index, elements); while (current != null && isParagraph(current)) { section.addParagraph(current.getValue()); current = getNext(++index, elements); } if (current == null) { return section; } int nextLevel = getHeaderLevel(current); List<Element> els = new ArrayList<Element>(); while (current != null) { if (isHeader(current) && nextLevel == getHeaderLevel(current) && !els.isEmpty()) { DocumentSection n = createPart(els, level+1); section.addSection(n); els.clear(); } els.add(current); current = getNext(++index, elements); } if (!els.isEmpty()) { DocumentSection n = createPart(els, level+1); section.addSection(n); } return section; } private boolean isHeader(Element element) { return element.getName().toLowerCase(Locale.ENGLISH).startsWith("h"); } private boolean isParagraph(Element element) { return element.getName().equals("p"); } private int getHeaderLevel(Element element) { return Integer.parseInt(element.getName().replaceAll("[^0-9]+", "")); } private Element getNext(int index, List<Element> elements) { if (index < elements.size()) { return elements.get(index); } return null; } @Override public List<ContentStructure> readAll(String string, Object... hints) throws TransformationException { throw new UnsupportedOperationException("Not supported yet."); } @Override public List<ContentStructure> readAll(Reader reader, Object... hints) throws TransformationException { throw new UnsupportedOperationException("Not supported yet."); } }
5,776
33.386905
106
java
CERMINE
CERMINE-master/cermine-impl/src/main/java/pl/edu/icm/cermine/content/headers/SVMContentHeadersExtractor.java
/** * This file is part of CERMINE project. * Copyright (c) 2011-2018 ICM-UW * * CERMINE is free software: you can redistribute it and/or modify * it under the terms of the GNU Affero General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * CERMINE is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU Affero General Public License for more details. * * You should have received a copy of the GNU Affero General Public License * along with CERMINE. If not, see <http://www.gnu.org/licenses/>. */ package pl.edu.icm.cermine.content.headers; import java.io.BufferedReader; import pl.edu.icm.cermine.content.model.BxContentStructure; import pl.edu.icm.cermine.exception.AnalysisException; import pl.edu.icm.cermine.structure.model.*; /** * @author Dominika Tkaczyk (d.tkaczyk@icm.edu.pl) */ public class SVMContentHeadersExtractor implements ContentHeadersExtractor { private static final String MODEL_FILE_PATH = "/pl/edu/icm/cermine/content/header.model"; private static final String RANGE_FILE_PATH = "/pl/edu/icm/cermine/content/header.range"; private SVMHeaderLinesClassifier contentHeaderClassifier; private SingleLinkageHeadersClusterizer headersClusterizer; private HeaderLinesCompletener headerLinesCompletener; public SVMContentHeadersExtractor() throws AnalysisException { this(MODEL_FILE_PATH, RANGE_FILE_PATH); } public SVMContentHeadersExtractor(SVMHeaderLinesClassifier contentHeaderClassifier) { this.contentHeaderClassifier = contentHeaderClassifier; this.headersClusterizer = new SingleLinkageHeadersClusterizer(); this.headerLinesCompletener = new HeaderLinesCompletener(); } public SVMContentHeadersExtractor(BufferedReader modelFile, BufferedReader rangeFile) throws AnalysisException { this.contentHeaderClassifier = new SVMHeaderLinesClassifier(modelFile, rangeFile); this.headersClusterizer = new SingleLinkageHeadersClusterizer(); this.headerLinesCompletener = new HeaderLinesCompletener(); } public SVMContentHeadersExtractor(String modelFilePath, String rangeFilePath) throws AnalysisException { this.contentHeaderClassifier = new SVMHeaderLinesClassifier(modelFilePath, rangeFilePath); this.headersClusterizer = new SingleLinkageHeadersClusterizer(); this.headerLinesCompletener = new HeaderLinesCompletener(); } private boolean isHeader(BxLine line, BxPage page) { BxZoneLabel label = contentHeaderClassifier.predictLabel(line, page); return label.equals(BxZoneLabel.BODY_HEADING); } @Override public BxContentStructure extractHeaders(BxDocument document) throws AnalysisException { BxContentStructure contentStructure = new BxContentStructure(); BxLine lastHeaderLine = null; for (BxPage page : document) { for (BxZone zone : page) { if (zone.getLabel().isOfCategoryOrGeneral(BxZoneLabelCategory.CAT_BODY)) { for (BxLine line : zone) { if (isHeader(line, page)) { contentStructure.addFirstHeaderLine(page, line); lastHeaderLine = line; } else if (zone.getLabel().equals(BxZoneLabel.BODY_CONTENT) || zone.getLabel().equals(BxZoneLabel.GEN_BODY)) { if (lastHeaderLine == null) { BxChunk chunk = new BxChunk(new BxBounds(), "--"); BxWord word = new BxWord().addChunk(chunk); lastHeaderLine = new BxLine().addWord(word); contentStructure.addFirstHeaderLine(page, lastHeaderLine); } contentStructure.addContentLine(lastHeaderLine, line); } } } } } headersClusterizer.clusterHeaders(contentStructure); headerLinesCompletener.completeLines(contentStructure); return contentStructure; } }
4,358
42.158416
134
java
CERMINE
CERMINE-master/cermine-impl/src/main/java/pl/edu/icm/cermine/content/headers/HeadersClusterizer.java
/** * This file is part of CERMINE project. * Copyright (c) 2011-2018 ICM-UW * * CERMINE is free software: you can redistribute it and/or modify * it under the terms of the GNU Affero General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * CERMINE is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU Affero General Public License for more details. * * You should have received a copy of the GNU Affero General Public License * along with CERMINE. If not, see <http://www.gnu.org/licenses/>. */ package pl.edu.icm.cermine.content.headers; import pl.edu.icm.cermine.content.model.BxContentStructure; /** * @author Dominika Tkaczyk (d.tkaczyk@icm.edu.pl) */ public interface HeadersClusterizer { void clusterHeaders(BxContentStructure contentStructure); }
1,010
31.612903
78
java
CERMINE
CERMINE-master/cermine-impl/src/main/java/pl/edu/icm/cermine/content/headers/ContentHeadersExtractor.java
/** * This file is part of CERMINE project. * Copyright (c) 2011-2018 ICM-UW * * CERMINE is free software: you can redistribute it and/or modify * it under the terms of the GNU Affero General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * CERMINE is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU Affero General Public License for more details. * * You should have received a copy of the GNU Affero General Public License * along with CERMINE. If not, see <http://www.gnu.org/licenses/>. */ package pl.edu.icm.cermine.content.headers; import pl.edu.icm.cermine.content.model.BxContentStructure; import pl.edu.icm.cermine.exception.AnalysisException; import pl.edu.icm.cermine.structure.model.BxDocument; /** * @author Dominika Tkaczyk (d.tkaczyk@icm.edu.pl) */ public interface ContentHeadersExtractor { BxContentStructure extractHeaders(BxDocument document) throws AnalysisException; }
1,147
33.787879
84
java
CERMINE
CERMINE-master/cermine-impl/src/main/java/pl/edu/icm/cermine/content/headers/SimpleHeadersClusterizer.java
/** * This file is part of CERMINE project. * Copyright (c) 2011-2018 ICM-UW * * CERMINE is free software: you can redistribute it and/or modify * it under the terms of the GNU Affero General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * CERMINE is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU Affero General Public License for more details. * * You should have received a copy of the GNU Affero General Public License * along with CERMINE. If not, see <http://www.gnu.org/licenses/>. */ package pl.edu.icm.cermine.content.headers; import java.util.HashSet; import java.util.List; import java.util.Set; import pl.edu.icm.cermine.content.model.BxContentStructure; import pl.edu.icm.cermine.structure.model.BxLine; /** * @author Dominika Tkaczyk (d.tkaczyk@icm.edu.pl) */ public class SimpleHeadersClusterizer implements HeadersClusterizer { public static final double DEFAULT_MAX_HEIGHT_DIFF = 1; private double maxHeightDiff = DEFAULT_MAX_HEIGHT_DIFF; @Override public void clusterHeaders(BxContentStructure contentStructure) { List<BxLine> lines = contentStructure.getFirstHeaderLines(); contentStructure.setHeaderLevelIds(clusterLines(lines)); } public int[] clusterLines(List<BxLine> lines) { int[] clusters = new int[lines.size()]; Set<BxLine> done = new HashSet<BxLine>(); int i = 0; for (BxLine line : lines) { if (line.getMostPopularFontName() == null) { clusters[lines.indexOf(line)] = 0; done.add(line); } if (done.contains(line)) { continue; } for (BxLine line2 : lines) { if (line2.getMostPopularFontName() == null) { clusters[lines.indexOf(line2)] = 0; done.add(line2); } if (line.getMostPopularFontName().equals(line2.getMostPopularFontName()) && Math.abs(line.getHeight()-line2.getHeight()) < maxHeightDiff) { clusters[lines.indexOf(line2)] = i; done.add(line2); } } i++; } return clusters; } public double getMaxHeightDiff() { return maxHeightDiff; } public void setMaxHeightDiff(double maxHeightDiff) { this.maxHeightDiff = maxHeightDiff; } }
2,663
32.3
89
java
CERMINE
CERMINE-master/cermine-impl/src/main/java/pl/edu/icm/cermine/content/headers/SingleLinkageHeadersClusterizer.java
/** * This file is part of CERMINE project. * Copyright (c) 2011-2018 ICM-UW * * CERMINE is free software: you can redistribute it and/or modify * it under the terms of the GNU Affero General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * CERMINE is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU Affero General Public License for more details. * * You should have received a copy of the GNU Affero General Public License * along with CERMINE. If not, see <http://www.gnu.org/licenses/>. */ package pl.edu.icm.cermine.content.headers; import pl.edu.icm.cermine.content.model.BxContentStructure; import pl.edu.icm.cermine.structure.model.BxLine; import pl.edu.icm.cermine.structure.model.BxPage; import pl.edu.icm.cermine.tools.classification.clustering.Clusterizer; import pl.edu.icm.cermine.tools.classification.clustering.FeatureVectorClusterizer; import pl.edu.icm.cermine.tools.classification.clustering.SingleLinkageClusterizer; import pl.edu.icm.cermine.tools.classification.general.FeatureVectorBuilder; import pl.edu.icm.cermine.tools.distance.FeatureVectorDistanceMetric; import pl.edu.icm.cermine.tools.distance.FeatureVectorEuclideanMetric; /** * @author Dominika Tkaczyk (d.tkaczyk@icm.edu.pl) */ public class SingleLinkageHeadersClusterizer implements HeadersClusterizer { public static final double DEFAULT_MAX_HEADER_LEV_DIST = 1; private double maxHeaderLevelDistance = DEFAULT_MAX_HEADER_LEV_DIST; private FeatureVectorBuilder<BxLine, BxPage> vectorBuilder; private Clusterizer clusterizer; private FeatureVectorDistanceMetric metric; public SingleLinkageHeadersClusterizer() { this.vectorBuilder = HeaderExtractingTools.CLUSTERING_VB; this.clusterizer = new SingleLinkageClusterizer(); this.metric = new FeatureVectorEuclideanMetric(); } public SingleLinkageHeadersClusterizer(FeatureVectorBuilder<BxLine, BxPage> vectorBuilder, Clusterizer clusterizer, FeatureVectorDistanceMetric metric) { this.vectorBuilder = vectorBuilder; this.clusterizer = clusterizer; this.metric = metric; } @Override public void clusterHeaders(BxContentStructure contentStructure) { FeatureVectorClusterizer fvClusterizer = new FeatureVectorClusterizer(); fvClusterizer.setClusterizer(clusterizer); int[] clusters = fvClusterizer.clusterize(contentStructure.getFirstHeaderFeatureVectors(vectorBuilder), vectorBuilder, metric, maxHeaderLevelDistance, true); contentStructure.setHeaderLevelIds(clusters); } public void setClusterizer(Clusterizer clusterizer) { this.clusterizer = clusterizer; } public void setMaxHeaderLevelDistance(double maxHeaderLevelDistance) { this.maxHeaderLevelDistance = maxHeaderLevelDistance; } public void setMetric(FeatureVectorDistanceMetric metric) { this.metric = metric; } public void setVectorBuilder(FeatureVectorBuilder<BxLine, BxPage> vectorBuilder) { this.vectorBuilder = vectorBuilder; } }
3,326
38.607143
157
java
CERMINE
CERMINE-master/cermine-impl/src/main/java/pl/edu/icm/cermine/content/headers/HeuristicContentHeadersExtractor.java
/** * This file is part of CERMINE project. * Copyright (c) 2011-2018 ICM-UW * * CERMINE is free software: you can redistribute it and/or modify * it under the terms of the GNU Affero General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * CERMINE is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU Affero General Public License for more details. * * You should have received a copy of the GNU Affero General Public License * along with CERMINE. If not, see <http://www.gnu.org/licenses/>. */ package pl.edu.icm.cermine.content.headers; import com.google.common.collect.Lists; import com.google.common.collect.Sets; import java.util.Map.Entry; import java.util.*; import pl.edu.icm.cermine.content.model.BxContentStructure; import pl.edu.icm.cermine.exception.AnalysisException; import pl.edu.icm.cermine.structure.model.*; import pl.edu.icm.cermine.tools.CountMap; import pl.edu.icm.cermine.tools.statistics.Population; import pl.edu.icm.cermine.tools.timeout.TimeoutRegister; /** * @author Dominika Tkaczyk (d.tkaczyk@icm.edu.pl) */ public class HeuristicContentHeadersExtractor implements ContentHeadersExtractor { private final SimpleHeadersClusterizer headersClusterizer; private final HeaderLinesCompletener headerLinesCompletener; public HeuristicContentHeadersExtractor() { this.headersClusterizer = new SimpleHeadersClusterizer(); this.headerLinesCompletener = new HeaderLinesCompletener(); } @Override public BxContentStructure extractHeaders(BxDocument document) throws AnalysisException { Population heightPopulation = new Population(); Population fontPopulation = new Population(); Population distancePopulation = new Population(); Population lengthPopulation = new Population(); Population indentationPopulation = new Population(); Set<BxLine> candidates = new HashSet<BxLine>(); for (BxPage page : document) { for (BxZone zone : page) { if (zone.getLabel().equals(BxZoneLabel.BODY_CONTENT) || zone.getLabel().equals(BxZoneLabel.GEN_BODY)) { for (BxLine line : zone) { heightPopulation.addObservation(line.getHeight()); lengthPopulation.addObservation(line.getWidth()); indentationPopulation.addObservation(line.getX()); if (line.hasPrev() && line.getY()-line.getPrev().getY() > 0) { distancePopulation.addObservation(line.getY()-line.getPrev().getY()); } fontPopulation.addObservation(getFontIndex(line)); if (isFirstInZone(line) && looksLikeHeader(line)) { candidates.add(line); } TimeoutRegister.get().check(); } } } } Set<BxLine> toDelete = new HashSet<BxLine>(); for (BxLine line : candidates){ if (shouldBeRemoved(line, heightPopulation, fontPopulation, distancePopulation, indentationPopulation)) { toDelete.add(line); } if (lengthPopulation.getZScore(line.getWidth()) > CAND_MAX_LENGTH_ZSCORE) { toDelete.add(line); } } candidates.removeAll(toDelete); toDelete.clear(); Set<String> headerFonts = new HashSet<String>(); List<BxLine> candidatesList = Lists.newArrayList(candidates); Set<String> docFontPopulation = Sets.newHashSet(); if (!candidatesList.isEmpty()) { docFontPopulation = candidatesList.get(0).getParent().getParent().getParent().getFontNames(); } CountMap<String> fontCandidates = new CountMap<String>(); for (int x = 0; x < candidatesList.size(); x++) { fontCandidates.add(candidatesList.get(x).getMostPopularFontName()); } for (Entry<String, Integer> entry : fontCandidates.getSortedEntries(3)) { if (Math.abs(fontPopulation.getZScore(getFontIndex(entry.getKey(), docFontPopulation))) > OUTL_FONT_ZSCORE) { headerFonts.add(entry.getKey()); } TimeoutRegister.get().check(); } for (BxPage page : document) { for (BxZone zone : page) { if (zone.getLabel().equals(BxZoneLabel.BODY_CONTENT) || zone.getLabel().equals(BxZoneLabel.GEN_BODY)) { for (BxLine line : zone) { if (looksLikeHeader(line) && headerFonts.contains(line.getMostPopularFontName())) { candidates.add(line); } } } } } for (BxLine line : candidates){ if (shouldBeRemoved(line, heightPopulation, fontPopulation, distancePopulation, indentationPopulation)) { toDelete.add(line); } if (lengthPopulation.getZScore(line.getWidth()) > CAND_MAX_LENGTH_ZSCORE_2) { toDelete.add(line); } } candidates.removeAll(toDelete); toDelete.clear(); for (BxLine line : candidates) { int i = 0; for (BxLine line2 : candidates) { if (line.equals(line2)) { continue; } if (areSimilar(line, line2)) { i++; } } if (i == 0 || i > MAX_SIMILAR_LINES_COUNT) { toDelete.add(line); for (BxLine line2 : candidates) { if (areSimilar(line, line2)) { toDelete.add(line2); } } } } candidates.removeAll(toDelete); candidatesList = new ArrayList<BxLine>(); for (BxPage page : document) { for (BxZone zone : page) { for (BxLine line : zone) { if (candidates.contains(line)) { candidatesList.add(line); } } } } int clusters[] = headersClusterizer.clusterLines(candidatesList); Set<Integer> keptClusters = new HashSet<Integer>(); for (int clusterIdx = 0; clusterIdx < clusters.length; clusterIdx++) { int cluster = clusters[clusterIdx]; if (keptClusters.size() < 3) { keptClusters.add(cluster); } if (!keptClusters.contains(cluster)) { candidates.remove(candidatesList.get(clusterIdx)); } } BxContentStructure contentStructure = new BxContentStructure(); BxLine lastHeaderLine = null; for (BxPage page : document) { for (BxZone zone : page) { if (zone.getLabel().equals(BxZoneLabel.BODY_CONTENT) || zone.getLabel().equals(BxZoneLabel.GEN_BODY)) { for (BxLine line : zone) { if (candidates.contains(line)) { contentStructure.addFirstHeaderLine(page, line); lastHeaderLine = line; } else if (zone.getLabel().equals(BxZoneLabel.BODY_CONTENT) || zone.getLabel().equals(BxZoneLabel.GEN_BODY)) { if (lastHeaderLine == null) { BxChunk chunk = new BxChunk(new BxBounds(), "--"); BxWord word = new BxWord().addChunk(chunk); lastHeaderLine = new BxLine().addWord(word); contentStructure.addFirstHeaderLine(page, lastHeaderLine); } contentStructure.addContentLine(lastHeaderLine, line); } } } } } headerLinesCompletener.completeLines(contentStructure); return contentStructure; } private double getFontIndex(BxLine line) { return getFontIndex(line.getMostPopularFontName(), line.getParent().getParent().getParent().getFontNames()); } private double getFontIndex(String fontName, Set<String> population) { List<String> fonts = Lists.newArrayList(population); Collections.sort(fonts); return fonts.indexOf(fontName); } private boolean isFirstInZone(BxLine line) { return !line.hasPrev() || line.getParent() != line.getPrev().getParent(); } private boolean looksLikeHeader(BxLine line) { String text = line.toText(); return text.matches("^[A-Z].*") || text.matches("^[1-9].*[a-zA-Z].*") || text.matches("^[a-h]\\).*[a-zA-Z].*"); } private boolean looksLikeEquation(BxLine line) { return line.toText().contains("="); } private boolean looksLikeFigure(BxLine line) { return line.toText().toLowerCase(Locale.ENGLISH).matches("fig\\.? .*") || line.toText().toLowerCase(Locale.ENGLISH).matches("figure .*"); } private boolean looksLikeTable(BxLine line) { return line.toText().toLowerCase(Locale.ENGLISH).matches("table .*"); } private boolean containsMostlyLetters(BxLine line) { double letterCount = 0; for (char ch : line.toText().toCharArray()) { if (Character.isLetter(ch)) { letterCount++; } } return 2*letterCount > line.toText().length(); } private boolean containsWord(BxLine line) { return line.toText().toLowerCase(Locale.ENGLISH).matches(".*[a-z][a-z][a-z][a-z].*"); } private boolean startsWithLargeNumber(BxLine line) { return line.toText().matches("[0-9][0-9].*"); } private boolean areSimilar(BxLine line1, BxLine line2){ return line1.getMostPopularFontName().equals(line2.getMostPopularFontName()) && Math.abs(line1.getHeight()-line2.getHeight()) < MAX_HEIGHT_SIMILARITY; } private boolean shouldBeRemoved(BxLine line, Population heightPopulation, Population fontPopulation, Population distancePopulation, Population indentationPopulation) { if (line.getMostPopularFontName() == null) { return true; } if (heightPopulation.getZScore(line.getHeight()) < CAND_MIN_HEIGHT_ZSCORE) { return true; } if (looksLikeEquation(line)) { return true; } if (looksLikeFigure(line)) { return true; } if (looksLikeTable(line)) { return true; } if (!containsMostlyLetters(line)) { return true; } if (!containsWord(line)) { return true; } if (startsWithLargeNumber(line)) { return true; } if (heightPopulation.getZScore(line.getHeight()) < OUTL_HEIGHT_ZSCORE && Math.abs(fontPopulation.getZScore(getFontIndex(line))) < OUTL_FONT_ZSCORE && (!line.hasPrev() || distancePopulation.getZScore(line.getY()-line.getPrev().getY()) < OUTL_DIST_ZSCORE) && Math.abs(indentationPopulation.getZScore(line.getX())) < OUTL_INDENT_ZSCORE) { return true; } int i = 0; BxLine actLine = line; while (actLine.hasNext()) { actLine = actLine.getNext(); if (actLine.toText().matches("[A-Z].*")) { break; } if (i++ == MAX_HEADER_LINE_COUNT) { return true; } } return false; } private static final double CAND_MAX_LENGTH_ZSCORE = -0.1; private static final double CAND_MAX_LENGTH_ZSCORE_2 = 1; private static final double CAND_MIN_HEIGHT_ZSCORE = -1; private static final double OUTL_HEIGHT_ZSCORE = 0.5; private static final double OUTL_FONT_ZSCORE = 0.5; private static final double OUTL_DIST_ZSCORE = 0.4; private static final double OUTL_INDENT_ZSCORE = 0.5; private static final double MAX_HEIGHT_SIMILARITY = 1; private static final int MAX_SIMILAR_LINES_COUNT = 50; private static final int MAX_HEADER_LINE_COUNT = 5; }
12,803
37.917933
134
java
CERMINE
CERMINE-master/cermine-impl/src/main/java/pl/edu/icm/cermine/content/headers/HeaderExtractingTools.java
/** * This file is part of CERMINE project. * Copyright (c) 2011-2018 ICM-UW * * CERMINE is free software: you can redistribute it and/or modify * it under the terms of the GNU Affero General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * CERMINE is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU Affero General Public License for more details. * * You should have received a copy of the GNU Affero General Public License * along with CERMINE. If not, see <http://www.gnu.org/licenses/>. */ package pl.edu.icm.cermine.content.headers; import java.util.Arrays; import java.util.EnumMap; import java.util.List; import java.util.Map; import pl.edu.icm.cermine.content.headers.features.*; import pl.edu.icm.cermine.exception.AnalysisException; import pl.edu.icm.cermine.exception.TransformationException; import pl.edu.icm.cermine.structure.model.*; import pl.edu.icm.cermine.tools.BxDocUtils; import pl.edu.icm.cermine.tools.classification.general.*; import pl.edu.icm.cermine.tools.classification.sampleselection.OversamplingSelector; import pl.edu.icm.cermine.tools.classification.sampleselection.SampleSelector; /** * @author Dominika Tkaczyk (d.tkaczyk@icm.edu.pl) */ public final class HeaderExtractingTools { public static final FeatureVectorBuilder<BxLine, BxPage> EXTRACT_VB = new FeatureVectorBuilder<BxLine, BxPage>(); static { EXTRACT_VB.setFeatureCalculators(Arrays.<FeatureCalculator<BxLine, BxPage>>asList( new WordsUppercaseFeature(), new RomanDigitsSchemaFeature(), new TripleDigitSchemaFeature(), new PrevSpaceFeature(), new WordsAllUppercaseFeature(), new HeightFeature(), new IsHigherThanNeighborsFeature(), new NextLineIndentationFeature(), new IndentationFeature(), new DigitParSchemaFeature(), new DoubleDigitSchemaFeature(), new LowercaseSchemaFeature(), new UppercaseSchemaFeature(), new LengthFeature(), new DigitDotSchemaFeature() )); } public static final FeatureVectorBuilder<BxLine, BxPage> CLUSTERING_VB = new FeatureVectorBuilder<BxLine, BxPage>(); static { CLUSTERING_VB.setFeatureCalculators(Arrays.<FeatureCalculator<BxLine, BxPage>>asList( new DigitDotSchemaFeature(), new DigitParSchemaFeature(), new DoubleDigitSchemaFeature(), new LowercaseSchemaFeature(), new RomanDigitsSchemaFeature(), new TripleDigitSchemaFeature(), new UppercaseSchemaFeature() )); } public static List<TrainingSample<BxZoneLabel>> toTrainingSamples(String trainPath) throws AnalysisException, TransformationException { List<BxDocument> documents = BxDocUtils.getDocumentsFromPath(trainPath); return toTrainingSamples(documents); } public static List<TrainingSample<BxZoneLabel>> toTrainingSamples(List<BxDocument> documents) throws AnalysisException { List<TrainingSample<BxZoneLabel>> trainingSamples; SampleSelector<BxZoneLabel> selector = new OversamplingSelector<BxZoneLabel>(1.0); Map<BxZoneLabel, BxZoneLabel> map = new EnumMap<BxZoneLabel, BxZoneLabel>(BxZoneLabel.class); map.put(BxZoneLabel.BODY_JUNK, BxZoneLabel.BODY_CONTENT); trainingSamples = BxDocsToTrainingSamplesConverter.getLineTrainingSamples(documents, EXTRACT_VB, map); trainingSamples = ClassificationUtils.filterElements(trainingSamples, BxZoneLabelCategory.CAT_BODY); trainingSamples = selector.pickElements(trainingSamples); return trainingSamples; } private HeaderExtractingTools() { } }
4,096
41.237113
139
java
CERMINE
CERMINE-master/cermine-impl/src/main/java/pl/edu/icm/cermine/content/headers/HeaderLinesCompletener.java
/** * This file is part of CERMINE project. * Copyright (c) 2011-2018 ICM-UW * * CERMINE is free software: you can redistribute it and/or modify * it under the terms of the GNU Affero General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * CERMINE is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU Affero General Public License for more details. * * You should have received a copy of the GNU Affero General Public License * along with CERMINE. If not, see <http://www.gnu.org/licenses/>. */ package pl.edu.icm.cermine.content.headers; import java.util.ArrayList; import java.util.List; import pl.edu.icm.cermine.content.model.BxContentStructure; import pl.edu.icm.cermine.structure.model.BxLine; /** * @author Dominika Tkaczyk (d.tkaczyk@icm.edu.pl) */ public class HeaderLinesCompletener { public static final int DEFAULT_MAX_ADDED_LINES = 2; public static final double DEFAULT_HEADER_HEIGHT_TOL = 0.1; public static final int DEFAULT_MIN_HEADER_SCORE = 2; public static final double DEFAULT_HEADER_LINE_WIDTH_MULT = 0.7; public static final double DEFAULT_HEADER_LINE_MULT = 0.7; public static final int DEFAULT_MIN_HEADER_LINE_SCORE = 2; /** * The maximum number of additional line following the first header line added as a part of the header. */ private int maxAddedHeaderLines = DEFAULT_MAX_ADDED_LINES; /** * The maximum difference between heights of lines belonging to the same header. */ private double headerHeightTolerance = DEFAULT_HEADER_HEIGHT_TOL; /** * The minimum score for a line to be considered as a candidate for header expanding. */ private int minHeaderCandidateScore = DEFAULT_MIN_HEADER_SCORE; private double headerLineWidthMultiplier = DEFAULT_HEADER_LINE_WIDTH_MULT; private double headerLineSpacingMultiplier = DEFAULT_HEADER_LINE_MULT; private int minHeaderLineScore = DEFAULT_MIN_HEADER_LINE_SCORE; public void completeLines(BxContentStructure contentStructure) { for (BxLine headerLine : contentStructure.getFirstHeaderLines()) { int added = 0; BxLine actLine = headerLine; List<BxLine> candidates = new ArrayList<BxLine>(); while (actLine.hasNext()) { if (added > maxAddedHeaderLines) { break; } actLine = actLine.getNext(); if (contentStructure.containsFirstHeaderLine(actLine)) { break; } int score = 0; if (Math.abs(actLine.getHeight() - headerLine.getHeight()) < headerHeightTolerance) { score++; } if (actLine.getMostPopularFontName().equals(headerLine.getMostPopularFontName())) { score++; } if (score >= minHeaderCandidateScore) { candidates.add(actLine); added++; } else { break; } } if (added == 0) { continue; } int score = 0; BxLine firstCandidate = candidates.get(0); BxLine lastCandidate = candidates.get(added-1); if (lastCandidate.getWidth() < headerLine.getWidth() * headerLineWidthMultiplier) { score++; } if (lastCandidate.hasNext() && Math.abs(headerLine.getY() - firstCandidate.getY()) < Math.abs(lastCandidate.getY() - lastCandidate.getNext().getY()) * headerLineSpacingMultiplier) { score++; } if (lastCandidate.hasNext() && lastCandidate.getNext().toText().matches("[A-Z].*")) { score++; } if (lastCandidate.hasNext() && !lastCandidate.getMostPopularFontName().equals(lastCandidate.getNext().getMostPopularFontName())) { score++; } if (score >= minHeaderLineScore) { for (BxLine candidate : candidates) { contentStructure.addAdditionalHeaderLine(headerLine, candidate); } } } } public void setHeaderHeightTolerance(double headerHeightTolerance) { this.headerHeightTolerance = headerHeightTolerance; } public void setHeaderLineSpacingMultiplier(double headerLineSpacingMultiplier) { this.headerLineSpacingMultiplier = headerLineSpacingMultiplier; } public void setHeaderLineWidthMultiplier(double headerLineWidthMultiplier) { this.headerLineWidthMultiplier = headerLineWidthMultiplier; } public void setMaxAddedHeaderLines(int maxAddedHeaderLines) { this.maxAddedHeaderLines = maxAddedHeaderLines; } public void setMinHeaderCandidateScore(int minHeaderCandidateScore) { this.minHeaderCandidateScore = minHeaderCandidateScore; } public void setMinHeaderLineScore(int minHeaderLineScore) { this.minHeaderLineScore = minHeaderLineScore; } }
5,386
35.89726
142
java
CERMINE
CERMINE-master/cermine-impl/src/main/java/pl/edu/icm/cermine/content/headers/SVMHeaderLinesClassifier.java
/** * This file is part of CERMINE project. * Copyright (c) 2011-2018 ICM-UW * * CERMINE is free software: you can redistribute it and/or modify * it under the terms of the GNU Affero General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * CERMINE is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU Affero General Public License for more details. * * You should have received a copy of the GNU Affero General Public License * along with CERMINE. If not, see <http://www.gnu.org/licenses/>. */ package pl.edu.icm.cermine.content.headers; import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; import java.util.logging.Level; import java.util.logging.Logger; import pl.edu.icm.cermine.exception.AnalysisException; import pl.edu.icm.cermine.structure.model.BxLine; import pl.edu.icm.cermine.structure.model.BxPage; import pl.edu.icm.cermine.structure.model.BxZoneLabel; import pl.edu.icm.cermine.tools.classification.general.FeatureVectorBuilder; import pl.edu.icm.cermine.tools.classification.svm.SVMClassifier; /** * @author Dominika Tkaczyk (d.tkaczyk@icm.edu.pl) */ public class SVMHeaderLinesClassifier extends SVMClassifier<BxLine, BxPage, BxZoneLabel> { public SVMHeaderLinesClassifier() throws AnalysisException { super(HeaderExtractingTools.EXTRACT_VB, BxZoneLabel.class); } public SVMHeaderLinesClassifier(FeatureVectorBuilder<BxLine, BxPage> featureVectorBuilder) throws AnalysisException { super(featureVectorBuilder, BxZoneLabel.class); } public SVMHeaderLinesClassifier(BufferedReader modelFile, BufferedReader rangeFile) throws AnalysisException { this(modelFile, rangeFile, HeaderExtractingTools.EXTRACT_VB); } public SVMHeaderLinesClassifier(String modelFilePath, String rangeFilePath) throws AnalysisException { this(modelFilePath, rangeFilePath, HeaderExtractingTools.EXTRACT_VB); } public SVMHeaderLinesClassifier(BufferedReader modelFile, BufferedReader rangeFile, FeatureVectorBuilder<BxLine, BxPage> featureVectorBuilder) throws AnalysisException { super(featureVectorBuilder, BxZoneLabel.class); try { loadModelFromFile(modelFile, rangeFile); } catch (IOException ex) { throw new AnalysisException("Cannot create SVM classifier!", ex); } } public SVMHeaderLinesClassifier(String modelFilePath, String rangeFilePath, FeatureVectorBuilder<BxLine, BxPage> featureVectorBuilder) throws AnalysisException { super(featureVectorBuilder, BxZoneLabel.class); InputStreamReader modelISR = null; try { modelISR = new InputStreamReader(SVMHeaderLinesClassifier.class .getResourceAsStream(modelFilePath), "UTF-8"); BufferedReader modelFile = new BufferedReader(modelISR); InputStreamReader rangeISR = new InputStreamReader(SVMHeaderLinesClassifier.class .getResourceAsStream(rangeFilePath), "UTF-8"); BufferedReader rangeFile = new BufferedReader(rangeISR); loadModelFromFile(modelFile, rangeFile); } catch (IOException ex) { throw new AnalysisException("Cannot create SVM classifier!", ex); } finally { try { if (modelISR != null) { modelISR.close(); } } catch (IOException ex) { Logger.getLogger(SVMHeaderLinesClassifier.class.getName()).log(Level.SEVERE, null, ex); } } } }
3,781
42.471264
173
java
CERMINE
CERMINE-master/cermine-impl/src/main/java/pl/edu/icm/cermine/content/headers/features/PrevSpaceFeature.java
/** * This file is part of CERMINE project. * Copyright (c) 2011-2018 ICM-UW * * CERMINE is free software: you can redistribute it and/or modify * it under the terms of the GNU Affero General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * CERMINE is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU Affero General Public License for more details. * * You should have received a copy of the GNU Affero General Public License * along with CERMINE. If not, see <http://www.gnu.org/licenses/>. */ package pl.edu.icm.cermine.content.headers.features; import pl.edu.icm.cermine.structure.model.BxLine; import pl.edu.icm.cermine.structure.model.BxPage; import pl.edu.icm.cermine.tools.classification.general.FeatureCalculator; /** * @author Dominika Tkaczyk (d.tkaczyk@icm.edu.pl) */ public class PrevSpaceFeature extends FeatureCalculator<BxLine, BxPage> { @Override public double calculateFeatureValue(BxLine line, BxPage page) { if (!line.hasPrev() || line.getPrev().getY() > line.getY()) { return 0; } double space = line.getY() - line.getPrev().getY(); BxLine l = line; int i = 0; while (l.hasPrev()) { l = l.getPrev(); if (!l.hasPrev()) { break; } if (i >= 4 || l.getPrev().getY() > l.getY()) { break; } if (l.getY() - l.getPrev().getY() > space) { space = l.getY() - l.getPrev().getY(); } i++; } return (Math.abs(space - line.getY() + line.getPrev().getY()) < 0.1) ? 1 : 0; } }
1,899
31.758621
85
java
CERMINE
CERMINE-master/cermine-impl/src/main/java/pl/edu/icm/cermine/content/headers/features/EndsWithInterpunctionFeature.java
/** * This file is part of CERMINE project. * Copyright (c) 2011-2018 ICM-UW * * CERMINE is free software: you can redistribute it and/or modify * it under the terms of the GNU Affero General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * CERMINE is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU Affero General Public License for more details. * * You should have received a copy of the GNU Affero General Public License * along with CERMINE. If not, see <http://www.gnu.org/licenses/>. */ package pl.edu.icm.cermine.content.headers.features; import java.util.regex.Pattern; import pl.edu.icm.cermine.structure.model.BxLine; import pl.edu.icm.cermine.structure.model.BxPage; import pl.edu.icm.cermine.tools.classification.general.FeatureCalculator; /** * @author Dominika Tkaczyk (d.tkaczyk@icm.edu.pl) */ public class EndsWithInterpunctionFeature extends FeatureCalculator<BxLine, BxPage> { @Override public double calculateFeatureValue(BxLine refLine, BxPage refs) { String text = refLine.toText(); return Pattern.matches(".*?[\\.:]$", text) ? 1 : 0; } }
1,342
34.342105
85
java
CERMINE
CERMINE-master/cermine-impl/src/main/java/pl/edu/icm/cermine/content/headers/features/IndentationFeature.java
/** * This file is part of CERMINE project. * Copyright (c) 2011-2018 ICM-UW * * CERMINE is free software: you can redistribute it and/or modify * it under the terms of the GNU Affero General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * CERMINE is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU Affero General Public License for more details. * * You should have received a copy of the GNU Affero General Public License * along with CERMINE. If not, see <http://www.gnu.org/licenses/>. */ package pl.edu.icm.cermine.content.headers.features; import pl.edu.icm.cermine.structure.model.BxLine; import pl.edu.icm.cermine.structure.model.BxPage; import pl.edu.icm.cermine.tools.classification.general.FeatureCalculator; /** * @author Dominika Tkaczyk (d.tkaczyk@icm.edu.pl) */ public class IndentationFeature extends FeatureCalculator<BxLine, BxPage> { private static final int MAX_LINES = 5; @Override public double calculateFeatureValue(BxLine line, BxPage page) { int i = 0; BxLine l = line; double meanX = 0; while (l.hasNext() && i < MAX_LINES) { l = l.getNext(); if ((line.getX() < l.getX() && l.getX() < line.getX() + line.getWidth()) || (l.getX() < line.getX() && line.getX() < l.getX() + l.getWidth())) { meanX += l.getX(); i++; } else { break; } } if (i == 0 || line.getWidth() == 0) { return 0.0; } meanX /= i; return Math.abs(line.getX() - meanX) / (double) line.getWidth(); } }
1,876
32.517857
91
java
CERMINE
CERMINE-master/cermine-impl/src/main/java/pl/edu/icm/cermine/content/headers/features/ContainsTypicalHeaderKeywordFeature.java
/** * This file is part of CERMINE project. * Copyright (c) 2011-2018 ICM-UW * * CERMINE is free software: you can redistribute it and/or modify * it under the terms of the GNU Affero General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * CERMINE is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU Affero General Public License for more details. * * You should have received a copy of the GNU Affero General Public License * along with CERMINE. If not, see <http://www.gnu.org/licenses/>. */ package pl.edu.icm.cermine.content.headers.features; import pl.edu.icm.cermine.structure.model.BxLine; import pl.edu.icm.cermine.structure.model.BxPage; import pl.edu.icm.cermine.tools.classification.general.FeatureCalculator; /** * @author Dominika Tkaczyk (d.tkaczyk@icm.edu.pl) */ public class ContainsTypicalHeaderKeywordFeature extends FeatureCalculator<BxLine, BxPage> { String[] keywords = { "A(?i)uthors", "I(?i)ntroduct", "D(?i)iscuss", "A(?i)bbrevi", "C(?i)onclus", "M(?i)ateri", "M(?i)ethod"}; @Override public double calculateFeatureValue(BxLine line, BxPage context) { for (String keyword: keywords){ if (line.toText().matches(".*?" + keyword + ".*")) { return 1; } } return 0; } }
1,541
34.045455
92
java
CERMINE
CERMINE-master/cermine-impl/src/main/java/pl/edu/icm/cermine/content/headers/features/ContainsInterpunctionInsideFeature.java
/** * This file is part of CERMINE project. * Copyright (c) 2011-2018 ICM-UW * * CERMINE is free software: you can redistribute it and/or modify * it under the terms of the GNU Affero General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * CERMINE is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU Affero General Public License for more details. * * You should have received a copy of the GNU Affero General Public License * along with CERMINE. If not, see <http://www.gnu.org/licenses/>. */ package pl.edu.icm.cermine.content.headers.features; import java.util.regex.Pattern; import pl.edu.icm.cermine.structure.model.BxLine; import pl.edu.icm.cermine.structure.model.BxPage; import pl.edu.icm.cermine.tools.classification.general.FeatureCalculator; /** * @author Jan Lasek */ public class ContainsInterpunctionInsideFeature extends FeatureCalculator<BxLine, BxPage> { @Override public double calculateFeatureValue(BxLine line, BxPage context) { String text = line.toText(); return Pattern.matches("^.+[\\.:]\\s.+$", text) ? 1 : 0; } }
1,320
33.763158
91
java
CERMINE
CERMINE-master/cermine-impl/src/main/java/pl/edu/icm/cermine/content/headers/features/FontCodeLeftToInterpFeature.java
/** * This file is part of CERMINE project. * Copyright (c) 2011-2018 ICM-UW * * CERMINE is free software: you can redistribute it and/or modify * it under the terms of the GNU Affero General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * CERMINE is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU Affero General Public License for more details. * * You should have received a copy of the GNU Affero General Public License * along with CERMINE. If not, see <http://www.gnu.org/licenses/>. */ package pl.edu.icm.cermine.content.headers.features; import com.google.common.collect.Lists; import java.util.List; import java.util.Map; import pl.edu.icm.cermine.structure.model.BxChunk; import pl.edu.icm.cermine.structure.model.BxLine; import pl.edu.icm.cermine.structure.model.BxPage; import pl.edu.icm.cermine.structure.model.BxWord; import pl.edu.icm.cermine.tools.CountMap; import pl.edu.icm.cermine.tools.classification.general.FeatureCalculator; /** * @author Jan Lasek */ public class FontCodeLeftToInterpFeature extends FeatureCalculator<BxLine, BxPage> { String[] fontNames; public FontCodeLeftToInterpFeature(List<Map.Entry<String, Integer>> fontNames2) { String[] fontNamesTmp = new String[fontNames2.size()]; for(int i = 0; i < fontNamesTmp.length; i++) { fontNamesTmp[i] = fontNames2.get(i).getKey(); } fontNames = fontNamesTmp; } @Override public double calculateFeatureValue(BxLine line, BxPage context) { int i = 0; for (BxWord word : line){ i++; String wordProcessed = word.toText().replaceAll("[^a-zA-Z\\.:\\?\\)\\(]", ""); if (wordProcessed.matches("([a-zA-Z]{2,}|(.*?\\)))(\\.|:|\\?)")) { break; } } CountMap<String> mapLeft = new CountMap<String>(); for (BxWord word : Lists.newArrayList(line).subList(0, i)) { for (BxChunk chunk : word) { if (chunk.getFontName() != null) { mapLeft.add(chunk.getFontName()); } } } String fontNameLeft = mapLeft.getMaxCountObject(); if (fontNameLeft == null) { return -1; } else { int l = 0; while (l < fontNames.length && !fontNameLeft.equals(this.fontNames[l])) { l++; } return (double) l; } } }
2,679
33.805195
90
java
CERMINE
CERMINE-master/cermine-impl/src/main/java/pl/edu/icm/cermine/content/headers/features/IndentationPageFeature.java
/** * This file is part of CERMINE project. * Copyright (c) 2011-2018 ICM-UW * * CERMINE is free software: you can redistribute it and/or modify * it under the terms of the GNU Affero General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * CERMINE is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU Affero General Public License for more details. * * You should have received a copy of the GNU Affero General Public License * along with CERMINE. If not, see <http://www.gnu.org/licenses/>. */ package pl.edu.icm.cermine.content.headers.features; import pl.edu.icm.cermine.structure.model.BxLine; import pl.edu.icm.cermine.structure.model.BxPage; import pl.edu.icm.cermine.tools.classification.general.FeatureCalculator; /** * @author Dominika Tkaczyk (d.tkaczyk@icm.edu.pl) */ public class IndentationPageFeature extends FeatureCalculator<BxLine, BxPage> { @Override public double calculateFeatureValue(BxLine object, BxPage context) { return object.getBounds().getX(); } }
1,244
33.583333
79
java
CERMINE
CERMINE-master/cermine-impl/src/main/java/pl/edu/icm/cermine/content/headers/features/LowercaseSchemaFeature.java
/** * This file is part of CERMINE project. * Copyright (c) 2011-2018 ICM-UW * * CERMINE is free software: you can redistribute it and/or modify * it under the terms of the GNU Affero General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * CERMINE is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU Affero General Public License for more details. * * You should have received a copy of the GNU Affero General Public License * along with CERMINE. If not, see <http://www.gnu.org/licenses/>. */ package pl.edu.icm.cermine.content.headers.features; import pl.edu.icm.cermine.structure.model.BxLine; import pl.edu.icm.cermine.structure.model.BxPage; import pl.edu.icm.cermine.tools.classification.general.FeatureCalculator; /** * @author Dominika Tkaczyk (d.tkaczyk@icm.edu.pl) */ public class LowercaseSchemaFeature extends FeatureCalculator<BxLine, BxPage> { @Override public double calculateFeatureValue(BxLine line, BxPage page) { return (line.toText().matches("^[a-z]\\) [A-Z].*$")) ? 1 : 0; } }
1,271
34.333333
79
java
CERMINE
CERMINE-master/cermine-impl/src/main/java/pl/edu/icm/cermine/content/headers/features/NumberOfCharactersFeature.java
/** * This file is part of CERMINE project. * Copyright (c) 2011-2018 ICM-UW * * CERMINE is free software: you can redistribute it and/or modify * it under the terms of the GNU Affero General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * CERMINE is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU Affero General Public License for more details. * * You should have received a copy of the GNU Affero General Public License * along with CERMINE. If not, see <http://www.gnu.org/licenses/>. */ package pl.edu.icm.cermine.content.headers.features; import pl.edu.icm.cermine.structure.model.BxLine; import pl.edu.icm.cermine.structure.model.BxPage; import pl.edu.icm.cermine.tools.classification.general.FeatureCalculator; /** * @author Jan Lasek */ public class NumberOfCharactersFeature extends FeatureCalculator<BxLine, BxPage> { @Override public double calculateFeatureValue(BxLine object, BxPage context) { return (double) object.toText().length(); } }
1,225
33.055556
82
java
CERMINE
CERMINE-master/cermine-impl/src/main/java/pl/edu/icm/cermine/content/headers/features/WordsAllUppercaseFeature.java
/** * This file is part of CERMINE project. * Copyright (c) 2011-2018 ICM-UW * * CERMINE is free software: you can redistribute it and/or modify * it under the terms of the GNU Affero General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * CERMINE is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU Affero General Public License for more details. * * You should have received a copy of the GNU Affero General Public License * along with CERMINE. If not, see <http://www.gnu.org/licenses/>. */ package pl.edu.icm.cermine.content.headers.features; import pl.edu.icm.cermine.structure.model.BxLine; import pl.edu.icm.cermine.structure.model.BxPage; import pl.edu.icm.cermine.tools.classification.general.FeatureCalculator; /** * @author Dominika Tkaczyk (d.tkaczyk@icm.edu.pl) */ public class WordsAllUppercaseFeature extends FeatureCalculator<BxLine, BxPage> { @Override public double calculateFeatureValue(BxLine line, BxPage page) { String text = line.toText(); String[] words = text.split("\\s"); int upperWordsCount = 0; for (String word : words) { if (word.matches("^[A-Z][-'A-Z]+$")) { upperWordsCount++; } } return (words.length == 0) ? 0 : (double) upperWordsCount / (double) words.length; } }
1,554
34.340909
90
java
CERMINE
CERMINE-master/cermine-impl/src/main/java/pl/edu/icm/cermine/content/headers/features/DigitDotSchemaFeature.java
/** * This file is part of CERMINE project. * Copyright (c) 2011-2018 ICM-UW * * CERMINE is free software: you can redistribute it and/or modify * it under the terms of the GNU Affero General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * CERMINE is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU Affero General Public License for more details. * * You should have received a copy of the GNU Affero General Public License * along with CERMINE. If not, see <http://www.gnu.org/licenses/>. */ package pl.edu.icm.cermine.content.headers.features; import pl.edu.icm.cermine.structure.model.BxLine; import pl.edu.icm.cermine.structure.model.BxPage; import pl.edu.icm.cermine.tools.classification.general.FeatureCalculator; /** * @author Dominika Tkaczyk (d.tkaczyk@icm.edu.pl) */ public class DigitDotSchemaFeature extends FeatureCalculator<BxLine, BxPage> { @Override public double calculateFeatureValue(BxLine line, BxPage page) { return (line.toText().matches("^[1-9]\\.? [A-Z].*$")) ? 1 : 0; } }
1,271
34.333333
78
java
CERMINE
CERMINE-master/cermine-impl/src/main/java/pl/edu/icm/cermine/content/headers/features/WordsUppercaseFeature.java
/** * This file is part of CERMINE project. * Copyright (c) 2011-2018 ICM-UW * * CERMINE is free software: you can redistribute it and/or modify * it under the terms of the GNU Affero General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * CERMINE is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU Affero General Public License for more details. * * You should have received a copy of the GNU Affero General Public License * along with CERMINE. If not, see <http://www.gnu.org/licenses/>. */ package pl.edu.icm.cermine.content.headers.features; import pl.edu.icm.cermine.structure.model.BxLine; import pl.edu.icm.cermine.structure.model.BxPage; import pl.edu.icm.cermine.tools.classification.general.FeatureCalculator; /** * @author Dominika Tkaczyk (d.tkaczyk@icm.edu.pl) */ public class WordsUppercaseFeature extends FeatureCalculator<BxLine, BxPage> { @Override public double calculateFeatureValue(BxLine line, BxPage page) { String text = line.toText(); String[] words = text.split("\\s"); int upperWordsCount = 0; for (String word : words) { if (word.matches("^[A-Z][-'a-z]+$")) { upperWordsCount++; } } return (words.length == 0) ? 0 : (double) upperWordsCount / (double) words.length; } }
1,551
34.272727
90
java
CERMINE
CERMINE-master/cermine-impl/src/main/java/pl/edu/icm/cermine/content/headers/features/ContainsEquationCharacterFeature.java
/** * This file is part of CERMINE project. * Copyright (c) 2011-2018 ICM-UW * * CERMINE is free software: you can redistribute it and/or modify * it under the terms of the GNU Affero General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * CERMINE is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU Affero General Public License for more details. * * You should have received a copy of the GNU Affero General Public License * along with CERMINE. If not, see <http://www.gnu.org/licenses/>. */ package pl.edu.icm.cermine.content.headers.features; import java.util.regex.Pattern; import pl.edu.icm.cermine.structure.model.BxLine; import pl.edu.icm.cermine.structure.model.BxPage; import pl.edu.icm.cermine.tools.classification.general.FeatureCalculator; /** * @author Jan Lasek */ public class ContainsEquationCharacterFeature extends FeatureCalculator<BxLine, BxPage> { @Override public double calculateFeatureValue(BxLine line, BxPage context) { String text = line.toText(); return Pattern.matches(".*?(\\+|=|<|>|%|\\(|\\)|\\[|\\]).*?$", text) ? 1 : 0; } }
1,339
34.263158
89
java
CERMINE
CERMINE-master/cermine-impl/src/main/java/pl/edu/icm/cermine/content/headers/features/IsHigherThanNeighborsFeature.java
/** * This file is part of CERMINE project. * Copyright (c) 2011-2018 ICM-UW * * CERMINE is free software: you can redistribute it and/or modify * it under the terms of the GNU Affero General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * CERMINE is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU Affero General Public License for more details. * * You should have received a copy of the GNU Affero General Public License * along with CERMINE. If not, see <http://www.gnu.org/licenses/>. */ package pl.edu.icm.cermine.content.headers.features; import pl.edu.icm.cermine.structure.model.BxLine; import pl.edu.icm.cermine.structure.model.BxPage; import pl.edu.icm.cermine.tools.classification.general.FeatureCalculator; /** * @author Dominika Tkaczyk (d.tkaczyk@icm.edu.pl) */ public class IsHigherThanNeighborsFeature extends FeatureCalculator<BxLine, BxPage> { @Override public double calculateFeatureValue(BxLine line, BxPage page) { double score = 0; double max = line.getHeight(); double min = line.getHeight(); BxLine l = line; int i = 0; while (l.hasPrev() && i < 2) { l = l.getPrev(); max = Math.max(l.getHeight(), max); min = Math.min(l.getHeight(), min); ++i; } if (Math.abs(max - line.getHeight()) < 0.1 && Math.abs(min - line.getHeight()) > 1) { score += 0.5; } max = line.getHeight(); min = line.getHeight(); i = 0; l = line; while (l.hasNext() && i < 2) { l = l.getNext(); max = Math.max(l.getHeight(), max); min = Math.min(l.getHeight(), min); ++i; } if (Math.abs(max - line.getHeight()) < 0.1 && Math.abs(min - line.getHeight()) > 1) { score += 0.5; } return score; } }
2,118
29.710145
93
java
CERMINE
CERMINE-master/cermine-impl/src/main/java/pl/edu/icm/cermine/content/headers/features/CapitalizedWordWithInterpunctionFeature.java
/** * This file is part of CERMINE project. * Copyright (c) 2011-2018 ICM-UW * * CERMINE is free software: you can redistribute it and/or modify * it under the terms of the GNU Affero General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * CERMINE is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU Affero General Public License for more details. * * You should have received a copy of the GNU Affero General Public License * along with CERMINE. If not, see <http://www.gnu.org/licenses/>. */ package pl.edu.icm.cermine.content.headers.features; import java.util.regex.Pattern; import pl.edu.icm.cermine.structure.model.BxLine; import pl.edu.icm.cermine.structure.model.BxPage; import pl.edu.icm.cermine.tools.classification.general.FeatureCalculator; /** * @author Jan Lasek */ public class CapitalizedWordWithInterpunctionFeature extends FeatureCalculator<BxLine, BxPage> { @Override public double calculateFeatureValue(BxLine line, BxPage context) { String text = line.toText(); return Pattern.matches("^(([1-9]\\.)*\\s)?[A-Z][a-z]+(\\.|:).*", text) ? 1 : 0; } }
1,349
33.615385
96
java
CERMINE
CERMINE-master/cermine-impl/src/main/java/pl/edu/icm/cermine/content/headers/features/PrevEndsWithDotFeature.java
/** * This file is part of CERMINE project. * Copyright (c) 2011-2018 ICM-UW * * CERMINE is free software: you can redistribute it and/or modify * it under the terms of the GNU Affero General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * CERMINE is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU Affero General Public License for more details. * * You should have received a copy of the GNU Affero General Public License * along with CERMINE. If not, see <http://www.gnu.org/licenses/>. */ package pl.edu.icm.cermine.content.headers.features; import pl.edu.icm.cermine.structure.model.BxLine; import pl.edu.icm.cermine.structure.model.BxPage; import pl.edu.icm.cermine.tools.classification.general.FeatureCalculator; /** * @author Dominika Tkaczyk (d.tkaczyk@icm.edu.pl) */ public class PrevEndsWithDotFeature extends FeatureCalculator<BxLine, BxPage> { @Override public double calculateFeatureValue(BxLine line, BxPage page) { if (!line.hasPrev()) { return 0; } return (line.getPrev().toText().endsWith(".")) ? 1 : 0; } }
1,328
33.076923
79
java
CERMINE
CERMINE-master/cermine-impl/src/main/java/pl/edu/icm/cermine/content/headers/features/NextStartsWithUppercaseFeature.java
/** * This file is part of CERMINE project. * Copyright (c) 2011-2018 ICM-UW * * CERMINE is free software: you can redistribute it and/or modify * it under the terms of the GNU Affero General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * CERMINE is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU Affero General Public License for more details. * * You should have received a copy of the GNU Affero General Public License * along with CERMINE. If not, see <http://www.gnu.org/licenses/>. */ package pl.edu.icm.cermine.content.headers.features; import pl.edu.icm.cermine.structure.model.BxLine; import pl.edu.icm.cermine.structure.model.BxPage; import pl.edu.icm.cermine.tools.classification.general.FeatureCalculator; /** * @author Dominika Tkaczyk (d.tkaczyk@icm.edu.pl) */ public class NextStartsWithUppercaseFeature extends FeatureCalculator<BxLine, BxPage> { @Override public double calculateFeatureValue(BxLine line, BxPage page) { if (!line.hasNext()) { return 0; } return (line.getNext().toText().matches("^[A-Z].*$")) ? 1 : 0; } }
1,343
33.461538
87
java
CERMINE
CERMINE-master/cermine-impl/src/main/java/pl/edu/icm/cermine/content/headers/features/IndentationZoneFeature.java
/** * This file is part of CERMINE project. * Copyright (c) 2011-2018 ICM-UW * * CERMINE is free software: you can redistribute it and/or modify * it under the terms of the GNU Affero General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * CERMINE is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU Affero General Public License for more details. * * You should have received a copy of the GNU Affero General Public License * along with CERMINE. If not, see <http://www.gnu.org/licenses/>. */ package pl.edu.icm.cermine.content.headers.features; import pl.edu.icm.cermine.structure.model.BxLine; import pl.edu.icm.cermine.structure.model.BxPage; import pl.edu.icm.cermine.tools.classification.general.FeatureCalculator; /** * @author Dominika Tkaczyk (d.tkaczyk@icm.edu.pl) */ public class IndentationZoneFeature extends FeatureCalculator<BxLine, BxPage> { @Override public double calculateFeatureValue(BxLine object, BxPage context) { return object.getBounds().getX() - context.getX(); } }
1,261
34.055556
79
java
CERMINE
CERMINE-master/cermine-impl/src/main/java/pl/edu/icm/cermine/content/headers/features/DigitRelativeCountFeature.java
/** * This file is part of CERMINE project. * Copyright (c) 2011-2018 ICM-UW * * CERMINE is free software: you can redistribute it and/or modify * it under the terms of the GNU Affero General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * CERMINE is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU Affero General Public License for more details. * * You should have received a copy of the GNU Affero General Public License * along with CERMINE. If not, see <http://www.gnu.org/licenses/>. */ package pl.edu.icm.cermine.content.headers.features; import pl.edu.icm.cermine.structure.model.BxLine; import pl.edu.icm.cermine.structure.model.BxPage; import pl.edu.icm.cermine.tools.classification.general.FeatureCalculator; /** * @author Jan Lasek */ public class DigitRelativeCountFeature extends FeatureCalculator<BxLine, BxPage> { @Override public double calculateFeatureValue(BxLine object, BxPage context) { char[] charArray = object.toText().toCharArray(); int digit = 0; for (int i = 0; i < charArray.length; i++) { if (Character.isDigit(charArray[i])) { digit++; } } return digit / (double) object.toText().length(); } }
1,468
32.386364
82
java
CERMINE
CERMINE-master/cermine-impl/src/main/java/pl/edu/icm/cermine/content/headers/features/MoreThanOneFontUsedFeature.java
/** * This file is part of CERMINE project. * Copyright (c) 2011-2018 ICM-UW * * CERMINE is free software: you can redistribute it and/or modify * it under the terms of the GNU Affero General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * CERMINE is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU Affero General Public License for more details. * * You should have received a copy of the GNU Affero General Public License * along with CERMINE. If not, see <http://www.gnu.org/licenses/>. */ package pl.edu.icm.cermine.content.headers.features; import java.util.Set; import pl.edu.icm.cermine.structure.model.BxLine; import pl.edu.icm.cermine.structure.model.BxPage; import pl.edu.icm.cermine.tools.classification.general.FeatureCalculator; /** * @author Jan Lasek */ public class MoreThanOneFontUsedFeature extends FeatureCalculator<BxLine, BxPage> { @Override public double calculateFeatureValue(BxLine line, BxPage context) { Set<String> fontsUsed = line.getFontNames(); return fontsUsed.size() > 1 ? 1 : 0; } }
1,298
33.184211
83
java
CERMINE
CERMINE-master/cermine-impl/src/main/java/pl/edu/icm/cermine/content/headers/features/DoubleDigitSchemaFeature.java
/** * This file is part of CERMINE project. * Copyright (c) 2011-2018 ICM-UW * * CERMINE is free software: you can redistribute it and/or modify * it under the terms of the GNU Affero General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * CERMINE is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU Affero General Public License for more details. * * You should have received a copy of the GNU Affero General Public License * along with CERMINE. If not, see <http://www.gnu.org/licenses/>. */ package pl.edu.icm.cermine.content.headers.features; import pl.edu.icm.cermine.structure.model.BxLine; import pl.edu.icm.cermine.structure.model.BxPage; import pl.edu.icm.cermine.tools.classification.general.FeatureCalculator; /** * @author Dominika Tkaczyk (d.tkaczyk@icm.edu.pl) */ public class DoubleDigitSchemaFeature extends FeatureCalculator<BxLine, BxPage> { @Override public double calculateFeatureValue(BxLine line, BxPage page) { return (line.toText().matches("^[1-9]\\.[1-9]\\.? [A-Z].*$")) ? 1 : 0; } }
1,282
34.638889
81
java
CERMINE
CERMINE-master/cermine-impl/src/main/java/pl/edu/icm/cermine/content/headers/features/MajorityFontFeature.java
/** * This file is part of CERMINE project. * Copyright (c) 2011-2018 ICM-UW * * CERMINE is free software: you can redistribute it and/or modify * it under the terms of the GNU Affero General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * CERMINE is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU Affero General Public License for more details. * * You should have received a copy of the GNU Affero General Public License * along with CERMINE. If not, see <http://www.gnu.org/licenses/>. */ package pl.edu.icm.cermine.content.headers.features; import pl.edu.icm.cermine.structure.model.BxLine; import pl.edu.icm.cermine.structure.model.BxZone; import pl.edu.icm.cermine.tools.classification.general.FeatureCalculator; /** * @author Jan Lasek */ public class MajorityFontFeature extends FeatureCalculator<BxLine, BxZone> { private final String mostPopularFont; public MajorityFontFeature(String mostPopularFont) { this.mostPopularFont = mostPopularFont; } @Override public double calculateFeatureValue(BxLine object, BxZone context) { String fn = object.getMostPopularFontName(); if (mostPopularFont == null) { return 0; } return (fn.equals(mostPopularFont) ? 1 : 0); } }
1,504
32.444444
78
java
CERMINE
CERMINE-master/cermine-impl/src/main/java/pl/edu/icm/cermine/content/headers/features/EquationCharacterRelativeCountFeature.java
/** * This file is part of CERMINE project. * Copyright (c) 2011-2018 ICM-UW * * CERMINE is free software: you can redistribute it and/or modify * it under the terms of the GNU Affero General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * CERMINE is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU Affero General Public License for more details. * * You should have received a copy of the GNU Affero General Public License * along with CERMINE. If not, see <http://www.gnu.org/licenses/>. */ package pl.edu.icm.cermine.content.headers.features; import pl.edu.icm.cermine.structure.model.BxLine; import pl.edu.icm.cermine.structure.model.BxPage; import pl.edu.icm.cermine.tools.classification.general.FeatureCalculator; /** * @author Jan Lasek */ public class EquationCharacterRelativeCountFeature extends FeatureCalculator<BxLine, BxPage> { @Override public double calculateFeatureValue(BxLine object, BxPage context) { char[] charArray = object.toText().toCharArray(); char[] eqSymbols = {'+', '=', '*', '<', '>', '%'}; int equation = 0; for (int i = 0; i < charArray.length; i++) { for(int j = 0; j <eqSymbols.length; j++){ if (Character.valueOf(charArray[i]).compareTo(eqSymbols[j]) == 0){ equation++; } } } return (double) equation / (double) object.toText().length(); } }
1,691
33.530612
94
java
CERMINE
CERMINE-master/cermine-impl/src/main/java/pl/edu/icm/cermine/content/headers/features/FontCodeFeature.java
/** * This file is part of CERMINE project. * Copyright (c) 2011-2018 ICM-UW * * CERMINE is free software: you can redistribute it and/or modify * it under the terms of the GNU Affero General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * CERMINE is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU Affero General Public License for more details. * * You should have received a copy of the GNU Affero General Public License * along with CERMINE. If not, see <http://www.gnu.org/licenses/>. */ package pl.edu.icm.cermine.content.headers.features; import java.util.List; import java.util.Map; import pl.edu.icm.cermine.structure.model.BxLine; import pl.edu.icm.cermine.structure.model.BxPage; import pl.edu.icm.cermine.tools.classification.general.FeatureCalculator; /** * @author Jan Lasek */ public class FontCodeFeature extends FeatureCalculator<BxLine, BxPage> { String[] fontNames; public FontCodeFeature(List<Map.Entry<String, Integer>> fontNames2) { String[] fontNamesTmp = new String[fontNames2.size()]; for(int i = 0; i < fontNamesTmp.length; i++) { fontNamesTmp[i] = fontNames2.get(i).getKey(); } fontNames = fontNamesTmp; } @Override public double calculateFeatureValue(BxLine object, BxPage context) { String fn = object.getMostPopularFontName(); int i = 0; while(i < fontNames.length && !fn.equals(this.fontNames[i])) { i++; } return (double) i; } }
1,739
32.461538
78
java
CERMINE
CERMINE-master/cermine-impl/src/main/java/pl/edu/icm/cermine/content/headers/features/SpaceBetweenLineAboveFeature.java
/** * This file is part of CERMINE project. * Copyright (c) 2011-2018 ICM-UW * * CERMINE is free software: you can redistribute it and/or modify * it under the terms of the GNU Affero General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * CERMINE is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU Affero General Public License for more details. * * You should have received a copy of the GNU Affero General Public License * along with CERMINE. If not, see <http://www.gnu.org/licenses/>. */ package pl.edu.icm.cermine.content.headers.features; import pl.edu.icm.cermine.structure.model.BxLine; import pl.edu.icm.cermine.structure.model.BxPage; import pl.edu.icm.cermine.structure.model.BxZoneLabel; import pl.edu.icm.cermine.tools.classification.general.FeatureCalculator; /** * @author Dominika Tkaczyk (d.tkaczyk@icm.edu.pl) */ public class SpaceBetweenLineAboveFeature extends FeatureCalculator<BxLine, BxPage> { @Override public double calculateFeatureValue(BxLine object, BxPage context) { if (object.getPrev() == null || !object.getPrev().getParent().getLabel().equals(BxZoneLabel.BODY_CONTENT)) { return -2; } double space = object.getBounds().getY() - object.getPrev().getBounds().getY() - object.getPrev().getBounds().getHeight(); return (space < 0 ? -1 : space); } }
1,585
38.65
130
java
CERMINE
CERMINE-master/cermine-impl/src/main/java/pl/edu/icm/cermine/content/headers/features/CapitalizedWords23WithInterpunctionFeature.java
/** * This file is part of CERMINE project. * Copyright (c) 2011-2018 ICM-UW * * CERMINE is free software: you can redistribute it and/or modify * it under the terms of the GNU Affero General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * CERMINE is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU Affero General Public License for more details. * * You should have received a copy of the GNU Affero General Public License * along with CERMINE. If not, see <http://www.gnu.org/licenses/>. */ package pl.edu.icm.cermine.content.headers.features; import java.util.regex.Pattern; import pl.edu.icm.cermine.structure.model.BxLine; import pl.edu.icm.cermine.structure.model.BxPage; import pl.edu.icm.cermine.tools.classification.general.FeatureCalculator; /** * @author Jan Lasek */ public class CapitalizedWords23WithInterpunctionFeature extends FeatureCalculator<BxLine, BxPage> { @Override public double calculateFeatureValue(BxLine line, BxPage context) { String text = line.toText(); return Pattern.matches("^(([1-9]\\.)*\\s)[A-Z][a-z]+(\\s[A-Za-z]+){1,2}(\\.|:).*", text) ? 1 : 0; } }
1,369
35.052632
105
java
CERMINE
CERMINE-master/cermine-impl/src/main/java/pl/edu/icm/cermine/content/headers/features/HeightFeature.java
/** * This file is part of CERMINE project. * Copyright (c) 2011-2018 ICM-UW * * CERMINE is free software: you can redistribute it and/or modify * it under the terms of the GNU Affero General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * CERMINE is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU Affero General Public License for more details. * * You should have received a copy of the GNU Affero General Public License * along with CERMINE. If not, see <http://www.gnu.org/licenses/>. */ package pl.edu.icm.cermine.content.headers.features; import pl.edu.icm.cermine.structure.model.BxLine; import pl.edu.icm.cermine.structure.model.BxPage; import pl.edu.icm.cermine.tools.classification.general.FeatureCalculator; /** * @author Jan Lasek */ public class HeightFeature extends FeatureCalculator<BxLine, BxPage> { @Override public double calculateFeatureValue(BxLine object, BxPage context) { return (double) object.getHeight(); } }
1,207
32.555556
78
java
CERMINE
CERMINE-master/cermine-impl/src/main/java/pl/edu/icm/cermine/content/headers/features/DigitParSchemaFeature.java
/** * This file is part of CERMINE project. * Copyright (c) 2011-2018 ICM-UW * * CERMINE is free software: you can redistribute it and/or modify * it under the terms of the GNU Affero General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * CERMINE is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU Affero General Public License for more details. * * You should have received a copy of the GNU Affero General Public License * along with CERMINE. If not, see <http://www.gnu.org/licenses/>. */ package pl.edu.icm.cermine.content.headers.features; import pl.edu.icm.cermine.structure.model.BxLine; import pl.edu.icm.cermine.structure.model.BxPage; import pl.edu.icm.cermine.tools.classification.general.FeatureCalculator; /** * @author Dominika Tkaczyk (d.tkaczyk@icm.edu.pl) */ public class DigitParSchemaFeature extends FeatureCalculator<BxLine, BxPage> { @Override public double calculateFeatureValue(BxLine line, BxPage page) { return (line.toText().matches("^[1-9]\\)? [A-Z].*$")) ? 1 : 0; } }
1,271
34.333333
78
java
CERMINE
CERMINE-master/cermine-impl/src/main/java/pl/edu/icm/cermine/content/headers/features/NumberOfWordsFeature.java
/** * This file is part of CERMINE project. * Copyright (c) 2011-2018 ICM-UW * * CERMINE is free software: you can redistribute it and/or modify * it under the terms of the GNU Affero General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * CERMINE is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU Affero General Public License for more details. * * You should have received a copy of the GNU Affero General Public License * along with CERMINE. If not, see <http://www.gnu.org/licenses/>. */ package pl.edu.icm.cermine.content.headers.features; import pl.edu.icm.cermine.structure.model.BxLine; import pl.edu.icm.cermine.structure.model.BxPage; import pl.edu.icm.cermine.tools.classification.general.FeatureCalculator; /** * @author Jan Lasek */ public class NumberOfWordsFeature extends FeatureCalculator<BxLine, BxPage> { @Override public double calculateFeatureValue(BxLine object, BxPage context) { return object.childrenCount(); } }
1,209
32.611111
78
java
CERMINE
CERMINE-master/cermine-impl/src/main/java/pl/edu/icm/cermine/content/headers/features/StartsWithUppercaseFeature.java
/** * This file is part of CERMINE project. * Copyright (c) 2011-2018 ICM-UW * * CERMINE is free software: you can redistribute it and/or modify * it under the terms of the GNU Affero General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * CERMINE is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU Affero General Public License for more details. * * You should have received a copy of the GNU Affero General Public License * along with CERMINE. If not, see <http://www.gnu.org/licenses/>. */ package pl.edu.icm.cermine.content.headers.features; import pl.edu.icm.cermine.structure.model.BxLine; import pl.edu.icm.cermine.structure.model.BxPage; import pl.edu.icm.cermine.tools.classification.general.FeatureCalculator; /** * @author Dominika Tkaczyk (d.tkaczyk@icm.edu.pl) */ public class StartsWithUppercaseFeature extends FeatureCalculator<BxLine, BxPage> { @Override public double calculateFeatureValue(BxLine object, BxPage context) { return (object.toText().length() > 0 && Character.isUpperCase(object.toText().charAt(0))) ? 1 : 0; } }
1,313
35.5
106
java
CERMINE
CERMINE-master/cermine-impl/src/main/java/pl/edu/icm/cermine/content/headers/features/RomanDigitsSchemaFeature.java
/** * This file is part of CERMINE project. * Copyright (c) 2011-2018 ICM-UW * * CERMINE is free software: you can redistribute it and/or modify * it under the terms of the GNU Affero General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * CERMINE is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU Affero General Public License for more details. * * You should have received a copy of the GNU Affero General Public License * along with CERMINE. If not, see <http://www.gnu.org/licenses/>. */ package pl.edu.icm.cermine.content.headers.features; import pl.edu.icm.cermine.structure.model.BxLine; import pl.edu.icm.cermine.structure.model.BxPage; import pl.edu.icm.cermine.tools.classification.general.FeatureCalculator; /** * @author Dominika Tkaczyk (d.tkaczyk@icm.edu.pl) */ public class RomanDigitsSchemaFeature extends FeatureCalculator<BxLine, BxPage> { @Override public double calculateFeatureValue(BxLine line, BxPage page) { return (line.toText().matches("^[IVX]+\\.? [A-Z].*$")) ? 1 : 0; } }
1,275
34.444444
81
java
CERMINE
CERMINE-master/cermine-impl/src/main/java/pl/edu/icm/cermine/content/headers/features/PrevLineLengthFeature.java
/** * This file is part of CERMINE project. * Copyright (c) 2011-2018 ICM-UW * * CERMINE is free software: you can redistribute it and/or modify * it under the terms of the GNU Affero General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * CERMINE is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU Affero General Public License for more details. * * You should have received a copy of the GNU Affero General Public License * along with CERMINE. If not, see <http://www.gnu.org/licenses/>. */ package pl.edu.icm.cermine.content.headers.features; import pl.edu.icm.cermine.structure.model.BxLine; import pl.edu.icm.cermine.structure.model.BxPage; import pl.edu.icm.cermine.structure.model.BxZone; import pl.edu.icm.cermine.tools.classification.general.FeatureCalculator; /** * @author Dominika Tkaczyk (d.tkaczyk@icm.edu.pl) */ public class PrevLineLengthFeature extends FeatureCalculator<BxLine, BxPage> { @Override public double calculateFeatureValue(BxLine line, BxPage page) { if (!line.hasPrev()) { return 1.0; } double avLength = 0; int linesCount = 0; for (BxZone zone : page) { for (BxLine l : zone) { linesCount++; avLength += l.getBounds().getWidth(); } } if (linesCount == 0 || avLength == 0) { return 0; } avLength /= linesCount; return line.getPrev().getBounds().getWidth() / avLength; } }
1,747
30.781818
78
java
CERMINE
CERMINE-master/cermine-impl/src/main/java/pl/edu/icm/cermine/content/headers/features/LengthFeature.java
/** * This file is part of CERMINE project. * Copyright (c) 2011-2018 ICM-UW * * CERMINE is free software: you can redistribute it and/or modify * it under the terms of the GNU Affero General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * CERMINE is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU Affero General Public License for more details. * * You should have received a copy of the GNU Affero General Public License * along with CERMINE. If not, see <http://www.gnu.org/licenses/>. */ package pl.edu.icm.cermine.content.headers.features; import pl.edu.icm.cermine.structure.model.BxLine; import pl.edu.icm.cermine.structure.model.BxPage; import pl.edu.icm.cermine.tools.classification.general.FeatureCalculator; /** * @author Jan Lasek */ public class LengthFeature extends FeatureCalculator<BxLine, BxPage> { @Override public double calculateFeatureValue(BxLine object, BxPage context) { return (double) object.getWidth(); } }
1,206
32.527778
78
java
CERMINE
CERMINE-master/cermine-impl/src/main/java/pl/edu/icm/cermine/content/headers/features/NumberOfFontsUsedFeature.java
/** * This file is part of CERMINE project. * Copyright (c) 2011-2018 ICM-UW * * CERMINE is free software: you can redistribute it and/or modify * it under the terms of the GNU Affero General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * CERMINE is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU Affero General Public License for more details. * * You should have received a copy of the GNU Affero General Public License * along with CERMINE. If not, see <http://www.gnu.org/licenses/>. */ package pl.edu.icm.cermine.content.headers.features; import java.util.Set; import pl.edu.icm.cermine.structure.model.BxLine; import pl.edu.icm.cermine.structure.model.BxPage; import pl.edu.icm.cermine.tools.classification.general.FeatureCalculator; /** * @author Jan Lasek */ public class NumberOfFontsUsedFeature extends FeatureCalculator<BxLine, BxPage> { @Override public double calculateFeatureValue(BxLine line, BxPage context) { Set<String> fontsUsed = line.getFontNames(); return (double) fontsUsed.size(); } }
1,293
33.052632
81
java
CERMINE
CERMINE-master/cermine-impl/src/main/java/pl/edu/icm/cermine/content/headers/features/UppercaseRelativeCountFeature.java
/** * This file is part of CERMINE project. * Copyright (c) 2011-2018 ICM-UW * * CERMINE is free software: you can redistribute it and/or modify * it under the terms of the GNU Affero General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * CERMINE is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU Affero General Public License for more details. * * You should have received a copy of the GNU Affero General Public License * along with CERMINE. If not, see <http://www.gnu.org/licenses/>. */ package pl.edu.icm.cermine.content.headers.features; import pl.edu.icm.cermine.structure.model.BxLine; import pl.edu.icm.cermine.structure.model.BxPage; import pl.edu.icm.cermine.tools.classification.general.FeatureCalculator; /** * @author Jan Lasek */ public class UppercaseRelativeCountFeature extends FeatureCalculator<BxLine, BxPage> { @Override public double calculateFeatureValue(BxLine object, BxPage context) { char[] charArray = object.toText().toCharArray(); int uppercase = 0; for (int i = 0; i < charArray.length; i++) { if (Character.isUpperCase(charArray[i])) { uppercase++; } } return (double) uppercase / (double) object.toText().length(); } }
1,497
33.045455
86
java
CERMINE
CERMINE-master/cermine-impl/src/main/java/pl/edu/icm/cermine/content/headers/features/PrevDistanceFeature.java
/** * This file is part of CERMINE project. * Copyright (c) 2011-2018 ICM-UW * * CERMINE is free software: you can redistribute it and/or modify * it under the terms of the GNU Affero General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * CERMINE is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU Affero General Public License for more details. * * You should have received a copy of the GNU Affero General Public License * along with CERMINE. If not, see <http://www.gnu.org/licenses/>. */ package pl.edu.icm.cermine.content.headers.features; import pl.edu.icm.cermine.structure.model.BxLine; import pl.edu.icm.cermine.structure.model.BxPage; import pl.edu.icm.cermine.tools.classification.general.FeatureCalculator; /** * @author Dominika Tkaczyk (d.tkaczyk@icm.edu.pl) */ public class PrevDistanceFeature extends FeatureCalculator<BxLine, BxPage> { @Override public double calculateFeatureValue(BxLine line, BxPage page) { return line.hasPrev() ? line.getPrev().getBounds().getY() - line.getBounds().getY() : 0; } }
1,295
35
96
java
CERMINE
CERMINE-master/cermine-impl/src/main/java/pl/edu/icm/cermine/content/headers/features/NextLineIndentationFeature.java
/** * This file is part of CERMINE project. * Copyright (c) 2011-2018 ICM-UW * * CERMINE is free software: you can redistribute it and/or modify * it under the terms of the GNU Affero General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * CERMINE is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU Affero General Public License for more details. * * You should have received a copy of the GNU Affero General Public License * along with CERMINE. If not, see <http://www.gnu.org/licenses/>. */ package pl.edu.icm.cermine.content.headers.features; import pl.edu.icm.cermine.structure.model.BxLine; import pl.edu.icm.cermine.structure.model.BxPage; import pl.edu.icm.cermine.tools.classification.general.FeatureCalculator; /** * @author Dominika Tkaczyk (d.tkaczyk@icm.edu.pl) */ public class NextLineIndentationFeature extends FeatureCalculator<BxLine, BxPage> { @Override public double calculateFeatureValue(BxLine line, BxPage page) { if (!line.hasNext()) { return 0.0; } int i = 0; BxLine l = line.getNext(); double meanX = 0; while (l.hasNext() && i < 5) { l = l.getNext(); if ((line.getX() < l.getX() && l.getX() < line.getX() + line.getWidth()) || (l.getX() < line.getX() && line.getX() < l.getX() + l.getWidth())) { meanX += l.getX(); i++; } else { break; } } if (i == 0 || line.getWidth() == 0) { return 0.0; } meanX /= i; return Math.abs(line.getNext().getX() - meanX) / (double) line.getWidth(); } }
1,916
32.631579
91
java
CERMINE
CERMINE-master/cermine-impl/src/main/java/pl/edu/icm/cermine/content/headers/features/TripleDigitSchemaFeature.java
/** * This file is part of CERMINE project. * Copyright (c) 2011-2018 ICM-UW * * CERMINE is free software: you can redistribute it and/or modify * it under the terms of the GNU Affero General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * CERMINE is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU Affero General Public License for more details. * * You should have received a copy of the GNU Affero General Public License * along with CERMINE. If not, see <http://www.gnu.org/licenses/>. */ package pl.edu.icm.cermine.content.headers.features; import pl.edu.icm.cermine.structure.model.BxLine; import pl.edu.icm.cermine.structure.model.BxPage; import pl.edu.icm.cermine.tools.classification.general.FeatureCalculator; /** * @author Dominika Tkaczyk (d.tkaczyk@icm.edu.pl) */ public class TripleDigitSchemaFeature extends FeatureCalculator<BxLine, BxPage> { @Override public double calculateFeatureValue(BxLine line, BxPage page) { return (line.toText().matches("^[1-9]\\.[1-9]\\.[1-9]\\.? [A-Z].*$")) ? 1 : 0; } }
1,290
34.861111
86
java
CERMINE
CERMINE-master/cermine-impl/src/main/java/pl/edu/icm/cermine/content/headers/features/EndsWithDotFeature.java
/** * This file is part of CERMINE project. * Copyright (c) 2011-2018 ICM-UW * * CERMINE is free software: you can redistribute it and/or modify * it under the terms of the GNU Affero General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * CERMINE is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU Affero General Public License for more details. * * You should have received a copy of the GNU Affero General Public License * along with CERMINE. If not, see <http://www.gnu.org/licenses/>. */ package pl.edu.icm.cermine.content.headers.features; import java.util.regex.Pattern; import pl.edu.icm.cermine.structure.model.BxLine; import pl.edu.icm.cermine.structure.model.BxPage; import pl.edu.icm.cermine.tools.classification.general.FeatureCalculator; /** * @author Dominika Tkaczyk (d.tkaczyk@icm.edu.pl) */ public class EndsWithDotFeature extends FeatureCalculator<BxLine, BxPage> { @Override public double calculateFeatureValue(BxLine refLine, BxPage refs) { String text = refLine.toText(); return Pattern.matches(".*\\.$", text) ? 1 : 0; } }
1,328
33.973684
78
java
CERMINE
CERMINE-master/cermine-impl/src/main/java/pl/edu/icm/cermine/content/headers/features/UppercaseSchemaFeature.java
/** * This file is part of CERMINE project. * Copyright (c) 2011-2018 ICM-UW * * CERMINE is free software: you can redistribute it and/or modify * it under the terms of the GNU Affero General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * CERMINE is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU Affero General Public License for more details. * * You should have received a copy of the GNU Affero General Public License * along with CERMINE. If not, see <http://www.gnu.org/licenses/>. */ package pl.edu.icm.cermine.content.headers.features; import pl.edu.icm.cermine.structure.model.BxLine; import pl.edu.icm.cermine.structure.model.BxPage; import pl.edu.icm.cermine.tools.classification.general.FeatureCalculator; /** * @author Dominika Tkaczyk (d.tkaczyk@icm.edu.pl) */ public class UppercaseSchemaFeature extends FeatureCalculator<BxLine, BxPage> { @Override public double calculateFeatureValue(BxLine line, BxPage page) { return (line.toText().matches("^[A-H]\\.? [A-Z].*$")) ? 1 : 0; } }
1,272
34.361111
79
java