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/test/java/pl/edu/icm/cermine/metadata/affiliation/features/AffiliationDictionaryFeatureTest.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.metadata.affiliation.features; import java.util.List; import org.junit.Test; import pl.edu.icm.cermine.exception.AnalysisException; import pl.edu.icm.cermine.metadata.affiliation.tools.AffiliationTokenizer; import pl.edu.icm.cermine.metadata.model.AffiliationLabel; import pl.edu.icm.cermine.metadata.tools.MetadataTools; import pl.edu.icm.cermine.parsing.model.Token; import static org.junit.Assert.assertEquals; /** * @author Bartosz Tarnawski */ public class AffiliationDictionaryFeatureTest { private static final AffiliationDictionaryFeature FEATURE_CASE_SENSITIVE; private static final AffiliationDictionaryFeature FEATURE_IGNORE_CASE; static { try { FEATURE_CASE_SENSITIVE = new AffiliationDictionaryFeature("HIT", "/pl/edu/icm/cermine/metadata/affiliation/features/mock-dictionary.txt", true); FEATURE_IGNORE_CASE = new AffiliationDictionaryFeature("HIT", "/pl/edu/icm/cermine/metadata/affiliation/features/mock-dictionary.txt", false); } catch (AnalysisException e) { throw new RuntimeException("Failed to initialize dictionary features"); } } @Test public void testAddFeatures() { String text = "elo meLo 320, Elo Melo 32.0. Hejka ziomeczku,:-P. W W chrzaszczu szczebrzeszyn .."; int expectFeature[] = {0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0}; List<Token<AffiliationLabel>> tokens = new AffiliationTokenizer().tokenize(MetadataTools.cleanAndNormalize(text)); assertEquals(expectFeature.length, tokens.size()); FEATURE_CASE_SENSITIVE.calculateDictionaryFeatures(tokens); for (int i = 0; i < expectFeature.length; i++) { assertEquals("Token: " + i + " " + tokens.get(i).getText(), expectFeature[i], tokens.get(i).getFeatures().size()); } text = "elo meLo 320, Elo Melo 32.0. Hejka ziómeczku,:-P. W W chrzaszczu szczebrzeszyn .."; int expectFeature2[] = {1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 1, 1, 1, 1, 1, 1, 0, 0, 1, 1, 1, 1, 0}; tokens = new AffiliationTokenizer().tokenize(MetadataTools.cleanAndNormalize(text)); assertEquals(expectFeature2.length, tokens.size()); FEATURE_IGNORE_CASE.calculateDictionaryFeatures(tokens); for (int i = 0; i < expectFeature2.length; i++) { assertEquals("Token: " + i + " " + tokens.get(i).getText(), expectFeature2[i], tokens.get(i).getFeatures().size()); } } }
3,323
43.32
149
java
CERMINE
CERMINE-master/cermine-impl/src/main/java/pl/edu/icm/cermine/ComponentConfiguration.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; import java.io.IOException; import java.io.InputStream; import pl.edu.icm.cermine.bibref.BibReferenceExtractor; import pl.edu.icm.cermine.bibref.BibReferenceParser; import pl.edu.icm.cermine.bibref.model.BibEntry; import pl.edu.icm.cermine.configuration.ExtractionConfigRegister; import pl.edu.icm.cermine.configuration.ExtractionConfigProperty; import pl.edu.icm.cermine.content.citations.ContentCitationPositionFinder; 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.headers.HeadersClusterizer; import pl.edu.icm.cermine.exception.AnalysisException; import pl.edu.icm.cermine.metadata.MetadataExtractor; import pl.edu.icm.cermine.metadata.model.DocumentAffiliation; import pl.edu.icm.cermine.metadata.model.DocumentMetadata; import pl.edu.icm.cermine.parsing.tools.ParsableStringParser; import pl.edu.icm.cermine.structure.CharacterExtractor; import pl.edu.icm.cermine.structure.DocumentSegmenter; import pl.edu.icm.cermine.structure.ReadingOrderResolver; import pl.edu.icm.cermine.structure.ZoneClassifier; import pl.edu.icm.cermine.tools.timeout.TimeoutRegister; /** * The class represents the configuration of the extraction system. * It contains all the objects performing the individual steps * of an extraction task. * * @author Dominika Tkaczyk (d.tkaczyk@icm.edu.pl) */ public class ComponentConfiguration { /** character extractor */ private CharacterExtractor characterExtractor; /** document object segmenter */ private DocumentSegmenter documentSegmenter; /** reading order resolver */ private ReadingOrderResolver readingOrderResolver; /** initial zone classifier */ private ZoneClassifier initialClassifier; /** metadata zone classifier */ private ZoneClassifier metadataClassifier; /** metadata extractor from labelled zones */ private MetadataExtractor<DocumentMetadata> metadataExtractor; /** affiliation parser **/ private ParsableStringParser<DocumentAffiliation> affiliationParser; /** references strings extractor */ private BibReferenceExtractor bibReferenceExtractor; /** bibliographic references parser */ private BibReferenceParser<BibEntry> bibReferenceParser; /** content filter */ private ContentFilter contentFilter; /** content header extractor */ private ContentHeadersExtractor contentHeaderExtractor; /** content header clusterizer */ private HeadersClusterizer contentHeaderClusterizer; /** content cleaner */ private ContentCleaner contentCleaner; /** citation position finder */ private ContentCitationPositionFinder citationPositionFinder; public ComponentConfiguration() throws AnalysisException { try { characterExtractor = ComponentFactory.getCharacterExtractor(); documentSegmenter = ComponentFactory.getDocumentSegmenter(); readingOrderResolver = ComponentFactory.getReadingOrderResolver(); initialClassifier = ComponentFactory.getInitialZoneClassifier( ExtractionConfigRegister.get().getStringProperty(ExtractionConfigProperty.INITIAL_ZONE_CLASSIFIER_MODEL_PATH), ExtractionConfigRegister.get().getStringProperty(ExtractionConfigProperty.INITIAL_ZONE_CLASSIFIER_RANGE_PATH)); TimeoutRegister.get().check(); metadataClassifier = ComponentFactory.getMetadataZoneClassifier( ExtractionConfigRegister.get().getStringProperty(ExtractionConfigProperty.METADATA_ZONE_CLASSIFIER_MODEL_PATH), ExtractionConfigRegister.get().getStringProperty(ExtractionConfigProperty.METADATA_ZONE_CLASSIFIER_RANGE_PATH)); TimeoutRegister.get().check(); metadataExtractor = ComponentFactory.getMetadataExtractor(); TimeoutRegister.get().check(); affiliationParser = ComponentFactory.getAffiliationParser(); TimeoutRegister.get().check(); bibReferenceExtractor = ComponentFactory.getBibReferenceExtractor(); bibReferenceParser = ComponentFactory.getBibReferenceParser(); contentFilter = ComponentFactory.getContentFilter( ExtractionConfigRegister.get().getStringProperty(ExtractionConfigProperty.CONTENT_FILTER_MODEL_PATH), ExtractionConfigRegister.get().getStringProperty(ExtractionConfigProperty.CONTENT_FILTER_RANGE_PATH)); TimeoutRegister.get().check(); contentHeaderExtractor = ComponentFactory.getContentHeaderExtractor(); contentHeaderClusterizer = ComponentFactory.getContentHeaderClusterizer(); contentCleaner = ComponentFactory.getContentCleaner(); citationPositionFinder = ComponentFactory.getCitationPositionFinder(); } catch (IOException ex) { throw new AnalysisException("Cannot create ComponentConfiguration!", ex); } } public void setCharacterExtractor(CharacterExtractor characterExtractor) { this.characterExtractor = characterExtractor; } public void setDocumentSegmenter(DocumentSegmenter documentSegmenter) { this.documentSegmenter = documentSegmenter; } public void setReadingOrderResolver(ReadingOrderResolver readingOrderResolver) { this.readingOrderResolver = readingOrderResolver; } public void setInitialZoneClassifier(ZoneClassifier initialClassifier) { this.initialClassifier = initialClassifier; } public void setInitialZoneClassifier(InputStream model, InputStream range) throws AnalysisException, IOException { this.initialClassifier = ComponentFactory.getInitialZoneClassifier(model, range); } public void setMetadataZoneClassifier(ZoneClassifier metadataClassifier) { this.metadataClassifier = metadataClassifier; } public void setMetadataZoneClassifier(InputStream model, InputStream range) throws AnalysisException, IOException { this.metadataClassifier = ComponentFactory.getMetadataZoneClassifier(model, range); } public void setMetadataExtractor(MetadataExtractor<DocumentMetadata> metadataExtractor) { this.metadataExtractor = metadataExtractor; } public void setAffiliationParser(ParsableStringParser<DocumentAffiliation> affiliationParser) { this.affiliationParser = affiliationParser; } public void setBibReferenceExtractor(BibReferenceExtractor bibReferenceExtractor) { this.bibReferenceExtractor = bibReferenceExtractor; } public void setBibReferenceParser(BibReferenceParser<BibEntry> bibReferenceParser) { this.bibReferenceParser = bibReferenceParser; } public void setBibReferenceParser(InputStream model, InputStream terms, InputStream journals, InputStream surnames, InputStream insts) throws AnalysisException { this.bibReferenceParser = ComponentFactory.getBibReferenceParser(model, terms, journals, surnames, insts); } public void setContentCleaner(ContentCleaner contentCleaner) { this.contentCleaner = contentCleaner; } public void setContentFilter(ContentFilter contentFilter) { this.contentFilter = contentFilter; } public void setContentFilter(InputStream model, InputStream range) throws AnalysisException, IOException { this.contentFilter = ComponentFactory.getContentFilter(model, range); } public void setContentHeaderExtractor(ContentHeadersExtractor contentHeaderExtractor) { this.contentHeaderExtractor = contentHeaderExtractor; } public void setContentHeaderExtractor(InputStream model, InputStream range) throws AnalysisException, IOException { this.contentHeaderExtractor = ComponentFactory.getContentHeaderExtractor(model, range); } public HeadersClusterizer getContentHeaderClusterizer() { return contentHeaderClusterizer; } public void setContentHeaderClusterizer(HeadersClusterizer contentHeaderClusterizer) { this.contentHeaderClusterizer = contentHeaderClusterizer; } public ParsableStringParser<DocumentAffiliation> getAffiliationParser() { return affiliationParser; } public BibReferenceExtractor getBibRefExtractor() { return bibReferenceExtractor; } public BibReferenceParser<BibEntry> getBibRefParser() { return bibReferenceParser; } public CharacterExtractor getCharacterExtractor() { return characterExtractor; } public DocumentSegmenter getDocumentSegmenter() { return documentSegmenter; } public ZoneClassifier getInitialClassifier() { return initialClassifier; } public ContentCleaner getContentCleaner() { return contentCleaner; } public ContentFilter getContentFilter() { return contentFilter; } public ContentHeadersExtractor getContentHeaderExtractor() { return contentHeaderExtractor; } public ZoneClassifier getMetadataClassifier() { return metadataClassifier; } public MetadataExtractor<DocumentMetadata> getMetadataExtractor() { return metadataExtractor; } public ReadingOrderResolver getReadingOrderResolver() { return readingOrderResolver; } public ContentCitationPositionFinder getCitationPositionFinder() { return citationPositionFinder; } public void setCitationPositionFinder(ContentCitationPositionFinder citationPositionFinder) { this.citationPositionFinder = citationPositionFinder; } }
10,562
39.471264
132
java
CERMINE
CERMINE-master/cermine-impl/src/main/java/pl/edu/icm/cermine/PdfNLMContentExtractor.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; import com.google.common.collect.Lists; import java.io.*; import java.util.Collection; import org.apache.commons.cli.ParseException; import org.apache.commons.io.FileUtils; import org.jdom.Element; import org.jdom.output.Format; import org.jdom.output.XMLOutputter; import pl.edu.icm.cermine.configuration.ExtractionConfigRegister; import pl.edu.icm.cermine.configuration.ExtractionConfigBuilder; import pl.edu.icm.cermine.exception.AnalysisException; import pl.edu.icm.cermine.exception.TransformationException; import pl.edu.icm.cermine.structure.model.BxDocument; import pl.edu.icm.cermine.structure.transformers.BxDocumentToTrueVizWriter; /** * NLM-based content extractor from PDF files. * * @deprecated use {@link ContentExtractor} instead. * * @author Dominika Tkaczyk (d.tkaczyk@icm.edu.pl) */ @Deprecated public class PdfNLMContentExtractor { private final ContentExtractor extractor; private boolean extractMetadata = true; private boolean extractReferences = true; private boolean extractText = true; public PdfNLMContentExtractor() throws AnalysisException { extractor = new ContentExtractor(); } /** * Extracts content from PDF file and stores it in NLM format. * * @param stream input stream * @return extracted content in NLM format * @throws AnalysisException AnalysisException */ public Element extractContent(InputStream stream) throws AnalysisException { try { extractor.reset(); extractor.setPDF(stream); return extractor.getContentAsNLM(); } catch (IOException ex) { throw new AnalysisException(ex); } } /** * Extracts content from a BxDocument and stores it in NLM format. * * @param document document's structure * @return extracted content in NLM format * @throws AnalysisException AnalysisException */ public Element extractContent(BxDocument document) throws AnalysisException { try { extractor.reset(); extractor.setBxDocument(document); return extractor.getContentAsNLM(); } catch (IOException ex) { throw new AnalysisException(ex); } } public BxDocument extractBxDocument(InputStream stream) throws AnalysisException { try { extractor.reset(); extractor.setPDF(stream); return extractor.getBxDocument(); } catch (IOException ex) { throw new AnalysisException(ex); } } public ComponentConfiguration getConf() { return extractor.getConf(); } public void setConf(ComponentConfiguration conf) { extractor.setConf(conf); } public boolean isExtractMetadata() { return extractMetadata; } public void setExtractMetadata(boolean extractMetadata) { this.extractMetadata = extractMetadata; } public boolean isExtractReferences() { return extractReferences; } public void setExtractReferences(boolean extractReferences) { this.extractReferences = extractReferences; } public boolean isExtractText() { return extractText; } public void setExtractText(boolean extractText) { this.extractText = extractText; } public static void main(String[] args) throws ParseException, IOException { CommandLineOptionsParser parser = new CommandLineOptionsParser(); String error = parser.parse(args); if (error != null) { System.err.println(error + "\n"); System.err.println( "Usage: PdfNLMContentExtractor -path <path> [optional parameters]\n\n" + "Tool for extracting metadata and content from PDF files.\n\n" + "Arguments:\n" + " -path <path> path to a PDF file or directory containing PDF files\n" + " -ext <extension> (optional) the extension of the resulting metadata file;\n" + " default: \"cermxml\"; used only if passed path is a directory\n" + " -configuration <path> (optional) path to configuration properties file\n" + " see https://github.com/CeON/CERMINE\n" + " for description of available configuration properties\n" + " -str whether to store structure (TrueViz) files as well;\n" + " used only if passed path is a directory\n" + " -strext <extension> (optional) the extension of the structure (TrueViz) file;\n" + " default: \"cxml\"; used only if passed path is a directory\n" ); System.exit(1); } String path = parser.getPath(); String extension = parser.getNLMExtension(); boolean extractStr = parser.extractStructure(); String strExtension = parser.getBxExtension(); ExtractionConfigBuilder builder = new ExtractionConfigBuilder(); if (parser.getConfigurationPath() != null) { builder.addConfiguration(parser.getConfigurationPath()); } ExtractionConfigRegister.set(builder.buildConfiguration()); File file = new File(path); if (file.isFile()) { try { PdfNLMContentExtractor extractor = new PdfNLMContentExtractor(); InputStream in = new FileInputStream(file); Element result = extractor.extractContent(in); XMLOutputter outputter = new XMLOutputter(Format.getPrettyFormat()); System.out.println(outputter.outputString(result)); } catch (AnalysisException ex) { ex.printStackTrace(); } } else { Collection<File> files = FileUtils.listFiles(file, new String[]{"pdf"}, true); int i = 0; for (File pdf : files) { File xmlF = new File(pdf.getPath().replaceAll("pdf$", extension)); if (xmlF.exists()) { i++; continue; } long start = System.currentTimeMillis(); float elapsed = 0; System.out.println(pdf.getPath()); try { PdfNLMContentExtractor extractor = new PdfNLMContentExtractor(); InputStream in = new FileInputStream(pdf); BxDocument doc = extractor.extractBxDocument(in); Element result = extractor.extractContent(doc); long end = System.currentTimeMillis(); elapsed = (end - start) / 1000F; XMLOutputter outputter = new XMLOutputter(Format.getPrettyFormat()); if (!xmlF.createNewFile()) { System.out.println("Cannot create new file!"); } FileUtils.writeStringToFile(xmlF, outputter.outputString(result)); if (extractStr) { BxDocumentToTrueVizWriter writer = new BxDocumentToTrueVizWriter(); File strF = new File(pdf.getPath().replaceAll("pdf$", strExtension)); Writer fw = new OutputStreamWriter(new FileOutputStream(strF), "UTF-8"); writer.write(fw, Lists.newArrayList(doc), "UTF-8"); } } catch (AnalysisException ex) { ex.printStackTrace(); } catch (TransformationException ex) { ex.printStackTrace(); } i++; int percentage = i*100/files.size(); if (elapsed == 0) { elapsed = (System.currentTimeMillis() - start) / 1000F; } System.out.println("Extraction time: " + Math.round(elapsed) + "s"); System.out.println(percentage + "% done (" + i +" out of " + files.size() + ")"); System.out.println(""); } } } }
9,198
37.651261
113
java
CERMINE
CERMINE-master/cermine-impl/src/main/java/pl/edu/icm/cermine/CommandLineOptionsParser.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; import com.google.common.collect.Lists; import java.util.HashMap; import java.util.List; import java.util.Map; import org.apache.commons.cli.*; import org.apache.commons.lang.ArrayUtils; /** * @author Dominika Tkaczyk (d.tkaczyk@icm.edu.pl) */ public class CommandLineOptionsParser { private final Options options; private CommandLine commandLine; public CommandLineOptionsParser() { options = new Options(); options.addOption("path", true, "file or directory path"); options.addOption("outputs", true, "types of the output"); options.addOption("exts", true, "extensions of the output files"); options.addOption("ext", true, "metadata file extension"); options.addOption("override", false, "override existing files"); options.addOption("str", false, "store structure (TrueViz) files as well"); options.addOption("strext", true, "structure file extension"); options.addOption("configuration", true, "path to configuration file"); options.addOption("timeout", true, "time in seconds"); } public String parse(String[] args) throws ParseException { CommandLineParser clParser = new DefaultParser(); commandLine = clParser.parse(options, args); if (commandLine.getOptionValue("path") == null) { return "\"path\" parameter not specified"; } String output = commandLine.getOptionValue("outputs"); String exts = commandLine.getOptionValue("exts"); if (output != null) { List<String> outputs = Lists.newArrayList(output.split(",")); outputs.removeAll(Lists.newArrayList("jats", "text", "zones", "trueviz", "images", "bibtex")); if (!outputs.isEmpty()) { return "Unknown output types: " + outputs; } if (exts != null && output.split(",").length != exts.split(",").length) { return "\"output\" and \"exts\" lists have different lengths"; } } return null; } public String getPath() { return commandLine.getOptionValue("path"); } public Map<String, String> getTypesAndExtensions() { Map<String, String> typesAndExts = new HashMap<String, String>(); typesAndExts.put("jats", "cermxml"); typesAndExts.put("text", "cermtxt"); typesAndExts.put("zones", "cermzones"); typesAndExts.put("trueviz", "cermstr"); typesAndExts.put("images", "images"); typesAndExts.put("bibtex", "bibtex"); String[] types = getStringOptionValue("jats,images", "outputs").split(","); for (String type: Lists.newArrayList(typesAndExts.keySet())) { if (!ArrayUtils.contains(types, type)) { typesAndExts.remove(type); } } String exts = commandLine.getOptionValue("exts"); if (exts != null) { String[] extArr = exts.split(","); if (types.length == extArr.length) { for (int i = 0; i < types.length; i++) { typesAndExts.put(types[i], extArr[i]); } } } return typesAndExts; } public boolean override() { return commandLine.hasOption("override"); } public String getNLMExtension() { return this.getStringOptionValue("cermxml", "ext"); } public String getTextExtension() { return this.getStringOptionValue("cermtxt", "ext"); } public boolean extractStructure() { return commandLine.hasOption("str"); } public String getBxExtension() { return this.getStringOptionValue("cxml", "strext"); } /** * @return timeout in seconds; Null if no timeout is set. */ public Long getTimeout() { if (!commandLine.hasOption("timeout")) { return null; } else { Long value = Long.parseLong(commandLine.getOptionValue("timeout")); if (value < 0) { throw new RuntimeException("The 'timeout' value given as a " + "command line parameter has to be nonnegative."); } return value; } } public String getConfigurationPath() { return getStringOptionValue(null, "configuration"); } private String getStringOptionValue(String defaultValue, String name) { String value = defaultValue; if (commandLine.hasOption(name)) { value = commandLine.getOptionValue(name); } return value; } }
5,448
33.707006
106
java
CERMINE
CERMINE-master/cermine-impl/src/main/java/pl/edu/icm/cermine/ContentExtractor.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; import java.io.File; import java.io.FileInputStream; import java.io.IOException; import java.io.InputStream; import java.util.Collection; import java.util.List; import org.apache.commons.cli.ParseException; import org.apache.commons.io.FileUtils; import org.apache.commons.lang.exception.ExceptionUtils; import org.jdom.Element; import org.jdom.output.Format; import org.jdom.output.XMLOutputter; import com.google.common.collect.Lists; import java.io.FileOutputStream; import java.io.OutputStreamWriter; import java.io.Writer; import java.util.HashMap; import java.util.Map; import javax.imageio.ImageIO; import org.jdom.DocType; import pl.edu.icm.cermine.bibref.model.BibEntry; import pl.edu.icm.cermine.configuration.ExtractionConfigRegister; import pl.edu.icm.cermine.configuration.ExtractionConfigBuilder; import pl.edu.icm.cermine.configuration.ExtractionConfigProperty; import pl.edu.icm.cermine.content.model.ContentStructure; import pl.edu.icm.cermine.exception.AnalysisException; import pl.edu.icm.cermine.exception.TransformationException; import pl.edu.icm.cermine.metadata.model.DocumentMetadata; import pl.edu.icm.cermine.structure.model.BxDocument; import pl.edu.icm.cermine.structure.model.BxImage; import pl.edu.icm.cermine.structure.transformers.BxDocumentToTrueVizWriter; import pl.edu.icm.cermine.tools.timeout.Timeout; import pl.edu.icm.cermine.tools.timeout.TimeoutException; import pl.edu.icm.cermine.tools.timeout.TimeoutRegister; /** * Extracts content from PDF files. * <p> * It stores the results of the extraction in various formats. The extraction * process is performed only if the requested result is not available yet. * <p> * User can set a timeout to limit the processing time of the <code>get*</code> * methods of the class. * * @author Dominika Tkaczyk (d.tkaczyk@icm.edu.pl) * @author Mateusz Kobos */ public class ContentExtractor { private static final long SECONDS_TO_MILLIS = 1000; private final InternalContentExtractor extractor; private Timeout mainTimeout = new Timeout(); /** * Creates the object with overridden default configuration. * * @throws AnalysisException thrown when there was an error while initializing object */ public ContentExtractor() throws AnalysisException { this.extractor = new InternalContentExtractor(); } /** * Creates the object with overridden default configuration and sets * the object-bound timeout before any other initialization in the constructor is done. * <p>See {@link #setTimeout(long)} for more details about the timeout.</p> * * @param timeoutSeconds approximate timeout in seconds * @throws AnalysisException thrown when there was an error while initializing object * @throws TimeoutException thrown when timeout deadline has passed. */ public ContentExtractor(long timeoutSeconds) throws AnalysisException, TimeoutException { this.setTimeout(timeoutSeconds); try { TimeoutRegister.set(mainTimeout); TimeoutRegister.get().check(); this.extractor = new InternalContentExtractor(); } finally { TimeoutRegister.remove(); } } /** * Set object-bound timeout. * <p> * If the deadline time specified by the timeout passes while one of the * <code>get*</code> methods of the class is running, the processing stops * and the method throws an exception. * <p> * In case the <code>get*</code> method defines a timeout by itself, it is * treated as an additional time restriction (i.e., the effective timeout * deadline is a minimum value of both timeout deadlines). * <p> * The value of the timeout is approximate. This is because in some cases, * the program might be allowed to slightly exceeded the timeout, say by a * second or two (depending on the processor speed and processed file * complexity). * * @param timeoutSeconds approximate timeout in seconds */ public void setTimeout(long timeoutSeconds) { this.mainTimeout = new Timeout(timeoutSeconds * SECONDS_TO_MILLIS); } /** * Remove the object-bound timeout. */ public void removeTimeout() { this.mainTimeout = new Timeout(); } /** * Stores the input PDF stream. * * @param pdfFile PDF stream * @throws IOException IOException */ public void setPDF(InputStream pdfFile) throws IOException { this.extractor.setPDF(pdfFile); } /** * Sets the input bx document. * * @param bxDocument bx document * @throws IOException IOException */ public void setBxDocument(BxDocument bxDocument) throws IOException { this.extractor.setBxDocument(bxDocument); } /** * Resets the extraction results. * * @throws IOException IOException */ public void reset() throws IOException { this.extractor.reset(); } public ComponentConfiguration getConf() { return this.extractor.getConf(); } public void setConf(ComponentConfiguration conf) { this.extractor.setConf(conf); } private BxDocument getBxDocument(Timeout timeout) throws AnalysisException, TimeoutException { try { TimeoutRegister.set(timeout); TimeoutRegister.get().check(); return extractor.getBxDocument(); } finally { TimeoutRegister.remove(); } } /** * Extracts geometric structure. * * @return geometric structure * @throws AnalysisException AnalysisException * @throws TimeoutException thrown when timeout deadline has passed. See * {@link #setTimeout(long)} for additional information about the timeout. */ public BxDocument getBxDocument() throws AnalysisException, TimeoutException { return getBxDocument(mainTimeout); } /** * The same as {@link #getBxDocument()} but with a timeout. * * @param timeoutSeconds approximate timeout in seconds * @return geometric structure * @throws AnalysisException AnalysisException * @throws TimeoutException thrown when timeout deadline has passed. See * {@link #setTimeout(long)} for additional information about the timeout. */ public BxDocument getBxDocument(long timeoutSeconds) throws AnalysisException, TimeoutException { return getBxDocument(combineWithMainTimeout(timeoutSeconds)); } private BxDocument getBxDocumentWithGeneralLabels(Timeout timeout) throws AnalysisException, TimeoutException { try { TimeoutRegister.set(timeout); TimeoutRegister.get().check(); return extractor.getBxDocumentWithGeneralLabels(); } finally { TimeoutRegister.remove(); } } /** * Extracts geometric structure with general labels. * * @return geometric structure * @throws AnalysisException AnalysisException * @throws TimeoutException thrown when timeout deadline has passed. See * {@link #setTimeout(long)} for additional information about the timeout. */ public BxDocument getBxDocumentWithGeneralLabels() throws AnalysisException, TimeoutException { return getBxDocumentWithGeneralLabels(mainTimeout); } /** * The same as {@link #getBxDocumentWithGeneralLabels()} but with a timeout. * * @param timeoutSeconds approximate timeout in seconds * @return geometric structure * @throws AnalysisException AnalysisException * @throws TimeoutException thrown when timeout deadline has passed. See * {@link #setTimeout(long)} for additional information about the timeout. */ public BxDocument getBxDocumentWithGeneralLabels(long timeoutSeconds) throws AnalysisException, TimeoutException { return getBxDocumentWithGeneralLabels(combineWithMainTimeout(timeoutSeconds)); } private BxDocument getBxDocumentWithSpecificLabels(Timeout timeout) throws AnalysisException, TimeoutException { try { TimeoutRegister.set(timeout); TimeoutRegister.get().check(); return extractor.getBxDocumentWithSpecificLabels(); } finally { TimeoutRegister.remove(); } } /** * Extracts geometric structure with specific labels. * * @return geometric structure * @throws AnalysisException AnalysisException * @throws TimeoutException thrown when timeout deadline has passed. See * {@link #setTimeout(long)} for additional information about the timeout. */ public BxDocument getBxDocumentWithSpecificLabels() throws AnalysisException, TimeoutException { return getBxDocumentWithSpecificLabels(mainTimeout); } /** * The same as {@link #getBxDocumentWithSpecificLabels()} but with a timeout. * * @param timeoutSeconds approximate timeout in seconds * @return geometric structure * @throws AnalysisException AnalysisException * @throws TimeoutException thrown when timeout deadline has passed. See * {@link #setTimeout(long)} for additional information about the timeout. */ public BxDocument getBxDocumentWithSpecificLabels(long timeoutSeconds) throws AnalysisException, TimeoutException { return getBxDocumentWithSpecificLabels(combineWithMainTimeout(timeoutSeconds)); } private List<BxImage> getImages(String imagesPrefix, Timeout timeout) throws AnalysisException, TimeoutException { try { TimeoutRegister.set(timeout); TimeoutRegister.get().check(); return extractor.getImages(imagesPrefix); } finally { TimeoutRegister.remove(); } } /** * Extracts images. * * @param imagesPrefix images prefix * @return images * @throws AnalysisException AnalysisException * @throws TimeoutException thrown when timeout deadline has passed. See * {@link #setTimeout(long)} for additional information about the timeout. */ public List<BxImage> getImages(String imagesPrefix) throws AnalysisException, TimeoutException { return getImages(imagesPrefix, mainTimeout); } /** * The same as {@link #getImages(String)} but with a timeout. * * @param imagesPrefix imagesPrefix * @param timeoutSeconds approximate timeout in seconds * @return images * @throws AnalysisException AnalysisException * @throws TimeoutException thrown when timeout deadline has passed. See * {@link #setTimeout(long)} for additional information about the timeout. */ public List<BxImage> getImages(String imagesPrefix, long timeoutSeconds) throws AnalysisException, TimeoutException { return getImages(imagesPrefix, combineWithMainTimeout(timeoutSeconds)); } private DocumentMetadata getMetadata(Timeout timeout) throws AnalysisException, TimeoutException { try { TimeoutRegister.set(timeout); TimeoutRegister.get().check(); return extractor.getMetadata(); } finally { TimeoutRegister.remove(); } } /** * Extracts the metadata. * * @return the metadata * @throws AnalysisException AnalysisException * @throws TimeoutException thrown when timeout deadline has passed. See * {@link #setTimeout(long)} for additional information about the timeout. */ public DocumentMetadata getMetadata() throws AnalysisException, TimeoutException { return getMetadata(mainTimeout); } /** * The same as {@link #getMetadata()} but with a timeout. * * @param timeoutSeconds approximate timeout in seconds * @return metadata * @throws AnalysisException AnalysisException * @throws TimeoutException thrown when timeout deadline has passed. See * {@link #setTimeout(long)} for additional information about the timeout. */ public DocumentMetadata getMetadata(long timeoutSeconds) throws AnalysisException, TimeoutException { return getMetadata(combineWithMainTimeout(timeoutSeconds)); } private Element getMetadataAsNLM(Timeout timeout) throws AnalysisException, TimeoutException { try { TimeoutRegister.set(timeout); TimeoutRegister.get().check(); return extractor.getMetadataAsNLM(); } finally { TimeoutRegister.remove(); } } /** * Extracts the metadata in NLM format. * * @return the metadata in NLM format * @throws AnalysisException AnalysisException * @throws TimeoutException thrown when timeout deadline has passed. See * {@link #setTimeout(long)} for additional information about the timeout. */ public Element getMetadataAsNLM() throws AnalysisException, TimeoutException { return getMetadataAsNLM(mainTimeout); } /** * The same as {@link #getMetadataAsNLM()} but with a timeout. * * @param timeoutSeconds approximate timeout in seconds * @return metadata in NLM * @throws AnalysisException AnalysisException * @throws TimeoutException thrown when timeout deadline has passed. See * {@link #setTimeout(long)} for additional information about the timeout. */ public Element getMetadataAsNLM(long timeoutSeconds) throws AnalysisException, TimeoutException { return getMetadataAsNLM(combineWithMainTimeout(timeoutSeconds)); } private List<BibEntry> getReferences(Timeout timeout) throws AnalysisException, TimeoutException { try { TimeoutRegister.set(timeout); TimeoutRegister.get().check(); return extractor.getReferences(); } finally { TimeoutRegister.remove(); } } /** * Extracts the references. * * @return the list of references * @throws AnalysisException AnalysisException * @throws TimeoutException thrown when timeout deadline has passed. See * {@link #setTimeout(long)} for additional information about the timeout. */ public List<BibEntry> getReferences() throws AnalysisException, TimeoutException { return getReferences(mainTimeout); } /** * The same as {@link #getReferences()} but with a timeout. * * @param timeoutSeconds approximate timeout in seconds * @return list of references * @throws AnalysisException AnalysisException * @throws TimeoutException thrown when timeout deadline has passed. See * {@link #setTimeout(long)} for additional information about the timeout. */ public List<BibEntry> getReferences(long timeoutSeconds) throws AnalysisException, TimeoutException { return getReferences(combineWithMainTimeout(timeoutSeconds)); } private List<Element> getReferencesAsNLM(Timeout timeout) throws AnalysisException, TimeoutException { try { TimeoutRegister.set(timeout); TimeoutRegister.get().check(); return extractor.getReferencesAsNLM(); } finally { TimeoutRegister.remove(); } } /** * Extracts the references in NLM format. * * @return the list of references * @throws AnalysisException AnalysisException * @throws TimeoutException thrown when timeout deadline has passed. See * {@link #setTimeout(long)} for additional information about the timeout. */ public List<Element> getReferencesAsNLM() throws AnalysisException, TimeoutException { return getReferencesAsNLM(mainTimeout); } /** * The same as {@link #getReferencesAsNLM()} but with a timeout. * * @param timeoutSeconds approximate timeout in seconds * @return the list of references * @throws AnalysisException AnalysisException * @throws TimeoutException thrown when timeout deadline has passed. See * {@link #setTimeout(long)} for additional information about the timeout. */ public List<Element> getReferencesAsNLM(long timeoutSeconds) throws AnalysisException, TimeoutException { return getReferencesAsNLM(combineWithMainTimeout(timeoutSeconds)); } private String getRawFullText(Timeout timeout) throws AnalysisException, TimeoutException { try { TimeoutRegister.set(timeout); TimeoutRegister.get().check(); return extractor.getRawFullText(); } finally { TimeoutRegister.remove(); } } /** * Extracts raw text. * * @return raw text * @throws AnalysisException AnalysisException * @throws TimeoutException thrown when timeout deadline has passed. See * {@link #setTimeout(long)} for additional information about the timeout. */ public String getRawFullText() throws AnalysisException, TimeoutException { return getRawFullText(mainTimeout); } /** * The same as {@link #getRawFullText()} but with a timeout. * * @param timeoutSeconds approximate timeout in seconds * @return full text * @throws AnalysisException AnalysisException * @throws TimeoutException thrown when timeout deadline has passed. See * {@link #setTimeout(long)} for additional information about the timeout. */ public String getRawFullText(long timeoutSeconds) throws AnalysisException, TimeoutException { return getRawFullText(combineWithMainTimeout(timeoutSeconds)); } private Element getLabelledFullText(Timeout timeout) throws AnalysisException, TimeoutException { try { TimeoutRegister.set(timeout); TimeoutRegister.get().check(); return extractor.getLabelledFullText(); } finally { TimeoutRegister.remove(); } } /** * Extracts labeled raw text. * * @return labeled raw text * @throws AnalysisException AnalysisException * @throws TimeoutException thrown when timeout deadline has passed. See * {@link #setTimeout(long)} for additional information about the timeout. */ public Element getLabelledFullText() throws AnalysisException, TimeoutException { return getLabelledFullText(mainTimeout); } /** * The same as {@link #getLabelledFullText()} but with a timeout. * * @param timeoutSeconds approximate timeout in seconds * @return labelled full text * @throws AnalysisException AnalysisException * @throws TimeoutException thrown when timeout deadline has passed. See * {@link #setTimeout(long)} for additional information about the timeout. */ public Element getLabelledFullText(long timeoutSeconds) throws AnalysisException, TimeoutException { return getLabelledFullText(combineWithMainTimeout(timeoutSeconds)); } private ContentStructure getBody(Timeout timeout) throws AnalysisException, TimeoutException { try { TimeoutRegister.set(timeout); TimeoutRegister.get().check(); return extractor.getBody(); } finally { TimeoutRegister.remove(); } } /** * Extracts structured full text. * * @return full text * @throws AnalysisException AnalysisException * @throws TimeoutException thrown when timeout deadline has passed. See * {@link #setTimeout(long)} for additional information about the timeout. */ public ContentStructure getBody() throws AnalysisException, TimeoutException { return getBody(mainTimeout); } /** * The same as {@link #getBody()} but with a timeout. * * @param timeoutSeconds approximate timeout in seconds * @return full text * @throws AnalysisException AnalysisException * @throws TimeoutException thrown when timeout deadline has passed. See * {@link #setTimeout(long)} for additional information about the timeout. */ public ContentStructure getBody(long timeoutSeconds) throws AnalysisException, TimeoutException { return getBody(combineWithMainTimeout(timeoutSeconds)); } private Element getBodyAsNLM(String imagesPrefix, Timeout timeout) throws AnalysisException, TimeoutException { try { TimeoutRegister.set(timeout); TimeoutRegister.get().check(); return extractor.getBodyAsNLM(imagesPrefix); } finally { TimeoutRegister.remove(); } } /** * Extracts structured full text. * * @return full text in NLM format * @throws AnalysisException AnalysisException * @throws TimeoutException thrown when timeout deadline has passed. See * {@link #setTimeout(long)} for additional information about the timeout. */ public Element getBodyAsNLM() throws AnalysisException, TimeoutException { return getBodyAsNLM(null, mainTimeout); } /** * Extracts structured full text. * * @param imagesPrefix images prefix * @return full text in NLM format * @throws AnalysisException AnalysisException * @throws TimeoutException thrown when timeout deadline has passed. See * {@link #setTimeout(long)} for additional information about the timeout. */ public Element getBodyAsNLM(String imagesPrefix) throws AnalysisException, TimeoutException { return getBodyAsNLM(imagesPrefix, mainTimeout); } /** * The same as {@link #getBodyAsNLM()} but with a timeout. * * @param timeoutSeconds approximate timeout in seconds * @return full text in NLM * @throws AnalysisException AnalysisException * @throws TimeoutException thrown when timeout deadline has passed. See * {@link #setTimeout(long)} for additional information about the timeout. */ public Element getBodyAsNLM(long timeoutSeconds) throws AnalysisException, TimeoutException { return getBodyAsNLM(null, combineWithMainTimeout(timeoutSeconds)); } /** * The same as {@link #getBodyAsNLM()} but with a timeout. * * @param imagesPrefix images prefix * @param timeoutSeconds approximate timeout in seconds * @return full text in NLM * @throws AnalysisException AnalysisException * @throws TimeoutException thrown when timeout deadline has passed. See * {@link #setTimeout(long)} for additional information about the timeout. */ public Element getBodyAsNLM(String imagesPrefix, long timeoutSeconds) throws AnalysisException, TimeoutException { return getBodyAsNLM(imagesPrefix, combineWithMainTimeout(timeoutSeconds)); } private Element getContentAsNLM(String imagesPrefix, Timeout timeout) throws AnalysisException, TimeoutException { try { TimeoutRegister.set(timeout); TimeoutRegister.get().check(); return extractor.getContentAsNLM(imagesPrefix); } finally { TimeoutRegister.remove(); } } /** * Extracts full content in NLM format. * * @return full content in NLM format * @throws AnalysisException AnalysisException * @throws TimeoutException thrown when timeout deadline has passed. See * {@link #setTimeout(long)} for additional information about the timeout. */ public Element getContentAsNLM() throws AnalysisException, TimeoutException { return getContentAsNLM(null, mainTimeout); } /** * Extracts full content in NLM format. * * @param imagesPrefix imagesPrefix * @return full content in NLM format * @throws AnalysisException AnalysisException * @throws TimeoutException thrown when timeout deadline has passed. See * {@link #setTimeout(long)} for additional information about the timeout. */ public Element getContentAsNLM(String imagesPrefix) throws AnalysisException, TimeoutException { return getContentAsNLM(imagesPrefix, mainTimeout); } /** * The same as {@link #getContentAsNLM()} but with a timeout. * * @param timeoutSeconds approximate timeout in seconds * @return the content in NLM * @throws AnalysisException AnalysisException * @throws TimeoutException thrown when timeout deadline has passed. See * {@link #setTimeout(long)} for additional information about the timeout. */ public Element getContentAsNLM(long timeoutSeconds) throws AnalysisException, TimeoutException { return getContentAsNLM(null, combineWithMainTimeout(timeoutSeconds)); } /** * The same as {@link #getContentAsNLM()} but with a timeout. * * @param imagesPrefix images prefix * @param timeoutSeconds approximate timeout in seconds * @return the content in NLM * @throws AnalysisException AnalysisException * @throws TimeoutException thrown when timeout deadline has passed. See * {@link #setTimeout(long)} for additional information about the timeout. */ public Element getContentAsNLM(String imagesPrefix, long timeoutSeconds) throws AnalysisException, TimeoutException { return getContentAsNLM(imagesPrefix, combineWithMainTimeout(timeoutSeconds)); } private Timeout combineWithMainTimeout(long timeoutSeconds) { Timeout local = new Timeout(timeoutSeconds * SECONDS_TO_MILLIS); return Timeout.min(mainTimeout, local); } public static void main(String[] args) throws ParseException, AnalysisException, IOException, TransformationException { CommandLineOptionsParser parser = new CommandLineOptionsParser(); String error = parser.parse(args); if (error != null) { System.err.println(error + "\n"); System.err.println( "Usage: ContentExtractor -path <path> [optional parameters]\n\n" + "Tool for extracting metadata and content from PDF files.\n\n" + "Arguments:\n" + " -path <path> path to a directory containing PDF files\n" + " -outputs <list> (optional) comma-separated list of extraction\n" + " output(s); possible values: \"jats\" (document\n" + " metadata and content in NLM JATS format), \"text\"\n" + " (raw document text), \"zones\" (text zones with\n" + " their labels), \"trueviz\" (geometric structure in\n" + " TrueViz format), \"images\" (images from the\n" + " document), \"bibtex\" (references in BibTex format);\n" + " default: \"jats,images\"\n" + " -exts <list> (optional) comma-separated list of extensions of the\n" + " resulting files; the list has to have the same\n" + " length as output list; default: \"cermxml,images\"\n" + " -override override already existing files\n" + " -timeout <seconds> (optional) approximate maximum allowed processing\n" + " time for a PDF file in seconds; by default, no\n" + " timeout is used; the value is approximate because in\n" + " some cases, the program might be allowed to slightly\n" + " exceeded this time, say by a second or two\n" + " -configuration <path> (optional) path to configuration properties file\n" + " see https://github.com/CeON/CERMINE\n" + " for description of available configuration properties\n" ); System.exit(1); } boolean override = parser.override(); Long timeoutSeconds = parser.getTimeout(); String path = parser.getPath(); Map<String, String> extensions = parser.getTypesAndExtensions(); File file = new File(path); Collection<File> files = FileUtils.listFiles(file, new String[]{"pdf"}, true); ExtractionConfigBuilder builder = new ExtractionConfigBuilder(); if (parser.getConfigurationPath() != null) { builder.addConfiguration(parser.getConfigurationPath()); } builder.setProperty(ExtractionConfigProperty.IMAGES_EXTRACTION, extensions.containsKey("images")); ExtractionConfigRegister.set(builder.buildConfiguration()); int i = 0; for (File pdf : files) { Map<String, File> outputs = new HashMap<String, File>(); for (Map.Entry<String, String> entry : extensions.entrySet()) { File outputFile = getOutputFile(pdf, entry.getValue()); if (override || !outputFile.exists()) { outputs.put(entry.getKey(), outputFile); } } if (outputs.isEmpty()) { i++; continue; } long start = System.currentTimeMillis(); float elapsed; System.out.println("File processed: " + pdf.getPath()); ContentExtractor extractor = null; try { extractor = createContentExtractor(timeoutSeconds); InputStream in = new FileInputStream(pdf); extractor.setPDF(in); if (outputs.containsKey("images")) { List<BxImage> images = extractor.getImages(outputs.get("images").getPath()); FileUtils.forceMkdir(outputs.get("images")); for (BxImage image : images) { ImageIO.write(image.getImage(), "png", new File(image.getPath())); } } if (outputs.containsKey("jats")) { Element jats; if (outputs.containsKey("images")) { jats = extractor.getContentAsNLM(outputs.get("images").getPath()); } else { jats = extractor.getContentAsNLM(null); } XMLOutputter outputter = new XMLOutputter(Format.getPrettyFormat()); DocType dt = new DocType("article", "-//NLM//DTD JATS (Z39.96) Journal Archiving and Interchange DTD v1.0 20120330//EN", "JATS-archivearticle1.dtd"); FileUtils.writeStringToFile(outputs.get("jats"), outputter.outputString(dt), "UTF-8"); FileUtils.writeStringToFile(outputs.get("jats"), "\n", "UTF-8", true); FileUtils.writeStringToFile(outputs.get("jats"), outputter.outputString(jats), "UTF-8", true); } if (outputs.containsKey("trueviz")) { BxDocument doc = extractor.getBxDocumentWithSpecificLabels(); BxDocumentToTrueVizWriter writer = new BxDocumentToTrueVizWriter(); Writer fw = new OutputStreamWriter(new FileOutputStream(outputs.get("trueviz")), "UTF-8"); writer.write(fw, Lists.newArrayList(doc), "UTF-8"); } if (outputs.containsKey("zones")) { Element text = extractor.getLabelledFullText(); XMLOutputter outputter = new XMLOutputter(Format.getPrettyFormat()); FileUtils.writeStringToFile(outputs.get("zones"), outputter.outputString(text), "UTF-8"); } if (outputs.containsKey("text")) { String text = extractor.getRawFullText(); FileUtils.writeStringToFile(outputs.get("text"), text, "UTF-8"); } if (outputs.containsKey("bibtex")) { List<BibEntry> references = extractor.getReferences(); for (BibEntry reference: references) { FileUtils.writeStringToFile(outputs.get("bibtex"), reference.toBibTeX(), "UTF-8", true); FileUtils.writeStringToFile(outputs.get("bibtex"), "\n", "UTF-8", true); } } } catch (AnalysisException ex) { printException(ex); } catch (TransformationException ex) { printException(ex); } catch (TimeoutException ex) { printException(ex); } finally { if (extractor != null) { extractor.removeTimeout(); } long end = System.currentTimeMillis(); elapsed = (end - start) / 1000F; } i++; int percentage = i * 100 / files.size(); System.out.println("Extraction time: " + Math.round(elapsed) + "s"); System.out.println("Progress: " + percentage + "% done (" + i + " out of " + files.size() + ")"); System.out.println(""); } } private static ContentExtractor createContentExtractor(Long timeoutSeconds) throws TimeoutException, AnalysisException { ContentExtractor extractor; if (timeoutSeconds != null) { extractor = new ContentExtractor(timeoutSeconds); } else { extractor = new ContentExtractor(); } TimeoutRegister.get().check(); return extractor; } private static File getOutputFile(File pdf, String ext) { return new File(pdf.getPath().replaceFirst("pdf$", ext)); } private static void printException(Exception ex) { System.out.print("Exception occured: " + ExceptionUtils.getStackTrace(ex)); } }
35,437
38.595531
169
java
CERMINE
CERMINE-master/cermine-impl/src/main/java/pl/edu/icm/cermine/PdfBxStructureExtractor.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; import com.google.common.collect.Lists; import java.io.*; import java.util.Collection; import org.apache.commons.cli.ParseException; import org.apache.commons.io.FileUtils; import pl.edu.icm.cermine.configuration.ExtractionConfigRegister; import pl.edu.icm.cermine.configuration.ExtractionConfigBuilder; import pl.edu.icm.cermine.exception.AnalysisException; import pl.edu.icm.cermine.exception.TransformationException; import pl.edu.icm.cermine.structure.model.BxDocument; import pl.edu.icm.cermine.structure.transformers.BxDocumentToTrueVizWriter; /** * Document geometric structure extractor. Extracts the geometric hierarchical structure * (pages, zones, lines, words and characters) from a PDF file and stores it as a BxDocument object. * * @deprecated use {@link ContentExtractor} instead. * * @author Dominika Tkaczyk (d.tkaczyk@icm.edu.pl) */ @Deprecated public class PdfBxStructureExtractor { private final ContentExtractor extractor; public PdfBxStructureExtractor() throws AnalysisException { extractor = new ContentExtractor(); } /** * Extracts the geometric structure from a PDF file and stores it as BxDocument. * * @param stream PDF stream * @return BxDocument object storing the geometric structure * @throws AnalysisException AnalysisException */ public BxDocument extractStructure(InputStream stream) throws AnalysisException { try { extractor.setPDF(stream); return extractor.getBxDocument(); } catch (IOException ex) { throw new AnalysisException(ex); } } public ComponentConfiguration getConf() { return extractor.getConf(); } public void setConf(ComponentConfiguration conf) { extractor.setConf(conf); } public static void main(String[] args) throws ParseException, IOException { CommandLineOptionsParser parser = new CommandLineOptionsParser(); String error = parser.parse(args); if (error != null) { System.err.println(error + "\n"); System.err.println( "Usage: PdfBxStructureExtractor -path <path> [optional parameters]\n\n" + "Tool for extracting structured content from PDF files.\n\n" + "Arguments:\n" + " -path <path> path to a PDF file or directory containing PDF files\n" + " -configuration <path> (optional) path to configuration properties file\n" + " see https://github.com/CeON/CERMINE\n" + " for description of available configuration properties\n" + " -strext <extension> (optional) the extension of the structure (TrueViz) file;\n" + " default: \"cxml\"; used only if passed path is a directory\n" ); System.exit(1); } String path = parser.getPath(); String strExtension = parser.getBxExtension(); File file = new File(path); Collection<File> files = FileUtils.listFiles(file, new String[]{"pdf"}, true); ExtractionConfigBuilder builder = new ExtractionConfigBuilder(); if (parser.getConfigurationPath() != null) { builder.addConfiguration(parser.getConfigurationPath()); } ExtractionConfigRegister.set(builder.buildConfiguration()); int i = 0; for (File pdf : files) { File strF = new File(pdf.getPath().replaceAll("pdf$", strExtension)); if (strF.exists()) { i++; continue; } long start = System.currentTimeMillis(); float elapsed = 0; System.out.println(pdf.getPath()); try { PdfBxStructureExtractor extractor = new PdfBxStructureExtractor(); InputStream in = new FileInputStream(pdf); BxDocument doc = extractor.extractStructure(in); doc = extractor.getConf().getMetadataClassifier().classifyZones(doc); long end = System.currentTimeMillis(); elapsed = (end - start) / 1000F; BxDocumentToTrueVizWriter writer = new BxDocumentToTrueVizWriter(); Writer fw = new OutputStreamWriter(new FileOutputStream(strF), "UTF-8"); writer.write(fw, Lists.newArrayList(doc), "UTF-8"); } catch (AnalysisException ex) { ex.printStackTrace(); } catch (TransformationException ex) { ex.printStackTrace(); } i++; int percentage = i*100/files.size(); if (elapsed == 0) { elapsed = (System.currentTimeMillis() - start) / 1000F; } System.out.println("Extraction time: " + Math.round(elapsed) + "s"); System.out.println(percentage + "% done (" + i +" out of " + files.size() + ")"); System.out.println(""); } } }
5,937
38.852349
110
java
CERMINE
CERMINE-master/cermine-impl/src/main/java/pl/edu/icm/cermine/ComponentFactory.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; import java.io.BufferedReader; import java.io.IOException; import java.io.InputStream; import java.io.InputStreamReader; import pl.edu.icm.cermine.bibref.BibReferenceExtractor; import pl.edu.icm.cermine.bibref.BibReferenceParser; import pl.edu.icm.cermine.bibref.CRFBibReferenceParser; import pl.edu.icm.cermine.bibref.KMeansBibReferenceExtractor; import pl.edu.icm.cermine.bibref.model.BibEntry; import pl.edu.icm.cermine.content.citations.ContentCitationPositionFinder; import pl.edu.icm.cermine.content.cleaning.ContentCleaner; import pl.edu.icm.cermine.content.filtering.ContentFilter; import pl.edu.icm.cermine.content.filtering.SVMContentFilter; import pl.edu.icm.cermine.content.headers.*; import pl.edu.icm.cermine.exception.AnalysisException; import pl.edu.icm.cermine.metadata.EnhancerMetadataExtractor; import pl.edu.icm.cermine.metadata.MetadataExtractor; import pl.edu.icm.cermine.metadata.affiliation.CRFAffiliationParser; import pl.edu.icm.cermine.metadata.model.DocumentAffiliation; import pl.edu.icm.cermine.metadata.model.DocumentMetadata; import pl.edu.icm.cermine.parsing.tools.ParsableStringParser; import pl.edu.icm.cermine.structure.*; import pl.edu.icm.cermine.tools.ResourceUtils; /** * A factory of extraction components. * * @author Dominika Tkaczyk (d.tkaczyk@icm.edu.pl) */ public class ComponentFactory { /** * The method creates an instance of a default character extractor. * * @return character extractor */ public static CharacterExtractor getCharacterExtractor() { return new ITextCharacterExtractor(); } /** * The method creates an instance of a default page segmenter. * * @return page segmenter */ public static DocumentSegmenter getDocumentSegmenter() { return new DocstrumSegmenter(); } /** * The method creates an instance of a default reading order resolver. * * @return reading order resolver */ public static ReadingOrderResolver getReadingOrderResolver() { return new HierarchicalReadingOrderResolver(); } /** * The method creates an instance of an initial zone classifier. * * @param modelPath Path to svm model file (can be regular file or a classpath resource). * For classpath resource, path should be prefixed with <code>classpath:</code> * @param rangePath Path to svm range file (can be regular file or a classpath resource). * For classpath resource, path should be prefixed with <code>classpath:</code> * @return initial zone classifier * @throws AnalysisException AnalysisException * @throws IOException IOException */ public static ZoneClassifier getInitialZoneClassifier(String modelPath, String rangePath) throws AnalysisException, IOException { return getInitialZoneClassifier(ResourceUtils.openResourceStream(modelPath), ResourceUtils.openResourceStream(rangePath)); } /** * The method creates an instance of an initial zone classifier. * * @param model svm model * @param range svm range file * @return initial zone classifier * @throws AnalysisException AnalysisException * @throws IOException IOException */ public static ZoneClassifier getInitialZoneClassifier(InputStream model, InputStream range) throws AnalysisException, IOException { BufferedReader modelFileBR = new BufferedReader(new InputStreamReader(model, "UTF-8")); BufferedReader rangeFileBR = new BufferedReader(new InputStreamReader(range, "UTF-8")); ZoneClassifier classifier; try { classifier = new SVMInitialZoneClassifier(modelFileBR, rangeFileBR); } finally { modelFileBR.close(); rangeFileBR.close(); } return classifier; } /** * The method creates an instance of a metadata zone classifier. * * @param modelPath Path to svm model file (can be regular file or a classpath resource). * For classpath resource, path should be prefixed with <code>classpath:</code> * @param rangePath Path to svm range file (can be regular file or a classpath resource). * For classpath resource, path should be prefixed with <code>classpath:</code> * @return metadata zone classifier * @throws AnalysisException AnalysisException * @throws IOException IOException */ public static ZoneClassifier getMetadataZoneClassifier(String modelPath, String rangePath) throws AnalysisException, IOException { return getMetadataZoneClassifier(ResourceUtils.openResourceStream(modelPath), ResourceUtils.openResourceStream(rangePath)); } /** * The method creates an instance of a metadata zone classifier. * * @param model svm model * @param range svm range file * @return metadata zone classifier * @throws AnalysisException AnalysisException * @throws IOException IOException */ public static ZoneClassifier getMetadataZoneClassifier(InputStream model, InputStream range) throws AnalysisException, IOException { BufferedReader modelFileBR = new BufferedReader(new InputStreamReader(model, "UTF-8")); BufferedReader rangeFileBR = new BufferedReader(new InputStreamReader(range, "UTF-8")); ZoneClassifier classifier; try { classifier = new SVMMetadataZoneClassifier(modelFileBR, rangeFileBR); } finally { modelFileBR.close(); rangeFileBR.close(); } return classifier; } /** * The method creates an instance of a default metadata extractor. * * @return metadata extractor */ public static MetadataExtractor<DocumentMetadata> getMetadataExtractor() { return new EnhancerMetadataExtractor(); } /** * The method creates an instance of a default affiliation parser. * * @return affiliation parser * @throws AnalysisException AnalysisException */ public static ParsableStringParser<DocumentAffiliation> getAffiliationParser() throws AnalysisException { return new CRFAffiliationParser(); } /** * The method creates an instance of a default bib reference extractor. * * @return bib reference extractor */ public static BibReferenceExtractor getBibReferenceExtractor() { return new KMeansBibReferenceExtractor(); } /** * The method creates an instance of a default bib reference parser. * * @return bib reference parser * @throws AnalysisException AnalysisException */ public static BibReferenceParser<BibEntry> getBibReferenceParser() throws AnalysisException { return CRFBibReferenceParser.getInstance(); } /** * The method creates an instance of a bib reference parser. * * @param model crf model * @param terms terms file * @param journals journals file * @param surnames surnames file * @param insts institutions file * @return parser * @throws AnalysisException AnalysisException */ public static BibReferenceParser<BibEntry> getBibReferenceParser(InputStream model, InputStream terms, InputStream journals, InputStream surnames, InputStream insts) throws AnalysisException { return new CRFBibReferenceParser(model, terms, journals, surnames, insts); } /** * The method creates an instance of a default content filter. * * @param modelPath Path to svm model file (can be regular file or a classpath resource). * For classpath resource, path should be prefixed with <code>classpath:</code> * @param rangePath Path to svm range file (can be regular file or a classpath resource). * For classpath resource, path should be prefixed with <code>classpath:</code> * @return content filter * @throws AnalysisException AnalysisException * @throws IOException IOException */ public static ContentFilter getContentFilter(String modelPath, String rangePath) throws AnalysisException, IOException { return getContentFilter(ResourceUtils.openResourceStream(modelPath), ResourceUtils.openResourceStream(rangePath)); } /** * The method creates an instance of a content filter. * * @param model svm model file * @param range svm range file * @return content filter * @throws AnalysisException AnalysisException * @throws IOException IOException */ public static ContentFilter getContentFilter(InputStream model, InputStream range) throws AnalysisException, IOException { BufferedReader modelFileBR = new BufferedReader(new InputStreamReader(model, "UTF-8")); BufferedReader rangeFileBR = new BufferedReader(new InputStreamReader(range, "UTF-8")); ContentFilter filter; try { filter = new SVMContentFilter(modelFileBR, rangeFileBR); } finally { modelFileBR.close(); rangeFileBR.close(); } return filter; } /** * The method creates an instance of a default content header extractor. * * @return content header extractor * @throws AnalysisException AnalysisException */ public static ContentHeadersExtractor getContentHeaderExtractor() throws AnalysisException { return new HeuristicContentHeadersExtractor(); } public static HeadersClusterizer getContentHeaderClusterizer() throws AnalysisException { return new SimpleHeadersClusterizer(); } /** * The method creates an instance of a content header extractor. * * @param model svm model file * @param range svm range file * @return content header extractor * @throws AnalysisException AnalysisException * @throws IOException IOException */ public static ContentHeadersExtractor getContentHeaderExtractor(InputStream model, InputStream range) throws AnalysisException, IOException { BufferedReader modelFileBR = new BufferedReader(new InputStreamReader(model, "UTF-8")); BufferedReader rangeFileBR = new BufferedReader(new InputStreamReader(range, "UTF-8")); ContentHeadersExtractor extractor; try { extractor = new SVMContentHeadersExtractor(modelFileBR, rangeFileBR); } finally { modelFileBR.close(); rangeFileBR.close(); } return extractor; } /** * The method creates an instance of a default content cleaner. * * @return content cleaner */ public static ContentCleaner getContentCleaner() { return new ContentCleaner(); } /** * The method creates an instance of the default citation reference finder. * * @return citation reference finder */ public static ContentCitationPositionFinder getCitationPositionFinder() { return new ContentCitationPositionFinder(); } }
11,844
38.092409
196
java
CERMINE
CERMINE-master/cermine-impl/src/main/java/pl/edu/icm/cermine/PdfRawTextExtractor.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; import java.io.File; import java.io.FileInputStream; import java.io.IOException; import java.io.InputStream; import java.util.Collection; import org.apache.commons.cli.ParseException; import org.apache.commons.io.FileUtils; import pl.edu.icm.cermine.exception.AnalysisException; import pl.edu.icm.cermine.structure.model.BxDocument; /** * Text extractor from PDF files. Extracted text includes * all text strings found in the document in correct reading order. * * @deprecated use {@link ContentExtractor} instead. * * @author Pawel Szostek * @author Dominika Tkaczyk (d.tkaczyk@icm.edu.pl) */ @Deprecated public class PdfRawTextExtractor { private final ContentExtractor extractor; public PdfRawTextExtractor() throws AnalysisException { extractor = new ContentExtractor(); } /** * Extracts content of a PDF as a plain text. * * @param stream input stream * @return pdf's content as plain text * @throws AnalysisException AnalysisException */ public String extractText(InputStream stream) throws AnalysisException { try { extractor.setPDF(stream); return extractor.getRawFullText(); } catch (IOException ex) { throw new AnalysisException(ex); } } /** * Extracts content of a PDF as a plain text. * * @param document document's structure * @return pdf's content as plain text * @throws AnalysisException AnalysisException */ public String extractText(BxDocument document) throws AnalysisException { try { extractor.setBxDocument(document); return extractor.getRawFullText(); } catch (IOException ex) { throw new AnalysisException(ex); } } public ComponentConfiguration getConf() { return extractor.getConf(); } public void setConf(ComponentConfiguration conf) { extractor.setConf(conf); } public static void main(String[] args) throws ParseException, IOException { CommandLineOptionsParser parser = new CommandLineOptionsParser(); String error = parser.parse(args); if (error != null) { System.err.println(error + "\n"); System.err.println( "Usage: PdfRawTextExtractor -path <path> [optional parameters]\n\n" + "Tool for extracting full text in the right reading order from PDF files.\n\n" + "Arguments:\n" + " -path <path> path to a PDF file or directory containing PDF files\n" + " -ext <extension> (optional) the extension of the resulting text file;\n" + " default: \"cermtxt\"; used only if passed path is a directory\n" ); System.exit(1); } String path = parser.getPath(); String extension = parser.getTextExtension(); File file = new File(path); if (file.isFile()) { try { PdfRawTextExtractor extractor = new PdfRawTextExtractor(); InputStream in = new FileInputStream(file); String result = extractor.extractText(in); System.out.println(result); } catch (AnalysisException ex) { ex.printStackTrace(); } } else { Collection<File> files = FileUtils.listFiles(file, new String[]{"pdf"}, true); int i = 0; for (File pdf : files) { File xmlF = new File(pdf.getPath().replaceAll("pdf$", extension)); if (xmlF.exists()) { i++; continue; } long start = System.currentTimeMillis(); float elapsed = 0; System.out.println(pdf.getPath()); try { PdfRawTextExtractor extractor = new PdfRawTextExtractor(); InputStream in = new FileInputStream(pdf); String result = extractor.extractText(in); long end = System.currentTimeMillis(); elapsed = (end - start) / 1000F; if (!xmlF.createNewFile()) { System.out.println("Cannot create new file!"); } FileUtils.writeStringToFile(xmlF, result); } catch (AnalysisException ex) { ex.printStackTrace(); } i++; int percentage = i*100/files.size(); if (elapsed == 0) { elapsed = (System.currentTimeMillis() - start) / 1000F; } System.out.println("Extraction time: " + Math.round(elapsed) + "s"); System.out.println(percentage + "% done (" + i +" out of " + files.size() + ")"); System.out.println(""); } } } }
5,852
34.689024
113
java
CERMINE
CERMINE-master/cermine-impl/src/main/java/pl/edu/icm/cermine/ExtractionUtils.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; import com.google.common.collect.Lists; import com.google.common.collect.Sets; import java.io.InputStream; import java.util.ArrayList; import java.util.EnumSet; import java.util.List; import java.util.Set; import pl.edu.icm.cermine.bibref.model.BibEntry; import pl.edu.icm.cermine.configuration.ExtractionConfigRegister; import pl.edu.icm.cermine.configuration.ExtractionConfigProperty; import pl.edu.icm.cermine.content.citations.ContentStructureCitationPositions; 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.metadata.model.DocumentAffiliation; import pl.edu.icm.cermine.metadata.model.DocumentMetadata; import pl.edu.icm.cermine.structure.model.BxDocument; import pl.edu.icm.cermine.tools.timeout.TimeoutRegister; /** * Extraction utility class * * @author Dominika Tkaczyk (d.tkaczyk@icm.edu.pl) */ public class ExtractionUtils { private static void debug(double start, String msg) { if (ExtractionConfigRegister.get().getBooleanProperty(ExtractionConfigProperty.DEBUG_PRINT_TIME)) { double elapsed = (System.currentTimeMillis() - start) / 1000.; System.out.println(msg + ": " + elapsed); } } //1.1 Character extraction public static BxDocument extractCharacters(ComponentConfiguration conf, InputStream stream) throws AnalysisException { long start = System.currentTimeMillis(); BxDocument doc = conf.getCharacterExtractor().extractCharacters(stream); debug(start, "1.1 Character extraction"); return doc; } //1.2 Page segmentation public static BxDocument segmentPages(ComponentConfiguration conf, BxDocument doc) throws AnalysisException { long start = System.currentTimeMillis(); TimeoutRegister.get().check(); doc = conf.getDocumentSegmenter().segmentDocument(doc); debug(start, "1.2 Page segmentation"); return doc; } //1.3 Reading order resolving public static BxDocument resolveReadingOrder(ComponentConfiguration conf, BxDocument doc) throws AnalysisException { long start = System.currentTimeMillis(); doc = conf.getReadingOrderResolver().resolve(doc); debug(start, "1.3 Reading order resolving"); return doc; } //1.4 Initial classification public static BxDocument classifyInitially(ComponentConfiguration conf, BxDocument doc) throws AnalysisException { long start = System.currentTimeMillis(); doc = conf.getInitialClassifier().classifyZones(doc); debug(start, "1.4 Initial classification"); return doc; } //2.1 Metadata classification public static BxDocument classifyMetadata(ComponentConfiguration conf, BxDocument doc) throws AnalysisException { long start = System.currentTimeMillis(); doc = conf.getMetadataClassifier().classifyZones(doc); debug(start, "2.1 Metadata classification"); return doc; } //2.2 Metadata cleaning public static DocumentMetadata cleanMetadata(ComponentConfiguration conf, BxDocument doc) throws AnalysisException { long start = System.currentTimeMillis(); DocumentMetadata metadata = conf.getMetadataExtractor().extractMetadata(doc); debug(start, "2.2 Metadata cleaning"); return metadata; } //2.3 Affiliation parsing public static DocumentMetadata parseAffiliations(ComponentConfiguration conf, DocumentMetadata metadata) throws AnalysisException { long start = System.currentTimeMillis(); for (DocumentAffiliation aff : metadata.getAffiliations()) { conf.getAffiliationParser().parse(aff); } debug(start, "2.3 Affiliation parsing"); return metadata; } //3.1 Reference extraction public static List<String> extractRefStrings(ComponentConfiguration conf, BxDocument doc) throws AnalysisException { long start = System.currentTimeMillis(); String[] refs = conf.getBibRefExtractor().extractBibReferences(doc); List<String> references = Lists.newArrayList(refs); debug(start, "3.1 Reference extraction"); return references; } //3.2 Reference parsing public static List<BibEntry> parseReferences(ComponentConfiguration conf, List<String> refs) throws AnalysisException { long start = System.currentTimeMillis(); List<BibEntry> parsedRefs = new ArrayList<BibEntry>(); for (String ref : refs) { parsedRefs.add(conf.getBibRefParser().parseBibReference(ref)); } debug(start, "3.2 Reference parsing"); return parsedRefs; } //4.1 Content filtering public static BxDocument filterContent(ComponentConfiguration conf, BxDocument doc) throws AnalysisException { long start = System.currentTimeMillis(); doc = conf.getContentFilter().filter(doc); debug(start, "4.1 Content filtering"); return doc; } //4.2 Headers extraction public static BxContentStructure extractHeaders(ComponentConfiguration conf, BxDocument doc) throws AnalysisException { long start = System.currentTimeMillis(); BxContentStructure contentStructure = conf.getContentHeaderExtractor().extractHeaders(doc); debug(start, "4.2 Headers extraction"); return contentStructure; } //4.3 Headers clustering public static BxContentStructure clusterHeaders(ComponentConfiguration conf, BxContentStructure contentStructure) throws AnalysisException { long start = System.currentTimeMillis(); conf.getContentHeaderClusterizer().clusterHeaders(contentStructure); debug(start, "4.3 Headers clustering"); return contentStructure; } //4.4 Content cleaner public static ContentStructure cleanStructure(ComponentConfiguration conf, BxContentStructure contentStructure) throws AnalysisException { try { long start = System.currentTimeMillis(); conf.getContentCleaner().cleanupContent(contentStructure); BxContentToDocContentConverter converter = new BxContentToDocContentConverter(); ContentStructure structure = converter.convert(contentStructure); debug(start, "4.4 Content cleaning"); return structure; } catch (TransformationException ex) { throw new AnalysisException(ex); } } //4.5 Citation positions finding public static ContentStructureCitationPositions findCitationPositions(ComponentConfiguration conf, ContentStructure struct, List<BibEntry> citations) { long start = System.currentTimeMillis(); ContentStructureCitationPositions positions = conf.getCitationPositionFinder().findReferences(struct, citations); debug(start, "4.5 Citation positions finding"); return positions; } public enum Step { CHARACTER_EXTRACTION (null), PAGE_SEGMENTATION (setOf(CHARACTER_EXTRACTION)), READING_ORDER (setOf(PAGE_SEGMENTATION)), INITIAL_CLASSIFICATION (setOf(READING_ORDER)), METADATA_CLASSIFICATION (setOf(INITIAL_CLASSIFICATION)), METADATA_CLEANING (setOf(METADATA_CLASSIFICATION)), AFFILIATION_PARSING (setOf(METADATA_CLEANING)), REFERENCE_EXTRACTION (setOf(INITIAL_CLASSIFICATION)), REFERENCE_PARSING (setOf(REFERENCE_EXTRACTION)), CONTENT_FILTERING (setOf(INITIAL_CLASSIFICATION)), HEADER_DETECTION (setOf(CONTENT_FILTERING)), TOC_EXTRACTION (setOf(HEADER_DETECTION)), CONTENT_CLEANING (setOf(TOC_EXTRACTION)), CITPOS_DETECTION (setOf(CONTENT_CLEANING, REFERENCE_PARSING)); private Set<Step> prerequisites; Step(Set<Step> prerequisites) { this.prerequisites = prerequisites; } public Set<Step> getPrerequisites() { return prerequisites; } private static Set<Step> setOf(Step... steps) { return Sets.newHashSet(steps); } static { for (Step s : values()) { if (s.prerequisites == null) { s.prerequisites = EnumSet.noneOf(Step.class); } else { s.prerequisites = EnumSet.copyOf(s.prerequisites); } } } } }
9,774
37.789683
121
java
CERMINE
CERMINE-master/cermine-impl/src/main/java/pl/edu/icm/cermine/InternalContentExtractor.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; import com.google.common.collect.Lists; import java.io.IOException; import java.io.InputStream; import java.util.List; import org.jdom.Element; import java.util.ArrayList; import java.util.EnumSet; import java.util.Set; import org.jdom.Namespace; import pl.edu.icm.cermine.ExtractionUtils.Step; import pl.edu.icm.cermine.bibref.model.BibEntry; import pl.edu.icm.cermine.bibref.transformers.BibEntryToNLMConverter; import pl.edu.icm.cermine.content.RawTextWithLabelsExtractor; import pl.edu.icm.cermine.content.citations.ContentStructureCitationPositions; import pl.edu.icm.cermine.content.cleaning.ContentCleaner; import pl.edu.icm.cermine.content.model.BxContentStructure; import pl.edu.icm.cermine.content.model.ContentStructure; import pl.edu.icm.cermine.content.transformers.DocContentStructToNLMElementConverter; import pl.edu.icm.cermine.exception.AnalysisException; import pl.edu.icm.cermine.exception.TransformationException; import pl.edu.icm.cermine.metadata.model.DocumentMetadata; import pl.edu.icm.cermine.metadata.transformers.MetadataToNLMConverter; import pl.edu.icm.cermine.structure.model.BxDocument; import pl.edu.icm.cermine.structure.model.BxImage; import pl.edu.icm.cermine.structure.model.BxZone; import pl.edu.icm.cermine.structure.model.BxZoneLabel; import pl.edu.icm.cermine.structure.tools.BxModelUtils; import pl.edu.icm.cermine.tools.transformers.ModelToModelConverter; /** * Content extractor from PDF files. * The extractor stores the results of the extraction in various formats. * The extraction process is performed only if the requested results * is not available yet. * * This class is intended to be used internally by the library. * * @author Dominika Tkaczyk (d.tkaczyk@icm.edu.pl) */ public class InternalContentExtractor { private ComponentConfiguration conf; /** input PDF file */ private InputStream pdfFile; /** document's geometric structure */ private BxDocument bxDocument; /** document's metadata */ private DocumentMetadata metadata; /** document's list of references */ private List<BibEntry> references; /** body structure */ private ContentStructure body; private List<String> referenceStrings; private BxContentStructure bxBody; private ContentStructureCitationPositions citationPositions; private final Set<Step> stepsDone; /** * Creates the object with provided configuration. * * @throws AnalysisException thrown when there was an error while initializing object */ public InternalContentExtractor() throws AnalysisException { conf = new ComponentConfiguration(); stepsDone = EnumSet.noneOf(Step.class); } /** * Stores the input PDF stream. * * @param pdfFile PDF stream * @throws IOException IOException */ public void setPDF(InputStream pdfFile) throws IOException { reset(); this.pdfFile = pdfFile; } /** * Sets the input bx document. * * @param bxDocument geometric structure * @throws IOException IOException */ public void setBxDocument(BxDocument bxDocument) throws IOException { reset(); this.bxDocument = bxDocument; stepsDone.add(Step.CHARACTER_EXTRACTION); stepsDone.add(Step.PAGE_SEGMENTATION); } /** * Extracts geometric structure. * * @return geometric structure * @throws AnalysisException AnalysisException */ public BxDocument getBxDocument() throws AnalysisException { doWork(Step.INITIAL_CLASSIFICATION); return BxModelUtils.deepClone(bxDocument); } /** * Extracts geometric structure with general labels. * * @return geometric structure * @throws AnalysisException AnalysisException */ public BxDocument getBxDocumentWithGeneralLabels() throws AnalysisException { doWork(Step.INITIAL_CLASSIFICATION); BxDocument doc = BxModelUtils.deepClone(bxDocument); for (BxZone zone : doc.asZones()) { zone.setLabel(zone.getLabel().getGeneralLabel()); } return doc; } /** * Extracts geometric structure with specific labels. * * @return geometric structure * @throws AnalysisException AnalysisException */ public BxDocument getBxDocumentWithSpecificLabels() throws AnalysisException { doWork(Step.METADATA_CLASSIFICATION); doWork(Step.CONTENT_FILTERING); BxDocument doc = BxModelUtils.deepClone(bxDocument); for (BxZone zone : doc.asZones()) { if (BxZoneLabel.GEN_REFERENCES.equals(zone.getLabel())) { zone.setLabel(BxZoneLabel.REFERENCES); } if (BxZoneLabel.GEN_OTHER.equals(zone.getLabel())) { zone.setLabel(BxZoneLabel.OTH_UNKNOWN); } } return doc; } public List<BxImage> getImages(String imagesPrefix) throws AnalysisException { doWork(Step.CHARACTER_EXTRACTION); List<BxImage> images = Lists.newArrayList(bxDocument.asImages()); for (BxImage image : images) { image.setPrefix(imagesPrefix); } return images; } /** * Extracts the metadata. * * @return the metadata * @throws AnalysisException AnalysisException */ public DocumentMetadata getMetadata() throws AnalysisException { doWork(Step.AFFILIATION_PARSING); return metadata; } /** * Extracts the metadata in NLM format. * * @return the metadata in NLM format * @throws AnalysisException AnalysisException */ public Element getMetadataAsNLM() throws AnalysisException { try { doWork(Step.AFFILIATION_PARSING); MetadataToNLMConverter converter = new MetadataToNLMConverter(); return converter.convert(metadata); } catch (TransformationException ex) { throw new AnalysisException(ex); } } /** * Extracts the references. * * @return the list of references * @throws AnalysisException AnalysisException */ public List<BibEntry> getReferences() throws AnalysisException { doWork(Step.REFERENCE_PARSING); return references; } /** * Extracts the references in NLM format. * * @return the list of references * @throws AnalysisException AnalysisException */ public List<Element> getReferencesAsNLM() throws AnalysisException { doWork(Step.REFERENCE_PARSING); List<Element> refs = new ArrayList<Element>(); BibEntryToNLMConverter converter = new BibEntryToNLMConverter(); for (BibEntry ref : references) { try { refs.add(converter.convert(ref)); } catch (TransformationException ex) { throw new AnalysisException(ex); } } return refs; } /** * Extracts raw text. * * @return raw text * @throws AnalysisException AnalysisException */ public String getRawFullText() throws AnalysisException { doWork(Step.READING_ORDER); return ContentCleaner.cleanAll(bxDocument.toText()); } /** * Extracts labelled raw text. * * @return labelled raw text * @throws AnalysisException AnalysisException */ public Element getLabelledFullText() throws AnalysisException { doWork(Step.METADATA_CLASSIFICATION); doWork(Step.TOC_EXTRACTION); RawTextWithLabelsExtractor textExtractor = new RawTextWithLabelsExtractor(); return textExtractor.extractRawTextWithLabels(bxDocument, bxBody); } /** * Extracts structured full text. * * @return full text model * @throws AnalysisException AnalysisException */ public ContentStructure getBody() throws AnalysisException { doWork(Step.CONTENT_CLEANING); return body; } /** * Extracts structured full text. * * @param imagesPrefix images prefix * @return full text in NLM format * @throws AnalysisException AnalysisException */ public Element getBodyAsNLM(String imagesPrefix) throws AnalysisException { try { doWork(Step.CITPOS_DETECTION); ModelToModelConverter<ContentStructure, Element> converter = new DocContentStructToNLMElementConverter(); if (imagesPrefix == null) { return converter.convert(body, citationPositions); } return converter.convert(body, citationPositions, getImages(imagesPrefix)); } catch (TransformationException ex) { throw new AnalysisException(ex); } } /** * Extracts full content in NLM format. * * @param imagesPrefix images prefix * @return full content in NLM format * @throws AnalysisException AnalysisException */ public Element getContentAsNLM(String imagesPrefix) throws AnalysisException { doWork(Step.AFFILIATION_PARSING); doWork(Step.REFERENCE_PARSING); doWork(Step.CITPOS_DETECTION); Element nlmMetadata = getMetadataAsNLM(); List<Element> nlmReferences = getReferencesAsNLM(); Element nlmFullText = getBodyAsNLM(imagesPrefix); Element nlmContent = new Element("article"); for (Object ns : nlmFullText.getAdditionalNamespaces()) { if (ns instanceof Namespace) { nlmContent.addNamespaceDeclaration((Namespace)ns); } } Element meta = (Element) nlmMetadata.getChild("front").clone(); nlmContent.addContent(meta); nlmContent.addContent(nlmFullText); Element back = new Element("back"); Element refList = new Element("ref-list"); for (int i = 0; i < nlmReferences.size(); i++) { Element ref = nlmReferences.get(i); Element r = new Element("ref"); r.setAttribute("id", "ref" + String.valueOf(i+1)); r.addContent(ref); refList.addContent(r); } back.addContent(refList); nlmContent.addContent(back); return nlmContent; } private void doWork(Step step) throws AnalysisException { if (step == null || stepsDone.contains(step)) { return; } for (Step ps : step.getPrerequisites()) { doWork(ps); } switch (step) { case CHARACTER_EXTRACTION: if (pdfFile == null) { throw new AnalysisException("No PDF document uploaded!"); } bxDocument = ExtractionUtils.extractCharacters(conf, pdfFile); break; case PAGE_SEGMENTATION: bxDocument = ExtractionUtils.segmentPages(conf, bxDocument); break; case READING_ORDER: bxDocument = ExtractionUtils.resolveReadingOrder(conf, bxDocument); break; case INITIAL_CLASSIFICATION: bxDocument = ExtractionUtils.classifyInitially(conf, bxDocument); break; case METADATA_CLASSIFICATION: bxDocument = ExtractionUtils.classifyMetadata(conf, bxDocument); break; case METADATA_CLEANING: metadata = ExtractionUtils.cleanMetadata(conf, bxDocument); break; case AFFILIATION_PARSING: metadata = ExtractionUtils.parseAffiliations(conf, metadata); break; case REFERENCE_EXTRACTION: referenceStrings = ExtractionUtils.extractRefStrings(conf, bxDocument); break; case REFERENCE_PARSING: references = ExtractionUtils.parseReferences(conf, referenceStrings); break; case CONTENT_FILTERING: bxDocument = ExtractionUtils.filterContent(conf, bxDocument); break; case HEADER_DETECTION: bxBody = ExtractionUtils.extractHeaders(conf, bxDocument); break; case TOC_EXTRACTION: bxBody = ExtractionUtils.clusterHeaders(conf, bxBody); break; case CONTENT_CLEANING: body = ExtractionUtils.cleanStructure(conf, bxBody); break; case CITPOS_DETECTION: citationPositions = ExtractionUtils.findCitationPositions(conf, body, references); break; default: break; } stepsDone.add(step); } /** * Resets the extraction results. * * @throws IOException IOException */ public void reset() throws IOException { referenceStrings = null; bxBody = null; citationPositions = null; bxDocument = null; metadata = null; references = null; body = null; if (pdfFile != null) { pdfFile.close(); } pdfFile = null; stepsDone.clear(); } public ComponentConfiguration getConf() { return conf; } public void setConf(ComponentConfiguration conf) { this.conf = conf; } }
14,210
32.675355
98
java
CERMINE
CERMINE-master/cermine-impl/src/main/java/pl/edu/icm/cermine/PdfRawTextWithLabelsExtractor.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; import java.io.File; import java.io.FileInputStream; import java.io.IOException; import java.io.InputStream; import java.util.Collection; import org.apache.commons.cli.ParseException; import org.apache.commons.io.FileUtils; import org.jdom.Element; import org.jdom.output.Format; import org.jdom.output.XMLOutputter; import pl.edu.icm.cermine.configuration.ExtractionConfigRegister; import pl.edu.icm.cermine.configuration.ExtractionConfigBuilder; import pl.edu.icm.cermine.exception.AnalysisException; import pl.edu.icm.cermine.structure.model.BxDocument; /** * Text extractor from PDF files. Extracted text includes * all text strings found in the document in correct reading order * as well as labels for text fragments. * * @deprecated use {@link ContentExtractor} instead. * * @author Dominika Tkaczyk (d.tkaczyk@icm.edu.pl) */ @Deprecated public class PdfRawTextWithLabelsExtractor { private final ContentExtractor extractor; public PdfRawTextWithLabelsExtractor() throws AnalysisException { extractor = new ContentExtractor(); } /** * Extracts content of a PDF with labels. * * @param stream input stream * @return pdf's content as plain text * @throws AnalysisException AnalysisException */ public Element extractRawText(InputStream stream) throws AnalysisException { try { extractor.setPDF(stream); return extractor.getLabelledFullText(); } catch (IOException ex) { throw new AnalysisException(ex); } } /** * Extracts content of a PDF with labels. * * @param document document's structure * @return pdf's content as plain text * @throws AnalysisException AnalysisException */ public Element extractRawText(BxDocument document) throws AnalysisException { try { extractor.setBxDocument(document); return extractor.getLabelledFullText(); } catch (IOException ex) { throw new AnalysisException(ex); } } public ComponentConfiguration getConf() { return extractor.getConf(); } public void setConf(ComponentConfiguration conf) { extractor.setConf(conf); } public static void main(String[] args) throws ParseException, IOException { CommandLineOptionsParser parser = new CommandLineOptionsParser(); String error = parser.parse(args); if (error != null) { System.err.println(error + "\n"); System.err.println( "Usage: PdfRawTextWithLabelsExtractor -path <path> [optional parameters]\n\n" + "Tool for extracting labelled full text in the right reading order from PDF files.\n\n" + "Arguments:\n" + " -path <path> path to a PDF file or directory containing PDF files\n" + " -ext <extension> (optional) the extension of the resulting text file;\n" + " default: \"cermtxt\"; used only if passed path is a directory\n" + " -configuration <path> (optional) path to configuration properties file\n" + " see https://github.com/CeON/CERMINE\n" + " for description of available configuration properties\n" ); System.exit(1); } String path = parser.getPath(); String extension = parser.getTextExtension(); ExtractionConfigBuilder builder = new ExtractionConfigBuilder(); if (parser.getConfigurationPath() != null) { builder.addConfiguration(parser.getConfigurationPath()); } ExtractionConfigRegister.set(builder.buildConfiguration()); File file = new File(path); if (file.isFile()) { try { PdfRawTextWithLabelsExtractor extractor = new PdfRawTextWithLabelsExtractor(); InputStream in = new FileInputStream(file); Element result = extractor.extractRawText(in); XMLOutputter outputter = new XMLOutputter(Format.getPrettyFormat()); System.out.println(outputter.outputString(result)); } catch (AnalysisException ex) { ex.printStackTrace(); } } else { Collection<File> files = FileUtils.listFiles(file, new String[]{"pdf"}, true); int i = 0; for (File pdf : files) { File xmlF = new File(pdf.getPath().replaceAll("pdf$", extension)); if (xmlF.exists()) { i++; continue; } long start = System.currentTimeMillis(); float elapsed = 0; System.out.println(pdf.getPath()); try { PdfRawTextWithLabelsExtractor extractor = new PdfRawTextWithLabelsExtractor(); InputStream in = new FileInputStream(pdf); Element result = extractor.extractRawText(in); long end = System.currentTimeMillis(); elapsed = (end - start) / 1000F; XMLOutputter outputter = new XMLOutputter(Format.getPrettyFormat()); if (!xmlF.createNewFile()) { System.out.println("Cannot create new file!"); } FileUtils.writeStringToFile(xmlF, outputter.outputString(result)); } catch (AnalysisException ex) { ex.printStackTrace(); } i++; int percentage = i*100/files.size(); if (elapsed == 0) { elapsed = (System.currentTimeMillis() - start) / 1000F; } System.out.println("Extraction time: " + Math.round(elapsed) + "s"); System.out.println(percentage + "% done (" + i +" out of " + files.size() + ")"); System.out.println(""); } } } }
7,026
37.823204
113
java
CERMINE
CERMINE-master/cermine-impl/src/main/java/pl/edu/icm/cermine/tools/DocumentsExtractor.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.tools; import java.util.List; import pl.edu.icm.cermine.exception.TransformationException; import pl.edu.icm.cermine.structure.model.BxDocument; /** * Documents extractor interface. * * @author Pawel Szostek */ public interface DocumentsExtractor { /** * Extracts documents. * * @return a list of extracted documents * @throws TransformationException TransformationException */ List<BxDocument> getDocuments() throws TransformationException; }
1,248
30.225
78
java
CERMINE
CERMINE-master/cermine-impl/src/main/java/pl/edu/icm/cermine/tools/XMLTools.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.tools; import org.jdom.Element; import org.jdom.Namespace; import org.jdom.Text; import org.jdom.Verifier; /** * @author Dominika Tkaczyk (d.tkaczyk@icm.edu.pl) */ public class XMLTools { public static final Namespace NS_XLINK = Namespace.getNamespace("xlink", "http://www.w3.org/1999/xlink"); public static String getTextContent(Element element) { StringBuilder ret = new StringBuilder(); if (element == null) { return ""; } for (Object cont: element.getContent()) { if (cont instanceof Text) { ret.append(((Text) cont).getText()); ret.append(" "); } else if (cont instanceof Element) { ret.append(getTextContent((Element) cont)); ret.append(" "); } } return ret.toString().replaceAll("\\s+", " ").trim(); } public static String removeInvalidXMLChars(String text) { StringBuilder sb = new StringBuilder(); for (int i = 0; i < text.length(); i++) { char ch = text.charAt(i); if (Verifier.isXMLCharacter(ch)) { sb.append(ch); } } return sb.toString(); } }
2,011
31.451613
78
java
CERMINE
CERMINE-master/cermine-impl/src/main/java/pl/edu/icm/cermine/tools/ResourceUtils.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.tools; import java.io.FileInputStream; import java.io.IOException; import java.io.InputStream; import org.apache.commons.lang.StringUtils; /** * @author madryk */ public class ResourceUtils { private static final String CLASSPATH_RESOURCE_PREFIX = "classpath:"; public static InputStream openResourceStream(String resourcePath) throws IOException { if (StringUtils.startsWith(resourcePath, CLASSPATH_RESOURCE_PREFIX)) { InputStream inputStream = ResourceUtils.class.getResourceAsStream(resourcePath.substring(CLASSPATH_RESOURCE_PREFIX.length())); return inputStream; } return new FileInputStream(resourcePath); } }
1,463
33.046512
138
java
CERMINE
CERMINE-master/cermine-impl/src/main/java/pl/edu/icm/cermine/tools/ZipExtractor.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.tools; import java.io.File; import java.io.IOException; import java.io.InputStreamReader; import java.net.URI; import java.net.URISyntaxException; import java.net.URL; import java.util.ArrayList; import java.util.Enumeration; import java.util.List; import java.util.zip.ZipEntry; import java.util.zip.ZipFile; import pl.edu.icm.cermine.exception.TransformationException; import pl.edu.icm.cermine.structure.model.BxDocument; import pl.edu.icm.cermine.structure.model.BxPage; import pl.edu.icm.cermine.structure.transformers.TrueVizToBxDocumentReader; /** * @author Pawel Szostek */ public class ZipExtractor implements DocumentsExtractor { protected ZipFile zipFile; public ZipExtractor(String path) throws IOException, URISyntaxException { URL url = path.getClass().getResource(path); URI uri = url.toURI(); File file = new File(uri); this.zipFile = new ZipFile(file); } public ZipExtractor(File file) throws IOException { this.zipFile = new ZipFile(file); } public ZipExtractor(ZipFile zipFile) { this.zipFile = zipFile; } @Override public List<BxDocument> getDocuments() throws TransformationException { List<BxDocument> documents = new ArrayList<BxDocument>(); TrueVizToBxDocumentReader tvReader = new TrueVizToBxDocumentReader(); Enumeration<? extends ZipEntry> entries = zipFile.entries(); while (entries.hasMoreElements()) { ZipEntry zipEntry = (ZipEntry) entries.nextElement(); if (zipEntry.getName().endsWith("xml")) { try { List<BxPage> pages = tvReader.read(new InputStreamReader(zipFile.getInputStream(zipEntry), "UTF-8")); BxDocument newDoc = new BxDocument(); for (BxPage page : pages) { page.setParent(newDoc); } newDoc.setFilename(zipEntry.getName()); newDoc.setPages(pages); documents.add(newDoc); } catch (IOException ex) { throw new TransformationException("Cannot read file!", ex); } } } return documents; } }
3,007
34.809524
121
java
CERMINE
CERMINE-master/cermine-impl/src/main/java/pl/edu/icm/cermine/tools/Pair.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.tools; /** * @author Pawel Szostek * @param <S> first element * @param <T> second element */ public class Pair<S, T> { private S first; private T second; public Pair(S first, T second) { this.first = first; this.second = second; } @Override public int hashCode() { final int prime = 31; int result = 1; result = prime * result + ((first == null) ? 0 : first.hashCode()); result = prime * result + ((second == null) ? 0 : second.hashCode()); return result; } @Override public boolean equals(Object obj) { if (this == obj) { return true; } if (obj == null) { return false; } if (!(obj instanceof Pair)) { return false; } Pair other = (Pair) obj; if (first == null) { if (other.first != null) { return false; } } else if (!first.equals(other.first)) { return false; } if (second == null) { if (other.second != null) { return false; } } else if (!second.equals(other.second)) { return false; } return true; } public S getFirst() { return first; } public void setFirst(S first) { this.first = first; } public T getSecond() { return second; } public void setSecond(T second) { this.second = second; } }
2,286
24.411111
78
java
CERMINE
CERMINE-master/cermine-impl/src/main/java/pl/edu/icm/cermine/tools/PrefixTree.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.tools; import com.google.common.collect.Lists; import java.util.ArrayList; import java.util.Arrays; import java.util.List; import java.util.Set; /** * * @author Dominika Tkaczyk (d.tkaczyk@icm.edu.pl) */ public class PrefixTree { public static final String START_TERM = "<START>"; private final String term; List<PrefixTree> subTrees = new ArrayList<PrefixTree>(); public PrefixTree(String term) { this.term = term; } public void build(Set<String> sentences) { for (String sentence : sentences) { String[] terms = sentence.split(" "); String first = terms[0]; PrefixTree subTree = null; for (PrefixTree pt : subTrees) { if (pt.term.equals(first)) { subTree = pt; } } if (subTree == null) { subTree = new PrefixTree(first); subTrees.add(subTree); } List<String> addTerms = new ArrayList<String>(Arrays.asList(terms)); addTerms.remove(0); subTree.add(addTerms); } } public void add(List<String> terms) { if (terms.isEmpty()) { for (PrefixTree pt : subTrees) { if (pt.term == null) { return; } } subTrees.add(new PrefixTree(null)); return; } String first = terms.get(0); PrefixTree subTree = null; for (PrefixTree pt : subTrees) { if (first.equals(pt.term)) { subTree = pt; } } if (subTree == null) { subTree = new PrefixTree(first); subTrees.add(subTree); } terms.remove(0); subTree.add(terms); } public int match(List<String> terms) { if (terms.isEmpty()) { return term == null ? 0 : -1; } if (term == null) { return 0; } if (term.equals(START_TERM)) { int best = -1; for (PrefixTree t : subTrees) { int m = t.match(terms); if (m > best) { best = m; } } return best; } if (term.equals(terms.get(0))) { int best = -1; for (PrefixTree t : subTrees) { int m = t.match(Lists.newArrayList(terms.subList(1, terms.size()))); if (m > -1 && m+1 > best) { best = m+1; } } return best; } return -1; } public void print() { print(""); } private void print(String pref) { System.out.println(pref + "term: " + term); for (PrefixTree t : subTrees) { t.print(pref + " "); } } }
3,675
27.71875
84
java
CERMINE
CERMINE-master/cermine-impl/src/main/java/pl/edu/icm/cermine/tools/RecursiveDirExtractor.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.tools; import java.io.*; import java.util.ArrayList; import java.util.List; import org.apache.commons.io.FileUtils; import pl.edu.icm.cermine.exception.TransformationException; import pl.edu.icm.cermine.structure.model.BxDocument; import pl.edu.icm.cermine.structure.model.BxPage; import pl.edu.icm.cermine.structure.transformers.TrueVizToBxDocumentReader; /** * @author Pawel Szostek */ public class RecursiveDirExtractor implements DocumentsExtractor { protected File directory; public RecursiveDirExtractor(String path) { directory = new File(path); if (!directory.exists() || !directory.isDirectory()) { throw new RuntimeException("Source directory for documents doesn't exist: " + path); } } public RecursiveDirExtractor(File directory) { this.directory = directory; } @Override public List<BxDocument> getDocuments() throws TransformationException { TrueVizToBxDocumentReader tvReader = new TrueVizToBxDocumentReader(); List<BxDocument> documents = new ArrayList<BxDocument>(); for (File file : FileUtils.listFiles(directory, new String[]{"xml"}, true)) { InputStream is = null; try { is = new FileInputStream(file); List<BxPage> pages = tvReader.read(new InputStreamReader(is, "UTF-8")); BxDocument doc = new BxDocument(); doc.setFilename(file.getName()); doc.setPages(pages); documents.add(doc); } catch (FileNotFoundException ex) { throw new TransformationException(ex); } catch (UnsupportedEncodingException ex) { throw new TransformationException(ex); } finally { if (is != null) { try { is.close(); } catch (IOException ex) { throw new TransformationException("Cannot close stream!", ex); } } } } return documents; } }
2,862
34.345679
96
java
CERMINE
CERMINE-master/cermine-impl/src/main/java/pl/edu/icm/cermine/tools/Utils.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.tools; /** * General purpose utility class. * * @author Dominika Tkaczyk (d.tkaczyk@icm.edu.pl) */ public class Utils { /** * Compares two doubles according to a given precision. * * @param d1 double * @param d2 double * @param precision precision * @return 0 if arguments are equal, 1 if the first argument is greater, -1 otherwise */ public static int compareDouble(double d1, double d2, double precision) { if (Double.isNaN(d1) || Double.isNaN(d2)) { return Double.compare(d1, d2); } if (precision == 0) { precision = 1; } long i1 = Math.round(d1 / precision); long i2 = Math.round(d2 / precision); return Long.valueOf(i1).compareTo(i2); } }
1,548
30.612245
89
java
CERMINE
CERMINE-master/cermine-impl/src/main/java/pl/edu/icm/cermine/tools/DirExtractor.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.tools; import java.io.*; import java.util.ArrayList; import java.util.List; import pl.edu.icm.cermine.exception.TransformationException; import pl.edu.icm.cermine.structure.model.BxDocument; import pl.edu.icm.cermine.structure.model.BxPage; import pl.edu.icm.cermine.structure.transformers.TrueVizToBxDocumentReader; /** * @author Pawel Szostek */ public class DirExtractor implements DocumentsExtractor { protected File directory; public DirExtractor(String path) { directory = new File(path); if (!directory.exists() || !directory.isDirectory()) { throw new RuntimeException("Source directory for documents doesn't exist: " + path); } } public DirExtractor(File directory) { this.directory = directory; } @Override public List<BxDocument> getDocuments() throws TransformationException { String dirPath = directory.getPath(); TrueVizToBxDocumentReader tvReader = new TrueVizToBxDocumentReader(); List<BxDocument> documents = new ArrayList<BxDocument>(); if (!dirPath.endsWith(File.separator)) { dirPath += File.separator; } for (String filename : directory.list()) { if (!new File(dirPath + filename).isFile()) { continue; } if (filename.endsWith("xml")) { InputStream is = null; try { is = new FileInputStream(dirPath + filename); List<BxPage> pages = tvReader.read(new InputStreamReader(is, "UTF-8")); BxDocument newDoc = new BxDocument(); for (BxPage page : pages) { page.setParent(newDoc); } newDoc.setFilename(filename); newDoc.setPages(pages); documents.add(newDoc); } catch (IllegalStateException ex) { System.err.println(ex.getMessage()); System.err.println(dirPath + filename); throw ex; } catch (FileNotFoundException ex) { throw new TransformationException("File not found!", ex); } catch (UnsupportedEncodingException ex) { throw new TransformationException("Unsupported encoding!", ex); } finally { if (is != null) { try { is.close(); } catch (IOException ex) { throw new TransformationException("Cannot close stream!", ex); } } } } } return documents; } }
3,523
36.892473
96
java
CERMINE
CERMINE-master/cermine-impl/src/main/java/pl/edu/icm/cermine/tools/BxDocUtils.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.tools; import com.google.common.collect.Lists; import java.io.*; import java.util.Iterator; import java.util.List; import java.util.NoSuchElementException; import org.apache.commons.io.FileUtils; import pl.edu.icm.cermine.exception.TransformationException; import pl.edu.icm.cermine.structure.model.BxDocument; import pl.edu.icm.cermine.structure.model.BxPage; import pl.edu.icm.cermine.structure.transformers.TrueVizToBxDocumentReader; /** * @author Pawel Szostek */ public class BxDocUtils { public static List<BxDocument> getDocumentsFromPath(String inputDirPath) throws TransformationException { if (inputDirPath == null) { throw new IllegalArgumentException("Input directory must not be null."); } if (!inputDirPath.endsWith(File.separator)) { inputDirPath += File.separator; } DocumentsExtractor extractor = new DirExtractor(inputDirPath); List<BxDocument> evaluationDocuments; evaluationDocuments = extractor.getDocuments(); return evaluationDocuments; } public static BxDocument getDocument(File file) throws IOException, TransformationException { TrueVizToBxDocumentReader tvReader = new TrueVizToBxDocumentReader(); BxDocument newDoc = new BxDocument(); InputStream is = new FileInputStream(file); try { List<BxPage> pages = tvReader.read(new InputStreamReader(is, "UTF-8")); for (BxPage page : pages) { page.setParent(newDoc); } newDoc.setFilename(file.getName()); newDoc.setPages(pages); return newDoc; } finally { is.close(); } } public static class DocumentsIterator implements Iterable<BxDocument> { private File dir; private int curIdx; private File[] files; public DocumentsIterator(String dirPath) { this(dirPath, "cxml"); } public DocumentsIterator(String dirPath, String extension) { if (!dirPath.endsWith(File.separator)) { dirPath += File.separator; } this.dir = new File(dirPath); this.curIdx = -1; List<File> list = Lists.newArrayList(FileUtils.listFiles(dir, new String[]{extension}, true)); this.files = list.toArray(new File[list.size()]); } @Override public Iterator<BxDocument> iterator() { return new Iterator<BxDocument>() { @Override public boolean hasNext() { return curIdx + 1 < files.length; } @Override public BxDocument next() { ++curIdx; if (curIdx >= files.length) { throw new NoSuchElementException(); } try { return getDocument(files[curIdx]); } catch (IOException e) { return null; } catch (TransformationException e) { return null; } } @Override public void remove() { ++curIdx; } }; } } }
4,100
32.072581
109
java
CERMINE
CERMINE-master/cermine-impl/src/main/java/pl/edu/icm/cermine/tools/ResourcesReader.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.tools; import java.io.BufferedReader; import java.io.IOException; import java.io.InputStream; import java.io.InputStreamReader; import java.util.ArrayList; import java.util.List; import pl.edu.icm.cermine.exception.TransformationException; /** * @author Dominika Tkaczyk (d.tkaczyk@icm.edu.pl) */ public class ResourcesReader { public static List<String> readLinesAsList(String file) throws TransformationException { return readLinesAsList(file, ID_TRANSFORMER); } public static List<String> readLinesAsList(String file, StringTransformer transformer) throws TransformationException { List<String> lines = new ArrayList<String>(); InputStream is = ResourcesReader.class.getResourceAsStream(file); if (is == null) { throw new TransformationException("Resource not found: " + file); } BufferedReader in = null; try { in = new BufferedReader(new InputStreamReader(is, "UTF-8")); String line; while ((line = in.readLine()) != null) { lines.add(transformer.transform(line)); } } catch (IOException ex) { throw new TransformationException(ex); } finally { try { if (in != null) { in.close(); } } catch (IOException ex) { throw new TransformationException(ex); } } return lines; } public interface StringTransformer { String transform(String original); } public static final StringTransformer ID_TRANSFORMER = new StringTransformer() { @Override public String transform(String original) { return original; } }; public static final StringTransformer TRIM_TRANSFORMER = new StringTransformer() { @Override public String transform(String original) { return original.trim(); } }; private ResourcesReader() { } }
2,816
31.37931
92
java
CERMINE
CERMINE-master/cermine-impl/src/main/java/pl/edu/icm/cermine/tools/SmartHashMap.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.tools; import java.util.HashMap; import java.util.List; import java.util.Locale; import pl.edu.icm.cermine.structure.model.BxZoneLabel; /** * @author Pawel Szostek */ public class SmartHashMap extends HashMap<String, BxZoneLabel> { private static final long serialVersionUID = 74383628471L; public SmartHashMap putIf(String string, BxZoneLabel label) { if (string != null && !string.isEmpty()) { string = string.toLowerCase(Locale.ENGLISH); put(string, label); } return this; } public SmartHashMap putIf(List<String> strings, BxZoneLabel label) { for (String string : strings) { putIf(string, label); } return this; } }
1,495
30.166667
78
java
CERMINE
CERMINE-master/cermine-impl/src/main/java/pl/edu/icm/cermine/tools/CumulativeFunc.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.tools; import java.util.*; /** * @author Pawel Szostek */ public class CumulativeFunc { public static Map<Double, Integer> calculate(List<Double> values) { Collections.sort(values); List<Double> uniqueValues = new ArrayList<Double>(new HashSet<Double>(values)); Collections.sort(uniqueValues); Map<Double, Integer> quantities = new HashMap<Double, Integer>(); for (Double value : values) { if (quantities.containsKey(value)) { quantities.put(value, quantities.get(value) + 1); } else { quantities.put(value, 1); } } Map<Double, Integer> cumulated = new HashMap<Double, Integer>(); cumulated.put(values.get(0), quantities.get(values.get(0))); int prevQuantity = 0; if (!uniqueValues.contains(0.0)) { cumulated.put(0.0, 0); } for (Double value : uniqueValues) { int curQuantity = quantities.get(value) + prevQuantity; cumulated.put(value, curQuantity); prevQuantity = curQuantity; } return cumulated; } }
1,908
34.351852
87
java
CERMINE
CERMINE-master/cermine-impl/src/main/java/pl/edu/icm/cermine/tools/DisjointSets.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.tools; import java.util.*; /** * A disjoint-set data structure. * * @author Krzysztof Rusek * @param <E> element type */ public class DisjointSets<E> implements Iterable<Set<E>> { private final Map<E, Entry<E>> map = new HashMap<E, Entry<E>>(); /** * Constructs a new set of singletons. * * @param c elements of singleton sets */ public DisjointSets(Collection<? extends E> c) { for (E element : c) { map.put(element, new Entry<E>(element)); } } /** * Checks if elements are in the same subsets. * * @param e1 element from a subset * @param e2 element from a subset * @return true if elements are in the same subset; false otherwise */ public boolean areTogether(E e1, E e2) { return map.get(e1).findRepresentative() == map.get(e2).findRepresentative(); } /** * Merges subsets which elements e1 and e2 belong to. * * @param e1 element from a subset * @param e2 element from a subset */ public void union(E e1, E e2) { Entry<E> r1 = map.get(e1).findRepresentative(); Entry<E> r2 = map.get(e2).findRepresentative(); if (r1 != r2) { if (r1.size <= r2.size) { r2.mergeWith(r1); } else { r1.mergeWith(r2); } } } @Override public Iterator<Set<E>> iterator() { return new Iterator<Set<E>>() { private final Iterator<Entry<E>> iterator = map.values().iterator(); private Entry<E> nextRepresentative; { findNextRepresentative(); } @Override public boolean hasNext() { return nextRepresentative != null; } @Override public Set<E> next() { if (nextRepresentative == null) { throw new NoSuchElementException(); } Set<E> result = nextRepresentative.asSet(); findNextRepresentative(); return result; } private void findNextRepresentative() { while(iterator.hasNext()) { Entry<E> candidate = iterator.next(); if (candidate.isRepresentative()) { nextRepresentative = candidate; return; } } nextRepresentative = null; } @Override public void remove() { throw new UnsupportedOperationException(); } }; } public static <E extends Enum<E>> DisjointSets<E> singletonsOf(Class<E> elementType) { return new DisjointSets(Arrays.asList(elementType.getEnumConstants())); } private static class Entry<E> { private int size = 1; private final E value; private Entry<E> parent = this; private Entry<E> next = null; private Entry<E> last = this; Entry(E value) { this.value = value; } void mergeWith(Entry<E> otherRepresentative) { size += otherRepresentative.size; last.next = otherRepresentative; last = otherRepresentative.last; otherRepresentative.parent = this; } Entry<E> findRepresentative() { Entry<E> representative = parent; while (representative.parent != representative) { representative = representative.parent; } for (Entry<E> entry = this; entry != representative; ) { Entry<E> nextEntry = entry.parent; entry.parent = representative; entry = nextEntry; } return representative; } boolean isRepresentative() { return parent == this; } Set<E> asSet() { return new AbstractSet<E>() { @Override public Iterator<E> iterator() { return new Iterator<E>() { private Entry<E> nextEntry = findRepresentative(); @Override public boolean hasNext() { return nextEntry != null; } @Override public E next() { if (nextEntry == null) { throw new NoSuchElementException(); } E result = nextEntry.value; nextEntry = nextEntry.next; return result; } @Override public void remove() { throw new UnsupportedOperationException(); } }; } @Override public int size() { return findRepresentative().size; } }; } } }
5,934
29.126904
90
java
CERMINE
CERMINE-master/cermine-impl/src/main/java/pl/edu/icm/cermine/tools/TextUtils.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.tools; import java.text.DateFormatSymbols; import java.util.ArrayList; import java.util.Arrays; import java.util.List; import java.util.Locale; import java.util.regex.Pattern; /** * @author Dominika Tkaczyk (d.tkaczyk@icm.edu.pl) */ public class TextUtils { public static boolean isNumberBetween(String s, int lower, int upper) { try { int n = Integer.parseInt(s); return n >= lower && n < upper; } catch (NumberFormatException e) { return false; } } public static String removeOrphantSpaces(String text) { if (text.length() < 5) { return text; } StringBuilder ret = new StringBuilder(); boolean evenSpaces = true; for (int idx = 0; idx < text.length(); idx += 2) { if (text.charAt(idx) != ' ') { evenSpaces = false; break; } } if (evenSpaces) { for (int idx = 1; idx < text.length(); idx += 2) { ret.append(text.charAt(idx)); } return ret.toString(); } boolean oddSpaces = true; for (int idx = 1; idx < text.length(); idx += 2) { if (text.charAt(idx) != ' ') { oddSpaces = false; break; } } if (oddSpaces) { for (int idx = 0; idx < text.length(); idx += 2) { ret.append(text.charAt(idx)); } return ret.toString(); } return text; } public static String cleanLigatures(String str) { return str.replaceAll("\uFB00", "ff") .replaceAll("\uFB01", "fi") .replaceAll("\uFB02", "fl") .replaceAll("\uFB03", "ffi") .replaceAll("\uFB04", "ffl") .replaceAll("\uFB05", "ft") .replaceAll("\uFB06", "st"); } public static List<String> tokenize(String text) { List<String> roughRet = new ArrayList<String>(Arrays.asList(text.split(" |=|\\(|\\)|\n|,|\\. |&|;|:|\\-|/"))); List<String> ret = new ArrayList<String>(); for (String candidate : roughRet) { if (candidate.length() > 1) { ret.add(candidate.toLowerCase(Locale.ENGLISH)); } } return ret; } public static int tokLen(String text) { return tokenize(text).size(); } public static String joinStrings(List<String> strings) { StringBuilder ret = new StringBuilder(); for (String str : strings) { if (str != null) { ret.append(str).append(" "); } } return ret.toString(); } public static String joinStrings(List<String> strings, char delim) { if (strings.isEmpty()) { return ""; } else if (strings.size() == 1) { return strings.get(0); } else { StringBuilder ret = new StringBuilder(); for (int partIdx = 0; partIdx < strings.size() - 1; ++partIdx) { ret.append(strings.get(partIdx)).append(delim); } ret.append(strings.get(strings.size() - 1)); return ret.toString(); } } public static String joinStrings(String[] strings) { return joinStrings(new ArrayList<String>(Arrays.asList(strings))); } static String getFileCoreName(String path) { String[] parts = path.split("\\."); if (parts.length == 2) { return parts[0]; } else if (parts.length > 1) { StringBuilder ret = new StringBuilder(); ret.append(parts[0]); for (int partIdx = 1; partIdx < parts.length - 1; ++partIdx) { ret.append(".").append(parts[partIdx]); } return ret.toString(); } else { return parts[0]; } } public static List<String> produceDates(List<String> date) { List<String> ret = new ArrayList<String>(); int monthInt = Integer.parseInt(date.get(1)); if (monthInt >= 1 && monthInt <= 12) { DateFormatSymbols dfs = new DateFormatSymbols(Locale.ENGLISH); String[] months = dfs.getMonths(); String month = months[monthInt - 1]; ret.add(joinStrings(new String[]{date.get(0), month, date.get(2)})); ret.add(joinStrings(new String[]{date.get(0), month.substring(0, 3), date.get(2)})); } ret.add(joinStrings(date)); return ret; } public static String getTrueVizPath(String pdfPath) { return getFileCoreName(pdfPath) + ".xml"; } public static String getNLMPath(String pdfPath) { return getFileCoreName(pdfPath) + ".nxml"; } private static final Pattern NOT_WORD_PATTERN = Pattern.compile("[^a-zA-Z]"); private static final Pattern NOT_NUMBER_PATTERN = Pattern.compile("[^0-9]"); private static final Pattern NOT_UPPERCASE_PATTERN = Pattern.compile("[^A-Z]"); private static final Pattern NOT_LOWERCASE_PATTERN = Pattern.compile("[^a-z]"); private static final Pattern NOT_ALPHANUM_PATTERN = Pattern.compile("[^a-zA-Z0-9]"); /** * @param text text * @return whether the text is a single word */ public static boolean isWord(String text) { return !NOT_WORD_PATTERN.matcher(text).find(); } /** * @param text text * @return whether the text is a single number */ public static boolean isNumber(String text) { return !NOT_NUMBER_PATTERN.matcher(text).find(); } /** * @param text text * @return whether the text is a single word with the first letter in upper * case and all the rest in lower case */ public static boolean isOnlyFirstUpperCase(String text) { boolean firstUpperCase = !NOT_UPPERCASE_PATTERN.matcher(text.substring(0, 1)).find(); boolean restLowerCase = !NOT_LOWERCASE_PATTERN.matcher(text.substring(1)).find(); return firstUpperCase && restLowerCase; } /** * @param text text * @return whether the text is a single word with all letters in upper case */ public static boolean isAllUpperCase(String text) { return !NOT_UPPERCASE_PATTERN.matcher(text).find(); } /** * @param text text * @return whether the text is a single word with all letters in upper case */ public static boolean isAllLowerCase(String text) { return !NOT_LOWERCASE_PATTERN.matcher(text).find(); } /** * @param text text * @return whether the word is a commonly used separator ("." "," ";") */ public static boolean isSeparator(String text) { return text.equals(".") || text.equals(",") || text.equals(";"); } /** * @param text text * @return whether the word is not alphanumeric and is not a separator */ public static boolean isNonAlphanumSep(String text) { return NOT_ALPHANUM_PATTERN.matcher(text).find() && !isSeparator(text); } }
7,850
32.408511
118
java
CERMINE
CERMINE-master/cermine-impl/src/main/java/pl/edu/icm/cermine/tools/CountMap.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.tools; import com.google.common.collect.Lists; import java.util.*; import java.util.Map.Entry; /** * @author Dominika Tkaczyk (d.tkaczyk@icm.edu.pl) * @param <T> element type */ public class CountMap<T> { private final Map<T, Integer> map = new HashMap<T, Integer>(); public void add(T object) { if (map.get(object) == null) { map.put(object, 0); } map.put(object, map.get(object) + 1); } public void clear() { map.clear(); } public int getCount(T object) { return (map.get(object) == null) ? 0 : map.get(object); } public int size() { return map.size(); } public T getMaxCountObject() { if (size() == 0) { return null; } List<Map.Entry<T, Integer>> list = Lists.newArrayList(map.entrySet()); list = sortEntries(list); return list.get(0).getKey(); } public List<Map.Entry<T, Integer>> getSortedEntries() { List<Map.Entry<T, Integer>> list = Lists.newArrayList(map.entrySet()); return sortEntries(list); } public List<Map.Entry<T, Integer>> getSortedEntries(int minCount) { List<Map.Entry<T, Integer>> list = new ArrayList<Map.Entry<T, Integer>>(); for (Map.Entry<T, Integer> entry : map.entrySet()) { if (entry.getValue() >= minCount) { list.add(entry); } } return sortEntries(list); } private List<Map.Entry<T, Integer>> sortEntries(List<Map.Entry<T, Integer>> list) { Collections.sort(list, new Comparator<Map.Entry<T, Integer>>() { @Override public int compare(Entry<T, Integer> t, Entry<T, Integer> t1) { return t1.getValue().compareTo(t.getValue()); } }); return list; } }
2,643
28.707865
87
java
CERMINE
CERMINE-master/cermine-impl/src/main/java/pl/edu/icm/cermine/tools/PatternUtils.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.tools; /** * @author Dominika Tkaczyk (d.tkaczyk@icm.edu.pl) */ public class PatternUtils { public static final String DOI_PATTERN = "10\\.\\d{4,9}/\\S*\\w"; }
937
31.344828
78
java
CERMINE
CERMINE-master/cermine-impl/src/main/java/pl/edu/icm/cermine/tools/Histogram.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.tools; import java.util.Collection; import java.util.Iterator; import java.util.NoSuchElementException; /** * Histogram for double values in range [minValue, maxValue]. * * @author Krzysztof Rusek */ public class Histogram implements Iterable<Histogram.Bin> { private static final double EPSILON = 1.0e-6; private final double min; private final double delta; private final double resolution; private double[] frequencies; /** * Constructs a new histogram for values in range [minValue, maxValue] with * given resolution. * * @param minValue - minimum allowed value * @param maxValue - maximum allowed value * @param resolution - histogram's resolution */ public Histogram(double minValue, double maxValue, double resolution) { this.min = minValue - EPSILON; this.delta = maxValue - minValue + 2 * EPSILON; int size = Math.max(1, (int) Math.round((maxValue - minValue) / resolution)); this.resolution = this.delta / size; this.frequencies = new double[size]; } /** * Smooths the histogram using a rectangular smoothing window. * * @param windowLength - smoothing window length */ public void smooth(double windowLength) { int size = (int) Math.round(windowLength / resolution) / 2; double sum = 0.0; for (int i = 0; i <= size; i++) { sum += frequencies[i]; } double[] newFrequencies = new double[frequencies.length]; for (int i = 0; i < size; i++) { newFrequencies[i] = sum / (2 * size + 1); sum += frequencies[i + size + 1]; } for (int i = size; i < frequencies.length - size - 1; i++) { newFrequencies[i] = sum / (2 * size + 1); sum += frequencies[i + size + 1]; sum -= frequencies[i - size]; } for (int i = frequencies.length - size - 1; i < frequencies.length; i++) { newFrequencies[i] = sum / (2 * size + 1); sum -= frequencies[i - size]; } frequencies = newFrequencies; } /** * Circularly smooths the histogram using a rectangular smoothing window. * * @param windowLength - smoothing window length */ public void circularSmooth(double windowLength) { int size = (int) Math.round(windowLength / resolution) / 2; double sum = frequencies[0]; for (int i = 1; i <= size; i++) { sum += frequencies[i] + frequencies[frequencies.length - i]; } double[] newFrequencies = new double[frequencies.length]; for (int i = 0; i < frequencies.length; i++) { newFrequencies[i] = sum / (2 * size + 1); sum += frequencies[i + size + 1 < frequencies.length ? i + size + 1 : i + size + 1 - frequencies.length]; sum -= frequencies[i - size < 0 ? frequencies.length + i - size : i - size]; } frequencies = newFrequencies; } public void kernelSmooth(double[] kernel) { double[] newFrequencies = new double[frequencies.length]; int shift = (kernel.length - 1) / 2; for (int i = 0; i < kernel.length; i++) { int jStart = Math.max(0, i - shift); int jEnd = Math.min(frequencies.length, frequencies.length + i - shift); for (int j = jStart; j < jEnd; j++) { newFrequencies[j - i + shift] += kernel[i] * frequencies[j]; } } frequencies = newFrequencies; } public void circularKernelSmooth(double[] kernel) { double[] newFrequencies = new double[frequencies.length]; int shift = (kernel.length - 1) / 2; for (int i = 0; i < frequencies.length; i++) { for (int d = 0; d < kernel.length; d++) { int j = i + d - shift; if (j < 0) { j += frequencies.length; } else if (j >= frequencies.length) { j -= frequencies.length; } newFrequencies[i] += kernel[d] * frequencies[j]; } } frequencies = newFrequencies; } public double[] createGaussianKernel(double length, double stdDeviation) { int r = (int) Math.round(length / resolution) / 2; stdDeviation /= resolution; int size = 2 * r + 1; double[] kernel = new double[size]; double sum = 0; double b = 2 * stdDeviation * stdDeviation; double a = 1 / Math.sqrt(Math.PI * b); for (int i = 0; i < size; i++) { kernel[i] = a * Math.exp(-(i - r) * (i - r) / b); sum += kernel[i]; } for (int i = 0; i < size; i++) { kernel[i] /= sum; } return kernel; } public void circularGaussianSmooth(double windowLength, double stdDeviation) { circularKernelSmooth(createGaussianKernel(windowLength, stdDeviation)); } public void gaussianSmooth(double windowLength, double stdDeviation) { kernelSmooth(createGaussianKernel(windowLength, stdDeviation)); } /** * Adds single occurrence of given value to the histogram. * * @param value inserted values */ public void add(double value) { frequencies[(int) ((value - min) / resolution)] += 1.0; } /** * Returns histogram's number of bins. * * @return number of bins */ public int getSize() { return frequencies.length; } /** * Returns the height of the bin at the specified position. * * @param index bin index * @return bin height */ public double getFrequency(int index) { return frequencies[index]; } /** * Finds the histogram's peak value. * * @return peak value */ public double getPeakValue() { int peakIndex = 0; for (int i = 1; i < frequencies.length; i++) { if (frequencies[i] > frequencies[peakIndex]) { peakIndex = i; } } int peakEndIndex = peakIndex + 1; final double EPS = 0.0001; while (peakEndIndex < frequencies.length && Math.abs(frequencies[peakEndIndex] - frequencies[peakIndex]) < EPS) { peakEndIndex++; } return ((double) peakIndex + peakEndIndex) / 2 * resolution + min; } public static Histogram fromValues(Collection<Double> samples, double resolution) { double min = Double.POSITIVE_INFINITY; double max = Double.NEGATIVE_INFINITY; for (double sample : samples) { min = Math.min(min, sample); max = Math.max(max, sample); } Histogram histogram = new Histogram(min, max, resolution); for (double sample : samples) { histogram.add(sample); } return histogram; } @Override public Iterator<Bin> iterator() { return new Iterator() { private int index = 0; @Override public boolean hasNext() { return index < frequencies.length; } @Override public Object next() { if (index >= frequencies.length) { throw new NoSuchElementException(); } return new Bin(index++); } @Override public void remove() { throw new UnsupportedOperationException("Not supported yet."); } }; } public final class Bin { private final int index; private Bin(int index) { this.index = index; } public int getIndex() { return index; } public double getFrequency() { return frequencies[index]; } public double getValue() { return (index + 0.5) * resolution + min; } } }
8,710
31.143911
121
java
CERMINE
CERMINE-master/cermine-impl/src/main/java/pl/edu/icm/cermine/tools/CharacterUtils.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.tools; /** * @author Dominika Tkaczyk (d.tkaczyk@icm.edu.pl) */ public class CharacterUtils { public static char[] DASH_CHARS = { '\u002D', '\u00AD', '\u2010', '\u2011', '\u2012', '\u2013', '\u2014', '\u2015', '\u207B', '\u208B', '\u2212', '-'}; public static char[] ROMAN_CHARS = {'I', 'V', 'X', 'L', 'C', 'D', 'M'}; }
1,127
33.181818
88
java
CERMINE
CERMINE-master/cermine-impl/src/main/java/pl/edu/icm/cermine/tools/FileExtractor.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.tools; import java.io.IOException; import java.io.InputStream; import java.io.InputStreamReader; import java.io.UnsupportedEncodingException; import java.util.logging.Level; import java.util.logging.Logger; import pl.edu.icm.cermine.exception.TransformationException; import pl.edu.icm.cermine.structure.model.BxDocument; import pl.edu.icm.cermine.structure.transformers.TrueVizToBxDocumentReader; /** * @author Pawel Szostek */ public class FileExtractor { private final InputStream inputStream; public FileExtractor(InputStream is) { this.inputStream = is; } public BxDocument getDocument() throws TransformationException { InputStreamReader isr = null; try { isr = new InputStreamReader(inputStream, "UTF-8"); TrueVizToBxDocumentReader reader = new TrueVizToBxDocumentReader(); return new BxDocument().setPages(reader.read(isr)); } catch (UnsupportedEncodingException ex) { throw new TransformationException("Unsupported encoding!", ex); } finally { try { if (isr != null) { isr.close(); } } catch (IOException ex) { Logger.getLogger(FileExtractor.class.getName()).log(Level.SEVERE, null, ex); } } } }
2,096
33.377049
92
java
CERMINE
CERMINE-master/cermine-impl/src/main/java/pl/edu/icm/cermine/tools/classification/general/PenaltyCalculator.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.tools.classification.general; import java.util.ArrayList; import java.util.Collections; import java.util.List; import pl.edu.icm.cermine.structure.model.BxZoneLabel; /** * @author Pawel Szostek */ public class PenaltyCalculator { private final List<TrainingSample<BxZoneLabel>> samples; private List<BxZoneLabel> classes = null; public PenaltyCalculator(List<TrainingSample<BxZoneLabel>> samples) { this.samples = samples; } public double getPenaltyWeigth(BxZoneLabel label) { int allSamples = samples.size(); int thisSamples = 0; for (TrainingSample<BxZoneLabel> sample : samples) { if (sample.getLabel() == label) { ++thisSamples; } } return (double) allSamples / thisSamples; } public List<BxZoneLabel> getClasses() { if (classes == null) { classes = new ArrayList<BxZoneLabel>(); for (TrainingSample<BxZoneLabel> sample : samples) { if (!classes.contains(sample.getLabel())) { classes.add(sample.getLabel()); } } Collections.sort(classes); } return classes; } }
1,982
30.983871
78
java
CERMINE
CERMINE-master/cermine-impl/src/main/java/pl/edu/icm/cermine/tools/classification/general/FeatureVectorBuilder.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.tools.classification.general; import java.util.ArrayList; import java.util.List; /** * Feature vector builder (GoF factory pattern). The builder calculates feature * vectors for objects using a list of single feature calculators. * * @author Dominika Tkaczyk (d.tkaczyk@icm.edu.pl) * * @param <S> Type of objects for whom features' values can be calculated. * @param <T> Type of additional context objects that can be used for * calculation. */ public class FeatureVectorBuilder<S, T> { private List<FeatureCalculator<S, T>> featureCalculators = new ArrayList<FeatureCalculator<S, T>>(); public FeatureVector getFeatureVector(S object, T context) { FeatureVector featureVector = new FeatureVector(); for (FeatureCalculator<S, T> fc : featureCalculators) { featureVector.addFeature(fc.getFeatureName(), fc.calculateFeatureValue(object, context)); } return featureVector; } public List<String> getFeatureNames() { List<String> ret = new ArrayList<String>(); for (FeatureCalculator<S, T> fc : featureCalculators) { ret.add(fc.getFeatureName()); } return ret; } public int size() { return featureCalculators.size(); } public List<FeatureCalculator<S, T>> getFeatureCalculators() { return featureCalculators; } public void setFeatureCalculators( List<FeatureCalculator<S, T>> featureCalculators) { this.featureCalculators = featureCalculators; } }
2,312
33.014706
104
java
CERMINE
CERMINE-master/cermine-impl/src/main/java/pl/edu/icm/cermine/tools/classification/general/ClassificationUtils.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.tools.classification.general; import java.util.ArrayList; import java.util.List; import pl.edu.icm.cermine.structure.model.BxZoneLabel; import pl.edu.icm.cermine.structure.model.BxZoneLabelCategory; /** * @author Pawel Szostek */ public class ClassificationUtils { public static List<TrainingSample<BxZoneLabel>> filterElements(List<TrainingSample<BxZoneLabel>> elements, BxZoneLabelCategory category) { if (category == BxZoneLabelCategory.CAT_ALL) { List<TrainingSample<BxZoneLabel>> ret = new ArrayList<TrainingSample<BxZoneLabel>>(); ret.addAll(elements); return ret; } List<TrainingSample<BxZoneLabel>> ret = new ArrayList<TrainingSample<BxZoneLabel>>(); for (TrainingSample<BxZoneLabel> elem : elements) { if (elem.getLabel() == null) { continue; } if (elem.getLabel().getCategory() == category) { ret.add(elem); } } return ret; } public static List<TrainingSample<BxZoneLabel>> filterElements(List<TrainingSample<BxZoneLabel>> elements, List<BxZoneLabel> labels) { List<TrainingSample<BxZoneLabel>> ret = new ArrayList<TrainingSample<BxZoneLabel>>(); for (TrainingSample<BxZoneLabel> elem : elements) { if (labels.contains(elem.getLabel())) { ret.add(elem); } } return ret; } }
2,206
34.031746
142
java
CERMINE
CERMINE-master/cermine-impl/src/main/java/pl/edu/icm/cermine/tools/classification/general/FeatureCalculator.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.tools.classification.general; /** * Feature calculator is able to calculate a single feature's value. * * @author Dominika Tkaczyk (d.tkaczyk@icm.edu.pl) * * @param <S> Type of objects whose feature value can be calculated. * @param <T> Type of an additional context object that can be used * for calculation. */ public abstract class FeatureCalculator<S, T> { private String featureName; /** * Returns the name of the feature that can be calculated by the calculator. * Two different feature calculators of the same parameter types should * return different feature names. * * @return Feature name. */ public String getFeatureName() { if (featureName == null) { String className = this.getClass().getName(); String[] classNameParts = className.split("\\."); className = classNameParts[classNameParts.length-1]; if (className.contains("Feature")) { featureName = className.replace("Feature", ""); } else { featureName = className; } } return featureName; } /** * Calculates the value of a single feature. * * @param object An object whose feature value will be calculated. * @param context An additional context object used for calculation. * @return Calculated feature value. */ public abstract double calculateFeatureValue(S object, T context); }
2,243
33
80
java
CERMINE
CERMINE-master/cermine-impl/src/main/java/pl/edu/icm/cermine/tools/classification/general/BxDocsToTrainingSamplesConverter.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.tools.classification.general; import java.util.*; import pl.edu.icm.cermine.exception.AnalysisException; import pl.edu.icm.cermine.metadata.zoneclassification.tools.ZoneClassificationUtils; import pl.edu.icm.cermine.structure.model.*; /** * BxDocument objects to HMM training elements converter node. The observations * emitted by resulting training elements are vectors of features. * * @author Dominika Tkaczyk (d.tkaczyk@icm.edu.pl) */ public abstract class BxDocsToTrainingSamplesConverter { public static List<TrainingSample<BxZoneLabel>> getZoneTrainingSamples(Iterator<BxDocument> documents, FeatureVectorBuilder<BxZone, BxPage> vectorBuilder, Map<BxZoneLabel, BxZoneLabel> labelMap) throws AnalysisException { List<TrainingSample<BxZoneLabel>> trainingList = new ArrayList<TrainingSample<BxZoneLabel>>(); int i = 0; while (documents.hasNext()) { BxDocument doc = documents.next(); if (labelMap != null) { ZoneClassificationUtils.mapZoneLabels(doc, labelMap); } for (BxPage page : doc) { for (BxZone zone : page) { FeatureVector featureVector = vectorBuilder.getFeatureVector(zone, page); TrainingSample<BxZoneLabel> element = new TrainingSample<BxZoneLabel>(featureVector, zone.getLabel()); element.setData(zone.toText()); trainingList.add(element); } } System.out.println("Converting document: "+(++i)); } return trainingList; } public static List<TrainingSample<BxZoneLabel>> getZoneTrainingSamples(List<BxDocument> documents, FeatureVectorBuilder<BxZone, BxPage> vectorBuilder, Map<BxZoneLabel, BxZoneLabel> labelMap) throws AnalysisException { List<TrainingSample<BxZoneLabel>> trainingList = new ArrayList<TrainingSample<BxZoneLabel>>(documents.size()); for (BxDocument doc : documents) { if (labelMap != null) { ZoneClassificationUtils.mapZoneLabels(doc, labelMap); } for (BxPage page : doc) { for (BxZone zone : page) { FeatureVector featureVector = vectorBuilder.getFeatureVector(zone, page); TrainingSample<BxZoneLabel> element = new TrainingSample<BxZoneLabel>(featureVector, zone.getLabel()); trainingList.add(element); } } } return trainingList; } public static List<TrainingSample<BxZoneLabel>> getZoneTrainingSamples(List<BxDocument> documents, FeatureVectorBuilder<BxZone, BxPage> vectorBuilder) throws AnalysisException { return getZoneTrainingSamples(documents, vectorBuilder, null); } public static List<TrainingSample<BxZoneLabel>> getZoneTrainingSamples(BxDocument document, FeatureVectorBuilder<BxZone, BxPage> vectorBuilder, Map<BxZoneLabel, BxZoneLabel> labelMap) throws AnalysisException { return getZoneTrainingSamples(Arrays.asList(document), vectorBuilder, labelMap); } public static List<TrainingSample<BxZoneLabel>> getZoneTrainingSamples(BxDocument document, FeatureVectorBuilder<BxZone, BxPage> vectorBuilder) throws AnalysisException { return getZoneTrainingSamples(Arrays.asList(document), vectorBuilder, null); } public static List<TrainingSample<BxZoneLabel>> getLineTrainingSamples(List<BxDocument> documents, FeatureVectorBuilder<BxLine, BxPage> vectorBuilder, Map<BxZoneLabel, BxZoneLabel> labelMap) throws AnalysisException { List<TrainingSample<BxZoneLabel>> trainingList = new ArrayList<TrainingSample<BxZoneLabel>>(documents.size()); for (BxDocument doc : documents) { if (labelMap != null) { ZoneClassificationUtils.mapZoneLabels(doc, labelMap); } for (BxPage page : doc) { for (BxZone zone : page) { for (BxLine line : zone) { FeatureVector featureVector = vectorBuilder.getFeatureVector(line, page); TrainingSample<BxZoneLabel> element = new TrainingSample<BxZoneLabel>(featureVector, zone.getLabel()); trainingList.add(element); } } } } return trainingList; } public static List<TrainingSample<BxZoneLabel>> getLineTrainingSamples(List<BxDocument> documents, FeatureVectorBuilder<BxLine, BxPage> vectorBuilder) throws AnalysisException { return getLineTrainingSamples(documents, vectorBuilder, null); } public static List<TrainingSample<BxZoneLabel>> getLineTrainingSamples(BxDocument document, FeatureVectorBuilder<BxLine, BxPage> vectorBuilder, Map<BxZoneLabel, BxZoneLabel> labelMap) throws AnalysisException { return getLineTrainingSamples(Arrays.asList(document), vectorBuilder, labelMap); } public static List<TrainingSample<BxZoneLabel>> getLineTrainingSamples(BxDocument document, FeatureVectorBuilder<BxLine, BxPage> vectorBuilder) throws AnalysisException { return getLineTrainingSamples(Arrays.asList(document), vectorBuilder, null); } }
6,147
45.931298
130
java
CERMINE
CERMINE-master/cermine-impl/src/main/java/pl/edu/icm/cermine/tools/classification/general/FeatureLimits.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.tools.classification.general; /** * @author Pawel Szostek */ public class FeatureLimits { private double min; private double max; public FeatureLimits(double minValue, double maxValue) { min = minValue; max = maxValue; } public double getMin() { return min; } public void setMin(double min) { this.min = min; } public double getMax() { return max; } public void setMax(double max) { this.max = max; } }
1,272
24.46
78
java
CERMINE
CERMINE-master/cermine-impl/src/main/java/pl/edu/icm/cermine/tools/classification/general/FeatureVectorScalerNoOp.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.tools.classification.general; import java.io.IOException; import java.util.List; /** * @author Mateusz Fedoryszak */ public class FeatureVectorScalerNoOp implements FeatureVectorScaler { @Override public FeatureVector scaleFeatureVector(FeatureVector fv) { return fv; } @Override public <A extends Enum<A>> void calculateFeatureLimits(List<TrainingSample<A>> trainingElements) { // intentionally left blank } @Override public void saveRangeFile(String path) throws IOException { // intentionally left blank } }
1,350
29.704545
102
java
CERMINE
CERMINE-master/cermine-impl/src/main/java/pl/edu/icm/cermine/tools/classification/general/FeatureVectorScaler.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.tools.classification.general; import java.io.IOException; import java.util.List; /** * @author Mateusz Fedoryszak */ public interface FeatureVectorScaler { FeatureVector scaleFeatureVector(FeatureVector fv); <A extends Enum<A>> void calculateFeatureLimits(List<TrainingSample<A>> trainingElements); void saveRangeFile(String path) throws IOException; }
1,153
31.055556
94
java
CERMINE
CERMINE-master/cermine-impl/src/main/java/pl/edu/icm/cermine/tools/classification/general/TrainingSample.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.tools.classification.general; /** * @author Dominika Tkaczyk (d.tkaczyk@icm.edu.pl) * @param <S> class label */ public class TrainingSample<S> implements Cloneable { private FeatureVector features; private S label; private String data; public TrainingSample(FeatureVector features, S label) { this.features = features; this.label = label; } public FeatureVector getFeatureVector() { return features; } public void setFeatureVectors(FeatureVector features) { this.features = features; } public S getLabel() { return label; } public void setLabel(S label) { this.label = label; } @Override public TrainingSample<S> clone() throws CloneNotSupportedException { TrainingSample<S> element = (TrainingSample) super.clone(); element.label = label; element.features = features.copy(); return element; } public String getData() { return data; } public void setData(String data) { this.data = data; } }
1,865
25.657143
78
java
CERMINE
CERMINE-master/cermine-impl/src/main/java/pl/edu/icm/cermine/tools/classification/general/FeatureVectorScalerImpl.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.tools.classification.general; import java.io.BufferedReader; import java.io.BufferedWriter; import java.io.FileOutputStream; import java.io.IOException; import java.io.OutputStreamWriter; import java.io.Writer; import java.util.*; import org.apache.commons.io.IOUtils; import pl.edu.icm.cermine.tools.timeout.TimeoutRegister; /** * @author Pawel Szostek */ public class FeatureVectorScalerImpl implements FeatureVectorScaler { protected FeatureLimits[] limits; protected double scaledLowerBound; protected double scaledUpperBound; protected ScalingStrategy strategy; public FeatureVectorScalerImpl(int size, double lowerBound, double upperBound) { this.scaledLowerBound = lowerBound; this.scaledUpperBound = upperBound; limits = new FeatureLimits[size]; //set default limits to: max = -inf, min = +inf for (int idx = 0; idx < size; ++idx) { limits[idx] = new FeatureLimits(Double.POSITIVE_INFINITY, Double.NEGATIVE_INFINITY); } strategy = new LinearScaling(); } public void setStrategy(ScalingStrategy strategy) { this.strategy = strategy; } @Override public FeatureVector scaleFeatureVector(FeatureVector fv) { for (FeatureLimits l : limits) { assert l.getMin() != Double.POSITIVE_INFINITY && l.getMax() != Double.NEGATIVE_INFINITY; } return strategy.scaleFeatureVector(scaledLowerBound, scaledUpperBound, limits, fv); } public void setFeatureLimits(List<FeatureLimits> featureLimits) { this.limits = featureLimits.toArray(new FeatureLimits[featureLimits.size()]); } @Override public <A extends Enum<A>> void calculateFeatureLimits(List<TrainingSample<A>> trainingElements) { for (TrainingSample<A> trainingElem: trainingElements) { FeatureVector fv = trainingElem.getFeatureVector(); List<String> names = fv.getFeatureNames(); int featureIdx = 0; for (String name: names) { double val = fv.getValue(name); if (val > limits[featureIdx].getMax()) { limits[featureIdx].setMax(val); } if (val < limits[featureIdx].getMin()){ limits[featureIdx].setMin(val); } ++featureIdx; } TimeoutRegister.get().check(); } for (FeatureLimits limit : limits) { if (Double.isInfinite(limit.getMin()) || Double.isInfinite(limit.getMax())) { throw new RuntimeException("Feature limit is not calculated properly!"); } } } public FeatureLimits[] getLimits() { return limits; } @Override public void saveRangeFile(String path) throws IOException { BufferedWriter fp_save = null; try { Formatter formatter = new Formatter(new StringBuilder()); Writer fw = new OutputStreamWriter(new FileOutputStream(path), "UTF-8"); fp_save = new BufferedWriter(fw); double lower = 0.0; double upper = 1.0; formatter.format("x%n"); formatter.format(Locale.ENGLISH, "%.16g %.16g%n", lower, upper); for (int i = 0; i < limits.length; ++i) { formatter.format(Locale.ENGLISH, "%d %.16g %.16g%n", i, limits[i].getMin(), limits[i].getMax()); } fp_save.write(formatter.toString()); } finally { if (fp_save != null) { fp_save.close(); } } } public static FeatureVectorScalerImpl fromRangeReader(BufferedReader rangeFile) throws IOException { try { double feature_min, feature_max; if (rangeFile.read() == 'x') { rangeFile.readLine(); // pass the '\n' after 'x' String line = rangeFile.readLine(); if (line == null) { line = ""; } StringTokenizer st = new StringTokenizer(line); double scaledLowerBound = Double.parseDouble(st.nextToken()); double scaledUpperBound = Double.parseDouble(st.nextToken()); if (scaledLowerBound != 0 || scaledUpperBound != 1) { throw new RuntimeException("Feature lower bound and upper bound must" + "be set in range file to resepctively 0 and 1"); } String restore_line; List<FeatureLimits> limits = new ArrayList<FeatureLimits>(); while ((restore_line = rangeFile.readLine()) != null) { StringTokenizer st2 = new StringTokenizer(restore_line); st2.nextToken(); //discard feature index feature_min = Double.parseDouble(st2.nextToken()); feature_max = Double.parseDouble(st2.nextToken()); FeatureLimits newLimit = new FeatureLimits(feature_min, feature_max); limits.add(newLimit); } FeatureVectorScalerImpl scaler = new FeatureVectorScalerImpl(limits.size(), scaledLowerBound, scaledUpperBound); scaler.setStrategy(new LinearScaling()); scaler.setFeatureLimits(limits); return scaler; } else { throw new RuntimeException("y scaling not supported"); } } finally { IOUtils.closeQuietly(rangeFile); } } }
6,168
36.846626
128
java
CERMINE
CERMINE-master/cermine-impl/src/main/java/pl/edu/icm/cermine/tools/classification/general/ScalingStrategy.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.tools.classification.general; /** * @author Pawel Szostek */ public interface ScalingStrategy { FeatureVector scaleFeatureVector(double scaledLowerBound, double scaledUpperBound, FeatureLimits[] limits, FeatureVector fv); }
1,007
35
79
java
CERMINE
CERMINE-master/cermine-impl/src/main/java/pl/edu/icm/cermine/tools/classification/general/FeatureVector.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.tools.classification.general; import java.util.ArrayList; import java.util.List; /** * Simple feature vector. * * @author Dominika Tkaczyk (d.tkaczyk@icm.edu.pl) * @author Pawel Szostek */ public class FeatureVector { private List<String> names = new ArrayList<String>(); private List<Double> values = new ArrayList<Double>(); public int size() { return values.size(); } public List<String> getFeatureNames() { return names; } public double getValue(String name) { if (!names.contains(name)) { throw new IllegalArgumentException("Feature vector does not contain feature '" + name + "'!"); } return values.get(names.indexOf(name)); } public double getValue(int index) { if (index < 0 || index >= values.size()) { throw new IllegalArgumentException("Feature vector contains only " + size()+ " features!"); } return values.get(index); } public double[] getValues() { double[] ret = new double[size()]; for (int i = 0; i < size(); i++) { ret[i] = values.get(i); } return ret; } public void addFeature(String name, double value) { names.add(name); values.add(value); } public void setValue(String name, double value) { if (!names.contains(name)) { throw new IllegalArgumentException("Feature vector does not contain feature '" + name + "'!"); } values.add(names.indexOf(name), value); values.remove(names.indexOf(name) + 1); } public void setValue(int index, double value) { if (index < 0 || index >= values.size()) { throw new IllegalArgumentException("Feature vector contains only " + size()+ " features!"); } values.add(index, value); values.remove(index + 1); } public void setValues(double[] values) { if (names.size() != values.length) { throw new IllegalArgumentException("This feature vector has " + names.size() + " features!"); } this.values.clear(); for (double value: values) { this.values.add(value); } } public String dump() { StringBuilder ret = new StringBuilder(); for(int idx=0; idx<size(); ++idx) { String name = names.get(idx); String shortName = (name.length() > 18 ? name.substring(0, 18) : name); ret.append(String.format("%18s: %5.2f%n", shortName, values.get(idx))); } return ret.toString(); } public FeatureVector copy() { FeatureVector ret = new FeatureVector(); ret.names = new ArrayList<String>(names); ret.values = new ArrayList<Double>(values); return ret; } }
3,544
29.560345
106
java
CERMINE
CERMINE-master/cermine-impl/src/main/java/pl/edu/icm/cermine/tools/classification/general/LinearScaling.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.tools.classification.general; import pl.edu.icm.cermine.tools.timeout.TimeoutRegister; /** * @author Pawel Szostek */ public class LinearScaling implements ScalingStrategy { @Override public FeatureVector scaleFeatureVector(double scaledLowerBound, double scaledUpperBound, FeatureLimits[] limits, FeatureVector fv) { final double EPS = 0.00001; FeatureVector newVector = new FeatureVector(); int featureIdx = 0; for (String name : fv.getFeatureNames()) { //scaling function: y = a*x+b // featureLower = a*v_min + b // featureUpper = a*v_max + b if (Math.abs(limits[featureIdx].getMax() - limits[featureIdx].getMin()) < EPS) { newVector.addFeature(name, 1.0); } else { Double featureValue = fv.getValue(name); double a = (scaledUpperBound - scaledLowerBound) / (limits[featureIdx].getMax() - limits[featureIdx].getMin()); double b = scaledLowerBound - a * limits[featureIdx].getMin(); featureValue = a * featureValue + b; if (featureValue.isNaN()) { throw new RuntimeException("Feature value is set to NaN: "+name); } newVector.addFeature(name, featureValue); } ++featureIdx; TimeoutRegister.get().check(); } return newVector; } }
2,125
35.655172
127
java
CERMINE
CERMINE-master/cermine-impl/src/main/java/pl/edu/icm/cermine/tools/classification/clustering/Clusterizer.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.tools.classification.clustering; /** * Clusterizer interface. * * @author Dominika Tkaczyk (d.tkaczyk@icm.edu.pl) */ public interface Clusterizer { int[] clusterize(double distanceMatrix[][], double maxDistance); }
999
30.25
78
java
CERMINE
CERMINE-master/cermine-impl/src/main/java/pl/edu/icm/cermine/tools/classification/clustering/FeatureVectorClusterizer.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.tools.classification.clustering; import pl.edu.icm.cermine.tools.classification.general.FeatureVector; import pl.edu.icm.cermine.tools.classification.general.FeatureVectorBuilder; import pl.edu.icm.cermine.tools.distance.FeatureVectorDistanceMetric; /** * @author Dominika Tkaczyk (d.tkaczyk@icm.edu.pl) */ public class FeatureVectorClusterizer { private Clusterizer clusterizer; public int[] clusterize(FeatureVector[] vectors, FeatureVectorBuilder builder, FeatureVectorDistanceMetric metric, double maxDistance, boolean normalize) { if (normalize){ FeatureVectorsNormalizer.normalize(vectors, builder); } double distanceMatrix[][] = new double[vectors.length][vectors.length]; for (int i = 0; i < vectors.length; i++) { for (int j = 0; j < vectors.length; j++) { distanceMatrix[i][j] = metric.getDistance(vectors[i], vectors[j]); distanceMatrix[j][i] = metric.getDistance(vectors[i], vectors[j]); } } return clusterizer.clusterize(distanceMatrix, maxDistance); } public void setClusterizer(Clusterizer clusterizer) { this.clusterizer = clusterizer; } }
2,005
36.849057
119
java
CERMINE
CERMINE-master/cermine-impl/src/main/java/pl/edu/icm/cermine/tools/classification/clustering/ClusteringEvaluator.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.tools.classification.clustering; /** * Interface for classes evaluating the effects of clustering. * * @author Dominika Tkaczyk (d.tkaczyk@icm.edu.pl) */ public interface ClusteringEvaluator { /** * Checks, whether the effects of clustering are acceptable * * @param clusters clusters * @return whether clustering is acceptable */ boolean isAcceptable(int[] clusters); }
1,185
31.054054
78
java
CERMINE
CERMINE-master/cermine-impl/src/main/java/pl/edu/icm/cermine/tools/classification/clustering/FeatureVectorsNormalizer.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.tools.classification.clustering; 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 final class FeatureVectorsNormalizer { public static void normalize(FeatureVector[] vectors, FeatureVectorBuilder<?,?> builder) { for (String feature : builder.getFeatureNames()) { double min = Double.POSITIVE_INFINITY; double max = Double.NEGATIVE_INFINITY; for (FeatureVector vector : vectors) { if (vector.getValue(feature) < min) { min = vector.getValue(feature); } if (vector.getValue(feature) > max) { max = vector.getValue(feature); } } for (FeatureVector vector : vectors) { if (max - min == 0) { vector.addFeature(feature, 0); } else { vector.addFeature(feature, (vector.getValue(feature) - min) / (max - min)); } } } } private FeatureVectorsNormalizer() {} }
2,010
34.910714
95
java
CERMINE
CERMINE-master/cermine-impl/src/main/java/pl/edu/icm/cermine/tools/classification/clustering/CompleteLinkageClusterizer.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.tools.classification.clustering; import com.google.common.collect.Sets; import java.util.HashSet; import java.util.Set; /** * Complete linkage clusterizer. * * @author Dominika Tkaczyk (d.tkaczyk@icm.edu.pl) */ public class CompleteLinkageClusterizer implements Clusterizer { private ClusteringEvaluator evaluator; public CompleteLinkageClusterizer() { } public CompleteLinkageClusterizer(ClusteringEvaluator evaluator) { this.evaluator = evaluator; } @Override public int[] clusterize(double distanceMatrix[][], double maxDistance) { Set<Set<Integer>> clusters = new HashSet<Set<Integer>>(); for (int i = 0; i < distanceMatrix.length; i++) { clusters.add(Sets.newHashSet(i)); } while (true) { double mind = Double.POSITIVE_INFINITY; Set<Integer> minClust1 = null; Set<Integer> minClust2 = null; for (Set<Integer> clust1 : clusters) { for (Set<Integer> clust2 : clusters) { if (clust1.equals(clust2)) { continue; } double maxd = Double.NEGATIVE_INFINITY; for (int i : clust1) { for (int j : clust2) { if (distanceMatrix[i][j] > maxd) { maxd = distanceMatrix[i][j]; } } } if (maxd < mind) { mind = maxd; minClust1 = clust1; minClust2 = clust2; } } } int[] clusterArray = createClusterArray(distanceMatrix.length, clusters); if (mind < maxDistance || (evaluator != null && !evaluator.isAcceptable(clusterArray))) { clusters.remove(minClust1); clusters.remove(minClust2); if (minClust1 == null) { minClust1 = new HashSet<Integer>(); } minClust1.addAll(minClust2); clusters.add(minClust1); } else { break; } } return createClusterArray(distanceMatrix.length, clusters); } private int[] createClusterArray(int length, Set<Set<Integer>> clusters) { int[] clusterArray = new int[length]; int clusterIndex = 0; for (Set<Integer> cluster : clusters) { for (int element : cluster) { clusterArray[element] = clusterIndex; } clusterIndex++; } return clusterArray; } public ClusteringEvaluator getEvaluator() { return evaluator; } public void setEvaluator(ClusteringEvaluator evaluator) { this.evaluator = evaluator; } }
3,737
31.789474
101
java
CERMINE
CERMINE-master/cermine-impl/src/main/java/pl/edu/icm/cermine/tools/classification/clustering/SingleLinkageClusterizer.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.tools.classification.clustering; /** * Single linkage clusterizer. * * @author Dominika Tkaczyk (d.tkaczyk@icm.edu.pl) */ public class SingleLinkageClusterizer implements Clusterizer { @Override public int[] clusterize(double distanceMatrix[][], double maxDistance) { int[] clusters = new int[distanceMatrix.length]; for (int i = 0; i < clusters.length; i++) { clusters[i] = i; } while (true) { int mini = -1; int minj = -1; for (int k = 0; k < distanceMatrix.length; k++) { for (int l = 0; l < distanceMatrix.length; l++) { if (distanceMatrix[k][l] < maxDistance && clusters[k] != clusters[l]) { mini = k; minj = l; } } } if (mini == -1) { return clusters; } int old = clusters[mini]; for (int i = 0; i < clusters.length; i++) { if (clusters[i] == old) { clusters[i] = clusters[minj]; } } } } }
1,968
30.253968
91
java
CERMINE
CERMINE-master/cermine-impl/src/main/java/pl/edu/icm/cermine/tools/classification/clustering/KMeansWithInitialCentroids.java
/** * The code was originally copied from Java Machine Learning Library. * Changes have been introduced in the original code. * * Copyright (c) 2006-2009, Thomas Abeel (original author) * Project: http://java-ml.sourceforge.net/ (original project) * * This file is part of CERMINE project. * * 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.tools.classification.clustering; import java.util.ArrayList; import java.util.List; import java.util.Random; import pl.edu.icm.cermine.tools.classification.general.FeatureVector; import pl.edu.icm.cermine.tools.distance.FeatureVectorDistanceMetric; import pl.edu.icm.cermine.tools.distance.FeatureVectorEuclideanMetric; public class KMeansWithInitialCentroids { /** * The number of clusters. */ private int numberOfClusters = -1; /** * The number of iterations the algorithm should make. If this value is * Integer.INFINITY, then the algorithm runs until the centroids no longer * change. * */ private int numberOfIterations = -1; /** * Random generator for this clusterer. */ private Random rg; /** * The distance measure used in the algorithm, defaults to Euclidean * distance. */ private FeatureVectorDistanceMetric dm; /** * The centroids of the different clusters. */ private FeatureVector[] centroids; /** * Constuct a default K-means clusterer with 100 iterations, 4 clusters, a * default random generator and using the Euclidean distance. */ public KMeansWithInitialCentroids() { this(4); } /** * Constuct a default K-means clusterer with the specified number of * clusters, 100 iterations, a default random generator and using the * Euclidean distance. * * @param k the number of clusters to create */ public KMeansWithInitialCentroids(int k) { this(k, 100); } /** * Create a new Simple K-means clusterer with the given number of clusters * and iterations. The internal random generator is a new one based upon the * current system time. For the distance we use the Euclidean n-space * distance. * * @param clusters * the number of clusters * @param iterations * the number of iterations */ public KMeansWithInitialCentroids(int clusters, int iterations) { this(clusters, iterations, new FeatureVectorEuclideanMetric()); } /** * Create a new K-means clusterer with the given number of clusters and * iterations. Also the Random Generator for the clusterer is given as * parameter. * * @param clusters * the number of clustesr * @param iterations * the number of iterations * * @param dm * the distance measure to use */ public KMeansWithInitialCentroids(int clusters, int iterations, FeatureVectorDistanceMetric dm) { this.numberOfClusters = clusters; this.numberOfIterations = iterations; this.dm = dm; rg = new Random(System.currentTimeMillis()); } public void setCentroids(FeatureVector[] centroids) { this.centroids = new FeatureVector[centroids.length]; System.arraycopy(centroids, 0, this.centroids, 0, centroids.length); } public List<FeatureVector>[] cluster(List<FeatureVector> data) { if (data.isEmpty()) { throw new RuntimeException("The dataset should not be empty"); } if (numberOfClusters == 0) { throw new RuntimeException("There should be at least one cluster"); } // Place K points into the space represented by the objects that are // being clustered. These points represent the initial group of // centroids. // DatasetTools. int instanceLength = data.get(0).size(); double[] min = new double[instanceLength]; double[] max = new double[instanceLength]; for (int i = 0; i < instanceLength; i++) { min[i] = data.get(0).getValue(i); max[i] = data.get(0).getValue(i); } for (FeatureVector fv : data) { for (int i = 0; i < instanceLength; i++) { if (fv.getValue(i) < min[i]) { min[i] = fv.getValue(i); } if (fv.getValue(i) > max[i]) { max[i] = fv.getValue(i); } } } if (this.centroids == null) { this.centroids = new FeatureVector[numberOfClusters]; for (int j = 0; j < numberOfClusters; j++) { double[] randomInstance = new double[instanceLength]; for (int i = 0; i < instanceLength; i++) { double dist = Math.abs(max[i] - min[i]); randomInstance[i] = (float) (min[i] + rg.nextDouble() * dist); } this.centroids[j] = data.get(0).copy(); this.centroids[j].setValues(randomInstance); } } int iterationCount = 0; boolean centroidsChanged = true; boolean randomCentroids = true; while (randomCentroids || (iterationCount < this.numberOfIterations && centroidsChanged)) { iterationCount++; // Assign each object to the group that has the closest centroid. int[] assignment = new int[data.size()]; for (int i = 0; i < data.size(); i++) { int tmpCluster = 0; double minDistance = dm.getDistance(centroids[0], data.get(i)); for (int j = 1; j < centroids.length; j++) { double dist = dm.getDistance(centroids[j], data.get(i)); if (dist < minDistance) { minDistance = dist; tmpCluster = j; } } assignment[i] = tmpCluster; } // When all objects have been assigned, recalculate the positions of // the K centroids and start over. // The new position of the centroid is the weighted center of the // current cluster. double[][] sumPosition = new double[this.numberOfClusters][instanceLength]; int[] countPosition = new int[this.numberOfClusters]; for (int i = 0; i < data.size(); i++) { FeatureVector in = data.get(i); for (int j = 0; j < instanceLength; j++) { sumPosition[assignment[i]][j] += in.getValue(j); } countPosition[assignment[i]]++; } centroidsChanged = false; randomCentroids = false; for (int i = 0; i < this.numberOfClusters; i++) { if (countPosition[i] > 0) { double[] tmp = new double[instanceLength]; for (int j = 0; j < instanceLength; j++) { tmp[j] = (float) sumPosition[i][j] / countPosition[i]; } FeatureVector newCentroid = data.get(0).copy(); newCentroid.setValues(tmp); if (dm.getDistance(newCentroid, centroids[i]) > 0.0001) { centroidsChanged = true; centroids[i] = newCentroid; } } else { double[] randomInstance = new double[instanceLength]; for (int j = 0; j < instanceLength; j++) { double dist = Math.abs(max[j] - min[j]); randomInstance[j] = (float) (min[j] + rg.nextDouble() * dist); } randomCentroids = true; this.centroids[i] = data.get(0).copy(); this.centroids[i].setValues(randomInstance); } } } List<FeatureVector>[] output = new List[centroids.length]; for (int i = 0; i < centroids.length; i++) { output[i] = new ArrayList<FeatureVector>(); } for (int i = 0; i < data.size(); i++) { int tmpCluster = 0; double minDistance = dm.getDistance(centroids[0], data.get(i)); for (int j = 0; j < centroids.length; j++) { double dist = dm.getDistance(centroids[j], data.get(i)); if (dist < minDistance) { minDistance = dist; tmpCluster = j; } } output[tmpCluster].add(data.get(i)); } return output; } }
9,356
36.428
101
java
CERMINE
CERMINE-master/cermine-impl/src/main/java/pl/edu/icm/cermine/tools/classification/sampleselection/SampleFilter.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.tools.classification.sampleselection; import java.util.ArrayList; import java.util.List; import pl.edu.icm.cermine.structure.model.BxZoneLabel; import pl.edu.icm.cermine.structure.model.BxZoneLabelCategory; import pl.edu.icm.cermine.tools.classification.general.TrainingSample; /** * @author Pawel Szostek */ public class SampleFilter implements SampleSelector<BxZoneLabel> { private final BxZoneLabelCategory category; public SampleFilter(BxZoneLabelCategory category) { this.category = category; } @Override public List<TrainingSample<BxZoneLabel>> pickElements(List<TrainingSample<BxZoneLabel>> inputElements) { List<TrainingSample<BxZoneLabel>> ret = new ArrayList<TrainingSample<BxZoneLabel>>(); for (TrainingSample<BxZoneLabel> elem : inputElements) { if (elem.getLabel().getCategory() == category) { ret.add(elem); } } return ret; } }
1,717
34.061224
108
java
CERMINE
CERMINE-master/cermine-impl/src/main/java/pl/edu/icm/cermine/tools/classification/sampleselection/OversamplingSelector.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.tools.classification.sampleselection; import java.util.Map.Entry; import java.util.*; import pl.edu.icm.cermine.tools.classification.general.TrainingSample; /** * @author Pawel Szostek * @param <S> sample type */ public class OversamplingSelector<S> implements SampleSelector<S> { private final double inequalityFactor; public OversamplingSelector(double inequalityFactor) { this.inequalityFactor = inequalityFactor; } @Override public List<TrainingSample<S>> pickElements(List<TrainingSample<S>> inputElements) { Map<S, Integer> labelCount = new HashMap<S, Integer>(); for (TrainingSample<S> elem : inputElements) { if (!labelCount.containsKey(elem.getLabel())) { labelCount.put(elem.getLabel(), 0); } labelCount.put(elem.getLabel(), labelCount.get(elem.getLabel()) + 1); } int greatestClassNumber = 0; for (Entry<S, Integer> entry : labelCount.entrySet()) { if (entry.getValue() > greatestClassNumber) { greatestClassNumber = entry.getValue(); } System.out.println(entry.getKey() + " " + entry.getValue()); } List<TrainingSample<S>> trainingSamples = new ArrayList<TrainingSample<S>>(); for (S label : labelCount.keySet()) { List<TrainingSample<S>> thisLabelElements = new ArrayList<TrainingSample<S>>(); for (TrainingSample<S> elem : inputElements) { if (elem.getLabel() == label) { thisLabelElements.add(elem); } } if (thisLabelElements.size() == greatestClassNumber || thisLabelElements.size() > greatestClassNumber * inequalityFactor) { trainingSamples.addAll(thisLabelElements); System.out.println(label + " " + thisLabelElements.size()); } else { Random randomGenerator = new Random(); List<TrainingSample<S>> chosenElements = new ArrayList<TrainingSample<S>>(); while (chosenElements.size() < greatestClassNumber * inequalityFactor) { int randInt = randomGenerator.nextInt(thisLabelElements.size()); TrainingSample<S> randElem = thisLabelElements.get(randInt); chosenElements.add(randElem); } trainingSamples.addAll(chosenElements); System.out.println(label + " " + chosenElements.size()); } } return trainingSamples; } }
3,335
39.192771
135
java
CERMINE
CERMINE-master/cermine-impl/src/main/java/pl/edu/icm/cermine/tools/classification/sampleselection/UndersamplingSelector.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.tools.classification.sampleselection; import java.util.Map.Entry; import java.util.*; import pl.edu.icm.cermine.tools.classification.general.TrainingSample; /** * @author Pawel Szostek * @param <S> sample type */ public class UndersamplingSelector<S> implements SampleSelector<S> { private final double inequalityFactor; public UndersamplingSelector(double inequalityFactor) { assert inequalityFactor > 1.0; this.inequalityFactor = inequalityFactor; } @Override public List<TrainingSample<S>> pickElements(List<TrainingSample<S>> inputElements) { Map<S, Integer> labelCount = new HashMap<S, Integer>(); for (TrainingSample<S> elem : inputElements) { if (!labelCount.containsKey(elem.getLabel())) { labelCount.put(elem.getLabel(), 0); } labelCount.put(elem.getLabel(), labelCount.get(elem.getLabel()) + 1); } int smallestClassNumber = Integer.MAX_VALUE; for (Entry<S, Integer> entry : labelCount.entrySet()) { if (entry.getValue() < smallestClassNumber) { smallestClassNumber = entry.getValue(); } System.out.println(entry.getKey() + " " + entry.getValue()); } List<TrainingSample<S>> trainingSamples = new ArrayList<TrainingSample<S>>(); for (S label : labelCount.keySet()) { List<TrainingSample<S>> thisLabelElements = new ArrayList<TrainingSample<S>>(); for (TrainingSample<S> elem : inputElements) { if (elem.getLabel() == label) { thisLabelElements.add(elem); } } if (thisLabelElements.size() < smallestClassNumber * inequalityFactor) { trainingSamples.addAll(thisLabelElements); } else { Random randomGenerator = new Random(); List<TrainingSample<S>> chosenElements = new ArrayList<TrainingSample<S>>(); while (chosenElements.size() < smallestClassNumber * inequalityFactor) { int randInt = randomGenerator.nextInt(thisLabelElements.size()); TrainingSample<S> randElem = thisLabelElements.get(randInt); if (!chosenElements.contains(randElem)) { chosenElements.add(randElem); } } trainingSamples.addAll(chosenElements); } } return trainingSamples; } }
3,280
38.059524
92
java
CERMINE
CERMINE-master/cermine-impl/src/main/java/pl/edu/icm/cermine/tools/classification/sampleselection/NormalSelector.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.tools.classification.sampleselection; import java.util.ArrayList; import java.util.List; import pl.edu.icm.cermine.tools.classification.general.TrainingSample; /** * @author Pawel Szostek * @param <S> sample type */ public class NormalSelector<S> implements SampleSelector<S> { @Override public List<TrainingSample<S>> pickElements(List<TrainingSample<S>> inputElements) { return new ArrayList<TrainingSample<S>>(inputElements); } }
1,223
33
88
java
CERMINE
CERMINE-master/cermine-impl/src/main/java/pl/edu/icm/cermine/tools/classification/sampleselection/SampleSelector.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.tools.classification.sampleselection; import java.util.List; import pl.edu.icm.cermine.tools.classification.general.TrainingSample; /** * Interface for picking samples according to a certain strategy from the * input set. * * @author Pawel Szostek * * @param <S> label type (BxZoneLabel by default) */ public interface SampleSelector<S> { List<TrainingSample<S>> pickElements(List<TrainingSample<S>> inputElements); }
1,198
32.305556
80
java
CERMINE
CERMINE-master/cermine-impl/src/main/java/pl/edu/icm/cermine/tools/classification/knn/KnnClassifier.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.tools.classification.knn; import java.util.Comparator; import java.util.HashMap; import java.util.Iterator; import java.util.Map; import java.util.Map.Entry; import pl.edu.icm.cermine.tools.classification.general.FeatureVector; import pl.edu.icm.cermine.tools.classification.general.TrainingSample; import pl.edu.icm.cermine.tools.distance.FeatureVectorDistanceMetric; /** * @author Dominika Tkaczyk (d.tkaczyk@icm.edu.pl) * @param <T> class label */ public class KnnClassifier<T> { public T classify(KnnModel<T> model, FeatureVectorDistanceMetric metric, FeatureVector sample, int samplesCount) { FVEuclideanDistanceComparator comparator = new FVEuclideanDistanceComparator(sample, metric); TrainingSample[] voters = new TrainingSample[samplesCount]; Iterator<TrainingSample<T>> trainingIterator = model.getIterator(); int i = 0; TrainingSample<T> largest = null; int largestIndex = 0; while (trainingIterator.hasNext()) { if (i < samplesCount) { voters[i] = trainingIterator.next(); } else { if (largest == null) { largest = voters[0]; largestIndex = 0; for (int j = 1; j < samplesCount; j++) { if (comparator.compare(largest, voters[j]) < 0) { largest = voters[j]; largestIndex = j; } } } TrainingSample<T> next = trainingIterator.next(); if (comparator.compare(largest, next) > 0) { voters[largestIndex] = next; largest = null; } } i++; } Map<T,Integer> labelCountMap = new HashMap<T,Integer>(); for (TrainingSample<T> trainingSample : voters) { if (trainingSample != null) { T label = trainingSample.getLabel(); if (labelCountMap.get(label) == null) { labelCountMap.put(label, 1); } else { labelCountMap.put(label, labelCountMap.get(label)+1); } } } T label = null; int labelCount = 0; for (Entry<T, Integer> entry : labelCountMap.entrySet()) { if (labelCountMap.get(entry.getKey()) > labelCount) { label = entry.getKey(); labelCount = labelCountMap.get(entry.getKey()); } } return label; } public class FVEuclideanDistanceComparator implements Comparator<TrainingSample<T>> { private final FeatureVectorDistanceMetric metric; private final FeatureVector sample; public FVEuclideanDistanceComparator(FeatureVector sample, FeatureVectorDistanceMetric metric) { this.sample = sample; this.metric = metric; } @Override public int compare(TrainingSample<T> ts1, TrainingSample<T> ts2) { double dist1 = metric.getDistance(sample, ts1.getFeatureVector()); double dist2 = metric.getDistance(sample, ts2.getFeatureVector()); return Double.compare(dist1, dist2); } } }
4,121
35.803571
118
java
CERMINE
CERMINE-master/cermine-impl/src/main/java/pl/edu/icm/cermine/tools/classification/knn/KnnModel.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.tools.classification.knn; import java.util.HashSet; import java.util.Iterator; import java.util.Set; import pl.edu.icm.cermine.tools.classification.general.TrainingSample; /** * @author Dominika Tkaczyk (d.tkaczyk@icm.edu.pl) * @param <T> label */ public class KnnModel<T> { private final Set<TrainingSample<T>> trainingSamples; public KnnModel(Set<TrainingSample<T>> trainingSamples) { this.trainingSamples = trainingSamples; } public KnnModel() { trainingSamples = new HashSet<TrainingSample<T>>(); } public void addTrainingSample(TrainingSample<T> sample) { trainingSamples.add(sample); } public Iterator<TrainingSample<T>> getIterator() { return trainingSamples.iterator(); } }
1,536
29.74
78
java
CERMINE
CERMINE-master/cermine-impl/src/main/java/pl/edu/icm/cermine/tools/classification/svm/SVMClassifier.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.tools.classification.svm; import java.io.BufferedReader; import java.io.FileInputStream; import java.io.IOException; import java.io.InputStreamReader; import java.util.HashMap; import java.util.Iterator; import java.util.List; import java.util.Map; import libsvm.*; import org.apache.commons.collections.iterators.ArrayIterator; import pl.edu.icm.cermine.tools.classification.general.*; import pl.edu.icm.cermine.tools.timeout.TimeoutRegister; /** * @author Pawel Szostek * * @param <S> classified object's class * @param <T> context class * @param <E> target enumeration for labels */ public abstract class SVMClassifier<S, T, E extends Enum<E>> { protected static final svm_parameter DEFAULT_PARAMETER = new svm_parameter(); static { // default values DEFAULT_PARAMETER.svm_type = svm_parameter.C_SVC; DEFAULT_PARAMETER.C = 8; DEFAULT_PARAMETER.kernel_type = svm_parameter.POLY; DEFAULT_PARAMETER.degree = 3; DEFAULT_PARAMETER.gamma = 1.0 / 8.0; // 1/k DEFAULT_PARAMETER.coef0 = 0.5; DEFAULT_PARAMETER.nu = 0.5; DEFAULT_PARAMETER.cache_size = 100; DEFAULT_PARAMETER.eps = 1e-3; DEFAULT_PARAMETER.p = 0.1; DEFAULT_PARAMETER.shrinking = 1; DEFAULT_PARAMETER.probability = 0; DEFAULT_PARAMETER.nr_weight = 0; DEFAULT_PARAMETER.weight_label = new int[0]; DEFAULT_PARAMETER.weight = new double[0]; } protected FeatureVectorBuilder<S, T> featureVectorBuilder; protected FeatureVectorScaler scaler; protected String[] featuresNames; protected svm_parameter param; protected svm_problem problem; protected svm_model model; protected Class<E> enumClassObj; public SVMClassifier(FeatureVectorBuilder<S, T> featureVectorBuilder, Class<E> enumClassObj) { this.featureVectorBuilder = featureVectorBuilder; this.enumClassObj = enumClassObj; int dimensions = featureVectorBuilder.size(); double scaledLowerBound = 0.0; double scaledUpperBound = 1.0; FeatureVectorScalerImpl lScaler = new FeatureVectorScalerImpl(dimensions, scaledLowerBound, scaledUpperBound); lScaler.setStrategy(new LinearScaling()); this.scaler = lScaler; featuresNames = featureVectorBuilder.getFeatureNames().toArray(new String[featureVectorBuilder.getFeatureNames().size()]); param = getDefaultParam(); } protected static svm_parameter clone(svm_parameter param) { svm_parameter ret = new svm_parameter(); // default values ret.svm_type = param.svm_type; ret.C = param.C; ret.kernel_type = param.kernel_type; ret.degree = param.degree; ret.gamma = param.gamma; // 1/k ret.coef0 = param.coef0; ret.nu = param.nu; ret.cache_size = param.cache_size; ret.eps = param.eps; ret.p = param.p; ret.shrinking = param.shrinking; ret.probability = param.probability; ret.nr_weight = param.nr_weight; ret.weight_label = param.weight_label; ret.weight = param.weight; return ret; } public static svm_parameter getDefaultParam() { return clone(DEFAULT_PARAMETER); } public void buildClassifier(List<TrainingSample<E>> trainingElements) { assert trainingElements.size() > 0; scaler.calculateFeatureLimits(trainingElements); problem = buildDatasetForTraining(trainingElements); model = libsvm.svm.svm_train(problem, param); } public E predictLabel(S object, T context) { svm_node[] instance = buildDatasetForClassification(object, context); TimeoutRegister.get().check(); //12s-70s int predictedVal = (int)svm.svm_predict(model, instance); TimeoutRegister.get().check(); return enumClassObj.getEnumConstants()[predictedVal]; } public E predictLabel(TrainingSample<E> sample) { svm_node[] instance = buildDatasetForClassification(sample.getFeatureVector()); TimeoutRegister.get().check(); int predictedVal = (int)svm.svm_predict(model, instance); TimeoutRegister.get().check(); return enumClassObj.getEnumConstants()[predictedVal]; } public Map<E, Double> predictProbabilities(S object, T context) { svm_node[] instance = buildDatasetForClassification(object, context); double[] probEstimates = new double[enumClassObj.getEnumConstants().length]; svm.svm_predict_probability(model, instance, probEstimates); Map<E, Double> result = new HashMap<E, Double>(); for (int i = 0; i < probEstimates.length; ++i) { result.put(enumClassObj.getEnumConstants()[model.label[i]], probEstimates[i]); } return result; } protected svm_problem buildDatasetForTraining(List<TrainingSample<E>> trainingElements) { svm_problem svmProblem = new svm_problem(); svmProblem.l = trainingElements.size(); svmProblem.x = new svm_node[svmProblem.l][trainingElements.get(0).getFeatureVector().size()]; svmProblem.y = new double[svmProblem.l]; int elemIdx = 0; for (TrainingSample<E> trainingElem : trainingElements) { FeatureVector scaledFV = scaler.scaleFeatureVector(trainingElem.getFeatureVector()); int featureIdx = 0; for (double val : scaledFV.getValues()) { svm_node cur = new svm_node(); cur.index = featureIdx; cur.value = val; svmProblem.x[elemIdx][featureIdx] = cur; ++featureIdx; } svmProblem.y[elemIdx] = trainingElem.getLabel().ordinal(); ++elemIdx; } return svmProblem; } protected svm_node[] buildDatasetForClassification(FeatureVector fv) { FeatureVector scaled = scaler.scaleFeatureVector(fv); svm_node[] ret = new svm_node[featureVectorBuilder.size()]; int featureIdx = 0; for (double val : scaled.getValues()) { svm_node cur = new svm_node(); cur.index = featureIdx; cur.value = val; ret[featureIdx] = cur; ++featureIdx; } return ret; } protected svm_node[] buildDatasetForClassification(S object, T context) { return buildDatasetForClassification(featureVectorBuilder.getFeatureVector(object, context)); } public double[] getWeights() { double[][] coef = model.sv_coef; double[][] prob = new double[model.SV.length][featureVectorBuilder.size()]; for (int i = 0; i < model.SV.length; i++) { for (int j = 0; j < model.SV[i].length; j++) { prob[i][j] = model.SV[i][j].value; } } double w_list[][][] = new double[model.nr_class][model.nr_class - 1][model.SV[0].length]; for (int i = 0; i < model.SV[0].length; ++i) { for (int j = 0; j < model.nr_class - 1; ++j) { int index = 0; int end; double acc; for (int k = 0; k < model.nr_class; ++k) { acc = 0.0; index += (k == 0) ? 0 : model.nSV[k - 1]; end = index + model.nSV[k]; for (int m = index; m < end; ++m) { acc += coef[j][m] * prob[m][i]; } w_list[k][j][i] = acc; } } } double[] weights = new double[model.SV[0].length]; for (int i = 0; i < model.nr_class - 1; ++i) { for (int j = i + 1, k = i; j < model.nr_class; ++j, ++k) { for (int m = 0; m < model.SV[0].length; ++m) { weights[m] = (w_list[i][k][m] + w_list[j][i][m]); } } } return weights; } public void loadModelFromResources(String modelFilePath, String rangeFilePath) throws IOException { InputStreamReader modelISR = new InputStreamReader(SVMClassifier.class.getResourceAsStream(modelFilePath), "UTF-8"); BufferedReader modelFile = new BufferedReader(modelISR); InputStreamReader rangeISR = new InputStreamReader(SVMClassifier.class.getResourceAsStream(rangeFilePath), "UTF-8"); BufferedReader rangeFile = new BufferedReader(rangeISR); loadModelFromFile(modelFile, rangeFile); } public void loadModelFromFile(String modelFilePath, String rangeFilePath) throws IOException { BufferedReader modelFile = new BufferedReader(new InputStreamReader(new FileInputStream(modelFilePath), "UTF-8")); BufferedReader rangeFile = null; if (rangeFilePath != null) { rangeFile = new BufferedReader(new InputStreamReader(new FileInputStream(rangeFilePath), "UTF-8")); } loadModelFromFile(modelFile, rangeFile); } public void loadModelFromFile(BufferedReader modelFile, BufferedReader rangeFile) throws IOException { if (rangeFile == null) { this.scaler = new FeatureVectorScalerNoOp(); } else { FeatureVectorScalerImpl lScaler = FeatureVectorScalerImpl.fromRangeReader(rangeFile); if (lScaler.getLimits().length != featureVectorBuilder.size()) { throw new IllegalArgumentException("Supplied .range file has " + "wrong number of features (got " + lScaler.getLimits().length + ", expected " + featureVectorBuilder.size() + " )"); } this.scaler = lScaler; } this.model = svm.svm_load_model(modelFile); } public void saveModel(String modelPath) throws IOException { scaler.saveRangeFile(modelPath + ".range"); svm.svm_save_model(modelPath, model); } public void printWeigths(FeatureVectorBuilder<S, T> vectorBuilder) { List<String> fnames = featureVectorBuilder.getFeatureNames(); Iterator<String> namesIt = fnames.iterator(); Iterator<Double> valueIt = (Iterator<Double>) new ArrayIterator(getWeights()); assert fnames.size() == getWeights().length; while (namesIt.hasNext() && valueIt.hasNext()) { String name = namesIt.next(); Double val = valueIt.next(); System.out.println(name + " " + val); } } public void setParameter(svm_parameter param) { this.param = param; } }
11,060
37.010309
130
java
CERMINE
CERMINE-master/cermine-impl/src/main/java/pl/edu/icm/cermine/tools/classification/svm/SVMZoneClassifier.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.tools.classification.svm; import java.io.*; import java.util.ArrayList; import java.util.List; import java.util.regex.Pattern; import pl.edu.icm.cermine.exception.AnalysisException; import pl.edu.icm.cermine.structure.ZoneClassifier; import pl.edu.icm.cermine.structure.model.BxDocument; import pl.edu.icm.cermine.structure.model.BxPage; import pl.edu.icm.cermine.structure.model.BxZone; import pl.edu.icm.cermine.structure.model.BxZoneLabel; import pl.edu.icm.cermine.tools.classification.general.FeatureVector; import pl.edu.icm.cermine.tools.classification.general.FeatureVectorBuilder; import pl.edu.icm.cermine.tools.classification.general.TrainingSample; /** * @author Pawel Szostek */ public class SVMZoneClassifier extends SVMClassifier<BxZone, BxPage, BxZoneLabel> implements ZoneClassifier { public SVMZoneClassifier(FeatureVectorBuilder<BxZone, BxPage> featureVectorBuilder) { super(featureVectorBuilder, BxZoneLabel.class); } @Override public BxDocument classifyZones(BxDocument document) throws AnalysisException { for (BxZone zone : document.asZones()) { BxZoneLabel predicted = predictLabel(zone, zone.getParent()); zone.setLabel(predicted); } return document; } public static List<TrainingSample<BxZoneLabel>> loadProblem(String path, FeatureVectorBuilder<BxZone, BxPage> fvb) throws IOException { File file = new File(path); return loadProblem(file, fvb); } public static List<TrainingSample<BxZoneLabel>> loadProblem(File file, FeatureVectorBuilder<BxZone, BxPage> fvb) throws IOException { List<TrainingSample<BxZoneLabel>> ret = new ArrayList<TrainingSample<BxZoneLabel>>(); BufferedReader br = null; try { br = new BufferedReader(new InputStreamReader(new FileInputStream(file), "UTF-8")); String line; final Pattern partsPattern = Pattern.compile(" "); final Pattern twopartPattern = Pattern.compile(":"); while ((line = br.readLine()) != null) { String[] parts = partsPattern.split(line); BxZoneLabel label = BxZoneLabel.values()[Integer.parseInt(parts[0])]; FeatureVector fv = new FeatureVector(); List<String> featureNames = fvb.getFeatureNames(); for (int partIdx = 1; partIdx < parts.length; ++partIdx) { String[] subparts = twopartPattern.split(parts[partIdx]); fv.addFeature(featureNames.get(partIdx - 1), Double.parseDouble(subparts[1])); } TrainingSample<BxZoneLabel> sample = new TrainingSample<BxZoneLabel>(fv, label); ret.add(sample); } } finally { if (br != null) { br.close(); } } return ret; } }
3,640
41.835294
139
java
CERMINE
CERMINE-master/cermine-impl/src/main/java/pl/edu/icm/cermine/tools/timeout/Timeout.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.tools.timeout; import com.google.common.base.Preconditions; /** * Class that throws an exception when given amount of time has already passed * when its {@link #check()} method is called. * * @author Mateusz Kobos */ public class Timeout { private final long deadlineMillis; /** * Create a new instance with the deadline set corresponding to given * timeout value. If the timeout is set to 0, the first call of * {@link #check()} method will result in throwing the * {@link TimeoutException}. * * @param timeoutMillis timeout in milliseconds */ public Timeout(long timeoutMillis) { Preconditions.checkArgument(timeoutMillis >= 0); long startTime = getCurrentTime(); this.deadlineMillis = startTime + timeoutMillis; } /** * Create a new instance and with the deadline set in an unattainable * future. */ public Timeout() { this.deadlineMillis = Long.MAX_VALUE; } /** * Throw exception if it already is the deadline time or past it. * * @throws TimeoutException TimeoutException */ public void check() throws TimeoutException { long currTimeMillis = getCurrentTime(); if (currTimeMillis >= deadlineMillis) { throw new TimeoutException(currTimeMillis, deadlineMillis); } } private static long getCurrentTime() { return System.currentTimeMillis(); } /** * Return the timeout corresponding to the more immediate deadline. * @param t0 timeout * @param t1 timeout * @return earlier timeout */ public static Timeout min(Timeout t0, Timeout t1) { if (t0.deadlineMillis < t1.deadlineMillis) { return t0; } else { return t1; } } }
2,575
29.666667
78
java
CERMINE
CERMINE-master/cermine-impl/src/main/java/pl/edu/icm/cermine/tools/timeout/TimeoutRegister.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.tools.timeout; import com.google.common.base.Preconditions; /** * Thread-local singleton for setting and removing timeout for the thread. * <br> * The standard way of using this class in order to set timeout is to: * <ul> * <li>Register the timeout using {@link #set(Timeout)} method.</li> * <li>Call {@link #get()} to retrieve the {@link Timeout} object. User can * subsequently use the {@link Timeout} object to check if the timeout time has * passed or not.</li> * <li>Remove the timeout from the register {@link #remove()}, i.e., remove the * timeout. After removal, if {@link #get()} is called to get the * {@link Timeout} object, an object will be returned with no timeout set.</li> * </ul> * * Typical usage: * <pre> * <code> * try { * TimeoutRegister.set(new Timeout(300)); * doStuff(); * } finally { * TimeoutRegister.remove(); * } * </code> * </pre> * * @author Mateusz Kobos */ public class TimeoutRegister { private static final Timeout NO_TIMEOUT = new Timeout(); private static final ThreadLocal<Timeout> INSTANCE = new ThreadLocal<Timeout>() { @Override protected Timeout initialValue() { return NO_TIMEOUT; } }; public static Timeout get() { return INSTANCE.get(); } public static void set(Timeout timeout) { Preconditions.checkNotNull(timeout); INSTANCE.set(timeout); } public static void remove() { INSTANCE.remove(); } }
2,247
29.378378
85
java
CERMINE
CERMINE-master/cermine-impl/src/main/java/pl/edu/icm/cermine/tools/timeout/TimeoutException.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.tools.timeout; /** * @author Mateusz Kobos */ public class TimeoutException extends RuntimeException { private static final long serialVersionUID = 1L; public TimeoutException(long currentTimeMillis, long deadlineMillis) { super(String.format("Timeout occured: when checked, it was " + "%d milliseconds past the deadline time", currentTimeMillis - deadlineMillis)); } /** * Constructor to be used when you want to re-throw a timeout-related * exception. * * @param ex original exception */ public TimeoutException(Exception ex) { super(ex); } }
1,411
31.837209
78
java
CERMINE
CERMINE-master/cermine-impl/src/main/java/pl/edu/icm/cermine/tools/distance/FeatureVectorDistanceMetric.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.tools.distance; import pl.edu.icm.cermine.tools.classification.general.FeatureVector; /** * Feature vector distance metric interface. * * @author Dominika Tkaczyk (d.tkaczyk@icm.edu.pl) */ public interface FeatureVectorDistanceMetric { /** * Calculates distance between two feature vectors. * * @param vector1 vector * @param vector2 vector * @return the distance */ double getDistance(FeatureVector vector1, FeatureVector vector2); }
1,250
30.275
78
java
CERMINE
CERMINE-master/cermine-impl/src/main/java/pl/edu/icm/cermine/tools/distance/CosineDistance.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.tools.distance; import java.util.HashMap; import java.util.List; import java.util.Map; import java.util.Map.Entry; /** * @author Pawel Szostek */ public class CosineDistance { private Map<String, Integer> calculateVector(List<String> tokens) { HashMap<String, Integer> vector = new HashMap<String, Integer>(); for (String token : tokens) { if (vector.containsKey(token)) { vector.put(token, vector.get(token) + 1); } else { vector.put(token, 1); } } return vector; } private double vectorLength(Map<String, Integer> vector) { double ret = 0.0; for (Entry<String, Integer> entry : vector.entrySet()) { ret += entry.getValue() * entry.getValue(); } return Math.sqrt(ret); } private double dotProduct(Map<String, Integer> vector1, Map<String, Integer> vector2) { double ret = 0.0; for (Entry<String, Integer> entry : vector1.entrySet()) { if (vector2.containsKey(entry.getKey())) { ret += entry.getValue() * vector2.get(entry.getKey()); } } return ret; } public double compare(List<String> s1, List<String> s2) { Map<String, Integer> v1 = calculateVector(s1); Map<String, Integer> v2 = calculateVector(s2); return dotProduct(v1, v2) / (vectorLength(v1) * vectorLength(v2)); } }
2,220
31.661765
91
java
CERMINE
CERMINE-master/cermine-impl/src/main/java/pl/edu/icm/cermine/tools/distance/SmithWatermanDistance.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.tools.distance; import java.util.List; /** * @author Pawel Szostek */ public class SmithWatermanDistance { private final double mu; private final double delta; public SmithWatermanDistance(double mu, double delta) { this.mu = mu; this.delta = delta; } private double similarityScore(String a, String b) { double result; if (a.equals(b)) { result = 1.; } else { result = -mu; } return result; } private double findArrayMax(double array[]) { double max = array[0]; // start with max = first element for (int i = 1; i < array.length; i++) { if (array[i] > max) { max = array[i]; } } return max; // return highest value in array } private enum Move { OMIT_S1, OMIT_S2, OMIT_BOTH, MATCH, NN }; public double compare(List<String> s1, List<String> s2) { int N_a = s1.size(); // get the actual lengths of the sequences int N_b = s2.size(); // initialize H double H[][] = new double[N_a + 1][N_b + 1]; for (int i = 0; i <= N_a; i++) { for (int j = 0; j <= N_b; j++) { H[i][j] = 0; } } double temp[] = new double[4]; // here comes the actual algorithm for (int i = 1; i <= N_a; i++) { for (int j = 1; j <= N_b; j++) { temp[0] = H[i - 1][j - 1] + similarityScore(s1.get(i - 1), s2.get(j - 1)); temp[1] = H[i - 1][j] - delta; temp[2] = H[i][j - 1] - delta; temp[3] = 0.; H[i][j] = findArrayMax(temp); } } // search H for the maximal score double H_max = 0.; for (int i = 1; i <= N_a; i++) { for (int j = 1; j <= N_b; j++) { if (H[i][j] > H_max) { H_max = H[i][j]; } } } return H_max; } }
2,857
27.019608
91
java
CERMINE
CERMINE-master/cermine-impl/src/main/java/pl/edu/icm/cermine/tools/distance/FeatureVectorEuclideanMetric.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.tools.distance; import com.google.common.collect.Sets; import java.util.List; import pl.edu.icm.cermine.tools.classification.general.FeatureVector; /** * @author Dominika Tkaczyk (d.tkaczyk@icm.edu.pl) */ public class FeatureVectorEuclideanMetric implements FeatureVectorDistanceMetric { @Override public double getDistance(FeatureVector vector1, FeatureVector vector2) { double sum = 0; List<String> featureNames1 = vector1.getFeatureNames(); List<String> featureNames2 = vector2.getFeatureNames(); if (Sets.newHashSet(featureNames1).equals(Sets.newHashSet(featureNames2))) { for (String feature : featureNames1) { sum += Math.pow(vector1.getValue(feature) - vector2.getValue(feature), 2); } } else { for (int i = 0; i < vector1.size(); i++) { sum += Math.pow(vector1.getValue(i) - vector2.getValue(i), 2); } } return Math.sqrt(sum); } }
1,766
35.061224
90
java
CERMINE
CERMINE-master/cermine-impl/src/main/java/pl/edu/icm/cermine/tools/distance/LevenshteinDistance.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.tools.distance; import java.util.ArrayList; import java.util.List; /** * @author Pawel Szostek */ public class LevenshteinDistance { public Integer compare(List<String> s1, List<String> s2) { int retval; final int n = s1.size(); final int m = s2.size(); if (n == 0) { retval = m; } else if (m == 0) { retval = n; } else { retval = compare(s1, n, s2, m); } return retval; } public Integer compareRec(List<String> tokens1, List<String> tokens2) { Integer length1 = tokens1.size(); Integer length2 = tokens2.size(); Integer distance = 0; if (length1 == 0) { return length2; } else if (length2 == 0) { return length1; } else { if (!tokens1.get(0).equals(tokens2.get(0))) { distance = 1; } return min3(compareRec(slice(tokens1, 1, length1 - 1), tokens2) + 1, compareRec(tokens1, slice(tokens2, 1, length2 - 1)) + 1, compareRec(slice(tokens1, 1, length1 - 1), slice(tokens2, 1, length2 - 1)) + distance); } } private static <T> List<T> slice(List<T> list, int index, int count) { List<T> result = new ArrayList<T>(); if (index >= 0 && index < list.size()) { int end = index + count < list.size() ? index + count : list.size(); for (int i = index; i < end; i++) { result.add(list.get(i)); } } return result; } private int compare(List<String> s1, final int n, List<String> s2, final int m) { int matrix[][] = new int[n + 1][m + 1]; for (int i = 0; i <= n; i++) { matrix[i][0] = i; } for (int i = 0; i <= m; i++) { matrix[0][i] = i; } for (int i = 1; i <= n; i++) { String s1i = s1.get(i - 1); for (int j = 1; j <= m; j++) { String s2j = s2.get(j - 1); final int cost = s1i.equals(s2j) ? 0 : 1; matrix[i][j] = min3(matrix[i - 1][j] + 1, matrix[i][j - 1] + 1, matrix[i - 1][j - 1] + cost); } } return matrix[n][m]; } private int min3(final int a, final int b, final int c) { return Math.min(Math.min(a, b), c); } }
3,191
31.907216
107
java
CERMINE
CERMINE-master/cermine-impl/src/main/java/pl/edu/icm/cermine/tools/statistics/Population.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.tools.statistics; import com.google.common.collect.HashMultiset; import com.google.common.collect.Multiset; /** * @author Dominika Tkaczyk (d.tkaczyk@icm.edu.pl) */ public class Population { private final Multiset<Double> observations = HashMultiset.create(); private double mean = Double.NaN; private double sd = Double.NaN; public void addObservation(double observation) { observations.add(observation); mean = Double.NaN; sd = Double.NaN; } public void reset() { observations.clear(); mean = Double.NaN; sd = Double.NaN; } public double getMean() { if (!Double.isNaN(mean)) { return mean; } mean = 0; for (double observation : observations) { mean += observation; } mean = mean / observations.size(); return mean; } public double getSD() { if (!Double.isNaN(sd)) { return sd; } double sse = 0; for (double observation : observations) { sse += Math.pow(observation - getMean(), 2); } sd = Math.sqrt(sse / observations.size()); return sd; } public double getZScore(double observation) { return (observation - getMean()) / getSD(); } }
2,112
27.173333
78
java
CERMINE
CERMINE-master/cermine-impl/src/main/java/pl/edu/icm/cermine/tools/statistics/ProbabilityDistribution.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.tools.statistics; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.Map; /** A Generic container for keeping information on events' probabilities. * * @param <E> is a type of the event (i.e. observations, states) * @author Dominika Tkaczyk (d.tkaczyk@icm.edu.pl) */ public class ProbabilityDistribution<E> { private final Map<E, Integer> eventCount = new HashMap<E, Integer>(); private int totalCount = 0; public void addEvent(E event) { if (!eventCount.containsKey(event)) { eventCount.put(event, 0); } eventCount.put(event, eventCount.get(event) + 1); totalCount++; } public void removeEvent(E event) { if (eventCount.containsKey(event) && eventCount.get(event) > 0) { eventCount.put(event, eventCount.get(event) - 1); totalCount--; } } public List<E> getEvents() { return new ArrayList<E>(eventCount.keySet()); } public int getEventCount(E event) { return eventCount.containsKey(event) ? eventCount.get(event) : 0; } public double getProbability(E event) { return (totalCount == 0 || !eventCount.containsKey(event)) ? (double) 0 : (double) eventCount.get(event) / (double) totalCount; } public double getEntropy() { if (totalCount == 0) { return 0; } double entropy = 0; for (E event : eventCount.keySet()) { double probability = getProbability(event); if (probability > 0) { entropy -= probability * Math.log(probability) / Math.log(2); } } return entropy; } }
2,486
29.703704
78
java
CERMINE
CERMINE-master/cermine-impl/src/main/java/pl/edu/icm/cermine/tools/transformers/FormatToModelReader.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.tools.transformers; import java.io.Reader; import java.util.List; import pl.edu.icm.cermine.exception.TransformationException; /** * Interface for readers of model objects. * * @author Dominika Tkaczyk (d.tkaczyk@icm.edu.pl) * @param <T> the type of model */ public interface FormatToModelReader<T> { /** * Reads the format into the model object. * * @param string input object in a certain format * @param hints additional hints used during the conversion * @return a model object * @throws TransformationException TransformationException */ T read(String string, Object... hints) throws TransformationException; /** * Reads the format into the list of model objects. * * @param string input object in a certain format * @param hints additional hints used during the conversion * @return a list of model object * @throws TransformationException TransformationException */ List<T> readAll(String string, Object... hints) throws TransformationException; /** * Reads the format into the model object. * * @param reader input reader * @param hints additional hints used during the conversion * @return a model object * @throws TransformationException TransformationException */ T read(Reader reader, Object... hints) throws TransformationException; /** * Reads the format into the model object. * * @param reader input reader * @param hints additional hints used during the conversion * @return a list of model objects * @throws TransformationException TransformationException */ List<T> readAll(Reader reader, Object... hints) throws TransformationException; }
2,523
33.575342
83
java
CERMINE
CERMINE-master/cermine-impl/src/main/java/pl/edu/icm/cermine/tools/transformers/ModelToModelConverter.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.tools.transformers; import java.util.List; import pl.edu.icm.cermine.exception.TransformationException; /** * Interface for converters between models. * * @author Dominika Tkaczyk (d.tkaczyk@icm.edu.pl) * @param <S> type of input model * @param <T> type of output model */ public interface ModelToModelConverter<S, T> { /** * Converts source model into the target model. * * @param source the source object * @param hints additional hints used during the conversion * @return the converted object * @throws TransformationException TransformationException */ T convert(S source, Object... hints) throws TransformationException; /** * Converts source model into the target model. * * @param source the list of source objects * @param hints additional hints used during the conversion * @return the list of converted objects * @throws TransformationException TransformationException */ List<T> convertAll(List<S> source, Object... hints) throws TransformationException; }
1,839
33.716981
87
java
CERMINE
CERMINE-master/cermine-impl/src/main/java/pl/edu/icm/cermine/tools/transformers/ModelToFormatWriter.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.tools.transformers; import java.io.Writer; import java.util.List; import pl.edu.icm.cermine.exception.TransformationException; /** * Interface for writers of model objects. * * @author Dominika Tkaczyk (d.tkaczyk@icm.edu.pl) * @param <T> the type of model */ public interface ModelToFormatWriter<T> { /** * Writes a model object to a string. * * @param object a model object * @param hints additional hints used during the conversion * @return written object * @throws TransformationException TransformationException */ String write(T object, Object... hints) throws TransformationException; /** * Writes a list of model objects to a string. * * @param objects a list of model objects * @param hints additional hints used during the conversion * @return written object * @throws TransformationException TransformationException */ String writeAll(List<T> objects, Object... hints) throws TransformationException; /** * Writes a model object using the given writer. * * @param writer writer * @param object a model object * @param hints additional hints used during the conversion * @throws TransformationException TransformationException */ void write(Writer writer, T object, Object... hints) throws TransformationException; /** * Writes a list of model objects using the given writer. * * @param writer writer * @param objects a list of model objects * @param hints additional hints used during the conversion * @throws TransformationException TransformationException */ void writeAll(Writer writer, List<T> objects, Object... hints) throws TransformationException; }
2,538
33.310811
98
java
CERMINE
CERMINE-master/cermine-impl/src/main/java/pl/edu/icm/cermine/configuration/ExtractionConfigRegister.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.configuration; import com.google.common.base.Preconditions; /** * Loader of configuration properties for {@link pl.edu.icm.cermine.ContentExtractor} * * @author madryk */ public class ExtractionConfigRegister { private static final ThreadLocal<ExtractionConfig> INSTANCE = new ThreadLocal<ExtractionConfig>() { @Override protected ExtractionConfig initialValue() { return new ExtractionConfigBuilder().buildConfiguration(); } }; public static void set(ExtractionConfig config) { Preconditions.checkNotNull(config); INSTANCE.set(config); } public static ExtractionConfig get() { return INSTANCE.get(); } public static void remove() { INSTANCE.remove(); } }
1,560
29.019231
85
java
CERMINE
CERMINE-master/cermine-impl/src/main/java/pl/edu/icm/cermine/configuration/ExtractionConfigBuilder.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.configuration; import java.io.File; import java.net.URL; import java.util.HashMap; import java.util.Iterator; import org.apache.commons.configuration.Configuration; import org.apache.commons.configuration.ConfigurationException; import org.apache.commons.configuration.MapConfiguration; import org.apache.commons.configuration.PropertiesConfiguration; /** * Loader of configuration properties for {@link pl.edu.icm.cermine.ContentExtractor} * * @author madryk */ public class ExtractionConfigBuilder { private static final String DEFAULT_CONFIGURATION_CLASSPATH = "pl/edu/icm/cermine/application-default.properties"; private static final Configuration DEFAULT_OTHER = new MapConfiguration(new HashMap<String, Object>()); static { DEFAULT_OTHER.addProperty(ExtractionConfigProperty.IMAGES_EXTRACTION.getPropertyKey(), true); } private final Configuration configuration; public ExtractionConfigBuilder() { // prevents MALLET from printing info messages System.setProperty("java.util.logging.config.file", "edu/umass/cs/mallet/base/util/resources/logging.properties"); this.configuration = new MapConfiguration(new HashMap<String, Object>()); URL propertiesUrl = ExtractionConfigBuilder.class.getClassLoader().getResource(DEFAULT_CONFIGURATION_CLASSPATH); try { update(new PropertiesConfiguration(propertiesUrl)); } catch (ConfigurationException e) { throw new RuntimeException("Unable to load default configuration", e); } update(DEFAULT_OTHER); } public ExtractionConfigBuilder addConfiguration(String configurationFilePath) { try { update(new PropertiesConfiguration(new File(configurationFilePath))); } catch (ConfigurationException e) { throw new RuntimeException("Unable to load configuration from file " + configurationFilePath, e); } return this; } public ExtractionConfigBuilder addConfiguration(Configuration config) { update(config); return this; } public ExtractionConfigBuilder setProperty(ExtractionConfigProperty property, Object value) { configuration.setProperty(property.getPropertyKey(), value); return this; } public ExtractionConfig buildConfiguration() { return new ExtractionConfig(configuration); } private void update(Configuration conf) { Iterator<String> it = conf.getKeys(); while (it.hasNext()) { String key = it.next(); configuration.setProperty(key, conf.getProperty(key)); } } }
3,433
36.326087
120
java
CERMINE
CERMINE-master/cermine-impl/src/main/java/pl/edu/icm/cermine/configuration/ExtractionConfig.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.configuration; import org.apache.commons.configuration.Configuration; /** * Class that holds configuration for {@link pl.edu.icm.cermine.ContentExtractor}.<br> * An object of this class can be obtained by {@link pl.edu.icm.cermine.configuration.ExtractionConfigRegister} * * @author madryk */ public class ExtractionConfig { private final Configuration configuration; /** * Default constructor * * @param configuration - configuration object that contains all the configuration properties * available to {@link ContentExtractor} */ ExtractionConfig(Configuration configuration) { this.configuration = configuration; } /** * Returns value of the configuration property * @param property property * @return property value */ public String getStringProperty(ExtractionConfigProperty property) { return configuration.getString(property.getPropertyKey()); } public boolean getBooleanProperty(ExtractionConfigProperty property) { return configuration.getBoolean(property.getPropertyKey()); } }
1,887
32.714286
111
java
CERMINE
CERMINE-master/cermine-impl/src/main/java/pl/edu/icm/cermine/configuration/ExtractionConfigProperty.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.configuration; /** * Enumeration that contains all available configuration properties for * {@link pl.edu.icm.cermine.ContentExtractor} * * @author Dominika Tkaczyk (d.tkaczyk@icm.edu.pl) */ public enum ExtractionConfigProperty { INITIAL_ZONE_CLASSIFIER_MODEL_PATH ("zoneClassifier.initial.model"), INITIAL_ZONE_CLASSIFIER_RANGE_PATH ("zoneClassifier.initial.ranges"), METADATA_ZONE_CLASSIFIER_MODEL_PATH ("zoneClassifier.metadata.model"), METADATA_ZONE_CLASSIFIER_RANGE_PATH ("zoneClassifier.metadata.ranges"), CONTENT_FILTER_MODEL_PATH ("contentFilter.model"), CONTENT_FILTER_RANGE_PATH ("contentFilter.ranges"), BIBREF_MODEL_PATH ("bibref.model"), BIBREF_TERMS_PATH ("bibref.terms"), BIBREF_JOURNALS_PATH ("bibref.journals"), BIBREF_SURNAMES_PATH ("bibref.surnames"), BIBREF_INSTITUTIONS_PATH ("bibref.institutions"), IMAGES_EXTRACTION ("images.extraction"), DEBUG_PRINT_TIME ("debug.print.time"); private final String propertyKey; private ExtractionConfigProperty(String propertyKey) { this.propertyKey = propertyKey; } public String getPropertyKey() { return propertyKey; } }
2,105
34.694915
78
java
CERMINE
CERMINE-master/cermine-impl/src/main/java/pl/edu/icm/cermine/structure/DocstrumSegmenterOrig.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; import com.google.common.collect.Lists; import java.util.*; import pl.edu.icm.cermine.exception.AnalysisException; import pl.edu.icm.cermine.structure.model.*; import pl.edu.icm.cermine.structure.tools.BxBoundsBuilder; import pl.edu.icm.cermine.structure.tools.BxModelUtils; import pl.edu.icm.cermine.tools.DisjointSets; import pl.edu.icm.cermine.tools.Histogram; /** * Page segmenter using Docstrum algorithm. * * @author Krzysztof Rusek */ public class DocstrumSegmenterOrig implements DocumentSegmenter { public static final int MAX_ZONES_PER_PAGE = 300; public static final int PAGE_MARGIN = 2; public static final double ORIENTATION_MARGIN = 0.2; public static final int LINES_PER_PAGE_MARGIN = 100; private double docOrientation = Double.NaN; private Map<BxPage, List<Component>> componentMap = new HashMap<BxPage, List<Component>>(); @Override public BxDocument segmentDocument(BxDocument document) throws AnalysisException { computeDocumentOrientation(document); BxDocument output = new BxDocument(); for (BxPage page: document) { BxPage segmentedPage = segmentPage(page); if (segmentedPage.getBounds() != null) { output.addPage(segmentedPage); } } return output; } protected void computeDocumentOrientation(BxDocument document) throws AnalysisException { List<Component> components = new ArrayList<Component>(); for (BxPage page : document.asPages()) { List<Component> pageComponents = createComponents(page); componentMap.put(page, pageComponents); components.addAll(pageComponents); } docOrientation = computeInitialOrientation(components); } protected void computeDocumentOrientation(Map<BxPage, List<Component>> componentMap) throws AnalysisException { this.componentMap = componentMap; List<Component> components = new ArrayList<Component>(); for (Map.Entry<BxPage, List<Component>> entry : componentMap.entrySet()) { components.addAll(entry.getValue()); } docOrientation = computeInitialOrientation(components); } protected BxPage segmentPage(BxPage page) throws AnalysisException { List<Component> components = componentMap.get(page); double orientation = docOrientation; if (Double.isNaN(orientation)) { orientation = computeInitialOrientation(components); } double characterSpacing = computeCharacterSpacing(components, orientation); double lineSpacing = computeLineSpacing(components, orientation); double spacing = computeSpacing(components); List<ComponentLine> lines = determineLines(components, orientation, spacing * 2, spacing * 2); if (Math.abs(orientation) > ORIENTATION_MARGIN) { List<ComponentLine> linesZero = determineLines(components, 0, characterSpacing * COMP_DIST_CHAR, lineSpacing * MAX_VERTICAL_COMP_DIST); if (Math.abs(lines.size() - LINES_PER_PAGE_MARGIN) > Math.abs(linesZero.size() - LINES_PER_PAGE_MARGIN)) { orientation = 0; lines = linesZero; } } double lineOrientation = computeOrientation(lines); if (!Double.isNaN(lineOrientation)) { orientation = lineOrientation; } List<List<ComponentLine>> zones = determineZones(lines, orientation, characterSpacing * MIN_HORIZONTAL_DIST, Double.POSITIVE_INFINITY, lineSpacing * MIN_VERTICAL_DIST, lineSpacing * MAX_VERTICAL_DIST, characterSpacing * MIN_HORIZONTAL_MERGE_DIST, 0.0, 0.0, lineSpacing * MAX_VERTICAL_MERGE_DIST); return convertToBxModel(page, zones, WORD_DIST_MULT * characterSpacing); } /** * Constructs sorted by x coordinate array of components from page's chunks. * * @param page page containing chunks * @return array of components * @throws AnalysisException AnalysisException */ protected List<Component> createComponents(BxPage page) throws AnalysisException { List<BxChunk> chunks = Lists.newArrayList(page.getChunks()); Component[] components = new Component[chunks.size()]; for (int i = 0; i < components.length; i++) { try { components[i] = new Component(chunks.get(i)); } catch(IllegalArgumentException ex) { throw new AnalysisException(ex); } } Arrays.sort(components, ComponentXComparator.getInstance()); findNeighbors(components); return Arrays.asList(components); } /** * Performs for each component search for nearest-neighbors and stores the * result in component's neighbors attribute. * * @param components array of components * @throws AnalysisException if the number of components is less than or * equal to the number of nearest-neighbors per component. */ private void findNeighbors(Component[] components) throws AnalysisException { if (components.length == 0) { return; } if (components.length == 1) { components[0].setNeighbors(new ArrayList<Neighbor>()); return; } int pageNeighborCount = NEIGHBOUR_COUNT; if (components.length <= NEIGHBOUR_COUNT) { pageNeighborCount = components.length - 1; } List<Neighbor> candidates = new ArrayList<Neighbor>(); for (int i = 0; i < components.length; i++) { int start = i, end = i + 1; // Contains components from components array // from ranges [start, i) and [i+1, end) double dist = Double.POSITIVE_INFINITY; for (double searchDist = 0; searchDist < dist; ) { searchDist += DISTANCE_STEP; boolean newCandidatesFound = false; while (start > 0 && components[i].getX() - components[start - 1].getX() < searchDist) { start--; candidates.add(new Neighbor(components[start], components[i])); if (candidates.size() > pageNeighborCount) { Collections.sort(candidates, NeighborDistanceComparator.getInstance()); candidates.subList(pageNeighborCount, candidates.size()).clear(); } newCandidatesFound = true; } while (end < components.length && components[end].getX() - components[i].getX() < searchDist) { candidates.add(new Neighbor(components[end], components[i])); if (candidates.size() > pageNeighborCount) { Collections.sort(candidates, NeighborDistanceComparator.getInstance()); candidates.subList(pageNeighborCount, candidates.size()).clear(); } end++; newCandidatesFound = true; } if (newCandidatesFound && candidates.size() >= pageNeighborCount) { Collections.sort(candidates, NeighborDistanceComparator.getInstance()); dist = candidates.get(pageNeighborCount - 1).getDistance(); } } candidates.subList(pageNeighborCount, candidates.size()).clear(); components[i].setNeighbors(new ArrayList<Neighbor>(candidates)); candidates.clear(); } } /** * Computes initial orientation estimation based on nearest-neighbors' angles. * * @param components components * @return initial orientation estimation */ private double computeInitialOrientation(List<Component> components) { Histogram histogram = new Histogram(-Math.PI/2, Math.PI/2, ANGLE_HIST_RESOLUTION); for (Component component : components) { for (Neighbor neighbor : component.getNeighbors()) { histogram.add(neighbor.getAngle()); } } histogram.circularSmooth(1); return histogram.getPeakValue(); } private double computeSpacing(List<Component> components) { double maxDistance = Double.NEGATIVE_INFINITY; for (Component component : components) { for (Neighbor neighbor : component.getNeighbors()) { maxDistance = Math.max(maxDistance, neighbor.getDistance()); } } Histogram histogram = new Histogram(0, maxDistance, SPACING_HIST_RESOLUTION); for (Component component : components) { for (Neighbor neighbor : component.getNeighbors()) { histogram.add(neighbor.getDistance()); } } histogram.smooth(1); return histogram.getPeakValue(); } /** * Computes within-line spacing based on nearest-neighbors distances. * * @param components components * @param orientation estimated text orientation * @return estimated within-line spacing */ private double computeCharacterSpacing(List<Component> components, double orientation) { return computeSpacing(components, orientation); } /** * Computes between-line spacing based on nearest-neighbors distances. * * @param components * @param orientation estimated text orientation * @return estimated between-line spacing */ private double computeLineSpacing(List<Component> components, double orientation) { if (orientation >= 0) { return computeSpacing(components, orientation - Math.PI / 2); } else { return computeSpacing(components, orientation + Math.PI / 2); } } private double computeSpacing(List<Component> components, double angle) { double maxDistance = Double.NEGATIVE_INFINITY; for (Component component : components) { for (Neighbor neighbor : component.getNeighbors()) { maxDistance = Math.max(maxDistance, neighbor.getDistance()); } } Histogram histogram = new Histogram(0, maxDistance, SPACING_HIST_RESOLUTION); AngleFilter filter = AngleFilter.newInstance(angle - ANGLE_TOLERANCE, angle + ANGLE_TOLERANCE); for (Component component : components) { for (Neighbor neighbor : component.getNeighbors()) { if (filter.matches(neighbor)) { histogram.add(neighbor.getDistance()); } } } histogram.smooth(1); return histogram.getPeakValue(); } /** * Groups components into text lines. * * @param components * @param orientation - estimated text orientation * @param maxHorizontalDistance - maximum horizontal distance between components * @param maxVerticalDistance - maximum vertical distance between components * @return lines of components */ private List<ComponentLine> determineLines(List<Component> components, double orientation, double maxHorizontalDistance, double maxVerticalDistance) { DisjointSets<Component> sets = new DisjointSets<Component>(components); AngleFilter filter = AngleFilter.newInstance(orientation - ANGLE_TOLERANCE, orientation + ANGLE_TOLERANCE); for (Component component : components) { for (Neighbor neighbor : component.getNeighbors()) { double x = neighbor.getHorizontalDistance(orientation) / maxHorizontalDistance; double y = neighbor.getVerticalDistance(orientation) / maxVerticalDistance; if (filter.matches(neighbor) && x * x + y * y <= 1) { sets.union(component, neighbor.getComponent()); } } } List<ComponentLine> lines = new ArrayList<ComponentLine>(); for (Set<Component> group : sets) { List<Component> lineComponents = new ArrayList<Component>(group); Collections.sort(lineComponents, ComponentXComparator.getInstance()); lines.add(new ComponentLine(lineComponents, orientation)); } return lines; } private double computeOrientation(List<ComponentLine> lines) { // Compute weighted mean of line angles double valueSum = 0.0; double weightSum = 0.0; for (ComponentLine line : lines) { valueSum += line.getAngle() * line.getLength(); weightSum += line.getLength(); } return valueSum / weightSum; } private List<List<ComponentLine>> determineZones(List<ComponentLine> lines, double orientation, double minHorizontalDistance, double maxHorizontalDistance, double minVerticalDistance, double maxVerticalDistance, double minHorizontalMergeDistance, double maxHorizontalMergeDistance, double minVerticalMergeDistance, double maxVerticalMergeDistance) { DisjointSets<ComponentLine> sets = new DisjointSets<ComponentLine>(lines); for (int i = 0; i < lines.size(); i++) { ComponentLine li = lines.get(i); for (int j = i + 1; j < lines.size(); j++) { ComponentLine lj = lines.get(j); double scale = 1; // "<=" is used instead of "<" for consistency and to allow setting minVertical(Merge)Distance // to 0.0 with meaning "no minimal distance required" if (!sets.areTogether(li, lj) && li.angularDifference(lj) <= ANGLE_TOLERANCE) { double hDist = li.horizontalDistance(lj, orientation) / scale; double vDist = li.verticalDistance(lj, orientation) / scale; // Line over or above if (minHorizontalDistance <= hDist && hDist <= maxHorizontalDistance && minVerticalDistance <= vDist && vDist <= maxVerticalDistance) { sets.union(li, lj); } // Split line that needs later merging else if (minHorizontalMergeDistance <= hDist && hDist <= maxHorizontalMergeDistance && minVerticalMergeDistance <= vDist && vDist <= maxVerticalMergeDistance) { sets.union(li, lj); } } } } List<List<ComponentLine>> zones = new ArrayList<List<ComponentLine>>(); for (Set<ComponentLine> group : sets) { zones.add(new ArrayList<ComponentLine>(group)); } return zones; } /** * Converts list of zones from internal format (using components and * component lines) to BxModel. * * @param zones zones in internal format * @param wordSpacing - maximum allowed distance between components that * belong to one word * @return BxModel page */ private BxPage convertToBxModel(BxPage origPage, List<List<ComponentLine>> zones, double wordSpacing) { BxPage page = new BxPage(); List<BxPage> pages = Lists.newArrayList(origPage.getParent()); int pageIndex = pages.indexOf(origPage); boolean groupped = false; if (zones.size() > MAX_ZONES_PER_PAGE && pageIndex >= PAGE_MARGIN && pageIndex < pages.size() - PAGE_MARGIN) { List<ComponentLine> oneZone = new ArrayList<ComponentLine>(); for (List<ComponentLine> zone : zones) { oneZone.addAll(zone); } zones = new ArrayList<List<ComponentLine>>(); zones.add(oneZone); groupped = true; } for (List<ComponentLine> lines : zones) { BxZone zone = new BxZone(); if (groupped) { zone.setLabel(BxZoneLabel.GEN_OTHER); } for (ComponentLine line : lines) { zone.addLine(line.convertToBxLine(wordSpacing)); } List<BxLine> zLines = Lists.newArrayList(zone); Collections.sort(zLines, new Comparator<BxLine>() { @Override public int compare(BxLine o1, BxLine o2) { return Double.compare(o1.getBounds().getY(), o2.getBounds().getY()); } }); zone.setLines(zLines); BxBoundsBuilder.setBounds(zone); page.addZone(zone); } BxModelUtils.sortZonesYX(page); BxBoundsBuilder.setBounds(page); return page; } /** * Internal representation of character. */ protected static class Component { private final double x; private final double y; private final BxChunk chunk; private List<Neighbor> neighbors; public Component(BxChunk chunk) { BxBounds bounds = chunk.getBounds(); if (bounds == null) { throw new IllegalArgumentException("Bounds must not be null"); } if (Double.isNaN(bounds.getX()) || Double.isInfinite(bounds.getX())) { throw new IllegalArgumentException("Bounds x coordinate must be finite"); } if (Double.isNaN(bounds.getY()) || Double.isInfinite(bounds.getY())) { throw new IllegalArgumentException("Bounds y coordinate must be finite"); } if (Double.isNaN(bounds.getWidth()) || Double.isInfinite(bounds.getWidth())) { throw new IllegalArgumentException("Bounds width must be finite"); } if (Double.isNaN(bounds.getHeight()) || Double.isInfinite(bounds.getHeight())) { throw new IllegalArgumentException("Bounds height must be finite"); } this.x = chunk.getBounds().getX() + chunk.getBounds().getWidth() / 2; this.y = chunk.getBounds().getY() + chunk.getBounds().getHeight() / 2; this.chunk = chunk; } public double getX() { return x; } public double getY() { return y; } public double getHeight() { return chunk.getBounds().getHeight(); } public double distance(Component c) { double dx = getX() - c.getX(), dy = getY() - c.getY(); return Math.sqrt(dx * dx + dy * dy); } /** * Computes horizontal distance between components. * * @param c component * @param orientation orientation angle * @return distance */ public double horizontalDistance(Component c, double orientation) { // TODO: take orientation into account return Math.abs(getX() - c.getX()); } public double verticalDistance(Component c, double orientation) { return Math.abs(getY() - c.getY()); } public double horizontalBoundsDistance(Component c, double orientation) { // TODO: take orientation into account return horizontalDistance(c, orientation) - getChunk().getBounds().getWidth() / 2 - c.getChunk().getBounds().getWidth() / 2; } public BxChunk getChunk() { return chunk; } public List<Neighbor> getNeighbors() { return neighbors; } public void setNeighbors(List<Neighbor> neighbors) { this.neighbors = neighbors; } private double angle(Component c) { if (getX() > c.getX()) { return Math.atan2(getY() - c.getY(), getX() - c.getX()); } else { return Math.atan2(c.getY() - getY(), c.getX() - getX()); } } public double overlappingDistance(Component other, double orientation) { double[] xs = new double[4]; double s = Math.sin(-orientation), c = Math.cos(-orientation); xs[0] = c * x - s * y; xs[1] = c * (x+chunk.getWidth()) - s * (y+chunk.getHeight()); xs[2] = c * other.x - s * other.y; xs[3] = c * (other.x+other.chunk.getWidth()) - s * (other.y+other.chunk.getHeight()); boolean overlapping = xs[1] >= xs[2] && xs[3] >= xs[0]; Arrays.sort(xs); return Math.abs(xs[2] - xs[1]) * (overlapping ? 1 : -1); } } /** * Class representing nearest-neighbor pair. */ protected static class Neighbor { private final double distance; private final double angle; private final Component component; private final Component origin; public Neighbor(Component neighbor, Component origin) { this.distance = neighbor.distance(origin); this.angle = neighbor.angle(origin); this.component = neighbor; this.origin = origin; } public double getDistance() { return distance; } public double getHorizontalDistance(double orientation) { return component.horizontalDistance(origin, orientation); } public double getVerticalDistance(double orientation) { return component.verticalDistance(origin, orientation); } public double getAngle() { return angle; } public Component getComponent() { return component; } } /** * Component comparator based on x coordinate of the centroid of component. * * The ordering is not consistent with equals. */ protected static final class ComponentXComparator implements Comparator<Component> { private ComponentXComparator() { } @Override public int compare(Component o1, Component o2) { return Double.compare(o1.getX(), o2.getX()); } private static final ComponentXComparator INSTANCE = new ComponentXComparator(); public static ComponentXComparator getInstance() { return INSTANCE; } } /** * Neighbor distance comparator based on the distance. * * The ordering is not consistent with equals. */ protected static final class NeighborDistanceComparator implements Comparator<Neighbor> { private NeighborDistanceComparator() { } @Override public int compare(Neighbor o1, Neighbor o2) { return Double.compare(o1.getDistance(), o2.getDistance()); } private static final NeighborDistanceComparator INSTANCE = new NeighborDistanceComparator(); public static NeighborDistanceComparator getInstance() { return INSTANCE; } } /** * Internal representation of the text line. */ protected static class ComponentLine { private final double x0; private final double y0; private final double x1; private final double y1; private final double height; private final List<Component> components; public ComponentLine(List<Component> components, double orientation) { this.components = components; if (components.size() >= 2) { // Simple linear regression double sx = 0.0, sxx = 0.0, sxy = 0.0, sy = 0.0; for (Component component : components) { sx += component.getX(); sxx += component.getX() * component.getX(); sxy += component.getX() * component.getY(); sy += component.getY(); } double b = (components.size() * sxy - sx * sy) / (components.size() * sxx - sx * sx); double a = (sy - b * sx) / components.size(); this.x0 = components.get(0).getX(); this.y0 = a + b * this.x0; this.x1 = components.get(components.size() - 1).getX(); this.y1 = a + b * this.x1; } else if (! components.isEmpty()) { Component component = components.get(0); double dx = component.getChunk().getBounds().getWidth() / 3; double dy = dx * Math.tan(orientation); this.x0 = component.getX() - dx; this.x1 = component.getX() + dx; this.y0 = component.getY() - dy; this.y1 = component.getY() + dy; } else { throw new IllegalArgumentException("Component list must not be empty"); } height = computeHeight(); } public double getAngle() { return Math.atan2(y1 - y0, x1 - x0); } public double getSlope() { return (y1 - y0) / (x1 - x0); } public double getLength() { return Math.sqrt((x0 - x1) * (x0 - x1) + (y0 - y1) * (y0 - y1)); } private double computeHeight() { double sum = 0.0; for (Component component : components) { sum += component.getHeight(); } return sum / components.size(); } public double getHeight() { return height; } public List<Component> getComponents() { return components; } public double angularDifference(ComponentLine j) { double diff = Math.abs(getAngle() - j.getAngle()); if (diff <= Math.PI/2) { return diff; } else { return Math.PI - diff; } } public double horizontalDistance(ComponentLine other, double orientation) { double[] xs = new double[4]; double s = Math.sin(-orientation), c = Math.cos(-orientation); xs[0] = c * x0 - s * y0; xs[1] = c * x1 - s * y1; xs[2] = c * other.x0 - s * other.y0; xs[3] = c * other.x1 - s * other.y1; boolean overlapping = xs[1] >= xs[2] && xs[3] >= xs[0]; Arrays.sort(xs); return Math.abs(xs[2] - xs[1]) * (overlapping ? 1 : -1); } public double verticalDistance(ComponentLine other, double orientation) { double xm = (x0 + x1) / 2, ym = (y0 + y1) / 2; double xn = (other.x0 + other.x1) / 2, yn = (other.y0 + other.y1) / 2; double a = Math.tan(orientation); return Math.abs(a * (xn - xm) + ym - yn) / Math.sqrt(a * a + 1); } public BxLine convertToBxLine(double wordSpacing) { BxLine line = new BxLine(); BxWord word = new BxWord(); Component previousComponent = null; for (Component component : components) { if (previousComponent != null) { double dist = component.getChunk().getBounds().getX() - previousComponent.getChunk().getBounds().getX() - previousComponent.getChunk().getBounds().getWidth(); if(dist > wordSpacing) { BxBoundsBuilder.setBounds(word); line.addWord(word); word = new BxWord(); } } word.addChunk(component.getChunk()); previousComponent = component; } BxBoundsBuilder.setBounds(word); line.addWord(word); BxBoundsBuilder.setBounds(line); return line; } } /** * Filter class for neighbor objects that checks if the angle of the * neighbor is within specified range. */ protected abstract static class AngleFilter { private final double lowerAngle; private final double upperAngle; private AngleFilter(double lowerAngle, double upperAngle) { this.lowerAngle = lowerAngle; this.upperAngle = upperAngle; } /** * Constructs new angle filter. * * @param lowerAngle minimum angle in range [-3*pi/2, pi/2) * @param upperAngle maximum angle in range [-pi/2, 3*pi/2) * @return newly constructed angle filter */ public static AngleFilter newInstance(double lowerAngle, double upperAngle) { if (lowerAngle < -Math.PI/2) { lowerAngle += Math.PI; } if (upperAngle >= Math.PI/2) { upperAngle -= Math.PI; } if (lowerAngle <= upperAngle) { return new AndFilter(lowerAngle, upperAngle); } else { return new OrFilter(lowerAngle, upperAngle); } } public double getLowerAngle() { return lowerAngle; } public double getUpperAngle() { return upperAngle; } public abstract boolean matches(Neighbor neighbor); public static final class AndFilter extends AngleFilter { private AndFilter(double lowerAngle, double upperAngle) { super(lowerAngle, upperAngle); } @Override public boolean matches(Neighbor neighbor) { return getLowerAngle() <= neighbor.getAngle() && neighbor.getAngle() < getUpperAngle(); } } public static final class OrFilter extends AngleFilter { private OrFilter(double lowerAngle, double upperAngle) { super(lowerAngle, upperAngle); } @Override public boolean matches(Neighbor neighbor) { return getLowerAngle() <= neighbor.getAngle() || neighbor.getAngle() < getUpperAngle(); } } } private static final double DISTANCE_STEP = 16.0; /** * Angle histogram resolution in radians per bin. */ private static final double ANGLE_HIST_RESOLUTION = Math.toRadians(0.5); /** * Spacing histogram resolution per bin. */ private static final double SPACING_HIST_RESOLUTION = 0.5; /** * Maximum vertical component distance multiplier used during line * determination. * * Maximum vertical distance between components (characters) that belong * to the same line is equal to the product of this value and estimated * between-line spacing. */ private static final double MAX_VERTICAL_COMP_DIST = 0.67; /** * Minimum horizontal line distance multiplier. * * Minimum horizontal distance between lines that belong to the same zone * is equal to the product of this value and estimated within-line spacing. */ private static final double MIN_HORIZONTAL_DIST = -0.5; /** * Minimum vertical line distance multiplier. * * Minimum vertical distance between lines that belong to the same zone * is equal to the product of this value and estimated between-line spacing. */ private static final double MIN_VERTICAL_DIST = 0.0; /** * Maximum vertical line distance multiplier. * * Maximum vertical distance between lines that belong to the same zone * is equal to the product of this value and estimated between-line spacing. */ private static final double MAX_VERTICAL_DIST = 1.2; /** * Component distance character spacing multiplier. * * Maximum distance between components that belong to the same line is * equal to (lineSpacing * componentDistanceLineMultiplier + * characterSpacing * componentDistanceCharacterMultiplier), where * lineSpacing and characterSpacing are estimated between-line and * within-line spacing, respectively. */ private static final double COMP_DIST_CHAR = 3.5; /** * Word distance multiplier. * * Maximum distance between components that belong to the same word is * equal to the product of this value and estimated within-line spacing. */ private static final double WORD_DIST_MULT = 0.2; /** * Minimum horizontal line merge distance multiplier. * * Minimum horizontal distance between lines that should be merged is equal * to the product of this value and estimated within-line spacing. * * Because split lines do not overlap this value should be negative. */ private static final double MIN_HORIZONTAL_MERGE_DIST = -3.0; /** * Maximum vertical line merge distance multiplier. * * Maximum vertical distance between lines that should be merged is equal * to the product of this value and estimated between-line spacing. */ private static final double MAX_VERTICAL_MERGE_DIST = 0.5; /** * Angle tolerance for comparisons of angles between components and angles * between lines. */ private static final double ANGLE_TOLERANCE = Math.PI / 6; /** * Number of nearest-neighbors found per component. */ private static final int NEIGHBOUR_COUNT = 5; }
34,118
36.867925
118
java
CERMINE
CERMINE-master/cermine-impl/src/main/java/pl/edu/icm/cermine/structure/ReadingOrderResolver.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; import pl.edu.icm.cermine.exception.AnalysisException; import pl.edu.icm.cermine.structure.model.BxDocument; /** * Determining the order in which the elements on all levels should be read. * * @author Dominika Tkaczyk (d.tkaczyk@icm.edu.pl) */ public interface ReadingOrderResolver { /** * Resolves the reading order of the document's objects. * * @param document document * @return the document with the reading order set. * @throws AnalysisException AnalysisException */ BxDocument resolve(BxDocument document) throws AnalysisException; }
1,372
32.487805
78
java
CERMINE
CERMINE-master/cermine-impl/src/main/java/pl/edu/icm/cermine/structure/CharacterExtractor.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; import java.io.InputStream; import pl.edu.icm.cermine.exception.AnalysisException; import pl.edu.icm.cermine.structure.model.BxDocument; /** * Interface for extracting individual characters along with their bounding boxes from a file. * * @author Dominika Tkaczyk (d.tkaczyk@icm.edu.pl) */ public interface CharacterExtractor { /** * Extracts characters from the file. * * @param stream PDF stream * @return a document containing pages with individual characters. * @throws AnalysisException AnalysisException */ BxDocument extractCharacters(InputStream stream) throws AnalysisException; }
1,414
33.512195
95
java
CERMINE
CERMINE-master/cermine-impl/src/main/java/pl/edu/icm/cermine/structure/SVMMetadataZoneClassifier.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; import java.io.BufferedReader; import java.io.IOException; import java.util.Arrays; import pl.edu.icm.cermine.exception.AnalysisException; import pl.edu.icm.cermine.metadata.zoneclassification.features.*; import pl.edu.icm.cermine.structure.model.BxDocument; import pl.edu.icm.cermine.structure.model.BxPage; import pl.edu.icm.cermine.structure.model.BxZone; import pl.edu.icm.cermine.structure.model.BxZoneLabelCategory; import pl.edu.icm.cermine.tools.classification.general.FeatureCalculator; import pl.edu.icm.cermine.tools.classification.general.FeatureVectorBuilder; import pl.edu.icm.cermine.tools.classification.svm.SVMZoneClassifier; /** * SVM-based metadata zone classifier. * * @author Pawel Szostek */ public class SVMMetadataZoneClassifier extends SVMZoneClassifier { public SVMMetadataZoneClassifier(BufferedReader modelFile, BufferedReader rangeFile) throws AnalysisException { super(getFeatureVectorBuilder()); try { loadModelFromFile(modelFile, rangeFile); } catch (IOException ex) { throw new AnalysisException("Cannot create SVM classifier!", ex); } } public SVMMetadataZoneClassifier(String modelFilePath, String rangeFilePath) throws AnalysisException { this(modelFilePath, rangeFilePath, false); } public SVMMetadataZoneClassifier(String modelFilePath, String rangeFilePath, boolean fromResources) throws AnalysisException { super(getFeatureVectorBuilder()); try { if (fromResources) { loadModelFromResources(modelFilePath, rangeFilePath); } else { loadModelFromFile(modelFilePath, rangeFilePath); } } catch (IOException ex) { throw new AnalysisException("Cannot create SVM classifier!", ex); } } public static FeatureVectorBuilder<BxZone, BxPage> getFeatureVectorBuilder() { FeatureVectorBuilder<BxZone, BxPage> vectorBuilder = new FeatureVectorBuilder<BxZone, BxPage>(); vectorBuilder.setFeatureCalculators(Arrays .<FeatureCalculator<BxZone, BxPage>>asList( new LineHeightMaxMeanFeature(), new KeywordsFeature(), new IsRightFeature(), new BibinfoFeature(), new IsGreatestFontOnPageFeature(), new AuthorFeature(), new CorrespondenceFeature(), new IsLowestOnThePageFeature(), new AbstractFeature(), new AtCountFeature(), new IsAfterMetTitleFeature(), new LicenseFeature(), new DotCountFeature(), new AtRelativeCountFeature(), new WordLengthMedianFeature(), new AffiliationFeature(), new DigitCountFeature(), new YearFeature(), new IsHighestOnThePageFeature(), new AuthorNameRelativeFeature(), new CommaCountFeature(), new LineXPositionMeanFeature(), new IsOnSurroundingPagesFeature(), new UppercaseCountFeature(), new UppercaseWordCountFeature(), new IsAnywhereElseFeature(), new IsFirstPageFeature(), new PageNumberFeature(), new LastButOneZoneFeature(), new LineRelativeCountFeature(), new DotRelativeCountFeature(), new PreviousZoneFeature(), new FullWordsRelativeFeature(), new CommaRelativeCountFeature(), new HorizontalRelativeProminenceFeature(), new UppercaseWordRelativeCountFeature(), new LowercaseCountFeature(), new DigitRelativeCountFeature(), new PunctuationRelativeCountFeature(), new LineXWidthPositionDiffFeature(), new FontHeightMeanFeature(), new UppercaseRelativeCountFeature(), new LowercaseRelativeCountFeature(), new DistanceFromNearestNeighbourFeature(), new HeightRelativeFeature(), new EmptySpaceFeature(), new EmptySpaceRelativeFeature(), new VerticalProminenceFeature(), new YPositionFeature(), new YPositionRelativeFeature(), new LineWidthMeanFeature(), new ProportionsFeature(), new RelativeMeanLengthFeature() ) ); return vectorBuilder; } @Override public BxDocument classifyZones(BxDocument document) throws AnalysisException { for (BxPage page : document) { for (BxZone zone : page) { zone.setParent(page); } } for (BxZone zone : document.asZones()) { if (zone.getLabel().isOfCategoryOrGeneral(BxZoneLabelCategory.CAT_METADATA)) { zone.setLabel(predictLabel(zone, zone.getParent())); } } return document; } }
6,326
42.9375
130
java
CERMINE
CERMINE-master/cermine-impl/src/main/java/pl/edu/icm/cermine/structure/SVMInitialZoneClassifier.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; import java.io.BufferedReader; import java.io.IOException; import java.util.Arrays; import pl.edu.icm.cermine.exception.AnalysisException; import pl.edu.icm.cermine.metadata.zoneclassification.features.*; import pl.edu.icm.cermine.structure.model.BxDocument; import pl.edu.icm.cermine.structure.model.BxPage; import pl.edu.icm.cermine.structure.model.BxZone; import pl.edu.icm.cermine.structure.model.BxZoneLabel; import pl.edu.icm.cermine.tools.classification.general.FeatureCalculator; import pl.edu.icm.cermine.tools.classification.general.FeatureVectorBuilder; import pl.edu.icm.cermine.tools.classification.svm.SVMZoneClassifier; import pl.edu.icm.cermine.tools.timeout.TimeoutRegister; /** * Classifying zones as: METADATA, BODY, REFERENCES, OTHER. * * @author Pawel Szostek */ public class SVMInitialZoneClassifier extends SVMZoneClassifier { public SVMInitialZoneClassifier(BufferedReader modelFile, BufferedReader rangeFile) throws AnalysisException, IOException { super(getFeatureVectorBuilder()); loadModelFromFile(modelFile, rangeFile); } public SVMInitialZoneClassifier(String modelFilePath, String rangeFilePath) throws AnalysisException, IOException { super(getFeatureVectorBuilder()); loadModelFromFile(modelFilePath, rangeFilePath); } public static FeatureVectorBuilder<BxZone, BxPage> getFeatureVectorBuilder() { FeatureVectorBuilder<BxZone, BxPage> vectorBuilder = new FeatureVectorBuilder<BxZone, BxPage>(); vectorBuilder.setFeatureCalculators(Arrays.<FeatureCalculator<BxZone, BxPage>>asList( new AbstractFeature(), new IsSingleWordFeature(), new AtRelativeCountFeature(), new IsGreatestFontOnPageFeature(), new ReferencesTitleFeature(), new ReferencesFeature(), new DateFeature(), new StartsWithDigitFeature(), new BracketRelativeCountFeature(), new IsLastPageFeature(), new BibinfoFeature(), new IsPageNumberFeature(), new IsLowestOnThePageFeature(), new CommaCountFeature(), new LineCountFeature(), new AuthorNameRelativeFeature(), new DotCountFeature(), new DigitCountFeature(), new IsOnSurroundingPagesFeature(), new IsFirstPageFeature(), new UppercaseWordCountFeature(), new PageNumberFeature(), new IsAnywhereElseFeature(), new IsHighestOnThePageFeature(), new YearFeature(), new LineXPositionMeanFeature(), new CommaRelativeCountFeature(), new LowercaseCountFeature(), new LastButOneZoneFeature(), new XVarianceFeature(), new FullWordsRelativeFeature(), new DotRelativeCountFeature(), new UppercaseWordRelativeCountFeature(), new LineRelativeCountFeature(), new PreviousZoneFeature(), new PunctuationRelativeCountFeature(), new LineXWidthPositionDiffFeature(), new UppercaseRelativeCountFeature(), new WordLengthMeanFeature(), new DigitRelativeCountFeature(), new LineHeightMeanFeature(), new LowercaseRelativeCountFeature(), new XPositionFeature(), new HorizontalRelativeProminenceFeature(), new EmptySpaceFeature(), new DistanceFromNearestNeighbourFeature(), new VerticalProminenceFeature(), new AreaFeature(), new YPositionFeature(), new YPositionRelativeFeature(), new WordWidthMeanFeature(), new LineWidthMeanFeature(), new ProportionsFeature(), new RelativeMeanLengthFeature() )); return vectorBuilder; } @Override public BxDocument classifyZones(BxDocument document) throws AnalysisException { for (BxZone zone : document.asZones()) { if (zone.getLabel() == null) { BxZoneLabel predicted = predictLabel(zone, zone.getParent()); zone.setLabel(predicted); TimeoutRegister.get().check(); } } return document; } }
5,295
41.368
127
java
CERMINE
CERMINE-master/cermine-impl/src/main/java/pl/edu/icm/cermine/structure/ITextCharacterExtractor.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; import com.google.common.collect.Lists; import com.itextpdf.text.Rectangle; import com.itextpdf.text.exceptions.InvalidImageException; import com.itextpdf.text.exceptions.InvalidPdfException; import com.itextpdf.text.pdf.PRIndirectReference; import com.itextpdf.text.pdf.PdfDictionary; import com.itextpdf.text.pdf.PdfName; import com.itextpdf.text.pdf.PdfReader; import com.itextpdf.text.pdf.parser.*; import com.itextpdf.text.pdf.parser.Vector; import java.awt.image.BufferedImage; import java.io.IOException; import java.io.InputStream; import java.util.*; import pl.edu.icm.cermine.configuration.ExtractionConfigProperty; import pl.edu.icm.cermine.configuration.ExtractionConfigRegister; import pl.edu.icm.cermine.exception.AnalysisException; import pl.edu.icm.cermine.structure.model.BxBounds; import pl.edu.icm.cermine.structure.model.BxChunk; import pl.edu.icm.cermine.structure.model.BxDocument; import pl.edu.icm.cermine.structure.model.BxImage; import pl.edu.icm.cermine.structure.model.BxPage; import pl.edu.icm.cermine.structure.tools.BxBoundsBuilder; import pl.edu.icm.cermine.tools.timeout.TimeoutRegister; /** * Extracts text chunks from PDFs along with their position on the page, width and height. * * @author Dominika Tkaczyk (d.tkaczyk@icm.edu.pl) */ public class ITextCharacterExtractor implements CharacterExtractor { public static final int DEFAULT_FRONT_PAGES_LIMIT = 20; public static final int DEFAULT_BACK_PAGES_LIMIT = 20; private int frontPagesLimit = DEFAULT_FRONT_PAGES_LIMIT; private int backPagesLimit = DEFAULT_BACK_PAGES_LIMIT; private static final int PAGE_GRID_SIZE = 10; private static final int CHUNK_DENSITY_LIMIT = 15; protected static final Map<String, PdfName> ALT_TO_STANDART_FONTS = new HashMap<String, PdfName>(); static { ALT_TO_STANDART_FONTS.put("CourierNew", PdfName.COURIER); ALT_TO_STANDART_FONTS.put("CourierNew,Bold", PdfName.COURIER_BOLD); ALT_TO_STANDART_FONTS.put("CourierNew,BoldItalic", PdfName.COURIER_BOLDOBLIQUE); ALT_TO_STANDART_FONTS.put("CourierNew,Italic", PdfName.COURIER_OBLIQUE); ALT_TO_STANDART_FONTS.put("Arial", PdfName.HELVETICA); ALT_TO_STANDART_FONTS.put("Arial,Bold", PdfName.HELVETICA_BOLD); ALT_TO_STANDART_FONTS.put("Arial,BoldItalic", PdfName.HELVETICA_BOLDOBLIQUE); ALT_TO_STANDART_FONTS.put("Arial,Italic", PdfName.HELVETICA_OBLIQUE); ALT_TO_STANDART_FONTS.put("TimesNewRoman", PdfName.TIMES_ROMAN); ALT_TO_STANDART_FONTS.put("TimesNewRoman,Bold", PdfName.TIMES_BOLD); ALT_TO_STANDART_FONTS.put("TimesNewRoman,BoldItalic", PdfName.TIMES_BOLDITALIC); ALT_TO_STANDART_FONTS.put("TimesNewRoman,Italic", PdfName.TIMES_ITALIC); } /** * Extracts text chunks from PDF using iText and stores them in BxDocument object. * Depending on parsed PDF, extracted text chunks may or may not be individual glyphs, * they correspond to single string operands of PDF's text-showing operators * (Tj, TJ, ' and "). * @param stream PDF's stream * @return BxDocument containing pages with extracted chunks stored as BxChunk lists * @throws AnalysisException AnalysisException */ @Override public BxDocument extractCharacters(InputStream stream) throws AnalysisException { try { BxDocumentCreator documentCreator = new BxDocumentCreator(); PdfReader reader = new PdfReader(stream); PdfContentStreamProcessor processor = new PdfContentStreamProcessor(documentCreator); for (int pageNumber = 1; pageNumber <= reader.getNumberOfPages(); pageNumber++) { if (frontPagesLimit >= 0 && backPagesLimit >= 0 && pageNumber > frontPagesLimit && pageNumber <= reader.getNumberOfPages() - backPagesLimit) { continue; } documentCreator.processNewBxPage(reader.getPageSize(pageNumber)); PdfDictionary resources = reader.getPageN(pageNumber).getAsDict(PdfName.RESOURCES); processAlternativeFontNames(resources); processAlternativeColorSpace(resources); processor.reset(); processor.processContent(ContentByteUtils.getContentBytesForPage(reader, pageNumber), resources); TimeoutRegister.get().check(); } BxDocument doc = filterComponents(removeDuplicateChunks(documentCreator.document)); if (doc.getFirstChild() == null) { throw new AnalysisException("Document contains no pages"); } return doc; } catch (InvalidPdfException ex) { throw new AnalysisException("Invalid PDF file", ex); } catch (IOException ex) { throw new AnalysisException("Cannot extract characters from PDF file", ex); } } /** * Processes PDF's fonts dictionary. During the process alternative names * of Standard 14 Fonts are changed to the standard ones, provided that * the font definition doesn't include Widths array. * * Font dictionary in PDF file often includes an array of individual glyphs' widths. * Widths array is always required except for the Standard 14 Fonts, which widths * are kept by iText itself. Unfortunately, if the font uses alternative name instead of * standard one (see PDF Reference 1.7, table H.3), iText doesn't recognize the font as * one of the Standard 14 Fonts, and is unable to determine glyphs widths. In such cases * this method will change alternative names to standard ones before PDF's parsing process */ private void processAlternativeFontNames(PdfDictionary resources) { if (resources == null) { return; } PdfDictionary fontsDictionary = resources.getAsDict(PdfName.FONT); if (fontsDictionary == null) { return; } for (PdfName pdfFontName : fontsDictionary.getKeys()) { if (!(fontsDictionary.get(pdfFontName) instanceof PRIndirectReference)) { return; } PRIndirectReference indRef = (PRIndirectReference) fontsDictionary.get(pdfFontName); if (!(PdfReader.getPdfObjectRelease(indRef) instanceof PdfDictionary)) { return; } PdfDictionary fontDictionary = (PdfDictionary) PdfReader.getPdfObjectRelease(indRef); PdfName baseFont = fontDictionary.getAsName(PdfName.BASEFONT); if (baseFont != null) { String fontName = PdfName.decodeName(baseFont.toString()); if (fontDictionary.getAsArray(PdfName.WIDTHS) == null && ALT_TO_STANDART_FONTS.containsKey(fontName)) { fontDictionary.put(PdfName.BASEFONT, ALT_TO_STANDART_FONTS.get(fontName)); } } } } private void processAlternativeColorSpace(PdfDictionary resources) { if (resources == null) { return; } PdfDictionary csDictionary = resources.getAsDict(PdfName.COLORSPACE); if (csDictionary == null) { return; } for (PdfName csName : csDictionary.getKeys()) { if (csDictionary.getAsArray(csName) != null) { csDictionary.put(csName, PdfName.DEVICEGRAY); } } } private BxDocument removeDuplicateChunks(BxDocument document) { for (BxPage page : document) { List<BxChunk> chunks = Lists.newArrayList(page.getChunks()); List<BxChunk> filteredChunks = new ArrayList<BxChunk>(); Map<Integer, Map<Integer, Set<BxChunk>>> chunkMap = new HashMap<Integer, Map<Integer, Set<BxChunk>>>(); for (BxChunk chunk : chunks) { int x = (int) chunk.getX(); int y = (int) chunk.getY(); boolean duplicate = false; duplicateSearch: for (int i = x-1; i <= x+1; i++) { for (int j = y-1; j <= y+1; j++) { if (chunkMap.get(i) == null || chunkMap.get(i).get(j) == null) { continue; } for (BxChunk ch : chunkMap.get(i).get(j)) { if (chunk.toText().equals(ch.toText()) && chunk.getBounds().isSimilarTo(ch.getBounds(), 1)) { duplicate = true; break duplicateSearch; } } } } if (!duplicate) { filteredChunks.add(chunk); x = (int) chunk.getX(); y = (int) chunk.getY(); if (chunkMap.get(x) == null) { chunkMap.put(x, new HashMap<Integer, Set<BxChunk>>()); } if (chunkMap.get(x).get(y) == null) { chunkMap.get(x).put(y, new HashSet<BxChunk>()); } chunkMap.get(x).get(y).add(chunk); } } page.setChunks(filteredChunks); } return document; } private BxDocument filterComponents(BxDocument document) { for (BxPage page : document) { BxBoundsBuilder bounds = new BxBoundsBuilder(); List<BxChunk> chunks = Lists.newArrayList(page.getChunks()); for (BxChunk ch : chunks) { bounds.expand(ch.getBounds()); } double density = (double)100.0*chunks.size() / (bounds.getBounds().getWidth()*bounds.getBounds().getHeight()); if (Double.isNaN(density) || density < CHUNK_DENSITY_LIMIT) { continue; } Map<String, List<BxChunk>> map = new HashMap<String, List<BxChunk>>(); for (BxChunk ch : chunks) { int x = (int)ch.getX()/PAGE_GRID_SIZE; int y = (int)ch.getY()/PAGE_GRID_SIZE; String key = Integer.toString(x)+" "+Integer.toString(y); if (map.get(key) == null) { map.put(key, new ArrayList<BxChunk>()); } map.get(key).add(ch); } for (List<BxChunk> list : map.values()) { if (list.size() > CHUNK_DENSITY_LIMIT) { for (BxChunk ch : list) { chunks.remove(ch); } } } page.setChunks(chunks); } return document; } /** * Listener class receives information of text chunks and their render info * from PDF content processor. Listener uses this to construct a BxDocument object * containing lists of BxChunk elements. */ static class BxDocumentCreator implements RenderListener { private BxDocument document = new BxDocument(); private BxPage actPage; private int pageNumber = 0; private int imageNumber; private final BxBoundsBuilder boundsBuilder = new BxBoundsBuilder(); private Rectangle pageRectangle; private void processNewBxPage(Rectangle pageRectangle) { if (actPage != null) { actPage.setBounds(boundsBuilder.getBounds()); boundsBuilder.clear(); } actPage = new BxPage(); document.addPage(actPage); pageNumber++; imageNumber = 1; this.pageRectangle = pageRectangle; } @Override public void beginTextBlock() { } @Override public void renderText(TextRenderInfo tri) { for (TextRenderInfo charTri : tri.getCharacterRenderInfos()) { String text = charTri.getText(); if (text == null || text.isEmpty()) { continue; } float absoluteCharLeft = charTri.getDescentLine().getStartPoint().get(Vector.I1); float absoluteCharBottom = charTri.getDescentLine().getStartPoint().get(Vector.I2); float charLeft = absoluteCharLeft - pageRectangle.getLeft(); float charBottom = absoluteCharBottom - pageRectangle.getBottom(); float charHeight = charTri.getAscentLine().getStartPoint().get(Vector.I2) - charTri.getDescentLine().getStartPoint().get(Vector.I2); float charWidth = charTri.getDescentLine().getLength(); if (Float.isNaN(charHeight) || Float.isInfinite(charHeight)) { charHeight = 0; } if (Float.isNaN(charWidth) || Float.isInfinite(charWidth)) { charWidth = 0; } if (absoluteCharLeft < pageRectangle.getLeft() || absoluteCharLeft + charWidth > pageRectangle.getRight() || absoluteCharBottom < pageRectangle.getBottom() || absoluteCharBottom + charHeight > pageRectangle.getTop()) { continue; } BxBounds bounds = new BxBounds(charLeft, pageRectangle.getHeight() - charBottom - charHeight, charWidth, charHeight); if (Double.isNaN(bounds.getX()) || Double.isInfinite(bounds.getX()) || Double.isNaN(bounds.getY()) || Double.isInfinite(bounds.getY()) || Double.isNaN(bounds.getHeight()) || Double.isInfinite(bounds.getHeight()) || Double.isNaN(bounds.getWidth()) || Double.isInfinite(bounds.getWidth())) { continue; } char[] textChars = text.toCharArray(); double chw = bounds.getWidth() / textChars.length; for (int i = 0; i < textChars.length; i++) { char ch = textChars[i]; if (ch <= ' ' || text.matches("^[\uD800-\uD8FF]$") || text.matches("^[\uDC00-\uDFFF]$") || text.matches("^[\uFFF0-\uFFFF]$")) { continue; } BxBounds chBounds = new BxBounds(bounds.getX() + i * chw, bounds.getY(), chw, bounds.getHeight()); BxChunk chunk = new BxChunk(chBounds, String.valueOf(ch)); chunk.setFontName(tri.getFont().getFullFontName()[0][3]); actPage.addChunk(chunk); boundsBuilder.expand(bounds); } } } @Override public void endTextBlock() { } @Override public void renderImage(ImageRenderInfo iri) { if (!ExtractionConfigRegister.get().getBooleanProperty(ExtractionConfigProperty.IMAGES_EXTRACTION)) { return; } try { if (iri.getArea() < 0) { return; } BufferedImage bi = iri.getImage().getBufferedImage(); if (bi == null || bi.getHeight() <= 1 || bi.getWidth() <= 1) { return; } for (BxImage img : actPage.getImages()) { if (img.getX() == iri.getStartPoint().get(0) && img.getY() == iri.getStartPoint().get(1)) { return; } } actPage.addImage(new BxImage( "img_" + pageNumber + "_" + (imageNumber++) + ".png", bi, iri.getStartPoint().get(0), iri.getStartPoint().get(1))); } catch (IOException ex) { } catch (InvalidImageException ex) {} } } public int getBackPagesLimit() { return backPagesLimit; } public int getFrontPagesLimit() { return frontPagesLimit; } /** * Sets the number of front and back pages to be processed and returned. * If any of the values is set to 0 or less, the whole document is processed. * This may cause long processing time for large documents. * @param frontPagesLimit front pages limit * @param backPagesLimit back pages limit */ public void setPagesLimits(int frontPagesLimit, int backPagesLimit) { this.frontPagesLimit = frontPagesLimit; this.backPagesLimit = backPagesLimit; } }
17,717
42.426471
122
java
CERMINE
CERMINE-master/cermine-impl/src/main/java/pl/edu/icm/cermine/structure/HierarchicalReadingOrderResolver.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; import com.google.common.collect.Lists; import java.util.*; import pl.edu.icm.cermine.structure.model.*; import pl.edu.icm.cermine.structure.readingorder.BxZoneGroup; import pl.edu.icm.cermine.structure.readingorder.DistElem; import pl.edu.icm.cermine.structure.readingorder.DocumentPlane; import pl.edu.icm.cermine.structure.readingorder.TreeToListConverter; import pl.edu.icm.cermine.tools.Utils; import pl.edu.icm.cermine.tools.timeout.TimeoutRegister; /** * Class for setting a correct logical reading order of objects embedded in a BxDocument. * * @author Pawel Szostek */ public class HierarchicalReadingOrderResolver implements ReadingOrderResolver { static final int GRIDSIZE = 50; static final double BOXES_FLOW = 0.5; static final double EPS = 0.01; static final int MAX_ZONES = 1000; static final Comparator<BxObject> Y_ASCENDING_ORDER = new Comparator<BxObject>() { @Override public int compare(BxObject o1, BxObject o2) { return Utils.compareDouble(o1.getY(), o2.getY(), EPS); } }; static final Comparator<BxObject> X_ASCENDING_ORDER = new Comparator<BxObject>() { @Override public int compare(BxObject o1, BxObject o2) { return Utils.compareDouble(o1.getX(), o2.getX(), EPS); } }; static final Comparator<BxObject> YX_ASCENDING_ORDER = new Comparator<BxObject>() { @Override public int compare(BxObject o1, BxObject o2) { int yCompare = Y_ASCENDING_ORDER.compare(o1, o2); return yCompare == 0 ? X_ASCENDING_ORDER.compare(o1, o2) : yCompare; } }; @Override public BxDocument resolve(BxDocument messyDoc) { BxDocument orderedDoc = new BxDocument(); List<BxPage> pages = Lists.newArrayList(messyDoc); for (BxPage page : pages) { List<BxZone> zones = Lists.newArrayList(page); for (BxZone zone : zones) { List<BxLine> lines = Lists.newArrayList(zone); for (BxLine line : lines) { List<BxWord> words = Lists.newArrayList(line); for (BxWord word : words) { List<BxChunk> chunks = Lists.newArrayList(word); Collections.sort(chunks, X_ASCENDING_ORDER); word.resetText(); word.setChunks(chunks); } Collections.sort(words, X_ASCENDING_ORDER); line.resetText(); line.setWords(words); } Collections.sort(lines, YX_ASCENDING_ORDER); zone.resetText(); zone.setLines(lines); } List<BxZone> orderedZones; if (zones.size() > MAX_ZONES) { orderedZones = new ArrayList<BxZone>(zones); Collections.sort(orderedZones, YX_ASCENDING_ORDER); } else { orderedZones = reorderZones(zones); } page.setZones(orderedZones); page.resetText(); orderedDoc.addPage(page); TimeoutRegister.get().check(); } setIdsAndLinkTogether(orderedDoc); return orderedDoc; } /** * Builds a binary tree from list of text zones by doing a hierarchical clustering and converting the result tree to * an ordered list. * * @param zones is a list of unordered zones * @return a list of ordered zones */ private List<BxZone> reorderZones(List<BxZone> unorderedZones) { if (unorderedZones.isEmpty()) { return new ArrayList<BxZone>(); } else if (unorderedZones.size() == 1) { List<BxZone> ret = new ArrayList<BxZone>(1); ret.add(unorderedZones.get(0)); return ret; } else { BxZoneGroup bxZonesTree = groupZonesHierarchically(unorderedZones); sortGroupedZones(bxZonesTree); TreeToListConverter treeConverter = new TreeToListConverter(); List<BxZone> orderedZones = treeConverter.convertToList(bxZonesTree); assert unorderedZones.size() == orderedZones.size(); return orderedZones; } } /** * Generic function for setting IDs and creating a linked list by filling references. Used solely by * setIdsAndLinkTogether(). Can Handle all classes implementing Indexable interface. * * @param list is a list of Indexable objects */ private <A extends Indexable<A>> void setIdsGenericImpl(List<A> list) { if (list.isEmpty()) { return; } if (list.size() == 1) { A elem = list.get(0); elem.setNext(null); elem.setPrev(null); elem.setId("0"); elem.setNextId("-1"); return; } //unroll the loop for the first and last element A firstElem = list.get(0); firstElem.setId("0"); firstElem.setNextId("1"); firstElem.setNext(list.get(1)); firstElem.setPrev(null); for (int idx = 1; idx < list.size() - 1; ++idx) { A elem = list.get(idx); elem.setId(Integer.toString(idx)); elem.setNextId(Integer.toString(idx + 1)); elem.setNext(list.get(idx + 1)); elem.setPrev(list.get(idx - 1)); } A lastElem = list.get(list.size() - 1); lastElem.setId(Integer.toString(list.size() - 1)); lastElem.setNextId("-1"); lastElem.setNext(null); lastElem.setPrev(list.get(list.size() - 2)); } /** * Function for setting up indices and reference for the linked list. Causes objects of BxPage, BxZone, BxLine, * BxWord and BxChunk to be included in the document's list of elements and sets indices according to the * corresponding list order. * * @param doc is a reference to a document with properly set reading order */ private void setIdsAndLinkTogether(BxDocument doc) { setIdsGenericImpl(Lists.newArrayList(doc)); setIdsGenericImpl(Lists.newArrayList(doc.asZones())); setIdsGenericImpl(Lists.newArrayList(doc.asLines())); setIdsGenericImpl(Lists.newArrayList(doc.asWords())); setIdsGenericImpl(Lists.newArrayList(doc.asChunks())); } /** * Builds a binary tree of zones and groups of zones from a list of unordered zones. This is done in hierarchical * clustering by joining two least distant nodes. Distance is calculated in the distance() method. * * @param zones is a list of unordered zones * @return root of the zones clustered in a tree */ private BxZoneGroup groupZonesHierarchically(List<BxZone> zones) { /* * Distance tuples are stored sorted by ascending distance value */ List<DistElem<BxObject>> dists = new ArrayList<DistElem<BxObject>>(zones.size()*zones.size()/2); for (int idx1 = 0; idx1 < zones.size(); ++idx1) { for (int idx2 = idx1 + 1; idx2 < zones.size(); ++idx2) { BxZone zone1 = zones.get(idx1); BxZone zone2 = zones.get(idx2); dists.add(new DistElem<BxObject>(false, distance(zone1, zone2), zone1, zone2)); } } Collections.sort(dists); TimeoutRegister.get().check(); DocumentPlane plane = new DocumentPlane(zones, GRIDSIZE); while (!dists.isEmpty()) { DistElem<BxObject> distElem = dists.get(0); dists.remove(0); if (!distElem.isC() && plane.anyObjectsBetween(distElem.getObj1(), distElem.getObj2())) { dists.add(new DistElem<BxObject>(true, distElem.getDist(), distElem.getObj1(), distElem.getObj2())); continue; } TimeoutRegister.get().check(); BxZoneGroup newGroup = new BxZoneGroup(distElem.getObj1(), distElem.getObj2()); plane.remove(distElem.getObj1()).remove(distElem.getObj2()); dists = removeDistElementsContainingObject(dists, distElem.getObj1()); dists = removeDistElementsContainingObject(dists, distElem.getObj2()); for (BxObject other : plane.getObjects()) { dists.add(new DistElem<BxObject>(false, distance(other, newGroup), newGroup, other)); TimeoutRegister.get().check(); } Collections.sort(dists); TimeoutRegister.get().check(); plane.add(newGroup); } assert plane.getObjects().size() == 1 : "There should be one object left at the plane after grouping"; return (BxZoneGroup) plane.getObjects().get(0); } /** * Removes all distance tuples containing obj */ private List<DistElem<BxObject>> removeDistElementsContainingObject(Collection<DistElem<BxObject>> list, BxObject obj) { List<DistElem<BxObject>> ret = new ArrayList<DistElem<BxObject>>(); for (DistElem<BxObject> distElem : list) { if (distElem.getObj1() != obj && distElem.getObj2() != obj) { ret.add(distElem); } } return ret; } /** * Swaps children of BxZoneGroup if necessary. A group with smaller sort factor is placed to the left (leftChild). * An object with greater sort factor is placed on the right (rightChild). This plays an important role when * traversing the tree in conversion to a one dimensional list. * * @param group */ private void sortGroupedZones(BxZoneGroup group) { BxObject leftChild = group.getLeftChild(); BxObject rightChild = group.getRightChild(); if (shouldBeSwapped(leftChild, rightChild)) { // swap group.setLeftChild(rightChild); group.setRightChild(leftChild); } if (leftChild instanceof BxZoneGroup) // if the child is a tree node, then recurse { sortGroupedZones((BxZoneGroup) leftChild); } if (rightChild instanceof BxZoneGroup) // as above - recurse { sortGroupedZones((BxZoneGroup) rightChild); } } private boolean shouldBeSwapped(BxObject first, BxObject second) { double cx, cy, cw, ch, ox, oy, ow, oh; cx = first.getBounds().getX(); cy = first.getBounds().getY(); cw = first.getBounds().getWidth(); ch = first.getBounds().getHeight(); ox = second.getBounds().getX(); oy = second.getBounds().getY(); ow = second.getBounds().getWidth(); oh = second.getBounds().getHeight(); // Determine Octant // // 0 | 1 | 2 // __|___|__ // 7 | 9 | 3 First is placed in 9th square // __|___|__ // 6 | 5 | 4 if (cx + cw <= ox) { //2,3,4 return false; } else if (ox + ow <= cx) { //0,6,7 return true; //6 } else if (cy + ch <= oy) { return false; //5 } else if (oy + oh <= cy) { return true; //1 } else { //two zones double xdiff = ox+ow/2 - cx-cw/2; double ydiff = oy+oh/2 - cy-ch/2; return xdiff + ydiff < 0; } } /** * A distance function between two TextBoxes. * * Consider the bounding rectangle for obj1 and obj2. Return its area minus the areas of obj1 and obj2, shown as * 'www' below. This value may be negative. (x0,y0) +------+..........+ | obj1 |wwwwwwwwww: +------+www+------+ * :wwwwwwwwww| obj2 | +..........+------+ (x1,y1) * * @return distance value based on objects' coordinates and physical size on a plane * */ private double distance(BxObject obj1, BxObject obj2) { double x0 = Math.min(obj1.getX(), obj2.getX()); double y0 = Math.min(obj1.getY(), obj2.getY()); double x1 = Math.max(obj1.getX() + obj1.getWidth(), obj2.getX() + obj2.getWidth()); double y1 = Math.max(obj1.getY() + obj1.getHeight(), obj2.getY() + obj2.getHeight()); double dist = ((x1 - x0) * (y1 - y0) - obj1.getArea() - obj2.getArea()); double obj1X = obj1.getX(); double obj1CenterX = obj1.getX() + obj1.getWidth() / 2; double obj1CenterY = obj1.getY() + obj1.getHeight() / 2; double obj2X = obj2.getX(); double obj2CenterX = obj2.getX() + obj2.getWidth() / 2; double obj2CenterY = obj2.getY() + obj2.getHeight() / 2; double obj1obj2VectorCosineAbsLeft = Math.abs((obj2X - obj1X) / Math.sqrt((obj2X - obj1X) * (obj2X - obj1X) + (obj2CenterY - obj1CenterY) * (obj2CenterY - obj1CenterY))); double obj1obj2VectorCosineAbsCenter = Math.abs((obj2CenterX - obj1CenterX) / Math.sqrt((obj2CenterX - obj1CenterX) * (obj2CenterX - obj1CenterX) + (obj2CenterY - obj1CenterY) * (obj2CenterY - obj1CenterY))); double cosine = Math.min(obj1obj2VectorCosineAbsLeft, obj1obj2VectorCosineAbsCenter); final double MAGIC_COEFF = 0.5; return dist * (MAGIC_COEFF + cosine); } }
14,004
39.712209
216
java
CERMINE
CERMINE-master/cermine-impl/src/main/java/pl/edu/icm/cermine/structure/DocumentSegmenter.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; import pl.edu.icm.cermine.exception.AnalysisException; import pl.edu.icm.cermine.structure.model.BxDocument; /** * Building hierarchical geometric structure containing: pages, zones, lines, words and characters. * * @author Dominika Tkaczyk (d.tkaczyk@icm.edu.pl) */ public interface DocumentSegmenter { /** * Builds hierarchical structure of the document. * * @param document document * @return the document storing hierarchical structure. * @throws AnalysisException AnalysisException */ BxDocument segmentDocument(BxDocument document) throws AnalysisException; }
1,389
33.75
99
java
CERMINE
CERMINE-master/cermine-impl/src/main/java/pl/edu/icm/cermine/structure/DocstrumSegmenter.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; import com.google.common.collect.Lists; import java.util.*; import pl.edu.icm.cermine.exception.AnalysisException; import pl.edu.icm.cermine.structure.model.*; import pl.edu.icm.cermine.structure.tools.BxBoundsBuilder; import pl.edu.icm.cermine.structure.tools.BxModelUtils; import pl.edu.icm.cermine.tools.DisjointSets; import pl.edu.icm.cermine.tools.Histogram; import pl.edu.icm.cermine.tools.timeout.TimeoutRegister; /** * Page segmenter using Docstrum algorithm. * * @author Krzysztof Rusek */ public class DocstrumSegmenter implements DocumentSegmenter { public static final int MAX_ZONES_PER_PAGE = 300; public static final int PAGE_MARGIN = 2; public static final double ORIENTATION_MARGIN = 0.2; public static final int LINES_PER_PAGE_MARGIN = 100; private double docOrientation = Double.NaN; private Map<BxPage, List<Component>> componentMap = new HashMap<BxPage, List<Component>>(); @Override public BxDocument segmentDocument(BxDocument document) throws AnalysisException { computeDocumentOrientation(document); BxDocument output = new BxDocument(); for (BxPage page: document) { BxPage segmentedPage = segmentPage(page); if (segmentedPage.getBounds() != null) { output.addPage(segmentedPage); } } return output; } protected void computeDocumentOrientation(BxDocument document) throws AnalysisException { List<Component> components = new ArrayList<Component>(); for (BxPage page : document.asPages()) { List<Component> pageComponents = createComponents(page); componentMap.put(page, pageComponents); components.addAll(pageComponents); } docOrientation = computeInitialOrientation(components); } protected void computeDocumentOrientation(Map<BxPage, List<Component>> componentMap) throws AnalysisException { this.componentMap = componentMap; List<Component> components = new ArrayList<Component>(); for (Map.Entry<BxPage, List<Component>> entry : componentMap.entrySet()) { components.addAll(entry.getValue()); } docOrientation = computeInitialOrientation(components); } protected BxPage segmentPage(BxPage page) throws AnalysisException { List<Component> components = componentMap.get(page); double orientation = docOrientation; if (Double.isNaN(orientation)) { orientation = computeInitialOrientation(components); } double characterSpacing = computeCharacterSpacing(components, orientation); double lineSpacing = computeLineSpacing(components, orientation); List<ComponentLine> lines = determineLines(components, orientation, characterSpacing * COMP_DIST_CHAR, lineSpacing * MAX_VERTICAL_COMP_DIST); if (Math.abs(orientation) > ORIENTATION_MARGIN) { List<ComponentLine> linesZero = determineLines(components, 0, characterSpacing * COMP_DIST_CHAR, lineSpacing * MAX_VERTICAL_COMP_DIST); if (Math.abs(lines.size() - LINES_PER_PAGE_MARGIN) > Math.abs(linesZero.size() - LINES_PER_PAGE_MARGIN)) { orientation = 0; lines = linesZero; } } double lineOrientation = computeOrientation(lines); if (!Double.isNaN(lineOrientation)) { orientation = lineOrientation; } List<List<ComponentLine>> zones = determineZones(lines, orientation, characterSpacing * MIN_HORIZONTAL_DIST, Double.POSITIVE_INFINITY, lineSpacing * MIN_VERTICAL_DIST, lineSpacing * MAX_VERTICAL_DIST, characterSpacing * MIN_HORIZONTAL_MERGE_DIST, 0.0, 0.0, lineSpacing * MAX_VERTICAL_MERGE_DIST); zones = mergeZones(zones, characterSpacing * 0.5); zones = mergeLines(zones, orientation, Double.NEGATIVE_INFINITY, 0.0, 0.0, lineSpacing * MAX_VERTICAL_MERGE_DIST); return convertToBxModel(page, zones, WORD_DIST_MULT * characterSpacing); } /** * Constructs sorted by x coordinate array of components from page's chunks. * * @param page page containing chunks * @return array of components * @throws AnalysisException AnalysisException */ protected List<Component> createComponents(BxPage page) throws AnalysisException { List<BxChunk> chunks = Lists.newArrayList(page.getChunks()); Component[] components = new Component[chunks.size()]; for (int i = 0; i < components.length; i++) { try { components[i] = new Component(chunks.get(i)); } catch(IllegalArgumentException ex) { throw new AnalysisException(ex); } } TimeoutRegister.get().check(); Arrays.sort(components, ComponentXComparator.getInstance()); TimeoutRegister.get().check(); findNeighbors(components); return Arrays.asList(components); } /** * Performs for each component search for nearest-neighbors and stores the * result in component's neighbors attribute. * * @param components array of components * @throws AnalysisException if the number of components is less than or * equal to the number of nearest-neighbors per component. */ private void findNeighbors(Component[] components) throws AnalysisException { if (components.length == 0) { return; } if (components.length == 1) { components[0].setNeighbors(new ArrayList<Neighbor>()); return; } int pageNeighborCount = NEIGHBOUR_COUNT; if (components.length <= NEIGHBOUR_COUNT) { pageNeighborCount = components.length - 1; } List<Neighbor> candidates = new ArrayList<Neighbor>(); for (int i = 0; i < components.length; i++) { int start = i, end = i + 1; // Contains components from components array // from ranges [start, i) and [i+1, end) double dist = Double.POSITIVE_INFINITY; for (double searchDist = 0; searchDist < dist; ) { searchDist += DISTANCE_STEP; boolean newCandidatesFound = false; while (start > 0 && components[i].getX() - components[start - 1].getX() < searchDist) { start--; candidates.add(new Neighbor(components[start], components[i])); if (candidates.size() > pageNeighborCount) { Collections.sort(candidates, NeighborDistanceComparator.getInstance()); candidates.subList(pageNeighborCount, candidates.size()).clear(); } newCandidatesFound = true; } TimeoutRegister.get().check(); while (end < components.length && components[end].getX() - components[i].getX() < searchDist) { candidates.add(new Neighbor(components[end], components[i])); if (candidates.size() > pageNeighborCount) { Collections.sort(candidates, NeighborDistanceComparator.getInstance()); candidates.subList(pageNeighborCount, candidates.size()).clear(); } end++; newCandidatesFound = true; } if (newCandidatesFound && candidates.size() >= pageNeighborCount) { Collections.sort(candidates, NeighborDistanceComparator.getInstance()); dist = candidates.get(pageNeighborCount - 1).getDistance(); } TimeoutRegister.get().check(); } candidates.subList(pageNeighborCount, candidates.size()).clear(); components[i].setNeighbors(new ArrayList<Neighbor>(candidates)); candidates.clear(); } } /** * Computes initial orientation estimation based on nearest-neighbors' angles. * * @param components * @return initial orientation estimation */ private double computeInitialOrientation(List<Component> components) { Histogram histogram = new Histogram(-Math.PI/2, Math.PI/2, ANGLE_HIST_RESOLUTION); for (Component component : components) { for (Neighbor neighbor : component.getNeighbors()) { histogram.add(neighbor.getAngle()); } } // Rectangular smoothing window has been replaced with gaussian smoothing window histogram.circularGaussianSmooth(ANGLE_HIST_SMOOTHING_LEN, ANGLE_HIST_SMOOTHING_STDDEV); return histogram.getPeakValue(); } /** * Computes within-line spacing based on nearest-neighbors distances. * * @param components * @param orientation estimated text orientation * @return estimated within-line spacing */ private double computeCharacterSpacing(List<Component> components, double orientation) { return computeSpacing(components, orientation); } /** * Computes between-line spacing based on nearest-neighbors distances. * * @param components * @param orientation estimated text orientation * @return estimated between-line spacing */ private double computeLineSpacing(List<Component> components, double orientation) { if (orientation >= 0) { return computeSpacing(components, orientation - Math.PI / 2); } else { return computeSpacing(components, orientation + Math.PI / 2); } } private double computeSpacing(List<Component> components, double angle) { double maxDistance = Double.NEGATIVE_INFINITY; for (Component component : components) { for (Neighbor neighbor : component.getNeighbors()) { maxDistance = Math.max(maxDistance, neighbor.getDistance()); } } Histogram histogram = new Histogram(0, maxDistance, SPACING_HIST_RESOLUTION); AngleFilter filter = AngleFilter.newInstance(angle - ANGLE_TOLERANCE, angle + ANGLE_TOLERANCE); for (Component component : components) { for (Neighbor neighbor : component.getNeighbors()) { if (filter.matches(neighbor)) { histogram.add(neighbor.getDistance()); } } } // Rectangular smoothing window has been replaced with gaussian smoothing window histogram.gaussianSmooth(SPACING_HIST_SMOOTHING_LEN, SPACING_HIST_SMOOTHING_STDDEV); return histogram.getPeakValue(); } /** * Groups components into text lines. * * @param components component list * @param orientation - estimated text orientation * @param maxHorizontalDistance - maximum horizontal distance between components * @param maxVerticalDistance - maximum vertical distance between components * @return lines of components */ private List<ComponentLine> determineLines(List<Component> components, double orientation, double maxHorizontalDistance, double maxVerticalDistance) { DisjointSets<Component> sets = new DisjointSets<Component>(components); AngleFilter filter = AngleFilter.newInstance(orientation - ANGLE_TOLERANCE, orientation + ANGLE_TOLERANCE); for (Component component : components) { for (Neighbor neighbor : component.getNeighbors()) { double x = neighbor.getHorizontalDistance(orientation) / maxHorizontalDistance; double y = neighbor.getVerticalDistance(orientation) / maxVerticalDistance; if (filter.matches(neighbor) && x * x + y * y <= 1) { sets.union(component, neighbor.getComponent()); } } } List<ComponentLine> lines = new ArrayList<ComponentLine>(); for (Set<Component> group : sets) { List<Component> lineComponents = new ArrayList<Component>(group); Collections.sort(lineComponents, ComponentXComparator.getInstance()); lines.add(new ComponentLine(lineComponents, orientation)); } return lines; } private double computeOrientation(List<ComponentLine> lines) { // Compute weighted mean of line angles double valueSum = 0.0; double weightSum = 0.0; for (ComponentLine line : lines) { valueSum += line.getAngle() * line.getLength(); weightSum += line.getLength(); } return valueSum / weightSum; } private List<List<ComponentLine>> determineZones(List<ComponentLine> lines, double orientation, double minHorizontalDistance, double maxHorizontalDistance, double minVerticalDistance, double maxVerticalDistance, double minHorizontalMergeDistance, double maxHorizontalMergeDistance, double minVerticalMergeDistance, double maxVerticalMergeDistance) { DisjointSets<ComponentLine> sets = new DisjointSets<ComponentLine>(lines); // Mean height is computed so that all distances can be scaled // relative to the line height double meanHeight = 0.0, weights = 0.0; for (ComponentLine line : lines) { double weight = line.getLength(); meanHeight += line.getHeight() * weight; weights += weight; } meanHeight /= weights; for (int i = 0; i < lines.size(); i++) { ComponentLine li = lines.get(i); for (int j = i + 1; j < lines.size(); j++) { ComponentLine lj = lines.get(j); double scale = Math.min(li.getHeight(), lj.getHeight()) / meanHeight; scale = Math.max(MIN_LINE_SIZE_SCALE, Math.min(scale, MAX_LINE_SIZE_SCALE)); // "<=" is used instead of "<" for consistency and to allow setting minVertical(Merge)Distance // to 0.0 with meaning "no minimal distance required" if (!sets.areTogether(li, lj) && li.angularDifference(lj) <= ANGLE_TOLERANCE) { double hDist = li.horizontalDistance(lj, orientation) / scale; double vDist = li.verticalDistance(lj, orientation) / scale; // Line over or above if (minHorizontalDistance <= hDist && hDist <= maxHorizontalDistance && minVerticalDistance <= vDist && vDist <= maxVerticalDistance) { sets.union(li, lj); } // Split line that needs later merging else if (minHorizontalMergeDistance <= hDist && hDist <= maxHorizontalMergeDistance && minVerticalMergeDistance <= vDist && vDist <= maxVerticalMergeDistance) { sets.union(li, lj); } } TimeoutRegister.get().check(); } } List<List<ComponentLine>> zones = new ArrayList<List<ComponentLine>>(); for (Set<ComponentLine> group : sets) { zones.add(new ArrayList<ComponentLine>(group)); } return zones; } private List<List<ComponentLine>> mergeZones(List<List<ComponentLine>> zones, double tolerance) { List<BxBounds> bounds = new ArrayList<BxBounds>(zones.size()); for (List<ComponentLine> zone : zones) { BxBoundsBuilder builder = new BxBoundsBuilder(); for (ComponentLine line : zone) { for (Component component : line.getComponents()) { builder.expand(component.getChunk().getBounds()); } } bounds.add(builder.getBounds()); } List<List<ComponentLine>> outputZones = new ArrayList<List<ComponentLine>>(); mainFor: for (int i = 0; i < zones.size(); i++) { for (int j = 0; j < zones.size(); j++) { if (i == j || bounds.get(j) == null || bounds.get(i) == null) { continue; } if (BxModelUtils.contains(bounds.get(j), bounds.get(i), tolerance)) { zones.get(j).addAll(zones.get(i)); bounds.set(i, null); continue mainFor; } TimeoutRegister.get().check(); } outputZones.add(zones.get(i)); } return outputZones; } private List<List<ComponentLine>> mergeLines(List<List<ComponentLine>> zones, double orientation, double minHorizontalDistance, double maxHorizontalDistance, double minVerticalDistance, double maxVerticalDistance) { List<List<ComponentLine>> outputZones = new ArrayList<List<ComponentLine>>(zones.size()); for (List<ComponentLine> zone : zones) { outputZones.add(mergeLinesInZone(zone, orientation, minHorizontalDistance, maxHorizontalDistance, minVerticalDistance, maxVerticalDistance)); } return outputZones; } private List<ComponentLine> mergeLinesInZone(List<ComponentLine> lines, double orientation, double minHorizontalDistance, double maxHorizontalDistance, double minVerticalDistance, double maxVerticalDistance) { DisjointSets<ComponentLine> sets = new DisjointSets<ComponentLine>(lines); for (int i = 0; i < lines.size(); i++) { ComponentLine li = lines.get(i); for (int j = i + 1; j < lines.size(); j++) { ComponentLine lj = lines.get(j); double hDist = li.horizontalDistance(lj, orientation); double vDist = li.verticalDistance(lj, orientation); if (minHorizontalDistance <= hDist && hDist <= maxHorizontalDistance && minVerticalDistance <= vDist && vDist <= maxVerticalDistance) { sets.union(li, lj); } else if (minVerticalDistance <= vDist && vDist <= maxVerticalDistance && Math.abs(hDist-Math.min(li.getLength(), lj.getLength())) < 0.1) { boolean componentOverlap = false; int overlappingCount = 0; for (Component ci : li.getComponents()) { for (Component cj : lj.getComponents()) { double dist = ci.overlappingDistance(cj, orientation); if (dist > 2) { componentOverlap = true; } if (dist > 0) { overlappingCount++; } } } if (!componentOverlap && overlappingCount <= 2) { sets.union(li, lj); } } } } List<ComponentLine> outputZone = new ArrayList<ComponentLine>(); for (Set<ComponentLine> group : sets) { List<Component> components = new ArrayList<Component>(); for (ComponentLine line : group) { components.addAll(line.getComponents()); } Collections.sort(components, ComponentXComparator.getInstance()); outputZone.add(new ComponentLine(components, orientation)); } return outputZone; } /** * Converts list of zones from internal format (using components and * component lines) to BxModel. * * @param zones zones in internal format * @param wordSpacing - maximum allowed distance between components that * belong to one word * @return BxModel page */ private BxPage convertToBxModel(BxPage origPage, List<List<ComponentLine>> zones, double wordSpacing) { BxPage page = new BxPage(); page.addImages(origPage.getImages()); List<BxPage> pages = Lists.newArrayList(origPage.getParent()); int pageIndex = pages.indexOf(origPage); boolean groupped = false; if (zones.size() > MAX_ZONES_PER_PAGE && pageIndex >= PAGE_MARGIN && pageIndex < pages.size() - PAGE_MARGIN) { List<ComponentLine> oneZone = new ArrayList<ComponentLine>(); for (List<ComponentLine> zone : zones) { oneZone.addAll(zone); } zones = new ArrayList<List<ComponentLine>>(); zones.add(oneZone); groupped = true; } for (List<ComponentLine> lines : zones) { BxZone zone = new BxZone(); if (groupped) { zone.setLabel(BxZoneLabel.GEN_OTHER); } for (ComponentLine line : lines) { zone.addLine(line.convertToBxLine(wordSpacing)); } List<BxLine> zLines = Lists.newArrayList(zone); Collections.sort(zLines, new Comparator<BxLine>() { @Override public int compare(BxLine o1, BxLine o2) { return Double.compare(o1.getBounds().getY(), o2.getBounds().getY()); } }); zone.setLines(zLines); BxBoundsBuilder.setBounds(zone); page.addZone(zone); } BxModelUtils.sortZonesYX(page); BxBoundsBuilder.setBounds(page); return page; } /** * Internal representation of character. */ protected static class Component { private final double x; private final double y; private final BxChunk chunk; private List<Neighbor> neighbors; public Component(BxChunk chunk) { BxBounds bounds = chunk.getBounds(); if (bounds == null) { throw new IllegalArgumentException("Bounds must not be null"); } if (Double.isNaN(bounds.getX()) || Double.isInfinite(bounds.getX())) { throw new IllegalArgumentException("Bounds x coordinate must be finite"); } if (Double.isNaN(bounds.getY()) || Double.isInfinite(bounds.getY())) { throw new IllegalArgumentException("Bounds y coordinate must be finite"); } if (Double.isNaN(bounds.getWidth()) || Double.isInfinite(bounds.getWidth())) { throw new IllegalArgumentException("Bounds width must be finite"); } if (Double.isNaN(bounds.getHeight()) || Double.isInfinite(bounds.getHeight())) { throw new IllegalArgumentException("Bounds height must be finite"); } this.x = chunk.getBounds().getX() + chunk.getBounds().getWidth() / 2; this.y = chunk.getBounds().getY() + chunk.getBounds().getHeight() / 2; this.chunk = chunk; } public double getX() { return x; } public double getY() { return y; } public double getHeight() { return chunk.getBounds().getHeight(); } public double distance(Component c) { double dx = getX() - c.getX(), dy = getY() - c.getY(); return Math.sqrt(dx * dx + dy * dy); } /** * Computes horizontal distance between components. * * @param c component * @param orientation orientation angle * @return distance */ public double horizontalDistance(Component c, double orientation) { // TODO: take orientation into account return Math.abs(getX() - c.getX()); } public double verticalDistance(Component c, double orientation) { return Math.abs(getY() - c.getY()); } public double horizontalBoundsDistance(Component c, double orientation) { // TODO: take orientation into account return horizontalDistance(c, orientation) - getChunk().getBounds().getWidth() / 2 - c.getChunk().getBounds().getWidth() / 2; } public BxChunk getChunk() { return chunk; } public List<Neighbor> getNeighbors() { return neighbors; } public void setNeighbors(List<Neighbor> neighbors) { this.neighbors = neighbors; } private double angle(Component c) { if (getX() > c.getX()) { return Math.atan2(getY() - c.getY(), getX() - c.getX()); } else { return Math.atan2(c.getY() - getY(), c.getX() - getX()); } } public double overlappingDistance(Component other, double orientation) { double[] xs = new double[4]; double s = Math.sin(-orientation), c = Math.cos(-orientation); xs[0] = c * x - s * y; xs[1] = c * (x+chunk.getWidth()) - s * (y+chunk.getHeight()); xs[2] = c * other.x - s * other.y; xs[3] = c * (other.x+other.chunk.getWidth()) - s * (other.y+other.chunk.getHeight()); boolean overlapping = xs[1] >= xs[2] && xs[3] >= xs[0]; Arrays.sort(xs); return Math.abs(xs[2] - xs[1]) * (overlapping ? 1 : -1); } } /** * Class representing nearest-neighbor pair. */ protected static class Neighbor { private final double distance; private final double angle; private final Component component; private final Component origin; public Neighbor(Component neighbor, Component origin) { this.distance = neighbor.distance(origin); this.angle = neighbor.angle(origin); this.component = neighbor; this.origin = origin; } public double getDistance() { return distance; } public double getHorizontalDistance(double orientation) { return component.horizontalDistance(origin, orientation); } public double getVerticalDistance(double orientation) { return component.verticalDistance(origin, orientation); } public double getAngle() { return angle; } public Component getComponent() { return component; } } /** * Component comparator based on x coordinate of the centroid of component. * * The ordering is not consistent with equals. */ protected static final class ComponentXComparator implements Comparator<Component> { private ComponentXComparator() { } @Override public int compare(Component o1, Component o2) { return Double.compare(o1.getX(), o2.getX()); } private static final ComponentXComparator instance = new ComponentXComparator(); public static ComponentXComparator getInstance() { return instance; } } /** * Neighbor distance comparator based on the distance. * * The ordering is not consistent with equals. */ protected static final class NeighborDistanceComparator implements Comparator<Neighbor> { private NeighborDistanceComparator() { } @Override public int compare(Neighbor o1, Neighbor o2) { return Double.compare(o1.getDistance(), o2.getDistance()); } private static final NeighborDistanceComparator instance = new NeighborDistanceComparator(); public static NeighborDistanceComparator getInstance() { return instance; } } /** * Internal representation of the text line. */ protected static class ComponentLine { private final double x0; private final double y0; private final double x1; private final double y1; private final double height; private final List<Component> components; public ComponentLine(List<Component> components, double orientation) { this.components = components; if (components.size() >= 2) { // Simple linear regression double sx = 0.0, sxx = 0.0, sxy = 0.0, sy = 0.0; for (Component component : components) { sx += component.getX(); sxx += component.getX() * component.getX(); sxy += component.getX() * component.getY(); sy += component.getY(); } double b = (components.size() * sxy - sx * sy) / (components.size() * sxx - sx * sx); double a = (sy - b * sx) / components.size(); this.x0 = components.get(0).getX(); this.y0 = a + b * this.x0; this.x1 = components.get(components.size() - 1).getX(); this.y1 = a + b * this.x1; } else if (! components.isEmpty()) { Component component = components.get(0); double dx = component.getChunk().getBounds().getWidth() / 3; double dy = dx * Math.tan(orientation); this.x0 = component.getX() - dx; this.x1 = component.getX() + dx; this.y0 = component.getY() - dy; this.y1 = component.getY() + dy; } else { throw new IllegalArgumentException("Component list must not be empty"); } height = computeHeight(); } public double getAngle() { return Math.atan2(y1 - y0, x1 - x0); } public double getSlope() { return (y1 - y0) / (x1 - x0); } public double getLength() { return Math.sqrt((x0 - x1) * (x0 - x1) + (y0 - y1) * (y0 - y1)); } private double computeHeight() { double sum = 0.0; for (Component component : components) { sum += component.getHeight(); } return sum / components.size(); } public double getHeight() { return height; } public List<Component> getComponents() { return components; } public double angularDifference(ComponentLine j) { double diff = Math.abs(getAngle() - j.getAngle()); if (diff <= Math.PI/2) { return diff; } else { return Math.PI - diff; } } public double horizontalDistance(ComponentLine other, double orientation) { double[] xs = new double[4]; double s = Math.sin(-orientation), c = Math.cos(-orientation); xs[0] = c * x0 - s * y0; xs[1] = c * x1 - s * y1; xs[2] = c * other.x0 - s * other.y0; xs[3] = c * other.x1 - s * other.y1; boolean overlapping = xs[1] >= xs[2] && xs[3] >= xs[0]; Arrays.sort(xs); return Math.abs(xs[2] - xs[1]) * (overlapping ? 1 : -1); } public double verticalDistance(ComponentLine other, double orientation) { double xm = (x0 + x1) / 2, ym = (y0 + y1) / 2; double xn = (other.x0 + other.x1) / 2, yn = (other.y0 + other.y1) / 2; double a = Math.tan(orientation); return Math.abs(a * (xn - xm) + ym - yn) / Math.sqrt(a * a + 1); } public BxLine convertToBxLine(double wordSpacing) { BxLine line = new BxLine(); BxWord word = new BxWord(); Component previousComponent = null; for (Component component : components) { if (previousComponent != null) { double dist = component.getChunk().getBounds().getX() - previousComponent.getChunk().getBounds().getX() - previousComponent.getChunk().getBounds().getWidth(); if (dist > wordSpacing) { BxBoundsBuilder.setBounds(word); line.addWord(word); word = new BxWord(); } } word.addChunk(component.getChunk()); previousComponent = component; } BxBoundsBuilder.setBounds(word); line.addWord(word); BxBoundsBuilder.setBounds(line); return line; } } /** * Filter class for neighbor objects that checks if the angle of the * neighbor is within specified range. */ protected abstract static class AngleFilter { private final double lowerAngle; private final double upperAngle; private AngleFilter(double lowerAngle, double upperAngle) { this.lowerAngle = lowerAngle; this.upperAngle = upperAngle; } /** * Constructs new angle filter. * * @param lowerAngle minimum angle in range [-3*pi/2, pi/2) * @param upperAngle maximum angle in range [-pi/2, 3*pi/2) * @return newly constructed angle filter */ public static AngleFilter newInstance(double lowerAngle, double upperAngle) { if (lowerAngle < -Math.PI/2) { lowerAngle += Math.PI; } if (upperAngle >= Math.PI/2) { upperAngle -= Math.PI; } if (lowerAngle <= upperAngle) { return new AndFilter(lowerAngle, upperAngle); } else { return new OrFilter(lowerAngle, upperAngle); } } public double getLowerAngle() { return lowerAngle; } public double getUpperAngle() { return upperAngle; } public abstract boolean matches(Neighbor neighbor); public static final class AndFilter extends AngleFilter { private AndFilter(double lowerAngle, double upperAngle) { super(lowerAngle, upperAngle); } @Override public boolean matches(Neighbor neighbor) { return getLowerAngle() <= neighbor.getAngle() && neighbor.getAngle() < getUpperAngle(); } } public static final class OrFilter extends AngleFilter { private OrFilter(double lowerAngle, double upperAngle) { super(lowerAngle, upperAngle); } @Override public boolean matches(Neighbor neighbor) { return getLowerAngle() <= neighbor.getAngle() || neighbor.getAngle() < getUpperAngle(); } } } private static final double DISTANCE_STEP = 16.0; /** * Angle histogram resolution in radians per bin. */ private static final double ANGLE_HIST_RESOLUTION = Math.toRadians(0.5); /** * Angle histogram smoothing window length in radians. * Length of angle histogram is equal to pi. */ private static final double ANGLE_HIST_SMOOTHING_LEN = 0.25 * Math.PI; /** * Angle histogram gaussian smoothing window standard deviation in radians. */ private static final double ANGLE_HIST_SMOOTHING_STDDEV = 0.0625 * Math.PI; /** * Spacing histogram resolution per bin. */ private static final double SPACING_HIST_RESOLUTION = 0.5; /** * Spacing histogram smoothing window length. */ private static final double SPACING_HIST_SMOOTHING_LEN = 2.5; /** * Spacing histogram gaussian smoothing window standard deviation. */ private static final double SPACING_HIST_SMOOTHING_STDDEV = 0.5; /** * Maximum vertical component distance multiplier used during line * determination. * * Maximum vertical distance between components (characters) that belong * to the same line is equal to the product of this value and estimated * between-line spacing. */ private static final double MAX_VERTICAL_COMP_DIST = 0.67; /** * Minimum line size scale value. * * During zone determination (merging lines into zones) line height is * taken into account. To achieve this, line size scale is estimated and * limited to range [minLineSizeScale, maxLineSizeScale]. */ private static final double MIN_LINE_SIZE_SCALE = 0.9; /** * Maximum line size scale value. * * See minLineSizeScale for more information. */ private static final double MAX_LINE_SIZE_SCALE = 2.5; /** * Minimum horizontal line distance multiplier. * * Minimum horizontal distance between lines that belong to the same zone * is equal to the product of this value and estimated within-line spacing. */ private static final double MIN_HORIZONTAL_DIST = -0.5; /** * Minimum vertical line distance multiplier. * * Minimum vertical distance between lines that belong to the same zone * is equal to the product of this value and estimated between-line spacing. */ private static final double MIN_VERTICAL_DIST = 0.0; /** * Maximum vertical line distance multiplier. * * Maximum vertical distance between lines that belong to the same zone * is equal to the product of this value and estimated between-line spacing. */ private static final double MAX_VERTICAL_DIST = 1.2; /** * Component distance character spacing multiplier. * * Maximum distance between components that belong to the same line is * equal to (lineSpacing * componentDistanceLineMultiplier + * characterSpacing * componentDistanceCharacterMultiplier), where * lineSpacing and characterSpacing are estimated between-line and * within-line spacing, respectively. */ private static final double COMP_DIST_CHAR = 3.5; /** * Word distance multiplier. * * Maximum distance between components that belong to the same word is * equal to the product of this value and estimated within-line spacing. */ private static final double WORD_DIST_MULT = 0.2; /** * Minimum horizontal line merge distance multiplier. * * Minimum horizontal distance between lines that should be merged is equal * to the product of this value and estimated within-line spacing. * * Because split lines do not overlap this value should be negative. */ private static final double MIN_HORIZONTAL_MERGE_DIST = -3.0; /** * Maximum vertical line merge distance multiplier. * * Maximum vertical distance between lines that should be merged is equal * to the product of this value and estimated between-line spacing. */ private static final double MAX_VERTICAL_MERGE_DIST = 0.5; /** * Angle tolerance for comparisons of angles between components and angles * between lines. */ private static final double ANGLE_TOLERANCE = Math.PI / 6; /** * Number of nearest-neighbors found per component. */ private static final int NEIGHBOUR_COUNT = 5; }
40,191
38.021359
118
java
CERMINE
CERMINE-master/cermine-impl/src/main/java/pl/edu/icm/cermine/structure/ZoneClassifier.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; import pl.edu.icm.cermine.exception.AnalysisException; import pl.edu.icm.cermine.structure.model.BxDocument; /** * Interface for classifying zones of the document. * * @author Dominika Tkaczyk (d.tkaczyk@icm.edu.pl) */ public interface ZoneClassifier { /** * Sets labels for the document's zones. * * @param document document * @return a documents with labels set * @throws AnalysisException AnalysisException */ BxDocument classifyZones(BxDocument document) throws AnalysisException; }
1,309
31.75
78
java
CERMINE
CERMINE-master/cermine-impl/src/main/java/pl/edu/icm/cermine/structure/ParallelDocstrumSegmenter.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; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.Map; import java.util.concurrent.*; import pl.edu.icm.cermine.exception.AnalysisException; import pl.edu.icm.cermine.structure.model.BxDocument; import pl.edu.icm.cermine.structure.model.BxPage; import pl.edu.icm.cermine.tools.timeout.Timeout; import pl.edu.icm.cermine.tools.timeout.TimeoutException; import pl.edu.icm.cermine.tools.timeout.TimeoutRegister; /** * Page segmenter using Docstrum algorithm. * * @author Krzysztof Rusek */ public class ParallelDocstrumSegmenter extends DocstrumSegmenter { static class NumBxPage { int index = -1; BxPage page; List<Component> components; public NumBxPage(BxPage page, int index) { this.page = page; this.index = index; } public NumBxPage(BxPage page) { this.page = page; } } class SingleSegmenter implements Callable<NumBxPage> { NumBxPage page; private final Timeout timeout; public SingleSegmenter(BxPage page, int index, Timeout timeout) { this.page = new NumBxPage(page, index); this.timeout = timeout; } @Override public NumBxPage call() throws AnalysisException { try { TimeoutRegister.set(timeout); return new NumBxPage(segmentPage(page.page), page.index); } finally { TimeoutRegister.remove(); } } } class ComponentCounter implements Callable<NumBxPage> { NumBxPage page; private final Timeout timeout; public ComponentCounter(BxPage page, Timeout timeout) { this.page = new NumBxPage(page); this.timeout = timeout; } @Override public NumBxPage call() throws AnalysisException { try { TimeoutRegister.set(timeout); TimeoutRegister.get().check(); page.components = createComponents(page.page); return page; } finally { TimeoutRegister.remove(); } } } @Override public BxDocument segmentDocument(BxDocument document) throws AnalysisException { Map<BxPage, List<Component>> componentMap = new HashMap<BxPage, List<Component>>(); ExecutorService exec = Executors.newFixedThreadPool(3); ArrayList<Callable<NumBxPage>> tasks = new ArrayList<Callable<NumBxPage>>(); for (BxPage page : document) { tasks.add(new ComponentCounter(page, TimeoutRegister.get())); } List<Future<NumBxPage>> results; try { results = exec.invokeAll(tasks); exec.shutdown(); for (Future<NumBxPage> result : results) { NumBxPage p = result.get(); componentMap.put(p.page, p.components); } TimeoutRegister.get().check(); } catch (ExecutionException ex) { if (ex.getCause() instanceof TimeoutException){ throw new TimeoutException((Exception)ex); } else { throw new AnalysisException("Cannot segment pages!", ex); } } catch (InterruptedException ex) { throw new AnalysisException("Cannot segment pages!", ex); } this.computeDocumentOrientation(componentMap); BxDocument output = new BxDocument(); BxPage[] pages = new BxPage[document.childrenCount()]; exec = Executors.newFixedThreadPool(3); tasks = new ArrayList<Callable<NumBxPage>>(); int i = 0; for (BxPage page : document) { tasks.add(new SingleSegmenter(page, i++, TimeoutRegister.get())); } try { results = exec.invokeAll(tasks); exec.shutdown(); for (Future<NumBxPage> result : results) { NumBxPage p = result.get(); pages[p.index] = p.page; } TimeoutRegister.get().check(); for (BxPage p : pages) { if (p.getBounds() != null) { output.addPage(p); } } return output; } catch (ExecutionException ex) { if (ex.getCause() instanceof TimeoutException){ throw new TimeoutException((Exception)ex); } else { throw new AnalysisException("Cannot segment pages!", ex); } } catch (InterruptedException ex) { throw new AnalysisException("Cannot segment pages!", ex); } } }
5,552
32.251497
91
java
CERMINE
CERMINE-master/cermine-impl/src/main/java/pl/edu/icm/cermine/structure/tools/BxModelUtils.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.tools; import com.google.common.collect.Lists; import java.util.*; import pl.edu.icm.cermine.structure.model.*; import pl.edu.icm.cermine.tools.Utils; /** * @author Krzysztof Rusek * @author Dominika Tkaczyk */ public final class BxModelUtils { private static final double SIMILARITY_TOLERANCE = 0.001; private BxModelUtils() { } public static void setParents(BxDocument doc) { for (BxPage page : doc) { page.setParent(doc); setParents(page); } } public static void setParents(BxPage page) { for (BxZone zone : page) { for (BxLine line : zone) { for (BxWord word : line) { for (BxChunk chunk : word) { chunk.setParent(word); } word.setParent(line); } line.setParent(zone); } zone.setParent(page); } } public static void sortZonesYX(BxPage page, final double tolerance) { List<BxZone> zones = Lists.newArrayList(page); Collections.sort(zones, new Comparator<BxZone>() { @Override public int compare(BxZone o1, BxZone o2) { int cmp = Utils.compareDouble(o1.getBounds().getY(), o2.getBounds().getY(), tolerance); if (cmp == 0) { return Utils.compareDouble(o1.getBounds().getX(), o2.getBounds().getX(), tolerance); } return cmp; } }); page.setZones(zones); } public static void sortZonesYX(BxPage page) { sortZonesYX(page, 0); } public static void sortZonesXY(BxPage page, final double tolerance) { List<BxZone> zones = Lists.newArrayList(page); Collections.sort(zones, new Comparator<BxZone>() { @Override public int compare(BxZone o1, BxZone o2) { int cmp = Utils.compareDouble(o1.getBounds().getX(), o2.getBounds().getX(), tolerance); if (cmp == 0) { return Utils.compareDouble(o1.getBounds().getY(), o2.getBounds().getY(), tolerance); } return cmp; } }); page.setZones(zones); } public static void sortZonesXY(BxPage page) { sortZonesXY(page, 0); } public static void sortLines(BxZone zone) { List<BxLine> lines = Lists.newArrayList(zone); Collections.sort(lines, new Comparator<BxLine>() { @Override public int compare(BxLine o1, BxLine o2) { int cmp = Double.compare(o1.getBounds().getY(), o2.getBounds().getY()); if (cmp == 0) { cmp = Double.compare(o1.getBounds().getX(), o2.getBounds().getX()); } return cmp; } }); zone.setLines(lines); } public static void sortWords(BxLine line) { List<BxWord> words = Lists.newArrayList(line); Collections.sort(words, new Comparator<BxWord>() { @Override public int compare(BxWord o1, BxWord o2) { return Double.compare(o1.getBounds().getX(), o2.getBounds().getX()); } }); line.setWords(words); } public static void sortChunks(BxWord word) { List<BxChunk> chunks = Lists.newArrayList(word); Collections.sort(chunks, new Comparator<BxChunk>() { @Override public int compare(BxChunk o1, BxChunk o2) { return Double.compare(o1.getBounds().getX(), o2.getBounds().getX()); } }); word.setChunks(chunks); } public static void sortZoneRecursively(BxZone zone) { sortLines(zone); for (BxLine line : zone) { sortWords(line); for (BxWord word : line) { sortChunks(word); } } } public static void sortZonesRecursively(BxPage page) { for (BxZone zone : page) { sortZoneRecursively(zone); } } public static void sortZonesRecursively(BxDocument document) { for (BxPage page : document) { sortZonesRecursively(page); } } public static BxBounds deepClone(BxBounds bounds) { return new BxBounds(bounds.getX(), bounds.getY(), bounds.getWidth(), bounds.getHeight()); } public static BxChunk deepClone(BxChunk chunk) { BxChunk copy = new BxChunk(deepClone(chunk.getBounds()), chunk.toText()); copy.setFontName(chunk.getFontName()); copy.setId(chunk.getId()); copy.setNextId(chunk.getNextId()); return copy; } /** * Creates a deep copy of the word. * * @param word word * @return copy */ public static BxWord deepClone(BxWord word) { BxWord copy = new BxWord().setBounds(deepClone(word.getBounds())); copy.setId(word.getId()); copy.setNextId(word.getNextId()); BxChunk prev = null; for (BxChunk chunk : word) { BxChunk copiedChunk = deepClone(chunk); copiedChunk.setPrev(prev); if (prev != null) { prev.setNext(copiedChunk); } prev = copiedChunk; copy.addChunk(copiedChunk); } return copy; } /** * Creates a deep copy of the line. * * @param line line * @return copy */ public static BxLine deepClone(BxLine line) { BxLine copy = new BxLine().setBounds(deepClone(line.getBounds())); copy.setId(line.getId()); copy.setNextId(line.getNextId()); BxWord prevW = null; BxChunk prevC = null; for (BxWord word : line) { BxWord copiedWord = deepClone(word); copiedWord.setPrev(prevW); if (prevW != null) { prevW.setNext(copiedWord); } prevW = copiedWord; for (BxChunk ch : copiedWord) { ch.setPrev(prevC); if (prevC != null) { prevC.setNext(ch); } prevC = ch; } copy.addWord(copiedWord); } return copy; } /** * Creates a deep copy of the zone. * * @param zone zone * @return copy */ public static BxZone deepClone(BxZone zone) { BxZone copy = new BxZone().setLabel(zone.getLabel()).setBounds(deepClone(zone.getBounds())); copy.setId(zone.getId()); copy.setNextId(zone.getNextId()); BxLine prevL = null; BxWord prevW = null; BxChunk prevC = null; for (BxLine line : zone) { BxLine copiedLine = deepClone(line); copiedLine.setPrev(prevL); if (prevL != null) { prevL.setNext(copiedLine); } prevL = copiedLine; for (BxWord w : copiedLine) { w.setPrev(prevW); if (prevW != null) { prevW.setNext(w); } prevW = w; for (BxChunk ch : w) { ch.setPrev(prevC); if (prevC != null) { prevC.setNext(ch); } prevC = ch; } } copy.addLine(copiedLine); } for (BxChunk chunk : zone.getChunks()) { copy.addChunk(chunk); } return copy; } /** * Creates a deep copy of the page. * * @param page page * @return copy */ public static BxPage deepClone(BxPage page) { BxPage copy = new BxPage().setBounds(deepClone(page.getBounds())); copy.setId(page.getId()); copy.setNextId(page.getNextId()); BxZone prevZ = null; BxLine prevL = null; BxWord prevW = null; BxChunk prevC = null; for (BxZone zone : page) { BxZone copiedZone = deepClone(zone); copiedZone.setPrev(prevZ); if (prevZ != null) { prevZ.setNext(copiedZone); } prevZ = copiedZone; for (BxLine l : copiedZone) { l.setPrev(prevL); if (prevL != null) { prevL.setNext(l); } prevL = l; for (BxWord w : l) { w.setPrev(prevW); if (prevW != null) { prevW.setNext(w); } prevW = w; for (BxChunk ch : w) { ch.setPrev(prevC); if (prevC != null) { prevC.setNext(ch); } prevC = ch; } } } copy.addZone(copiedZone); } Iterator<BxChunk> chunks = page.getChunks(); while (chunks.hasNext()) { copy.addChunk(deepClone(chunks.next())); } return copy; } /** * Creates a deep copy of the document. * * @param document document * @return copy */ public static BxDocument deepClone(BxDocument document) { BxDocument copy = new BxDocument(); copy.setFilename(document.getFilename()); BxPage prevP = null; BxZone prevZ = null; BxLine prevL = null; BxWord prevW = null; BxChunk prevC = null; for (BxPage page : document) { BxPage copiedPage = deepClone(page); copiedPage.setPrev(prevP); if (prevP != null) { prevP.setNext(copiedPage); } prevP = copiedPage; for (BxZone z : copiedPage) { z.setPrev(prevZ); if (prevZ != null) { prevZ.setNext(z); } prevZ = z; for (BxLine l : z) { l.setPrev(prevL); if (prevL != null) { prevL.setNext(l); } prevL = l; for (BxWord w : l) { w.setPrev(prevW); if (prevW != null) { prevW.setNext(w); } prevW = w; for (BxChunk ch : w) { ch.setPrev(prevC); if (prevC != null) { prevC.setNext(ch); } prevC = ch; } } } } copy.addPage(copiedPage); } return copy; } public static List<BxDocument> deepClone(List<BxDocument> documents) { List<BxDocument> copy = new ArrayList<BxDocument>(documents.size()); for (BxDocument doc : documents) { copy.add(deepClone(doc)); } return copy; } /** * Maps segmented chunks to words which they belong to. * * @param page page * @return map */ public static Map<BxChunk, BxWord> mapChunksToWords(BxPage page) { Map<BxChunk, BxWord> map = new HashMap<BxChunk, BxWord>(); for (BxZone zone : page) { for (BxLine line : zone) { for (BxWord word : line) { for (BxChunk chunk : word) { map.put(chunk, word); } } } } return map; } /** * Maps segmented chunks to lines which they belong to. * * @param page page * @return map */ public static Map<BxChunk, BxLine> mapChunksToLines(BxPage page) { Map<BxChunk, BxLine> map = new HashMap<BxChunk, BxLine>(); for (BxZone zone : page) { for (BxLine line : zone) { for (BxWord word : line) { for (BxChunk chunk : word) { map.put(chunk, line); } } } } return map; } /** * Maps segmented chunks to zones which they belong to. * * @param page page containing zones * @return map */ public static Map<BxChunk, BxZone> mapChunksToZones(BxPage page) { Map<BxChunk, BxZone> map = new HashMap<BxChunk, BxZone>(); for (BxZone zone : page) { for (BxLine line : zone) { for (BxWord word : line) { for (BxChunk chunk : word) { map.put(chunk, zone); } } } } return map; } /** * Counts segmented chunks in line. * * @param line line * @return number of segmented chunks */ public static int countChunks(BxLine line) { int chunkCount = 0; for (BxWord word : line) { chunkCount += word.childrenCount(); } return chunkCount; } /** * Counts segmented chunks in zone. * * @param zone zone * @return number of segmented chunks */ public static int countChunks(BxZone zone) { int chunkCount = 0; for (BxLine line : zone) { for (BxWord word : line) { chunkCount += word.childrenCount(); } } return chunkCount; } public static boolean contains(BxBounds containing, BxBounds contained, double tolerance) { return containing.getX() <= contained.getX() + tolerance && containing.getY() <= contained.getY() + tolerance && containing.getX() + containing.getWidth() >= contained.getX() + contained.getWidth() - tolerance && containing.getY() + containing.getHeight() >= contained.getY() + contained.getHeight() - tolerance; } public static boolean areEqual(BxChunk chunk1, BxChunk chunk2) { if (!chunk1.toText().equals(chunk2.toText())) { return false; } if (!chunk1.getFontName().equals(chunk2.getFontName())) { return false; } if (!chunk1.getId().equals(chunk2.getId())) { return false; } return chunk1.getBounds().isSimilarTo(chunk2.getBounds(), SIMILARITY_TOLERANCE); } public static boolean areEqual(BxWord word1, BxWord word2) { if (!word1.getId().equals(word2.getId())) { return false; } if (word1.childrenCount() != word2.childrenCount()) { return false; } for (int i = 0; i < word1.childrenCount(); i++) { if (!areEqual(word1.getChild(i), word2.getChild(i))) { return false; } } return true; } public static boolean areEqual(BxLine line1, BxLine line2) { if (!line1.getId().equals(line2.getId())) { return false; } if (line1.childrenCount() != line2.childrenCount()) { return false; } for (int i = 0; i < line1.childrenCount(); i++) { if (!areEqual(line1.getChild(i), line2.getChild(i))) { return false; } } return true; } public static boolean areEqual(BxZone zone1, BxZone zone2) { if (!zone1.getId().equals(zone2.getId())) { return false; } if (zone1.getLabel() != zone2.getLabel()){ return false; } if (zone1.childrenCount() != zone2.childrenCount()) { return false; } for (int i = 0; i < zone1.childrenCount(); i++) { if (!areEqual(zone1.getChild(i), zone2.getChild(i))) { return false; } } return true; } public static boolean areEqual(BxPage page1, BxPage page2) { if (!page1.getId().equals(page2.getId())) { return false; } if (page1.childrenCount() != page2.childrenCount()) { return false; } for (int i = 0; i < page1.childrenCount(); i++) { if (!areEqual(page1.getChild(i), page2.getChild(i))) { return false; } } return true; } public static boolean areEqual(BxDocument doc1, BxDocument doc2) { if (doc1.getFilename() == null && doc2.getFilename() != null) { return false; } if (doc1.getFilename() != null && doc2.getFilename() == null) { return false; } if (doc1.getFilename() != null && doc2.getFilename() != null && !doc1.getFilename().equals(doc2.getFilename())) { return false; } if (doc1.childrenCount() != doc2.childrenCount()) { return false; } for (int i = 0; i < doc1.childrenCount(); i++) { if (!areEqual(doc1.getChild(i), doc2.getChild(i))) { return false; } } return true; } }
17,997
30.192374
118
java
CERMINE
CERMINE-master/cermine-impl/src/main/java/pl/edu/icm/cermine/structure/tools/UnsegmentedPagesFlattener.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.tools; import java.util.ArrayList; import pl.edu.icm.cermine.structure.model.*; /** * @author Dominika Tkaczyk (d.tkaczyk@icm.edu.pl) */ public class UnsegmentedPagesFlattener implements DocumentProcessor { @Override public void process(BxDocument document) { for (BxPage page: document) { for (BxZone zone: page) { for (BxChunk chunk : zone.getChunks()) { page.addChunk(chunk); } for (BxLine line: zone) { for (BxWord word: line) { for (BxChunk chunk : word) { page.addChunk(chunk); } } } } page.setZones(new ArrayList<BxZone>()); } } }
1,582
31.306122
78
java
CERMINE
CERMINE-master/cermine-impl/src/main/java/pl/edu/icm/cermine/structure/tools/UnclassifiedZonesPreprocessor.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.tools; import pl.edu.icm.cermine.structure.model.BxDocument; import pl.edu.icm.cermine.structure.model.BxPage; import pl.edu.icm.cermine.structure.model.BxZone; import pl.edu.icm.cermine.structure.model.BxZoneLabel; /** * @author Dominika Tkaczyk (d.tkaczyk@icm.edu.pl) */ public class UnclassifiedZonesPreprocessor implements DocumentProcessor { @Override public void process(BxDocument document) { for (BxPage page: document) { for (BxZone zone: page) { zone.setLabel(BxZoneLabel.OTH_UNKNOWN); } } } }
1,352
32
78
java
CERMINE
CERMINE-master/cermine-impl/src/main/java/pl/edu/icm/cermine/structure/tools/BxBoundsBuilder.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.tools; import pl.edu.icm.cermine.structure.model.*; /** * Bounding box builder class. * * Initially bounding box builder contains empty bounding box (null). Successive * calls of expand methods expand current bounding box so that it contains given * objects. If current bonding box is empty, expanding it is equivalent to * setting it to the dimensions of the given object. * * @author Krzysztof Rusek */ public class BxBoundsBuilder { private double minX = Double.POSITIVE_INFINITY; private double minY = Double.POSITIVE_INFINITY; private double maxX = Double.NEGATIVE_INFINITY; private double maxY = Double.NEGATIVE_INFINITY; /** * Expands current bounding box so that it contains bounding boxes * of page zones. * * @param page page */ public void expandByZones(BxPage page) { for (BxZone zone : page) { expand(zone.getBounds()); } } /** * Expands current bounding box so that it contains bounding boxes * of zone lines. * * @param zone zone */ public void expandByLines(BxZone zone) { for (BxLine line : zone) { expand(line.getBounds()); } } /** * Expands current bounding box so that it contains bounding boxes * of line words. * * @param line line */ public void expandByWords(BxLine line) { for (BxWord word : line) { expand(word.getBounds()); } } /** * Expands current bounding box so that it contains bounding boxes * of word chunks. * * @param word word */ public void expandByChunks(BxWord word) { for (BxChunk chunk : word) { expand(chunk.getBounds()); } } /** * Expands current bounding box so that it contains the point (x, y). * * @param x x coordinate of the point * @param y y coordinate of the point */ public void expand(double x, double y) { minX = Math.min(minX, x); minY = Math.min(minY, y); maxX = Math.max(maxX, x); maxY = Math.max(maxY, y); } /** * Expands current bounding box so that it contains given bounding box. * If given bounding box is null, this method has no effect. * * @param bounds bounds */ public void expand(BxBounds bounds) { if (bounds != null) { minX = Math.min(minX, bounds.getX()); minY = Math.min(minY, bounds.getY()); maxX = Math.max(maxX, bounds.getX() + bounds.getWidth()); maxY = Math.max(maxY, bounds.getY() + bounds.getHeight()); } } /** * Returns current bounding box or null if current bounding box is empty. * * @return bounds */ public BxBounds getBounds() { if (minX <= maxX && minY <= maxY) { return new BxBounds(minX, minY, maxX - minX, maxY - minY); } else { return new BxBounds(0, 0, 0, 0); } } /** * Replaces current bounding box with empty bounding box. */ public void clear() { minX = Double.POSITIVE_INFINITY; minY = Double.POSITIVE_INFINITY; maxX = Double.NEGATIVE_INFINITY; maxY = Double.NEGATIVE_INFINITY; } /** * Sets the bounding box of page based on bounding boxes of page zones. * * @param page page */ public static void setBounds(BxPage page) { BxBoundsBuilder builder = new BxBoundsBuilder(); builder.expandByZones(page); page.setBounds(builder.getBounds()); } /** * Sets the bounding box of zone based on bounding boxes of zone lines. * * @param zone zone */ public static void setBounds(BxZone zone) { BxBoundsBuilder builder = new BxBoundsBuilder(); builder.expandByLines(zone); zone.setBounds(builder.getBounds()); } /** * Sets the bounding box of line based on bounding boxes of line words. * * @param line line */ public static void setBounds(BxLine line) { BxBoundsBuilder builder = new BxBoundsBuilder(); builder.expandByWords(line); line.setBounds(builder.getBounds()); } /** * Sets the bounding box of word based on bounding boxes of word chunks. * * @param word word */ public static void setBounds(BxWord word) { BxBoundsBuilder builder = new BxBoundsBuilder(); builder.expandByChunks(word); word.setBounds(builder.getBounds()); } }
5,324
28.098361
80
java
CERMINE
CERMINE-master/cermine-impl/src/main/java/pl/edu/icm/cermine/structure/tools/BxZoneTree.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.tools; import java.util.ArrayList; import java.util.List; import pl.edu.icm.cermine.structure.model.BxZone; /** * @author Pawel Szostek */ public class BxZoneTree { public static class BxZoneTreeNode { private BxZoneOrderTuple tuple; private BxZoneTreeNode parent; private final List<BxZoneTreeNode> children; public BxZoneTreeNode getParent() { return parent; } public void setParent(BxZoneTreeNode parent) { this.parent = parent; } public BxZoneTreeNode(BxZone zone, int order, BxZoneTreeNode parent) { this.tuple = new BxZoneOrderTuple(zone, order); this.children = new ArrayList<BxZoneTreeNode>(); this.parent = parent; } public BxZoneTreeNode(BxZoneOrderTuple node, BxZoneTreeNode parent) { this.tuple = node; this.children = new ArrayList<BxZoneTreeNode>(); this.parent = parent; } public BxZoneOrderTuple getTuple() { return tuple; } public void setTuple(BxZoneOrderTuple tuple) { this.tuple = tuple; } public List<BxZoneTreeNode> getChildren() { return children; } public BxZoneTreeNode addChild(BxZoneOrderTuple tuple) { if (this.tuple.getOrder() == tuple.getOrder()) { parent.getChildren().add(new BxZoneTreeNode(tuple, parent)); return parent; } else if (this.tuple.getOrder() > tuple.getOrder()) { return parent.addChild(tuple); } else { if (children.isEmpty()) { children.add(new BxZoneTreeNode(tuple, this)); return this; } else { BxZoneTreeNode lastChild = children.get(children.size() - 1); if (lastChild.getTuple().getOrder() == tuple.getOrder() || lastChild.getTuple().getOrder() > tuple.getOrder()) { children.add(new BxZoneTreeNode(tuple, this)); return this; } else { return lastChild.addChild(tuple); } } } } private boolean checkChildren(BxZoneTreeNode other) { for (int i = 0; i < getChildren().size(); ++i) { if (!getChildren().get(i).correspondsTo(other.getChildren().get(i))) { return false; } } return true; } private boolean correspondsTo(BxZoneTreeNode other) { if (getTuple().getZone() == null && other.getTuple().getZone() == null) { if (getChildren().size() != other.getChildren().size()) { return false; } return checkChildren(other); } if (getTuple().getZone() == null && other.getTuple().getZone() != null) { return false; } else if (getTuple().getZone() != null && other.getTuple().getZone() == null) { return false; } else if (!getTuple().getZone().equals(other.getTuple().getZone())) { return false; } else if (getChildren().size() != other.getChildren().size()) { return false; } else { return checkChildren(other); } } }; private BxZoneTreeNode root; private BxZoneTreeNode lastNodeExtended; public BxZoneTree() { this.root = new BxZoneTreeNode(null, -1, null); this.lastNodeExtended = this.root; } public BxZoneTreeNode getRoot() { return root; } public void addToRoot(BxZoneOrderTuple node) { root.addChild(node); } public BxZoneTree addNode(BxZone zone, int order) { return this.addNode(new BxZoneOrderTuple(zone, order)); } public BxZoneTree addNode(BxZoneOrderTuple what) { lastNodeExtended = lastNodeExtended.addChild(what); return this; } public boolean correspondsTo(BxZoneTree other) { return root.correspondsTo(other.root); } }
5,016
32.446667
92
java
CERMINE
CERMINE-master/cermine-impl/src/main/java/pl/edu/icm/cermine/structure/tools/ClassificationTransfer.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.tools; import java.util.*; import pl.edu.icm.cermine.structure.model.*; /** * @author Krzysztof Rusek */ public class ClassificationTransfer { private static final double TOLERANCE = 1.0e-3; public void transferClassification(BxDocument source, BxDocument target) { if (source.childrenCount() != target.childrenCount()) { throw new IllegalArgumentException("Page counts of the documents must be equal"); } for (int i = 0; i < source.childrenCount(); i++) { transferClassification(source.getChild(i), target.getChild(i)); } } public void transferClassification(BxPage source, BxPage target) { Map<String, Map<BxChunk, Entry>> map = new HashMap<String, Map<BxChunk, Entry>>(); List<Entry> entries = new ArrayList<Entry>(); for (BxZone zone : target) { Entry entry = new Entry(); entry.zone = zone; for (BxLine line : zone) { for (BxWord word : line) { for (BxChunk chunk : word) { Map<BxChunk, Entry> map2 = map.get(chunk.toText()); if (map2 == null) { map2 = new HashMap<BxChunk, Entry>(); map.put(chunk.toText(), map2); } map2.put(chunk, entry); } } } entries.add(entry); } for (BxZone zone : source) { if (zone.getLabel() == null || zone.getLabel() == BxZoneLabel.OTH_UNKNOWN) { continue; } for (BxLine line : zone) { for (BxWord word : line) { chunkLoop: for (BxChunk chunk : word) { Map<BxChunk, Entry> map2 = map.get(chunk.toText()); if (map2 != null) { for(Map.Entry<BxChunk, Entry> mapEntry : map2.entrySet()) { if (mapEntry.getKey().getBounds().isSimilarTo(chunk.getBounds(), TOLERANCE)) { mapEntry.getValue().hit(zone.getLabel()); continue chunkLoop; } } } } } } } for(Entry entry : entries) { entry.zone.setLabel(entry.findBest()); } } private static class Entry { BxZone zone; Map<BxZoneLabel, Integer> hits = new EnumMap<BxZoneLabel, Integer>(BxZoneLabel.class); Entry() { for(BxZoneLabel label : BxZoneLabel.values()) { hits.put(label, 0); } } void hit(BxZoneLabel label) { hits.put(label, hits.get(label) + 1); } BxZoneLabel findBest() { BxZoneLabel best = BxZoneLabel.OTH_UNKNOWN; int bestHits = 0; for (Map.Entry<BxZoneLabel, Integer> entry : hits.entrySet()) { if (entry.getValue() > bestHits) { bestHits = entry.getValue(); best = entry.getKey(); } } return best; } } }
4,066
34.675439
110
java
CERMINE
CERMINE-master/cermine-impl/src/main/java/pl/edu/icm/cermine/structure/tools/BxZoneOrderTuple.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.tools; import pl.edu.icm.cermine.structure.model.BxZone; /** * @author Pawel Szostek */ public class BxZoneOrderTuple { private BxZone zone; private int order; public BxZoneOrderTuple(BxZone zone, int order) { this.zone = zone; this.order = order; } public BxZone getZone() { return zone; } public void setZone(BxZone zone) { this.zone = zone; } public int getOrder() { return order; } public void setOrder(int order) { this.order = order; } }
1,324
24.480769
78
java
CERMINE
CERMINE-master/cermine-impl/src/main/java/pl/edu/icm/cermine/structure/tools/DocumentProcessor.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.tools; import pl.edu.icm.cermine.exception.AnalysisException; import pl.edu.icm.cermine.structure.model.BxDocument; /** * Document processor interface. * * @author Dominika Tkaczyk (d.tkaczyk@icm.edu.pl) */ public interface DocumentProcessor { /** * Performs an operation on a document. * * @param document document * @throws AnalysisException AnalysisException */ void process(BxDocument document) throws AnalysisException; }
1,242
30.871795
78
java
CERMINE
CERMINE-master/cermine-impl/src/main/java/pl/edu/icm/cermine/structure/tools/UnsegmentedZonesFlattener.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.tools; import com.google.common.collect.Lists; import java.util.ArrayList; import pl.edu.icm.cermine.structure.model.*; /** * @author Dominika Tkaczyk (d.tkaczyk@icm.edu.pl) */ public class UnsegmentedZonesFlattener implements DocumentProcessor { @Override public void process(BxDocument document) { for (BxPage page: document) { for (BxZone zone: page) { for (BxLine line: zone) { for (BxWord word: line) { zone.getChunks().addAll(Lists.newArrayList(word)); } } zone.setLines(new ArrayList<BxLine>()); } } } }
1,455
31.355556
78
java
CERMINE
CERMINE-master/cermine-impl/src/main/java/pl/edu/icm/cermine/structure/tools/InitiallyClassifiedZonesPreprocessor.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.tools; import pl.edu.icm.cermine.structure.model.BxDocument; import pl.edu.icm.cermine.structure.model.BxPage; import pl.edu.icm.cermine.structure.model.BxZone; /** * @author Dominika Tkaczyk (d.tkaczyk@icm.edu.pl) */ public class InitiallyClassifiedZonesPreprocessor implements DocumentProcessor { @Override public void process(BxDocument document) { for (BxPage page: document) { for (BxZone zone: page) { zone.setLabel(zone.getLabel().getGeneralLabel()); } } } }
1,314
31.875
80
java
CERMINE
CERMINE-master/cermine-impl/src/main/java/pl/edu/icm/cermine/structure/readingorder/BxZoneGroup.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.Iterator; import java.util.Set; import pl.edu.icm.cermine.structure.model.BxBounds; import pl.edu.icm.cermine.structure.model.BxObject; import pl.edu.icm.cermine.structure.model.BxZone; /** * Class used for clustering BxObjects into a tree * * @author Pawel Szostek */ public class BxZoneGroup extends BxObject<BxZoneGroup, BxZoneGroup, BxZoneGroup> { private static final long serialVersionUID = 1111043717957023347L; private BxObject leftChild; private BxObject rightChild; public BxZoneGroup(BxObject child1, BxObject child2) { this.leftChild = child1; this.rightChild = child2; setBounds(Math.min(child1.getX(), child2.getX()), Math.min(child1.getY(), child2.getY()), Math.max(child1.getX() + child1.getWidth(), child2.getX() + child2.getWidth()), Math.max(child1.getY() + child1.getHeight(), child2.getY() + child2.getHeight())); } public BxZoneGroup(BxObject zone) { this.leftChild = zone; this.rightChild = null; setBounds(zone.getBounds()); } @Override public BxZoneGroup setBounds(BxBounds bounds) { super.setBounds(bounds); return this; } public boolean hasZone() { return (rightChild == null); } public BxZone getZone() { if (!hasZone()) { throw new RuntimeException(); } assert this.leftChild instanceof BxZone : "There is one child and its not of type BxZone. How comes?"; return (BxZone) this.leftChild; } public BxObject getLeftChild() { return leftChild; } public BxObject getRightChild() { return rightChild; } public BxZoneGroup setLeftChild(BxObject obj) { this.leftChild = obj; return this; } public BxZoneGroup setRightChild(BxObject obj) { this.rightChild = obj; return this; } public BxZoneGroup setBounds(double x0, double y0, double x1, double y1) { assert x1 >= x0; assert y1 >= y0; this.setBounds(new BxBounds(x0, y0, x1 - x0, y1 - y0)); return this; } @Override public String getMostPopularFontName() { throw new UnsupportedOperationException("Not supported yet."); } @Override public Set<String> getFontNames() { throw new UnsupportedOperationException("Not supported yet."); } @Override public String toText() { return leftChild.toText() + "\n" + rightChild.toText(); } @Override public Iterator<BxZoneGroup> iterator() { throw new UnsupportedOperationException("Not supported yet."); } @Override public int childrenCount() { throw new UnsupportedOperationException("Not supported yet."); } @Override public BxZoneGroup getChild(int index) { throw new UnsupportedOperationException("Not supported yet."); } }
3,733
28.401575
110
java
CERMINE
CERMINE-master/cermine-impl/src/main/java/pl/edu/icm/cermine/structure/readingorder/DocumentPlane.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.HashMap; import java.util.List; import java.util.Map; import pl.edu.icm.cermine.structure.model.BxBounds; import pl.edu.icm.cermine.structure.model.BxObject; import pl.edu.icm.cermine.structure.model.BxZone; /** * A set-like data structure for objects placed on a plane. Can efficiently find objects in a certain rectangular area. * It maintains two parallel lists of objects, each of which is sorted by its x or y coordinate. * * @author Pawel Szostek */ public class DocumentPlane { /** * List of objects on the plane. Stored in a random order */ private final List<BxObject> objs; /** * Size of a grid square. If gridSize=50, then the plane is divided into squares of size 50. Each square contains * objects placed in a 50x50 area */ private final int gridSize; /** * Redundant dictionary of objects on the plane. Allows efficient 2D space search. Keys are X-Y coordinates of a * grid square. Single object can be stored under several keys (depending on its physical size). Grid squares are * lazy-initialized. */ private final Map<GridXY, List<BxObject>> grid; /** * Representation of XY coordinates */ private static class GridXY { public int x; public int y; public GridXY(int x, int y) { this.x = x; this.y = y; } @Override public int hashCode() { return x * y; } @Override public boolean equals(Object obj) { if (obj == null || getClass() != obj.getClass()) { return false; } GridXY comparedObj = (GridXY) obj; return x == comparedObj.x && y == comparedObj.y; } @Override public String toString() { return "(" + x + "," + y + ")"; } } public List<BxObject> getObjects() { return objs; } public DocumentPlane(List<BxZone> objectList, int gridSize) { this.grid = new HashMap<GridXY, List<BxObject>>(); this.objs = new ArrayList<BxObject>(); this.gridSize = gridSize; for (BxZone obj : objectList) { add(obj); } } /** * Looks for objects placed between obj1 and obj2 excluding them * @param obj1 object * @param obj2 object * @return object list */ public List<BxObject> findObjectsBetween(BxObject obj1, BxObject obj2) { double x0 = Math.min(obj1.getX(), obj2.getX()); double y0 = Math.min(obj1.getY(), obj2.getY()); double x1 = Math.max(obj1.getX() + obj1.getWidth(), obj2.getX() + obj2.getWidth()); double y1 = Math.max(obj1.getY() + obj1.getHeight(), obj2.getY() + obj2.getHeight()); assert x1 >= x0 && y1 >= y0; BxBounds searchBounds = new BxBounds(x0, y0, x1 - x0, y1 - y0); List<BxObject> objsBetween = find(searchBounds); /* * the rectangle area must contain at least obj1 and obj2 */ objsBetween.remove(obj1); objsBetween.remove(obj2); return objsBetween; } /** * Checks if there is any object placed between obj1 and obj2 * @param obj1 object * @param obj2 object * @return true if anything is placed between, false otherwise */ public boolean anyObjectsBetween(BxObject obj1, BxObject obj2) { List<BxObject> lObjs = findObjectsBetween(obj1, obj2); return !(lObjs.isEmpty()); } /** * Adds object to the plane * @param obj object * @return document plane */ public DocumentPlane add(BxObject obj) { int objsBefore = this.objs.size(); /* * iterate over grid squares */ for (int y = ((int) obj.getY()) / gridSize; y <= ((int) (obj.getY() + obj.getHeight() + gridSize - 1)) / gridSize; ++y) { for (int x = ((int) obj.getX()) / gridSize; x <= ((int) (obj.getX() + obj.getWidth() + gridSize - 1)) / gridSize; ++x) { GridXY xy = new GridXY(x, y); if (!grid.keySet().contains(xy)) { /* * add the non-existing key */ grid.put(xy, new ArrayList<BxObject>()); grid.get(xy).add(obj); assert grid.get(xy).size() == 1; } else { grid.get(xy).add(obj); } } } objs.add(obj); /* * size of the object list should be incremented */ assert objsBefore + 1 == objs.size(); /* * object list must contain the same number of objects as object dictionary */ assert objs.size() == elementsInGrid(); return this; } public DocumentPlane remove(BxObject obj) { /* * iterate over grid squares */ for (int y = ((int) obj.getY()) / gridSize; y <= ((int) (obj.getY() + obj.getHeight() + gridSize - 1)) / gridSize; ++y) { for (int x = ((int) obj.getX()) / gridSize; x <= ((int) (obj.getX() + obj.getWidth() + gridSize - 1)) / gridSize; ++x) { GridXY xy = new GridXY(x, y); if (grid.get(xy).contains(obj)) { grid.get(xy).remove(obj); } } } objs.remove(obj); assert objs.size() == elementsInGrid(); return this; } /** * Find objects within search bounds * * @param searchBounds is a search rectangle * @return list of objects in!side search rectangle */ public List<BxObject> find(BxBounds searchBounds) { List<BxObject> done = new ArrayList<BxObject>(); //contains already considered objects (wrt. optimization) List<BxObject> ret = new ArrayList<BxObject>(); double x0 = searchBounds.getX(); double y0 = searchBounds.getY(); double y1 = searchBounds.getY() + searchBounds.getHeight(); double x1 = searchBounds.getX() + searchBounds.getWidth(); /* * iterate over grid squares */ for (int y = (int)y0 / gridSize; y < ((int) (y1 + gridSize - 1)) / gridSize; ++y) { for (int x = (int)x0 / gridSize; x < ((int) (x1 + gridSize - 1)) / gridSize; ++x) { GridXY xy = new GridXY(x, y); if (!grid.containsKey(xy)) { continue; } for (BxObject obj : grid.get(xy)) { if (done.contains(obj)) /* * omit if already checked */ { continue; } /* * add to the checked objects */ done.add(obj); /* * check if two objects overlap */ if (obj.getX() + obj.getWidth() <= x0 || x1 <= obj.getX() || obj.getY() + obj.getHeight() <= y0 || y1 <= obj.getY()) { continue; } ret.add(obj); } } } return ret; } /** * Count objects stored in objects dictionary * @return number of elements */ protected int elementsInGrid() { List<BxObject> objs_ = new ArrayList<BxObject>(); for (GridXY coord : grid.keySet()) { for (BxObject obj : grid.get(coord)) { if (!objs_.contains(obj)) { objs_.add(obj); } } } return objs_.size(); } public String dump() { StringBuilder sb = new StringBuilder(); for (GridXY iter : grid.keySet()) { sb.append(iter.toString()).append(" ["); for (BxObject obj : grid.get(iter)) { if (obj instanceof BxZoneGroup) { BxZoneGroup group = (BxZoneGroup) obj; sb.append(group.getLeftChild()); sb.append(group.getRightChild()); } else if (obj instanceof BxZone) { BxZone zone = (BxZone) obj; sb.append(zone); } sb.append("\n"); } sb.append("]\n"); } return sb.toString(); } }
9,237
33.470149
132
java