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-tools/src/main/java/pl/edu/icm/cermine/evaluation/transformers/ParscitToContentConverter.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.evaluation.transformers; import java.util.List; import org.jdom.Element; import pl.edu.icm.cermine.content.model.ContentStructure; import pl.edu.icm.cermine.content.model.DocumentSection; import pl.edu.icm.cermine.exception.TransformationException; import pl.edu.icm.cermine.tools.XMLTools; import pl.edu.icm.cermine.tools.transformers.ModelToModelConverter; /** * @author Dominika Tkaczyk (d.tkaczyk@icm.edu.pl) */ public class ParscitToContentConverter implements ModelToModelConverter<Element, ContentStructure> { @Override public ContentStructure convert(Element source, Object... hints) throws TransformationException { ContentStructure struct = new ContentStructure(); if (source == null) { return struct; } DocumentSection sec1 = null; DocumentSection sec2 = null; for (Object secElem : source.getChildren()) { if (!(secElem instanceof Element)) { continue; } Element sectionNode = (Element) secElem; if (!sectionNode.getName().endsWith("sectionHeader")) { continue; } DocumentSection section = new DocumentSection(); section.setTitle(XMLTools.getTextContent(sectionNode)); if (sec1 == null || sec2 == null) { DocumentSection s = new DocumentSection(); s.setTitle("-"); s.setLevel(1); struct.addSection(s); sec1 = s; sec2 = s; } if ("sectionHeader".equals(sectionNode.getName())) { section.setLevel(1); struct.addSection(section); sec1 = section; sec2 = section; } else if ("subsectionHeader".equals(sectionNode.getName())) { section.setLevel(2); sec1.addSection(section); sec2 = section; } else if ("subsubsectionHeader".equals(sectionNode.getName())) { section.setLevel(3); sec2.addSection(section); } } return struct; } @Override public List<ContentStructure> convertAll(List<Element> source, Object... hints) throws TransformationException { throw new UnsupportedOperationException("Not supported yet."); } }
3,166
35.825581
116
java
CERMINE
CERMINE-master/cermine-tools/src/main/java/pl/edu/icm/cermine/evaluation/transformers/ParscitToMetadataConverter.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.evaluation.transformers; import java.util.ArrayList; import java.util.List; import org.jdom.Element; import org.jdom.JDOMException; import org.jdom.xpath.XPath; import pl.edu.icm.cermine.exception.TransformationException; import pl.edu.icm.cermine.metadata.model.DocumentMetadata; import pl.edu.icm.cermine.tools.XMLTools; import pl.edu.icm.cermine.tools.transformers.ModelToModelConverter; /** * @author Dominika Tkaczyk (d.tkaczyk@icm.edu.pl) */ public class ParscitToMetadataConverter implements ModelToModelConverter<Element, DocumentMetadata> { @Override public DocumentMetadata convert(Element source, Object... hints) throws TransformationException { try { DocumentMetadata metadata = new DocumentMetadata(); convertTitle(source, metadata); convertAbstract(source, metadata); convertAuthors(source, metadata); convertEmails(source, metadata); convertAffiliations(source, metadata); return metadata; } catch (JDOMException ex) { throw new TransformationException(ex); } } private void convertTitle(Element source, DocumentMetadata metadata) throws JDOMException { XPath xpath = XPath.newInstance("//algorithm[@name='ParsHed']//title"); metadata.setTitle(selectWithMaxConfidence(xpath.selectNodes(source))); } private void convertAbstract(Element source, DocumentMetadata metadata) throws JDOMException { XPath xpath = XPath.newInstance("//algorithm[@name='ParsHed']//abstract"); metadata.setAbstrakt(selectWithMaxConfidence(xpath.selectNodes(source))); } private void convertAuthors(Element source, DocumentMetadata metadata) throws JDOMException { XPath xpath = XPath.newInstance("//algorithm[@name='ParsHed']//author"); List authors = xpath.selectNodes(source); for (Object a : authors) { Element author = (Element) a; metadata.addAuthor(XMLTools.getTextContent(author), new ArrayList<String>()); } } private void convertEmails(Element source, DocumentMetadata metadata) throws JDOMException { XPath xpath = XPath.newInstance("//algorithm[@name='ParsHed']//email"); List authors = xpath.selectNodes(source); for (Object a : authors) { Element author = (Element) a; metadata.addEmail(XMLTools.getTextContent(author)); } } private void convertAffiliations(Element source, DocumentMetadata metadata) throws JDOMException { XPath xpath = XPath.newInstance("//algorithm[@name='ParsHed']//affiliation"); List affs = xpath.selectNodes(source); for (Object a : affs) { Element affiliation = (Element)a; metadata.addAffiliationToAllAuthors(XMLTools.getTextContent(affiliation)); } } private String selectWithMaxConfidence(List elements) { double maxConf = 0; String content = null; for (Object element: elements) { Element node = (Element) element; if (content == null) { content = XMLTools.getTextContent(node); } if (node.getAttribute("confidence") != null) { double conf = Double.valueOf(node.getAttributeValue("confidence")); if (conf > maxConf) { maxConf = conf; content = XMLTools.getTextContent(node); } } } return content; } @Override public List<DocumentMetadata> convertAll(List<Element> source, Object... hints) throws TransformationException { throw new UnsupportedOperationException("Not supported yet."); } }
4,540
38.486957
116
java
CERMINE
CERMINE-master/cermine-tools/src/main/java/pl/edu/icm/cermine/evaluation/transformers/GrobidToDocumentReader.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.evaluation.transformers; import java.io.IOException; import java.io.Reader; import java.io.StringReader; import java.util.ArrayList; import java.util.List; import org.jdom.Element; import org.jdom.JDOMException; import org.jdom.input.SAXBuilder; import org.jdom.xpath.XPath; import pl.edu.icm.cermine.bibref.model.BibEntry; import pl.edu.icm.cermine.content.model.ContentStructure; import pl.edu.icm.cermine.exception.TransformationException; import pl.edu.icm.cermine.metadata.model.DocumentMetadata; import pl.edu.icm.cermine.model.Document; import pl.edu.icm.cermine.tools.transformers.FormatToModelReader; import pl.edu.icm.cermine.tools.transformers.ModelToModelConverter; /** * @author Dominika Tkaczyk (d.tkaczyk@icm.edu.pl) */ public class GrobidToDocumentReader implements FormatToModelReader<Document> { @Override public Document read(String string, Object... hints) throws TransformationException { return read(new StringReader(string), hints); } @Override public Document read(Reader reader, Object... hints) throws TransformationException { try { ModelToModelConverter<Element, DocumentMetadata> metaConverter = new GrobidToMetadataConverter(); ModelToModelConverter<Element, ContentStructure> structConverter = new GrobidToContentConverter(); ModelToModelConverter<Element, BibEntry> refConverter = new ElementToBibEntryConverter(); Element root = getRoot(reader); Document document = new Document(); XPath xpath = XPath.newInstance("/x:TEI/x:teiHeader"); xpath.addNamespace("x", root.getNamespaceURI()); Element parshed = (Element) xpath.selectSingleNode(root); document.setMetadata(metaConverter.convert(parshed)); xpath = XPath.newInstance("/x:TEI/x:text/x:body"); xpath.addNamespace("x", root.getNamespaceURI()); Element sectlabel = (Element) xpath.selectSingleNode(root); document.setContent(structConverter.convert(sectlabel)); xpath = XPath.newInstance("/x:TEI/x:text/x:back//x:listBibl//x:biblStruct"); xpath.addNamespace("x", root.getNamespaceURI()); List nodes = xpath.selectNodes(root); List<Element> refElems = new ArrayList<Element>(); for(Object node: nodes) { refElems.add((Element) node); } document.setReferences(refConverter.convertAll(refElems)); return document; } catch (JDOMException ex) { throw new TransformationException(ex); } catch (IOException ex) { throw new TransformationException(ex); } } private Element getRoot(Reader reader) throws JDOMException, IOException { SAXBuilder builder = new SAXBuilder("org.apache.xerces.parsers.SAXParser"); builder.setValidation(false); builder.setFeature("http://xml.org/sax/features/validation", false); builder.setFeature("http://apache.org/xml/features/nonvalidating/load-dtd-grammar", false); builder.setFeature("http://apache.org/xml/features/nonvalidating/load-external-dtd", false); org.jdom.Document dom = builder.build(reader); return dom.getRootElement(); } @Override public List<Document> readAll(String string, Object... hints) throws TransformationException { throw new UnsupportedOperationException("Not supported yet."); } @Override public List<Document> readAll(Reader reader, Object... hints) throws TransformationException { throw new UnsupportedOperationException("Not supported yet."); } }
4,485
40.925234
110
java
CERMINE
CERMINE-master/cermine-tools/src/main/java/pl/edu/icm/cermine/evaluation/transformers/BwmetaToMetadataConverter.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.evaluation.transformers; import java.util.ArrayList; import java.util.List; import org.jdom.Attribute; import org.jdom.Element; import org.jdom.JDOMException; import org.jdom.xpath.XPath; import pl.edu.icm.cermine.exception.TransformationException; import pl.edu.icm.cermine.metadata.model.DateType; import pl.edu.icm.cermine.metadata.model.DocumentMetadata; import pl.edu.icm.cermine.metadata.model.IDType; import pl.edu.icm.cermine.tools.XMLTools; import pl.edu.icm.cermine.tools.transformers.ModelToModelConverter; /** * @author Dominika Tkaczyk (d.tkaczyk@icm.edu.pl) */ public class BwmetaToMetadataConverter implements ModelToModelConverter<Element, DocumentMetadata> { @Override public DocumentMetadata convert(Element source, Object... hints) throws TransformationException { try { DocumentMetadata metadata = new DocumentMetadata(); convertTitle(source, metadata); convertAbstract(source, metadata); convertJournal(source, metadata); convertVolume(source, metadata); convertIssue(source, metadata); convertPages(source, metadata); convertKeywords(source, metadata); convertDoi(source, metadata); convertYear(source, metadata); convertAuthors(source, metadata); convertAffiliations(source, metadata); return metadata; } catch (JDOMException ex) { throw new TransformationException(ex); } } private void convertTitle(Element source, DocumentMetadata metadata) throws JDOMException { XPath xpath = XPath.newInstance("./x:element/x:name[not(@type)]"); xpath.addNamespace("x", source.getNamespaceURI()); Element title = (Element)xpath.selectSingleNode(source); if (title != null) { metadata.setTitle(XMLTools.getTextContent(title)); } } private void convertAbstract(Element source, DocumentMetadata metadata) throws JDOMException { XPath xpath = XPath.newInstance("./x:element/x:description[@type='abstract']"); xpath.addNamespace("x", source.getNamespaceURI()); Element abstrakt = (Element)xpath.selectSingleNode(source); if (abstrakt != null) { metadata.setAbstrakt(XMLTools.getTextContent(abstrakt)); } } private void convertJournal(Element source, DocumentMetadata metadata) throws JDOMException { XPath xpath = XPath.newInstance("./x:element/x:structure/x:ancestor[@level='bwmeta1.level.hierarchy_Journal_Journal']/x:name[@type='canonical']"); xpath.addNamespace("x", source.getNamespaceURI()); Element journal = (Element)xpath.selectSingleNode(source); if (journal != null) { metadata.setJournal(XMLTools.getTextContent(journal)); } } private void convertVolume(Element source, DocumentMetadata metadata) throws JDOMException { XPath xpath = XPath.newInstance("./x:element/x:structure/x:ancestor[@level='bwmeta1.level.hierarchy_Journal_Volume']/x:name[@type='canonical']"); xpath.addNamespace("x", source.getNamespaceURI()); Element volume = (Element)xpath.selectSingleNode(source); if (volume != null) { metadata.setVolume(XMLTools.getTextContent(volume)); } } private void convertIssue(Element source, DocumentMetadata metadata) throws JDOMException { XPath xpath = XPath.newInstance("./x:element/x:structure/x:ancestor[@level='bwmeta1.level.hierarchy_Journal_Number']/x:name[@type='canonical']"); xpath.addNamespace("x", source.getNamespaceURI()); Element issue = (Element)xpath.selectSingleNode(source); if (issue != null) { metadata.setIssue(XMLTools.getTextContent(issue)); } } private void convertPages(Element source, DocumentMetadata metadata) throws JDOMException { XPath xpath = XPath.newInstance("./x:element/x:structure/x:current[@level='bwmeta1.level.hierarchy_Journal_Article']/@position"); xpath.addNamespace("x", source.getNamespaceURI()); Attribute pages = (Attribute)xpath.selectSingleNode(source); if (pages != null) { String fp = pages.getValue().replaceFirst("-.*", ""); String lp = pages.getValue().replaceFirst(".*-", ""); metadata.setPages(fp, lp); } } private void convertKeywords(Element source, DocumentMetadata metadata) throws JDOMException { XPath xpath = XPath.newInstance("./x:element/x:tags[@type='keyword']/x:tag"); xpath.addNamespace("x", source.getNamespaceURI()); List keywords = xpath.selectNodes(source); for (Object keyword : keywords) { metadata.addKeyword(XMLTools.getTextContent((Element)keyword)); } } private void convertDoi(Element source, DocumentMetadata metadata) throws JDOMException { XPath xpath = XPath.newInstance("./x:element/x:id[@scheme='bwmeta1.id-class.DOI']/@value"); xpath.addNamespace("x", source.getNamespaceURI()); Attribute doi = (Attribute)xpath.selectSingleNode(source); if (doi != null) { metadata.addId(IDType.DOI, doi.getValue()); } } private void convertYear(Element source, DocumentMetadata metadata) throws JDOMException { XPath xpath = XPath.newInstance("./x:element/x:structure/x:ancestor[@level='bwmeta1.level.hierarchy_Journal_Year']/x:name[@type='canonical']"); xpath.addNamespace("x", source.getNamespaceURI()); Element year = (Element)xpath.selectSingleNode(source); if (year != null) { metadata.setDate(DateType.PUBLISHED, null, null, XMLTools.getTextContent(year)); } } private void convertAuthors(Element source, DocumentMetadata metadata) throws JDOMException { XPath xpath = XPath.newInstance("./x:element/x:contributor[@role='author']"); xpath.addNamespace("x", source.getNamespaceURI()); List authors = xpath.selectNodes(source); for (Object a : authors) { Element author = (Element) a; XPath nxpath = XPath.newInstance("./x:name[@type='canonical']"); nxpath.addNamespace("x", author.getNamespaceURI()); Element authorName = (Element)nxpath.selectSingleNode(author); if (authorName == null) { continue; } List<String> ais = new ArrayList<String>(); nxpath = XPath.newInstance("./x:affiliation-ref/@ref"); nxpath.addNamespace("x", author.getNamespaceURI()); List affRefs = nxpath.selectNodes(author); for (Object affRef : affRefs) { ais.add(((Attribute)affRef).getValue()); } nxpath = XPath.newInstance("./x:attribute[@key='contact-email']/x:value"); nxpath.addNamespace("x", author.getNamespaceURI()); Element email = (Element)nxpath.selectSingleNode(author); if (email == null) { metadata.addAuthor(XMLTools.getTextContent(authorName), ais); } else { metadata.addAuthor(XMLTools.getTextContent(authorName), ais, XMLTools.getTextContent(email)); } } } private void convertAffiliations(Element source, DocumentMetadata metadata) throws JDOMException { XPath xpath = XPath.newInstance("./x:element/x:affiliation"); xpath.addNamespace("x", source.getNamespaceURI()); List affs = xpath.selectNodes(source); for (Object a : affs) { Element affiliation = (Element)a; String id = affiliation.getAttributeValue("id"); String text = XMLTools.getTextContent(affiliation.getChild("text", source.getNamespace())); if (id == null) { metadata.addAffiliationToAllAuthors(text); } else { metadata.setAffiliationByIndex(id, text); } } } @Override public List<DocumentMetadata> convertAll(List<Element> source, Object... hints) throws TransformationException { throw new UnsupportedOperationException("Not supported yet."); } }
9,037
44.417085
154
java
CERMINE
CERMINE-master/cermine-tools/src/main/java/pl/edu/icm/cermine/evaluation/transformers/GrobidToContentConverter.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.evaluation.transformers; import java.util.List; import org.jdom.Element; import org.jdom.JDOMException; import org.jdom.xpath.XPath; import pl.edu.icm.cermine.content.model.ContentStructure; import pl.edu.icm.cermine.content.model.DocumentSection; import pl.edu.icm.cermine.exception.TransformationException; import pl.edu.icm.cermine.tools.XMLTools; import pl.edu.icm.cermine.tools.transformers.ModelToModelConverter; /** * @author Dominika Tkaczyk (d.tkaczyk@icm.edu.pl) */ public class GrobidToContentConverter implements ModelToModelConverter<Element, ContentStructure> { @Override public ContentStructure convert(Element source, Object... hints) throws TransformationException { try { ContentStructure struct = new ContentStructure(); if (source == null) { return struct; } XPath xpath = XPath.newInstance(".//x:div/x:head"); xpath.addNamespace("x", source.getNamespaceURI()); for (Object secElem : xpath.selectNodes(source)) { Element sectionNode = (Element) secElem; DocumentSection section = new DocumentSection(); section.setTitle(XMLTools.getTextContent(sectionNode)); struct.addSection(section); } return struct; } catch (JDOMException ex) { throw new TransformationException(ex); } } @Override public List<ContentStructure> convertAll(List<Element> source, Object... hints) throws TransformationException { throw new UnsupportedOperationException("Not supported yet."); } }
2,427
36.353846
116
java
CERMINE
CERMINE-master/cermine-tools/src/main/java/pl/edu/icm/cermine/evaluation/transformers/NLMToDocumentReader.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.evaluation.transformers; import java.io.IOException; import java.io.Reader; import java.io.StringReader; import java.util.ArrayList; import java.util.List; import org.jdom.Element; import org.jdom.JDOMException; import org.jdom.input.SAXBuilder; import pl.edu.icm.cermine.bibref.model.BibEntry; import pl.edu.icm.cermine.content.model.ContentStructure; import pl.edu.icm.cermine.exception.TransformationException; import pl.edu.icm.cermine.metadata.model.DocumentMetadata; import pl.edu.icm.cermine.metadata.transformers.NLMToMetadataConverter; import pl.edu.icm.cermine.model.Document; import pl.edu.icm.cermine.tools.transformers.FormatToModelReader; import pl.edu.icm.cermine.tools.transformers.ModelToModelConverter; /** * @author Dominika Tkaczyk (d.tkaczyk@icm.edu.pl) */ public class NLMToDocumentReader implements FormatToModelReader<Document> { @Override public Document read(String string, Object... hints) throws TransformationException { return read(new StringReader(string), hints); } @Override public Document read(Reader reader, Object... hints) throws TransformationException { try { ModelToModelConverter<Element, DocumentMetadata> metaConverter = new NLMToMetadataConverter(); ModelToModelConverter<Element, ContentStructure> structConverter = new NLMToContentConverter(); ModelToModelConverter<Element, BibEntry> refConverter = new ElementToBibEntryConverter(); Element root = getRoot(reader); Document document = new Document(); document.setMetadata(metaConverter.convert(root.getChild("front"))); document.setContent(structConverter.convert(root.getChild("body"))); if (root.getChild("back") != null && root.getChild("back").getChild("ref-list") != null) { document.setReferences(refConverter.convertAll(root.getChild("back") .getChild("ref-list").getChildren("ref"))); } else { document.setReferences(new ArrayList<BibEntry>()); } return document; } catch (JDOMException ex) { throw new TransformationException(ex); } catch (IOException ex) { throw new TransformationException(ex); } } private Element getRoot(Reader reader) throws JDOMException, IOException { SAXBuilder builder = new SAXBuilder("org.apache.xerces.parsers.SAXParser"); builder.setValidation(false); builder.setFeature("http://xml.org/sax/features/validation", false); builder.setFeature("http://apache.org/xml/features/nonvalidating/load-dtd-grammar", false); builder.setFeature("http://apache.org/xml/features/nonvalidating/load-external-dtd", false); org.jdom.Document dom = builder.build(reader); return dom.getRootElement(); } @Override public List<Document> readAll(String string, Object... hints) throws TransformationException { throw new UnsupportedOperationException("Not supported yet."); } @Override public List<Document> readAll(Reader reader, Object... hints) throws TransformationException { throw new UnsupportedOperationException("Not supported yet."); } }
4,043
41.125
118
java
CERMINE
CERMINE-master/cermine-tools/src/main/java/pl/edu/icm/cermine/evaluation/transformers/GrobidToMetadataConverter.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.evaluation.transformers; import java.util.ArrayList; import java.util.List; import org.jdom.Attribute; import org.jdom.Element; import org.jdom.JDOMException; import org.jdom.xpath.XPath; import pl.edu.icm.cermine.exception.TransformationException; import pl.edu.icm.cermine.metadata.model.DateType; import pl.edu.icm.cermine.metadata.model.DocumentMetadata; import pl.edu.icm.cermine.metadata.model.IDType; import pl.edu.icm.cermine.tools.XMLTools; import pl.edu.icm.cermine.tools.transformers.ModelToModelConverter; /** * @author Dominika Tkaczyk (d.tkaczyk@icm.edu.pl) */ public class GrobidToMetadataConverter implements ModelToModelConverter<Element, DocumentMetadata> { @Override public DocumentMetadata convert(Element source, Object... hints) throws TransformationException { try { DocumentMetadata metadata = new DocumentMetadata(); convertTitle(source, metadata); convertAbstract(source, metadata); convertJournal(source, metadata); convertVolume(source, metadata); convertIssue(source, metadata); convertPages(source, metadata); convertKeywords(source, metadata); convertDoi(source, metadata); convertYear(source, metadata); convertAuthors(source, metadata); return metadata; } catch (JDOMException ex) { throw new TransformationException(ex); } } private void convertTitle(Element source, DocumentMetadata metadata) throws JDOMException { XPath xpath = XPath.newInstance(".//x:titleStmt/x:title"); xpath.addNamespace("x", source.getNamespaceURI()); Element title = (Element)xpath.selectSingleNode(source); if (title != null) { metadata.setTitle(XMLTools.getTextContent(title)); } } private void convertAbstract(Element source, DocumentMetadata metadata) throws JDOMException { XPath xpath = XPath.newInstance(".//x:abstract"); xpath.addNamespace("x", source.getNamespaceURI()); Element abstrakt = (Element)xpath.selectSingleNode(source); if (abstrakt != null) { metadata.setAbstrakt(XMLTools.getTextContent(abstrakt)); } } private void convertJournal(Element source, DocumentMetadata metadata) throws JDOMException { XPath xpath = XPath.newInstance(".//x:monogr/x:title[@level='j' and @type='main']"); xpath.addNamespace("x", source.getNamespaceURI()); Element journal = (Element)xpath.selectSingleNode(source); if (journal != null) { metadata.setJournal(XMLTools.getTextContent(journal)); } } private void convertVolume(Element source, DocumentMetadata metadata) throws JDOMException { XPath xpath = XPath.newInstance(".//x:monogr/x:imprint/x:biblScope[@unit='volume']"); xpath.addNamespace("x", source.getNamespaceURI()); Element volume = (Element)xpath.selectSingleNode(source); if (volume != null) { metadata.setVolume(XMLTools.getTextContent(volume)); } } private void convertIssue(Element source, DocumentMetadata metadata) throws JDOMException { XPath xpath = XPath.newInstance(".//x:monogr/x:imprint/x:biblScope[@unit='issue']"); xpath.addNamespace("x", source.getNamespaceURI()); Element issue = (Element)xpath.selectSingleNode(source); if (issue != null) { metadata.setIssue(XMLTools.getTextContent(issue)); } } private void convertPages(Element source, DocumentMetadata metadata) throws JDOMException { XPath xpath = XPath.newInstance(".//x:monogr/x:imprint/x:biblScope[@unit='page']/@from"); xpath.addNamespace("x", source.getNamespaceURI()); Attribute fPage = (Attribute)xpath.selectSingleNode(source); String fp = ""; if (fPage != null) { fp = fPage.getValue(); } xpath = XPath.newInstance(".//x:monogr/x:imprint/x:biblScope[@unit='page']/@to"); xpath.addNamespace("x", source.getNamespaceURI()); Attribute lPage = (Attribute)xpath.selectSingleNode(source); String lp = ""; if (lPage != null) { lp = lPage.getValue(); } metadata.setPages(fp, lp); } private void convertKeywords(Element source, DocumentMetadata metadata) throws JDOMException { XPath xpath = XPath.newInstance(".//x:keywords//x:term"); xpath.addNamespace("x", source.getNamespaceURI()); List keywords = xpath.selectNodes(source); for (Object keyword : keywords) { metadata.addKeyword(XMLTools.getTextContent((Element)keyword)); } } private void convertDoi(Element source, DocumentMetadata metadata) throws JDOMException { XPath xpath = XPath.newInstance(".//x:idno[@type='DOI']"); xpath.addNamespace("x", source.getNamespaceURI()); Element doi = (Element)xpath.selectSingleNode(source); if (doi != null) { metadata.addId(IDType.DOI, XMLTools.getTextContent(doi)); } } private void convertYear(Element source, DocumentMetadata metadata) throws JDOMException { XPath xpath = XPath.newInstance(".//x:date[@type='published']/@when"); xpath.addNamespace("x", source.getNamespaceURI()); Attribute pubYear = (Attribute)xpath.selectSingleNode(source); if (pubYear != null) { metadata.setDate(DateType.PUBLISHED, null, null, pubYear.getValue()); } } private void convertAuthors(Element source, DocumentMetadata metadata) throws JDOMException { XPath xpath = XPath.newInstance(".//x:sourceDesc/x:biblStruct//x:author"); xpath.addNamespace("x", source.getNamespaceURI()); List authors = xpath.selectNodes(source); for (Object a : authors) { Element author = (Element)a; Element persName = author.getChild("persName", source.getNamespace()); String name = XMLTools.getTextContent(persName); if (name == null) { name = XMLTools.getTextContent(author.getChild("collab")); } Element emailNode = author.getChild("email", source.getNamespace()); String email = XMLTools.getTextContent(emailNode); List<String> affiliations = new ArrayList<String>(); for (Object ch: author.getChildren("affiliation", source.getNamespace())) { affiliations.add(XMLTools.getTextContent((Element) ch)); } metadata.addAuthorWithAffiliations(name, email, affiliations); } } @Override public List<DocumentMetadata> convertAll(List<Element> source, Object... hints) throws TransformationException { throw new UnsupportedOperationException("Not supported yet."); } }
7,754
41.60989
116
java
CERMINE
CERMINE-master/cermine-tools/src/main/java/pl/edu/icm/cermine/evaluation/transformers/BwmetaToDocumentReader.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.evaluation.transformers; import java.io.IOException; import java.io.Reader; import java.io.StringReader; import java.util.ArrayList; import java.util.List; import org.jdom.Element; import org.jdom.JDOMException; import org.jdom.input.SAXBuilder; import org.jdom.xpath.XPath; import pl.edu.icm.cermine.bibref.model.BibEntry; import pl.edu.icm.cermine.content.model.ContentStructure; import pl.edu.icm.cermine.exception.TransformationException; import pl.edu.icm.cermine.metadata.model.DocumentMetadata; import pl.edu.icm.cermine.model.Document; import pl.edu.icm.cermine.tools.transformers.FormatToModelReader; import pl.edu.icm.cermine.tools.transformers.ModelToModelConverter; /** * Reads DocumentContentStructure model from HTML format. * * @author Dominika Tkaczyk (d.tkaczyk@icm.edu.pl) */ public class BwmetaToDocumentReader implements FormatToModelReader<Document> { @Override public Document read(String string, Object... hints) throws TransformationException { return read(new StringReader(string), hints); } @Override public Document read(Reader reader, Object... hints) throws TransformationException { try { ModelToModelConverter<Element, DocumentMetadata> metaConverter = new BwmetaToMetadataConverter(); ModelToModelConverter<Element, BibEntry> refConverter = new ElementToBibEntryConverter(); Element root = getRoot(reader); Document document = new Document(); document.setMetadata(metaConverter.convert(root)); document.setContent(new ContentStructure()); XPath xpath = XPath.newInstance(".//x:relation[@type='reference-to']/x:attribute[@key='reference-text']/x:value"); xpath.addNamespace("x", root.getNamespaceURI()); List nodes = xpath.selectNodes(root); List<Element> refElems = new ArrayList<Element>(); for(Object node: nodes) { refElems.add((Element) node); } document.setReferences(refConverter.convertAll(refElems)); return document; } catch (JDOMException ex) { throw new TransformationException(ex); } catch (IOException ex) { throw new TransformationException(ex); } } private Element getRoot(Reader reader) throws JDOMException, IOException { SAXBuilder builder = new SAXBuilder("org.apache.xerces.parsers.SAXParser"); builder.setValidation(false); builder.setFeature("http://xml.org/sax/features/validation", false); builder.setFeature("http://apache.org/xml/features/nonvalidating/load-dtd-grammar", false); builder.setFeature("http://apache.org/xml/features/nonvalidating/load-external-dtd", false); org.jdom.Document dom = builder.build(reader); return dom.getRootElement(); } @Override public List<Document> readAll(String string, Object... hints) throws TransformationException { throw new UnsupportedOperationException("Not supported yet."); } @Override public List<Document> readAll(Reader reader, Object... hints) throws TransformationException { throw new UnsupportedOperationException("Not supported yet."); } }
4,030
39.31
126
java
CERMINE
CERMINE-master/cermine-tools/src/main/java/pl/edu/icm/cermine/evaluation/transformers/PdfxToDocumentReader.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.evaluation.transformers; import java.io.IOException; import java.io.Reader; import java.io.StringReader; import java.util.ArrayList; import java.util.List; import org.jdom.Element; import org.jdom.JDOMException; import org.jdom.input.SAXBuilder; import org.jdom.xpath.XPath; import pl.edu.icm.cermine.bibref.model.BibEntry; import pl.edu.icm.cermine.content.model.ContentStructure; import pl.edu.icm.cermine.exception.TransformationException; import pl.edu.icm.cermine.metadata.model.DocumentMetadata; import pl.edu.icm.cermine.model.Document; import pl.edu.icm.cermine.tools.transformers.FormatToModelReader; import pl.edu.icm.cermine.tools.transformers.ModelToModelConverter; /** * Reads DocumentContentStructure model from HTML format. * * @author Dominika Tkaczyk (d.tkaczyk@icm.edu.pl) */ public class PdfxToDocumentReader implements FormatToModelReader<Document> { @Override public Document read(String string, Object... hints) throws TransformationException { return read(new StringReader(string), hints); } @Override public Document read(Reader reader, Object... hints) throws TransformationException { try { ModelToModelConverter<Element, DocumentMetadata> metaConverter = new PdfxToMetadataConverter(); ModelToModelConverter<Element, ContentStructure> structConverter = new PdfxToContentConverter(); ModelToModelConverter<Element, BibEntry> refConverter = new ElementToBibEntryConverter(); Element root = getRoot(reader); Document document = new Document(); document.setMetadata(metaConverter.convert(root)); document.setContent(structConverter.convert(root.getChild("article").getChild("body"))); XPath xpath = XPath.newInstance("//ref-list/ref"); List nodes = xpath.selectNodes(root); List<Element> refElems = new ArrayList<Element>(); for(Object node: nodes) { refElems.add((Element) node); } document.setReferences(refConverter.convertAll(refElems)); return document; } catch (JDOMException ex) { throw new TransformationException(ex); } catch (IOException ex) { throw new TransformationException(ex); } } private Element getRoot(Reader reader) throws JDOMException, IOException { SAXBuilder builder = new SAXBuilder("org.apache.xerces.parsers.SAXParser"); builder.setValidation(false); builder.setFeature("http://xml.org/sax/features/validation", false); builder.setFeature("http://apache.org/xml/features/nonvalidating/load-dtd-grammar", false); builder.setFeature("http://apache.org/xml/features/nonvalidating/load-external-dtd", false); org.jdom.Document dom = builder.build(reader); return dom.getRootElement(); } @Override public List<Document> readAll(String string, Object... hints) throws TransformationException { throw new UnsupportedOperationException("Not supported yet."); } @Override public List<Document> readAll(Reader reader, Object... hints) throws TransformationException { throw new UnsupportedOperationException("Not supported yet."); } }
4,075
39.356436
108
java
CERMINE
CERMINE-master/cermine-tools/src/main/java/pl/edu/icm/cermine/evaluation/transformers/PdfExtractToDocumentReader.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.evaluation.transformers; import java.io.IOException; import java.io.Reader; import java.io.StringReader; import java.util.ArrayList; import java.util.List; import org.jdom.Element; import org.jdom.JDOMException; import org.jdom.input.SAXBuilder; import org.jdom.xpath.XPath; import pl.edu.icm.cermine.bibref.model.BibEntry; import pl.edu.icm.cermine.exception.TransformationException; import pl.edu.icm.cermine.metadata.model.DocumentMetadata; import pl.edu.icm.cermine.model.Document; import pl.edu.icm.cermine.tools.XMLTools; import pl.edu.icm.cermine.tools.transformers.FormatToModelReader; import pl.edu.icm.cermine.tools.transformers.ModelToModelConverter; /** * @author Dominika Tkaczyk (d.tkaczyk@icm.edu.pl) */ public class PdfExtractToDocumentReader implements FormatToModelReader<Document> { @Override public Document read(String string, Object... hints) throws TransformationException { return read(new StringReader(string), hints); } @Override public Document read(Reader reader, Object... hints) throws TransformationException { try { ModelToModelConverter<Element, BibEntry> refConverter = new ElementToBibEntryConverter(); Element root = getRoot(reader); Document document = new Document(); DocumentMetadata metadata = new DocumentMetadata(); XPath xpath = XPath.newInstance("/pdf/title"); Element title = (Element) xpath.selectSingleNode(root); metadata.setTitle(XMLTools.getTextContent(title)); document.setMetadata(metadata); xpath = XPath.newInstance("/pdf/reference"); List nodes = xpath.selectNodes(root); List<Element> refElems = new ArrayList<Element>(); for(Object node: nodes) { refElems.add((Element) node); } document.setReferences(refConverter.convertAll(refElems)); return document; } catch (JDOMException ex) { throw new TransformationException(ex); } catch (IOException ex) { throw new TransformationException(ex); } } private Element getRoot(Reader reader) throws JDOMException, IOException { SAXBuilder builder = new SAXBuilder("org.apache.xerces.parsers.SAXParser"); builder.setValidation(false); builder.setFeature("http://xml.org/sax/features/validation", false); builder.setFeature("http://apache.org/xml/features/nonvalidating/load-dtd-grammar", false); builder.setFeature("http://apache.org/xml/features/nonvalidating/load-external-dtd", false); org.jdom.Document dom = builder.build(reader); return dom.getRootElement(); } @Override public List<Document> readAll(String string, Object... hints) throws TransformationException { throw new UnsupportedOperationException("Not supported yet."); } @Override public List<Document> readAll(Reader reader, Object... hints) throws TransformationException { throw new UnsupportedOperationException("Not supported yet."); } }
3,891
37.92
101
java
CERMINE
CERMINE-master/cermine-tools/src/main/java/pl/edu/icm/cermine/libsvm/training/SVMBodyBuilder.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.libsvm.training; import java.io.File; import java.io.IOException; import java.util.ArrayList; import java.util.EnumMap; import java.util.List; import java.util.Map; import libsvm.svm_parameter; import org.apache.commons.cli.*; import pl.edu.icm.cermine.content.filtering.ContentFilterTools; import pl.edu.icm.cermine.exception.AnalysisException; 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.structure.model.BxZoneLabelCategory; import pl.edu.icm.cermine.tools.BxDocUtils.DocumentsIterator; import pl.edu.icm.cermine.tools.classification.general.*; import pl.edu.icm.cermine.tools.classification.svm.SVMZoneClassifier; /** * @author Dominika Tkaczyk (d.tkaczyk@icm.edu.pl) */ public class SVMBodyBuilder { protected static SVMZoneClassifier getZoneClassifier(List<TrainingSample<BxZoneLabel>> trainingSamples, int kernelType, double gamma, double C, int degree) throws IOException { trainingSamples = ClassificationUtils.filterElements(trainingSamples, BxZoneLabelCategory.CAT_BODY); System.out.println("Training samples " + trainingSamples.size()); PenaltyCalculator pc = new PenaltyCalculator(trainingSamples); int[] intClasses = new int[pc.getClasses().size()]; double[] classesWeights = new double[pc.getClasses().size()]; int labelIdx = 0; for (BxZoneLabel label : pc.getClasses()) { intClasses[labelIdx] = label.ordinal(); classesWeights[labelIdx] = pc.getPenaltyWeigth(label); ++labelIdx; } FeatureVectorBuilder<BxZone, BxPage> featureVectorBuilder = ContentFilterTools.VECTOR_BUILDER; SVMZoneClassifier zoneClassifier = new SVMZoneClassifier(featureVectorBuilder); svm_parameter param = SVMZoneClassifier.getDefaultParam(); param.svm_type = svm_parameter.C_SVC; param.gamma = gamma; param.C = C; System.out.println(degree); param.degree = degree; param.kernel_type = kernelType; param.weight = classesWeights; param.weight_label = intClasses; zoneClassifier.setParameter(param); zoneClassifier.buildClassifier(trainingSamples); zoneClassifier.printWeigths(featureVectorBuilder); return zoneClassifier; } public static void main(String[] args) throws ParseException, AnalysisException, IOException { Options options = new Options(); options.addOption("input", true, "input path"); options.addOption("output", true, "output model path"); options.addOption("kernel", true, "kernel type"); options.addOption("g", true, "gamma"); options.addOption("C", true, "C"); options.addOption("degree", true, "degree"); options.addOption("cross", false, ""); options.addOption("ext", true, "degree"); CommandLineParser parser = new DefaultParser(); CommandLine line = parser.parse(options, args); if (!line.hasOption("input") || !line.hasOption("output")) { System.err.println("Usage: SVMMetadataBuilder [-kernel <kernel type>] [-d <degree>] [-g <gamma>] [-C <error cost>] [-ext <extension>] -input <input dir> -output <path>"); System.exit(1); } Double C = 8.0; if (line.hasOption("C")) { C = Double.parseDouble(line.getOptionValue("C")); } Double gamma = 0.5; if (line.hasOption("g")) { gamma = Double.parseDouble(line.getOptionValue("g")); } String inDir = line.getOptionValue("input"); String outFile = line.getOptionValue("output"); String degreeStr = line.getOptionValue("degree"); Integer degree = -1; if (degreeStr != null && !degreeStr.isEmpty()) { degree = Integer.parseInt(degreeStr); } Integer kernelType = svm_parameter.RBF; if (line.hasOption("kernel")) { switch (Integer.parseInt(line.getOptionValue("kernel"))) { case 0: kernelType = svm_parameter.LINEAR; break; case 1: kernelType = svm_parameter.POLY; break; case 2: kernelType = svm_parameter.RBF; break; case 3: kernelType = svm_parameter.SIGMOID; break; default: throw new IllegalArgumentException("Invalid kernel value provided"); } } if (kernelType == svm_parameter.POLY && degree == -1) { System.err.println("Polynomial kernel requires the -degree option to be specified"); System.exit(1); } String ext = "cermstr"; if (line.hasOption("ext")) { ext = line.getOptionValue("ext"); } Map<BxZoneLabel, BxZoneLabel> map = new EnumMap<BxZoneLabel, BxZoneLabel>(BxZoneLabel.class); map.put(BxZoneLabel.BODY_ACKNOWLEDGMENT, BxZoneLabel.BODY_CONTENT); map.put(BxZoneLabel.BODY_CONFLICT_STMT, BxZoneLabel.BODY_CONTENT); map.put(BxZoneLabel.BODY_EQUATION, BxZoneLabel.BODY_JUNK); map.put(BxZoneLabel.BODY_FIGURE, BxZoneLabel.BODY_JUNK); map.put(BxZoneLabel.BODY_GLOSSARY, BxZoneLabel.BODY_JUNK); map.put(BxZoneLabel.BODY_TABLE, BxZoneLabel.BODY_JUNK); if (!line.hasOption("cross")) { File input = new File(inDir); List<TrainingSample<BxZoneLabel>> trainingSamples; if (input.isDirectory()) { DocumentsIterator it = new DocumentsIterator(inDir, ext); FeatureVectorBuilder<BxZone, BxPage> featureVectorBuilder = ContentFilterTools.VECTOR_BUILDER; trainingSamples = BxDocsToTrainingSamplesConverter.getZoneTrainingSamples(it.iterator(), featureVectorBuilder, map); } else { trainingSamples = SVMZoneClassifier.loadProblem(inDir, ContentFilterTools.VECTOR_BUILDER); } trainingSamples = ClassificationUtils.filterElements(trainingSamples, BxZoneLabelCategory.CAT_BODY); SVMZoneClassifier classifier = getZoneClassifier(trainingSamples, kernelType, gamma, C, degree); classifier.saveModel(outFile); } else { int foldness = 5; List<TrainingSample<BxZoneLabel>>[] trainingSamplesSet = new List[foldness]; for (int i = 0; i < foldness; i++) { File input = new File(inDir + "/" + i); List<TrainingSample<BxZoneLabel>> trainingSamples; if (input.isDirectory()) { DocumentsIterator it = new DocumentsIterator(inDir + "/" + i, ext); FeatureVectorBuilder<BxZone, BxPage> featureVectorBuilder = ContentFilterTools.VECTOR_BUILDER; trainingSamples = BxDocsToTrainingSamplesConverter.getZoneTrainingSamples(it.iterator(), featureVectorBuilder, map); } else { trainingSamples = SVMZoneClassifier.loadProblem(inDir + "/" + i, ContentFilterTools.VECTOR_BUILDER); } trainingSamples = ClassificationUtils.filterElements(trainingSamples, BxZoneLabelCategory.CAT_BODY); trainingSamplesSet[i] = trainingSamples; } for (int i = 0; i < foldness; i++) { List<TrainingSample<BxZoneLabel>> trainingSamples = new ArrayList<TrainingSample<BxZoneLabel>>(); for (int j = 0; j < foldness; j++) { if (i != j) { trainingSamples.addAll(trainingSamplesSet[j]); } } SVMZoneClassifier classifier = getZoneClassifier(trainingSamples, kernelType, gamma, C, degree); classifier.saveModel(outFile + "-" + i); } } } }
8,840
43.427136
182
java
CERMINE
CERMINE-master/cermine-tools/src/main/java/pl/edu/icm/cermine/libsvm/training/SVMMetadataBuilder.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.libsvm.training; import java.io.File; import java.io.IOException; import java.util.ArrayList; import java.util.List; import libsvm.svm_parameter; import org.apache.commons.cli.*; import pl.edu.icm.cermine.exception.AnalysisException; import pl.edu.icm.cermine.structure.SVMMetadataZoneClassifier; 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.structure.model.BxZoneLabelCategory; import pl.edu.icm.cermine.tools.BxDocUtils.DocumentsIterator; import pl.edu.icm.cermine.tools.classification.general.*; import pl.edu.icm.cermine.tools.classification.svm.SVMZoneClassifier; /** * @author Dominika Tkaczyk (d.tkaczyk@icm.edu.pl) */ public class SVMMetadataBuilder { protected static SVMZoneClassifier getZoneClassifier(List<TrainingSample<BxZoneLabel>> trainingSamples, int kernelType, double gamma, double C, int degree) throws IOException { trainingSamples = ClassificationUtils.filterElements(trainingSamples, BxZoneLabelCategory.CAT_METADATA); System.out.println("Training samples " + trainingSamples.size()); PenaltyCalculator pc = new PenaltyCalculator(trainingSamples); int[] intClasses = new int[pc.getClasses().size()]; double[] classesWeights = new double[pc.getClasses().size()]; int labelIdx = 0; for (BxZoneLabel label : pc.getClasses()) { intClasses[labelIdx] = label.ordinal(); classesWeights[labelIdx] = pc.getPenaltyWeigth(label); ++labelIdx; } FeatureVectorBuilder<BxZone, BxPage> featureVectorBuilder = SVMMetadataZoneClassifier.getFeatureVectorBuilder(); SVMZoneClassifier zoneClassifier = new SVMZoneClassifier(SVMMetadataZoneClassifier.getFeatureVectorBuilder()); svm_parameter param = SVMZoneClassifier.getDefaultParam(); param.svm_type = svm_parameter.C_SVC; param.gamma = gamma; param.C = C; System.out.println(degree); param.degree = degree; param.kernel_type = kernelType; param.weight = classesWeights; param.weight_label = intClasses; zoneClassifier.setParameter(param); zoneClassifier.buildClassifier(trainingSamples); zoneClassifier.printWeigths(featureVectorBuilder); return zoneClassifier; } public static void main(String[] args) throws ParseException, AnalysisException, IOException { Options options = new Options(); options.addOption("input", true, "input path"); options.addOption("output", true, "output model path"); options.addOption("kernel", true, "kernel type"); options.addOption("g", true, "gamma"); options.addOption("C", true, "C"); options.addOption("degree", true, "degree"); options.addOption("cross", false, ""); options.addOption("ext", true, "degree"); CommandLineParser parser = new DefaultParser(); CommandLine line = parser.parse(options, args); if (!line.hasOption("input") || !line.hasOption("output")) { System.err.println("Usage: SVMMetadataBuilder [-kernel <kernel type>] [-d <degree>] [-g <gamma>] [-C <error cost>] [-ext <extension>] -input <input dir> -output <path>"); System.exit(1); } Double C = 512.; if (line.hasOption("C")) { C = Double.parseDouble(line.getOptionValue("C")); } Double gamma = 0.03125; if (line.hasOption("g")) { gamma = Double.parseDouble(line.getOptionValue("g")); } String inDir = line.getOptionValue("input"); String outFile = line.getOptionValue("output"); Integer degree = 3; Integer kernelType = svm_parameter.POLY; if (line.hasOption("kernel")) { degree = -1; switch (Integer.parseInt(line.getOptionValue("kernel"))) { case 0: kernelType = svm_parameter.LINEAR; break; case 1: kernelType = svm_parameter.POLY; break; case 2: kernelType = svm_parameter.RBF; break; case 3: kernelType = svm_parameter.SIGMOID; break; default: throw new IllegalArgumentException("Invalid kernel value provided"); } } String degreeStr = line.getOptionValue("degree"); if (degreeStr != null && !degreeStr.isEmpty()) { degree = Integer.parseInt(degreeStr); } if (kernelType == svm_parameter.POLY && degree == -1) { System.err.println("Polynomial kernel requires the -degree option to be specified"); System.exit(1); } String ext = "cermstr"; if (line.hasOption("ext")) { ext = line.getOptionValue("ext"); } if (!line.hasOption("cross")) { File input = new File(inDir); List<TrainingSample<BxZoneLabel>> trainingSamples; if (input.isDirectory()) { DocumentsIterator it = new DocumentsIterator(inDir, ext); FeatureVectorBuilder<BxZone, BxPage> featureVectorBuilder = SVMMetadataZoneClassifier.getFeatureVectorBuilder(); trainingSamples = BxDocsToTrainingSamplesConverter.getZoneTrainingSamples(it.iterator(), featureVectorBuilder, BxZoneLabel.getIdentityMap()); } else { trainingSamples = SVMZoneClassifier.loadProblem(inDir, SVMMetadataZoneClassifier.getFeatureVectorBuilder()); } trainingSamples = ClassificationUtils.filterElements(trainingSamples, BxZoneLabelCategory.CAT_METADATA); SVMZoneClassifier classifier = getZoneClassifier(trainingSamples, kernelType, gamma, C, degree); classifier.saveModel(outFile); } else { int foldness = 5; List<TrainingSample<BxZoneLabel>>[] trainingSamplesSet = new List[foldness]; for (int i = 0; i < foldness; i++) { File input = new File(inDir + "/" + i); List<TrainingSample<BxZoneLabel>> trainingSamples; if (input.isDirectory()) { DocumentsIterator it = new DocumentsIterator(inDir + "/" + i, ext); FeatureVectorBuilder<BxZone, BxPage> featureVectorBuilder = SVMMetadataZoneClassifier.getFeatureVectorBuilder(); trainingSamples = BxDocsToTrainingSamplesConverter.getZoneTrainingSamples(it.iterator(), featureVectorBuilder, BxZoneLabel.getIdentityMap()); } else { trainingSamples = SVMZoneClassifier.loadProblem(inDir + "/" + i, SVMMetadataZoneClassifier.getFeatureVectorBuilder()); } trainingSamples = ClassificationUtils.filterElements(trainingSamples, BxZoneLabelCategory.CAT_METADATA); trainingSamplesSet[i] = trainingSamples; } for (int i = 0; i < foldness; i++) { List<TrainingSample<BxZoneLabel>> trainingSamples = new ArrayList<TrainingSample<BxZoneLabel>>(); for (int j = 0; j < foldness; j++) { if (i != j) { trainingSamples.addAll(trainingSamplesSet[j]); } } SVMZoneClassifier classifier = getZoneClassifier(trainingSamples, kernelType, gamma, C, degree); classifier.saveModel(outFile + "-" + i); } } } }
8,492
43.465969
182
java
CERMINE
CERMINE-master/cermine-tools/src/main/java/pl/edu/icm/cermine/libsvm/training/SVMInitialBuilder.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.libsvm.training; import java.io.File; import java.io.IOException; import java.util.ArrayList; import java.util.List; import libsvm.svm_parameter; import org.apache.commons.cli.*; import pl.edu.icm.cermine.exception.AnalysisException; import pl.edu.icm.cermine.structure.SVMInitialZoneClassifier; 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.BxDocUtils.DocumentsIterator; import pl.edu.icm.cermine.tools.classification.general.BxDocsToTrainingSamplesConverter; import pl.edu.icm.cermine.tools.classification.general.FeatureVectorBuilder; import pl.edu.icm.cermine.tools.classification.general.PenaltyCalculator; import pl.edu.icm.cermine.tools.classification.general.TrainingSample; import pl.edu.icm.cermine.tools.classification.svm.SVMZoneClassifier; /** * @author Dominika Tkaczyk (d.tkaczyk@icm.edu.pl) */ public class SVMInitialBuilder { protected static SVMZoneClassifier getZoneClassifier(List<TrainingSample<BxZoneLabel>> trainingSamples, int kernelType, double gamma, double C, int degree) throws IOException { PenaltyCalculator pc = new PenaltyCalculator(trainingSamples); int[] intClasses = new int[pc.getClasses().size()]; double[] classesWeights = new double[pc.getClasses().size()]; int labelIdx = 0; for (BxZoneLabel label : pc.getClasses()) { intClasses[labelIdx] = label.ordinal(); classesWeights[labelIdx] = pc.getPenaltyWeigth(label); ++labelIdx; } FeatureVectorBuilder<BxZone, BxPage> featureVectorBuilder = SVMInitialZoneClassifier.getFeatureVectorBuilder(); SVMZoneClassifier zoneClassifier = new SVMZoneClassifier(featureVectorBuilder); svm_parameter param = SVMZoneClassifier.getDefaultParam(); param.svm_type = svm_parameter.C_SVC; param.gamma = gamma; param.C = C; param.degree = degree; param.kernel_type = kernelType; param.weight_label = intClasses; param.weight = classesWeights; zoneClassifier.setParameter(param); zoneClassifier.buildClassifier(trainingSamples); zoneClassifier.printWeigths(featureVectorBuilder); return zoneClassifier; } public static void main(String[] args) throws ParseException, AnalysisException, IOException, CloneNotSupportedException { Options options = new Options(); options.addOption("input", true, "input path"); options.addOption("output", true, "output model path"); options.addOption("kernel", true, "kernel type"); options.addOption("g", true, "gamma"); options.addOption("C", true, "C"); options.addOption("degree", true, "degree"); options.addOption("cross", false, ""); options.addOption("ext", true, "degree"); CommandLineParser parser = new DefaultParser(); CommandLine line = parser.parse(options, args); if (!line.hasOption("input") || !line.hasOption("output")) { System.err.println("Usage: SVMInitialBuilder [-kernel <kernel type>] [-d <degree>] [-g <gamma>] [-C <error cost>] [-ext <extension>] -input <input dir> -output <path>"); System.exit(1); } Double C = 16.; if (line.hasOption("C")) { C = Double.parseDouble(line.getOptionValue("C")); } Double gamma = 1.; if (line.hasOption("g")) { gamma = Double.parseDouble(line.getOptionValue("g")); } String inDir = line.getOptionValue("input"); String outFile = line.getOptionValue("output"); String degreeStr = line.getOptionValue("degree"); Integer degree = -1; if (degreeStr != null && !degreeStr.isEmpty()) { degree = Integer.parseInt(degreeStr); } Integer kernelType = svm_parameter.RBF; if (line.hasOption("kernel")) { switch (Integer.parseInt(line.getOptionValue("kernel"))) { case 0: kernelType = svm_parameter.LINEAR; break; case 1: kernelType = svm_parameter.POLY; break; case 2: kernelType = svm_parameter.RBF; break; case 3: kernelType = svm_parameter.SIGMOID; break; default: throw new IllegalArgumentException("Invalid kernel value provided"); } } if (kernelType == svm_parameter.POLY && degree == -1) { System.err.println("Polynomial kernel requires the -degree option to be specified"); System.exit(1); } String ext = "cermstr"; if (line.hasOption("ext")) { ext = line.getOptionValue("ext"); } if (!line.hasOption("cross")) { File input = new File(inDir); if (input.isDirectory()) { DocumentsIterator it = new DocumentsIterator(inDir, ext); FeatureVectorBuilder<BxZone, BxPage> featureVectorBuilder = SVMInitialZoneClassifier.getFeatureVectorBuilder(); List<TrainingSample<BxZoneLabel>> trainingSamples = BxDocsToTrainingSamplesConverter.getZoneTrainingSamples(it.iterator(), featureVectorBuilder, BxZoneLabel.getLabelToGeneralMap()); SVMZoneClassifier classifier = getZoneClassifier(trainingSamples, kernelType, gamma, C, degree); classifier.saveModel(outFile); } else { List<TrainingSample<BxZoneLabel>> trainingSamples = SVMZoneClassifier.loadProblem(inDir, SVMInitialZoneClassifier.getFeatureVectorBuilder()); for (TrainingSample<BxZoneLabel> sample : trainingSamples) { sample.setLabel(sample.getLabel().getGeneralLabel()); } SVMZoneClassifier classifier = getZoneClassifier(trainingSamples, kernelType, gamma, C, degree); classifier.saveModel(outFile); } } else { int foldness = 5; List<TrainingSample<BxZoneLabel>>[] trainingSamplesSet = new List[foldness]; for (int i = 0; i < foldness; i++) { File input = new File(inDir + "/" + i); List<TrainingSample<BxZoneLabel>> trainingSamples; if (input.isDirectory()) { DocumentsIterator it = new DocumentsIterator(inDir + "/" + i, ext); FeatureVectorBuilder<BxZone, BxPage> featureVectorBuilder = SVMInitialZoneClassifier.getFeatureVectorBuilder(); trainingSamples = BxDocsToTrainingSamplesConverter.getZoneTrainingSamples(it.iterator(), featureVectorBuilder, BxZoneLabel.getLabelToGeneralMap()); } else { trainingSamples = SVMZoneClassifier.loadProblem(inDir + "/" + i, SVMInitialZoneClassifier.getFeatureVectorBuilder()); } trainingSamplesSet[i] = trainingSamples; } for (int i = 0; i < foldness; i++) { List<TrainingSample<BxZoneLabel>> trainingSamples = new ArrayList<TrainingSample<BxZoneLabel>>(); for (int j = 0; j < foldness; j++) { if (i != j) { trainingSamples.addAll(trainingSamplesSet[j]); } } SVMZoneClassifier classifier = getZoneClassifier(trainingSamples, kernelType, gamma, C, degree); classifier.saveModel(outFile + "-" + i); } } } }
8,562
44.306878
181
java
CERMINE
CERMINE-master/cermine-tools/src/main/java/pl/edu/icm/cermine/libsvm/export/LibSVMExporter.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.libsvm.export; import java.io.BufferedWriter; import java.io.File; import java.io.FileOutputStream; import java.io.IOException; import java.io.OutputStreamWriter; import java.io.Writer; import java.util.Formatter; import java.util.List; import java.util.Locale; import org.apache.commons.cli.*; import pl.edu.icm.cermine.exception.AnalysisException; import pl.edu.icm.cermine.exception.TransformationException; import pl.edu.icm.cermine.structure.HierarchicalReadingOrderResolver; import pl.edu.icm.cermine.structure.SVMInitialZoneClassifier; import pl.edu.icm.cermine.structure.SVMMetadataZoneClassifier; import pl.edu.icm.cermine.structure.model.*; import pl.edu.icm.cermine.tools.BxDocUtils.DocumentsIterator; import pl.edu.icm.cermine.tools.classification.general.BxDocsToTrainingSamplesConverter; import pl.edu.icm.cermine.tools.classification.general.FeatureVectorBuilder; import pl.edu.icm.cermine.tools.classification.general.TrainingSample; import pl.edu.icm.cermine.tools.classification.sampleselection.SampleFilter; /** * @author Dominika Tkaczyk (d.tkaczyk@icm.edu.pl) */ public class LibSVMExporter { public static void toLibSVM(TrainingSample<BxZoneLabel> trainingElement, BufferedWriter fileWriter) throws IOException { if (trainingElement.getLabel() == null) { return; } fileWriter.write(String.valueOf(trainingElement.getLabel().ordinal())); fileWriter.write(" "); Integer featureCounter = 1; for (Double value : trainingElement.getFeatureVector().getValues()) { StringBuilder sb = new StringBuilder(); Formatter formatter = new Formatter(sb, Locale.US); formatter.format("%d:%.5f", featureCounter++, value); fileWriter.write(sb.toString()); fileWriter.write(" "); } fileWriter.write("\n"); } public static void toLibSVM(List<TrainingSample<BxZoneLabel>> trainingElements, String filePath) throws IOException { BufferedWriter svmDataFile = null; try { Writer fstream = new OutputStreamWriter(new FileOutputStream(filePath), "UTF-8"); svmDataFile = new BufferedWriter(fstream); for (TrainingSample<BxZoneLabel> elem : trainingElements) { if (elem.getLabel() == null) { continue; } svmDataFile.write(String.valueOf(elem.getLabel().ordinal())); svmDataFile.write(" "); Integer featureCounter = 1; for (Double value : elem.getFeatureVector().getValues()) { StringBuilder sb = new StringBuilder(); Formatter formatter = new Formatter(sb, Locale.US); formatter.format("%d:%.5f", featureCounter++, value); svmDataFile.write(sb.toString()); svmDataFile.write(" "); } svmDataFile.write("\n"); } svmDataFile.close(); } finally { if (svmDataFile != null) { svmDataFile.close(); } } System.out.println("Done."); } public static void main(String[] args) throws ParseException, IOException, TransformationException, AnalysisException, CloneNotSupportedException { Options options = new Options(); CommandLineParser parser = new DefaultParser(); CommandLine line = parser.parse(options, args); if (args.length != 2) { HelpFormatter formatter = new HelpFormatter(); formatter.printHelp(" [-options] input-directory extension", options); System.exit(1); } String inputDirPath = line.getArgs()[0]; File inputDirFile = new File(inputDirPath); Integer docIdx = 0; HierarchicalReadingOrderResolver ror = new HierarchicalReadingOrderResolver(); DocumentsIterator iter = new DocumentsIterator(inputDirPath, line.getArgs()[1]); FeatureVectorBuilder<BxZone, BxPage> metaVectorBuilder = SVMMetadataZoneClassifier.getFeatureVectorBuilder(); FeatureVectorBuilder<BxZone, BxPage> initialVectorBuilder = SVMInitialZoneClassifier.getFeatureVectorBuilder(); SampleFilter metaSamplesFilter = new SampleFilter( BxZoneLabelCategory.CAT_METADATA); Writer initialStream = new OutputStreamWriter(new FileOutputStream("initial_" + inputDirFile.getName() + ".dat"), "UTF-8"); BufferedWriter svmInitialFile = new BufferedWriter(initialStream); Writer metaStream = new OutputStreamWriter( new FileOutputStream("meta_" + inputDirFile.getName() + ".dat"), "UTF-8"); BufferedWriter svmMetaFile = new BufferedWriter(metaStream); for (BxDocument doc : iter) { System.out.println(docIdx + ": " + doc.getFilename()); String filename = doc.getFilename(); doc = ror.resolve(doc); doc.setFilename(filename); for (BxZone zone : doc.asZones()) { if (zone.getLabel() != null) { if (zone.getLabel().getCategory() != BxZoneLabelCategory.CAT_METADATA) { zone.setLabel(zone.getLabel().getGeneralLabel()); } } else { zone.setLabel(BxZoneLabel.OTH_UNKNOWN); } } List<TrainingSample<BxZoneLabel>> newMetaSamples = BxDocsToTrainingSamplesConverter .getZoneTrainingSamples(doc, metaVectorBuilder, BxZoneLabel.getIdentityMap()); newMetaSamples = metaSamplesFilter.pickElements(newMetaSamples); List<TrainingSample<BxZoneLabel>> newInitialSamples = BxDocsToTrainingSamplesConverter .getZoneTrainingSamples(doc, initialVectorBuilder, BxZoneLabel.getLabelToGeneralMap()); for (TrainingSample<BxZoneLabel> sample : newMetaSamples) { toLibSVM(sample, svmMetaFile); } for (TrainingSample<BxZoneLabel> sample : newInitialSamples) { toLibSVM(sample, svmInitialFile); } ++docIdx; } svmInitialFile.close(); svmMetaFile.close(); } }
7,087
41.698795
151
java
CERMINE
CERMINE-master/cermine-tools/src/main/java/pl/edu/icm/cermine/libsvm/parameters/InitialClassifierParameterFinder.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.libsvm.parameters; import java.io.IOException; import java.util.List; import java.util.concurrent.ExecutionException; import libsvm.svm_parameter; import org.apache.commons.cli.ParseException; import pl.edu.icm.cermine.exception.AnalysisException; import pl.edu.icm.cermine.exception.TransformationException; import pl.edu.icm.cermine.structure.SVMInitialZoneClassifier; 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.BxDocUtils.DocumentsIterator; import pl.edu.icm.cermine.tools.classification.general.BxDocsToTrainingSamplesConverter; import pl.edu.icm.cermine.tools.classification.general.FeatureVectorBuilder; import pl.edu.icm.cermine.tools.classification.general.PenaltyCalculator; import pl.edu.icm.cermine.tools.classification.general.TrainingSample; import pl.edu.icm.cermine.tools.classification.svm.SVMZoneClassifier; /** * @author Dominika Tkaczyk (d.tkaczyk@icm.edu.pl) */ public class InitialClassifierParameterFinder extends SVMParameterFinder { @Override protected SVMZoneClassifier getZoneClassifier(List<TrainingSample<BxZoneLabel>> trainingSamples, int kernelType, double gamma, double C, int degree) throws IOException, AnalysisException, CloneNotSupportedException { for (TrainingSample<BxZoneLabel> trainingSample : trainingSamples) { trainingSample.setLabel(trainingSample.getLabel().getGeneralLabel()); } PenaltyCalculator pc = new PenaltyCalculator(trainingSamples); int[] intClasses = new int[pc.getClasses().size()]; double[] classesWeights = new double[pc.getClasses().size()]; int labelIdx = 0; for (BxZoneLabel label : pc.getClasses()) { intClasses[labelIdx] = label.ordinal(); classesWeights[labelIdx] = pc.getPenaltyWeigth(label); ++labelIdx; } SVMZoneClassifier zoneClassifier = new SVMZoneClassifier(SVMInitialZoneClassifier.getFeatureVectorBuilder()); svm_parameter param = SVMZoneClassifier.getDefaultParam(); param.svm_type = svm_parameter.C_SVC; param.gamma = gamma; param.C = C; System.out.println(degree); param.degree = degree; param.kernel_type = kernelType; param.weight = classesWeights; param.weight_label = intClasses; zoneClassifier.setParameter(param); zoneClassifier.buildClassifier(trainingSamples); return zoneClassifier; } public static void main(String[] args) throws ParseException, AnalysisException, IOException, TransformationException, CloneNotSupportedException, InterruptedException, ExecutionException { SVMParameterFinder.main(args, new InitialClassifierParameterFinder()); } @Override protected FeatureVectorBuilder<BxZone, BxPage> getFeatureVectorBuilder() { return SVMInitialZoneClassifier.getFeatureVectorBuilder(); } @Override public List<TrainingSample<BxZoneLabel>> getSamples(String inputFile, String ext) throws AnalysisException { DocumentsIterator it = new DocumentsIterator(inputFile, ext); return BxDocsToTrainingSamplesConverter.getZoneTrainingSamples(it.iterator(), getFeatureVectorBuilder(), BxZoneLabel.getLabelToGeneralMap()); } }
4,163
42.831579
220
java
CERMINE
CERMINE-master/cermine-tools/src/main/java/pl/edu/icm/cermine/libsvm/parameters/BodyClassifierParameterFinder.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.libsvm.parameters; import java.io.IOException; import java.util.EnumMap; import java.util.List; import java.util.Map; import java.util.concurrent.ExecutionException; import libsvm.svm_parameter; import org.apache.commons.cli.ParseException; import pl.edu.icm.cermine.content.filtering.ContentFilterTools; import pl.edu.icm.cermine.exception.AnalysisException; import pl.edu.icm.cermine.exception.TransformationException; 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.structure.model.BxZoneLabelCategory; import pl.edu.icm.cermine.tools.BxDocUtils.DocumentsIterator; import pl.edu.icm.cermine.tools.classification.general.*; import pl.edu.icm.cermine.tools.classification.svm.SVMZoneClassifier; /** * @author Dominika Tkaczyk (d.tkaczyk@icm.edu.pl) */ public class BodyClassifierParameterFinder extends SVMParameterFinder { @Override protected SVMZoneClassifier getZoneClassifier(List<TrainingSample<BxZoneLabel>> trainingSamples, int kernelType, double gamma, double C, int degree) throws IOException, AnalysisException, CloneNotSupportedException { PenaltyCalculator pc = new PenaltyCalculator(trainingSamples); int[] intClasses = new int[pc.getClasses().size()]; double[] classesWeights = new double[pc.getClasses().size()]; int labelIdx = 0; for (BxZoneLabel label : pc.getClasses()) { intClasses[labelIdx] = label.ordinal(); classesWeights[labelIdx] = pc.getPenaltyWeigth(label); ++labelIdx; } SVMZoneClassifier zoneClassifier = new SVMZoneClassifier(getFeatureVectorBuilder()); svm_parameter param = SVMZoneClassifier.getDefaultParam(); param.svm_type = svm_parameter.C_SVC; param.gamma = gamma; param.C = C; System.out.println(degree); param.degree = degree; param.kernel_type = kernelType; param.weight = classesWeights; param.weight_label = intClasses; zoneClassifier.setParameter(param); zoneClassifier.buildClassifier(trainingSamples); return zoneClassifier; } public static void main(String[] args) throws ParseException, AnalysisException, IOException, TransformationException, CloneNotSupportedException, InterruptedException, ExecutionException { SVMParameterFinder.main(args, new BodyClassifierParameterFinder()); } @Override protected FeatureVectorBuilder<BxZone, BxPage> getFeatureVectorBuilder() { return ContentFilterTools.VECTOR_BUILDER; } @Override public List<TrainingSample<BxZoneLabel>> getSamples(String inputFile, String ext) throws AnalysisException { Map<BxZoneLabel, BxZoneLabel> map = new EnumMap<BxZoneLabel, BxZoneLabel>(BxZoneLabel.class); map.put(BxZoneLabel.BODY_ACKNOWLEDGMENT, BxZoneLabel.BODY_CONTENT); map.put(BxZoneLabel.BODY_CONFLICT_STMT, BxZoneLabel.BODY_CONTENT); map.put(BxZoneLabel.BODY_EQUATION, BxZoneLabel.BODY_JUNK); map.put(BxZoneLabel.BODY_FIGURE, BxZoneLabel.BODY_JUNK); map.put(BxZoneLabel.BODY_GLOSSARY, BxZoneLabel.BODY_JUNK); map.put(BxZoneLabel.BODY_TABLE, BxZoneLabel.BODY_JUNK); DocumentsIterator it = new DocumentsIterator(inputFile, ext); List<TrainingSample<BxZoneLabel>> samples = BxDocsToTrainingSamplesConverter.getZoneTrainingSamples( it.iterator(), getFeatureVectorBuilder(), map); List<TrainingSample<BxZoneLabel>> tss = ClassificationUtils.filterElements(samples, BxZoneLabelCategory.CAT_BODY); return tss; } }
4,471
42
162
java
CERMINE
CERMINE-master/cermine-tools/src/main/java/pl/edu/icm/cermine/libsvm/parameters/SVMParameterFinder.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.libsvm.parameters; import java.io.IOException; import java.util.EnumMap; import java.util.List; import java.util.Map; import java.util.concurrent.*; import libsvm.svm_parameter; import org.apache.commons.cli.*; import pl.edu.icm.cermine.evaluation.tools.ClassificationResults; import pl.edu.icm.cermine.evaluation.tools.DividedEvaluationSet; import pl.edu.icm.cermine.exception.AnalysisException; 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.FeatureVectorBuilder; import pl.edu.icm.cermine.tools.classification.general.TrainingSample; import pl.edu.icm.cermine.tools.classification.svm.SVMZoneClassifier; /** * @author Dominika Tkaczyk (d.tkaczyk@icm.edu.pl) */ public abstract class SVMParameterFinder { private static final EnumMap<BxZoneLabel, BxZoneLabel> DEFAULT_LABEL_MAP = new EnumMap<BxZoneLabel, BxZoneLabel>(BxZoneLabel.class); static { for (BxZoneLabel label : BxZoneLabel.values()) { DEFAULT_LABEL_MAP.put(label, label); } } protected int foldness; private final Map<BxZoneLabel, BxZoneLabel> labelMap = DEFAULT_LABEL_MAP.clone(); public static void main(String[] args, SVMParameterFinder evaluator) throws ParseException, AnalysisException, InterruptedException, ExecutionException{ Options options = new Options(); options.addOption("fold", true, "foldness of cross-validation"); options.addOption("kernel", true, "kernel type"); options.addOption("degree", true, "degree"); options.addOption("ext", true, "file extension"); options.addOption("threads", true, "number of threads"); options.addOption("minc", true, ""); options.addOption("maxc", true, ""); options.addOption("ming", true, ""); options.addOption("maxg", true, ""); CommandLineParser parser = new DefaultParser(); CommandLine line = parser.parse(options, args); if (line.hasOption("help")) { HelpFormatter formatter = new HelpFormatter(); formatter.printHelp(args[0] + " [-options] input-file", options); } else { String[] remaining = line.getArgs(); if (remaining.length != 1) { throw new ParseException("Input file is missing!"); } if (!line.hasOption("fold")) { evaluator.foldness = 5; } else { evaluator.foldness = Integer.parseInt(line.getOptionValue("fold")); } String inputFile = remaining[0]; String degreeStr = line.getOptionValue("degree"); Integer degree = -1; if (degreeStr != null && !degreeStr.isEmpty()) { degree = Integer.parseInt(degreeStr); } Integer kernelType; switch(Integer.parseInt(line.getOptionValue("kernel"))) { case 0: kernelType = svm_parameter.LINEAR; break; case 1: kernelType = svm_parameter.POLY; break; case 2: kernelType = svm_parameter.RBF; break; case 3: kernelType = svm_parameter.SIGMOID; break; default: throw new IllegalArgumentException("Invalid kernel value provided"); } int threads = 3; String threadsStr = line.getOptionValue("threads"); if (threadsStr != null && !threadsStr.isEmpty()) { threads = Integer.parseInt(threadsStr); } String ext = "cxml"; String extStr = line.getOptionValue("ext"); if (extStr != null && !extStr.isEmpty()) { ext = extStr; } int minc = -5; if (line.hasOption("minc")) { minc = Integer.parseInt(line.getOptionValue("minc")); } int maxc = 15; if (line.hasOption("maxc")) { maxc = Integer.parseInt(line.getOptionValue("maxc")); } int ming = -15; if (line.hasOption("ming")) { ming = Integer.parseInt(line.getOptionValue("ming")); } int maxg = 3; if (line.hasOption("maxg")) { maxg = Integer.parseInt(line.getOptionValue("maxg")); } evaluator.setLabelMap(BxZoneLabel.getLabelToGeneralMap()); evaluator.run(inputFile, ext, threads, kernelType, degree, minc, maxc, ming, maxg); } } protected abstract List<TrainingSample<BxZoneLabel>> getSamples(String inputFile, String ext) throws AnalysisException; public void run(String inputFile, String ext, int threads, int kernel, int degree, int minc, int maxc, int ming, int maxg) throws AnalysisException, InterruptedException, ExecutionException { List<TrainingSample<BxZoneLabel>> samples = getSamples(inputFile, ext); ExecutorService executor = Executors.newFixedThreadPool(3); CompletionService<EvaluationParams> completionService = new ExecutorCompletionService<EvaluationParams>(executor); double bestRate = 0; int bestclog = 0; int bestglog = 0; int submitted = 0; for (int clog = minc; clog <= maxc; clog++) { for (int glog = maxg; glog >= ming; glog--) { completionService.submit(new Evaluator(samples, new EvaluationParams(clog, glog), kernel, degree)); submitted++; } } while (submitted > 0) { Future<EvaluationParams> f1 = completionService.take(); EvaluationParams p = f1.get(); if (p.rate > bestRate) { bestRate = p.rate; bestclog = p.clog; bestglog = p.glog; } System.out.println("Gamma: "+p.glog+", C: "+p.clog+", rate: "+p.rate+" (Best: "+bestglog+" "+bestclog+" "+bestRate+")"); submitted--; } executor.shutdown(); } private static class EvaluationParams { int clog; int glog; double rate; public EvaluationParams(int clog, int glog) { this.clog = clog; this.glog = glog; } } private class Evaluator implements Callable<EvaluationParams> { private final List<TrainingSample<BxZoneLabel>> samples; private final EvaluationParams params; private final int kernel; private final int degree; public Evaluator(List<TrainingSample<BxZoneLabel>> samples, EvaluationParams params, int kernel, int degree) { this.samples = samples; this.params = params; this.kernel = kernel; this.degree = degree; } @Override public EvaluationParams call() throws AnalysisException, IOException, CloneNotSupportedException { double gamma = Math.pow(2, params.glog); double c = Math.pow(2, params.clog); double rate = evaluate(samples, kernel, gamma, c, degree); params.rate = rate; return params; } } private double evaluate(List<TrainingSample<BxZoneLabel>> samples, int kernelType, double gamma, double C, int degree) throws AnalysisException, IOException, CloneNotSupportedException { ClassificationResults summary = new ClassificationResults(); List<DividedEvaluationSet> sampleSets = DividedEvaluationSet.build(samples, foldness); for (int fold = 0; fold < foldness; ++fold) { List<TrainingSample<BxZoneLabel>> trainingSamples = sampleSets.get(fold).getTrainingDocuments(); List<TrainingSample<BxZoneLabel>> testSamples = sampleSets.get(fold).getTestDocuments(); ClassificationResults iterationResults = new ClassificationResults(); SVMZoneClassifier zoneClassifier = getZoneClassifier(trainingSamples, kernelType, gamma, C, degree); for (TrainingSample<BxZoneLabel> testSample : testSamples) { BxZoneLabel expectedClass = testSample.getLabel(); BxZoneLabel inferedClass = zoneClassifier.predictLabel(testSample); ClassificationResults documentResults = compareItems(expectedClass, inferedClass); iterationResults.add(documentResults); } summary.add(iterationResults); } return summary.getMeanF1Score(); } protected ClassificationResults compareItems(BxZoneLabel expected, BxZoneLabel actual) { ClassificationResults pageResults = new ClassificationResults(); pageResults.addOneZoneResult(expected, actual); return pageResults; } public void setLabelMap(Map<BxZoneLabel, BxZoneLabel> value) { labelMap.putAll(DEFAULT_LABEL_MAP); labelMap.putAll(value); } protected abstract SVMZoneClassifier getZoneClassifier(List<TrainingSample<BxZoneLabel>> trainingSamples, int kernelType, double gamma, double C, int degree) throws AnalysisException, IOException, CloneNotSupportedException; protected abstract FeatureVectorBuilder<BxZone, BxPage> getFeatureVectorBuilder(); }
10,176
39.708
190
java
CERMINE
CERMINE-master/cermine-tools/src/main/java/pl/edu/icm/cermine/libsvm/parameters/MetadataClassifierParameterFinder.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.libsvm.parameters; import java.io.IOException; import java.util.List; import java.util.Map; import java.util.concurrent.ExecutionException; import libsvm.svm_parameter; import org.apache.commons.cli.ParseException; import pl.edu.icm.cermine.exception.AnalysisException; import pl.edu.icm.cermine.exception.TransformationException; import pl.edu.icm.cermine.structure.SVMMetadataZoneClassifier; 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.structure.model.BxZoneLabelCategory; import pl.edu.icm.cermine.tools.BxDocUtils.DocumentsIterator; import pl.edu.icm.cermine.tools.classification.general.*; import pl.edu.icm.cermine.tools.classification.svm.SVMZoneClassifier; /** * @author Dominika Tkaczyk (d.tkaczyk@icm.edu.pl) */ public class MetadataClassifierParameterFinder extends SVMParameterFinder { @Override protected SVMZoneClassifier getZoneClassifier(List<TrainingSample<BxZoneLabel>> trainingSamples, int kernelType, double gamma, double C, int degree) throws IOException, AnalysisException, CloneNotSupportedException { Map<BxZoneLabel, BxZoneLabel> labelMapper = BxZoneLabel.getLabelToGeneralMap(); for (TrainingSample<BxZoneLabel> sample : trainingSamples) { if (sample.getLabel().getCategory() != BxZoneLabelCategory.CAT_METADATA) { sample.setLabel(labelMapper.get(sample.getLabel())); } } PenaltyCalculator pc = new PenaltyCalculator(trainingSamples); int[] intClasses = new int[pc.getClasses().size()]; double[] classesWeights = new double[pc.getClasses().size()]; int labelIdx = 0; for (BxZoneLabel label : pc.getClasses()) { intClasses[labelIdx] = label.ordinal(); classesWeights[labelIdx] = pc.getPenaltyWeigth(label); ++labelIdx; } SVMZoneClassifier zoneClassifier = new SVMZoneClassifier(SVMMetadataZoneClassifier.getFeatureVectorBuilder()); svm_parameter param = SVMZoneClassifier.getDefaultParam(); param.svm_type = svm_parameter.C_SVC; param.gamma = gamma; param.C = C; System.out.println(degree); param.degree = degree; param.kernel_type = kernelType; param.weight = classesWeights; param.weight_label = intClasses; zoneClassifier.setParameter(param); zoneClassifier.buildClassifier(trainingSamples); return zoneClassifier; } public static void main(String[] args) throws ParseException, AnalysisException, IOException, TransformationException, CloneNotSupportedException, InterruptedException, ExecutionException { SVMParameterFinder.main(args, new MetadataClassifierParameterFinder()); } @Override protected FeatureVectorBuilder<BxZone, BxPage> getFeatureVectorBuilder() { return SVMMetadataZoneClassifier.getFeatureVectorBuilder(); } @Override public List<TrainingSample<BxZoneLabel>> getSamples(String inputFile, String ext) throws AnalysisException { DocumentsIterator it = new DocumentsIterator(inputFile, ext); List<TrainingSample<BxZoneLabel>> samples = BxDocsToTrainingSamplesConverter.getZoneTrainingSamples(it.iterator(), getFeatureVectorBuilder(), null); return ClassificationUtils.filterElements(samples, BxZoneLabelCategory.CAT_METADATA); } }
4,267
41.68
162
java
CERMINE
CERMINE-master/cermine-tools/src/main/java/pl/edu/icm/cermine/bx/BxReadingOrderSetter.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.bx; import java.io.IOException; import org.apache.commons.cli.ParseException; import pl.edu.icm.cermine.exception.AnalysisException; import pl.edu.icm.cermine.exception.TransformationException; import pl.edu.icm.cermine.structure.HierarchicalReadingOrderResolver; import pl.edu.icm.cermine.structure.ReadingOrderResolver; import pl.edu.icm.cermine.structure.model.BxDocument; /** * @author Dominika Tkaczyk (d.tkaczyk@icm.edu.pl) */ public class BxReadingOrderSetter extends BxDocRewriter { public static void main(String[] args) throws ParseException, TransformationException, IOException, AnalysisException { BxReadingOrderSetter corrector = new BxReadingOrderSetter(); corrector.run(args); } @Override protected BxDocument transform(BxDocument document) throws AnalysisException { ReadingOrderResolver roResolver = new HierarchicalReadingOrderResolver(); return roResolver.resolve(document); } }
1,720
38.113636
123
java
CERMINE
CERMINE-master/cermine-tools/src/main/java/pl/edu/icm/cermine/bx/BxDocKeyZonesPrinter.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.bx; import java.io.FileNotFoundException; import java.io.UnsupportedEncodingException; import java.util.EnumSet; import java.util.HashMap; import java.util.Map; import java.util.Set; import org.apache.commons.cli.*; import pl.edu.icm.cermine.exception.TransformationException; import pl.edu.icm.cermine.structure.model.*; /** * @author Dominika Tkaczyk (d.tkaczyk@icm.edu.pl) */ public class BxDocKeyZonesPrinter extends BxDocStatisticsPrinter { public static void main(String[] args) throws ParseException, TransformationException, FileNotFoundException, UnsupportedEncodingException { BxDocKeyZonesPrinter printer = new BxDocKeyZonesPrinter(); printer.run(args); } @Override protected Map<String, String> getStatistics(BxDocument document) { Map<String, String> statistics = new HashMap<String, String>(); Set<BxZoneLabel> set = EnumSet.noneOf(BxZoneLabel.class); int keys = 0; int all = 0; int good = 0; for (BxZone z : document.asZones()) { all++; if (BxZoneLabel.REFERENCES.equals(z.getLabel())) { keys = 1; } if (!z.getLabel().equals(BxZoneLabel.OTH_UNKNOWN)) { good++; } if (z.getLabel().isOfCategoryOrGeneral(BxZoneLabelCategory.CAT_METADATA)) { set.add(z.getLabel()); } } if (set.contains(BxZoneLabel.MET_AFFILIATION)) { keys++; } if (set.contains(BxZoneLabel.MET_AUTHOR)) { keys++; } if (set.contains(BxZoneLabel.MET_BIB_INFO)) { keys++; } if (set.contains(BxZoneLabel.MET_TITLE)) { keys++; } int intcov = 0; if (all > 0) { intcov = good * 100 / all; } statistics.put("Metadata labels number", String.valueOf(set.size())); statistics.put("Known label coverage", String.valueOf(intcov)); statistics.put("Key labels number", String.valueOf(keys)); return statistics; } }
2,858
33.445783
144
java
CERMINE
CERMINE-master/cermine-tools/src/main/java/pl/edu/icm/cermine/bx/BxDocShrinker.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.bx; import java.io.File; import java.io.FileInputStream; import java.io.FileOutputStream; import java.io.IOException; import java.io.InputStreamReader; import java.io.OutputStreamWriter; import java.io.Writer; import java.util.Collection; import java.util.List; import org.apache.commons.cli.CommandLine; import org.apache.commons.cli.CommandLineParser; import org.apache.commons.cli.DefaultParser; import org.apache.commons.cli.Options; import org.apache.commons.cli.ParseException; import org.apache.commons.io.FileUtils; import pl.edu.icm.cermine.exception.TransformationException; import pl.edu.icm.cermine.structure.model.BxPage; import pl.edu.icm.cermine.structure.transformers.BxDocumentToTrueVizWriter; import pl.edu.icm.cermine.structure.transformers.TrueVizToBxDocumentReader; /** * @author Dominika Tkaczyk (d.tkaczyk@icm.edu.pl) */ public class BxDocShrinker { public static void main(String[] args) throws ParseException, TransformationException, IOException { Options options = new Options(); options.addOption("input", true, "input path"); options.addOption("output", true, "output path"); options.addOption("ext", true, "extension"); CommandLineParser parser = new DefaultParser(); CommandLine line = parser.parse(options, args); String inDir = line.getOptionValue("input"); String outDir = line.getOptionValue("output"); String extension = line.getOptionValue("ext"); File dir = new File(inDir); Collection<File> files = FileUtils.listFiles(dir, new String[]{extension}, true); int i = 0; for (File f : files) { System.out.println(f.getPath()); TrueVizToBxDocumentReader tvReader = new TrueVizToBxDocumentReader(); List<BxPage> pages = tvReader.read(new InputStreamReader( new FileInputStream(f), "UTF-8")); File f2 = new File(outDir + f.getName()); BxDocumentToTrueVizWriter wrt = new BxDocumentToTrueVizWriter(); boolean created = f2.createNewFile(); if (!created) { throw new IOException("Cannot create file: "); } Writer fw = new OutputStreamWriter(new FileOutputStream(f2), "UTF-8"); wrt.write(fw, pages, BxDocumentToTrueVizWriter.MINIMAL_OUTPUT_SIZE); fw.flush(); fw.close(); i++; System.out.println("Progress: "+((double)i*100./(double)files.size())); } } }
3,358
38.05814
104
java
CERMINE
CERMINE-master/cermine-tools/src/main/java/pl/edu/icm/cermine/bx/BxDocViewer.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.bx; import java.io.FileNotFoundException; import java.io.UnsupportedEncodingException; import java.util.HashMap; import java.util.Map; import org.apache.commons.cli.*; import pl.edu.icm.cermine.exception.TransformationException; import pl.edu.icm.cermine.structure.model.BxDocument; import pl.edu.icm.cermine.structure.model.BxZone; /** * @author Dominika Tkaczyk (d.tkaczyk@icm.edu.pl) */ public class BxDocViewer extends BxDocStatisticsPrinter { public static void main(String[] args) throws ParseException, TransformationException, FileNotFoundException, UnsupportedEncodingException { BxDocViewer viewer = new BxDocViewer(); viewer.run(args); } @Override protected Map<String, String> getStatistics(BxDocument document) { for (BxZone z : document.asZones()) { System.out.println(); System.out.println(z.getLabel()+" "+z.toText()); } return new HashMap<String, String>(); } }
1,734
34.408163
145
java
CERMINE
CERMINE-master/cermine-tools/src/main/java/pl/edu/icm/cermine/bx/BxDocStatisticsPrinter.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.bx; import java.io.File; import java.io.FileInputStream; import java.io.FileNotFoundException; import java.io.InputStreamReader; import java.io.UnsupportedEncodingException; import java.util.List; import java.util.Map; import org.apache.commons.cli.*; import org.apache.commons.io.FileUtils; import pl.edu.icm.cermine.exception.TransformationException; import pl.edu.icm.cermine.structure.model.*; import pl.edu.icm.cermine.structure.transformers.TrueVizToBxDocumentReader; /** * @author Dominika Tkaczyk (d.tkaczyk@icm.edu.pl) */ public abstract class BxDocStatisticsPrinter { protected abstract Map<String, String> getStatistics(BxDocument document); public void run(String[] args) throws ParseException, TransformationException, FileNotFoundException, UnsupportedEncodingException { Options options = new Options(); options.addOption("input", true, "input path"); options.addOption("ext", true, "extension"); CommandLineParser parser = new DefaultParser(); CommandLine line = parser.parse(options, args); String inDir = line.getOptionValue("input"); String extension = line.getOptionValue("ext"); File dir = new File(inDir); for (File f : FileUtils.listFiles(dir, new String[]{extension}, true)) { TrueVizToBxDocumentReader tvReader = new TrueVizToBxDocumentReader(); List<BxPage> pages = tvReader.read(new InputStreamReader( new FileInputStream(f), "UTF8")); BxDocument doc = new BxDocument().setPages(pages); doc.setFilename(f.getName()); System.out.println("Document: " + f.getPath()); Map<String, String> statistics = getStatistics(doc); for (Map.Entry<String, String> statistic: statistics.entrySet()) { System.out.println(statistic.getKey() + ": " + statistic.getValue()); } System.out.println(); } } }
2,752
40.089552
136
java
CERMINE
CERMINE-master/cermine-tools/src/main/java/pl/edu/icm/cermine/bx/BxDocRewriter.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.bx; import com.google.common.collect.Lists; import java.io.File; import java.io.FileInputStream; import java.io.FileOutputStream; import java.io.IOException; import java.io.InputStreamReader; import java.io.OutputStreamWriter; import java.io.Writer; import java.util.List; import org.apache.commons.cli.*; import org.apache.commons.io.FileUtils; import pl.edu.icm.cermine.exception.AnalysisException; import pl.edu.icm.cermine.exception.TransformationException; import pl.edu.icm.cermine.structure.model.*; import pl.edu.icm.cermine.structure.transformers.BxDocumentToTrueVizWriter; import pl.edu.icm.cermine.structure.transformers.TrueVizToBxDocumentReader; /** * @author Dominika Tkaczyk (d.tkaczyk@icm.edu.pl) */ public abstract class BxDocRewriter { protected abstract BxDocument transform(BxDocument document) throws AnalysisException; public void run(String[] args) throws ParseException, TransformationException, IOException, AnalysisException { Options options = new Options(); options.addOption("input", true, "input path"); options.addOption("output", true, "output path"); options.addOption("ext", true, "extension"); CommandLineParser parser = new DefaultParser(); CommandLine line = parser.parse(options, args); String inDir = line.getOptionValue("input"); String outDir = line.getOptionValue("output"); String extension = line.getOptionValue("ext"); File dir = new File(inDir); for (File f : FileUtils.listFiles(dir, new String[]{extension}, true)) { TrueVizToBxDocumentReader tvReader = new TrueVizToBxDocumentReader(); List<BxPage> pages = tvReader.read(new InputStreamReader( new FileInputStream(f), "UTF-8")); BxDocument doc = new BxDocument().setPages(pages); doc.setFilename(f.getName()); BxDocument rewritten = transform(doc); File f2 = new File(outDir+doc.getFilename()); BxDocumentToTrueVizWriter wrt = new BxDocumentToTrueVizWriter(); boolean created = f2.createNewFile(); if (!created) { throw new IOException("Cannot create file: "); } Writer fw = new OutputStreamWriter(new FileOutputStream(f2), "UTF8"); wrt.write(fw, Lists.newArrayList(rewritten)); fw.flush(); fw.close(); } } }
3,242
39.037037
115
java
CERMINE
CERMINE-master/cermine-tools/src/main/java/pl/edu/icm/cermine/bx/BxDocMetadataZoneCoveragePrinter.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.bx; import java.io.FileNotFoundException; import java.io.UnsupportedEncodingException; import java.util.EnumSet; import java.util.HashMap; import java.util.Map; import java.util.Set; import org.apache.commons.cli.*; import pl.edu.icm.cermine.exception.TransformationException; import pl.edu.icm.cermine.structure.model.*; /** * @author Dominika Tkaczyk (d.tkaczyk@icm.edu.pl) */ public class BxDocMetadataZoneCoveragePrinter extends BxDocStatisticsPrinter { public static void main(String[] args) throws ParseException, TransformationException, FileNotFoundException, UnsupportedEncodingException { BxDocMetadataZoneCoveragePrinter printer = new BxDocMetadataZoneCoveragePrinter(); printer.run(args); } @Override protected Map<String, String> getStatistics(BxDocument document) { Map<String, String> statistics = new HashMap<String, String>(); Set<BxZoneLabel> set = EnumSet.noneOf(BxZoneLabel.class); for (BxZone z: document.asZones()) { if (z.getLabel().isOfCategoryOrGeneral(BxZoneLabelCategory.CAT_METADATA)) { set.add(z.getLabel()); } } statistics.put("Metadata labels number", String.valueOf(set.size())); return statistics; } }
2,061
34.551724
144
java
CERMINE
CERMINE-master/cermine-tools/src/main/java/pl/edu/icm/cermine/bx/BxDocZoneCoveragePrinter.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.bx; import java.io.FileNotFoundException; import java.io.UnsupportedEncodingException; import java.util.EnumSet; import java.util.HashMap; import java.util.Map; import java.util.Set; import org.apache.commons.cli.*; import pl.edu.icm.cermine.exception.TransformationException; import pl.edu.icm.cermine.structure.model.*; /** * @author Dominika Tkaczyk (d.tkaczyk@icm.edu.pl) */ public class BxDocZoneCoveragePrinter extends BxDocStatisticsPrinter { public static void main(String[] args) throws ParseException, TransformationException, FileNotFoundException, UnsupportedEncodingException { BxDocZoneCoveragePrinter printer = new BxDocZoneCoveragePrinter(); printer.run(args); } @Override protected Map<String, String> getStatistics(BxDocument document) { Map<String, String> statistics = new HashMap<String, String>(); Set<BxZoneLabel> set = EnumSet.noneOf(BxZoneLabel.class); int all = 0; int good = 0; for (BxZone z: document.asZones()) { all++; if (!z.getLabel().equals(BxZoneLabel.OTH_UNKNOWN)) { good++; } if (z.getLabel().isOfCategoryOrGeneral(BxZoneLabelCategory.CAT_METADATA)) { set.add(z.getLabel()); } } int intcov = 0; if (all > 0) { intcov = good*100/all; } statistics.put("Metadata labels number", String.valueOf(set.size())); statistics.put("Known label coverage", String.valueOf(intcov)); return statistics; } }
2,357
33.676471
144
java
CERMINE
CERMINE-master/cermine-tools/src/main/java/pl/edu/icm/cermine/bx/BxBibZonesCorrector.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.bx; import java.io.IOException; import java.util.Locale; import org.apache.commons.cli.ParseException; 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.model.BxZone; import pl.edu.icm.cermine.structure.model.BxZoneLabel; /** * @author Dominika Tkaczyk (d.tkaczyk@icm.edu.pl) */ public class BxBibZonesCorrector extends BxDocRewriter { public static void main(String[] args) throws ParseException, TransformationException, IOException, AnalysisException { BxBibZonesCorrector corrector = new BxBibZonesCorrector(); corrector.run(args); } @Override protected BxDocument transform(BxDocument document) { for (BxZone z : document.asZones()) { if (!BxZoneLabel.MET_BIB_INFO.equals(z.getLabel()) && !BxZoneLabel.REFERENCES.equals(z.getLabel()) && z.childrenCount() <= 2 && (z.toText().toLowerCase(Locale.ENGLISH).contains("journal ") || z.toText().toLowerCase(Locale.ENGLISH).contains("vol.") || z.toText().toLowerCase(Locale.ENGLISH).contains("vol ") || z.toText().toLowerCase(Locale.ENGLISH).contains("pp.") || z.toText().toLowerCase(Locale.ENGLISH).contains("volume ") || z.toText().toLowerCase(Locale.ENGLISH).contains("pp ") || z.toText().toLowerCase(Locale.ENGLISH).contains("issn") || z.toText().toLowerCase(Locale.ENGLISH).contains("doi:") || z.toText().toLowerCase(Locale.ENGLISH).contains("doi ") || z.toText().toLowerCase(Locale.ENGLISH).contains("citation:"))) { System.out.println("DETECTED BIBINFO: "); System.out.println(z.getLabel() + " " + z.toText()); System.out.println(""); z.setLabel(BxZoneLabel.MET_BIB_INFO); } else { if (!BxZoneLabel.OTH_UNKNOWN.equals(z.getLabel()) && !BxZoneLabel.MET_BIB_INFO.equals(z.getLabel()) && z.childrenCount() <= 2 && (z.toText().toLowerCase(Locale.ENGLISH).contains("page "))) { System.out.println("DETECTED PAGE: "); System.out.println(z.getLabel() + " " + z.toText()); System.out.println(""); z.setLabel(BxZoneLabel.OTH_UNKNOWN); } } } return document; } }
3,416
45.175676
123
java
CERMINE
CERMINE-master/cermine-tools/src/main/java/pl/edu/icm/cermine/bx/BxDocZoneNumberPrinter.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.bx; import com.google.common.collect.Lists; import java.io.FileNotFoundException; import java.io.UnsupportedEncodingException; import java.util.HashMap; import java.util.Map; import org.apache.commons.cli.*; import pl.edu.icm.cermine.exception.TransformationException; import pl.edu.icm.cermine.structure.model.*; /** * @author Dominika Tkaczyk (d.tkaczyk@icm.edu.pl) */ public class BxDocZoneNumberPrinter extends BxDocStatisticsPrinter { public static void main(String[] args) throws ParseException, TransformationException, FileNotFoundException, UnsupportedEncodingException { BxDocZoneNumberPrinter printer = new BxDocZoneNumberPrinter(); printer.run(args); } @Override protected Map<String, String> getStatistics(BxDocument document) { Map<String, String> statistics = new HashMap<String, String>(); int size = Lists.newArrayList(document.asZones()).size(); statistics.put("Zone number", String.valueOf(size)); return statistics; } }
1,782
36.145833
144
java
CERMINE
CERMINE-master/cermine-tools/src/main/java/pl/edu/icm/cermine/csv/ZonesToCSVExporter.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.csv; import java.io.*; import java.util.List; import org.apache.commons.cli.CommandLine; import org.apache.commons.cli.CommandLineParser; import org.apache.commons.cli.DefaultParser; import org.apache.commons.cli.Options; import org.apache.commons.cli.ParseException; import org.apache.commons.io.FileUtils; import pl.edu.icm.cermine.exception.TransformationException; import pl.edu.icm.cermine.metadata.zoneclassification.features.FeatureList; 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.transformers.TrueVizToBxDocumentReader; import pl.edu.icm.cermine.tools.classification.general.FeatureVector; import pl.edu.icm.cermine.tools.classification.general.FeatureVectorBuilder; /** * @author Dominika Tkaczyk (d.tkaczyk@icm.edu.pl) */ public class ZonesToCSVExporter { public static void main(String[] args) throws ParseException, FileNotFoundException, TransformationException, UnsupportedEncodingException { Options options = new Options(); options.addOption("input", true, "input path"); options.addOption("ext", true, "extension"); CommandLineParser parser = new DefaultParser(); CommandLine line = parser.parse(options, args); String inDir = line.getOptionValue("input"); String extension = line.getOptionValue("ext"); FeatureVectorBuilder<BxZone, BxPage> vectorBuilder = FeatureList.VECTOR_BUILDER; List<String> names = vectorBuilder.getFeatureNames(); System.out.print("Zone,Label"); for (String name : names) { System.out.print(","); System.out.print(name); } System.out.println(""); File dir = new File(inDir); for (File tv : FileUtils.listFiles(dir, new String[]{extension}, true)) { InputStream is = new FileInputStream(tv); TrueVizToBxDocumentReader reader = new TrueVizToBxDocumentReader(); Reader r = new InputStreamReader(is, "UTF-8"); BxDocument origBxDoc = new BxDocument().setPages(reader.read(r)); for (BxZone z : origBxDoc.asZones()) { FeatureVector fv = vectorBuilder.getFeatureVector(z, z.getParent()); String t = z.toText().replaceAll("[^a-zA-Z0-9 ]", ""); System.out.print("\""+t.substring(0, Math.min(50, t.length()))+"\""); System.out.print(","); System.out.print(z.getLabel()); for (String name : names) { System.out.print(","); System.out.print(fv.getValue(name)); } System.out.println(""); } } } }
3,588
41.72619
144
java
CERMINE
CERMINE-master/cermine-tools/src/main/java/pl/edu/icm/cermine/pubmed/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.pubmed; import java.util.ArrayList; import java.util.List; import org.w3c.dom.Node; import org.w3c.dom.NodeList; /** * @author Pawel Szostek */ public class XMLTools { public static String extractTextFromNode(Node node) { StringBuilder ret = new StringBuilder(); if (node == null) { return ""; } if (node.getChildNodes().getLength() == 0) { if (node.getNodeValue() != null) { return node.getNodeValue() + " "; } else { return ""; } } else { for (int childIdx = 0; childIdx < node.getChildNodes().getLength(); ++childIdx) { ret.append(extractTextFromNode(node.getChildNodes().item(childIdx))); } } return ret.toString().replaceAll("\n", " ").replaceAll("\\s+", " "); } public static String extractTextFromNodes(NodeList nodes) { StringBuilder ret = new StringBuilder(); for (int nodeIdx = 0; nodeIdx < nodes.getLength(); ++nodeIdx) { Node node = nodes.item(nodeIdx); ret.append(extractTextFromNode(node)); } return ret.toString(); } public static List<String> extractTextAsList(NodeList nodes) { List<String> ret = new ArrayList<String>(); for (int nodeIdx = 0; nodeIdx < nodes.getLength(); ++nodeIdx) { String extractedText = extractTextFromNode(nodes.item(nodeIdx)); extractedText = extractedText.trim(); if (!extractedText.isEmpty()) { ret.add(extractedText); } } return ret; } public static List<String> extractChildrenAsTextList(Node node) { List<String> ret = new ArrayList<String>(); if (node == null) { return ret; } if (node.getChildNodes().getLength() == 0 && node.getNodeValue() != null) { ret.add(node.getNodeValue()); } else { for (int childIdx = 0; childIdx < node.getChildNodes().getLength(); ++childIdx) { ret.addAll(extractChildrenAsTextList(node.getChildNodes().item(childIdx))); } } return ret; } }
2,972
32.404494
93
java
CERMINE
CERMINE-master/cermine-tools/src/main/java/pl/edu/icm/cermine/pubmed/PubmedZoneMerger.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.pubmed; import com.google.common.collect.Lists; import java.io.*; import java.util.*; import org.apache.commons.io.FileUtils; import pl.edu.icm.cermine.exception.AnalysisException; import pl.edu.icm.cermine.exception.TransformationException; import pl.edu.icm.cermine.structure.HierarchicalReadingOrderResolver; import pl.edu.icm.cermine.structure.ReadingOrderResolver; import pl.edu.icm.cermine.structure.model.*; import pl.edu.icm.cermine.structure.tools.BxBoundsBuilder; import pl.edu.icm.cermine.structure.transformers.BxDocumentToTrueVizWriter; import pl.edu.icm.cermine.structure.transformers.TrueVizToBxDocumentReader; import pl.edu.icm.cermine.tools.DisjointSets; /** * @author Dominika Tkaczyk (d.tkaczyk@icm.edu.pl) */ public class PubmedZoneMerger { public static void main(String[] args) throws TransformationException, AnalysisException, IOException { ReadingOrderResolver roResolver = new HierarchicalReadingOrderResolver(); File dir = new File(args[0]); int i = 0; Collection<File> files = FileUtils.listFiles(dir, new String[]{args[1]}, true); for (File tv : files) { System.out.println(tv.getPath()); String newPath = tv.getPath().replaceFirst(args[1], args[2]); File newFile = new File(newPath); if (newFile.exists()) { i++; continue; } InputStream is = new FileInputStream(tv); TrueVizToBxDocumentReader reader = new TrueVizToBxDocumentReader(); Reader r = new InputStreamReader(is, "UTF-8"); BxDocument bxDoc = new BxDocument().setPages(reader.read(r)); double avgDiffZone = 0; int countDZ = 0; for (BxLine line : bxDoc.asLines()) { if (!line.hasNext()) { continue; } double y1 = line.getY(); double y2 = line.getNext().getY(); double h1 = line.getHeight(); double h2 = line.getNext().getHeight(); if (y1 >= y2) { continue; } double x1 = line.getX(); double x1e = line.getX() + line.getWidth(); double x2 = line.getNext().getX(); double x2e = line.getNext().getX() + line.getNext().getWidth(); if (x1e < x2 || x2e < x1 || (x1 + 5 < x2 && x1e + 5 < x2e) || (x2 + 5 < x1 && x2e + 5 < x1e)) { continue; } double diff = y2 - y1 - h1; if (line.getParent().equals(line.getNext().getParent())) { avgDiffZone += diff; countDZ++; } } avgDiffZone /= countDZ; for (BxPage page : bxDoc) { List<BxLine> lines = new ArrayList<BxLine>(); for (BxZone z : page) { for (BxLine l : z) { lines.add(l); } } DisjointSets<BxLine> dLines = new DisjointSets<BxLine>(lines); for (BxLine line : lines) { for (BxLine ll : lines) { if (line.getParent().equals(ll.getParent())) { dLines.union(line, ll); } } } for (BxLine line : lines) { if (!line.hasNext()) { continue; } double y1 = line.getY(); double y2 = line.getNext().getY(); double h1 = line.getHeight(); double h2 = line.getNext().getHeight(); if (y1 >= y2) { continue; } double x1 = line.getX(); double x1e = line.getX() + line.getWidth(); double x2 = line.getNext().getX(); double x2e = line.getNext().getX() + line.getNext().getWidth(); if (x1e < x2 || x2e < x1 || (x1 + 5 < x2 && x1e + 5 < x2e) || (x2 + 5 < x1 && x2e + 5 < x1e)) { continue; } double diff = y2 - y1 - h1; if (!line.getParent().equals(line.getNext().getParent()) && (line.getParent().getLabel().equals(line.getNext().getParent().getLabel()) || line.getParent().getLabel().equals(BxZoneLabel.OTH_UNKNOWN) || line.getParent().getNext().getLabel().equals(BxZoneLabel.OTH_UNKNOWN))) { if (diff < 4.5 && Math.abs(diff - avgDiffZone) < 4.5) { dLines.union(line, line.getNext()); } } } Iterator<Set<BxLine>> it = dLines.iterator(); List<Set<BxLine>> l = new ArrayList<Set<BxLine>>(); while (it.hasNext()) { l.add(it.next()); } for (Set<BxLine> l1 : l) { for (Set<BxLine> l2 : l) { if (l1.equals(l2)) { continue; } BxBoundsBuilder b1 = new BxBoundsBuilder(); for (BxLine ll1 : l1) { b1.expand(ll1.getBounds()); } BxBounds bb1 = b1.getBounds(); BxBoundsBuilder b2 = new BxBoundsBuilder(); for (BxLine ll2 : l2) { b2.expand(ll2.getBounds()); } BxBounds bb2 = b2.getBounds(); if (l1.iterator().next().getParent().getLabel().equals(l2.iterator().next().getParent().getLabel()) && bb1.getX() <= bb2.getX() + bb2.getWidth() && bb2.getX() <= bb1.getX() + bb1.getWidth() && bb1.getY() <= bb2.getY() + bb2.getHeight() && bb2.getY() <= bb1.getY() + bb1.getHeight()) { dLines.union(l1.iterator().next(), l2.iterator().next()); } } } page.setZones(new ArrayList<BxZone>()); it = dLines.iterator(); while (it.hasNext()) { Set<BxLine> group = it.next(); BxBoundsBuilder builder = new BxBoundsBuilder(); BxZoneLabel label = null; BxZone zone = new BxZone(); List<BxLine> mylines = new ArrayList<BxLine>(); mylines.addAll(group); Collections.sort(mylines, new Comparator<BxLine>() { @Override public int compare(BxLine t, BxLine t1) { return Double.compare(t1.getY(), t.getY()); } }); BxLine prev = null; for (BxLine line : mylines) { label = line.getParent().getLabel(); builder.expandByWords(line); if (prev != null) { if (Math.abs(prev.getY() - line.getY()) < 1) { for (BxWord w : line) { prev.addWord(w); w.setParent(prev); } } else { zone.addLine(prev); prev.setParent(zone); prev = line; } } else { prev = line; } } if (prev != null) { zone.addLine(prev); prev.setParent(zone); } zone.setLabel(label); zone.setBounds(builder.getBounds()); page.addZone(zone); } } roResolver.resolve(bxDoc); Writer out = null; try { out = new OutputStreamWriter(new FileOutputStream(newPath), "UTF-8"); BxDocumentToTrueVizWriter writer = new BxDocumentToTrueVizWriter(); out.write(writer.write(Lists.newArrayList(bxDoc))); } finally { if (out != null) { out.close(); } } i++; System.out.println("Progress: " + i + " out of " + files.size() + " (" + (i * 100. / files.size()) + "%)"); } } }
9,767
39.032787
123
java
CERMINE
CERMINE-master/cermine-tools/src/main/java/pl/edu/icm/cermine/pubmed/RuleBasedPubmedXMLGenerator.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.pubmed; import pl.edu.icm.cermine.tools.SmartHashMap; import com.google.common.collect.Lists; import java.io.*; import java.util.Map.Entry; import java.util.*; import javax.xml.parsers.DocumentBuilder; import javax.xml.parsers.DocumentBuilderFactory; import javax.xml.parsers.ParserConfigurationException; import javax.xml.xpath.XPath; import javax.xml.xpath.XPathConstants; import javax.xml.xpath.XPathExpressionException; import javax.xml.xpath.XPathFactory; import org.apache.commons.io.FileUtils; import org.apache.commons.lang.StringUtils; import org.w3c.dom.Document; import org.w3c.dom.Node; import org.w3c.dom.NodeList; import org.xml.sax.SAXException; import pl.edu.icm.cermine.content.cleaning.ContentCleaner; import pl.edu.icm.cermine.exception.AnalysisException; import pl.edu.icm.cermine.exception.TransformationException; import pl.edu.icm.cermine.structure.model.*; import pl.edu.icm.cermine.structure.transformers.BxDocumentToTrueVizWriter; import pl.edu.icm.cermine.structure.transformers.TrueVizToBxDocumentReader; import pl.edu.icm.cermine.tools.TextUtils; import pl.edu.icm.cermine.tools.distance.CosineDistance; import pl.edu.icm.cermine.tools.distance.SmithWatermanDistance; /** * @author Dominika Tkaczyk (d.tkaczyk@icm.edu.pl) */ public class RuleBasedPubmedXMLGenerator { private static class LabelTrio { private final BxZoneLabel label; private final Double alignment; private final List<String> entryTokens; @Override public int hashCode() { final int prime = 31; int result = 1; result = prime * result + ((label == null) ? 0 : label.hashCode()); result = prime * result + ((alignment == null) ? 0 : alignment.hashCode()); return result; } @Override public boolean equals(Object obj) { if (this == obj) { return true; } if (obj == null) { return false; } if (getClass() != obj.getClass()) { return false; } LabelTrio other = (LabelTrio) obj; if (label != other.label) { return false; } if (alignment == null) { if (other.alignment != null) { return false; } } else if (!alignment.equals(other.alignment)) { return false; } return true; } public LabelTrio(BxZoneLabel label, List<String> tokens, Double similarity) { this.alignment = similarity; this.label = label; this.entryTokens = tokens; } } private boolean verbose = false; private void setVerbose(boolean verbose) { this.verbose = verbose; } private void printlnVerbose(String string) { if (verbose) { System.out.println(string); } } public BxDocument generateTrueViz(InputStream pdfStream, InputStream nlmStream) throws AnalysisException, ParserConfigurationException, SAXException, IOException, XPathExpressionException, TransformationException { XPath xpath = XPathFactory.newInstance().newXPath(); DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance(); dbf.setValidating(false); dbf.setFeature("http://xml.org/sax/features/namespaces", false); dbf.setFeature("http://xml.org/sax/features/validation", false); dbf.setFeature("http://apache.org/xml/features/nonvalidating/load-dtd-grammar", false); dbf.setFeature("http://apache.org/xml/features/nonvalidating/load-external-dtd", false); DocumentBuilder builder = dbf.newDocumentBuilder(); Document domDoc = builder.parse(nlmStream); TrueVizToBxDocumentReader reader = new TrueVizToBxDocumentReader(); Reader r = new InputStreamReader(pdfStream, "UTF-8"); BxDocument bxDoc = new BxDocument().setPages(reader.read(r)); List<BxZone> zones = Lists.newArrayList(bxDoc.asZones()); Integer bxDocLen = zones.size(); SmartHashMap entries = new SmartHashMap(); //abstract Node abstractNode = (Node) xpath.evaluate("/article/front/article-meta/abstract", domDoc, XPathConstants.NODE); String abstractString = XMLTools.extractTextFromNode(abstractNode); entries.putIf("Abstract " + abstractString, BxZoneLabel.MET_ABSTRACT); entries.putIf("Abstract", BxZoneLabel.MET_ABSTRACT); //title String titleString = (String) xpath.evaluate("/article/front/article-meta/title-group/article-title", domDoc, XPathConstants.STRING); entries.putIf(titleString, BxZoneLabel.MET_TITLE); String subtitleString = (String) xpath.evaluate("/article/front/article-meta/title-group/article-subtitle", domDoc, XPathConstants.STRING); entries.putIf(subtitleString, BxZoneLabel.MET_TITLE); //journal title String journalTitleString = (String) xpath.evaluate("/article/front/journal-meta/journal-title", domDoc, XPathConstants.STRING); if (journalTitleString == null || journalTitleString.isEmpty()) { journalTitleString = (String) xpath.evaluate("/article/front/journal-meta/journal-title-group/journal-title", domDoc, XPathConstants.STRING); } entries.putIf(journalTitleString, BxZoneLabel.MET_BIB_INFO); //journal publisher String journalPublisherString = (String) xpath.evaluate("/article/front/journal-meta/publisher/publisher-name", domDoc, XPathConstants.STRING); entries.putIf(journalPublisherString, BxZoneLabel.MET_BIB_INFO); String journalPublisherIdString = (String) xpath.evaluate("/article/front/journal-meta/journal-id[@journal-id-type='publisher-id']", domDoc, XPathConstants.STRING); entries.putIf(journalPublisherIdString, BxZoneLabel.MET_BIB_INFO); //journal issn String journalISSNString = (String) xpath.evaluate("/article/front/journal-meta/issn", domDoc, XPathConstants.STRING); entries.putIf(journalISSNString, BxZoneLabel.MET_BIB_INFO); //copyright/permissions String permissionsString = XMLTools.extractTextFromNode((Node) xpath.evaluate("/article/front/article-meta/permissions", domDoc, XPathConstants.NODE)); entries.putIf(permissionsString, BxZoneLabel.MET_COPYRIGHT); //license Node licenseNode = (Node) xpath.evaluate("/article/front/article-meta/license", domDoc, XPathConstants.NODE); String licenseString = (String) XMLTools.extractTextFromNode(licenseNode); entries.putIf(licenseString, BxZoneLabel.MET_COPYRIGHT); //article type NodeList articleTypeNodes = (NodeList) xpath.evaluate("/article/@article-type", domDoc, XPathConstants.NODESET); List<String> articleTypeStrings = XMLTools.extractTextAsList(articleTypeNodes); Node articleTypeNode = (Node) xpath.evaluate("/article/front/article-meta/article-categories/subj-group", domDoc, XPathConstants.NODE); articleTypeStrings.add(XMLTools.extractTextFromNode(articleTypeNode)); entries.putIf(articleTypeStrings, BxZoneLabel.MET_TYPE); //received date List<String> receivedDate = XMLTools.extractChildrenAsTextList((Node) xpath.evaluate("/article/front/article-meta/history/date[@date-type='received']", domDoc, XPathConstants.NODE)); if (!receivedDate.isEmpty() && receivedDate.size() >= 3) { for (String date : TextUtils.produceDates(receivedDate)) { entries.putIf(date, BxZoneLabel.MET_DATES); } } //accepted date List<String> acceptedDate = XMLTools.extractChildrenAsTextList((Node) xpath.evaluate("/article/front/article-meta/history/date[@date-type='accepted']", domDoc, XPathConstants.NODE)); if (!acceptedDate.isEmpty() && acceptedDate.size() >= 3) { for (String date : TextUtils.produceDates(acceptedDate)) { entries.putIf(date, BxZoneLabel.MET_DATES); } } //publication date List<String> pubdateString; if (((NodeList) xpath.evaluate("/article/front/article-meta/pub-date", domDoc, XPathConstants.NODESET)).getLength() > 1) { Node pubdateNode = (Node) xpath.evaluate("/article/front/article-meta/pub-date[@pub-type='epub']", domDoc, XPathConstants.NODE); pubdateString = XMLTools.extractChildrenAsTextList(pubdateNode); } else { Node pubdateNode = (Node) xpath.evaluate("/article/front/article-meta/pub-date[@pub-type='collection']", domDoc, XPathConstants.NODE); pubdateString = XMLTools.extractChildrenAsTextList(pubdateNode); } if (pubdateString != null && pubdateString.size() >= 3) { for (String date : TextUtils.produceDates(pubdateString)) { entries.putIf(date, BxZoneLabel.MET_DATES); } } if (pubdateString != null) { pubdateString.clear(); } if (((NodeList) xpath.evaluate("/article/front/article-meta/pub-date", domDoc, XPathConstants.NODESET)).getLength() > 1) { Node pubdateNode = (Node) xpath.evaluate("/article/front/article-meta/pub-date[@pub-type='ppub']", domDoc, XPathConstants.NODE); pubdateString = XMLTools.extractChildrenAsTextList(pubdateNode); } if (pubdateString != null && pubdateString.size() >= 3) { for (String date : TextUtils.produceDates(pubdateString)) { entries.putIf(date, BxZoneLabel.MET_DATES); } } String extLink = (String) xpath.evaluate("/article/front/article-meta/ext-link[@ext-link-type='uri']/xlink:href", domDoc, XPathConstants.STRING); printlnVerbose(extLink); entries.putIf(extLink, BxZoneLabel.MET_ACCESS_DATA); //keywords Node keywordsNode = (Node) xpath.evaluate("/article/front/article-meta/kwd-group", domDoc, XPathConstants.NODE); String keywordsString = XMLTools.extractTextFromNode(keywordsNode); entries.putIf(keywordsString, BxZoneLabel.MET_KEYWORDS); //DOI String doiString = (String) xpath.evaluate("/article/front/article-meta/article-id[@pub-id-type='doi']", domDoc, XPathConstants.STRING); entries.putIf("DOI " + doiString, BxZoneLabel.MET_BIB_INFO); //volume String volumeString = (String) xpath.evaluate("/article/front/article-meta/volume", domDoc, XPathConstants.STRING); entries.putIf("volume " + volumeString, BxZoneLabel.MET_BIB_INFO); entries.putIf("vol " + volumeString, BxZoneLabel.MET_BIB_INFO); //issue String issueString = (String) xpath.evaluate("/article/front/article-meta/issue", domDoc, XPathConstants.STRING); entries.putIf("number " + issueString, BxZoneLabel.MET_BIB_INFO); entries.putIf("journal", BxZoneLabel.MET_BIB_INFO); entries.putIf("et al", BxZoneLabel.MET_BIB_INFO); List<String> authorNames = new ArrayList<String>(); List<String> authorEmails = new ArrayList<String>(); List<String> authorAffiliations = new ArrayList<String>(); List<String> editors = new ArrayList<String>(); //pages String fPage = (String) xpath.evaluate("/article/front/article-meta/fpage", domDoc, XPathConstants.STRING); String lPage = (String) xpath.evaluate("/article/front/article-meta/lpage", domDoc, XPathConstants.STRING); entries.putIf("pages " + fPage + " " + lPage, BxZoneLabel.MET_BIB_INFO); entries.putIf("pp " + fPage + " " + lPage, BxZoneLabel.MET_BIB_INFO); entries.putIf(fPage, BxZoneLabel.MET_BIB_INFO); entries.putIf(lPage, BxZoneLabel.MET_BIB_INFO); entries.putIf(lPage, BxZoneLabel.OTH_PAGE_NUMBER); entries.putIf(lPage, BxZoneLabel.OTH_PAGE_NUMBER); try { int f = Integer.parseInt(fPage); int l = Integer.parseInt(lPage); while (f < l) { f++; entries.putIf(String.valueOf(f), BxZoneLabel.OTH_PAGE_NUMBER); } } catch (NumberFormatException ex) { } entries.putIf("page of", BxZoneLabel.OTH_PAGE_NUMBER); //editors NodeList editorNodes = (NodeList) xpath.evaluate("/article/front/article-meta/contrib-group/contrib[@contrib-type='editor']", domDoc, XPathConstants.NODESET); for (int nodeIdx = 0; nodeIdx < editorNodes.getLength(); ++nodeIdx) { String editorString = XMLTools.extractTextFromNode(editorNodes.item(nodeIdx)); editors.add(editorString); } entries.putIf(TextUtils.joinStrings(editors), BxZoneLabel.MET_EDITOR); NodeList authorsResult = (NodeList) xpath.evaluate("/article/front/article-meta/contrib-group/contrib[@contrib-type='author']", domDoc, XPathConstants.NODESET); for (int nodeIdx = 0; nodeIdx < authorsResult.getLength(); ++nodeIdx) { Node curNode = authorsResult.item(nodeIdx); //author names String name = (String) xpath.evaluate("name/given-names", curNode, XPathConstants.STRING); String surname = (String) xpath.evaluate("name/surname", curNode, XPathConstants.STRING); //author affiliation List<String> aff = XMLTools.extractTextAsList((NodeList) xpath.evaluate("/article/front/article-meta/contrib-group/aff", domDoc, XPathConstants.NODESET)); //author correspondence String email; try { email = (String) xpath.evaluate("address/email", curNode, XPathConstants.STRING); } catch (XPathExpressionException e) { email = ""; } if (email.isEmpty()) { try { email = (String) xpath.evaluate("email", curNode, XPathConstants.STRING); } catch (XPathExpressionException e) { //yaaay, probably there is no e-mail at all! => do nothing } } if (!email.isEmpty()) { authorEmails.add(email); } if (!aff.isEmpty()) { authorAffiliations.addAll(aff); } authorNames.add(name + " " + surname); } entries.putIf(TextUtils.joinStrings(authorNames), BxZoneLabel.MET_AUTHOR); //authors' affiliations NodeList affNodes = (NodeList) xpath.evaluate("/article/front/article-meta/aff", domDoc, XPathConstants.NODESET); authorAffiliations.addAll(XMLTools.extractTextAsList(affNodes)); entries.putIf(authorAffiliations, BxZoneLabel.MET_AFFILIATION); //correspondence again NodeList correspNodes = (NodeList) xpath.evaluate("/article/front/article-meta/author-notes/corresp", domDoc, XPathConstants.NODESET); authorEmails.add(XMLTools.extractTextFromNodes(correspNodes)); entries.putIf(authorEmails, BxZoneLabel.MET_CORRESPONDENCE); //author notes Node notesNode = (Node) xpath.evaluate("/article/front/article-meta/author-notes/corresp/fn", domDoc, XPathConstants.NODE); String notesString = XMLTools.extractTextFromNode(notesNode); entries.putIf(notesString, BxZoneLabel.MET_CORRESPONDENCE); notesString = XMLTools.extractTextFromNode((Node) xpath.evaluate("/article/back/notes", domDoc, XPathConstants.NODE)); //article body NodeList paragraphNodes = (NodeList) xpath.evaluate("/article/body//p", domDoc, XPathConstants.NODESET); List<String> paragraphStrings = XMLTools.extractTextAsList(paragraphNodes); entries.putIf(paragraphStrings, BxZoneLabel.BODY_CONTENT); NodeList appNodes = (NodeList) xpath.evaluate("/article/back/app-group//p", domDoc, XPathConstants.NODESET); String appStrings = XMLTools.extractTextFromNodes(appNodes); entries.putIf(appStrings, BxZoneLabel.BODY_CONTENT); //section titles NodeList sectionTitleNodes = (NodeList) xpath.evaluate("/article/body//title", domDoc, XPathConstants.NODESET); List<String> sectionTitles = XMLTools.extractTextAsList(sectionTitleNodes); entries.putIf(sectionTitles, BxZoneLabel.BODY_CONTENT); NodeList appTitleNodes = (NodeList) xpath.evaluate("/article/back/app-group//title", domDoc, XPathConstants.NODESET); List<String> appTitles = XMLTools.extractTextAsList(appTitleNodes); entries.putIf(appTitles, BxZoneLabel.BODY_CONTENT); //figures NodeList figureNodes = (NodeList) xpath.evaluate("/article/floats-wrap//fig", domDoc, XPathConstants.NODESET); List<String> figureStrings = XMLTools.extractTextAsList(figureNodes); figureNodes = (NodeList) xpath.evaluate("/article/floats-group//fig", domDoc, XPathConstants.NODESET); figureStrings.addAll(XMLTools.extractTextAsList(figureNodes)); figureNodes = (NodeList) xpath.evaluate("/article/back//fig", domDoc, XPathConstants.NODESET); figureStrings.addAll(XMLTools.extractTextAsList(figureNodes)); figureNodes = (NodeList) xpath.evaluate("/article/body//fig", domDoc, XPathConstants.NODESET); figureStrings.addAll(XMLTools.extractTextAsList(figureNodes)); figureNodes = (NodeList) xpath.evaluate("/article/back/app-group//fig", domDoc, XPathConstants.NODESET); figureStrings.addAll(XMLTools.extractTextAsList(figureNodes)); entries.putIf(figureStrings, BxZoneLabel.BODY_FIGURE); //tables List<String> tableCaptions = new ArrayList<String>(); List<String> tableBodies = new ArrayList<String>(); List<String> tableFootnotes = new ArrayList<String>(); //tableNodes NodeList tableNodes = (NodeList) xpath.evaluate("/article//table-wrap", domDoc, XPathConstants.NODESET); for (Integer nodeIdx = 0; nodeIdx < tableNodes.getLength(); ++nodeIdx) { Node tableNode = tableNodes.item(nodeIdx); String caption = (String) xpath.evaluate("caption", tableNode, XPathConstants.STRING); tableCaptions.add(caption); String body = XMLTools.extractTextFromNode((Node) xpath.evaluate("table", tableNode, XPathConstants.NODE)); tableBodies.add(body); List<String> footnotes = XMLTools.extractTextAsList((NodeList) xpath.evaluate("table-wrap-foot/fn", tableNode, XPathConstants.NODESET)); tableFootnotes.addAll(footnotes); entries.putIf(caption, BxZoneLabel.BODY_TABLE); entries.putIf(body, BxZoneLabel.BODY_TABLE); entries.putIf(footnotes, BxZoneLabel.BODY_TABLE); } //financial disclosure String financialDisclosure = XMLTools.extractTextFromNode((Node) xpath.evaluate("/article//fn[@fn-type='financial-disclosure']", domDoc, XPathConstants.NODE)); entries.putIf(financialDisclosure, BxZoneLabel.BODY_ACKNOWLEDGMENT); //conflict String conflictString = XMLTools.extractTextFromNode((Node) xpath.evaluate("/article//fn[@fn-type='conflict']", domDoc, XPathConstants.NODE)); entries.putIf(conflictString, BxZoneLabel.BODY_CONFLICT_STMT); //copyright String copyrightString = XMLTools.extractTextFromNode((Node) xpath.evaluate("/article/front/article-meta/permissions/copyright-statement", domDoc, XPathConstants.NODE)); entries.putIf(copyrightString, BxZoneLabel.MET_COPYRIGHT); //acknowledgment String acknowledgement = XMLTools.extractTextFromNode((Node) xpath.evaluate("/article/back/ack", domDoc, XPathConstants.NODE)); entries.putIf(acknowledgement, BxZoneLabel.BODY_ACKNOWLEDGMENT); acknowledgement = XMLTools.extractTextFromNode((Node) xpath.evaluate("/article/back/fn-group/fn", domDoc, XPathConstants.NODE)); entries.putIf(acknowledgement, BxZoneLabel.BODY_CONFLICT_STMT); //glossary String glossary = XMLTools.extractTextFromNode((Node) xpath.evaluate("/article/back/glossary", domDoc, XPathConstants.NODE)); entries.putIf(glossary, BxZoneLabel.BODY_GLOSSARY); //formula NodeList formulaNodes = (NodeList) xpath.evaluate("/article/body//disp-formula", domDoc, XPathConstants.NODESET); for (int nodeIdx = 0; nodeIdx < formulaNodes.getLength(); ++nodeIdx) { Node curFormulaNode = formulaNodes.item(nodeIdx); String label = (String) xpath.evaluate("label", curFormulaNode); entries.putIf(label, BxZoneLabel.BODY_EQUATION); NodeList curNodeChildren = curFormulaNode.getChildNodes(); List<String> formulaParts = new ArrayList<String>(); for (int childIdx = 0; childIdx < curNodeChildren.getLength(); ++childIdx) { Node curChild = curNodeChildren.item(childIdx); if (curChild.getNodeName().equals("label")) { continue; } formulaParts.add(XMLTools.extractTextFromNode(curChild)); } entries.putIf(TextUtils.joinStrings(formulaParts), BxZoneLabel.BODY_EQUATION); } //references List<String> refStrings = new ArrayList<String>(); Node refParentNode = (Node) xpath.evaluate("/article/back/ref-list", domDoc, XPathConstants.NODE); if (refParentNode != null) { for (Integer refIdx = 0; refIdx < refParentNode.getChildNodes().getLength(); ++refIdx) { refStrings.add(XMLTools.extractTextFromNode(refParentNode.getChildNodes().item(refIdx))); } } entries.putIf(TextUtils.joinStrings(refStrings), BxZoneLabel.REFERENCES); entries.put("references", BxZoneLabel.REFERENCES); Set<String> allBibInfos = new HashSet<String>(); for (Entry<String, BxZoneLabel> entry : entries.entrySet()) { if (BxZoneLabel.MET_BIB_INFO.equals(entry.getValue())) { allBibInfos.addAll(Arrays.asList(entry.getKey().split(" "))); } } entries.put(StringUtils.join(allBibInfos, " "), BxZoneLabel.MET_BIB_INFO); printlnVerbose("journalTitle: " + journalTitleString); printlnVerbose("journalPublisher: " + journalPublisherString); printlnVerbose("journalISSNPublisher: " + journalISSNString); printlnVerbose("articleType: " + articleTypeStrings); printlnVerbose("received: " + receivedDate); printlnVerbose("accepted: " + acceptedDate); printlnVerbose("pubdate: " + pubdateString); printlnVerbose("permissions: " + permissionsString); printlnVerbose("license: " + licenseString); printlnVerbose("title: " + titleString); printlnVerbose("abstract: " + abstractString); printlnVerbose("authorEmails: " + authorEmails); printlnVerbose("authorNames: " + authorNames); printlnVerbose("authorAff: " + authorAffiliations); printlnVerbose("authorNotes: " + notesString); printlnVerbose("editor: " + editors); printlnVerbose("keywords: " + keywordsString); printlnVerbose("DOI: " + doiString); printlnVerbose("volume: " + volumeString); printlnVerbose("issue: " + issueString); printlnVerbose("financial dis.: " + financialDisclosure); printlnVerbose("paragraphs: " + paragraphStrings); printlnVerbose("section titles: " + sectionTitles); printlnVerbose("tableBodies: " + tableBodies); printlnVerbose("tableCaptions: " + tableCaptions); printlnVerbose("tableFootnotes: " + tableFootnotes); printlnVerbose("figures: " + figureStrings); printlnVerbose("acknowledgement: " + acknowledgement); printlnVerbose("ref: " + refStrings.size() + " " + refStrings); SmithWatermanDistance smith = new SmithWatermanDistance(.1, 0.1); CosineDistance cos = new CosineDistance(); //index: (zone,entry) List<List<LabelTrio>> swLabelSim = new ArrayList<List<LabelTrio>>(bxDocLen); List<List<LabelTrio>> cosLabProb = new ArrayList<List<LabelTrio>>(bxDocLen); for (Integer i = 0; i < bxDocLen; ++i) { swLabelSim.add(new ArrayList<LabelTrio>()); cosLabProb.add(new ArrayList<LabelTrio>()); } //iterate over entries for (Entry<String, BxZoneLabel> entry : entries.entrySet()) { List<String> entryTokens = TextUtils.tokenize(entry.getKey()); printlnVerbose("--------------------"); printlnVerbose(entry.getValue() + " " + entry.getKey() + "\n"); //iterate over zones for (Integer zoneIdx = 0; zoneIdx < bxDocLen; ++zoneIdx) { BxZone curZone = zones.get(zoneIdx); List<String> zoneTokens = TextUtils.tokenize( TextUtils.removeOrphantSpaces( TextUtils.cleanLigatures( curZone.toText().toLowerCase(Locale.ENGLISH)))); Double smithSim; Double cosSim; if (curZone.toText().contains("www.biomedcentral.com")) { //ignore smithSim = 0.; cosSim = 0.; } else { smithSim = smith.compare(entryTokens, zoneTokens); cosSim = cos.compare(entryTokens, zoneTokens); } printlnVerbose(smithSim + " " + zones.get(zoneIdx).toText() + "\n\n"); swLabelSim.get(zoneIdx).add(new LabelTrio(entry.getValue(), entryTokens, smithSim)); cosLabProb.get(zoneIdx).add(new LabelTrio(entry.getValue(), entryTokens, cosSim)); } } for (BxPage pp : bxDoc) { boolean changed = true; while (changed) { changed = false; boolean wasIntro = false; for (BxZone z : pp) { BxZoneLabel orig = z.getLabel(); int i = zones.indexOf(z); double titleAl = 0; double authorAl = 0; List<LabelTrio> sims = swLabelSim.get(i); for (LabelTrio t : sims) { if (t.label.equals(BxZoneLabel.MET_TITLE)) { titleAl = t.alignment / t.entryTokens.size(); } if (t.label.equals(BxZoneLabel.MET_AUTHOR)) { authorAl = t.alignment / t.entryTokens.size(); } } String text = ContentCleaner.cleanAllAndBreaks(z.toText()).toLowerCase(Locale.ENGLISH); int linesCount = z.childrenCount(); int pageIdx = Lists.newArrayList(bxDoc).indexOf(z.getParent()); BxLine firstLine = z.getFirstChild(); if (pageIdx == 0 && (z.getLabel().equals(BxZoneLabel.MET_TITLE) || z.getLabel().equals(BxZoneLabel.BODY_CONTENT)) && titleAl >= 0.7 && authorAl >= 0.4) { z.setLabel(BxZoneLabel.MET_TITLE_AUTHOR); } if (linesCount == 2 && text.contains("page") && text.contains("of") && text.contains("page number not for")) { z.setLabel(BxZoneLabel.OTH_PAGE_NUMBER); } if (linesCount == 1 && (text.contains("page number not for") || (text.contains("page") && text.contains("of")))) { z.setLabel(BxZoneLabel.OTH_PAGE_NUMBER); } if (pageIdx == 0 && !z.getLabel().isOfCategory(BxZoneLabelCategory.CAT_METADATA) && linesCount < 11 && (text.contains("department") || text.contains("university"))) { z.setLabel(BxZoneLabel.MET_AFFILIATION); } if (pageIdx > 0 && z.getLabel().equals(BxZoneLabel.MET_COPYRIGHT)) { z.setLabel(BxZoneLabel.MET_BIB_INFO); } if (linesCount < 5 && firstLine.toText().length() < 11 && firstLine.toText().startsWith("Figure") && z.getLabel().equals(BxZoneLabel.BODY_CONTENT)) { z.setLabel(BxZoneLabel.BODY_FIGURE); } if (pageIdx > 0 && z.getLabel().equals(BxZoneLabel.MET_TITLE)) { z.setLabel(BxZoneLabel.BODY_CONTENT); } if (pageIdx > 0 && z.hasPrev() && z.hasNext() && (z.getLabel().equals(BxZoneLabel.BODY_CONTENT) || z.getLabel().equals(BxZoneLabel.OTH_UNKNOWN) || z.getLabel().equals(BxZoneLabel.MET_DATES) || z.getLabel().equals(BxZoneLabel.BODY_ACKNOWLEDGMENT)) && (z.getPrev().getLabel().equals(BxZoneLabel.BODY_TABLE) || z.getNext().getLabel().equals(BxZoneLabel.BODY_TABLE)) && z.getWidth() < 100) { if (z.getPrev().getLabel().equals(BxZoneLabel.BODY_TABLE) && z.getNext().getLabel().equals(BxZoneLabel.BODY_TABLE)) { z.setLabel(BxZoneLabel.BODY_TABLE); } if (z.getPrev().getLabel().equals(BxZoneLabel.BODY_TABLE)) { double prevMX = z.getPrev().getX() + z.getPrev().getWidth() / 2; double prevMY = z.getPrev().getY() + z.getPrev().getHeight() / 2; double zMX = z.getX() + z.getWidth() / 2; double zMY = z.getY() + z.getHeight() / 2; if (Math.abs(prevMX - zMX) < 200 && Math.abs(prevMY - zMY) < 200) { z.setLabel(BxZoneLabel.BODY_TABLE); } } if (z.getNext().getLabel().equals(BxZoneLabel.BODY_TABLE)) { double prevMX = z.getNext().getX() + z.getNext().getWidth() / 2; double prevMY = z.getNext().getY() + z.getNext().getHeight() / 2; double zMX = z.getX() + z.getWidth() / 2; double zMY = z.getY() + z.getHeight() / 2; if (Math.abs(prevMX - zMX) < 200 && Math.abs(prevMY - zMY) < 200) { z.setLabel(BxZoneLabel.BODY_TABLE); } } } if (pageIdx > 1 && (z.getLabel().equals(BxZoneLabel.MET_AFFILIATION) || z.getLabel().equals(BxZoneLabel.MET_ABSTRACT))) { z.setLabel(BxZoneLabel.BODY_CONTENT); } if (pageIdx == 0 && linesCount < 10 && (text.startsWith("citation:") || text.contains(" volume ") || text.contains("vol\\. ") || text.contains("doi"))) { z.setLabel(BxZoneLabel.MET_BIB_INFO); } if (pageIdx == 0 && (text.startsWith("editor:") || text.startsWith("academic editor:"))) { z.setLabel(BxZoneLabel.MET_EDITOR); } if (pageIdx == 0 && text.startsWith("copyright:")) { z.setLabel(BxZoneLabel.MET_COPYRIGHT); } if (z.getLabel().equals(BxZoneLabel.MET_DATES) && text.contains("volume") && text.contains("issue")) { z.setLabel(BxZoneLabel.MET_BIB_INFO); } if ((z.getLabel().equals(BxZoneLabel.BODY_CONTENT) || z.getLabel().equals(BxZoneLabel.MET_AUTHOR) || z.getLabel().equals(BxZoneLabel.REFERENCES) || z.getLabel().equals(BxZoneLabel.MET_DATES)) && linesCount < 6 && (z.getY() < 100 || z.getParent().getHeight() - z.getY() < 100)) { BxPage p = z.getParent(); if (pageIdx > 0) { BxPage prevPage = p.getPrev(); for (BxZone z1 : prevPage) { if (z1.toText().replaceAll("[^a-zA-Z]", "").equals(z.toText().replaceAll("[^a-zA-Z]", "")) && Math.abs(z1.getY() - z.getY()) < 10) { z.setLabel(BxZoneLabel.MET_BIB_INFO); } } } if (pageIdx < bxDoc.childrenCount() - 1) { BxPage nextPage = p.getNext(); for (BxZone z1 : nextPage) { if (z1.toText().replaceAll("[^a-zA-Z]", "").equals(z.toText().replaceAll("[^a-zA-Z]", "")) && Math.abs(z1.getY() - z.getY()) < 10) { z.setLabel(BxZoneLabel.MET_BIB_INFO); } } } if (pageIdx > 1) { BxPage prevPage = p.getPrev().getPrev(); for (BxZone z1 : prevPage) { if (z1.toText().replaceAll("[^a-zA-Z]", "").equals(z.toText().replaceAll("[^a-zA-Z]", "")) && Math.abs(z1.getY() - z.getY()) < 10) { z.setLabel(BxZoneLabel.MET_BIB_INFO); } } } if (pageIdx < bxDoc.childrenCount() - 2) { BxPage nextPage = p.getNext().getNext(); for (BxZone z1 : nextPage) { if (z1.toText().replaceAll("[^a-zA-Z]", "").equals(z.toText().replaceAll("[^a-zA-Z]", "")) && Math.abs(z1.getY() - z.getY()) < 10) { z.setLabel(BxZoneLabel.MET_BIB_INFO); } } } } if ((z.getLabel().equals(BxZoneLabel.BODY_CONTENT) || z.getLabel().equals(BxZoneLabel.OTH_UNKNOWN) || z.getLabel().equals(BxZoneLabel.MET_BIB_INFO) || z.getLabel().equals(BxZoneLabel.REFERENCES)) && text.matches("d?[0-9]+") && text.length() <= 4 && (z.getY() < 100 || z.getParent().getHeight() - z.getY() < 100)) { z.setLabel(BxZoneLabel.OTH_PAGE_NUMBER); } if (text.equals("acknowledgments")) { z.setLabel(BxZoneLabel.BODY_ACKNOWLEDGMENT); } if (text.startsWith("introduction") && z.hasPrev() && !z.getPrev().toText().equalsIgnoreCase("abstract")) { wasIntro = true; } if (wasIntro && z.getLabel().equals(BxZoneLabel.MET_ABSTRACT)) { z.setLabel(BxZoneLabel.BODY_CONTENT); } if (pageIdx == 0 && z.getLabel().equals(BxZoneLabel.REFERENCES) && !text.equals("references") && !(z.hasPrev() && z.getPrev().toText().toLowerCase(Locale.ENGLISH).equals("references"))) { z.setLabel(BxZoneLabel.MET_BIB_INFO); } if (z.getLabel().equals(BxZoneLabel.REFERENCES) && linesCount < 10 && !text.matches(".*[1-2][09][0-9][0-9].*") && z.hasNext() && z.hasPrev() && z.getPrev().getLabel().equals(BxZoneLabel.BODY_CONTENT) && z.getNext().getLabel().equals(BxZoneLabel.BODY_CONTENT)) { z.setLabel(BxZoneLabel.BODY_CONTENT); } if (z.getLabel().equals(BxZoneLabel.MET_ABSTRACT) && z.hasPrev() && z.getPrev().getLabel().equals(BxZoneLabel.MET_ABSTRACT) && z.getX() + 10 < z.getPrev().getX() && z.getWidth() * 2 < pp.getWidth()) { z.setLabel(BxZoneLabel.BODY_CONTENT); } if (z.getLabel().equals(BxZoneLabel.MET_ABSTRACT) && z.hasPrev() && z.getPrev().getLabel().equals(BxZoneLabel.BODY_CONTENT) && !text.startsWith("abstract") && z.getWidth() * 2 < pp.getWidth()) { z.setLabel(BxZoneLabel.BODY_CONTENT); } if ((z.getLabel().equals(BxZoneLabel.BODY_CONTENT) || z.getLabel().equals(BxZoneLabel.OTH_UNKNOWN)) && z.hasPrev() && z.getPrev().getLabel().equals(BxZoneLabel.REFERENCES) && (text.matches("[1-9][0-9]?[0-9]?\\.?") || text.matches(".*[1-2][0-9][0-9][0-9].*"))) { z.setLabel(BxZoneLabel.REFERENCES); } if ((z.getLabel().equals(BxZoneLabel.REFERENCES) || z.getLabel().equals(BxZoneLabel.BODY_CONTENT) || z.getLabel().equals(BxZoneLabel.OTH_UNKNOWN)) && (text.startsWith("doi") || text.startsWith("cite this article"))) { z.setLabel(BxZoneLabel.MET_BIB_INFO); } if ((z.getLabel().equals(BxZoneLabel.BODY_CONTENT) || z.getLabel().equals(BxZoneLabel.OTH_UNKNOWN)) && firstLine.toText().equalsIgnoreCase("author details")) { z.setLabel(BxZoneLabel.MET_AFFILIATION); } if ((z.getLabel().equals(BxZoneLabel.BODY_CONTENT) || z.getLabel().equals(BxZoneLabel.OTH_UNKNOWN)) && (firstLine.toText().toLowerCase(Locale.ENGLISH).equals("acknowledgments") || firstLine.toText().toLowerCase(Locale.ENGLISH).equals("acknowledgements"))) { z.setLabel(BxZoneLabel.BODY_ACKNOWLEDGMENT); } if (z.getLabel().equals(BxZoneLabel.MET_TITLE) && z.getY() * 2 > pp.getHeight()) { z.setLabel(BxZoneLabel.BODY_CONTENT); } if ((z.getY() < 100 || z.getParent().getHeight() - z.getY() < 100) && text.matches("sup-[0-9][0-9]?")) { z.setLabel(BxZoneLabel.OTH_PAGE_NUMBER); } if ((z.getLabel().equals(BxZoneLabel.BODY_CONTENT) || z.getLabel().equals(BxZoneLabel.OTH_UNKNOWN)) && firstLine.toText().equalsIgnoreCase("references")) { z.setLabel(BxZoneLabel.REFERENCES); } if (z.getLabel().equals(BxZoneLabel.BODY_CONTENT) && (firstLine.toText().matches("F[iI][gG][uU][rR][eE] [0-9IV][0-9IV]?[0-9IV]?[\\.:] [A-Z].*") || firstLine.toText().matches("F[iI][gG]\\. [0-9IV][0-9IV]?[0-9IV]?[\\.:] [A-Z].*") || firstLine.toText().matches("F[iI][gG][uU][rR][eE] [0-9IV][0-9IV]?[0-9IV]?\\.") || firstLine.toText().matches("F[iI][gG]\\. [0-9IV][0-9IV]?[0-9IV]?\\.") || firstLine.toText().matches("F[iI][gG][uU][rR][eE] [0-9IV][0-9IV]?[0-9IV]?") || firstLine.toText().matches("F[iI][gG]\\. [0-9IV][0-9IV]?[0-9IV]?"))) { z.setLabel(BxZoneLabel.BODY_FIGURE); } if (z.getLabel().equals(BxZoneLabel.BODY_CONTENT) && (firstLine.toText().matches("T[aA][bB][lL][eE] [0-9IV][0-9IV]?[0-9IV]?[\\.:] [A-Z].*") || firstLine.toText().matches("T[aA][bB][lL][eE] [0-9IV][0-9IV]?[0-9IV]?\\.?"))) { z.setLabel(BxZoneLabel.BODY_TABLE); } if (z.getLabel().equals(BxZoneLabel.BODY_ACKNOWLEDGMENT) && text.contains("this article is distributed")) { z.setLabel(BxZoneLabel.MET_COPYRIGHT); } if (pageIdx == 0 && !z.getLabel().isOfCategory(BxZoneLabelCategory.CAT_METADATA) && text.contains("journal")) { z.setLabel(BxZoneLabel.MET_BIB_INFO); } if (pageIdx == 0 && !z.getLabel().isOfCategory(BxZoneLabelCategory.CAT_METADATA) && text.contains("correspondence")) { z.setLabel(BxZoneLabel.MET_CORRESPONDENCE); } if (pageIdx == 0 && (z.getLabel().equals(BxZoneLabel.BODY_CONTENT) || z.getLabel().equals(BxZoneLabel.OTH_UNKNOWN)) && text.contains("accepted") && text.contains("published")) { z.setLabel(BxZoneLabel.MET_DATES); } if (pageIdx == 0 && linesCount < 10 && (z.getLabel().equals(BxZoneLabel.BODY_CONTENT) || z.getLabel().equals(BxZoneLabel.OTH_UNKNOWN)) && z.hasPrev() && z.getY() - z.getHeight() - z.getPrev().getY() < 4 && Math.abs(firstLine.getHeight() - z.getPrev().getFirstChild().getHeight()) < 0.5) { if (!z.getPrev().getLabel().equals(BxZoneLabel.MET_KEYWORDS)) { z.setLabel(z.getPrev().getLabel()); } } if (pageIdx == bxDoc.childrenCount() - 1 && (text.startsWith("publish with") || text.contains("will be the most significant development") || text.contains("disseminating the results of biomedical") || text.contains("sir paul nurse") || text.contains("your research papers") || text.contains("available free of charge") || text.contains("peer reviewed and published") || text.contains("cited in pubmed and archived") || text.contains("you keep the copyright") || text.contains("submit your manuscript") || text.contains("submit your next manuscript") || text.contains("online submission") || text.contains("peer review") || text.contains("space constraints") || text.contains("publication on acceptance") || text.contains("inclusion in pubmed") || text.contains("freely available") || text.contains("publication history"))) { z.setLabel(BxZoneLabel.OTH_UNKNOWN); } if (text.startsWith("funding:") || firstLine.toText().equals("Funding")) { z.setLabel(BxZoneLabel.BODY_ACKNOWLEDGMENT); } if (text.startsWith("conflicts of interest") || text.startsWith("conflict of interest") || text.startsWith("competing interests") || (z.hasPrev() && (z.getPrev().toText().toLowerCase(Locale.ENGLISH).equals("conflicts of interest") || z.getPrev().toText().toLowerCase(Locale.ENGLISH).equals("conflict of interest") || z.getPrev().toText().toLowerCase(Locale.ENGLISH).equals("competing interests")))) { z.setLabel(BxZoneLabel.BODY_CONFLICT_STMT); } changed = changed || !orig.equals(z.getLabel()); } boolean wasAuthor = false; for (BxZone z : pp) { BxZoneLabel orig = z.getLabel(); String text = ContentCleaner.cleanAllAndBreaks(z.toText()).toLowerCase(Locale.ENGLISH); if (BxZoneLabel.MET_AUTHOR.equals(z.getLabel()) && wasAuthor && ((text.contains("email") && text.contains("@")) || text.startsWith("correspondence"))) { z.setLabel(BxZoneLabel.MET_CORRESPONDENCE); } if (BxZoneLabel.MET_AUTHOR.equals(z.getLabel()) || BxZoneLabel.MET_TITLE_AUTHOR.equals(z.getLabel())) { wasAuthor = true; } changed = changed || !orig.equals(z.getLabel()); } } } return bxDoc; } public static void main(String[] args) throws FileNotFoundException, AnalysisException, ParserConfigurationException, SAXException, IOException, XPathExpressionException, TransformationException { if (args.length != 1) { System.err.println("Usage: <pubmed directory>"); System.exit(1); } File dir = new File(args[0]); Collection<File> files = FileUtils.listFiles(dir, new String[]{"pdf"}, true); int i = 0; for (File pdfFile : files) { String pdfPath = pdfFile.getPath(); String nxmlPath = TextUtils.getNLMPath(pdfPath); String cxmlPath = pdfPath.replaceFirst("\\.pdf", ".cxml"); String cpxmlPath = pdfPath.replaceFirst("\\.pdf", ".cxml-corr"); File cpxmlFile = new File(cpxmlPath); if (cpxmlFile.exists()) { i++; continue; } System.out.println(pdfPath); InputStream nxmlStream = new FileInputStream(nxmlPath); InputStream cxmlStream = new FileInputStream(cxmlPath); RuleBasedPubmedXMLGenerator datasetGenerator = new RuleBasedPubmedXMLGenerator(); datasetGenerator.setVerbose(false); BxDocument bxDoc = datasetGenerator.generateTrueViz(cxmlStream, nxmlStream); i++; Set<BxZoneLabel> set = EnumSet.noneOf(BxZoneLabel.class); for (BxZone z : bxDoc.asZones()) { if (z.getLabel() != null) { if (z.getLabel().isOfCategoryOrGeneral(BxZoneLabelCategory.CAT_METADATA)) { set.add(z.getLabel()); } } } Writer out = null; try { out = new OutputStreamWriter(new FileOutputStream(cpxmlPath), "UTF-8"); BxDocumentToTrueVizWriter writer = new BxDocumentToTrueVizWriter(); out.write(writer.write(Lists.newArrayList(bxDoc))); } finally { if (out != null) { out.close(); } } System.out.println("Progress: " + i + " out of " + files.size() + " (" + (i * 100. / files.size()) + "%)"); } } }
48,855
52.628979
200
java
CERMINE
CERMINE-master/cermine-tools/src/main/java/pl/edu/icm/cermine/pubmed/PubmedZoneLabelsEvaluator.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.pubmed; import com.google.common.collect.Lists; import java.io.*; import java.util.EnumMap; import java.util.List; import java.util.Map; 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.BxZone; import pl.edu.icm.cermine.structure.model.BxZoneLabel; import pl.edu.icm.cermine.structure.transformers.TrueVizToBxDocumentReader; /** * @author Dominika Tkaczyk (d.tkaczyk@icm.edu.pl) */ public class PubmedZoneLabelsEvaluator { public static void main(String[] args) throws FileNotFoundException, TransformationException, UnsupportedEncodingException { List<BxZoneLabel> labels = Lists.newArrayList( BxZoneLabel.MET_ABSTRACT, BxZoneLabel.BODY_ACKNOWLEDGMENT, BxZoneLabel.MET_AFFILIATION, BxZoneLabel.MET_AUTHOR, BxZoneLabel.MET_TITLE_AUTHOR, BxZoneLabel.MET_BIB_INFO, BxZoneLabel.BODY_CONTENT, BxZoneLabel.BODY_CONFLICT_STMT, BxZoneLabel.MET_COPYRIGHT, BxZoneLabel.MET_CORRESPONDENCE, BxZoneLabel.MET_DATES, BxZoneLabel.MET_EDITOR, BxZoneLabel.BODY_FIGURE, BxZoneLabel.BODY_GLOSSARY, BxZoneLabel.MET_KEYWORDS, BxZoneLabel.OTH_PAGE_NUMBER, BxZoneLabel.REFERENCES, BxZoneLabel.BODY_TABLE, BxZoneLabel.MET_TITLE, BxZoneLabel.MET_TYPE, BxZoneLabel.OTH_UNKNOWN); Map<BxZoneLabel, Map<BxZoneLabel, Integer>> map = new EnumMap<BxZoneLabel, Map<BxZoneLabel, Integer>>(BxZoneLabel.class); for (BxZoneLabel origLabel : labels) { Map<BxZoneLabel, Integer> smallMap = new EnumMap<BxZoneLabel, Integer>(BxZoneLabel.class); for (BxZoneLabel newLabel : labels) { smallMap.put(newLabel, 0); } map.put(origLabel, smallMap); } System.out.println(map); File dir = new File(args[0]); for (File tv : FileUtils.listFiles(dir, new String[]{"cxml-segm"}, true)) { System.out.println(tv.getPath()); InputStream is = new FileInputStream(tv); TrueVizToBxDocumentReader reader = new TrueVizToBxDocumentReader(); Reader r = new InputStreamReader(is, "UTF-8"); BxDocument origBxDoc = new BxDocument().setPages(reader.read(r)); File tv2 = new File(tv.getPath().replaceFirst(".cxml-segm", ".cxml-segm-m")); InputStream is2 = new FileInputStream(tv2); Reader r2 = new InputStreamReader(is2, "UTF-8"); BxDocument corrBxDoc = new BxDocument().setPages(reader.read(r2)); List<BxZone> origZones = Lists.newArrayList(origBxDoc.asZones()); List<BxZone> corrZones = Lists.newArrayList(corrBxDoc.asZones()); for (int i = 0; i < origZones.size(); i++) { BxZone origZone = origZones.get(i); BxZone corrZone = corrZones.get(i); map.get(origZone.getLabel()).put(corrZone.getLabel(), 1 + map.get(origZone.getLabel()).get(corrZone.getLabel())); } } for (BxZoneLabel origLabel : labels) { System.out.println(origLabel); Map<BxZoneLabel, Integer> smallMap = map.get(origLabel); for (BxZoneLabel newLabel : labels) { if (smallMap.get(newLabel) > 0) { System.out.println("\t" + newLabel + " " + smallMap.get(newLabel)); } } } int count = 0; int alll = 0; System.out.println(""); int sumPrec = 0; int countPrec = 0; int sumRecall = 0; int countRecall = 0; int sumF1 = 0; int countF1 = 0; for (BxZoneLabel origLabel : labels) { Map<BxZoneLabel, Integer> smallMap = map.get(origLabel); int good = smallMap.get(origLabel); count += good; int all = 0; for (BxZoneLabel newLabel : labels) { all += smallMap.get(newLabel); } alll += all; double prec = good * 100. / all; System.out.println("PREC " + origLabel + " " + (good * 100. / all)); if (all > 0) { sumPrec += (good * 100. / all); countPrec++; } all = 0; for (BxZoneLabel newLabel : labels) { all += map.get(newLabel).get(origLabel); } System.out.println("RECALL " + origLabel + " " + (good * 100. / all)); double rec = good * 100. / all; if (all > 0) { sumRecall += (good * 100. / all); countRecall++; } if (!Double.isNaN(rec) && !Double.isNaN(prec)) { sumF1 += (2 * prec * rec / (prec + rec)); countF1++; } System.out.println("F1 " + origLabel + " " + (2 * prec * rec / (prec + rec))); } System.out.println(""); System.out.println("AVG PREC " + ((double) sumPrec / (double) countPrec)); System.out.println("AVG RECALL " + ((double) sumRecall / (double) countRecall)); System.out.println("AVG F1 " + ((double) sumF1 / (double) countF1)); System.out.println(""); System.out.println("ACCURACY " + (count * 100. / alll)); } }
6,198
39.782895
129
java
CERMINE
CERMINE-master/cermine-tools/src/main/java/pl/edu/icm/cermine/pubmed/PubmedXMLGenerator.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.pubmed; import pl.edu.icm.cermine.tools.SmartHashMap; import com.google.common.collect.Lists; import java.io.*; import java.util.Map.Entry; import java.util.*; import javax.xml.parsers.DocumentBuilder; import javax.xml.parsers.DocumentBuilderFactory; import javax.xml.parsers.ParserConfigurationException; import javax.xml.xpath.XPath; import javax.xml.xpath.XPathConstants; import javax.xml.xpath.XPathExpressionException; import javax.xml.xpath.XPathFactory; import org.apache.commons.io.FileUtils; import org.apache.commons.lang.StringUtils; import org.w3c.dom.Document; import org.w3c.dom.Node; import org.w3c.dom.NodeList; import org.xml.sax.SAXException; import pl.edu.icm.cermine.ContentExtractor; import pl.edu.icm.cermine.exception.AnalysisException; import pl.edu.icm.cermine.exception.TransformationException; import pl.edu.icm.cermine.metadata.zoneclassification.tools.ZoneLocaliser; import pl.edu.icm.cermine.structure.model.*; import pl.edu.icm.cermine.structure.transformers.BxDocumentToTrueVizWriter; import pl.edu.icm.cermine.tools.TextUtils; import pl.edu.icm.cermine.tools.distance.CosineDistance; import pl.edu.icm.cermine.tools.distance.SmithWatermanDistance; /** * @author Dominika Tkaczyk (d.tkaczyk@icm.edu.pl) */ public class PubmedXMLGenerator { private static class LabelTrio { private final BxZoneLabel label; private final Double alignment; private final List<String> entryTokens; @Override public int hashCode() { final int prime = 31; int result = 1; result = prime * result + ((label == null) ? 0 : label.hashCode()); result = prime * result + ((alignment == null) ? 0 : alignment.hashCode()); return result; } @Override public boolean equals(Object obj) { if (this == obj) { return true; } if (obj == null) { return false; } if (getClass() != obj.getClass()) { return false; } LabelTrio other = (LabelTrio) obj; if (label != other.label) { return false; } if (alignment == null) { if (other.alignment != null) { return false; } } else if (!alignment.equals(other.alignment)) { return false; } return true; } public LabelTrio(BxZoneLabel label, List<String> tokens, Double similarity) { this.alignment = similarity; this.label = label; this.entryTokens = tokens; } }; private boolean verbose = false; private void setVerbose(boolean verbose) { this.verbose = verbose; } private void printlnVerbose(String string) { if (verbose) { System.out.println(string); } } private void printVerbose(String string) { if (verbose) { System.out.print(string); } } public BxDocument generateTrueViz(InputStream pdfStream, InputStream nlmStream) throws AnalysisException, ParserConfigurationException, SAXException, IOException, XPathExpressionException, TransformationException { XPath xpath = XPathFactory.newInstance().newXPath(); DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance(); dbf.setValidating(false); dbf.setFeature("http://xml.org/sax/features/namespaces", false); dbf.setFeature("http://xml.org/sax/features/validation", false); dbf.setFeature("http://apache.org/xml/features/nonvalidating/load-dtd-grammar", false); dbf.setFeature("http://apache.org/xml/features/nonvalidating/load-external-dtd", false); DocumentBuilder builder = dbf.newDocumentBuilder(); Document domDoc = builder.parse(nlmStream); ContentExtractor extractor = new ContentExtractor(); extractor.setPDF(pdfStream); BxDocument bxDoc = extractor.getBxDocument(); List<BxZone> zones = Lists.newArrayList(bxDoc.asZones()); Integer bxDocLen = zones.size(); SmartHashMap entries = new SmartHashMap(); //abstract Node abstractNode = (Node) xpath.evaluate("/article/front/article-meta/abstract", domDoc, XPathConstants.NODE); String abstractString = XMLTools.extractTextFromNode(abstractNode); entries.putIf("Abstract " + abstractString, BxZoneLabel.MET_ABSTRACT); entries.putIf("Abstract", BxZoneLabel.MET_ABSTRACT); //title String titleString = (String) xpath.evaluate("/article/front/article-meta/title-group/article-title", domDoc, XPathConstants.STRING); entries.putIf(titleString, BxZoneLabel.MET_TITLE); String subtitleString = (String) xpath.evaluate("/article/front/article-meta/title-group/article-subtitle", domDoc, XPathConstants.STRING); entries.putIf(subtitleString, BxZoneLabel.MET_TITLE); //journal title String journalTitleString = (String) xpath.evaluate("/article/front/journal-meta/journal-title", domDoc, XPathConstants.STRING); if (journalTitleString == null || journalTitleString.isEmpty()) { journalTitleString = (String) xpath.evaluate("/article/front/journal-meta/journal-title-group/journal-title", domDoc, XPathConstants.STRING); } entries.putIf(journalTitleString, BxZoneLabel.MET_BIB_INFO); //journal publisher String journalPublisherString = (String) xpath.evaluate("/article/front/journal-meta/publisher/publisher-name", domDoc, XPathConstants.STRING); entries.putIf(journalPublisherString, BxZoneLabel.MET_BIB_INFO); String journalPublisherIdString = (String) xpath.evaluate("/article/front/journal-meta/journal-id[@journal-id-type='publisher-id']", domDoc, XPathConstants.STRING); entries.putIf(journalPublisherIdString, BxZoneLabel.MET_BIB_INFO); //journal issn String journalISSNString = (String) xpath.evaluate("/article/front/journal-meta/issn", domDoc, XPathConstants.STRING); entries.putIf(journalISSNString, BxZoneLabel.MET_BIB_INFO); //copyright/permissions String permissionsString = XMLTools.extractTextFromNode((Node) xpath.evaluate("/article/front/article-meta/permissions", domDoc, XPathConstants.NODE)); entries.putIf(permissionsString, BxZoneLabel.MET_COPYRIGHT); //license Node licenseNode = (Node) xpath.evaluate("/article/front/article-meta/license", domDoc, XPathConstants.NODE); String licenseString = (String) XMLTools.extractTextFromNode(licenseNode); entries.putIf(licenseString, BxZoneLabel.MET_COPYRIGHT); //article type NodeList articleTypeNodes = (NodeList) xpath.evaluate("/article/@article-type", domDoc, XPathConstants.NODESET); List<String> articleTypeStrings = XMLTools.extractTextAsList(articleTypeNodes); Node articleTypeNode = (Node) xpath.evaluate("/article/front/article-meta/article-categories/subj-group", domDoc, XPathConstants.NODE); articleTypeStrings.add(XMLTools.extractTextFromNode(articleTypeNode)); entries.putIf(articleTypeStrings, BxZoneLabel.MET_TYPE); //received date List<String> receivedDate = XMLTools.extractChildrenAsTextList((Node) xpath.evaluate("/article/front/article-meta/history/date[@date-type='received']", domDoc, XPathConstants.NODE)); if (!receivedDate.isEmpty() && receivedDate.size() >= 3) { for (String date : TextUtils.produceDates(receivedDate)) { entries.putIf(date, BxZoneLabel.MET_DATES); } } //accepted date List<String> acceptedDate = XMLTools.extractChildrenAsTextList((Node) xpath.evaluate("/article/front/article-meta/history/date[@date-type='accepted']", domDoc, XPathConstants.NODE)); if (!acceptedDate.isEmpty() && acceptedDate.size() >= 3) { for (String date : TextUtils.produceDates(acceptedDate)) { entries.putIf(date, BxZoneLabel.MET_DATES); } } //publication date List<String> pubdateString; if (((NodeList) xpath.evaluate("/article/front/article-meta/pub-date", domDoc, XPathConstants.NODESET)).getLength() > 1) { Node pubdateNode = (Node) xpath.evaluate("/article/front/article-meta/pub-date[@pub-type='epub']", domDoc, XPathConstants.NODE); pubdateString = XMLTools.extractChildrenAsTextList(pubdateNode); } else { Node pubdateNode = (Node) xpath.evaluate("/article/front/article-meta/pub-date[@pub-type='collection']", domDoc, XPathConstants.NODE); pubdateString = XMLTools.extractChildrenAsTextList(pubdateNode); } if (pubdateString != null && pubdateString.size() >= 3) { for (String date : TextUtils.produceDates(pubdateString)) { entries.putIf(date, BxZoneLabel.MET_DATES); } } if (pubdateString != null) { pubdateString.clear(); } if (((NodeList) xpath.evaluate("/article/front/article-meta/pub-date", domDoc, XPathConstants.NODESET)).getLength() > 1) { Node pubdateNode = (Node) xpath.evaluate("/article/front/article-meta/pub-date[@pub-type='ppub']", domDoc, XPathConstants.NODE); pubdateString = XMLTools.extractChildrenAsTextList(pubdateNode); } if (pubdateString != null && pubdateString.size() >= 3) { for (String date : TextUtils.produceDates(pubdateString)) { entries.putIf(date, BxZoneLabel.MET_DATES); } } String extLink = (String) xpath.evaluate("/article/front/article-meta/ext-link[@ext-link-type='uri']/xlink:href", domDoc, XPathConstants.STRING); printlnVerbose(extLink); entries.putIf(extLink, BxZoneLabel.MET_ACCESS_DATA); //keywords Node keywordsNode = (Node) xpath.evaluate("/article/front/article-meta/kwd-group", domDoc, XPathConstants.NODE); String keywordsString = XMLTools.extractTextFromNode(keywordsNode); entries.putIf(keywordsString, BxZoneLabel.MET_KEYWORDS); //DOI String doiString = (String) xpath.evaluate("/article/front/article-meta/article-id[@pub-id-type='doi']", domDoc, XPathConstants.STRING); entries.putIf("DOI " + doiString, BxZoneLabel.MET_BIB_INFO); //volume String volumeString = (String) xpath.evaluate("/article/front/article-meta/volume", domDoc, XPathConstants.STRING); entries.putIf("volume " + volumeString, BxZoneLabel.MET_BIB_INFO); entries.putIf("vol " + volumeString, BxZoneLabel.MET_BIB_INFO); //issue String issueString = (String) xpath.evaluate("/article/front/article-meta/issue", domDoc, XPathConstants.STRING); entries.putIf("number " + issueString, BxZoneLabel.MET_BIB_INFO); entries.putIf("journal", BxZoneLabel.MET_BIB_INFO); entries.putIf("et al", BxZoneLabel.MET_BIB_INFO); List<String> authorNames = new ArrayList<String>(); List<String> authorEmails = new ArrayList<String>(); List<String> authorAffiliations = new ArrayList<String>(); List<String> editors = new ArrayList<String>(); //pages String fPage = (String) xpath.evaluate("/article/front/article-meta/fpage", domDoc, XPathConstants.STRING); String lPage = (String) xpath.evaluate("/article/front/article-meta/lpage", domDoc, XPathConstants.STRING); entries.putIf("pages " + fPage + " " + lPage, BxZoneLabel.MET_BIB_INFO); entries.putIf("pp " + fPage + " " + lPage, BxZoneLabel.MET_BIB_INFO); entries.putIf(fPage, BxZoneLabel.MET_BIB_INFO); entries.putIf(lPage, BxZoneLabel.MET_BIB_INFO); entries.putIf(lPage, BxZoneLabel.OTH_PAGE_NUMBER); entries.putIf(lPage, BxZoneLabel.OTH_PAGE_NUMBER); try { int f = Integer.parseInt(fPage); int l = Integer.parseInt(lPage); while (f < l) { f++; entries.putIf(String.valueOf(f), BxZoneLabel.OTH_PAGE_NUMBER); } } catch (NumberFormatException ex) { } entries.putIf("page of", BxZoneLabel.OTH_PAGE_NUMBER); //editors NodeList editorNodes = (NodeList) xpath.evaluate("/article/front/article-meta/contrib-group/contrib[@contrib-type='editor']", domDoc, XPathConstants.NODESET); for (int nodeIdx = 0; nodeIdx < editorNodes.getLength(); ++nodeIdx) { String editorString = XMLTools.extractTextFromNode(editorNodes.item(nodeIdx)); editors.add(editorString); } entries.putIf(TextUtils.joinStrings(editors), BxZoneLabel.MET_EDITOR); NodeList authorsResult = (NodeList) xpath.evaluate("/article/front/article-meta/contrib-group/contrib[@contrib-type='author']", domDoc, XPathConstants.NODESET); for (int nodeIdx = 0; nodeIdx < authorsResult.getLength(); ++nodeIdx) { Node curNode = authorsResult.item(nodeIdx); //author names String name = (String) xpath.evaluate("name/given-names", curNode, XPathConstants.STRING); String surname = (String) xpath.evaluate("name/surname", curNode, XPathConstants.STRING); //author affiliation List<String> aff = XMLTools.extractTextAsList((NodeList) xpath.evaluate("/article/front/article-meta/contrib-group/aff", domDoc, XPathConstants.NODESET)); //author correspondence String email; try { email = (String) xpath.evaluate("address/email", curNode, XPathConstants.STRING); } catch (XPathExpressionException e) { email = ""; } if (email.isEmpty()) { try { email = (String) xpath.evaluate("email", curNode, XPathConstants.STRING); } catch (XPathExpressionException e) { //yaaay, probably there is no e-mail at all! => do nothing } } if (!email.isEmpty()) { authorEmails.add(email); } if (!aff.isEmpty()) { authorAffiliations.addAll(aff); } authorNames.add(name + " " + surname); } entries.putIf(TextUtils.joinStrings(authorNames), BxZoneLabel.MET_AUTHOR); //authors' affiliations NodeList affNodes = (NodeList) xpath.evaluate("/article/front/article-meta/aff", domDoc, XPathConstants.NODESET); authorAffiliations.addAll(XMLTools.extractTextAsList(affNodes)); entries.putIf(authorAffiliations, BxZoneLabel.MET_AFFILIATION); //correspondence again NodeList correspNodes = (NodeList) xpath.evaluate("/article/front/article-meta/author-notes/corresp", domDoc, XPathConstants.NODESET); authorEmails.add(XMLTools.extractTextFromNodes(correspNodes)); entries.putIf(authorEmails, BxZoneLabel.MET_CORRESPONDENCE); //author notes Node notesNode = (Node) xpath.evaluate("/article/front/article-meta/author-notes/corresp/fn", domDoc, XPathConstants.NODE); String notesString = XMLTools.extractTextFromNode(notesNode); entries.putIf(notesString, BxZoneLabel.MET_CORRESPONDENCE); notesString = XMLTools.extractTextFromNode((Node) xpath.evaluate("/article/back/notes", domDoc, XPathConstants.NODE)); //article body NodeList paragraphNodes = (NodeList) xpath.evaluate("/article/body//p", domDoc, XPathConstants.NODESET); List<String> paragraphStrings = XMLTools.extractTextAsList(paragraphNodes); entries.putIf(paragraphStrings, BxZoneLabel.BODY_CONTENT); NodeList appNodes = (NodeList) xpath.evaluate("/article/back/app-group//p", domDoc, XPathConstants.NODESET); String appStrings = XMLTools.extractTextFromNodes(appNodes); entries.putIf(appStrings, BxZoneLabel.BODY_CONTENT); //section titles NodeList sectionTitleNodes = (NodeList) xpath.evaluate("/article/body//title", domDoc, XPathConstants.NODESET); List<String> sectionTitles = XMLTools.extractTextAsList(sectionTitleNodes); entries.putIf(sectionTitles, BxZoneLabel.BODY_CONTENT); NodeList appTitleNodes = (NodeList) xpath.evaluate("/article/back/app-group//title", domDoc, XPathConstants.NODESET); List<String> appTitles = XMLTools.extractTextAsList(appTitleNodes); entries.putIf(appTitles, BxZoneLabel.BODY_CONTENT); //figures NodeList figureNodes = (NodeList) xpath.evaluate("/article/floats-wrap//fig", domDoc, XPathConstants.NODESET); List<String> figureStrings = XMLTools.extractTextAsList(figureNodes); figureNodes = (NodeList) xpath.evaluate("/article/floats-group//fig", domDoc, XPathConstants.NODESET); figureStrings.addAll(XMLTools.extractTextAsList(figureNodes)); figureNodes = (NodeList) xpath.evaluate("/article/back//fig", domDoc, XPathConstants.NODESET); figureStrings.addAll(XMLTools.extractTextAsList(figureNodes)); figureNodes = (NodeList) xpath.evaluate("/article/body//fig", domDoc, XPathConstants.NODESET); figureStrings.addAll(XMLTools.extractTextAsList(figureNodes)); figureNodes = (NodeList) xpath.evaluate("/article/back/app-group//fig", domDoc, XPathConstants.NODESET); figureStrings.addAll(XMLTools.extractTextAsList(figureNodes)); entries.putIf(figureStrings, BxZoneLabel.BODY_FIGURE); //tables List<String> tableCaptions = new ArrayList<String>(); List<String> tableBodies = new ArrayList<String>(); List<String> tableFootnotes = new ArrayList<String>(); //tableNodes NodeList tableNodes = (NodeList) xpath.evaluate("/article//table-wrap", domDoc, XPathConstants.NODESET); for (Integer nodeIdx = 0; nodeIdx < tableNodes.getLength(); ++nodeIdx) { Node tableNode = tableNodes.item(nodeIdx); String caption = (String) xpath.evaluate("caption", tableNode, XPathConstants.STRING); tableCaptions.add(caption); String body = XMLTools.extractTextFromNode((Node) xpath.evaluate("table", tableNode, XPathConstants.NODE)); tableBodies.add(body); List<String> footnotes = XMLTools.extractTextAsList((NodeList) xpath.evaluate("table-wrap-foot/fn", tableNode, XPathConstants.NODESET)); tableFootnotes.addAll(footnotes); entries.putIf(caption, BxZoneLabel.BODY_TABLE); entries.putIf(body, BxZoneLabel.BODY_TABLE); entries.putIf(footnotes, BxZoneLabel.BODY_TABLE); } //financial disclosure String financialDisclosure = XMLTools.extractTextFromNode((Node) xpath.evaluate("/article//fn[@fn-type='financial-disclosure']", domDoc, XPathConstants.NODE)); entries.putIf(financialDisclosure, BxZoneLabel.BODY_ACKNOWLEDGMENT); //conflict String conflictString = XMLTools.extractTextFromNode((Node) xpath.evaluate("/article//fn[@fn-type='conflict']", domDoc, XPathConstants.NODE)); entries.putIf(conflictString, BxZoneLabel.BODY_CONFLICT_STMT); //copyright String copyrightString = XMLTools.extractTextFromNode((Node) xpath.evaluate("/article/front/article-meta/permissions/copyright-statement", domDoc, XPathConstants.NODE)); entries.putIf(copyrightString, BxZoneLabel.MET_COPYRIGHT); //acknowledgment String acknowledgement = XMLTools.extractTextFromNode((Node) xpath.evaluate("/article/back/ack", domDoc, XPathConstants.NODE)); entries.putIf(acknowledgement, BxZoneLabel.BODY_ACKNOWLEDGMENT); acknowledgement = XMLTools.extractTextFromNode((Node) xpath.evaluate("/article/back/fn-group/fn", domDoc, XPathConstants.NODE)); entries.putIf(acknowledgement, BxZoneLabel.BODY_CONFLICT_STMT); //glossary String glossary = XMLTools.extractTextFromNode((Node) xpath.evaluate("/article/back/glossary", domDoc, XPathConstants.NODE)); entries.putIf(glossary, BxZoneLabel.BODY_GLOSSARY); //formula NodeList formulaNodes = (NodeList) xpath.evaluate("/article/body//disp-formula", domDoc, XPathConstants.NODESET); for (int nodeIdx = 0; nodeIdx < formulaNodes.getLength(); ++nodeIdx) { Node curFormulaNode = formulaNodes.item(nodeIdx); String label = (String) xpath.evaluate("label", curFormulaNode); entries.putIf(label, BxZoneLabel.BODY_EQUATION); NodeList curNodeChildren = curFormulaNode.getChildNodes(); List<String> formulaParts = new ArrayList<String>(); for (int childIdx = 0; childIdx < curNodeChildren.getLength(); ++childIdx) { Node curChild = curNodeChildren.item(childIdx); if (curChild.getNodeName().equals("label")) { continue; } formulaParts.add(XMLTools.extractTextFromNode(curChild)); } entries.putIf(TextUtils.joinStrings(formulaParts), BxZoneLabel.BODY_EQUATION); } //references List<String> refStrings = new ArrayList<String>(); Node refParentNode = (Node) xpath.evaluate("/article/back/ref-list", domDoc, XPathConstants.NODE); if (refParentNode != null) { for (Integer refIdx = 0; refIdx < refParentNode.getChildNodes().getLength(); ++refIdx) { refStrings.add(XMLTools.extractTextFromNode(refParentNode.getChildNodes().item(refIdx))); } } entries.putIf(TextUtils.joinStrings(refStrings), BxZoneLabel.REFERENCES); entries.put("references", BxZoneLabel.REFERENCES); Set<String> allBibInfos = new HashSet<String>(); for (Entry<String, BxZoneLabel> entry : entries.entrySet()) { if (BxZoneLabel.MET_BIB_INFO.equals(entry.getValue())) { allBibInfos.addAll(Arrays.asList(entry.getKey().split(" "))); } } entries.put(StringUtils.join(allBibInfos, " "), BxZoneLabel.MET_BIB_INFO); printlnVerbose("journalTitle: " + journalTitleString); printlnVerbose("journalPublisher: " + journalPublisherString); printlnVerbose("journalISSNPublisher: " + journalISSNString); printlnVerbose("articleType: " + articleTypeStrings); printlnVerbose("received: " + receivedDate); printlnVerbose("accepted: " + acceptedDate); printlnVerbose("pubdate: " + pubdateString); printlnVerbose("permissions: " + permissionsString); printlnVerbose("license: " + licenseString); printlnVerbose("title: " + titleString); printlnVerbose("abstract: " + abstractString); printlnVerbose("authorEmails: " + authorEmails); printlnVerbose("authorNames: " + authorNames); printlnVerbose("authorAff: " + authorAffiliations); printlnVerbose("authorNotes: " + notesString); printlnVerbose("editor: " + editors); printlnVerbose("keywords: " + keywordsString); printlnVerbose("DOI: " + doiString); printlnVerbose("volume: " + volumeString); printlnVerbose("issue: " + issueString); printlnVerbose("financial dis.: " + financialDisclosure); printlnVerbose("paragraphs: " + paragraphStrings); printlnVerbose("section titles: " + sectionTitles); printlnVerbose("tableBodies: " + tableBodies); printlnVerbose("tableCaptions: " + tableCaptions); printlnVerbose("tableFootnotes: " + tableFootnotes); printlnVerbose("figures: " + figureStrings); printlnVerbose("acknowledgement: " + acknowledgement); printlnVerbose("ref: " + refStrings.size() + " " + refStrings); SmithWatermanDistance smith = new SmithWatermanDistance(.1, 0.1); CosineDistance cos = new CosineDistance(); //index: (zone,entry) List<List<LabelTrio>> swLabelSim = new ArrayList<List<LabelTrio>>(bxDocLen); List<List<LabelTrio>> cosLabProb = new ArrayList<List<LabelTrio>>(bxDocLen); for (Integer i = 0; i < bxDocLen; ++i) { swLabelSim.add(new ArrayList<LabelTrio>()); cosLabProb.add(new ArrayList<LabelTrio>()); } //iterate over entries for (Entry<String, BxZoneLabel> entry : entries.entrySet()) { List<String> entryTokens = TextUtils.tokenize(entry.getKey()); printlnVerbose("--------------------"); printlnVerbose(entry.getValue() + " " + entry.getKey() + "\n"); //iterate over zones for (Integer zoneIdx = 0; zoneIdx < bxDocLen; ++zoneIdx) { BxZone curZone = zones.get(zoneIdx); List<String> zoneTokens = TextUtils.tokenize( TextUtils.removeOrphantSpaces( TextUtils.cleanLigatures( curZone.toText().toLowerCase(Locale.ENGLISH)))); Double smithSim; Double cosSim; if (curZone.toText().contains("www.biomedcentral.com")) { //ignore smithSim = 0.; cosSim = 0.; } else { smithSim = smith.compare(entryTokens, zoneTokens); cosSim = cos.compare(entryTokens, zoneTokens); } printlnVerbose(smithSim + " " + zones.get(zoneIdx).toText() + "\n\n"); swLabelSim.get(zoneIdx).add(new LabelTrio(entry.getValue(), entryTokens, smithSim)); cosLabProb.get(zoneIdx).add(new LabelTrio(entry.getValue(), entryTokens, cosSim)); } } printlnVerbose("==========================="); for (BxPage page : bxDoc) { for (BxZone zone : page) { Integer zoneIdx = zones.indexOf(zone); BxZone curZone = zones.get(zoneIdx); String zoneText = TextUtils.removeOrphantSpaces(curZone.toText().toLowerCase(Locale.ENGLISH)); List<String> zoneTokens = TextUtils.tokenize(zoneText); Boolean valueSet = false; Collections.sort(swLabelSim.get(zoneIdx), new Comparator<LabelTrio>() { @Override public int compare(LabelTrio t1, LabelTrio t2) { Double simDif = t1.alignment / t1.entryTokens.size() - t2.alignment / t2.entryTokens.size(); if (Math.abs(simDif) < 0.0001) { return t2.entryTokens.size() - t1.entryTokens.size(); } if (simDif > 0) { return 1; } else { return -1; } } }); Collections.reverse(swLabelSim.get(zoneIdx)); List<String> entryTokens = swLabelSim.get(zoneIdx).get(0).entryTokens; if (Math.max(zoneTokens.size(), entryTokens.size()) > 0 && Math.min(zoneTokens.size(), entryTokens.size()) / Math.max(zoneTokens.size(), (double) entryTokens.size()) > 0.7 && swLabelSim.get(zoneIdx).get(0).alignment / entryTokens.size() > 0.7) { curZone.setLabel(swLabelSim.get(zoneIdx).get(0).label); valueSet = true; printVerbose("0 "); } if (!valueSet) { Collections.sort(swLabelSim.get(zoneIdx), new Comparator<LabelTrio>() { @Override public int compare(LabelTrio t1, LabelTrio t2) { Double simDif = t1.alignment - t2.alignment; if (Math.abs(simDif) < 0.0001) { return t2.entryTokens.size() - t1.entryTokens.size(); } if (simDif > 0) { return 1; } else { return -1; } } }); Collections.reverse(swLabelSim.get(zoneIdx)); printlnVerbose("-->" + swLabelSim.get(zoneIdx).get(0).alignment / zoneTokens.size()); if (swLabelSim.get(zoneIdx).get(0).alignment / zoneTokens.size() > 0.5) { curZone.setLabel(swLabelSim.get(zoneIdx).get(0).label); valueSet = true; printVerbose("1 "); } } if (!valueSet) { Map<BxZoneLabel, Double> cumulated = new EnumMap<BxZoneLabel, Double>(BxZoneLabel.class); for (LabelTrio trio : swLabelSim.get(zoneIdx)) { if (cumulated.containsKey(trio.label)) { cumulated.put(trio.label, cumulated.get(trio.label) + trio.alignment / Math.max(zoneTokens.size(), trio.entryTokens.size())); } else { cumulated.put(trio.label, trio.alignment / Math.max(zoneTokens.size(), trio.entryTokens.size())); } } Double max = Double.NEGATIVE_INFINITY; BxZoneLabel bestLabel = null; for (Entry<BxZoneLabel, Double> entry : cumulated.entrySet()) { if (entry.getValue() > max) { max = entry.getValue(); bestLabel = entry.getKey(); } } if (max >= 0.5) { curZone.setLabel(bestLabel); printVerbose("2 "); valueSet = true; } } if (!valueSet) { Collections.sort(swLabelSim.get(zoneIdx), new Comparator<LabelTrio>() { @Override public int compare(LabelTrio t1, LabelTrio t2) { Double simDif = t1.alignment / t1.entryTokens.size() - t2.alignment / t2.entryTokens.size(); if (Math.abs(simDif) < 0.001) { return t2.entryTokens.size() - t1.entryTokens.size(); } if (simDif > 0) { return 1; } else { return -1; } } }); Collections.reverse(swLabelSim.get(zoneIdx)); List<LabelTrio> l = swLabelSim.get(zoneIdx); BxZoneLabel best = null; int bestScore = 0; for (LabelTrio lt : l) { int i = 0; for (String zt : zoneTokens) { if (lt.entryTokens.contains(zt)) { i++; } } if (i > bestScore && i > 1) { best = lt.label; bestScore = i; } } if (best != null) { curZone.setLabel(best); valueSet = true; } else { for (LabelTrio lt : l) { int i = 0; for (String zt : zoneTokens) { for (String j : lt.entryTokens) { if (zt.replaceAll("[^0-9a-zA-Z,;\\.!\\?]", "").equals(j.replaceAll("[^0-9a-zA-Z,;\\.!\\?]", ""))) { i++; break; } } } if (i > bestScore && i > 1) { best = lt.label; bestScore = i; } } } if (best != null) { curZone.setLabel(best); valueSet = true; } } if (!valueSet) { curZone.setLabel(null); } printlnVerbose(zone.getLabel() + " " + zone.toText() + "\n"); } Map<BxZone, ZoneLocaliser> zoneLocMap = new HashMap<BxZone, ZoneLocaliser>(); Set<BxZone> unlabeledZones = new HashSet<BxZone>(); for (BxZone zone : page) { if (zone.getLabel() == null) { unlabeledZones.add(zone); zoneLocMap.put(zone, new ZoneLocaliser(zone)); } } Integer lastNumberOfUnlabeledZones; do { lastNumberOfUnlabeledZones = unlabeledZones.size(); infereLabels(unlabeledZones, zoneLocMap); infereLabels(unlabeledZones, zoneLocMap); } while (lastNumberOfUnlabeledZones != unlabeledZones.size()); } printlnVerbose("=>=>=>=>=>=>=>=>=>=>=>=>=>="); return bxDoc; } private void infereLabels(Set<BxZone> unlabeledZones, Map<BxZone, ZoneLocaliser> zoneLocMap) { Set<BxZone> toBeRemoved = new HashSet<BxZone>(); for (BxZone zone : unlabeledZones) { if (zone.getLabel() == null) { ZoneLocaliser loc = zoneLocMap.get(zone); if ((loc.getLeftZone() != null && loc.getRightZone() != null) && (loc.getLeftZone().getLabel() == loc.getRightZone().getLabel())) { zone.setLabel(loc.getLeftZone().getLabel()); printVerbose("3 "); toBeRemoved.add(zone); } else if ((loc.getLowerZone() != null && loc.getUpperZone() != null) && (loc.getLowerZone().getLabel() == loc.getUpperZone().getLabel())) { zone.setLabel(loc.getLowerZone().getLabel()); printVerbose("3 "); toBeRemoved.add(zone); } else if (zone.hasNext() && zone.hasPrev() && zone.getPrev().getLabel() == zone.getNext().getLabel()) { zone.setLabel(zone.getPrev().getLabel()); printVerbose("3 "); toBeRemoved.add(zone); } } } for (BxZone zone : toBeRemoved) { zoneLocMap.remove(zone); } unlabeledZones.removeAll(toBeRemoved); } public static void main(String[] args) throws FileNotFoundException, AnalysisException, ParserConfigurationException, SAXException, IOException, XPathExpressionException, TransformationException { if (args.length != 1) { System.err.println("Usage: <pubmed directory>"); System.exit(1); } File dir = new File(args[0]); for (File pdfFile : FileUtils.listFiles(dir, new String[]{"pdf"}, true)) { String pdfPath = pdfFile.getPath(); String nxmlPath = TextUtils.getNLMPath(pdfPath); File xmlFile = new File(TextUtils.getTrueVizPath(nxmlPath)); if (xmlFile.exists()) { continue; } System.out.print(pdfPath + " "); InputStream pdfStream = new FileInputStream(pdfPath); InputStream nxmlStream = new FileInputStream(nxmlPath); PubmedXMLGenerator datasetGenerator = new PubmedXMLGenerator(); datasetGenerator.setVerbose(false); BxDocument bxDoc = datasetGenerator.generateTrueViz(pdfStream, nxmlStream); int keys = 0; Set<BxZoneLabel> set = EnumSet.noneOf(BxZoneLabel.class); int total = 0; int known = 0; for (BxZone z : bxDoc.asZones()) { total++; if (z.getLabel() != null) { known++; if (z.getLabel().isOfCategoryOrGeneral(BxZoneLabelCategory.CAT_METADATA)) { set.add(z.getLabel()); } if (BxZoneLabel.REFERENCES.equals(z.getLabel())) { keys = 1; } } } if (set.contains(BxZoneLabel.MET_AFFILIATION)) { keys++; } if (set.contains(BxZoneLabel.MET_AUTHOR)) { keys++; } if (set.contains(BxZoneLabel.MET_BIB_INFO)) { keys++; } if (set.contains(BxZoneLabel.MET_TITLE)) { keys++; } int coverage = 0; if (total > 0) { coverage = known * 100 / total; } System.out.print(coverage + " " + set.size() + " " + keys); Writer fstream = new OutputStreamWriter(new FileOutputStream( TextUtils.getTrueVizPath(nxmlPath).replace(".xml", "." + coverage + ".cxml")), "UTF-8"); BufferedWriter out = null; try { out = new BufferedWriter(fstream); BxDocumentToTrueVizWriter writer = new BxDocumentToTrueVizWriter(); out.write(writer.write(Lists.newArrayList(bxDoc))); } finally { if (out != null) { out.close(); } } System.out.println(" done"); } } }
38,775
46.519608
200
java
CERMINE
CERMINE-master/cermine-tools/src/main/java/pl/edu/icm/cermine/affiliation/AffiliationTrainingDataExporter.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.affiliation; import java.io.*; import java.util.*; import org.apache.commons.cli.*; import org.jdom.JDOMException; import org.xml.sax.InputSource; import pl.edu.icm.cermine.exception.AnalysisException; import pl.edu.icm.cermine.metadata.affiliation.tools.AffiliationFeatureExtractor; import pl.edu.icm.cermine.metadata.affiliation.tools.AffiliationTokenizer; import pl.edu.icm.cermine.metadata.affiliation.tools.NLMAffiliationExtractor; import pl.edu.icm.cermine.metadata.model.AffiliationLabel; import pl.edu.icm.cermine.metadata.model.DocumentAffiliation; import pl.edu.icm.cermine.parsing.model.Token; import pl.edu.icm.cermine.parsing.tools.GrmmUtils; import pl.edu.icm.cermine.tools.TextUtils; /** * Class for converting affiliation features to GRMM file format. It reads * affiliations from an XML or text file, extracts their features and produces a * valid input for the ACRF model trainer. If the input file is an XML, it uses the * tags as labels. * * This class may be used to generate the ACRF training file, as well as to check * whether the Java implementation exports affiliations to the * GRMM format in the exactly same way as our Python code in the prototype. * * @author Bartosz Tarnawski */ public class AffiliationTrainingDataExporter { private static final AffiliationTokenizer TOKENIZER = new AffiliationTokenizer(); private static AffiliationFeatureExtractor featureExtractor = null; private static final String DEFAULT_INPUT = "affiliations/javatests/affs-real-like.xml"; private static final String DEFAULT_OUTPUT = "affiliations/javatests/features-actual-xml.txt"; private static final String DEFAULT_WORDS = "affiliations/javatests/words-actual-xml.txt"; private static final int DEFAULT_NEIGHBOR_THRESHOLD = 1; private static final int DEFAULT_RARE_THRESHOLD = 25; private static final String DEFAULT_INPUT_TYPE = "xml"; private static void writeAffiliation(DocumentAffiliation affiliation, PrintWriter writer, int neighborThreshold) { writer.write(GrmmUtils.toGrmmInput(affiliation.getTokens(), neighborThreshold)); writer.write("\n"); } private static void writeCommonWords(List<String> commonWords, PrintWriter wordsWriter) { Collections.sort(commonWords); for (String word : commonWords) { wordsWriter.write(word + '\n'); } } private static void addMockAffiliation(PrintWriter writer) { writer.write("TEXT ---- text\n\n"); } private static List<String> getCommonWordsFromAffs(List<DocumentAffiliation> affiliations, int rareThreshold) { Map<String, Integer> occurences = new HashMap<String, Integer>(); List<String> commonWords = new ArrayList<String>(); for (DocumentAffiliation affiliation : affiliations) { for (Token<AffiliationLabel> token: affiliation.getTokens()) { String text = token.getText(); if (!TextUtils.isWord(text)) { continue; } int wordOccurences = occurences.containsKey(text) ? occurences.get(text) : 0; occurences.put(text, wordOccurences + 1); } } for (Map.Entry<String, Integer> entry : occurences.entrySet()) { if (entry.getValue() > rareThreshold) { commonWords.add(entry.getKey()); } } return commonWords; } private static List<String> loadCommonWords(BufferedReader wordsReader) throws IOException { List<String> words = new ArrayList<String>(); String text; while ((text = wordsReader.readLine()) != null) { words.add(text); } return words; } private static List<DocumentAffiliation> loadAffiliationsFromTxt(BufferedReader reader) throws IOException { List<DocumentAffiliation> affiliations = new ArrayList<DocumentAffiliation>(); String text; while ((text = reader.readLine()) != null) { DocumentAffiliation affiliation = new DocumentAffiliation(text); affiliation.setTokens(TOKENIZER.tokenize(affiliation.getRawText())); affiliations.add(affiliation); } return affiliations; } public static void main(String[] args) throws AnalysisException, ParseException, JDOMException { Options options = new Options(); options.addOption("input", true, "input file (raw strings)"); options.addOption("output", true, "output file (GRMM format)"); options.addOption("common_words", true, "file with common (not-rare) words to generate"); options.addOption("neighbor", true, "neighbor influence threshold"); options.addOption("rare", true, "rare threshold"); options.addOption("input_type", true, "xml or txt"); options.addOption("add_mock_text", false, "should add TEXT"); options.addOption("load_words", false, "read common words from file instead of writing them"); CommandLineParser clParser = new DefaultParser(); CommandLine line = clParser.parse(options, args); String inputFileName = line.getOptionValue("input"); String outputFileName = line.getOptionValue("output"); String wordsFileName = line.getOptionValue("common_words"); String neighborThresholdString = line.getOptionValue("neighbor"); String rareThresholdString = line.getOptionValue("rare"); String inputType = line.getOptionValue("input_type"); int neighborThreshold = DEFAULT_NEIGHBOR_THRESHOLD; int rareThreshold = DEFAULT_RARE_THRESHOLD; boolean addMockText = false; boolean loadWords = false; if (line.hasOption("add_mock_text")) { addMockText = true; } if (line.hasOption("load_words")) { loadWords = true; } if (inputFileName == null) { inputFileName = DEFAULT_INPUT; } if (outputFileName == null) { outputFileName = DEFAULT_OUTPUT; } if (wordsFileName == null) { wordsFileName = DEFAULT_WORDS; } if (neighborThresholdString != null) { neighborThreshold = Integer.parseInt(neighborThresholdString); } if (rareThresholdString != null) { rareThreshold = Integer.parseInt(rareThresholdString); } if (inputType == null) { inputType = DEFAULT_INPUT_TYPE; } File file = new File(inputFileName); BufferedReader reader = null; BufferedReader wordsReader = null; PrintWriter writer = null; PrintWriter wordsWriter = null; NLMAffiliationExtractor nlmExtractor = new NLMAffiliationExtractor(); try { writer = new PrintWriter(outputFileName, "UTF-8"); if (loadWords) { wordsReader = new BufferedReader(new InputStreamReader( new FileInputStream(new File(wordsFileName)), "UTF-8")); } else { wordsWriter = new PrintWriter(wordsFileName, "UTF-8"); } List<DocumentAffiliation> affiliations = null; if (inputType.equals("txt")) { reader = new BufferedReader(new InputStreamReader( new FileInputStream(file), "UTF-8")); affiliations = loadAffiliationsFromTxt(reader); } else if (inputType.equals("xml")) { FileInputStream is = new FileInputStream(file); InputSource source = new InputSource(is); affiliations = nlmExtractor.extractStrings(source); } else { throw new ParseException("Unknown input type: " + inputType); } List <String> commonWords; if (loadWords) { commonWords = loadCommonWords(wordsReader); } else { commonWords = getCommonWordsFromAffs(affiliations, rareThreshold); } featureExtractor = new AffiliationFeatureExtractor(commonWords); for (DocumentAffiliation affiliation : affiliations) { featureExtractor.calculateFeatures(affiliation); writeAffiliation(affiliation, writer, neighborThreshold); } if (addMockText) { addMockAffiliation(writer); } if (!loadWords) { writeCommonWords(commonWords, wordsWriter); } } catch (FileNotFoundException e) { } catch (IOException e) { } finally { try { if (reader != null) { reader.close(); } if (wordsReader != null) { wordsReader.close(); } if (writer != null) { writer.close(); } if (wordsWriter != null) { wordsWriter.close(); } } catch (IOException e) { throw new RuntimeException("Can't close resources!"); } } } }
9,089
34.232558
101
java
CERMINE
CERMINE-master/cermine-tools/src/main/java/pl/edu/icm/cermine/bibref/CrossMalletTrainingFileGenerator.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.bibref; import java.io.*; import java.util.ArrayList; import java.util.Collections; import java.util.List; import java.util.Locale; import java.util.Random; import org.apache.commons.io.FileUtils; import org.apache.commons.lang.StringUtils; import org.jdom.Element; import org.jdom.JDOMException; import org.jdom.output.Format; import org.jdom.output.XMLOutputter; import org.xml.sax.InputSource; import pl.edu.icm.cermine.bibref.model.BibEntry; import pl.edu.icm.cermine.bibref.parsing.model.Citation; import pl.edu.icm.cermine.bibref.parsing.model.CitationToken; import pl.edu.icm.cermine.bibref.parsing.tools.CitationUtils; import pl.edu.icm.cermine.bibref.parsing.tools.NlmCitationExtractor; import pl.edu.icm.cermine.bibref.transformers.BibEntryToNLMConverter; import pl.edu.icm.cermine.exception.TransformationException; /** * @author Dominika Tkaczyk (d.tkaczyk@icm.edu.pl) */ public final class CrossMalletTrainingFileGenerator { private static final String NLM_FILE = "results/citations/dataset/citations.nxml"; private static final String OUT_FILE = "results/citations/training/training"; private static final String OUT_VALID_FILE = "results/citations/training/validation"; public static void main(String[] args) throws JDOMException, IOException, TransformationException { File file = new File(NLM_FILE); List<Citation> traincitations = new ArrayList<Citation>(); InputStream is = null; List<Citation> citations; try { is = new FileInputStream(file); InputSource source = new InputSource(is); citations = NlmCitationExtractor.extractCitations(source); } finally { if (is != null) { is.close(); } } Collections.shuffle(citations, new Random(5394)); traincitations.addAll(citations.subList(0, 2000)); File validFile = new File(OUT_VALID_FILE); for (Citation citation : citations) { for (CitationToken ct : citation.getTokens()) { if (ct.getText().matches("^[a-zA-Z]+$")) { FileUtils.writeStringToFile(validFile, ct.getText().toLowerCase(Locale.ENGLISH), "UTF-8", true); FileUtils.writeStringToFile(validFile, "\n", "UTF-8", true); } } } List<Citation>[] folds = new List[5]; for (int idx = 0; idx < traincitations.size(); idx++) { if (idx < 5) { folds[idx] = new ArrayList<Citation>(); } folds[idx % 5].add(traincitations.get(idx)); } Writer[] trainWriters = new Writer[5]; Writer[] testWriters = new Writer[5]; Writer[] nlmWriters = new Writer[5]; for (int idx = 0; idx < 5; idx++) { trainWriters[idx] = new OutputStreamWriter(new FileOutputStream(OUT_FILE + ".train." + idx), "UTF-8"); testWriters[idx] = new OutputStreamWriter(new FileOutputStream(OUT_FILE + ".test." + idx), "UTF-8"); nlmWriters[idx] = new OutputStreamWriter(new FileOutputStream(OUT_FILE + ".nlm." + idx), "UTF-8"); } for (int idx = 0; idx < folds.length; idx++) { XMLOutputter outputter = new XMLOutputter(Format.getPrettyFormat()); BibEntryToNLMConverter conv = new BibEntryToNLMConverter(); Element el = new Element("refs"); int k = 1; for (Citation be : folds[idx]) { BibEntry bb = CitationUtils.citationToBibref(be); Element e = conv.convert(bb); e.setAttribute("id", String.valueOf(k)); el.addContent(e); k++; } nlmWriters[idx].write(outputter.outputString(el)); } for (int idx = 0; idx < traincitations.size(); idx++) { List<String> tokens = CitationUtils.citationToMalletInputFormat(traincitations.get(idx)); String ma = StringUtils.join(tokens, "\n") + "\n\n"; for (int fIdx = 0; fIdx < 5; fIdx++) { if (fIdx == idx % 5) { testWriters[fIdx].write(ma); } else { trainWriters[fIdx].write(ma); } } } for (int idx = 0; idx < 5; idx++) { trainWriters[idx].flush(); testWriters[idx].flush(); nlmWriters[idx].flush(); } } private CrossMalletTrainingFileGenerator() { } }
5,270
37.195652
116
java
CERMINE
CERMINE-master/cermine-tools/src/main/java/pl/edu/icm/cermine/bibref/CitationDatasetGenerator.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.bibref; import com.google.common.collect.Lists; import java.io.File; import java.io.FileInputStream; import java.io.IOException; import java.io.InputStream; import java.util.*; import org.apache.commons.io.FileUtils; import org.jdom.Element; import org.jdom.JDOMException; import org.jdom.output.Format; import org.jdom.output.XMLOutputter; import org.xml.sax.InputSource; import pl.edu.icm.cermine.ContentExtractor; import pl.edu.icm.cermine.bibref.model.BibEntry; import pl.edu.icm.cermine.bibref.model.BibEntryFieldType; import pl.edu.icm.cermine.bibref.parsing.model.Citation; import pl.edu.icm.cermine.bibref.parsing.model.CitationToken; import pl.edu.icm.cermine.bibref.parsing.model.CitationTokenLabel; import pl.edu.icm.cermine.bibref.parsing.tools.CitationUtils; import pl.edu.icm.cermine.bibref.parsing.tools.NlmCitationExtractor; import pl.edu.icm.cermine.bibref.transformers.BibEntryToNLMConverter; import pl.edu.icm.cermine.exception.AnalysisException; import pl.edu.icm.cermine.exception.TransformationException; /** * @author Dominika Tkaczyk (d.tkaczyk@icm.edu.pl) */ public final class CitationDatasetGenerator { private static final String OUT_NLM = "citations.nxml"; private static final String OUT_BT = "citations.bibtex"; private static final String OUT_TXT = "citations.txt"; private static final int MAX_SET_SIZE = 100; private static final int TRIES_PER_FILE = 10; public static void main(String[] args) throws JDOMException, IOException, AnalysisException, TransformationException { if (args.length != 2) { System.out.println("Usage: PubMedToNLM <INPUT_DIR> <OUTPUT_DIR>"); System.exit(1); } Set<BibEntry> citations = new HashSet<BibEntry>(); File dir = new File(args[0]); Collection<File> files = FileUtils.listFiles(dir, new String[]{"pdf"}, true); Random random = new Random(5268); for (File file : files) { if (citations.size() == MAX_SET_SIZE) { break; } System.out.println("Processing: " + file.getPath()); InputStream isRefs = new FileInputStream(file); ContentExtractor extractor = new ContentExtractor(); extractor.setPDF(isRefs); List<BibEntry> cermineCitations = extractor.getReferences(); File nlm = new File(file.getPath().replace(".pdf", ".nxml")); FileInputStream isNLM = new FileInputStream(nlm); InputSource sourceNlm = new InputSource(isNLM); List<Citation> nlmCitations = NlmCitationExtractor.extractCitations(sourceNlm); Set<Integer> usedIndices = new HashSet<Integer>(); int added = 0; for (int j = 0; j < Math.min(nlmCitations.size(), TRIES_PER_FILE); j++) { if (citations.size() == MAX_SET_SIZE) { break; } int index = random.nextInt(nlmCitations.size()); if (usedIndices.contains(index)) { continue; } usedIndices.add(index); Citation nlmCitation = nlmCitations.get(index); BibEntry nlmBibEntry = CitationUtils.citationToBibref(nlmCitation); String nlmTitle = nlmBibEntry.getFirstFieldValue(BibEntryFieldType.TITLE); if (nlmTitle == null) { continue; } nlmTitle = nlmTitle.replaceAll("\\s+", " "); for (BibEntry cermineCitation: cermineCitations) { String cermineText = cermineCitation.getText().replaceAll("\\s+", " "); if (cermineText.contains(nlmTitle)) { Citation matchedCitation = CitationUtils.stringToCitation(cermineText); List<CitationToken> nlmTokens = Lists.newArrayList(nlmCitation.getTokens()); for (CitationToken matchedToken : matchedCitation.getTokens()) { matchedToken.setLabel(CitationTokenLabel.TEXT); if (matchedToken.getText().equals(",") || matchedToken.getText().equals(".") || matchedToken.getText().equals(":") || matchedToken.getText().equals(";")) { continue; } CitationToken chosenNlmToken = null; for (CitationToken nlmToken : nlmTokens) { if (nlmToken.getText().equals(matchedToken.getText())) { matchedToken.setLabel(nlmToken.getLabel()); chosenNlmToken = nlmToken; break; } } if (chosenNlmToken != null) { nlmTokens.remove(chosenNlmToken); } } List<CitationToken> tokens = matchedCitation.getTokens(); for (int k = 1; k < tokens.size()-1; k++) { CitationToken prev = tokens.get(k-1); CitationToken ct = tokens.get(k); CitationToken next = tokens.get(k+1); if (ct.getText().length() == 1 && prev.getLabel().equals(next.getLabel()) && !CitationTokenLabel.TEXT.equals(next.getLabel())) { ct.setLabel(prev.getLabel()); } } for (int k = 1; k < tokens.size()-1; k++) { CitationToken prev = tokens.get(k-1); CitationToken ct = tokens.get(k); if (ct.getLabel().equals(CitationTokenLabel.ARTICLE_TITLE)) { break; } if (ct.getText().matches("[A-Z]") || (prev.getText().matches("[A-Z]") && ct.getText().equals("."))) { ct.setLabel(CitationTokenLabel.GIVENNAME); } } BibEntry matchedBibEntry = CitationUtils.citationToBibref(matchedCitation); int unlabelledTotalLen = 0; int totalLen = 0; for (CitationToken ct : matchedCitation.getTokens()) { totalLen += ct.getText().length(); if (ct.getLabel().equals(CitationTokenLabel.TEXT)) { unlabelledTotalLen += ct.getText().length(); } } if (unlabelledTotalLen > 0.25 * totalLen) { continue; } citations.add(matchedBibEntry); added++; } } } System.out.println("Citations added: " + added); } File nlm = new File(args[1] + OUT_NLM); File bt = new File(args[1] + OUT_BT); File txt = new File(args[1] + OUT_TXT); BibEntryToNLMConverter converter = new BibEntryToNLMConverter(); XMLOutputter outputter = new XMLOutputter(Format.getRawFormat()); int k = 1; for (BibEntry citation : citations) { Element element = converter.convert(citation); element.setAttribute("id", String.valueOf(k++)); FileUtils.writeStringToFile(nlm, outputter.outputString(element), "UTF-8", true); FileUtils.writeStringToFile(bt, citation.toBibTeX(), "UTF-8", true); FileUtils.writeStringToFile(txt, citation.getText(), "UTF-8", true); FileUtils.writeStringToFile(nlm, "\n", "UTF-8", true); FileUtils.writeStringToFile(bt, "\n", "UTF-8", true); FileUtils.writeStringToFile(txt, "\n", "UTF-8", true); } } private CitationDatasetGenerator() { } }
9,227
45.84264
122
java
CERMINE
CERMINE-master/cermine-tools/src/main/java/pl/edu/icm/cermine/bibref/MalletTrainingFileGenerator.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.bibref; import java.io.*; import java.util.Map.Entry; import java.util.*; import org.jdom.JDOMException; import org.xml.sax.InputSource; import pl.edu.icm.cermine.bibref.parsing.model.Citation; import pl.edu.icm.cermine.bibref.parsing.model.CitationToken; import pl.edu.icm.cermine.bibref.parsing.model.CitationTokenLabel; import pl.edu.icm.cermine.bibref.parsing.tools.CitationUtils; import pl.edu.icm.cermine.bibref.parsing.tools.NlmCitationExtractor; import pl.edu.icm.cermine.tools.CountMap; import pl.edu.icm.cermine.tools.PrefixTree; /** * @author Dominika Tkaczyk (d.tkaczyk@icm.edu.pl) */ public final class MalletTrainingFileGenerator { private static final int MIN_TERM_COUNT = 3; private static final int MIN_JOURNAL_COUNT = 2; private static final int MIN_SURNAME_COUNT = 2; private static final int MIN_INST_COUNT = 1; public static void main(String[] args) throws JDOMException, IOException { File inputFile = new File(args[0]); List<Citation> citations = new ArrayList<Citation>(); CountMap<String> termCounts = new CountMap<String>(); CountMap<String> journalCounts = new CountMap<String>(); CountMap<String> surnameCounts = new CountMap<String>(); CountMap<String> instCounts = new CountMap<String>(); InputStream is = null; try { is = new FileInputStream(inputFile); InputSource source = new InputSource(is); citations = NlmCitationExtractor.extractCitations(source); } finally { if (is != null) { is.close(); } } for (Citation citation : citations) { for (CitationToken citationToken : citation.getTokens()) { String term = citationToken.getText().toLowerCase(Locale.ENGLISH); termCounts.add(term); } for (CitationToken citationToken : citation.getConcatenatedTokens()) { String term = citationToken.getText().toLowerCase(Locale.ENGLISH); if (citationToken.getLabel() == CitationTokenLabel.SOURCE) { journalCounts.add(term); } if (citationToken.getLabel() == CitationTokenLabel.SURNAME) { surnameCounts.add(term); } if (citationToken.getLabel() == CitationTokenLabel.INSTITUTION) { instCounts.add(term); } } } List<Entry<String, Integer>> wordCounts = termCounts.getSortedEntries(MIN_TERM_COUNT); Set<String> additionalFeatures = new HashSet<String>(); for (Entry<String, Integer> wordCount : wordCounts) { additionalFeatures.add(wordCount.getKey()); } List<Entry<String, Integer>> jCounts = journalCounts.getSortedEntries(MIN_JOURNAL_COUNT); Set<String> journals = new HashSet<String>(); for (Entry<String, Integer> jCount : jCounts) { journals.add(jCount.getKey()); } PrefixTree journalTree = new PrefixTree(PrefixTree.START_TERM); journalTree.build(journals); List<Entry<String, Integer>> sCounts = surnameCounts.getSortedEntries(MIN_SURNAME_COUNT); Set<String> surnames = new HashSet<String>(); for (Entry<String, Integer> sCount : sCounts) { surnames.add(sCount.getKey()); } PrefixTree surnameTree = new PrefixTree(PrefixTree.START_TERM); surnameTree.build(surnames); List<Entry<String, Integer>> iCounts = instCounts.getSortedEntries(MIN_INST_COUNT); Set<String> insts = new HashSet<String>(); for (Entry<String, Integer> iCount : iCounts) { insts.add(iCount.getKey()); } PrefixTree instTree = new PrefixTree(PrefixTree.START_TERM); instTree.build(insts); Writer featuresWriter = null; Writer termsWriter = null; Writer journalsWriter = null; Writer surnamesWriter = null; Writer instsWriter = null; try { featuresWriter = new OutputStreamWriter(new FileOutputStream(args[1]), "UTF-8"); termsWriter = new OutputStreamWriter(new FileOutputStream(args[2]), "UTF-8"); journalsWriter = new OutputStreamWriter(new FileOutputStream(args[3]), "UTF-8"); surnamesWriter = new OutputStreamWriter(new FileOutputStream(args[4]), "UTF-8"); instsWriter = new OutputStreamWriter(new FileOutputStream(args[5]), "UTF-8"); for (String s : additionalFeatures) { termsWriter.write(s); termsWriter.write("\n"); } termsWriter.flush(); termsWriter.close(); for (String s : journals) { journalsWriter.write(s); journalsWriter.write("\n"); } journalsWriter.flush(); journalsWriter.close(); for (String s : surnames) { surnamesWriter.write(s); surnamesWriter.write("\n"); } surnamesWriter.flush(); surnamesWriter.close(); for (String s : insts) { instsWriter.write(s); instsWriter.write("\n"); } instsWriter.flush(); instsWriter.close(); for (Citation citation : citations) { List<String> tokens = CitationUtils.citationToMalletInputFormat(citation, additionalFeatures, journalTree, surnameTree, instTree); for (String token : tokens) { featuresWriter.write(token); featuresWriter.write("\n"); } featuresWriter.write("\n"); } featuresWriter.flush(); } finally { if (featuresWriter != null) { featuresWriter.close(); } if (termsWriter != null) { termsWriter.close(); } } } private MalletTrainingFileGenerator() { } }
6,935
38.634286
146
java
CERMINE
CERMINE-master/cermine-tools/src/main/java/pl/edu/icm/cermine/bibref/CoraRefToNLM.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.bibref; import java.io.File; import java.io.FileInputStream; import java.io.IOException; import java.io.InputStream; import java.util.ArrayList; import java.util.List; import java.util.regex.Matcher; import java.util.regex.Pattern; import org.apache.commons.io.FileUtils; import org.jdom.Element; import org.jdom.JDOMException; import org.jdom.output.Format; import org.jdom.output.XMLOutputter; import org.xml.sax.InputSource; import pl.edu.icm.cermine.bibref.model.BibEntry; import pl.edu.icm.cermine.bibref.model.BibEntryFieldType; import pl.edu.icm.cermine.bibref.parsing.model.Citation; import pl.edu.icm.cermine.bibref.parsing.model.CitationToken; import pl.edu.icm.cermine.bibref.parsing.model.CitationTokenLabel; import pl.edu.icm.cermine.bibref.parsing.tools.CitationUtils; import pl.edu.icm.cermine.bibref.parsing.tools.NlmCitationExtractor; import pl.edu.icm.cermine.bibref.transformers.BibEntryToNLMConverter; import pl.edu.icm.cermine.exception.TransformationException; /** * @author Dominika Tkaczyk (d.tkaczyk@icm.edu.pl) */ public final class CoraRefToNLM { private static final String NLM_DIR = "cermine-tests/mixed.citations.xml"; private static final String OUT_NLM = "results/citations/citations.nxml"; private static final String OUT_BT = "results/citations/citations.bibtex"; private static final String OUT_TXT = "results/citations/citations.txt"; public static void main(String[] args) throws JDOMException, IOException, TransformationException { InputStream is = null; List<Citation> citations; try { is = new FileInputStream(new File(NLM_DIR)); InputSource source = new InputSource(is); citations = NlmCitationExtractor.extractCitations(source); } finally { if (is != null) { is.close(); } } outer: for (Citation citation : citations) { int ind = 0; boolean pagef = true; for (CitationToken ct : citation.getTokens()) { if (CitationTokenLabel.YEAR.equals(ct.getLabel()) && ct.getText().length() < 4) { ct.setLabel(CitationTokenLabel.TEXT); } if (CitationTokenLabel.ARTICLE_TITLE.equals(ct.getLabel()) && ind < citation.getTokens().size() - 1) { CitationToken next = citation.getTokens().get(ind + 1); if ((ct.getText().equals(".") || ct.getText().equals(",")) && !CitationTokenLabel.ARTICLE_TITLE.equals(next.getLabel())) { ct.setLabel(CitationTokenLabel.TEXT); } } if (CitationTokenLabel.SOURCE.equals(ct.getLabel()) && ind < citation.getTokens().size() - 1) { CitationToken next = citation.getTokens().get(ind + 1); if ((ct.getText().equals(".") || ct.getText().equals(",")) && !CitationTokenLabel.SOURCE.equals(next.getLabel())) { ct.setLabel(CitationTokenLabel.TEXT); } } if (CitationTokenLabel.PAGEF.equals(ct.getLabel())) { if (ct.getText().matches(".*\\d")) { if (pagef) { ct.setLabel(CitationTokenLabel.PAGEF); pagef = false; } else { ct.setLabel(CitationTokenLabel.PAGEL); pagef = true; } } else { ct.setLabel(CitationTokenLabel.TEXT); } } ind++; } ind = 0; CitationTokenLabel lastLabel = CitationTokenLabel.TEXT; for (CitationToken ct : citation.getTokens()) { if (CitationTokenLabel.SOURCE.equals(lastLabel) && CitationTokenLabel.TEXT.equals(ct.getLabel()) && ct.getText().matches("\\d+")) { ct.setLabel(CitationTokenLabel.VOLUME); } if (CitationTokenLabel.VOLUME.equals(lastLabel) && CitationTokenLabel.TEXT.equals(ct.getLabel()) && ct.getText().matches("\\d+")) { ct.setLabel(CitationTokenLabel.ISSUE); } if (!CitationTokenLabel.TEXT.equals(ct.getLabel())) { lastLabel = ct.getLabel(); } ind++; } BibEntry be = CitationUtils.citationToBibref(citation); List<String> toks = new ArrayList<String>(); List<CitationTokenLabel> labs = new ArrayList<CitationTokenLabel>(); for (String s : be.getAllFieldValues(BibEntryFieldType.AUTHOR)) { String tmp = s.trim().replaceAll(" +,", ",").replaceAll("\\.", " ").replaceAll(",", ", ").replaceAll(" +", " "); Pattern p1 = Pattern.compile("^[A-Z] [A-Z][-A-Za-z]+ ?($|,|and|AND|&)"); Pattern p2 = Pattern.compile("^[A-Z] [A-Z] [A-Z][-A-Za-z]+ ?($|,|and|AND|&)"); Pattern p3 = Pattern.compile("^[A-Z][-A-Za-z]+, [A-Z] ?($|,|and|AND|&)"); Pattern p4 = Pattern.compile("^[A-Z][-A-Za-z]+, [A-Z] ?[A-Z] ?($|,|and|AND|&)"); Pattern p5 = Pattern.compile("^[A-Z][-A-Za-z]+ [A-Z] [A-Z][-A-Za-z]+ ?($|,|and|AND|&)"); Pattern p6 = Pattern.compile("^[A-Z][-A-Za-z]+ [A-Z] [A-Z] [A-Z][-A-Za-z]+ ?($|,|and|AND|&)"); Pattern p7 = Pattern.compile("^[A-Z][-A-Za-z]+ [A-Z] ?($|,|and|AND|&)"); Pattern p8 = Pattern.compile("^[A-Z][-A-Za-z]+ [A-Z] [A-Z] ?($|,|and|AND|&)"); Pattern p9 = Pattern.compile("^[A-Z][-A-Za-z]+, [A-Z][-A-Za-z]+ ?($|,|and|AND|&)"); Pattern p10 = Pattern.compile("^[A-Z][-A-Za-z]+ [A-Z][-A-Za-z]+ ?($|,|and|AND|&)"); while (!tmp.isEmpty()) { tmp = tmp.trim().replaceAll("^, ", "").replaceAll("^and ", "").replaceAll("^& ", ""); Matcher m1 = p1.matcher(tmp); Matcher m2 = p2.matcher(tmp); Matcher m3 = p3.matcher(tmp); Matcher m4 = p4.matcher(tmp); Matcher m5 = p5.matcher(tmp); Matcher m6 = p6.matcher(tmp); Matcher m7 = p7.matcher(tmp); Matcher m8 = p8.matcher(tmp); Matcher m9 = p9.matcher(tmp); Matcher m10 = p10.matcher(tmp); if (m1.find() && m1.start() == 0) { String author = m1.group(); String initials = author.substring(0, 1); toks.add(initials); labs.add(CitationTokenLabel.GIVENNAME); author = author.substring(2).replaceAll("[^-A-Za-z].*", ""); d(author, toks, labs, CitationTokenLabel.SURNAME); tmp = tmp.substring(m1.end()); } else if (m2.find() && m2.start() == 0) { String author = m2.group(); String initials = author.substring(0, 1); toks.add(initials); labs.add(CitationTokenLabel.GIVENNAME); initials = author.substring(2, 3); toks.add(initials); labs.add(CitationTokenLabel.GIVENNAME); author = author.substring(4).replaceAll("[^-A-Za-z].*", ""); d(author, toks, labs, CitationTokenLabel.SURNAME); tmp = tmp.substring(m2.end()); } else if (m3.find() && m3.start() == 0) { String author = m3.group(); String sn = author.replaceAll(",.*", ""); d(sn, toks, labs, CitationTokenLabel.SURNAME); author = author.replaceAll("[^, ]+, ", ""); String initials = author.substring(0, 1); toks.add(initials); labs.add(CitationTokenLabel.GIVENNAME); tmp = tmp.substring(m3.end()); } else if (m4.find() && m4.start() == 0) { String author = m4.group(); String sn = author.replaceAll(",.*", ""); d(sn, toks, labs, CitationTokenLabel.SURNAME); author = author.replaceAll("[^, ]+, ", ""); String initials = author.substring(0, 1); toks.add(initials); labs.add(CitationTokenLabel.GIVENNAME); author = author.substring(1).trim(); initials = author.substring(0, 1); toks.add(initials); labs.add(CitationTokenLabel.GIVENNAME); tmp = tmp.substring(m4.end()); } else if (m5.find() && m5.start() == 0) { String author = m5.group(); String sn = author.replaceAll(" .*", ""); d(sn, toks, labs, CitationTokenLabel.GIVENNAME); author = author.replaceAll("^[-a-zA-Z]+ ", ""); String initials = author.substring(0, 1); toks.add(initials); labs.add(CitationTokenLabel.GIVENNAME); author = author.substring(1).trim().replaceAll("( |,|&).*", ""); d(author, toks, labs, CitationTokenLabel.SURNAME); tmp = tmp.substring(m5.end()); } else if (m6.find() && m6.start() == 0) { String author = m6.group(); String sn = author.replaceAll(" .*", ""); d(sn, toks, labs, CitationTokenLabel.GIVENNAME); author = author.replaceAll("^[-a-zA-Z]+ ", ""); String initials = author.substring(0, 1); toks.add(initials); labs.add(CitationTokenLabel.GIVENNAME); author = author.substring(1).trim(); initials = author.substring(0, 1); toks.add(initials); labs.add(CitationTokenLabel.GIVENNAME); author = author.substring(1).trim().replaceAll("( |,|&).*", ""); d(author, toks, labs, CitationTokenLabel.SURNAME); tmp = tmp.substring(m6.end()); } else if (m7.find() && m7.start() == 0) { String author = m7.group(); String sn = author.replaceAll(" .*", ""); d(sn, toks, labs, CitationTokenLabel.SURNAME); author = author.replaceAll("^[^ ]+ ", ""); String initials = author.substring(0, 1); toks.add(initials); labs.add(CitationTokenLabel.GIVENNAME); tmp = tmp.substring(m7.end()); } else if (m8.find() && m8.start() == 0) { String author = m8.group(); String sn = author.replaceAll(" .*", ""); d(sn, toks, labs, CitationTokenLabel.SURNAME); author = author.replaceAll("^[^ ]+ ", ""); String initials = author.substring(0, 1); toks.add(initials); labs.add(CitationTokenLabel.GIVENNAME); author = author.substring(1).trim(); initials = author.substring(0, 1); toks.add(initials); labs.add(CitationTokenLabel.GIVENNAME); tmp = tmp.substring(m8.end()); } else if (m9.find() && m9.start() == 0) { String author = m9.group(); String sn = author.replaceAll(",.*", ""); d(sn, toks, labs, CitationTokenLabel.SURNAME); author = author.replaceAll("^[^ ]+ ", ""); sn = author.replaceAll("( |,|&).*", ""); d(sn, toks, labs, CitationTokenLabel.GIVENNAME); tmp = tmp.substring(m9.end()); } else if (m10.find() && m10.start() == 0) { String author = m10.group(); String sn = author.replaceAll(" .*", ""); d(sn, toks, labs, CitationTokenLabel.GIVENNAME); author = author.replaceAll("^[^ ]+ ", ""); sn = author.replaceAll("( |,|&).*", ""); d(sn, toks, labs, CitationTokenLabel.SURNAME); tmp = tmp.substring(m10.end()); } else { break; } } if (!tmp.isEmpty()) { continue outer; } } ind = 0; CitationToken prev = null; for (CitationToken ct : citation.getTokens()) { if (CitationTokenLabel.SURNAME.equals(ct.getLabel())) { if (toks.isEmpty()) { break; } if (ind < toks.size() && ct.getText().equals(toks.get(ind))) { ct.setLabel(labs.get(ind)); ind++; } else if (prev != null && CitationTokenLabel.GIVENNAME.equals(prev.getLabel()) && ct.getText().equals(".")) { ct.setLabel(CitationTokenLabel.GIVENNAME); } else { ct.setLabel(CitationTokenLabel.TEXT); } } prev = ct; } } File nlm = new File(OUT_NLM); File bt = new File(OUT_BT); File txt = new File(OUT_TXT); BibEntryToNLMConverter conv = new BibEntryToNLMConverter(); XMLOutputter outputter = new XMLOutputter(Format.getRawFormat()); int k = 3421; for (Citation citation : citations) { Element e = conv.convert(CitationUtils.citationToBibref(citation)); e.setAttribute("id", String.valueOf(k++)); FileUtils.writeStringToFile(nlm, outputter.outputString(e), "UTF-8", true); FileUtils.writeStringToFile(bt, CitationUtils.citationToBibref(citation).toBibTeX(), "UTF-8", true); FileUtils.writeStringToFile(txt, CitationUtils.citationToBibref(citation).getText(), "UTF-8", true); FileUtils.writeStringToFile(nlm, "\n", "UTF-8", true); FileUtils.writeStringToFile(bt, "\n", "UTF-8", true); FileUtils.writeStringToFile(txt, "\n", "UTF-8", true); } } private static void d(String text, List<String> toks, List<CitationTokenLabel> labs, CitationTokenLabel label) { while (!text.isEmpty()) { if (text.charAt(0) == '-') { toks.add("-"); labs.add(label); text = text.substring(1); } else { toks.add(text.replaceAll("-.*", "")); labs.add(label); text = text.replaceAll("^[a-zA-Z]+", ""); } } } private CoraRefToNLM() { } }
16,618
45.814085
142
java
CERMINE
CERMINE-master/cermine-web/src/test/java/pl/edu/icm/cermine/service/CermineExtractorServiceImplTest.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.service; import java.io.InputStream; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.Map; import java.util.logging.Level; import static org.junit.Assert.*; import org.junit.*; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import pl.edu.icm.cermine.ContentExtractor; import pl.edu.icm.cermine.exception.AnalysisException; /** * @author Aleksander Nowinski (a.nowinski@icm.edu.pl) */ public class CermineExtractorServiceImplTest { Logger log = LoggerFactory.getLogger(CermineExtractorServiceImplTest.class); public CermineExtractorServiceImplTest() { } @BeforeClass public static void setUpClass() { } @AfterClass public static void tearDownClass() { } @Before public void setUp() { } @After public void tearDown() { } /** * Test of extractNLM method, of class CermineExtractorServiceImpl. * @throws java.lang.Exception */ @Test public void testExtractNLM() throws Exception { System.out.println("extractNLM"); InputStream is = this.getClass().getResourceAsStream("/pdf/test1.pdf"); log.debug("Input stream is: {}", is); CermineExtractorServiceImpl instance = new CermineExtractorServiceImpl(); instance.init(); ExtractionResult result = instance.extractNLM(is); assertNotNull(result); assertTrue(result.isSucceeded()); } /** * Test of extractNLM method, of class CermineExtractorServiceImpl. * @throws java.lang.Exception */ @Test public void testQueue() throws Exception { System.out.println("Queue overflow"); final CermineExtractorServiceImpl instance = new CermineExtractorServiceImpl(); instance.setThreadPoolSize(1); instance.setMaxQueueForBatch(1); instance.init(); final Map<Integer, Boolean> succ = new HashMap<Integer, Boolean>(); //run immediately two, then List<Thread> threads = new ArrayList<Thread>(); for (int i = 0; i < 4; i++) { final int k = i; threads.add(new Thread(new Runnable() { @Override public void run() { int idx = k; try { succ.put(idx, true); instance.extractNLM(this.getClass().getResourceAsStream("/pdf/test1.pdf")); log.debug("Extraction succeeeded..."); } catch (ServiceException ex) { succ.put(idx, false); log.debug("Service exception"); } catch (AnalysisException ex) { java.util.logging.Logger.getLogger(CermineExtractorServiceImplTest.class.getName()).log(Level.SEVERE, null, ex); } } })); } for (Thread t : threads) { t.start(); Thread.sleep(500); } for (Thread t : threads) { if (t.isAlive()) { t.join(); } } for (int i = 0; i < 2; i++) { assertTrue(succ.get(i)); } assertFalse(succ.get(2)); assertFalse(succ.get(3)); } boolean sleeping = true; /** * Test of obtainExtractor method, of class CermineExtractorServiceImpl. * @throws java.lang.Exception */ @Test public void testObtainExtractor() throws Exception { System.out.println("obtainExtractor"); final CermineExtractorServiceImpl instance = new CermineExtractorServiceImpl(); instance.setThreadPoolSize(3); instance.init(); List<ContentExtractor> list = new ArrayList<ContentExtractor>(); for (int i = 0; i < 3; i++) { list.add(instance.obtainExtractor()); } sleeping = true; new Thread(new Runnable() { @Override public void run() { ContentExtractor res = instance.obtainExtractor(); sleeping = false; } }).start(); assertTrue(sleeping); Thread.sleep(100); assertTrue(sleeping); instance.returnExtractor(list.remove(0)); Thread.sleep(100); assertFalse(sleeping); } }
5,089
30.8125
136
java
CERMINE
CERMINE-master/cermine-web/src/test/java/pl/edu/icm/cermine/service/ArticleMetaTest.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.service; import org.jdom.Document; import org.jdom.input.SAXBuilder; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertTrue; import org.junit.*; /** * @author Aleksander Nowinski (a.nowinski@icm.edu.pl) */ public class ArticleMetaTest { public ArticleMetaTest() { } @BeforeClass public static void setUpClass() { } @AfterClass public static void tearDownClass() { } @Before public void setUp() { } @After public void tearDown() { } /** * Test of extractNLM method, of class ArticleMeta. */ @Test public void testExtractNLM() throws Exception { System.out.println("extractNLM"); SAXBuilder builder = new SAXBuilder(); Document nlm = builder.build(this.getClass().getResourceAsStream("/sampleNlm.xml")); ArticleMeta result = ArticleMeta.extractNLM(nlm); assertEquals("Association des Annales de l’institut Fourier", result.getPublisher()); assertEquals("Annales de l’institut Fourier",result.getJournalTitle()); assertEquals("Analytic inversion of adjunction: blabla extension theorems with gain", result.getTitle()); assertEquals("10.1016/j.lisr.2011.06.002", result.getDoi()); assertEquals("Some abstract text...", result.getAbstractText()); assertEquals("703", result.getFpage()); assertEquals("718", result.getLpage()); assertEquals("57", result.getVolume()); assertEquals("3", result.getIssue()); assertEquals("2007", result.getPubDate()); assertEquals("2005-07-25", result.getReceivedDate()); assertEquals("2006-02-20", result.getAcceptedDate()); assertEquals(2, result.getAuthors().size()); assertTrue(result.getAuthors().get(0).getName().contains("McNeal")); assertTrue(result.getAuthors().get(0).getName().contains("Jeffery D.")); assertTrue(result.getKeywords().contains("32Q99")); assertTrue(result.getKeywords().contains("denominators")); assertEquals(8, result.getKeywords().size()); } }
2,874
33.638554
113
java
CERMINE
CERMINE-master/cermine-web/src/main/java/pl/edu/icm/cermine/service/ArticleMeta.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.service; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.Map; import org.jdom.Document; import org.jdom.Element; import org.jdom.JDOMException; import org.jdom.xpath.XPath; import org.slf4j.LoggerFactory; /** * @author Aleksander Nowinski (a.nowinski@icm.edu.pl) */ public class ArticleMeta { static org.slf4j.Logger log = LoggerFactory.getLogger(ArticleMeta.class); private String title; private String journalTitle; private String journalISSN; private String publisher; private String publisherLoc; private String doi; private String urn; private String abstractText; private List<ContributorMeta> authors; private List<ContributorMeta> editors; private List<String> keywords; private String fpage; private String lpage; private String volume; private String issue; private String pubDate; private String receivedDate; private String revisedDate; private String acceptedDate; private List<ArticleMeta> references; public String getTitle() { return title; } public void setTitle(String title) { this.title = title; } public String getJournalTitle() { return journalTitle; } public void setJournalTitle(String journalTitle) { this.journalTitle = journalTitle; } public String getJournalISSN() { return journalISSN; } public void setJournalISSN(String journalISSN) { this.journalISSN = journalISSN; } public String getPublisher() { return publisher; } public void setPublisher(String publisher) { this.publisher = publisher; } public String getPublisherLoc() { return publisherLoc; } public void setPublisherLoc(String publisherLoc) { this.publisherLoc = publisherLoc; } public String getDoi() { return doi; } public void setDoi(String doi) { this.doi = doi; } public String getUrn() { return urn; } public void setUrn(String urn) { this.urn = urn; } public String getAbstractText() { return abstractText; } public void setAbstractText(String abstractText) { this.abstractText = abstractText; } public List<ContributorMeta> getAuthors() { return authors; } public void setAuthors(List<ContributorMeta> authors) { this.authors = authors; } public List<ContributorMeta> getEditors() { return editors; } public void setEditors(List<ContributorMeta> editors) { this.editors = editors; } public String getKeywordsString() { StringBuilder resb = new StringBuilder(); for (String k : keywords) { resb.append(k).append("; "); } String res = resb.toString(); if (!res.isEmpty()) { res = res.substring(0, resb.length() - 2); } return res; } public String getFpage() { return fpage; } public void setFpage(String fpage) { this.fpage = fpage; } public String getLpage() { return lpage; } public void setLpage(String lpage) { this.lpage = lpage; } public String getPages() { if (fpage != null && !fpage.isEmpty() && lpage != null && !lpage.isEmpty()) { return fpage + "-" + lpage; } return fpage; } public String getVolume() { return volume; } public void setVolume(String volume) { this.volume = volume; } public String getIssue() { return issue; } public void setIssue(String issue) { this.issue = issue; } public List<String> getKeywords() { return keywords; } public void setKeywords(List<String> keywords) { this.keywords = keywords; } public String getPubDate() { return pubDate; } public void setPubDate(String pubDate) { this.pubDate = pubDate; } public String getReceivedDate() { return receivedDate; } public void setReceivedDate(String receivedDate) { this.receivedDate = receivedDate; } public String getRevisedDate() { return revisedDate; } public void setRevisedDate(String revisedDate) { this.revisedDate = revisedDate; } public String getAcceptedDate() { return acceptedDate; } public void setAcceptedDate(String acceptedDate) { this.acceptedDate = acceptedDate; } public List<ArticleMeta> getReferences() { return references; } public void setReferences(List<ArticleMeta> references) { this.references = references; } private static String extractXPathValue(Document nlm, String xpath) throws JDOMException { XPath xPath = XPath.newInstance(xpath); String res = xPath.valueOf(nlm); if (res != null) { res = res.trim(); } return res; } private static String extractDateValue(Document nlm, String xpath) throws JDOMException { String pubYear = extractXPathValue(nlm, xpath + "/year"); String pubMonth = extractXPathValue(nlm, xpath + "/month"); String pubDay = extractXPathValue(nlm, xpath + "/day"); String pubDate = pubYear; if (pubYear != null && !pubYear.isEmpty() && pubMonth != null && !pubMonth.isEmpty()) { pubDate += "-"; pubDate += pubMonth; if (pubDay != null && !pubDay.isEmpty()) { pubDate += "-"; pubDate += pubDay; } } return pubDate; } private static Map<String, String> extractAffiliations(Document nlm, String xpath) throws JDOMException { XPath xPath = XPath.newInstance(xpath); List<Element> nodes = xPath.selectNodes(nlm); Map<String, String> affMap = new HashMap<String, String>(); for (Element node : nodes) { String affId = node.getAttributeValue("id"); affMap.put(affId, node.getValue().trim().replaceFirst(affId, "").trim()); } return affMap; } private static List<ContributorMeta> extractContributorMeta(Document nlm, String xpath, Map<String, String> affiliations) throws JDOMException { XPath xPath = XPath.newInstance(xpath); List<Element> nodes = xPath.selectNodes(nlm); List<ContributorMeta> authors = new ArrayList<ContributorMeta>(); for (Element node : nodes) { Element nameEl = node.getChild("name"); String name; if (nameEl != null) { name = nameEl.getChildText("surname")+", "+nameEl.getChildText("given-names"); } else { name = node.getChildText("string-name"); } log.debug("Got author name: " + name); ContributorMeta author = new ContributorMeta(name); if (affiliations != null) { List xrefs = node.getChildren("xref"); for (Object xref : xrefs) { Element xrefEl = (Element) xref; String xrefType = xrefEl.getAttributeValue("ref-type"); String xrefId = xrefEl.getAttributeValue("rid"); if ("aff".equals(xrefType) && xrefId != null && affiliations.get(xrefId) != null) { log.debug("Got author affiliation: " + affiliations.get(xrefId)); author.addAffiliations(affiliations.get(xrefId)); } } } List<Element> emails = node.getChildren("email"); for (Element email : emails) { log.debug("Got author email: " + email); author.addEmail(email.getText()); } authors.add(author); } return authors; } private static List<ArticleMeta> extractReferences(Document nlm, String xpath) throws JDOMException { XPath xPath = XPath.newInstance(xpath); List<Element> nodes = xPath.selectNodes(nlm); List<ArticleMeta> references = new ArrayList<ArticleMeta>(); for (Element node : nodes) { ArticleMeta reference = new ArticleMeta(); reference.setAbstractText(node.getValue()); reference.setTitle(node.getChildText("article-title")); reference.setPublisher(node.getChildText("publisher-name")); reference.setPublisherLoc(node.getChildText("publisher-loc")); reference.setPubDate(node.getChildText("year")); reference.setFpage(node.getChildText("fpage")); reference.setLpage(node.getChildText("lpage")); reference.setJournalTitle(node.getChildText("source")); reference.setVolume(node.getChildText("volume")); reference.setIssue(node.getChildText("issue")); List<Element> authorNodes = node.getChildren("string-name"); List<ContributorMeta> authors = new ArrayList<ContributorMeta>(); for (Element authorNode : authorNodes) { ContributorMeta author = new ContributorMeta(); author.setGivennames(authorNode.getChildText("given-names")); author.setSurname(authorNode.getChildText("surname")); authors.add(author); } reference.setAuthors(authors); references.add(reference); } return references; } public static ArticleMeta extractNLM(Document nlm) { log.debug("Starting extraction from document..."); try { ArticleMeta res = new ArticleMeta(); res.setJournalTitle(extractXPathValue(nlm, "/article/front//journal-title")); log.debug("Got journal title: " + res.getJournalTitle()); res.setJournalISSN(extractXPathValue(nlm, "/article/front//journal-meta/issn[@pub-type='ppub']")); log.debug("Got journal ISSN: " + res.getJournalISSN()); res.setPublisher(extractXPathValue(nlm, "/article/front//publisher-name")); log.debug("Got publisher name: " + res.getPublisher()); res.setTitle(extractXPathValue(nlm, "/article/front//article-title")); log.debug("Got title from xpath: " + res.getTitle()); res.setDoi(extractXPathValue(nlm, "/article/front//article-id[@pub-id-type='doi']")); log.debug("Got doi from xpath: " + res.getDoi()); res.setUrn(extractXPathValue(nlm, "/article/front//article-id[@pub-id-type='urn']")); log.debug("Got urn: " + res.getUrn()); res.setAbstractText(extractXPathValue(nlm, "/article/front//abstract")); log.debug("Got abstract: " + res.getAbstractText()); //front and last page: res.setFpage(extractXPathValue(nlm, "/article/front/article-meta/fpage")); res.setLpage(extractXPathValue(nlm, "/article/front/article-meta/lpage")); res.setVolume(extractXPathValue(nlm, "/article/front/article-meta/volume")); res.setIssue(extractXPathValue(nlm, "/article/front/article-meta/issue")); Map<String, String> affiliations = extractAffiliations(nlm, "//aff"); res.setAuthors(extractContributorMeta(nlm, "//contrib[@contrib-type='author']", affiliations)); res.setEditors(extractContributorMeta(nlm, "//contrib[@contrib-type='editor']", null)); res.setPubDate(extractDateValue(nlm, "//pub-date")); res.setReceivedDate(extractDateValue(nlm, "//history/date[@date-type='received']")); res.setRevisedDate(extractDateValue(nlm, "//history/date[@date-type='revised']")); res.setAcceptedDate(extractDateValue(nlm, "//history/date[@date-type='accepted']")); XPath xPath = XPath.newInstance("//kwd"); List<String> kwds = new ArrayList<String>(); for (Object e : xPath.selectNodes(nlm)) { kwds.add(((Element) e).getTextTrim()); } res.setKeywords(kwds); res.setReferences(extractReferences(nlm, "//ref/mixed-citation")); return res; } catch (JDOMException ex) { log.error("Unexpected exception while working with xpath", ex); throw new RuntimeException(ex); } } public static class ContributorMeta { private String name; private String givennames; private String surname; private List<String> affiliations = new ArrayList<String>(); private List<String> emails = new ArrayList<String>(); public ContributorMeta() { } public ContributorMeta(String name) { this.name = name; } public String getName() { if (name == null) { if (givennames == null) { return surname; } else if (surname == null) { return givennames; } else { return surname + ", " + givennames; } } return name; } public String getGivennames() { return givennames; } public void setGivennames(String givennames) { this.givennames = givennames; } public String getSurname() { return surname; } public void setSurname(String surname) { this.surname = surname; } public void setName(String name) { this.name = name; } public List<String> getAffiliations() { return affiliations; } public void setAffiliations(List<String> affiliations) { this.affiliations = affiliations; } public void addAffiliations(String affiliation) { affiliations.add(affiliation); } public List<String> getEmails() { return emails; } public void setEmails(List<String> emails) { this.emails = emails; } public void addEmail(String email) { emails.add(email); } } }
15,306
31.023013
148
java
CERMINE
CERMINE-master/cermine-web/src/main/java/pl/edu/icm/cermine/service/CermineExtractorService.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.service; import java.io.InputStream; import pl.edu.icm.cermine.exception.AnalysisException; /** * Abstraction of the service used to extract metadata from submitted files. * Service is responsible for extraction and proper scheduling and resource * allocation. * * @author Aleksander Nowinski (a.nowinski@icm.edu.pl) */ public interface CermineExtractorService { /** * Method to extract metadata from the given pdf file. File is represented * as a InputStream, which will be passed to the extractor itself. * * @param ii input stream * @return result of the extraction, including basic request stats. * @throws AnalysisException AnalysisException * @throws ServiceException ServiceException */ ExtractionResult extractNLM(InputStream ii) throws AnalysisException, ServiceException; long initExtractionTask(byte[] pdf, String fileName); }
1,664
35.195652
91
java
CERMINE
CERMINE-master/cermine-web/src/main/java/pl/edu/icm/cermine/service/CermineExtractorServiceImpl.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.service; import java.io.ByteArrayInputStream; import java.io.InputStream; import java.util.ArrayList; import java.util.Date; import java.util.List; import java.util.concurrent.*; import javax.annotation.PostConstruct; import org.jdom.Document; import org.jdom.Element; import org.jdom.output.Format; import org.jdom.output.XMLOutputter; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Component; import pl.edu.icm.cermine.ContentExtractor; import pl.edu.icm.cermine.content.transformers.NLMToHTMLWriter; import pl.edu.icm.cermine.exception.AnalysisException; /** * @author Aleksander Nowinski (a.nowinski@icm.edu.pl) */ @Component public class CermineExtractorServiceImpl implements CermineExtractorService { int threadPoolSize = 4; int maxQueueForBatch = 0; Logger log = LoggerFactory.getLogger(CermineExtractorServiceImpl.class); List<ContentExtractor> extractors; ExecutorService processingExecutor; ExecutorService batchProcessingExecutor; @Autowired TaskManager taskManager; public CermineExtractorServiceImpl() { } @PostConstruct public void init() { try { processingExecutor = Executors.newFixedThreadPool(threadPoolSize); ArrayBlockingQueue<Runnable> q; if (maxQueueForBatch > 0) { q = new ArrayBlockingQueue<Runnable>(maxQueueForBatch); } else { q = new ArrayBlockingQueue<Runnable>(100000); } batchProcessingExecutor = new ThreadPoolExecutor(threadPoolSize, threadPoolSize, 1, TimeUnit.DAYS, q); extractors = new ArrayList<ContentExtractor>(); for (int i = 0; i < threadPoolSize; i++) { extractors.add(new ContentExtractor()); } } catch (Exception ex) { log.error("Failed to init content extractor", ex); throw new RuntimeException(ex); } } public int getThreadPoolSize() { return threadPoolSize; } public void setThreadPoolSize(int threadPoolSize) { this.threadPoolSize = threadPoolSize; } public int getMaxQueueForBatch() { return maxQueueForBatch; } public void setMaxQueueForBatch(int maxQueueForBatch) { this.maxQueueForBatch = maxQueueForBatch; } @Override public ExtractionResult extractNLM(InputStream is) throws AnalysisException, ServiceException { log.debug("Starting extractNLM task..."); ExtractionResult res = new ExtractionResult(); res.setSubmit(new Date()); log.debug("submitting extractNLM task..."); try { Future<ExtractionResult> future = batchProcessingExecutor.submit(new SimpleExtractionCallable(is, res)); Thread.yield(); log.debug("waiting for extractNLM task..."); res = future.get(); } catch (RejectedExecutionException rje) { throw new ServiceException("Queue size exceeded.", rje); } catch (Exception ex) { log.error("Exception while executing extraction task...", ex); throw new RuntimeException(ex); } log.debug("finished extractNLM task..."); return res; } @Override public long initExtractionTask(byte[] pdf, String fileName) { ExtractionTask task = new ExtractionTask(); task.setPdf(pdf); task.setFileName(fileName); task.setCreationDate(new Date()); task.setStatus(ExtractionTask.TaskStatus.CREATED); long id = taskManager.registerTask(task); //now process the task... task.setStatus(ExtractionTask.TaskStatus.QUEUED); processingExecutor.submit(new ExtractingTaskExecution(task)); return id; } protected ContentExtractor obtainExtractor() { log.debug("Obtaining extractor from the pool"); ContentExtractor res = null; try { synchronized (extractors) { while (extractors.isEmpty()) { log.debug("Extractor pool is empty, going to sleep..."); extractors.wait(); } res = extractors.remove(0); } return res; } catch (InterruptedException ire) { log.error("Unexpected exception while waiting for extractor...", ire); throw new RuntimeException(ire); } } protected void returnExtractor(ContentExtractor e) { log.debug("Returning extractor to the pool..."); synchronized (extractors) { try { e = new ContentExtractor(); extractors.add(e); } catch (AnalysisException ex) { throw new RuntimeException("Cannot create extractor!", ex); } extractors.notify(); } } /** * Method to perform real extraction. * * @param result * @param input * @return extraction results */ private ExtractionResult performExtraction(ExtractionResult result, InputStream input) { ContentExtractor e = null; try { e = obtainExtractor(); result.processingStart = new Date(); log.debug("Starting extraction on the input stream..."); e.setPDF(input); Element resEl = e.getContentAsNLM(); log.debug("Extraction ok.."); XMLOutputter outputter = new XMLOutputter(Format.getPrettyFormat()); Document doc = new Document(resEl); String res = outputter.outputString(doc); result.setNlm(res); String html = new NLMToHTMLWriter().write(resEl); result.setHtml(html); log.debug("Article meta extraction start:"); result.setMeta(ArticleMeta.extractNLM(doc)); log.debug("Article meta extraction succeeded"); result.setSucceeded(true); } catch (Exception anal) { log.debug("Exception from analysis: ", anal); result.setError(anal); result.setSucceeded(false); } finally { if (e != null) { returnExtractor(e); } result.setProcessingEnd(new Date()); } return result; } private class ExtractingTaskExecution implements Runnable { ExtractionTask task; public ExtractingTaskExecution(ExtractionTask task) { this.task = task; } @Override public void run() { log.debug("Starting processing task: " + task.getId()); task.setStatus(ExtractionTask.TaskStatus.PROCESSING); ExtractionResult result = new ExtractionResult(); result.setProcessingStart(new Date()); result.setSubmit(task.getCreationDate()); log.debug("Running extraction: " + task.getId()); performExtraction(result, new ByteArrayInputStream(task.getPdf())); task.setResult(result); log.debug("Processing finished: " + task.getId()); if (result.isSucceeded()) { task.setStatus(ExtractionTask.TaskStatus.FINISHED); } else { task.setStatus(ExtractionTask.TaskStatus.FAILED); } task.setPdf(null);//clean up memory, we will overflow after few request without it... log.debug("finishing task: " + task.getId()); } } private class SimpleExtractionCallable implements Callable<ExtractionResult> { public SimpleExtractionCallable(InputStream input, ExtractionResult result) { this.input = input; this.result = result; } InputStream input; ExtractionResult result; @Override public ExtractionResult call() { return performExtraction(result, input); } } }
8,741
34.392713
116
java
CERMINE
CERMINE-master/cermine-web/src/main/java/pl/edu/icm/cermine/service/NoSuchTaskException.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.service; /** * @author Aleksander Nowinski (a.nowinski@icm.edu.pl) */ public class NoSuchTaskException extends Exception { long taskId; public NoSuchTaskException(long taskId) { super(String.format("Task %d is not registered.", taskId)); this.taskId = taskId; } }
1,061
31.181818
78
java
CERMINE
CERMINE-master/cermine-web/src/main/java/pl/edu/icm/cermine/service/ServiceException.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.service; /** * @author Aleksander Nowinski (a.nowinski@icm.edu.pl) */ public class ServiceException extends Exception { /** * Creates a new instance of * <code>ServiceException</code> without detail message. */ public ServiceException() { } /** * Constructs an instance of * <code>ServiceException</code> with the specified detail message. * * @param msg the detail message. */ public ServiceException(String msg) { super(msg); } public ServiceException(String msg, Throwable throwable) { super(msg, throwable); } }
1,378
28.340426
78
java
CERMINE
CERMINE-master/cermine-web/src/main/java/pl/edu/icm/cermine/service/TaskManagerImpl.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.service; import java.util.*; import org.springframework.context.annotation.Scope; import org.springframework.stereotype.Service; /** * @author Aleksander Nowinski (a.nowinski@icm.edu.pl) */ @Service @Scope(value = "session") public class TaskManagerImpl implements TaskManager { private static final Random random = new Random(); Map<Long, ExtractionTask> tasks = new HashMap<Long, ExtractionTask>(); protected long newId() { long id = random.nextLong(); while (id < 0 || tasks.containsKey(id)) { id = random.nextLong(); } return id; } @Override public long registerTask(ExtractionTask task) { if (task.getId() == 0) { task.setId(newId()); } tasks.put(task.getId(), task); return task.getId(); } @Override public ExtractionTask getTask(long id) throws NoSuchTaskException { ExtractionTask t = tasks.get(id); if (t == null) { throw new NoSuchTaskException(id); } return t; } @Override public List<ExtractionTask> taskList() { List<ExtractionTask> res = new ArrayList<ExtractionTask>(); for (Map.Entry<Long, ExtractionTask> entries : tasks.entrySet()) { res.add(entries.getValue()); } Collections.sort(res, new Comparator<ExtractionTask>() { @Override public int compare(ExtractionTask t, ExtractionTask t1) { return t.getCreationDate().compareTo(t1.getCreationDate()); } }); return res; } public void deleteFinishedBefore(Date before) { List<Long> toRemove = new ArrayList<Long>(); for (Map.Entry<Long, ExtractionTask> entry : tasks.entrySet()) { if (entry.getValue().getStatus() == ExtractionTask.TaskStatus.FINISHED && entry.getValue().getResult().getProcessingEnd().before(before)) { toRemove.add(entry.getKey()); } } for (Long id : toRemove) { tasks.remove(id); } } @Override public String getProperFilename(String filename) { String fbase = filename; if (fbase == null || fbase.isEmpty()) { fbase = "input.pdf"; } boolean ok = true; for (Map.Entry<Long, ExtractionTask> entry : tasks.entrySet()) { if (fbase.equals(entry.getValue().getFileName())) { ok = false; break; } } int suffix = 1; String fname = fbase; while (!ok) { ok = true; fname = fbase + "#" + suffix; for (Map.Entry<Long, ExtractionTask> entry : tasks.entrySet()) { if (fname.equals(entry.getValue().getFileName())) { ok = false; break; } } suffix++; } return fname; } }
3,732
30.369748
88
java
CERMINE
CERMINE-master/cermine-web/src/main/java/pl/edu/icm/cermine/service/ExtractionResult.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.service; import java.util.Date; import org.slf4j.Logger; import org.slf4j.LoggerFactory; /** * @author Aleksander Nowinski (a.nowinski@icm.edu.pl) */ public class ExtractionResult { Logger log = LoggerFactory.getLogger(ExtractionResult.class); String requestMD5; Date submit, processingStart, processingEnd; String nlm; String dublinCore; ArticleMeta meta; String html; boolean succeeded; Throwable error; public ExtractionResult() { } public String getRequestMD5() { return requestMD5; } public void setRequestMD5(String requestMD5) { this.requestMD5 = requestMD5; } public Date getSubmit() { return submit; } public void setSubmit(Date submit) { this.submit = submit; } public Date getProcessingStart() { return processingStart; } public void setProcessingStart(Date processingStart) { this.processingStart = processingStart; } public Date getProcessingEnd() { return processingEnd; } public void setProcessingEnd(Date processingEnd) { this.processingEnd = processingEnd; } public String getNlm() { return nlm; } public void setNlm(String nlm) { this.nlm = nlm; } public String getDublinCore() { return dublinCore; } public void setDublinCore(String dublinCore) { this.dublinCore = dublinCore; } public ArticleMeta getMeta() { return meta; } public void setMeta(ArticleMeta meta) { this.meta = meta; } public String getHtml() { return html; } public void setHtml(String html) { this.html = html; } public boolean isSucceeded() { return succeeded; } public void setSucceeded(boolean succeeded) { this.succeeded = succeeded; } public Throwable getError() { return error; } public void setError(Throwable error) { this.error = error; } public double getQueueTimeSec() { return (processingStart.getTime() - submit.getTime()) / 1000.; } public double getProcessingTimeSec() { return (processingEnd.getTime() - processingStart.getTime()) / 1000.; } public String getErrorMessage() { String res; if (error != null) { res = error.getMessage(); if(res==null || res.isEmpty()) { res = "Exception is: "+error.getClass().toString(); } } else { res = "Unknown error"; log.warn("Unexpected question for error message while no exception. Wazzup?"); } return res; } }
3,467
22.917241
90
java
CERMINE
CERMINE-master/cermine-web/src/main/java/pl/edu/icm/cermine/service/TaskManager.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.service; import java.util.List; /** * @author Aleksander Nowinski (a.nowinski@icm.edu.pl) */ public interface TaskManager { ExtractionTask getTask(long id) throws NoSuchTaskException; long registerTask(ExtractionTask task); List<ExtractionTask> taskList(); String getProperFilename(String filename); }
1,099
28.72973
78
java
CERMINE
CERMINE-master/cermine-web/src/main/java/pl/edu/icm/cermine/service/ExtractionTask.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.service; import java.util.Date; /** * @author Aleksander Nowinski (a.nowinski@icm.edu.pl) */ public class ExtractionTask { public static enum TaskStatus { CREATED("queue", "SUBMITTED"), QUEUED("queue", "QUEUED"), PROCESSING("processing", "PROCESSING"), FINISHED("success", "SUCCESS", true), FAILED("failure", "FAILURE", true); String css; String text; boolean finalState; TaskStatus(String css, String text) { this(css, text, false); } TaskStatus(String css, String text, boolean f) { this.css = css; this.text = text; finalState = f; } public String getCss() { return css; } public String getText() { return text; } public boolean isFinalState() { return finalState; } } private long id; byte[] pdf; String fileName; String md5Sum; private TaskStatus status; private Date creationDate; private String clientAddress; private ExtractionResult result; public long getId() { return id; } public void setId(long id) { this.id = id; } public byte[] getPdf() { return pdf; } public void setPdf(byte[] pdf) { this.pdf = pdf; } public String getMd5Sum() { return md5Sum; } public void setMd5Sum(String md5Sum) { this.md5Sum = md5Sum; } public TaskStatus getStatus() { return status; } public void setStatus(TaskStatus status) { this.status = status; } public Date getCreationDate() { return creationDate; } public void setCreationDate(Date creationDate) { this.creationDate = creationDate; } public String getClientAddress() { return clientAddress; } public void setClientAddress(String clientAddress) { this.clientAddress = clientAddress; } public ExtractionResult getResult() { return result; } public void setResult(ExtractionResult result) { this.result = result; } public String getFileName() { return fileName; } public void setFileName(String fileName) { this.fileName = fileName; } public boolean isFinished() { return status.isFinalState(); } public boolean isSucceeded() { return isFinished() && status!=TaskStatus.FAILED; } public boolean isFailed() { return status==TaskStatus.FAILED; } }
3,409
21.434211
78
java
CERMINE
CERMINE-master/cermine-web/src/main/java/pl/edu/icm/cermine/web/controller/SimpleCORSFilter.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.web.controller; import java.io.IOException; import javax.servlet.Filter; import javax.servlet.FilterChain; import javax.servlet.FilterConfig; import javax.servlet.ServletException; import javax.servlet.ServletRequest; import javax.servlet.ServletResponse; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import org.springframework.stereotype.Component; /** * A simple <a href="https://en.wikipedia.org/wiki/Cross-origin_resource_sharing">CORS</a> * implementation in a filter. * * @author Aleksander Nowinski (a.nowinski@icm.edu.pl) */ @Component public class SimpleCORSFilter implements Filter { @Override public void doFilter(ServletRequest req, ServletResponse res, FilterChain chain) throws IOException, ServletException { if (((HttpServletRequest) req).getHeader("Origin") != null) { HttpServletResponse response = (HttpServletResponse) res; response.setHeader("Access-Control-Allow-Origin", "*"); response.setHeader("Access-Control-Allow-Methods", "POST, GET, OPTIONS, DELETE"); response.setHeader("Access-Control-Max-Age", "3600"); response.setHeader("Access-Control-Allow-Headers", "x-requested-with"); } chain.doFilter(req, res); } @Override public void init(FilterConfig filterConfig) { } @Override public void destroy() { } }
2,177
34.704918
123
java
CERMINE
CERMINE-master/cermine-web/src/main/java/pl/edu/icm/cermine/web/controller/DummyValidator.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.web.controller; import org.springframework.validation.Errors; import org.springframework.validation.Validator; /** * @author Aleksander Nowinski (a.nowinski@icm.edu.pl) */ public class DummyValidator implements Validator { @Override public boolean supports(Class<?> clazz) { return false; } @Override public void validate(Object target, Errors errors) { } }
1,160
29.552632
78
java
CERMINE
CERMINE-master/cermine-web/src/main/java/pl/edu/icm/cermine/web/controller/CermineController.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.web.controller; import java.io.ByteArrayInputStream; import java.io.IOException; import java.io.InputStream; import java.io.OutputStream; import static java.util.Collections.singletonList; import java.util.HashMap; import java.util.List; import java.util.Map; import java.util.logging.Level; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import org.apache.commons.io.IOUtils; import org.apache.commons.lang.StringEscapeUtils; import org.jdom.Element; import org.jdom.output.Format; import org.jdom.output.XMLOutputter; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.http.HttpHeaders; import org.springframework.http.HttpStatus; import org.springframework.http.MediaType; import org.springframework.http.ResponseEntity; import org.springframework.ui.Model; import org.springframework.web.bind.annotation.*; import org.springframework.web.multipart.MultipartFile; import org.springframework.web.servlet.ModelAndView; import pl.edu.icm.cermine.bibref.CRFBibReferenceParser; import pl.edu.icm.cermine.bibref.model.BibEntry; import pl.edu.icm.cermine.bibref.transformers.BibEntryToNLMConverter; import pl.edu.icm.cermine.metadata.affiliation.CRFAffiliationParser; import pl.edu.icm.cermine.service.*; /** * @author bart * @author Aleksander Nowinski (a.nowinski@icm.edu.pl) */ @org.springframework.stereotype.Controller public class CermineController { @Autowired CermineExtractorService extractorService; @Autowired TaskManager taskManager; Logger logger = LoggerFactory.getLogger(CermineController.class); @RequestMapping(value = "/index.html") public String showHome(Model model) { return "home"; } @RequestMapping(value = "/about.html") public String showAbout(Model model) { return "about"; } @RequestMapping(value = "/download.html") public ResponseEntity<String> downloadXML(@RequestParam("task") long taskId, @RequestParam("type") String resultType, Model model) throws NoSuchTaskException { ExtractionTask task = taskManager.getTask(taskId); if ("nlm".equals(resultType)) { String nlm = task.getResult().getNlm(); HttpHeaders responseHeaders = new HttpHeaders(); responseHeaders.set("Content-Type", "application/xml;charset=utf-8"); return new ResponseEntity<String>(nlm, responseHeaders, HttpStatus.OK); } else { throw new RuntimeException("Unknown request type: " + resultType); } } @RequestMapping(value = "/examplepdf.html", method = RequestMethod.GET) public void getExamplePDF(@RequestParam("file") String filename, HttpServletRequest request, HttpServletResponse response) { InputStream in = null; OutputStream out = null; try { if (!filename.matches("^example\\d+\\.pdf$")) { throw new RuntimeException("No such example file!"); } response.setContentType("application/pdf"); in = CermineController.class.getResourceAsStream("/examples/"+filename); if (in == null) { throw new RuntimeException("No such example file!"); } out = response.getOutputStream(); byte[] buf = new byte[1024]; int len; while ((len = in.read(buf)) > 0) { out.write(buf, 0, len); } } catch (IOException ex) { throw new RuntimeException(ex); } finally { try { if (in != null) { in.close(); } if (out != null) { out.close(); } } catch (IOException ex) { } } } @RequestMapping(value = "/uploadexample.do", method = RequestMethod.GET) public String uploadExampleFileStream(@RequestParam("file") String filename, HttpServletRequest request, Model model) { if (!filename.matches("^example\\d+\\.pdf$")) { throw new RuntimeException("No such example file!"); } logger.info("Got an upload request."); try { InputStream in = CermineController.class.getResourceAsStream("/examples/"+filename); if (in == null) { throw new RuntimeException("No such example file!"); } byte[] content = IOUtils.toByteArray(in); if (content.length == 0) { model.addAttribute("warning", "An empty or no file sent."); return "home"; } logger.debug("Original filename is: " + filename); filename = taskManager.getProperFilename(filename); logger.debug("Created filename: " + filename); long taskId = extractorService.initExtractionTask(content, filename); logger.debug("Task manager is: " + taskManager); return "redirect:/task.html?task=" + taskId; } catch (Exception ex) { throw new RuntimeException(ex); } } @RequestMapping(value = "/upload.do", method = RequestMethod.POST) public String uploadFileStream(@RequestParam("files") MultipartFile file, HttpServletRequest request, Model model) { logger.info("Got an upload request."); try { byte[] content = file.getBytes(); if (content.length == 0) { model.addAttribute("warning", "An empty or no file sent."); return "home"; } String filename = file.getOriginalFilename(); logger.debug("Original filename is: " + filename); filename = taskManager.getProperFilename(filename); logger.debug("Created filename: " + filename); long taskId = extractorService.initExtractionTask(content, filename); logger.debug("Task manager is: " + taskManager); return "redirect:/task.html?task=" + taskId; } catch (Exception ex) { throw new RuntimeException(ex); } } @RequestMapping(value = "/extract.do", method = RequestMethod.POST) public ResponseEntity<String> extractSync(@RequestBody byte[] content, HttpServletRequest request, Model model) { try { logger.debug("content length: {}", content.length); HttpHeaders responseHeaders = new HttpHeaders(); responseHeaders.setContentType(MediaType.APPLICATION_XML); ExtractionResult result = extractorService.extractNLM(new ByteArrayInputStream(content)); String nlm = result.getNlm(); return new ResponseEntity<String>(nlm, responseHeaders, HttpStatus.OK); } catch (Exception ex) { java.util.logging.Logger.getLogger(CermineController.class.getName()).log(Level.SEVERE, null, ex); return new ResponseEntity<String>("Exception: " + ex.getMessage(), null, HttpStatus.INTERNAL_SERVER_ERROR); } } @RequestMapping(value = "/parse.do", method = RequestMethod.POST) public ResponseEntity<String> parseSync(HttpServletRequest request, Model model) { try { String refText = request.getParameter("reference"); if (refText == null) { refText = request.getParameter("ref"); } String affText = request.getParameter("affiliation"); if (affText == null) { affText = request.getParameter("aff"); } if (refText == null && affText == null) { return new ResponseEntity<String>( "Exception: \"reference\" or \"affiliation\" parameter has to be passed!\n", null, HttpStatus.INTERNAL_SERVER_ERROR); } HttpHeaders responseHeaders = new HttpHeaders(); String response; if (refText != null) { String format = request.getParameter("format"); if (format == null) { format = "bibtex"; } format = format.toLowerCase(); if (!format.equals("nlm") && !format.equals("bibtex")) { return new ResponseEntity<String>( "Exception: format must be \"bibtex\" or \"nlm\"!\n", null, HttpStatus.INTERNAL_SERVER_ERROR); } CRFBibReferenceParser parser = CRFBibReferenceParser.getInstance(); BibEntry reference = parser.parseBibReference(refText); if (format.equals("bibtex")) { responseHeaders.setContentType(MediaType.TEXT_PLAIN); response = reference.toBibTeX(); } else { responseHeaders.setContentType(MediaType.APPLICATION_XML); BibEntryToNLMConverter converter = new BibEntryToNLMConverter(); Element element = converter.convert(reference); XMLOutputter outputter = new XMLOutputter(Format.getPrettyFormat()); response = outputter.outputString(element); } } else { responseHeaders.setContentType(MediaType.APPLICATION_XML); CRFAffiliationParser parser = new CRFAffiliationParser(); Element parsedAff = parser.parse(affText); XMLOutputter outputter = new XMLOutputter(Format.getPrettyFormat()); response = outputter.outputString(parsedAff); } return new ResponseEntity<String>(response+"\n", responseHeaders, HttpStatus.OK); } catch (Exception ex) { java.util.logging.Logger.getLogger(CermineController.class.getName()).log(Level.SEVERE, null, ex); return new ResponseEntity<String>("Exception: " + ex.getMessage(), null, HttpStatus.INTERNAL_SERVER_ERROR); } } @ExceptionHandler(value = NoSuchTaskException.class) public ModelAndView taskNotFoundHandler(NoSuchTaskException nste) { return new ModelAndView("error", "errorMessage", nste.getMessage()); } @RequestMapping(value = "/task.html", method = RequestMethod.GET) public ModelAndView showTask(@RequestParam("task") long id) throws NoSuchTaskException { ExtractionTask task = taskManager.getTask(id); HashMap<String, Object> model = new HashMap<String, Object>(); model.put("task", task); if (task.isFinished()) { model.put("result", task.getResult()); String nlmHtml = StringEscapeUtils.escapeHtml(task.getResult().getNlm()); model.put("nlm", nlmHtml); model.put("meta", task.getResult().getMeta()); model.put("html", task.getResult().getHtml()); } return new ModelAndView("task", model); } @RequestMapping(value = "/tasks.html") public ModelAndView showTasks() { return new ModelAndView("tasks", "tasks", taskManager.taskList()); } private static ResponseEntity<List<Map<String, Object>>> wrapResponse(Map<String, Object> rBody) { HttpHeaders headers = new HttpHeaders(); headers.setContentType(MediaType.TEXT_PLAIN); return new ResponseEntity<List<Map<String, Object>>>(singletonList(rBody), headers, HttpStatus.OK); } private static Map<String, Object> fileDetails(MultipartFile file, int size) { Map<String, Object> rBody = new HashMap<String, Object>(); rBody.put("name", file.getOriginalFilename()); rBody.put("size", size); return rBody; } public CermineExtractorService getExtractorService() { return extractorService; } public void setExtractorService(CermineExtractorService extractorService) { this.extractorService = extractorService; } public TaskManager getTaskManager() { return taskManager; } public void setTaskManager(TaskManager taskManager) { this.taskManager = taskManager; } }
13,037
40.788462
129
java
CERMINE
CERMINE-master/cermine-impl/src/test/java/pl/edu/icm/cermine/StandardDataExamples.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.StringReader; import java.util.ArrayList; import java.util.Arrays; import java.util.List; import org.jdom.Document; import org.jdom.Element; import org.jdom.JDOMException; import org.jdom.input.SAXBuilder; import pl.edu.icm.cermine.bibref.model.BibEntry; import pl.edu.icm.cermine.bibref.model.BibEntryFieldType; import pl.edu.icm.cermine.bibref.model.BibEntryType; /** * @author Dominika Tkaczyk (d.tkaczyk@icm.edu.pl) */ public class StandardDataExamples { public static List<Element> getReferencesAsNLMElement() throws IOException, JDOMException { String[] references = { "<mixed-citation>[6] <string-name><given-names>W.</given-names> <surname>Hoeffding</surname></string-name>, <article-title>Probability inequalities for sums of bounded random variables</article-title>, <source>J. Amer. Statist. Assoc.</source> <volume>58</volume> (<year>1963</year>) <fpage>13</fpage>-<lpage>30</lpage>.</mixed-citation>", "<mixed-citation><string-name><given-names>S.J.</given-names> <surname>Bean</surname></string-name> et <string-name><given-names>C.P.</given-names> <surname>Tsakas</surname></string-name> (<year>1980</year>). - <article-title>Developments in non-parametric density estimation</article-title>. <source>Inter. Stat. Review</source>, <volume>48</volume>, p. <fpage>267</fpage>-<lpage>287</lpage></mixed-citation>", "<mixed-citation>[27] <string-name><given-names>M-Y.</given-names> <surname>Wang</surname></string-name>, <string-name><given-names>X.</given-names> <surname>Wang</surname></string-name> and <string-name><given-names>D.</given-names> <surname>Guo</surname></string-name>, <article-title>A level-set method for structural topology optimization</article-title>. <source>Comput. Methods Appl. Mech. Engrg.</source> <volume>192</volume> (<year>2003</year>) <fpage>227</fpage>–<lpage>246</lpage>.</mixed-citation>", "<mixed-citation>[8] <string-name><given-names>R.</given-names> <surname>Kobayashi</surname></string-name>, <article-title>Einstein-Kähler V metrics on open Satake V -surfaces with isolated quotient singularities</article-title>, <source>Math. Ann.</source> <volume>272</volume> (<year>1985</year>), <fpage>385</fpage>-<lpage>398</lpage>.</mixed-citation>", "<mixed-citation>[15] <string-name><given-names>T.</given-names> <surname>Corvera-Tindel</surname></string-name>, <string-name><given-names>L. V.</given-names> <surname>Doering</surname></string-name>, <string-name><given-names>T.</given-names> <surname>Gomez</surname></string-name>, and <string-name><given-names>K.</given-names> <surname>Dracup</surname></string-name>, \"<article-title>Predictors of noncompliance to exercise training in heart failure</article-title>,\" <source>The Journal of Cardiovascular Nursing</source>, vol. <volume>19</volume>, no. <issue>4</issue>, pp. <fpage>269</fpage>–<lpage>279</lpage>, <year>2004</year>.</mixed-citation>", "<mixed-citation><string-name><surname>Van Heuven</surname> <given-names>WJB</given-names></string-name>, <string-name><surname>Dijkstra</surname> <given-names>T.</given-names></string-name> <article-title>Language comprehension in the bilingual brain: fMRI and ERP support for psycholinguistic models</article-title>. <source>Brain Res Rev</source>. <year>2010</year>; <volume>64</volume>(<issue>1</issue>):104 – 22. doi: <pub-id pub-id-type=\"doi\">10.1016/j.brainresrev.2010.03.002</pub-id> PMID: <pub-id pub-id-type=\"pmid\">20227440</pub-id></mixed-citation>" }; SAXBuilder saxBuilder = new SAXBuilder("org.apache.xerces.parsers.SAXParser"); List<Element> elements = new ArrayList<Element>(); for (String reference : references) { StringReader sr = new StringReader(reference); Document dom = saxBuilder.build(sr); Element nlm = dom.getRootElement(); elements.add(nlm); } return elements; } public static List<BibEntry> getReferencesAsBibEntry() { BibEntry[] entries = { new BibEntry(BibEntryType.ARTICLE) .setText("[6] W. Hoeffding, Probability inequalities for sums of bounded random variables, J. Amer. Statist. Assoc. 58 (1963) 13-30.") .addField(BibEntryFieldType.AUTHOR, "Hoeffding, W.", 4, 16) .addField(BibEntryFieldType.TITLE, "Probability inequalities for sums of bounded random variables", 18, 79) .addField(BibEntryFieldType.JOURNAL, "J. Amer. Statist. Assoc.", 81, 105) .addField(BibEntryFieldType.VOLUME, "58", 106, 108) .addField(BibEntryFieldType.YEAR, "1963", 110, 114) .addField(BibEntryFieldType.PAGES, "13--30", 116, 121), new BibEntry(BibEntryType.ARTICLE) .setText("S.J. Bean et C.P. Tsakas (1980). - Developments in non-parametric density estimation. Inter. Stat. Review, 48, p. 267-287") .addField(BibEntryFieldType.AUTHOR, "Bean, S.J.", 0, 9) .addField(BibEntryFieldType.AUTHOR, "Tsakas, C.P.", 13, 24) .addField(BibEntryFieldType.TITLE, "Developments in non-parametric density estimation", 35, 84) .addField(BibEntryFieldType.JOURNAL, "Inter. Stat. Review", 86, 105) .addField(BibEntryFieldType.VOLUME, "48", 107, 109) .addField(BibEntryFieldType.YEAR, "1980", 26, 30) .addField(BibEntryFieldType.PAGES, "267--287", 114, 121), new BibEntry(BibEntryType.ARTICLE) .setText("[27] M-Y. Wang, X. Wang and D. Guo, A level-set method for structural topology optimization. Comput. Methods Appl. Mech. Engrg. 192 (2003) 227–246.") .addField(BibEntryFieldType.AUTHOR, "Wang, M-Y.", 5, 14) .addField(BibEntryFieldType.AUTHOR, "Wang, X.", 16, 23) .addField(BibEntryFieldType.AUTHOR, "Guo, D.", 28, 34) .addField(BibEntryFieldType.TITLE, "A level-set method for structural topology optimization", 36, 91) .addField(BibEntryFieldType.JOURNAL, "Comput. Methods Appl. Mech. Engrg.", 93, 127) .addField(BibEntryFieldType.VOLUME, "192", 128, 131) .addField(BibEntryFieldType.YEAR, "2003", 133, 137) .addField(BibEntryFieldType.PAGES, "227--246", 139, 146), new BibEntry(BibEntryType.ARTICLE) .setText("[8] R. Kobayashi, Einstein-Kähler V metrics on open Satake V -surfaces with isolated quotient singularities, Math. Ann. 272 (1985), 385-398.") .addField(BibEntryFieldType.AUTHOR, "Kobayashi, R.", 4, 16) .addField(BibEntryFieldType.TITLE, "Einstein-Kähler V metrics on open Satake V -surfaces with isolated quotient singularities", 18, 107) .addField(BibEntryFieldType.JOURNAL, "Math. Ann.", 109, 119) .addField(BibEntryFieldType.VOLUME, "272", 120, 123) .addField(BibEntryFieldType.YEAR, "1985", 125, 129) .addField(BibEntryFieldType.PAGES, "385--398", 132, 139), new BibEntry(BibEntryType.ARTICLE) .setText("[15] T. Corvera-Tindel, L. V. Doering, T. Gomez, and K. Dracup, \"Predictors of noncompliance to exercise training in heart failure,\" The Journal of Cardiovascular Nursing, vol. 19, no. 4, pp. 269–279, 2004.") .addField(BibEntryFieldType.AUTHOR, "Corvera-Tindel, T.", 5, 22) .addField(BibEntryFieldType.AUTHOR, "Doering, L. V.", 24, 37) .addField(BibEntryFieldType.AUTHOR, "Gomez, T.", 39, 47) .addField(BibEntryFieldType.AUTHOR, "Dracup, K.", 53, 62) .addField(BibEntryFieldType.TITLE, "Predictors of noncompliance to exercise training in heart failure", 65, 130) .addField(BibEntryFieldType.JOURNAL, "The Journal of Cardiovascular Nursing", 133, 170) .addField(BibEntryFieldType.VOLUME, "19", 177, 179) .addField(BibEntryFieldType.NUMBER, "4", 185, 186) .addField(BibEntryFieldType.PAGES, "269--279", 192, 199) .addField(BibEntryFieldType.YEAR, "2004", 201, 205), new BibEntry(BibEntryType.ARTICLE) .setText("Van Heuven WJB, Dijkstra T. Language comprehension in the bilingual brain: fMRI and ERP support for psycholinguistic models. Brain Res Rev. 2010; 64(1):104 – 22. doi: 10.1016/j.brainresrev.2010.03.002 PMID: 20227440") .addField(BibEntryFieldType.AUTHOR, "Van Heuven, WJB", 0, 14) .addField(BibEntryFieldType.AUTHOR, "Dijkstra, T.", 16, 27) .addField(BibEntryFieldType.DOI, "10.1016/j.brainresrev.2010.03.002", 167, 200) .addField(BibEntryFieldType.JOURNAL, "Brain Res Rev", 125, 138) .addField(BibEntryFieldType.NUMBER, "1", 149, 150) .addField(BibEntryFieldType.TITLE, "Language comprehension in the bilingual brain: fMRI and ERP support for psycholinguistic models", 28, 123) .addField(BibEntryFieldType.VOLUME, "64", 146, 148) .addField(BibEntryFieldType.YEAR, "2010", 140, 144) .addField(BibEntryFieldType.PMID, "20227440", 207, 215) }; return Arrays.asList(entries); } public static List<String> getReferencesAsBibTeX() { String[] entries = { "@article{Hoeffding1963,\n" + "\tauthor = {Hoeffding, W.},\n" + "\tjournal = {J. Amer. Statist. Assoc.},\n" + "\tpages = {13--30},\n" + "\ttitle = {Probability inequalities for sums of bounded random variables},\n" + "\tvolume = {58},\n" + "\tyear = {1963},\n" + "}", "@article{Bean1980,\n" + "\tauthor = {Bean, S.J., Tsakas, C.P.},\n" + "\tjournal = {Inter. Stat. Review},\n" + "\tpages = {267--287},\n" + "\ttitle = {Developments in non-parametric density estimation},\n" + "\tvolume = {48},\n" + "\tyear = {1980},\n" + "}", "@article{Wang2003,\n" + "\tauthor = {Wang, M-Y., Wang, X., Guo, D.},\n" + "\tjournal = {Comput. Methods Appl. Mech. Engrg.},\n" + "\tpages = {227--246},\n" + "\ttitle = {A level-set method for structural topology optimization},\n" + "\tvolume = {192},\n" + "\tyear = {2003},\n" + "}", "@article{Kobayashi1985,\n" + "\tauthor = {Kobayashi, R.},\n" + "\tjournal = {Math. Ann.},\n" + "\tpages = {385--398},\n" + "\ttitle = {Einstein-Kähler V metrics on open Satake V -surfaces with isolated quotient singularities},\n" + "\tvolume = {272},\n" + "\tyear = {1985},\n" + "}", "@article{Corvera2004,\n" + "\tauthor = {Corvera-Tindel, T., Doering, L. V., Gomez, T., Dracup, K.},\n" + "\tjournal = {The Journal of Cardiovascular Nursing},\n" + "\tnumber = {4},\n" + "\tpages = {269--279},\n" + "\ttitle = {Predictors of noncompliance to exercise training in heart failure},\n" + "\tvolume = {19},\n" + "\tyear = {2004},\n" + "}", "@article{VanHeuven2010,\n" + "\tauthor = {Van Heuven, WJB, Dijkstra, T.},\n" + "\tdoi = {10.1016/j.brainresrev.2010.03.002},\n" + "\tjournal = {Brain Res Rev},\n" + "\tnumber = {1},\n" + "\tpmid = {20227440},\n" + "\ttitle = {Language comprehension in the bilingual brain: fMRI and ERP support for psycholinguistic models},\n" + "\tvolume = {64},\n" + "\tyear = {2010},\n" + "}", }; return Arrays.asList(entries); } }
12,883
69.404372
671
java
CERMINE
CERMINE-master/cermine-impl/src/test/java/pl/edu/icm/cermine/CommandLineOptionsParserTest.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 static org.junit.Assert.assertEquals; import static org.junit.Assert.assertFalse; import static org.junit.Assert.assertNull; import static org.junit.Assert.assertTrue; import java.util.Map; import org.apache.commons.cli.ParseException; import org.junit.Test; /** * @author madryk */ public class CommandLineOptionsParserTest { private final CommandLineOptionsParser cmdLineOptionsParser = new CommandLineOptionsParser(); @Test public void parse_NO_PATH() throws ParseException { // execute String error = cmdLineOptionsParser.parse(new String[] {}); // assert assertEquals("\"path\" parameter not specified", error); } @Test(expected = ParseException.class) public void parse_NO_PATH_VALUE() throws ParseException { // execute cmdLineOptionsParser.parse(new String[] {"-path"}); } @Test public void parse_WITH_PATH() throws ParseException { // execute String error = cmdLineOptionsParser.parse(new String[] {"-path", "/path/to/pdfs/folder"}); // assert assertNull(error); assertEquals("/path/to/pdfs/folder", cmdLineOptionsParser.getPath()); Map<String, String> typesAndExtensions = cmdLineOptionsParser.getTypesAndExtensions(); assertEquals(2, typesAndExtensions.size()); assertEquals("cermxml", typesAndExtensions.get("jats")); assertEquals("images", typesAndExtensions.get("images")); assertFalse(cmdLineOptionsParser.override()); assertNull(cmdLineOptionsParser.getTimeout()); assertNull(cmdLineOptionsParser.getConfigurationPath()); assertEquals("cermxml", cmdLineOptionsParser.getNLMExtension()); assertEquals("cermtxt", cmdLineOptionsParser.getTextExtension()); assertFalse(cmdLineOptionsParser.extractStructure()); assertEquals("cxml", cmdLineOptionsParser.getBxExtension()); } @Test public void parse_OVERRIDE_DEFAULTS() throws ParseException { // execute String error = cmdLineOptionsParser.parse(new String[] { "-path", "/path/to/pdfs/folder", "-outputs", "jats,zones,text", "-exts", "xml,data,txt", "-override", "-timeout", "120", "-configuration", "config.properties", "-ext", "xml2", "-str", "-strext", "xml3",}); // assert assertNull(error); assertEquals("/path/to/pdfs/folder", cmdLineOptionsParser.getPath()); Map<String, String> typesAndExtensions = cmdLineOptionsParser.getTypesAndExtensions(); assertEquals(3, typesAndExtensions.size()); assertEquals("xml", typesAndExtensions.get("jats")); assertEquals("data", typesAndExtensions.get("zones")); assertEquals("txt", typesAndExtensions.get("text")); assertTrue(cmdLineOptionsParser.override()); assertEquals(Long.valueOf(120L), cmdLineOptionsParser.getTimeout()); assertEquals("config.properties", cmdLineOptionsParser.getConfigurationPath()); assertEquals("xml2", cmdLineOptionsParser.getNLMExtension()); assertEquals("xml2", cmdLineOptionsParser.getTextExtension()); assertTrue(cmdLineOptionsParser.extractStructure()); assertEquals("xml3", cmdLineOptionsParser.getBxExtension()); } @Test public void parse_INVALID_EXTENSIONS_LIST_SIZE() throws ParseException { // execute String error = cmdLineOptionsParser.parse(new String[] { "-path", "/path/to/pdfs/folder", "-outputs", "jats,zones,trueviz", "-exts", "xml,xml2"}); // assert assertEquals("\"output\" and \"exts\" lists have different lengths", error); } @Test public void parse_UNKNOWN_OUTPUT_TYPE() throws ParseException { // execute String error = cmdLineOptionsParser.parse(new String[] { "-path", "/path/to/pdfs/folder", "-outputs", "jats,unknown,unknown2", "-exts", "xml,xml2,xml3"}); // assert assertEquals("Unknown output types: [unknown, unknown2]", error); } }
5,101
37.360902
98
java
CERMINE
CERMINE-master/cermine-impl/src/test/java/pl/edu/icm/cermine/ContentExtractorTest.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.awt.image.BufferedImage; import java.io.*; import java.net.URISyntaxException; import java.util.ArrayList; import java.util.Collections; import java.util.Comparator; import java.util.List; import javax.imageio.ImageIO; import org.apache.commons.io.IOUtils; import org.custommonkey.xmlunit.Diff; import org.jdom.Document; import org.jdom.Element; import org.jdom.JDOMException; import org.jdom.input.SAXBuilder; import org.jdom.output.Format; import org.jdom.output.XMLOutputter; import static org.junit.Assert.*; import org.junit.Before; import org.junit.Test; import org.xml.sax.SAXException; 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.model.BxImage; import pl.edu.icm.cermine.structure.tools.BxModelUtils; import pl.edu.icm.cermine.structure.transformers.TrueVizToBxDocumentReader; /** * @author Dominika Tkaczyk (d.tkaczyk@icm.edu.pl) */ public class ContentExtractorTest { static final private String TEST_PDF_1 = "/pl/edu/icm/cermine/test1.pdf"; static final private String EXP_STR_1 = "/pl/edu/icm/cermine/test1-structure.xml"; static final private String EXP_STR_GEN_1 = "/pl/edu/icm/cermine/test1-structure-general.xml"; static final private String EXP_STR_SPE_1 = "/pl/edu/icm/cermine/test1-structure-specific.xml"; static final private String EXP_MET_1 = "/pl/edu/icm/cermine/test1-metadata.xml"; static final private String TEST_PDF_2 = "/pl/edu/icm/cermine/test2.pdf"; static final private String EXP_CONT_2 = "/pl/edu/icm/cermine/test2-content.xml"; static final private String EXP_TEXT_2 = "/pl/edu/icm/cermine/test2-fulltext.txt"; static final private String EXP_ZONES_2 = "/pl/edu/icm/cermine/test2-zones.xml"; static final private String TEST_PDF_4 = "/pl/edu/icm/cermine/test4.pdf"; static final private String EXP_CONT_4 = "/pl/edu/icm/cermine/test4-content-images.xml"; static final private String EXP_IMGS_4 = "/pl/edu/icm/cermine/test4-images/"; static final private String TEST_PDF_5 = "/pl/edu/icm/cermine/test5.pdf"; static final private String EXP_CONT_5 = "/pl/edu/icm/cermine/test5-content.xml"; private ContentExtractor extractor; SAXBuilder saxBuilder; @Before public void setUp() throws AnalysisException, IOException { extractor = new ContentExtractor(); saxBuilder = new SAXBuilder("org.apache.xerces.parsers.SAXParser"); } @Test public void getBxDocumentTest() throws IOException, AnalysisException, URISyntaxException, TransformationException { InputStream testStream = ContentExtractorTest.class.getResourceAsStream(TEST_PDF_1); BxDocument testDocument; try { extractor.setPDF(testStream); testDocument = extractor.getBxDocument(); } finally { testStream.close(); } InputStream expStream = ContentExtractorTest.class.getResourceAsStream(EXP_STR_1); TrueVizToBxDocumentReader reader = new TrueVizToBxDocumentReader(); BxDocument expDocument = new BxDocument().setPages(reader.read(new InputStreamReader(expStream, "UTF-8"))); assertTrue(BxModelUtils.areEqual(expDocument, testDocument)); } @Test public void getBxDocumentWithGeneralLabelsTest() throws IOException, AnalysisException, URISyntaxException, TransformationException { InputStream testStream = ContentExtractorTest.class.getResourceAsStream(TEST_PDF_1); BxDocument testDocument; try { extractor.setPDF(testStream); testDocument = extractor.getBxDocumentWithGeneralLabels(); } finally { testStream.close(); } InputStream expStream = ContentExtractorTest.class.getResourceAsStream(EXP_STR_GEN_1); TrueVizToBxDocumentReader reader = new TrueVizToBxDocumentReader(); BxDocument expDocument = new BxDocument().setPages(reader.read(new InputStreamReader(expStream, "UTF-8"))); assertTrue(BxModelUtils.areEqual(expDocument, testDocument)); } @Test public void getBxDocumentWithSpecificLabelsTest() throws IOException, AnalysisException, URISyntaxException, TransformationException { InputStream testStream = ContentExtractorTest.class.getResourceAsStream(TEST_PDF_1); BxDocument testDocument; try { extractor.setPDF(testStream); testDocument = extractor.getBxDocumentWithSpecificLabels(); } finally { testStream.close(); } InputStream expStream = ContentExtractorTest.class.getResourceAsStream(EXP_STR_SPE_1); TrueVizToBxDocumentReader reader = new TrueVizToBxDocumentReader(); BxDocument expDocument = new BxDocument().setPages(reader.read(new InputStreamReader(expStream, "UTF-8"))); assertTrue(BxModelUtils.areEqual(expDocument, testDocument)); } @Test public void textRawFullTextTest() throws AnalysisException, JDOMException, IOException, SAXException { InputStream testStream = ContentExtractorTest.class.getResourceAsStream(TEST_PDF_2); String testContent; try { extractor.setPDF(testStream); testContent = extractor.getRawFullText(); } finally { testStream.close(); } InputStream expStream = ContentExtractorTest.class.getResourceAsStream(EXP_TEXT_2); BufferedReader reader = null; StringBuilder expectedContent = new StringBuilder(); try { reader = new BufferedReader(new InputStreamReader(expStream, "UTF-8")); String line; while ((line = reader.readLine()) != null) { expectedContent.append(line); expectedContent.append("\n"); } } finally { try { expStream.close(); } finally { if (reader != null) { reader.close(); } } } assertEquals(testContent.trim(), expectedContent.toString().trim()); } @Test public void getFullTextWithLabelsTest() throws AnalysisException, IOException, JDOMException, SAXException { InputStream testStream = ContentExtractorTest.class.getResourceAsStream(TEST_PDF_2); Element testContent; try { extractor.setPDF(testStream); testContent = extractor.getLabelledFullText(); } finally { testStream.close(); } InputStream expStream = ContentExtractorTest.class.getResourceAsStream(EXP_ZONES_2); InputStreamReader expReader = null; Document dom; try { expReader = new InputStreamReader(expStream, "UTF-8"); dom = saxBuilder.build(expReader); } finally { expStream.close(); if (expReader != null) { expReader.close(); } } Element expMetadata = dom.getRootElement(); XMLOutputter outputter = new XMLOutputter(Format.getPrettyFormat()); Diff diff = new Diff(outputter.outputString(expMetadata), outputter.outputString(testContent)); assertTrue(diff.similar()); } @Test public void getNLMMetadataTest() throws AnalysisException, IOException, JDOMException, SAXException { InputStream testStream = ContentExtractorTest.class.getResourceAsStream(TEST_PDF_1); Element testMetadata; try { extractor.setPDF(testStream); testMetadata = extractor.getMetadataAsNLM(); } finally { testStream.close(); } InputStream expStream = ContentExtractorTest.class.getResourceAsStream(EXP_MET_1); InputStreamReader expReader = null; Document dom; try { expReader = new InputStreamReader(expStream, "UTF-8"); dom = saxBuilder.build(expReader); } finally { expStream.close(); if (expReader != null) { expReader.close(); } } Element expMetadata = dom.getRootElement(); XMLOutputter outputter = new XMLOutputter(Format.getPrettyFormat()); Diff diff = new Diff(outputter.outputString(expMetadata), outputter.outputString(testMetadata)); assertTrue(diff.similar()); } @Test public void getNLMBodyTest() throws AnalysisException, IOException, JDOMException, SAXException { InputStream testStream = ContentExtractorTest.class.getResourceAsStream(TEST_PDF_2); Element testBody; try { extractor.setPDF(testStream); testBody = extractor.getBodyAsNLM(); } finally { testStream.close(); } InputStream expStream = ContentExtractorTest.class.getResourceAsStream(EXP_CONT_2); InputStreamReader expReader = null; Document dom; try { expReader = new InputStreamReader(expStream, "UTF-8"); dom = saxBuilder.build(expReader); } finally { expStream.close(); if (expReader != null) { expReader.close(); } } Element expMetadata = dom.getRootElement(); Element expContent = expMetadata.getChild("body"); XMLOutputter outputter = new XMLOutputter(Format.getPrettyFormat()); Diff diff = new Diff(outputter.outputString(expContent), outputter.outputString(testBody)); assertTrue(diff.similar()); } @Test public void getNLMReferencesTest() throws AnalysisException, JDOMException, IOException, SAXException { InputStream testStream = ContentExtractorTest.class.getResourceAsStream(TEST_PDF_2); List<Element> testReferences; try { extractor.setPDF(testStream); testReferences = extractor.getReferencesAsNLM(); } finally { testStream.close(); } InputStream expStream = ContentExtractorTest.class.getResourceAsStream(EXP_CONT_2); InputStreamReader expReader = null; Document dom; try { expReader = new InputStreamReader(expStream, "UTF-8"); dom = saxBuilder.build(expReader); } finally { expStream.close(); if (expReader != null) { expReader.close(); } } Element expNLM = dom.getRootElement(); Element back = expNLM.getChild("back"); Element refList = back.getChild("ref-list"); List<Element> expReferences = new ArrayList<Element>(); for (Object ref : refList.getChildren("ref")) { if (ref instanceof Element) { Element mixedCitation = ((Element)ref).getChild("mixed-citation"); expReferences.add(mixedCitation); } } assertEquals(testReferences.size(), expReferences.size()); XMLOutputter outputter = new XMLOutputter(Format.getPrettyFormat()); for (int i = 0; i < testReferences.size(); i++) { Diff diff = new Diff(outputter.outputString(testReferences.get(i)), outputter.outputString(expReferences.get(i))); assertTrue(diff.similar()); } } @Test public void getNLMContentTest() throws AnalysisException, JDOMException, IOException, SAXException { InputStream testStream = ContentExtractorTest.class.getResourceAsStream(TEST_PDF_2); Element testContent; try { extractor.setPDF(testStream); testContent = extractor.getContentAsNLM(); } finally { testStream.close(); } InputStream expStream = ContentExtractorTest.class.getResourceAsStream(EXP_CONT_2); InputStreamReader expReader = null; Document dom; try { expReader = new InputStreamReader(expStream, "UTF-8"); dom = saxBuilder.build(expReader); } finally { expStream.close(); if (expReader != null) { expReader.close(); } } Element expContent = dom.getRootElement(); XMLOutputter outputter = new XMLOutputter(Format.getPrettyFormat()); Diff diff = new Diff(outputter.outputString(expContent), outputter.outputString(testContent)); assertTrue(diff.similar()); } @Test public void getNLMContentRefsTest() throws AnalysisException, JDOMException, IOException, SAXException { InputStream testStream = ContentExtractorTest.class.getResourceAsStream(TEST_PDF_5); Element testContent; try { extractor.setPDF(testStream); testContent = extractor.getContentAsNLM(); } finally { testStream.close(); } InputStream expStream = ContentExtractorTest.class.getResourceAsStream(EXP_CONT_5); InputStreamReader expReader = null; Document dom; try { expReader = new InputStreamReader(expStream, "UTF-8"); dom = saxBuilder.build(expReader); } finally { expStream.close(); if (expReader != null) { expReader.close(); } } Element expContent = dom.getRootElement(); XMLOutputter outputter = new XMLOutputter(Format.getPrettyFormat()); Diff diff = new Diff(outputter.outputString(expContent), outputter.outputString(testContent)); assertTrue(diff.similar()); } @Test public void getImagesTest() throws IOException, AnalysisException, JDOMException, SAXException { InputStream testStream = ContentExtractorTest.class.getResourceAsStream(TEST_PDF_4); List<BxImage> images; try { extractor.setPDF(testStream); images = extractor.getImages("pref"); } finally { testStream.close(); } assertEquals(4, images.size()); Collections.sort(images, new Comparator<BxImage>(){ @Override public int compare(BxImage o1, BxImage o2) { return o1.getFilename().compareTo(o2.getFilename()); } }); List<String> files = IOUtils.readLines(ContentExtractorTest.class.getResourceAsStream(EXP_IMGS_4), "UTF-8"); Collections.sort(files); for (int i = 0; i < files.size(); i++) { String fileName = files.get(i); BxImage image = images.get(i); assertEquals(fileName, image.getFilename()); BufferedImage expImg = ImageIO.read(ContentExtractorTest.class.getResourceAsStream(EXP_IMGS_4+fileName)); BufferedImage testImg = image.getImage(); assertEquals(expImg.getHeight(), testImg.getHeight()); assertEquals(expImg.getWidth(), testImg.getWidth()); for (int y = 0; y < expImg.getHeight(); y++) { for (int x = 0; x < expImg.getWidth(); x++) { assertEquals(expImg.getRGB(x, y), testImg.getRGB(x, y)); } } } } @Test public void getContentWithImagesTest() throws IOException, AnalysisException, JDOMException, SAXException { InputStream testStream = ContentExtractorTest.class.getResourceAsStream(TEST_PDF_4); Element testContent; try { extractor.setPDF(testStream); testContent = extractor.getContentAsNLM("pref"); } finally { testStream.close(); } InputStream expStream = ContentExtractorTest.class.getResourceAsStream(EXP_CONT_4); InputStreamReader expReader = null; Document dom; try { expReader = new InputStreamReader(expStream, "UTF-8"); dom = saxBuilder.build(expReader); } finally { expStream.close(); if (expReader != null) { expReader.close(); } } Element expContent = dom.getRootElement(); XMLOutputter outputter = new XMLOutputter(Format.getPrettyFormat()); Diff diff = new Diff(outputter.outputString(expContent), outputter.outputString(testContent)); assertTrue(diff.similar()); } }
17,285
39.2
138
java
CERMINE
CERMINE-master/cermine-impl/src/test/java/pl/edu/icm/cermine/ContentExtractorLoopTest.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.ArrayList; import java.util.List; import org.junit.Before; import org.junit.Test; import static org.junit.Assert.*; import pl.edu.icm.cermine.exception.AnalysisException; /** * @author Dominika Tkaczyk (d.tkaczyk@icm.edu.pl) */ public class ContentExtractorLoopTest { static final private List<String> TEST_PDFS = Lists.newArrayList( "/pl/edu/icm/cermine/test1.pdf", "/pl/edu/icm/cermine/test2.pdf", "/pl/edu/icm/cermine/test3.pdf", "/pl/edu/icm/cermine/test4.pdf", "/pl/edu/icm/cermine/test5.pdf", "/pl/edu/icm/cermine/test6.pdf" ); private ContentExtractor extractor; @Before public void setUp() throws AnalysisException, IOException { extractor = new ContentExtractor(); } @Test public void extractionLoopTest() throws AnalysisException, IOException { List<String> titles = new ArrayList<String>(); for (String file : TEST_PDFS) { InputStream testStream = ContentExtractorLoopTest.class.getResourceAsStream(file); extractor.setPDF(testStream); extractor.getContentAsNLM(); titles.add(extractor.getMetadata().getTitle()); } assertEquals(Lists.newArrayList( "Complications related to deep venous thrombosis prophylaxis in trauma: a systematic review of the literature", "Patient Experiences of Structured Heart Failure Programmes", "Phytochemical and Biological investigations of Phoenix paludosa Roxb.", "The four Zn fingers of MBNL1 provide a flexible platform for recognition of its RNA binding elements", "Iron deficiency anaemia can be improved after eradication of Helicobacter pylori", "VESPA: Very large-scale Evolutionary and Selective Pressure Analyses"), titles); } }
2,806
37.986111
127
java
CERMINE
CERMINE-master/cermine-impl/src/test/java/pl/edu/icm/cermine/AltPdfNLMMetadataExtractorTest.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 java.io.InputStreamReader; import org.custommonkey.xmlunit.Diff; import org.jdom.Document; import org.jdom.Element; import org.jdom.JDOMException; import org.jdom.input.SAXBuilder; import org.jdom.output.Format; import org.jdom.output.XMLOutputter; import static org.junit.Assert.assertTrue; import org.junit.Before; import org.junit.Test; import org.xml.sax.SAXException; import pl.edu.icm.cermine.exception.AnalysisException; /** * @author Dominika Tkaczyk (d.tkaczyk@icm.edu.pl) */ public class AltPdfNLMMetadataExtractorTest { private final static String ALT_METADATA_CLASSIFIER_MODEL_PATH = "classpath:/pl/edu/icm/cermine/structure/model-metadata-humanities"; private final static String ALT_METADATA_CLASSIFIER_RANGE_PATH = "classpath:/pl/edu/icm/cermine/structure/model-metadata-humanities.range"; static final private String TEST_FILE = "/pl/edu/icm/cermine/test3.pdf"; static final private String EXP_FILE = "/pl/edu/icm/cermine/test3-metadata.xml"; private ContentExtractor extractor; @Before public void setUp() throws AnalysisException, IOException { extractor = new ContentExtractor(); extractor.getConf().setMetadataZoneClassifier(ComponentFactory.getMetadataZoneClassifier(ALT_METADATA_CLASSIFIER_MODEL_PATH, ALT_METADATA_CLASSIFIER_RANGE_PATH)); } @Test public void metadataExtractionTest() throws AnalysisException, IOException, JDOMException, SAXException { InputStream testStream = AltPdfNLMMetadataExtractorTest.class.getResourceAsStream(TEST_FILE); Element testMetadata; try { extractor.setPDF(testStream); testMetadata = extractor.getMetadataAsNLM(); } finally { testStream.close(); } InputStream expStream = null; InputStreamReader expReader = null; SAXBuilder saxBuilder; Document dom; Element expMetadata = null; try { expStream = AltPdfNLMMetadataExtractorTest.class.getResourceAsStream(EXP_FILE); expReader = new InputStreamReader(expStream, "UTF-8"); saxBuilder = new SAXBuilder("org.apache.xerces.parsers.SAXParser"); dom = saxBuilder.build(expReader); expMetadata = dom.getRootElement(); } finally { if (expStream != null) { expStream.close(); } if (expReader != null) { expReader.close(); } } XMLOutputter outputter = new XMLOutputter(Format.getPrettyFormat()); Diff diff = new Diff(outputter.outputString(expMetadata), outputter.outputString(testMetadata)); assertTrue(diff.similar()); } }
3,569
37.804348
170
java
CERMINE
CERMINE-master/cermine-impl/src/test/java/pl/edu/icm/cermine/ContentExtractorTimeoutTest.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 static org.junit.Assert.fail; import java.io.IOException; import java.io.InputStream; import java.util.Arrays; import java.util.Collection; import java.util.Collections; import java.util.List; import org.junit.Test; import pl.edu.icm.cermine.exception.AnalysisException; import pl.edu.icm.cermine.tools.timeout.TimeoutException; /** * @author Mateusz Kobos */ public class ContentExtractorTimeoutTest { static final private String COMPLEX_PDF_PATH = "/pl/edu/icm/cermine/tools/timeout/complex.pdf"; static final private String SIMPLE_PDF_PATH = "/pl/edu/icm/cermine/tools/timeout/simple.pdf"; static final private long ACCEPTABLE_DELAY_MILLIS = 5000; @Test public void testNoTimeout() throws AnalysisException, IOException { InputStream in = ContentExtractorTimeoutTest.class.getResourceAsStream(SIMPLE_PDF_PATH); try { ContentExtractor extractor = new ContentExtractor(); extractor.setPDF(in); extractor.getBxDocument(); } finally { in.close(); } } @Test public void testObjectTimeoutRemoval() throws IOException, TimeoutException, AnalysisException { InputStream in = ContentExtractorTimeoutTest.class.getResourceAsStream(SIMPLE_PDF_PATH); try { ContentExtractor extractor = new ContentExtractor(); extractor.setPDF(in); extractor.setTimeout(0); extractor.removeTimeout(); extractor.getBxDocument(); } finally { in.close(); } } @Test public void testObjectTimeoutSetInConstructor() throws IOException, TimeoutException, AnalysisException { InputStream in = ContentExtractorTimeoutTest.class.getResourceAsStream(COMPLEX_PDF_PATH); long start = System.currentTimeMillis(); try { ContentExtractor extractor = new ContentExtractor(1); extractor.setPDF(in); extractor.getBxDocument(); } catch (TimeoutException ex) { assumeTimeoutWithinTimeBound(start); return; } finally { in.close(); } fail("The processing should have been interrupted by timeout but wasn't"); } @Test public void testObjectTimeout() throws IOException, TimeoutException, AnalysisException { assumeOperationsEndInTimeout( new ContentExtractorFactory() { @Override public ContentExtractor create(InputStream document) throws AnalysisException, IOException { ContentExtractor extractor = new ContentExtractor(); extractor.setTimeout(1); extractor.setPDF(document); return extractor; } }, Collections.singletonList( new ExtractorOperation() { @Override public void run(ContentExtractor extractor) throws TimeoutException, AnalysisException { extractor.getBxDocument(); } }) ); } @Test public void testMethodTimeout() throws IOException, TimeoutException, AnalysisException { assumeOperationsEndInTimeout(Collections.singletonList( new ExtractorOperation() { @Override public void run(ContentExtractor extractor) throws TimeoutException, AnalysisException { extractor.getBxDocument(1); } } )); } @Test public void testAllExtractionOperationsEndInTimeout() throws AnalysisException, IOException { /** * The timeout set here is zero to make sure that the methods end in * timeout no matter how short they take to execute. */ List<? extends ExtractorOperation> list = Arrays.asList( new ExtractorOperation() { @Override public void run(ContentExtractor extractor) throws TimeoutException, AnalysisException { extractor.getBxDocument(0); } }, new ExtractorOperation() { @Override public void run(ContentExtractor extractor) throws TimeoutException, AnalysisException { extractor.getBxDocumentWithGeneralLabels(0); } }, new ExtractorOperation() { @Override public void run(ContentExtractor extractor) throws TimeoutException, AnalysisException { extractor.getBxDocumentWithSpecificLabels(0); } }, new ExtractorOperation() { @Override public void run(ContentExtractor extractor) throws TimeoutException, AnalysisException { extractor.getMetadata(0); } }, new ExtractorOperation() { @Override public void run(ContentExtractor extractor) throws TimeoutException, AnalysisException { extractor.getMetadataAsNLM(0); } }, new ExtractorOperation() { @Override public void run(ContentExtractor extractor) throws TimeoutException, AnalysisException { extractor.getReferences(0); } }, new ExtractorOperation() { @Override public void run(ContentExtractor extractor) throws TimeoutException, AnalysisException { extractor.getReferencesAsNLM(0); } }, new ExtractorOperation() { @Override public void run(ContentExtractor extractor) throws TimeoutException, AnalysisException { extractor.getRawFullText(0); } }, new ExtractorOperation() { @Override public void run(ContentExtractor extractor) throws TimeoutException, AnalysisException { extractor.getLabelledFullText(0); } }, new ExtractorOperation() { @Override public void run(ContentExtractor extractor) throws TimeoutException, AnalysisException { extractor.getBody(0); } }, new ExtractorOperation() { @Override public void run(ContentExtractor extractor) throws TimeoutException, AnalysisException { extractor.getBodyAsNLM(0); } }, new ExtractorOperation() { @Override public void run(ContentExtractor extractor) throws TimeoutException, AnalysisException { extractor.getContentAsNLM(0); } }); assumeOperationsEndInTimeout(list); } @Test public void testObjectAndMethodTimeoutCombinedWithObjectTimeoutActive() throws IOException, TimeoutException, AnalysisException { assumeOperationsEndInTimeout( new ContentExtractorFactory() { @Override public ContentExtractor create(InputStream document) throws AnalysisException, IOException { ContentExtractor extractor = new ContentExtractor(); extractor.setTimeout(1); extractor.setPDF(document); return extractor; } }, Collections.singletonList( new ExtractorOperation() { @Override public void run(ContentExtractor extractor) throws TimeoutException, AnalysisException { extractor.getBxDocument(100); } }) ); } @Test public void testObjectAndMethodTimeoutCombinedWithMethodTimeoutActive() throws IOException, TimeoutException, AnalysisException { assumeOperationsEndInTimeout( new ContentExtractorFactory() { @Override public ContentExtractor create(InputStream document) throws AnalysisException, IOException { ContentExtractor extractor = new ContentExtractor(); extractor.setTimeout(100); extractor.setPDF(document); return extractor; } }, Collections.singletonList( new ExtractorOperation() { @Override public void run(ContentExtractor extractor) throws TimeoutException, AnalysisException { extractor.getBxDocument(1); } }) ); } private static void assumeOperationsEndInTimeout( Collection<? extends ExtractorOperation> operations) throws AnalysisException, IOException { assumeOperationsEndInTimeout(new ContentExtractorFactory() { @Override public ContentExtractor create(InputStream document) throws AnalysisException, IOException { ContentExtractor extractor = new ContentExtractor(); extractor.setPDF(document); return extractor; } }, operations); } private static void assumeOperationsEndInTimeout( ContentExtractorFactory factory, Collection<? extends ExtractorOperation> operations) throws AnalysisException, IOException { InputStream in = ContentExtractorTimeoutTest.class .getResourceAsStream(COMPLEX_PDF_PATH); try { ContentExtractor extractor = factory.create(in); for (ExtractorOperation op : operations) { long start = System.currentTimeMillis(); try { op.run(extractor); } catch (TimeoutException ex) { assumeTimeoutWithinTimeBound(start); return; } fail("The processing should have been interrupted by timeout " + "but wasn't"); } } finally { in.close(); } } private static void assumeTimeoutWithinTimeBound(long startMillis) { long endMillis = System.currentTimeMillis(); long diff = endMillis - startMillis; if (diff > ACCEPTABLE_DELAY_MILLIS) { fail("The processing interrupted by the timeout took " + diff + " milliseconds while it should have taken no more than " + ACCEPTABLE_DELAY_MILLIS + " milliseconds"); } } } interface ExtractorOperation { void run(ContentExtractor extractor) throws TimeoutException, AnalysisException; } interface ContentExtractorFactory { ContentExtractor create(InputStream document) throws AnalysisException, IOException; }
12,050
35.853211
99
java
CERMINE
CERMINE-master/cermine-impl/src/test/java/pl/edu/icm/cermine/tools/PrefixTreeTest.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 com.google.common.collect.Sets; import static org.junit.Assert.*; import org.junit.Test; /** * @author Dominika Tkaczyk */ public class PrefixTreeTest { @Test public void testPT() { PrefixTree pt = new PrefixTree(PrefixTree.START_TERM); pt.build(Sets.newHashSet("one", "one two", "one two three", "one three", "four five")); assertEquals(1, pt.match(Lists.newArrayList("one"))); assertEquals(2, pt.match(Lists.newArrayList("one", "two"))); assertEquals(2, pt.match(Lists.newArrayList("one", "two", "five"))); assertEquals(-1, pt.match(Lists.newArrayList("four"))); assertEquals(-1, pt.match(Lists.newArrayList("four", "six"))); assertEquals(3, pt.match(Lists.newArrayList("one", "two", "three", "five"))); assertEquals(2, pt.match(Lists.newArrayList("four", "five", "six"))); } }
1,700
35.978261
95
java
CERMINE
CERMINE-master/cermine-impl/src/test/java/pl/edu/icm/cermine/tools/HistogramTest.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 static org.junit.Assert.assertEquals; import org.junit.Test; /** * @author Krzysztof Rusek */ public class HistogramTest { private static final double EPSILON = 1e-3; @Test public void testGetFrequency() { Histogram h = new Histogram(0, 16, 2); h.add(0); h.add(1); h.add(3); h.add(3); h.add(3.5); assertEquals(2.0, h.getFrequency(0), EPSILON); assertEquals(3.0, h.getFrequency(1), EPSILON); } @Test public void testGetPeakValue() { Histogram h = new Histogram(0, 16, 2); h.add(1); h.add(1); h.add(1); h.add(2.5); h.add(3.5); h.add(2.1); h.add(2.1); assertEquals(3.0, h.getPeakValue(), EPSILON); } @Test public void testSmooth() { Histogram h = new Histogram(20.0, 40.0, 2.0); h.add(21.0); h.add(21.0); h.add(21.0); h.smooth(6.0); assertEquals(1.0, h.getFrequency(0), EPSILON); assertEquals(1.0, h.getFrequency(1), EPSILON); assertEquals(0.0, h.getFrequency(2), EPSILON); } @Test public void testCircularSmooth() { Histogram h = new Histogram(0.0, 10.0, 1.0); h.add(0.5); h.circularSmooth(5.0); assertEquals(0.2, h.getFrequency(0), EPSILON); assertEquals(0.2, h.getFrequency(1), EPSILON); assertEquals(0.2, h.getFrequency(2), EPSILON); assertEquals(0.0, h.getFrequency(3), EPSILON); assertEquals(0.0, h.getFrequency(4), EPSILON); assertEquals(0.0, h.getFrequency(5), EPSILON); assertEquals(0.0, h.getFrequency(6), EPSILON); assertEquals(0.0, h.getFrequency(7), EPSILON); assertEquals(0.2, h.getFrequency(8), EPSILON); assertEquals(0.2, h.getFrequency(9), EPSILON); } }
2,563
30.268293
78
java
CERMINE
CERMINE-master/cermine-impl/src/test/java/pl/edu/icm/cermine/tools/TextUtilsTest.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 static org.junit.Assert.assertFalse; import static org.junit.Assert.assertTrue; import org.junit.Test; /** * @author Dominika Tkaczyk (d.tkaczyk@icm.edu.pl) */ public class TextUtilsTest { @Test public void testIsWord() { String word = "BabamaKota"; String notWord1 = "Baba ma"; String notWord2 = "Baba123"; assertTrue(TextUtils.isWord(word)); assertFalse(TextUtils.isWord(notWord1)); assertFalse(TextUtils.isWord(notWord2)); } @Test public void testIsNumber() { String number = "53253325"; String notNumber1 = "123 "; String notNumber2 = "123b"; assertTrue(TextUtils.isNumber(number)); assertFalse(TextUtils.isNumber(notNumber1)); assertFalse(TextUtils.isNumber(notNumber2)); } @Test public void testIsOnlyFirstUpperCase() { String firstUpperCase1 = "M"; String firstUpperCase2 = "Mama"; String notUpperCase = "aM"; String moreUpperCase = "MM"; String notWord = "Wombat1"; assertTrue(TextUtils.isOnlyFirstUpperCase(firstUpperCase1)); assertTrue(TextUtils.isOnlyFirstUpperCase(firstUpperCase2)); assertFalse(TextUtils.isOnlyFirstUpperCase(notUpperCase)); assertFalse(TextUtils.isOnlyFirstUpperCase(moreUpperCase)); assertFalse(TextUtils.isOnlyFirstUpperCase(notWord)); } @Test public void testAllUpperCase() { String firstUpperCase1 = "M"; String firstUpperCase2 = "Mama"; String notUpperCase = "aM"; String moreUpperCase = "MM"; String notWord = "W1"; assertTrue(TextUtils.isAllUpperCase(firstUpperCase1)); assertFalse(TextUtils.isAllUpperCase(firstUpperCase2)); assertFalse(TextUtils.isAllUpperCase(notUpperCase)); assertTrue(TextUtils.isAllUpperCase(moreUpperCase)); assertFalse(TextUtils.isAllUpperCase(notWord)); } @Test public void testIsSeparator() { String separator1 = "."; String separator2 = ","; String separator3 = ";"; String notSeparator = ":"; String twoSeparators = ".."; assertTrue(TextUtils.isSeparator(separator1)); assertTrue(TextUtils.isSeparator(separator2)); assertTrue(TextUtils.isSeparator(separator3)); assertFalse(TextUtils.isSeparator(notSeparator)); assertFalse(TextUtils.isSeparator(twoSeparators)); } @Test public void testIsNonAlphanumSep() { String alpha = "a"; String num = "1"; String sep = ","; String other = "("; assertFalse(TextUtils.isNonAlphanumSep(alpha)); assertFalse(TextUtils.isNonAlphanumSep(num)); assertFalse(TextUtils.isNonAlphanumSep(sep)); assertTrue(TextUtils.isNonAlphanumSep(other)); } }
3,603
33.653846
78
java
CERMINE
CERMINE-master/cermine-impl/src/test/java/pl/edu/icm/cermine/tools/ResourceUtilsTest.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 static org.junit.Assert.assertEquals; import java.io.IOException; import java.io.InputStream; import java.net.URL; import java.nio.charset.Charset; import java.util.List; import org.apache.commons.io.IOUtils; import org.junit.After; import org.junit.Test; /** * @author madryk */ public class ResourceUtilsTest { private final InputStream resourceStream = null; @After public void cleanup() throws IOException { if (resourceStream != null) { resourceStream.close(); } } @Test public void openResourceStream_FROM_CLASSPATH() throws IOException { InputStream inputStream = ResourceUtils.openResourceStream("classpath:/pl/edu/icm/cermine/tools/resourceFile.txt"); assertResourceContent(inputStream); } @Test public void openResourceStream_FROM_FILE() throws IOException { URL resourceUrl = ResourceUtilsTest.class.getClassLoader().getResource("pl/edu/icm/cermine/tools/resourceFile.txt"); InputStream inputStream = ResourceUtils.openResourceStream(resourceUrl.getPath()); assertResourceContent(inputStream); } private void assertResourceContent(InputStream inputStream) throws IOException { List<String> resourceLines = IOUtils.readLines(inputStream, Charset.forName("UTF-8")); assertEquals(1, resourceLines.size()); assertEquals("Resource file content", resourceLines.get(0)); } }
2,258
32.220588
124
java
CERMINE
CERMINE-master/cermine-impl/src/test/java/pl/edu/icm/cermine/tools/DisjointSetsTest.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.*; import static org.junit.Assert.*; import org.junit.Test; /** * @author Krzysztof Rusek */ public class DisjointSetsTest { private List<Integer> newRange(int start, int stop) { List<Integer> list = new ArrayList<Integer>(); for (int i = start; i < stop; i++) { list.add(i); } return list; } private Set<Integer> newSet(Integer... elements) { return new HashSet<Integer>(Arrays.asList(elements)); } @Test public void testConstruct() { DisjointSets<Integer> sets = new DisjointSets<Integer>(newRange(0, 10)); assertFalse(sets.areTogether(0, 1)); assertTrue(sets.areTogether(2, 2)); } @Test public void testUnion() { DisjointSets<Integer> sets = new DisjointSets<Integer>(newRange(0, 10)); sets.union(0, 8); assertTrue(sets.areTogether(0, 8)); sets.union(0, 4); assertTrue(sets.areTogether(0, 4)); assertTrue(sets.areTogether(4, 8)); sets.union(1, 3); sets.union(5, 7); sets.union(3, 5); assertTrue(sets.areTogether(1, 7)); sets.union(5, 4); assertTrue(sets.areTogether(0, 7)); assertTrue(sets.areTogether(4, 5)); } @Test public void testIterator() { DisjointSets<Integer> sets = new DisjointSets<Integer>(newRange(0, 10)); for (Set<Integer> subset : sets) { assertEquals(1, subset.size()); } Set<Set<Integer>> expected = new HashSet<Set<Integer>>(); sets.union(0, 4); expected.add(newSet(0, 4)); sets.union(1, 8); expected.add(newSet(1, 8)); sets.union(2, 9); expected.add(newSet(2, 9)); sets.union(3, 5); expected.add(newSet(3, 5)); sets.union(6, 7); expected.add(newSet(6, 7)); Set<Set<Integer>> actual = new HashSet<Set<Integer>>(); for (Set<Integer> subset : sets) { assertEquals(2, subset.size()); actual.add(subset); } assertEquals(expected, actual); } }
2,834
30.5
80
java
CERMINE
CERMINE-master/cermine-impl/src/test/java/pl/edu/icm/cermine/tools/timeout/TimeoutRegisterTest.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 static org.junit.Assert.assertTrue; import static org.junit.Assert.fail; import java.util.ArrayList; import java.util.List; import java.util.concurrent.BrokenBarrierException; import java.util.concurrent.Callable; import java.util.concurrent.CyclicBarrier; import java.util.concurrent.ExecutionException; import java.util.concurrent.ExecutorService; import java.util.concurrent.Executors; import java.util.concurrent.Future; import org.junit.Test; /** * @author Mateusz Kobos */ public class TimeoutRegisterTest { @Test(expected = TimeoutException.class) public void testBasic() throws InterruptedException { try { TimeoutRegister.set(new Timeout(10)); doStuff(); } finally { TimeoutRegister.remove(); } } private static void doStuff() throws InterruptedException { for (int i = 0; i < 10; i++) { Thread.sleep(5); TimeoutRegister.get().check(); } } @Test(expected = TimeoutException.class) public void testZeroTimeout() { Timeout t = new Timeout(0); t.check(); } @Test public void testRemoveTimeout() throws InterruptedException { try { TimeoutRegister.set(new Timeout(30000)); TimeoutRegister.get().check(); Thread.sleep(10); TimeoutRegister.get().check(); TimeoutRegister.remove(); TimeoutRegister.get().check(); Thread.sleep(10); TimeoutRegister.get().check(); } finally { TimeoutRegister.remove(); } } @Test(expected = TimeoutException.class) public void testSetingNewTimeoutAfterRemovingPreviousOne() throws InterruptedException { try { TimeoutRegister.set(new Timeout(30000)); TimeoutRegister.get().check(); TimeoutRegister.remove(); TimeoutRegister.set(new Timeout(5)); Thread.sleep(10); TimeoutRegister.get().check(); } finally { TimeoutRegister.remove(); } } @Test public void testTimeoutInChildThreadDoesntInfluenceParent() throws InterruptedException { Thread child = new Thread(new Runnable() { @Override public void run() { try { TimeoutRegister.set(new Timeout(0)); TimeoutRegister.get().check(); fail("Didn't throw the exception as expected"); } catch (TimeoutException ex){ /** empty */ } finally { /** * We don't call TimeoutRegister.remove() here, which we * would normally do, because we want to check if the * timeout is carried over to the parent thread. */ } } }); TimeoutRegister.get().check(); child.start(); child.join(); TimeoutRegister.get().check(); } @Test public void testTimeoutInParentThreadDoesntInfluenceChild() throws InterruptedException { try { TimeoutRegister.set(new Timeout(0)); Thread child = new Thread(new Runnable() { @Override public void run() { TimeoutRegister.get().check(); } }); child.start(); child.join(); } finally { TimeoutRegister.remove(); } } @Test public void testTimeoutInThreadDoesntInfluenceItsSibling() throws InterruptedException, BrokenBarrierException { ArrayList<Callable<Void>> tasks = createTasksWithBarriersToCall(); ExecutorService exec = Executors.newFixedThreadPool(2); List<Future<Void>> results = exec.invokeAll(tasks); exec.shutdown(); try { results.get(0).get(); fail("Didn't throw the exception as expected"); } catch (ExecutionException ex) { assertTrue(ex.getCause() instanceof TimeoutException); } results.get(1); } private static ArrayList<Callable<Void>> createTasksWithBarriersToCall(){ final CyclicBarrier barrier0 = new CyclicBarrier(2); final CyclicBarrier barrier1 = new CyclicBarrier(2); ArrayList<Callable<Void>> tasks = new ArrayList<Callable<Void>>(); tasks.add(new Callable<Void>() { @Override public Void call() throws InterruptedException, BrokenBarrierException { try { TimeoutRegister.set(new Timeout(0)); barrier0.await(); barrier1.await(); TimeoutRegister.get().check(); return null; } finally { TimeoutRegister.remove(); } } }); tasks.add(new Callable<Void>() { @Override public Void call() throws InterruptedException, BrokenBarrierException { barrier0.await(); TimeoutRegister.get().check(); barrier1.await(); return null; } }); return tasks; } }
6,167
31.808511
78
java
CERMINE
CERMINE-master/cermine-impl/src/test/java/pl/edu/icm/cermine/configuration/ExtractionConfigRegisterTest.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.junit.Test; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertFalse; import static org.junit.Assert.assertTrue; /** * @author madryk */ public class ExtractionConfigRegisterTest { @Test public void loadConfiguration_DEFAULT() { try { // execute ExtractionConfig configuration = ExtractionConfigRegister.get(); // assert assertEquals( "classpath:/pl/edu/icm/cermine/structure/model-initial-default", configuration.getStringProperty(ExtractionConfigProperty.INITIAL_ZONE_CLASSIFIER_MODEL_PATH)); assertEquals( "classpath:/pl/edu/icm/cermine/structure/model-initial-default.range", configuration.getStringProperty(ExtractionConfigProperty.INITIAL_ZONE_CLASSIFIER_RANGE_PATH)); assertEquals( "classpath:/pl/edu/icm/cermine/structure/model-metadata-default", configuration.getStringProperty(ExtractionConfigProperty.METADATA_ZONE_CLASSIFIER_MODEL_PATH)); assertEquals( "classpath:/pl/edu/icm/cermine/structure/model-metadata-default.range", configuration.getStringProperty(ExtractionConfigProperty.METADATA_ZONE_CLASSIFIER_RANGE_PATH)); assertEquals( "classpath:/pl/edu/icm/cermine/content/filtering.model", configuration.getStringProperty(ExtractionConfigProperty.CONTENT_FILTER_MODEL_PATH)); assertEquals( "classpath:/pl/edu/icm/cermine/content/filtering.range", configuration.getStringProperty(ExtractionConfigProperty.CONTENT_FILTER_RANGE_PATH)); assertTrue(configuration.getBooleanProperty(ExtractionConfigProperty.IMAGES_EXTRACTION)); assertFalse(configuration.getBooleanProperty(ExtractionConfigProperty.DEBUG_PRINT_TIME)); } finally { ExtractionConfigRegister.remove(); } } @Test public void loadConfiguration_OVERRIDE_DEFAULTS() { try { // given String configFilePath = ExtractionConfigRegisterTest.class.getClassLoader().getResource("pl/edu/icm/cermine/configuration/test-config.properties").getPath(); // execute ExtractionConfigRegister.set(new ExtractionConfigBuilder() .addConfiguration(configFilePath) .setProperty(ExtractionConfigProperty.IMAGES_EXTRACTION, false) .buildConfiguration() ); ExtractionConfig configuration = ExtractionConfigRegister.get(); // assert assertEquals( "classpath:/pl/edu/icm/cermine/structure/model-initial-default", configuration.getStringProperty(ExtractionConfigProperty.INITIAL_ZONE_CLASSIFIER_MODEL_PATH)); assertEquals( "classpath:/pl/edu/icm/cermine/structure/model-initial-default.range", configuration.getStringProperty(ExtractionConfigProperty.INITIAL_ZONE_CLASSIFIER_RANGE_PATH)); assertEquals( "/path/to/metadata/classifier/model", configuration.getStringProperty(ExtractionConfigProperty.METADATA_ZONE_CLASSIFIER_MODEL_PATH)); assertEquals( "/path/to/metadata/classifier/range", configuration.getStringProperty(ExtractionConfigProperty.METADATA_ZONE_CLASSIFIER_RANGE_PATH)); assertEquals( "classpath:/pl/edu/icm/cermine/content/filtering.model", configuration.getStringProperty(ExtractionConfigProperty.CONTENT_FILTER_MODEL_PATH)); assertEquals( "classpath:/pl/edu/icm/cermine/content/filtering.range", configuration.getStringProperty(ExtractionConfigProperty.CONTENT_FILTER_RANGE_PATH)); assertFalse(configuration.getBooleanProperty(ExtractionConfigProperty.IMAGES_EXTRACTION)); assertTrue(configuration.getBooleanProperty(ExtractionConfigProperty.DEBUG_PRINT_TIME)); } finally { ExtractionConfigRegister.remove(); } } }
5,191
45.774775
169
java
CERMINE
CERMINE-master/cermine-impl/src/test/java/pl/edu/icm/cermine/structure/HierarchicalReadingOrderResolverTest.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.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.Enumeration; import java.util.List; import java.util.zip.ZipEntry; import java.util.zip.ZipException; import java.util.zip.ZipFile; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertTrue; import org.junit.Before; import org.junit.Test; import pl.edu.icm.cermine.exception.TransformationException; import pl.edu.icm.cermine.structure.model.*; import pl.edu.icm.cermine.structure.transformers.TrueVizToBxDocumentReader; /** * @author Pawel Szostek */ public class HierarchicalReadingOrderResolverTest { private final static String PATH = "/pl/edu/icm/cermine/structure/"; private final static String[] TEST_FILENAMES = {"1748717X.xml"}; private final static String ZIP_FILE_NAME = "roa_test_small.zip"; private ZipFile zipFile; @Before public void setUp() throws URISyntaxException, ZipException, IOException { URL url = HierarchicalReadingOrderResolverTest.class.getResource(PATH + ZIP_FILE_NAME); URI uri = url.toURI(); File file = new File(uri); zipFile = new ZipFile(file); } private BxDocument getDocumentFromZip(String filename) throws TransformationException, IOException { TrueVizToBxDocumentReader tvReader = new TrueVizToBxDocumentReader(); Enumeration<? extends ZipEntry> entries = zipFile.entries(); while (entries.hasMoreElements()) { ZipEntry zipEntry = (ZipEntry) entries.nextElement(); if (zipEntry.getName().equals(filename)) { 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); return newDoc; } } return null; } private Boolean areDocumentsEqual(BxDocument doc1, BxDocument doc2) { if (doc1.childrenCount() != doc2.childrenCount()) { return false; } for (Integer pageIdx = 0; pageIdx < doc1.childrenCount(); ++pageIdx) { BxPage page1 = doc1.getChild(pageIdx); BxPage page2 = doc2.getChild(pageIdx); if (page1.childrenCount() != page2.childrenCount()) { return false; } for (Integer zoneIdx = 0; zoneIdx < page1.childrenCount(); ++zoneIdx) { BxZone zone1 = page1.getChild(zoneIdx); BxZone zone2 = page2.getChild(zoneIdx); if (zone1.getChunks().size() != zone2.getChunks().size()) { return false; } for (Integer chunkIdx = 0; chunkIdx < zone1.getChunks().size(); ++chunkIdx) { BxChunk chunk1 = zone1.getChunks().get(chunkIdx); BxChunk chunk2 = zone2.getChunks().get(chunkIdx); if (!chunk1.toText().equals(chunk2.toText())) { return false; } } } } return true; } @Test public void testSetReadingOrder() throws TransformationException, IOException { for (Enumeration<? extends ZipEntry> e = zipFile.entries(); e.hasMoreElements();) { String filename = e.nextElement().getName(); if (!filename.endsWith(".xml")) { continue; } BxDocument doc = getDocumentFromZip(filename); BxDocument modelOrderedDoc = getDocumentFromZip(filename + ".out"); HierarchicalReadingOrderResolver roa = new HierarchicalReadingOrderResolver(); BxDocument orderedDoc = roa.resolve(doc); assertTrue(areDocumentsEqual(orderedDoc, modelOrderedDoc)); } } @Test public void testConstantElementsNumber() throws TransformationException, IOException { for (String filename : TEST_FILENAMES) { BxDocument doc = getDocumentFromZip(filename); HierarchicalReadingOrderResolver roa = new HierarchicalReadingOrderResolver(); BxDocument orderedDoc = roa.resolve(doc); List<BxPage> pages1 = Lists.newArrayList(doc.asPages()); List<BxPage> pages2 = Lists.newArrayList(orderedDoc.asPages()); List<BxZone> zones1 = Lists.newArrayList(doc.asZones()); List<BxZone> zones2 = Lists.newArrayList(orderedDoc.asZones()); List<BxLine> lines1 = Lists.newArrayList(doc.asLines()); List<BxLine> lines2 = Lists.newArrayList(orderedDoc.asLines()); List<BxWord> words1 = Lists.newArrayList(doc.asWords()); List<BxWord> words2 = Lists.newArrayList(orderedDoc.asWords()); List<BxChunk> chunks1 = Lists.newArrayList(doc.asChunks()); List<BxChunk> chunks2 = Lists.newArrayList(orderedDoc.asChunks()); assertEquals(pages1.size(), pages2.size()); assertEquals(zones1.size(), zones2.size()); assertEquals(lines1.size(), lines2.size()); assertEquals(words1.size(), words2.size()); assertEquals(chunks1.size(), chunks2.size()); } } }
6,257
40.72
117
java
CERMINE
CERMINE-master/cermine-impl/src/test/java/pl/edu/icm/cermine/structure/ParallelDocstrumPageSegmenterTest.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.io.InputStream; import java.io.InputStreamReader; import java.io.Reader; import java.io.UnsupportedEncodingException; import java.util.List; import static org.junit.Assert.*; import org.junit.Test; import pl.edu.icm.cermine.exception.AnalysisException; import pl.edu.icm.cermine.exception.TransformationException; import pl.edu.icm.cermine.structure.model.*; import pl.edu.icm.cermine.structure.tools.UnsegmentedPagesFlattener; import pl.edu.icm.cermine.structure.transformers.TrueVizToBxDocumentReader; /** * @author Krzysztof Rusek */ public class ParallelDocstrumPageSegmenterTest { private InputStream getResource(String name) { return ParallelDocstrumPageSegmenterTest.class.getResourceAsStream("/pl/edu/icm/cermine/structure/" + name); } @Test public void testSegmentPages() throws TransformationException, AnalysisException, UnsupportedEncodingException { Reader reader = new InputStreamReader(getResource("DocstrumPageSegmenter01.xml"), "UTF-8"); BxDocument inDoc = new BxDocument().setPages(new TrueVizToBxDocumentReader().read(reader)); new UnsegmentedPagesFlattener().process(inDoc); DocstrumSegmenter pageSegmenter = new ParallelDocstrumSegmenter(); BxDocument outDoc = pageSegmenter.segmentDocument(inDoc); // Check whether zones are correctly detected assertEquals(1, outDoc.childrenCount()); // Check whether lines are correctly detected List<BxZone> outZones = Lists.newArrayList(outDoc.getFirstChild()); assertEquals(3, outZones.size()); assertEquals(3, outZones.get(0).childrenCount()); assertEquals(16, outZones.get(1).childrenCount()); assertEquals(16, outZones.get(2).childrenCount()); assertEquals(24, outZones.get(1).getFirstChild().childrenCount()); assertEquals("A", outZones.get(1).getFirstChild().getFirstChild().toText()); for (BxZone zone : outZones) { for (BxLine line : zone) { for (BxWord word : line) { for (BxChunk chunk : word) { assertContains(zone.getBounds(), chunk.getBounds()); } assertContains(zone.getBounds(), word.getBounds()); } assertContains(zone.getBounds(), line.getBounds()); } } assertNotNull(outDoc.getFirstChild().getBounds()); } public void testSegmentPages_badBounds(BxBounds bounds) throws AnalysisException { BxDocument doc = new BxDocument().addPage(new BxPage().addChunk(new BxChunk(bounds, "a"))); new DocstrumSegmenter().segmentDocument(doc); } @Test(expected=AnalysisException.class) public void testSegmentPages_badBounds1() throws AnalysisException { testSegmentPages_badBounds(null); } @Test(expected=AnalysisException.class) public void testSegmentPages_badBounds2() throws AnalysisException { testSegmentPages_badBounds(new BxBounds(Double.NaN, 0, 0, 0)); } @Test(expected=AnalysisException.class) public void testSegmentPages_badBounds3() throws AnalysisException { testSegmentPages_badBounds(new BxBounds(0, 0, Double.POSITIVE_INFINITY, 0)); } private static void assertContains(BxBounds big, BxBounds small) { assertTrue(big.getX() <= small.getX()); assertTrue(big.getY() <= small.getY()); assertTrue(big.getX() + big.getWidth() >= small.getX() + small.getWidth()); assertTrue(big.getY() + big.getHeight() >= small.getY() + small.getHeight()); } }
4,431
39.66055
116
java
CERMINE
CERMINE-master/cermine-impl/src/test/java/pl/edu/icm/cermine/structure/ITextCharacterExtractionTest.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.io.InputStream; import java.util.List; import static org.junit.Assert.assertTrue; import org.junit.Test; 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.BxPage; /** * @author Dominika Tkaczyk (d.tkaczyk@icm.edu.pl) */ public class ITextCharacterExtractionTest { static final private String INPUT_DIR = "/pl/edu/icm/cermine/structure/"; static final private String[] INPUT_FILES = {"1.pdf", "2.pdf", "3.pdf", "4.pdf", "5.pdf", "6.pdf"}; private final CharacterExtractor extractor = new ITextCharacterExtractor(); private final BxBounds b0 = new BxBounds(50.0, 79.0, 12.0, 16.65); private final BxBounds b1 = new BxBounds(62.0, 79.0, 12.0, 16.65); private final BxBounds b2 = new BxBounds(74.0, 79.0, 13.0, 16.65); private final BxBounds b3 = new BxBounds(87.0, 79.0, 13.0, 16.65); private final BxBounds b4 = new BxBounds(110.0, 79.0, 12.0, 16.65); private final BxBounds b5 = new BxBounds(122.0, 79.0, 11.0, 16.65); private final BxBounds b6 = new BxBounds(133.0, 79.0, 14.0, 16.65); private final BxBounds b7 = new BxBounds(147.0, 79.0, 13.0, 16.65); @Test public void metadataExtractionTest() throws AnalysisException { for (String file : INPUT_FILES) { InputStream testStream = ITextCharacterExtractionTest.class.getResourceAsStream(INPUT_DIR + file); BxDocument testDocument = extractor.extractCharacters(testStream); BxPage page = testDocument.getFirstChild(); List<BxChunk> chunks = Lists.newArrayList(page.getChunks()); assertTrue(chunks.get(0).getBounds().isSimilarTo(b0, 0.08)); assertTrue(chunks.get(1).getBounds().isSimilarTo(b1, 0.08)); assertTrue(chunks.get(2).getBounds().isSimilarTo(b2, 0.08)); assertTrue(chunks.get(3).getBounds().isSimilarTo(b3, 0.08)); assertTrue(chunks.get(4).getBounds().isSimilarTo(b4, 0.08)); assertTrue(chunks.get(5).getBounds().isSimilarTo(b5, 0.08)); assertTrue(chunks.get(6).getBounds().isSimilarTo(b6, 0.08)); assertTrue(chunks.get(7).getBounds().isSimilarTo(b7, 0.08)); } } }
3,188
45.217391
110
java
CERMINE
CERMINE-master/cermine-impl/src/test/java/pl/edu/icm/cermine/structure/SVMInitialClassifierTest.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.io.IOException; import java.net.URISyntaxException; import java.util.Arrays; import java.util.List; import java.util.zip.ZipException; import javax.xml.parsers.ParserConfigurationException; import org.junit.Before; import org.junit.Test; import org.xml.sax.SAXException; 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.model.BxZone; import pl.edu.icm.cermine.structure.tools.DocumentProcessor; import pl.edu.icm.cermine.tools.classification.svm.SVMZoneClassifier; /** * @author Pawel Szostek */ public class SVMInitialClassifierTest extends AbstractDocumentProcessorTest { protected static final String ZONE_CLASSIFIER_MODEL_PATH = SVMInitialClassifierTest.class.getResource("/pl/edu/icm/cermine/structure/model-initial-default").getPath(); protected static final String ZONE_CLASSIFIER_RANGE_PATH = SVMInitialClassifierTest.class.getResource("/pl/edu/icm/cermine/structure/model-initial-default.range").getPath(); protected static final String ZIP_RESOURCES = "/pl/edu/icm/cermine/structure/roa_test_small.zip"; protected static final double TEST_SUCCESS_PERCENTAGE = 80; protected SVMZoneClassifier classifier; protected ReadingOrderResolver ror; int allZones = 0; int badZones = 0; @Before public void setUp() throws IOException, AnalysisException { classifier = new SVMInitialZoneClassifier(ZONE_CLASSIFIER_MODEL_PATH, ZONE_CLASSIFIER_RANGE_PATH); ror = new HierarchicalReadingOrderResolver(); startProcessFlattener = new DocumentProcessor() { @Override public void process(BxDocument document) throws AnalysisException { ror.resolve(document); } }; endProcessFlattener = new DocumentProcessor() { @Override public void process(BxDocument document) throws AnalysisException { ror.resolve(document); } }; } @Test public void SVMInitialZoneClassifierTest() throws URISyntaxException, ZipException, IOException, ParserConfigurationException, SAXException, AnalysisException, TransformationException { testAllFilesFromZip(Arrays.asList(ZIP_RESOURCES), TEST_SUCCESS_PERCENTAGE); } @Override protected boolean compareDocuments(BxDocument testDoc, BxDocument expectedDoc) { if (testDoc.childrenCount() != expectedDoc.childrenCount()) { return false; } List<BxZone> testZones = Lists.newArrayList(testDoc.asZones()); List<BxZone> expZones = Lists.newArrayList(expectedDoc.asZones()); Integer correctZones = 0; Integer zones = testZones.size(); for (Integer zoneIdx = 0; zoneIdx < testZones.size(); ++zoneIdx) { BxZone testZone = testZones.get(zoneIdx); BxZone expectedZone = expZones.get(zoneIdx); ++allZones; if (testZone.getLabel() == expectedZone.getLabel().getGeneralLabel()) { ++correctZones; } else { ++badZones; } } return ((double) correctZones / (double) zones) >= TEST_SUCCESS_PERCENTAGE / 100.0; } @Override protected BxDocument process(BxDocument doc) throws AnalysisException { for (BxZone z : doc.asZones()) { z.setLabel(null); } classifier.classifyZones(doc); return doc; } }
4,381
37.104348
177
java
CERMINE
CERMINE-master/cermine-impl/src/test/java/pl/edu/icm/cermine/structure/AbstractDocumentProcessorTest.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.File; import java.io.IOException; import java.io.InputStreamReader; import java.io.Reader; import java.net.URISyntaxException; import java.util.*; import java.util.zip.ZipEntry; import java.util.zip.ZipException; import java.util.zip.ZipFile; import javax.xml.parsers.ParserConfigurationException; import org.xml.sax.SAXException; 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.tools.DocumentProcessor; import pl.edu.icm.cermine.structure.transformers.TrueVizToBxDocumentReader; import static org.junit.Assert.assertTrue; /** * @author Dominika Tkaczyk (d.tkaczyk@icm.edu.pl) */ public abstract class AbstractDocumentProcessorTest { private static final String XML_FILENAME_EX = ".xml"; protected DocumentProcessor startProcessFlattener; protected DocumentProcessor endProcessFlattener; protected abstract boolean compareDocuments(BxDocument testDoc, BxDocument expectedDoc); protected abstract BxDocument process(BxDocument doc) throws AnalysisException; protected void testFiles(Collection<String> files, double percentage) throws IOException, ParserConfigurationException, SAXException, AnalysisException, TransformationException { List<Reader> testReaders = new ArrayList<Reader>(); List<Reader> expectedReaders = new ArrayList<Reader>(); for (String file : files) { testReaders.add(new InputStreamReader(AbstractDocumentProcessorTest.class.getResourceAsStream(file), "UTF-8")); expectedReaders.add(new InputStreamReader(AbstractDocumentProcessorTest.class.getResourceAsStream(file), "UTF-8")); } testCollection(testReaders, expectedReaders, percentage); } protected void testAllFilesFromZip(Collection<String> zipFiles, double percentage) throws URISyntaxException, ZipException, IOException, ParserConfigurationException, SAXException, AnalysisException, TransformationException { testFilesFromZip(zipFiles, percentage, 1, -1); } protected void testSampleFilesFromZip(Collection<String> zipFiles, double percentage) throws ZipException, IOException, URISyntaxException, ParserConfigurationException, SAXException, AnalysisException, TransformationException { testFilesFromZip(zipFiles, percentage, 1, 1); } protected void testSampleFilesFromZip(Collection<String> zipFiles, int from, int to, double percentage) throws ZipException, IOException, URISyntaxException, ParserConfigurationException, SAXException, AnalysisException, TransformationException { testFilesFromZip(zipFiles, percentage, from, to); } private void testFilesFromZip(Collection<String> zipFiles, double percentage, int samplesFrom, int samplesTo) throws ZipException, IOException, URISyntaxException, ParserConfigurationException, SAXException, AnalysisException, TransformationException { List<Reader> testReaders = new ArrayList<Reader>(); List<Reader> expectedReaders = new ArrayList<Reader>(); Map<String, Integer> dirSamplesCount = new HashMap<String, Integer>(); for (String file : zipFiles) { ZipFile zipFile = null; try { zipFile = new ZipFile(new File(AbstractDocumentProcessorTest.class.getResource(file).toURI())); Enumeration entries = zipFile.entries(); while (entries.hasMoreElements()) { ZipEntry zipEntry = (ZipEntry) entries.nextElement(); if (zipEntry.getName().endsWith(XML_FILENAME_EX)) { String parent = new File(zipEntry.getName()).getParent(); if (dirSamplesCount.containsKey(parent)) { dirSamplesCount.put(parent, dirSamplesCount.get(parent) + 1); } else { dirSamplesCount.put(parent, 1); } if (dirSamplesCount.get(parent) >= samplesFrom && (samplesTo < 0 || dirSamplesCount.get(parent) <= samplesTo)) { testReaders.add(new InputStreamReader(zipFile.getInputStream(zipEntry), "UTF-8")); expectedReaders.add(new InputStreamReader(zipFile.getInputStream(zipEntry), "UTF-8")); } } } testCollection(testReaders, expectedReaders, percentage); } finally { if (zipFile != null) { zipFile.close(); } } } } private void testCollection(List<Reader> testReaders, List<Reader> expectedReaders, double percentage) throws IOException, ParserConfigurationException, SAXException, AnalysisException, TransformationException { int passed = 0; TrueVizToBxDocumentReader reader = new TrueVizToBxDocumentReader(); for (int i = 0; i < testReaders.size(); i++) { BxDocument testDoc = new BxDocument().setPages(reader.read(testReaders.get(i))); BxDocument expectedDoc = new BxDocument().setPages(reader.read(expectedReaders.get(i))); if (checkDocument(testDoc, expectedDoc)) { passed++; } } if (!testReaders.isEmpty()) { assertTrue((double) passed * 100.0f / (double) testReaders.size() >= percentage); } } private boolean checkDocument(BxDocument testDoc, BxDocument expectedDoc) throws IOException, ParserConfigurationException, SAXException, AnalysisException { if (startProcessFlattener != null) { startProcessFlattener.process(testDoc); } testDoc = process(testDoc); if (endProcessFlattener != null) { endProcessFlattener.process(expectedDoc); } return compareDocuments(testDoc, expectedDoc); } }
6,943
42.672956
127
java
CERMINE
CERMINE-master/cermine-impl/src/test/java/pl/edu/icm/cermine/structure/DocstrumPageSegmenterTest.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 java.io.InputStreamReader; import java.io.Reader; import java.io.UnsupportedEncodingException; import static org.junit.Assert.*; import org.junit.Test; import pl.edu.icm.cermine.exception.AnalysisException; import pl.edu.icm.cermine.exception.TransformationException; import pl.edu.icm.cermine.structure.model.*; import pl.edu.icm.cermine.structure.tools.UnsegmentedPagesFlattener; import pl.edu.icm.cermine.structure.transformers.TrueVizToBxDocumentReader; /** * @author Krzysztof Rusek */ public class DocstrumPageSegmenterTest { private InputStream getResource(String name) { return DocstrumPageSegmenterTest.class.getResourceAsStream("/pl/edu/icm/cermine/structure/" + name); } @Test public void testSegmentPages() throws TransformationException, AnalysisException, UnsupportedEncodingException { Reader reader = new InputStreamReader(getResource("DocstrumPageSegmenter01.xml"), "UTF-8"); BxDocument inDoc = new BxDocument().setPages(new TrueVizToBxDocumentReader().read(reader)); new UnsegmentedPagesFlattener().process(inDoc); DocstrumSegmenter pageSegmenter = new DocstrumSegmenter(); BxDocument outDoc = pageSegmenter.segmentDocument(inDoc); // Check whether zones are correctly detected assertEquals(1, outDoc.childrenCount()); // Check whether lines are correctly detected assertEquals(3, outDoc.getFirstChild().childrenCount()); assertEquals(3, outDoc.getFirstChild().getChild(0).childrenCount()); assertEquals(16, outDoc.getFirstChild().getChild(1).childrenCount()); assertEquals(16, outDoc.getFirstChild().getChild(2).childrenCount()); assertEquals(24, outDoc.getFirstChild().getChild(1).getFirstChild().childrenCount()); assertEquals("A", outDoc.getFirstChild().getChild(1).getFirstChild().getFirstChild().toText()); for (BxZone zone : outDoc.getFirstChild()) { for (BxLine line : zone) { for (BxWord word : line) { for (BxChunk chunk : word) { assertContains(zone.getBounds(), chunk.getBounds()); } assertContains(zone.getBounds(), word.getBounds()); } assertContains(zone.getBounds(), line.getBounds()); } } assertNotNull(outDoc.getFirstChild().getBounds()); } public void testSegmentPages_badBounds(BxBounds bounds) throws AnalysisException { BxDocument doc = new BxDocument().addPage(new BxPage().addChunk(new BxChunk(bounds, "a"))); new DocstrumSegmenter().segmentDocument(doc); } @Test(expected=AnalysisException.class) public void testSegmentPages_badBounds1() throws AnalysisException { testSegmentPages_badBounds(null); } @Test(expected=AnalysisException.class) public void testSegmentPages_badBounds2() throws AnalysisException { testSegmentPages_badBounds(new BxBounds(Double.NaN, 0, 0, 0)); } @Test(expected=AnalysisException.class) public void testSegmentPages_badBounds3() throws AnalysisException { testSegmentPages_badBounds(new BxBounds(0, 0, Double.POSITIVE_INFINITY, 0)); } private static void assertContains(BxBounds big, BxBounds small) { assertTrue(big.getX() <= small.getX()); assertTrue(big.getY() <= small.getY()); assertTrue(big.getX() + big.getWidth() >= small.getX() + small.getWidth()); assertTrue(big.getY() + big.getHeight() >= small.getY() + small.getHeight()); } }
4,400
40.518868
116
java
CERMINE
CERMINE-master/cermine-impl/src/test/java/pl/edu/icm/cermine/structure/tools/BxModelUtilsTest.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.io.*; import java.util.Stack; import static org.junit.Assert.*; import org.junit.Test; import pl.edu.icm.cermine.exception.TransformationException; import pl.edu.icm.cermine.structure.model.BxChunk; import pl.edu.icm.cermine.structure.model.BxDocument; import pl.edu.icm.cermine.structure.model.BxLine; import pl.edu.icm.cermine.structure.model.BxPage; import pl.edu.icm.cermine.structure.model.BxWord; import pl.edu.icm.cermine.structure.model.BxZone; import pl.edu.icm.cermine.structure.transformers.TrueVizToBxDocumentReader; /** * @author Dominika Tkaczyk (d.tkaczyk@icm.edu.pl) */ public class BxModelUtilsTest { static final private String EXP_STR_LAB_1 = "/pl/edu/icm/cermine/test1-structure-specific.xml"; @Test public void deepCloneTest() throws TransformationException, UnsupportedEncodingException { InputStream stream = BxModelUtilsTest.class.getResourceAsStream(EXP_STR_LAB_1); TrueVizToBxDocumentReader reader = new TrueVizToBxDocumentReader(); BxDocument doc = new BxDocument().setPages(reader.read(new InputStreamReader(stream, "UTF-8"))); BxDocument copy = BxModelUtils.deepClone(doc); assertFalse(doc == copy); assertTrue(BxModelUtils.areEqual(doc, copy)); Stack<BxPage> pages = new Stack<BxPage>(); Stack<BxZone> zones = new Stack<BxZone>(); Stack<BxLine> lines = new Stack<BxLine>(); Stack<BxWord> words = new Stack<BxWord>(); Stack<BxChunk> chunks = new Stack<BxChunk>(); for (BxPage page : copy) { assertTrue(page.getParent() == copy); for (BxZone zone : page) { assertTrue(zone.getParent() == page); for (BxLine line : zone) { assertTrue(line.getParent() == zone); for (BxWord word : line) { assertTrue(word.getParent() == line); for (BxChunk chunk : word) { assertTrue(chunk.getParent() == word); } } } } } BxPage page = copy.getFirstChild(); while (page != null) { pages.push(page); page = page.getNext(); } page = pages.peek(); BxZone zone = copy.getFirstChild().getFirstChild(); while (zone != null) { zones.push(zone); zone = zone.getNext(); } zone = zones.peek(); BxLine line = copy.getFirstChild().getFirstChild().getFirstChild(); while (line != null) { lines.push(line); line = line.getNext(); } line = lines.peek(); BxWord word = copy.getFirstChild().getFirstChild().getFirstChild().getFirstChild(); while (word != null) { words.push(word); word = word.getNext(); } word = words.peek(); BxChunk chunk = copy.getFirstChild().getFirstChild().getFirstChild().getFirstChild().getFirstChild(); while (chunk != null) { chunks.push(chunk); chunk = chunk.getNext(); } chunk = chunks.peek(); while (!pages.empty() && !zones.empty() && !lines.empty() && !words.empty() && !chunks.empty()) { BxChunk ch = chunks.pop(); assertTrue(ch.getParent() == words.peek()); assertTrue(words.peek().getParent() == lines.peek()); assertTrue(lines.peek().getParent() == zones.peek()); assertTrue(zones.peek().getParent() == pages.peek()); if (chunks.empty()) { words.pop(); lines.pop(); zones.pop(); pages.pop(); } else if (ch.getParent() != chunks.peek().getParent()) { BxWord w = words.pop(); assertFalse(words.empty()); if (w.getParent() != words.peek().getParent()) { BxLine l = lines.pop(); assertFalse(lines.empty()); if (l.getParent() != lines.peek().getParent()) { BxZone z = zones.pop(); assertFalse(zones.empty()); if (z.getParent() != zones.peek().getParent()) { pages.pop(); assertFalse(pages.empty()); } } } } } assertTrue(pages.empty()); assertTrue(zones.empty()); assertTrue(lines.empty()); assertTrue(words.empty()); assertTrue(chunks.empty()); while (page != null) { pages.push(page); page = page.getPrev(); } while (zone != null) { zones.push(zone); zone = zone.getPrev(); } while (line != null) { lines.push(line); line = line.getPrev(); } while (word != null) { words.push(word); word = word.getPrev(); } while (chunk != null) { chunks.push(chunk); chunk = chunk.getPrev(); } while (!pages.empty() && !zones.empty() && !lines.empty() && !words.empty() && !chunks.empty()) { BxChunk ch = chunks.pop(); assertTrue(ch.getParent() == words.peek()); assertTrue(words.peek().getParent() == lines.peek()); assertTrue(lines.peek().getParent() == zones.peek()); assertTrue(zones.peek().getParent() == pages.peek()); if (chunks.empty()) { words.pop(); lines.pop(); zones.pop(); pages.pop(); } else if (ch.getParent() != chunks.peek().getParent()) { BxWord w = words.pop(); assertFalse(words.empty()); if (w.getParent() != words.peek().getParent()) { BxLine l = lines.pop(); assertFalse(lines.empty()); if (l.getParent() != lines.peek().getParent()) { BxZone z = zones.pop(); assertFalse(zones.empty()); if (z.getParent() != zones.peek().getParent()) { pages.pop(); assertFalse(pages.empty()); } } } } } assertTrue(pages.empty()); assertTrue(zones.empty()); assertTrue(lines.empty()); assertTrue(words.empty()); assertTrue(chunks.empty()); } }
7,564
36.825
109
java
CERMINE
CERMINE-master/cermine-impl/src/test/java/pl/edu/icm/cermine/structure/tools/BxBoundsBuilderTest.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 static org.junit.Assert.assertEquals; import static org.junit.Assert.assertTrue; import org.junit.Test; import pl.edu.icm.cermine.structure.model.BxBounds; /** * @author Krzysztof Rusek */ public class BxBoundsBuilderTest { private static final double EPSILON = 0.001; @Test public void testExpand_bounds() { BxBoundsBuilder builder = new BxBoundsBuilder(); builder.expand(new BxBounds(0, 0, 1, 1)); assertBounds(0, 0, 1, 1, builder.getBounds()); builder.expand(new BxBounds(1, 1, 4, 5)); assertBounds(0, 0, 5, 6, builder.getBounds()); builder.expand(new BxBounds(3, 3, 2, 2)); assertBounds(0, 0, 5, 6, builder.getBounds()); } private static void assertBounds(double x, double y, double w, double h, BxBounds bounds) { assertTrue(bounds != null); assertEquals(x, bounds.getX(), EPSILON); assertEquals(y, bounds.getY(), EPSILON); assertEquals(w, bounds.getWidth(), EPSILON); assertEquals(h, bounds.getHeight(), EPSILON); } }
1,839
34.384615
95
java
CERMINE
CERMINE-master/cermine-impl/src/test/java/pl/edu/icm/cermine/structure/transformers/BxDocumentToMinimalTrueVizWriterTest.java
/** * This file is part of CERMINE project. * Copyright (c) 2011-2018 ICM-UW * * CERMINE is free software: you can redistribute it and/or modify * it under the terms of the GNU Affero General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * CERMINE is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU Affero General Public License for more details. * * You should have received a copy of the GNU Affero General Public License * along with CERMINE. If not, see <http://www.gnu.org/licenses/>. */ package pl.edu.icm.cermine.structure.transformers; import com.google.common.collect.Lists; import java.io.StringReader; import java.util.Locale; import javax.xml.xpath.XPath; import javax.xml.xpath.XPathConstants; import javax.xml.xpath.XPathExpressionException; import javax.xml.xpath.XPathFactory; import static org.junit.Assert.assertEquals; import org.junit.Before; import org.junit.Test; import org.w3c.dom.Document; import org.xml.sax.InputSource; import pl.edu.icm.cermine.structure.model.*; /** * @author Krzysztof Rusek */ public class BxDocumentToMinimalTrueVizWriterTest { private XPath xpath; private BxDocument bxDoc; private Document domDoc; @Before public void initialize() throws Exception { xpath = XPathFactory.newInstance().newXPath(); bxDoc = getBxDocument(); domDoc = bxToDom(bxDoc); } private void assertXpath(String expr, String expected) throws XPathExpressionException { String actual = (String) xpath.evaluate(expr, domDoc, XPathConstants.STRING); assertEquals(expected, actual); } private void assertXpathNoCase(String expr, String expected) throws XPathExpressionException { String actual = (String) xpath.evaluate(expr, domDoc, XPathConstants.STRING); assertEquals(expected.toLowerCase(Locale.ENGLISH), actual.toLowerCase(Locale.ENGLISH)); } private void assertXpath(String expr, double expected) throws XPathExpressionException { Double actual = (Double) xpath.evaluate(expr, domDoc, XPathConstants.NUMBER); assertEquals(expected, actual, 0.00001); } private BxDocument getBxDocument() { BxWord w = new BxWord(); w.setBounds(new BxBounds(0, 0, 1, 1)); w.addChunk(new BxChunk(new BxBounds(0, 0, 1, 1), "a")); w.addChunk(new BxChunk(new BxBounds(0, 0, 1, 1), "b")); BxLine l = new BxLine(); l.setBounds(new BxBounds(0, 0, 1, 1)); l.addWord(w); BxZone z = new BxZone(); z.setBounds(new BxBounds(10, 20, 30, 45)); z.setLabel(BxZoneLabel.MET_AUTHOR); z.addLine(l); BxPage p = new BxPage(); p.setBounds(new BxBounds(0, 0, 100, 100)); p.addZone(z); BxPage p2 = new BxPage(); p2.addZone(new BxZone().setLabel(BxZoneLabel.MET_ABSTRACT)); p2.addZone(new BxZone().setLabel(BxZoneLabel.MET_AFFILIATION)); p2.addZone(new BxZone().setLabel(BxZoneLabel.MET_AUTHOR)); p2.addZone(new BxZone().setLabel(BxZoneLabel.BODY_CONTENT)); p2.addZone(new BxZone().setLabel(BxZoneLabel.BODY_HEADING)); p2.addZone(new BxZone().setLabel(BxZoneLabel.MET_TITLE)); p2.addZone(new BxZone().setLabel(BxZoneLabel.OTH_UNKNOWN)); p2.addZone(new BxZone()); BxDocument doc = new BxDocument(); doc.addPage(p); doc.addPage(p2); return doc; } private Document bxToDom(BxDocument doc) throws Exception { BxDocumentToTrueVizWriter writer = new BxDocumentToTrueVizWriter(); String out = writer.write(Lists.newArrayList(doc), BxDocumentToTrueVizWriter.MINIMAL_OUTPUT_SIZE); return TrueVizUtils.newDocumentBuilder(true).parse(new InputSource(new StringReader(out))); } @Test public void testAppendCharacter() throws Exception { assertXpath("count(/Document/Page[1]/Zone[1]/Line[1]/Word[1]/Character[1]/CharacterCorners)", 1); assertXpath("count(/Document/Page[1]/Zone[1]/Line[1]/Word[1]/Character[1]/CharacterID)", 1); assertXpath("count(/Document/Page[1]/Zone[1]/Line[1]/Word[1]/Character[1]/CharacterNext)", 1); assertXpath("string(/Document/Page[1]/Zone[1]/Line[1]/Word[1]/Character[1]/GT_Text/@Value)", "a"); assertXpath("string(/Document/Page[1]/Zone[1]/Line[1]/Word[1]/Character[2]/GT_Text/@Value)", "b"); } @Test public void testAppendWord() throws Exception { assertXpath("count(/Document/Page[1]/Zone[1]/Line[1]/Word[1]/WordCorners)", 1); assertXpath("count(/Document/Page[1]/Zone[1]/Line[1]/Word[1]/WordID)", 1); assertXpath("count(/Document/Page[1]/Zone[1]/Line[1]/Word[1]/WordNext)", 1); assertXpath("count(/Document/Page[1]/Zone[1]/Line[1]/Word[1]/WordNumChars)", 1); assertXpath("count(/Document/Page[1]/Zone[1]/Line[1]/Word[1]/Character)", 2); } @Test public void testAppendLine() throws Exception { assertXpath("count(/Document/Page[1]/Zone[1]/Line[1]/LineCorners)", 1); assertXpath("count(/Document/Page[1]/Zone[1]/Line[1]/LineID)", 1); assertXpath("count(/Document/Page[1]/Zone[1]/Line[1]/LineNext)", 1); assertXpath("count(/Document/Page[1]/Zone[1]/Line[1]/LineNumChars)", 1); assertXpath("count(/Document/Page[1]/Zone[1]/Line[1]/Word)", 1); } @Test public void testAppendZone() throws Exception { assertXpath("count(/Document/Page[1]/Zone[1]/ZoneCorners)", 1); assertXpath("count(/Document/Page[1]/Zone[1]/Classification)", 1); assertXpathNoCase("string(/Document/Page[1]/Zone[1]/Classification/Category/@Value)", "Author"); assertXpath("count(/Document/Page[1]/Zone[1]/ZoneID)", 1); assertXpath("count(/Document/Page[1]/Zone[1]/ZoneInsets)", 1); assertXpath("count(/Document/Page[1]/Zone[1]/ZoneInsets/@Left)", 1); assertXpath("count(/Document/Page[1]/Zone[1]/ZoneInsets/@Right)", 1); assertXpath("count(/Document/Page[1]/Zone[1]/ZoneInsets/@Top)", 1); assertXpath("count(/Document/Page[1]/Zone[1]/ZoneInsets/@Bottom)", 1); assertXpath("count(/Document/Page[1]/Zone[1]/ZoneNext)", 1); assertXpath("count(/Document/Page[1]/Zone[1]/ZoneLines)", 1); assertXpath("count(/Document/Page[1]/Zone[1]/Line)", 1); assertXpathNoCase("string(/Document/Page[2]/Zone[1]/Classification/Category/@Value)", "abstract"); assertXpathNoCase("string(/Document/Page[2]/Zone[2]/Classification/Category/@Value)", "affiliation"); assertXpathNoCase("string(/Document/Page[2]/Zone[3]/Classification/Category/@Value)", "author"); assertXpathNoCase("string(/Document/Page[2]/Zone[4]/Classification/Category/@Value)", "body_content"); assertXpathNoCase("string(/Document/Page[2]/Zone[5]/Classification/Category/@Value)", "heading"); assertXpathNoCase("string(/Document/Page[2]/Zone[6]/Classification/Category/@Value)", "title"); assertXpathNoCase("string(/Document/Page[2]/Zone[7]/Classification/Category/@Value)", "unknown"); assertXpathNoCase("count(/Document/Page[2]/Zone[8]/Classification)", "0"); } @Test public void testAppendPage() throws Exception { assertXpath("count(/Document/Page[1]/Zone)", 1); assertXpath("count(/Document/Page[1]/PageID)", 1); assertXpath("count(/Document/Page[1]/PageType)", 1); assertXpath("count(/Document/Page[1]/PageNumber)", 1); assertXpath("count(/Document/Page[1]/PageColumns)", 1); assertXpath("count(/Document/Page[1]/PageNext)", 1); assertXpath("count(/Document/Page[1]/PageZones)", 1); } @Test public void testAppendBounds() throws Exception { assertXpath("number(/Document/Page[1]/Zone[1]/ZoneCorners/Vertex[1]/@x)", 10); assertXpath("number(/Document/Page[1]/Zone[1]/ZoneCorners/Vertex[1]/@y)", 20); assertXpath("number(/Document/Page[1]/Zone[1]/ZoneCorners/Vertex[2]/@x)", 40); assertXpath("number(/Document/Page[1]/Zone[1]/ZoneCorners/Vertex[2]/@y)", 65); assertXpath("count(/Document/Page[2]/Zone[1]/ZoneCorners)", 1); } }
8,339
42.894737
110
java
CERMINE
CERMINE-master/cermine-impl/src/test/java/pl/edu/icm/cermine/structure/transformers/BxDocumentToTrueVizWriterTest.java
/** * This file is part of CERMINE project. * Copyright (c) 2011-2018 ICM-UW * * CERMINE is free software: you can redistribute it and/or modify * it under the terms of the GNU Affero General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * CERMINE is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU Affero General Public License for more details. * * You should have received a copy of the GNU Affero General Public License * along with CERMINE. If not, see <http://www.gnu.org/licenses/>. */ package pl.edu.icm.cermine.structure.transformers; import com.google.common.collect.Lists; import java.io.StringReader; import java.util.Locale; import javax.xml.xpath.XPath; import javax.xml.xpath.XPathConstants; import javax.xml.xpath.XPathExpressionException; import javax.xml.xpath.XPathFactory; import static org.junit.Assert.assertEquals; import org.junit.Before; import org.junit.Test; import org.w3c.dom.Document; import org.xml.sax.InputSource; import pl.edu.icm.cermine.structure.model.*; /** * @author Krzysztof Rusek */ public class BxDocumentToTrueVizWriterTest { private XPath xpath; private BxDocument bxDoc; private Document domDoc; @Before public void initialize() throws Exception { xpath = XPathFactory.newInstance().newXPath(); bxDoc = getBxDocument(); domDoc = bxToDom(bxDoc); } private void assertXpath(String expr, String expected) throws XPathExpressionException { String actual = (String) xpath.evaluate(expr, domDoc, XPathConstants.STRING); assertEquals(expected, actual); } private void assertXpathNoCase(String expr, String expected) throws XPathExpressionException { String actual = (String) xpath.evaluate(expr, domDoc, XPathConstants.STRING); assertEquals(expected.toLowerCase(Locale.ENGLISH), actual.toLowerCase(Locale.ENGLISH)); } private void assertXpath(String expr, double expected) throws XPathExpressionException { Double actual = (Double) xpath.evaluate(expr, domDoc, XPathConstants.NUMBER); assertEquals(expected, actual, 0.00001); } private BxDocument getBxDocument() { BxWord w = new BxWord(); w.setBounds(new BxBounds(0, 0, 1, 1)); BxChunk ch1 = new BxChunk(new BxBounds(0, 0, 1, 1), "a"); ch1.setFontName("font-1"); BxChunk ch2 = new BxChunk(new BxBounds(0, 0, 1, 1), "b"); ch2.setFontName("font-2"); w.addChunk(ch1); w.addChunk(ch2); BxLine l = new BxLine(); l.setBounds(new BxBounds(0, 0, 1, 1)); l.addWord(w); BxZone z = new BxZone(); z.setBounds(new BxBounds(10, 20, 30, 45)); z.setLabel(BxZoneLabel.MET_AUTHOR); z.addLine(l); BxPage p = new BxPage(); p.setBounds(new BxBounds(0, 0, 100, 100)); p.addZone(z); BxPage p2 = new BxPage(); p2.addZone(new BxZone().setLabel(BxZoneLabel.MET_ABSTRACT)); p2.addZone(new BxZone().setLabel(BxZoneLabel.MET_AFFILIATION)); p2.addZone(new BxZone().setLabel(BxZoneLabel.MET_AUTHOR)); p2.addZone(new BxZone().setLabel(BxZoneLabel.BODY_CONTENT)); p2.addZone(new BxZone().setLabel(BxZoneLabel.BODY_HEADING)); p2.addZone(new BxZone().setLabel(BxZoneLabel.MET_TITLE)); p2.addZone(new BxZone().setLabel(BxZoneLabel.OTH_UNKNOWN)); p2.addZone(new BxZone()); BxDocument doc = new BxDocument(); doc.addPage(p); doc.addPage(p2); return doc; } private Document bxToDom(BxDocument doc) throws Exception { BxDocumentToTrueVizWriter writer = new BxDocumentToTrueVizWriter(); String out = writer.write(Lists.newArrayList(doc)); return TrueVizUtils.newDocumentBuilder(true).parse(new InputSource(new StringReader(out))); } @Test public void testAppendCharacter() throws Exception { assertXpath("count(/Document/Page[1]/Zone[1]/Line[1]/Word[1]/Character[1]/CharacterCorners)", 1); assertXpath("count(/Document/Page[1]/Zone[1]/Line[1]/Word[1]/Character[1]/CharacterID)", 1); assertXpath("count(/Document/Page[1]/Zone[1]/Line[1]/Word[1]/Character[1]/CharacterNext)", 1); assertXpath("string(/Document/Page[1]/Zone[1]/Line[1]/Word[1]/Character[1]/GT_Text/@Value)", "a"); assertXpath("string(/Document/Page[1]/Zone[1]/Line[1]/Word[1]/Character[2]/GT_Text/@Value)", "b"); assertXpath("string(/Document/Page[1]/Zone[1]/Line[1]/Word[1]/Character[1]/Font/@Type)", "font-1"); assertXpath("string(/Document/Page[1]/Zone[1]/Line[1]/Word[1]/Character[2]/Font/@Type)", "font-2"); } @Test public void testAppendWord() throws Exception { assertXpath("count(/Document/Page[1]/Zone[1]/Line[1]/Word[1]/WordCorners)", 1); assertXpath("count(/Document/Page[1]/Zone[1]/Line[1]/Word[1]/WordID)", 1); assertXpath("count(/Document/Page[1]/Zone[1]/Line[1]/Word[1]/WordNext)", 1); assertXpath("count(/Document/Page[1]/Zone[1]/Line[1]/Word[1]/WordNumChars)", 1); assertXpath("count(/Document/Page[1]/Zone[1]/Line[1]/Word[1]/Character)", 2); } @Test public void testAppendLine() throws Exception { assertXpath("count(/Document/Page[1]/Zone[1]/Line[1]/LineCorners)", 1); assertXpath("count(/Document/Page[1]/Zone[1]/Line[1]/LineID)", 1); assertXpath("count(/Document/Page[1]/Zone[1]/Line[1]/LineNext)", 1); assertXpath("count(/Document/Page[1]/Zone[1]/Line[1]/LineNumChars)", 1); assertXpath("count(/Document/Page[1]/Zone[1]/Line[1]/Word)", 1); } @Test public void testAppendZone() throws Exception { assertXpath("count(/Document/Page[1]/Zone[1]/ZoneCorners)", 1); assertXpath("count(/Document/Page[1]/Zone[1]/Classification)", 1); assertXpathNoCase("string(/Document/Page[1]/Zone[1]/Classification/Category/@Value)", "Author"); assertXpath("count(/Document/Page[1]/Zone[1]/ZoneID)", 1); assertXpath("count(/Document/Page[1]/Zone[1]/ZoneInsets)", 1); assertXpath("count(/Document/Page[1]/Zone[1]/ZoneInsets/@Left)", 1); assertXpath("count(/Document/Page[1]/Zone[1]/ZoneInsets/@Right)", 1); assertXpath("count(/Document/Page[1]/Zone[1]/ZoneInsets/@Top)", 1); assertXpath("count(/Document/Page[1]/Zone[1]/ZoneInsets/@Bottom)", 1); assertXpath("count(/Document/Page[1]/Zone[1]/ZoneNext)", 1); assertXpath("count(/Document/Page[1]/Zone[1]/ZoneLines)", 1); assertXpath("count(/Document/Page[1]/Zone[1]/Line)", 1); assertXpathNoCase("string(/Document/Page[2]/Zone[1]/Classification/Category/@Value)", "abstract"); assertXpathNoCase("string(/Document/Page[2]/Zone[2]/Classification/Category/@Value)", "affiliation"); assertXpathNoCase("string(/Document/Page[2]/Zone[3]/Classification/Category/@Value)", "author"); assertXpathNoCase("string(/Document/Page[2]/Zone[4]/Classification/Category/@Value)", "body_content"); assertXpathNoCase("string(/Document/Page[2]/Zone[5]/Classification/Category/@Value)", "heading"); assertXpathNoCase("string(/Document/Page[2]/Zone[6]/Classification/Category/@Value)", "title"); assertXpathNoCase("string(/Document/Page[2]/Zone[7]/Classification/Category/@Value)", "unknown"); assertXpathNoCase("count(/Document/Page[2]/Zone[8]/Classification)", "0"); } @Test public void testAppendPage() throws Exception { assertXpath("count(/Document/Page[1]/Zone)", 1); assertXpath("count(/Document/Page[1]/PageID)", 1); assertXpath("count(/Document/Page[1]/PageType)", 1); assertXpath("count(/Document/Page[1]/PageNumber)", 1); assertXpath("count(/Document/Page[1]/PageColumns)", 1); assertXpath("count(/Document/Page[1]/PageNext)", 1); assertXpath("count(/Document/Page[1]/PageZones)", 1); } @Test public void testAppendBounds() throws Exception { assertXpath("number(/Document/Page[1]/Zone[1]/ZoneCorners/Vertex[1]/@x)", 10); assertXpath("number(/Document/Page[1]/Zone[1]/ZoneCorners/Vertex[1]/@y)", 20); assertXpath("number(/Document/Page[1]/Zone[1]/ZoneCorners/Vertex[2]/@x)", 40); assertXpath("number(/Document/Page[1]/Zone[1]/ZoneCorners/Vertex[2]/@y)", 20); assertXpath("number(/Document/Page[1]/Zone[1]/ZoneCorners/Vertex[3]/@x)", 40); assertXpath("number(/Document/Page[1]/Zone[1]/ZoneCorners/Vertex[3]/@y)", 65); assertXpath("number(/Document/Page[1]/Zone[1]/ZoneCorners/Vertex[4]/@x)", 10); assertXpath("number(/Document/Page[1]/Zone[1]/ZoneCorners/Vertex[4]/@y)", 65); assertXpath("count(/Document/Page[2]/Zone[1]/ZoneCorners)", 1); } }
8,984
43.261084
110
java
CERMINE
CERMINE-master/cermine-impl/src/test/java/pl/edu/icm/cermine/structure/transformers/TrueVizToBxDocumentReaderTest.java
/** * This file is part of CERMINE project. * Copyright (c) 2011-2018 ICM-UW * * CERMINE is free software: you can redistribute it and/or modify * it under the terms of the GNU Affero General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * CERMINE is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU Affero General Public License for more details. * * You should have received a copy of the GNU Affero General Public License * along with CERMINE. If not, see <http://www.gnu.org/licenses/>. */ package pl.edu.icm.cermine.structure.transformers; import com.google.common.collect.Lists; import java.io.File; import java.io.IOException; import java.io.InputStream; import java.io.InputStreamReader; import java.net.URISyntaxException; import java.net.URL; import java.util.HashSet; import java.util.List; import java.util.Set; import java.util.zip.ZipFile; import javax.xml.parsers.ParserConfigurationException; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertTrue; import org.junit.Test; import org.xml.sax.SAXException; import pl.edu.icm.cermine.exception.TransformationException; import pl.edu.icm.cermine.structure.model.*; /** * @author Krzysztof Rusek * @author Kuba Jurkiewicz * @author Pawel Szostek */ public class TrueVizToBxDocumentReaderTest { static String PATH = "/pl/edu/icm/cermine/structure/"; @Test public void testImporter() throws IOException, ParserConfigurationException, SAXException, TransformationException { BxPage page = new TrueVizToBxDocumentReader().read(new InputStreamReader(TrueVizToBxDocumentReaderTest.class.getResourceAsStream("/pl/edu/icm/cermine/structure/imports/MargImporterTest1.xml"), "UTF-8")).get(0); boolean contains = false; boolean rightText = false; boolean rightSize = false; for (BxZone zone : page) { if (zone.getLabel() != null) { if (zone.getLabel().equals(BxZoneLabel.MET_AUTHOR)) { contains = true; if (zone.toText().trim().equalsIgnoreCase("Howard M Schachter Ba Pham Jim King tt\nStephanie Langford David Moher".trim())) { rightText = true; } if (zone.getBounds().getX() == 72 && zone.getBounds().getY() == 778 && zone.getBounds().getWidth() == 989 && zone.getBounds().getHeight() == 122) { rightSize = true; } } } } assertTrue(contains); assertTrue(rightText); assertTrue(rightSize); BxWord word = page.getChild(0).getChild(0).getChild(0); assertEquals("font-1", word.getChild(0).getFontName()); assertEquals("font-2", word.getChild(1).getFontName()); } private BxDocument getDocumentFromZipFile(String zipFilename, String filename) throws TransformationException, IOException, URISyntaxException { URL url = TrueVizToBxDocumentReaderTest.class.getResource(PATH + zipFilename); ZipFile zipFile = null; InputStream is = null; InputStreamReader isr = null; try { zipFile = new ZipFile(new File(url.toURI())); is = zipFile.getInputStream(zipFile.getEntry(filename)); isr = new InputStreamReader(is, "UTF-8"); TrueVizToBxDocumentReader reader = new TrueVizToBxDocumentReader(); BxDocument doc = new BxDocument().setPages(reader.read(isr)); return doc; } finally { if (zipFile != null) { zipFile.close(); } if (is != null) { is.close(); } if (isr != null) { isr.close(); } } } @Test public void testAllNextsAreSet1() throws TransformationException, IOException, URISyntaxException { BxDocument orderedDoc = getDocumentFromZipFile("roa_test.zip", "1748717X.xml.out"); Integer nextNulls = 0; for (BxPage page : orderedDoc.asPages()) { if (page.getNext() == null) { ++nextNulls; } } assertEquals(nextNulls, Integer.valueOf(1)); nextNulls = 0; for (BxZone zone : orderedDoc.asZones()) { if (zone.getNext() == null) { ++nextNulls; } } assertEquals(nextNulls, Integer.valueOf(1)); nextNulls = 0; for (BxLine line : orderedDoc.asLines()) { if (line.getNext() == null) { ++nextNulls; } } assertEquals(nextNulls, Integer.valueOf(1)); nextNulls = 0; for (BxWord word : orderedDoc.asWords()) { if (word.getNext() == null) { ++nextNulls; } } assertEquals(nextNulls, Integer.valueOf(1)); nextNulls = 0; for (BxChunk chunk : orderedDoc.asChunks()) { if (chunk.getNext() == null) { ++nextNulls; } } assertEquals(nextNulls, Integer.valueOf(1)); } private <A extends Indexable> Integer countChainedElements(List<A> list) throws TransformationException, IOException { Set<A> nextSet = new HashSet<A>(); for (A elem : list) { A next = (A) elem.getNext(); if (next != null && list.contains(next)) { nextSet.add(next); } } return nextSet.size(); } @Test public void testChainedElementsEven() throws TransformationException, IOException, URISyntaxException { BxDocument doc = getDocumentFromZipFile("roa_test.zip", "1748717X.xml.out"); List<BxPage> pages = Lists.newArrayList(doc); List<BxZone> zones = Lists.newArrayList(doc.asZones()); List<BxLine> lines = Lists.newArrayList(doc.asLines()); List<BxWord> words = Lists.newArrayList(doc.asWords()); List<BxChunk> chunks = Lists.newArrayList(doc.asChunks()); assertEquals(countChainedElements(pages), Integer.valueOf(pages.size() - 1)); assertEquals(countChainedElements(zones), Integer.valueOf(zones.size() - 1)); assertEquals(countChainedElements(lines), Integer.valueOf(lines.size() - 1)); assertEquals(countChainedElements(words), Integer.valueOf(words.size() - 1)); assertEquals(countChainedElements(chunks), Integer.valueOf(chunks.size() - 1)); } }
6,700
37.511494
218
java
CERMINE
CERMINE-master/cermine-impl/src/test/java/pl/edu/icm/cermine/parsing/tools/GrmmUtilsTest.java
/** * This file is part of CERMINE project. * Copyright (c) 2011-2018 ICM-UW * * CERMINE is free software: you can redistribute it and/or modify * it under the terms of the GNU Affero General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * CERMINE is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU Affero General Public License for more details. * * You should have received a copy of the GNU Affero General Public License * along with CERMINE. If not, see <http://www.gnu.org/licenses/>. */ package pl.edu.icm.cermine.parsing.tools; import java.util.Arrays; import static org.junit.Assert.assertEquals; import org.junit.Test; import pl.edu.icm.cermine.metadata.model.AffiliationLabel; import pl.edu.icm.cermine.parsing.model.Token; /** * @author Bartosz Tarnawski */ public class GrmmUtilsTest { @Test public void testToGrmmInput1() { String expected = "TEXT ---- F1 F2 F3"; String actual = GrmmUtils.toGrmmInput("TEXT", Arrays.asList("F1", "F2", "F3")); assertEquals(expected, actual); } @Test public void testToGrmmInput2() { Token<AffiliationLabel> token1 = new Token<AffiliationLabel>("sometext"); token1.setLabel(AffiliationLabel.TEXT); token1.getFeatures().add("F1"); token1.getFeatures().add("F2"); Token<AffiliationLabel> token2 = new Token<AffiliationLabel>("sometext2"); token2.setLabel(AffiliationLabel.TEXT); token2.getFeatures().add("F3"); String expected = "TEXT ---- F1 F2 Start@-1 F3@1\n" + "TEXT ---- F3 F1@-1 F2@-1 End@1\n"; String actual = GrmmUtils.toGrmmInput(Arrays.asList(token1, token2), 1); assertEquals(expected, actual); } }
1,950
33.839286
87
java
CERMINE
CERMINE-master/cermine-impl/src/test/java/pl/edu/icm/cermine/parsing/features/IsRareFeatureTest.java
/** * This file is part of CERMINE project. * Copyright (c) 2011-2018 ICM-UW * * CERMINE is free software: you can redistribute it and/or modify * it under the terms of the GNU Affero General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * CERMINE is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU Affero General Public License for more details. * * You should have received a copy of the GNU Affero General Public License * along with CERMINE. If not, see <http://www.gnu.org/licenses/>. */ package pl.edu.icm.cermine.parsing.features; import java.util.Arrays; import java.util.List; import org.junit.Test; import pl.edu.icm.cermine.metadata.model.AffiliationLabel; import pl.edu.icm.cermine.metadata.model.DocumentAffiliation; import pl.edu.icm.cermine.parsing.model.Token; import static org.junit.Assert.assertEquals; /** * @author Bartosz Tarnawski */ public class IsRareFeatureTest { private static final List<String> COMMON_WORDS = Arrays.asList("pies", "kot", "kot1"); private static final IsRareFeature FEATURE_CASE_SENSITIVE = new IsRareFeature(COMMON_WORDS, true); private static final IsRareFeature FEATURE_IGNORE_CASE = new IsRareFeature(COMMON_WORDS, false); @Test public void testCalculateFeaturePredicate() { Token<AffiliationLabel> inSet = new Token<AffiliationLabel>("kot"); Token<AffiliationLabel> lowerInSet = new Token<AffiliationLabel>("KOT"); Token<AffiliationLabel> notInSet = new Token<AffiliationLabel>("SZCZUR"); Token<AffiliationLabel> notWord = new Token<AffiliationLabel>("kot1"); DocumentAffiliation aff = new DocumentAffiliation(""); assertEquals(false, FEATURE_CASE_SENSITIVE.calculateFeaturePredicate(inSet, aff)); assertEquals(true, FEATURE_CASE_SENSITIVE.calculateFeaturePredicate(lowerInSet, aff)); assertEquals(true, FEATURE_CASE_SENSITIVE.calculateFeaturePredicate(notInSet, aff)); assertEquals(false, FEATURE_CASE_SENSITIVE.calculateFeaturePredicate(notWord, aff)); assertEquals(false, FEATURE_IGNORE_CASE.calculateFeaturePredicate(inSet, aff)); assertEquals(false, FEATURE_IGNORE_CASE.calculateFeaturePredicate(lowerInSet, aff)); assertEquals(true, FEATURE_IGNORE_CASE.calculateFeaturePredicate(notInSet, aff)); assertEquals(false, FEATURE_IGNORE_CASE.calculateFeaturePredicate(notWord, aff)); } }
2,618
45.767857
102
java
CERMINE
CERMINE-master/cermine-impl/src/test/java/pl/edu/icm/cermine/parsing/features/WordFeatureTest.java
/** * This file is part of CERMINE project. * Copyright (c) 2011-2018 ICM-UW * * CERMINE is free software: you can redistribute it and/or modify * it under the terms of the GNU Affero General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * CERMINE is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU Affero General Public License for more details. * * You should have received a copy of the GNU Affero General Public License * along with CERMINE. If not, see <http://www.gnu.org/licenses/>. */ package pl.edu.icm.cermine.parsing.features; import java.util.Arrays; import java.util.List; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertNull; import org.junit.Test; import pl.edu.icm.cermine.metadata.model.AffiliationLabel; import pl.edu.icm.cermine.metadata.model.DocumentAffiliation; import pl.edu.icm.cermine.parsing.model.Token; /** * @author Bartosz Tarnawski */ public class WordFeatureTest { @Test public void testComputeFeature() { String word = "BabaMaKota"; String notWord = "123"; List<Token<AffiliationLabel>> tokens = Arrays.asList( new Token<AffiliationLabel>(word), new Token<AffiliationLabel>(notWord) ); WordFeatureCalculator instance = new WordFeatureCalculator( Arrays.<BinaryTokenFeatureCalculator>asList(new IsNumberFeature()), true); DocumentAffiliation aff = new DocumentAffiliation(""); assertEquals("W=babamakota", instance.calculateFeatureValue(tokens.get(0), aff)); assertNull(instance.calculateFeatureValue(tokens.get(1), aff)); instance = new WordFeatureCalculator( Arrays.<BinaryTokenFeatureCalculator>asList(new IsNumberFeature()), false); assertEquals("W=BabaMaKota", instance.calculateFeatureValue(tokens.get(0), aff)); assertNull(instance.calculateFeatureValue(tokens.get(1), aff)); } }
2,171
35.813559
91
java
CERMINE
CERMINE-master/cermine-impl/src/test/java/pl/edu/icm/cermine/parsing/model/TokenTest.java
/** * This file is part of CERMINE project. * Copyright (c) 2011-2018 ICM-UW * * CERMINE is free software: you can redistribute it and/or modify * it under the terms of the GNU Affero General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * CERMINE is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU Affero General Public License for more details. * * You should have received a copy of the GNU Affero General Public License * along with CERMINE. If not, see <http://www.gnu.org/licenses/>. */ package pl.edu.icm.cermine.parsing.model; import java.util.Arrays; import java.util.List; import static org.junit.Assert.assertFalse; import static org.junit.Assert.assertTrue; import org.junit.Test; import pl.edu.icm.cermine.metadata.model.AffiliationLabel; /** * @author Bartosz Tarnawski */ public class TokenTest { @Test public void testSequenceEquals() { List<Token<AffiliationLabel>> sequence1 = Arrays.asList( new Token<AffiliationLabel>("Bob", 1, 23), new Token<AffiliationLabel>("Hop", 1, 23) ); List<Token<AffiliationLabel>> sequence2 = Arrays.asList( new Token<AffiliationLabel>("bob", 19, 23), new Token<AffiliationLabel>("hoP", 11, 87) ); List<Token<AffiliationLabel>> sequence3 = Arrays.asList( new Token<AffiliationLabel>("Bobb", 1, 23), new Token<AffiliationLabel>("Hop", 1, 23) ); List<Token<AffiliationLabel>> sequence4 = Arrays.asList( new Token<AffiliationLabel>("Bob", 19, 23) ); assertTrue(Token.sequenceTextEquals(sequence1, sequence2, false)); assertFalse(Token.sequenceTextEquals(sequence1, sequence2, true)); assertFalse(Token.sequenceTextEquals(sequence1, sequence3, false)); assertFalse(Token.sequenceTextEquals(sequence1, sequence4, false)); } }
2,137
37.178571
78
java
CERMINE
CERMINE-master/cermine-impl/src/test/java/pl/edu/icm/cermine/content/model/DocumentContentStructureTest.java
/** * This file is part of CERMINE project. * Copyright (c) 2011-2018 ICM-UW * * CERMINE is free software: you can redistribute it and/or modify * it under the terms of the GNU Affero General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * CERMINE is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU Affero General Public License for more details. * * You should have received a copy of the GNU Affero General Public License * along with CERMINE. If not, see <http://www.gnu.org/licenses/>. */ package pl.edu.icm.cermine.content.model; import java.io.IOException; import java.io.InputStream; import java.io.InputStreamReader; import java.net.URISyntaxException; import org.jdom.JDOMException; import static org.junit.Assert.assertEquals; import org.junit.Before; import org.junit.Test; import pl.edu.icm.cermine.content.transformers.HTMLToDocContentReader; import pl.edu.icm.cermine.exception.TransformationException; import pl.edu.icm.cermine.tools.transformers.FormatToModelReader; /** * @author Dominika Tkaczyk (d.tkaczyk@icm.edu.pl) */ public class DocumentContentStructureTest { String modelFilePath = "/pl/edu/icm/cermine/content/model/model.xml"; FormatToModelReader<ContentStructure> reader; ContentStructure structure; @Before public void setUp() throws JDOMException, IOException, TransformationException, URISyntaxException { reader = new HTMLToDocContentReader(); InputStream is = DocumentContentStructureTest.class.getResourceAsStream(modelFilePath); InputStreamReader isr = new InputStreamReader(is, "UTF-8"); structure = reader.read(isr); } @Test public void structureTest() { assertEquals(4, structure.getSections().size()); assertEquals("1. BACKGROUND", structure.getSections().get(0).getTitle()); DocumentSection firstLevelStruct = structure.getSections().get(1); assertEquals(1, firstLevelStruct.getLevel()); assertEquals("2. DATA MODELING AND MAPPING", firstLevelStruct.getTitle()); assertEquals(3, firstLevelStruct.getSubsections().size()); assertEquals("2.1 Lined Data", firstLevelStruct.getSubsections().get(0).getTitle()); } }
2,485
35.558824
104
java
CERMINE
CERMINE-master/cermine-impl/src/test/java/pl/edu/icm/cermine/content/transformers/BxToDocContentStructConverterTest.java
/** * This file is part of CERMINE project. * Copyright (c) 2011-2018 ICM-UW * * CERMINE is free software: you can redistribute it and/or modify * it under the terms of the GNU Affero General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * CERMINE is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU Affero General Public License for more details. * * You should have received a copy of the GNU Affero General Public License * along with CERMINE. If not, see <http://www.gnu.org/licenses/>. */ package pl.edu.icm.cermine.content.transformers; import java.io.IOException; import java.net.URISyntaxException; import java.util.ArrayList; import java.util.List; import org.custommonkey.xmlunit.Diff; import org.custommonkey.xmlunit.XMLUnit; import org.jdom.JDOMException; import static org.junit.Assert.assertTrue; import org.junit.Before; import org.junit.Test; import org.xml.sax.SAXException; import pl.edu.icm.cermine.content.model.BxContentStructure; import pl.edu.icm.cermine.content.model.BxContentStructure.BxDocContentPart; import pl.edu.icm.cermine.content.model.ContentStructure; import pl.edu.icm.cermine.exception.TransformationException; import pl.edu.icm.cermine.structure.model.BxBounds; import pl.edu.icm.cermine.structure.model.BxChunk; import pl.edu.icm.cermine.structure.model.BxLine; import pl.edu.icm.cermine.structure.model.BxWord; /** * @author Dominika Tkaczyk (d.tkaczyk@icm.edu.pl) */ public class BxToDocContentStructConverterTest { private final BxContentToDocContentConverter converter = new BxContentToDocContentConverter(); private final DocContentToHTMLWriter writer = new DocContentToHTMLWriter(); private static final String expectedHTML = "<html><H1>1. Section</H1><p>par1</p><p>par2</p>" +"<H1>2. Section</H1><p>par3</p>" +"<H2>2.1. Subsection</H2>" +"<H2>2.2. Subsection</H2><p>par4</p><p>par5</p>" +"<H3>2.2.1. Subsubsection</H3><p>par6</p><p>par7</p>" +"<H1>3. Section</H1><p>par8</p><p>par9</p><p>par10</p></html>"; private final BxContentStructure bxDocStruct = new BxContentStructure(); @Before public void setUp() throws JDOMException, IOException, TransformationException, URISyntaxException { BxLine line1 = constructLine("1. Section"); BxLine line2 = constructLine("par1"); BxLine line3 = constructLine("par2"); BxLine line4 = constructLine("2. Section"); BxLine line5 = constructLine("par3"); BxLine line6 = constructLine("2.1. Subsection"); BxLine line7 = constructLine("2.2. Subsection"); BxLine line8 = constructLine("par4"); BxLine line9 = constructLine("par5"); BxLine line10 = constructLine("2.2.1. Subsubsection"); BxLine line11 = constructLine("par6"); BxLine line12 = constructLine("par7"); BxLine line13 = constructLine("3. Section"); BxLine line14 = constructLine("par8"); BxLine line15 = constructLine("par9"); BxLine line16 = constructLine("par10"); int[] levelIds = {0, 0, 1, 1, 2, 0}; bxDocStruct.addFirstHeaderLine(null, line1); bxDocStruct.addContentLine(line1, line2); bxDocStruct.addContentLine(line1, line3); bxDocStruct.addFirstHeaderLine(null, line4); bxDocStruct.addContentLine(line4, line5); bxDocStruct.addFirstHeaderLine(null, line6); bxDocStruct.addFirstHeaderLine(null, line7); bxDocStruct.addContentLine(line7, line8); bxDocStruct.addContentLine(line7, line9); bxDocStruct.addFirstHeaderLine(null, line10); bxDocStruct.addContentLine(line10, line11); bxDocStruct.addContentLine(line10, line12); bxDocStruct.addFirstHeaderLine(null, line13); bxDocStruct.addContentLine(line13, line14); bxDocStruct.addContentLine(line13, line15); bxDocStruct.addContentLine(line13, line16); bxDocStruct.setHeaderLevelIds(levelIds); for (BxDocContentPart part : bxDocStruct.getParts()) { part.setCleanHeaderText(part.getFirstHeaderLine().toText()); List<String> contentTexts = new ArrayList<String>(); for (BxLine contentLine : part.getContentLines()) { contentTexts.add(contentLine.toText()); } part.setCleanContentTexts(contentTexts); } } @Test public void structToXMLTest() throws SAXException, IOException, TransformationException, JDOMException { ContentStructure dcs = converter.convert(bxDocStruct); String dcsHTML = writer.write(dcs); XMLUnit.setIgnoreWhitespace(true); Diff diff = new Diff(expectedHTML, dcsHTML); assertTrue(diff.similar()); } private BxLine constructLine(String text) { BxChunk chunk = new BxChunk(new BxBounds(), text); BxWord word = new BxWord().addChunk(chunk); return new BxLine().addWord(word); } }
5,235
41.225806
108
java
CERMINE
CERMINE-master/cermine-impl/src/test/java/pl/edu/icm/cermine/content/transformers/HTMLDocContentStructureConvertersTest.java
/** * This file is part of CERMINE project. * Copyright (c) 2011-2018 ICM-UW * * CERMINE is free software: you can redistribute it and/or modify * it under the terms of the GNU Affero General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * CERMINE is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU Affero General Public License for more details. * * You should have received a copy of the GNU Affero General Public License * along with CERMINE. If not, see <http://www.gnu.org/licenses/>. */ package pl.edu.icm.cermine.content.transformers; import java.io.File; import java.io.IOException; import java.io.InputStream; import java.io.InputStreamReader; import java.net.URISyntaxException; import org.apache.commons.io.FileUtils; import org.custommonkey.xmlunit.Diff; import org.custommonkey.xmlunit.XMLUnit; import org.jdom.JDOMException; import static org.junit.Assert.assertTrue; import org.junit.Before; import org.junit.Test; import org.xml.sax.SAXException; import pl.edu.icm.cermine.content.model.ContentStructure; import pl.edu.icm.cermine.exception.TransformationException; /** * @author Dominika Tkaczyk (d.tkaczyk@icm.edu.pl) */ public class HTMLDocContentStructureConvertersTest { String modelFilePath = "/pl/edu/icm/cermine/content/model/model.xml"; HTMLToDocContentReader reader; DocContentToHTMLWriter writer; @Before public void setUp() throws JDOMException, IOException, TransformationException, URISyntaxException { reader = new HTMLToDocContentReader(); writer = new DocContentToHTMLWriter(); } @Test public void readerWriterTest() throws URISyntaxException, IOException, TransformationException, SAXException { File file = new File(HTMLDocContentStructureConvertersTest.class.getResource(modelFilePath).toURI()); String expectedHTML = FileUtils.readFileToString(file, "UTF-8"); InputStream is = HTMLDocContentStructureConvertersTest.class.getResourceAsStream(modelFilePath); InputStreamReader isr = new InputStreamReader(is, "UTF-8"); ContentStructure structure = reader.read(isr); String structureHTML = writer.write(structure); XMLUnit.setIgnoreWhitespace(true); Diff diff = new Diff(expectedHTML, structureHTML); assertTrue(diff.similar()); } }
2,587
36.507246
114
java
CERMINE
CERMINE-master/cermine-impl/src/test/java/pl/edu/icm/cermine/content/citations/CitationReferenceFinderTest.java
/** * This file is part of CERMINE project. * Copyright (c) 2011-2018 ICM-UW * * CERMINE is free software: you can redistribute it and/or modify * it under the terms of the GNU Affero General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * CERMINE is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU Affero General Public License for more details. * * You should have received a copy of the GNU Affero General Public License * along with CERMINE. If not, see <http://www.gnu.org/licenses/>. */ package pl.edu.icm.cermine.content.citations; import java.util.ArrayList; import java.util.Arrays; import java.util.Collections; import java.util.Comparator; import java.util.List; import java.util.Set; import org.junit.Test; import pl.edu.icm.cermine.bibref.model.BibEntry; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertTrue; import pl.edu.icm.cermine.bibref.model.BibEntryFieldType; import pl.edu.icm.cermine.bibref.model.BibEntryType; /** * @author Dominika Tkaczyk (d.tkaczyk@icm.edu.pl) */ public class CitationReferenceFinderTest { private static final String DOCUMENT_TEXT1 = "This is a state of the art fragment with absolutely no references whatsoever."; private static final String DOCUMENT_TEXT2 = "This is a typical state of the art fragment. We can reference a single document " + "like this [2] or [ 12]."; private static final String DOCUMENT_TEXT3 = "This is a typical state of the art fragment. Sometimes we use [3,2, 4, 12 ] to " + "reference multiple documents in one place."; private static final String DOCUMENT_TEXT4 = "This is a typical state of the art fragment. To save space, the number can also " + "be given as ranges: [2-4] or [1-5, 7]."; private static final String DOCUMENT_TEXT5 = "This is a typical state of the art fragment. Reference can also be given by " + "author name (Hoeffding, 1963), multiple refs: (Agranovitch and Vishisk, 1964), " + "also multiple references: (Lee et al., 2004; Agranovitch and Vishisk, 1964; " + "Wang et al., 2003)"; private static final String DOCUMENT_TEXT6 = "This is a typical state of the art fragment. We can reference a single document " + "like this (2) or ( 1). Sometimes we use (3,2, 4, 12 ) to reference multiple " + "documents in one place. To save space, the number can also be given as ranges: " + "(2-4) or (1-5, 7)."; private static final BibEntry[] CITATIONS = { new BibEntry().setText(" [12] W. Hoeffding, Probability inequalities for sums of bounded random variables, J. Amer. Statist. Assoc, 58 (1963) 13-30.") .addField(BibEntryFieldType.AUTHOR, "Hoeffding, W.") .addField(BibEntryFieldType.TITLE, "Probability inequalities for sums of bounded random variables") .addField(BibEntryFieldType.JOURNAL, "J. Amer. Statist. Assoc") .addField(BibEntryFieldType.VOLUME, "58") .addField(BibEntryFieldType.YEAR, "1963") .addField(BibEntryFieldType.PAGES, "13--30"), new BibEntry().setText("[2] Agranovitch (M.S.) and Vishisk (M.I.). — Elliptic problems with a parameter and parabolic problems of general type, Russian Math. Surveys, 19, 1964, 53-157.") .addField(BibEntryFieldType.AUTHOR, "Agranovitch, M.S.") .addField(BibEntryFieldType.AUTHOR, "Vishisk, M.I.") .addField(BibEntryFieldType.TITLE, "Elliptic problems with a parameter and parabolic problems of general type") .addField(BibEntryFieldType.JOURNAL, "Russian Math. Surveys") .addField(BibEntryFieldType.VOLUME, "19") .addField(BibEntryFieldType.YEAR, "1964") .addField(BibEntryFieldType.PAGES, "53--157"), new BibEntry().setText("5. M-Y. Wang, X. Wang and D. Guo, A level-set method for structural topology optimization. Comput. Methods Appl. Mech. Engrg, 192 (2003) 227–246.") .addField(BibEntryFieldType.AUTHOR, "Wang, M-Y.") .addField(BibEntryFieldType.AUTHOR, "Wang, X.") .addField(BibEntryFieldType.AUTHOR, "Guo, D.") .addField(BibEntryFieldType.TITLE, "A level-set method for structural topology optimization") .addField(BibEntryFieldType.JOURNAL, "Comput. Methods Appl. Mech. Engrg") .addField(BibEntryFieldType.VOLUME, "192") .addField(BibEntryFieldType.YEAR, "2003") .addField(BibEntryFieldType.PAGES, "227--246"), new BibEntry().setText(" [4] R. Kobayashi, Einstein-Kähler V metrics on open Satake V -surfaces with isolated quotient singularities, Math. Ann. 272 (1985), 385-398.") .addField(BibEntryFieldType.AUTHOR, "Kobayashi, R.") .addField(BibEntryFieldType.TITLE, "Einstein-Kähler V metrics on open Satake V -surfaces with isolated quotient singularities") .addField(BibEntryFieldType.JOURNAL, "Math. Ann.") .addField(BibEntryFieldType.VOLUME, "272") .addField(BibEntryFieldType.YEAR, "1985") .addField(BibEntryFieldType.PAGES, "385--398"), new BibEntry(BibEntryType.ARTICLE) .setText("7. W. C. Lee, Y. E. Chavez, T. Baker, and B. R. Luce, “Economic burden of heart failure: a summary of recent literature,” Heart and Lung, vol. 33, no. 6, pp. 362–371, 2004.") .addField(BibEntryFieldType.AUTHOR, "Lee, W. C.") .addField(BibEntryFieldType.AUTHOR, "Chavez, Y. E.") .addField(BibEntryFieldType.AUTHOR, "Baker, T.") .addField(BibEntryFieldType.AUTHOR, "Luce, B. R.") .addField(BibEntryFieldType.TITLE, "Economic burden of heart failure: a summary of recent literature") .addField(BibEntryFieldType.JOURNAL, "Heart and Lung") .addField(BibEntryFieldType.VOLUME, "33") .addField(BibEntryFieldType.NUMBER, "6") .addField(BibEntryFieldType.YEAR, "2004") .addField(BibEntryFieldType.PAGES, "362--371"), }; @Test public void testReferenceFinderNoRefs() { CitationPositionFinder finder = new CitationPositionFinder(); List<Set<CitationPosition>> positions = finder.findReferences(DOCUMENT_TEXT1, Arrays.asList(CITATIONS)); assertEquals(5, positions.size()); for (Set<CitationPosition> pos : positions) { assertTrue(pos.isEmpty()); } } @Test public void testReferenceFinderSingleRefs() { CitationPositionFinder finder = new CitationPositionFinder(); List<Set<CitationPosition>> positions = finder.findReferences(DOCUMENT_TEXT2, Arrays.asList(CITATIONS)); assertEquals(5, positions.size()); assertEquals(1, positions.get(0).size()); assertEquals(98, positions.get(0).iterator().next().getStartRefPosition()); assertEquals(101, positions.get(0).iterator().next().getEndRefPosition()); assertEquals(1, positions.get(1).size()); assertEquals(91, positions.get(1).iterator().next().getStartRefPosition()); assertEquals(92, positions.get(1).iterator().next().getEndRefPosition()); } @Test public void testReferenceFinderMultipleRefs() { CitationPositionFinder finder = new CitationPositionFinder(); List<Set<CitationPosition>> positions = finder.findReferences(DOCUMENT_TEXT3, Arrays.asList(CITATIONS)); assertEquals(5, positions.size()); assertEquals(1, positions.get(0).size()); assertEquals(63, positions.get(0).iterator().next().getStartRefPosition()); assertEquals(74, positions.get(0).iterator().next().getEndRefPosition()); assertEquals(1, positions.get(1).size()); assertEquals(63, positions.get(1).iterator().next().getStartRefPosition()); assertEquals(74, positions.get(1).iterator().next().getEndRefPosition()); assertEquals(1, positions.get(3).size()); assertEquals(63, positions.get(3).iterator().next().getStartRefPosition()); assertEquals(74, positions.get(3).iterator().next().getEndRefPosition()); } @Test public void testReferenceFinderRangeRefs() { CitationPositionFinder finder = new CitationPositionFinder(); List<Set<CitationPosition>> positions = finder.findReferences(DOCUMENT_TEXT4, Arrays.asList(CITATIONS)); assertEquals(5, positions.size()); List<CitationPosition> pos1 = toSortedList(positions.get(1)); assertEquals(2, pos1.size()); assertEquals(101, pos1.get(0).getStartRefPosition()); assertEquals(104, pos1.get(0).getEndRefPosition()); assertEquals(110, pos1.get(1).getStartRefPosition()); assertEquals(116, pos1.get(1).getEndRefPosition()); List<CitationPosition> pos3 = toSortedList(positions.get(3)); assertEquals(2, pos3.size()); assertEquals(101, pos3.get(0).getStartRefPosition()); assertEquals(104, pos3.get(0).getEndRefPosition()); assertEquals(110, pos3.get(1).getStartRefPosition()); assertEquals(116, pos3.get(1).getEndRefPosition()); List<CitationPosition> pos4 = toSortedList(positions.get(4)); assertEquals(1, pos4.size()); assertEquals(110, pos4.get(0).getStartRefPosition()); assertEquals(116, pos4.get(0).getEndRefPosition()); } @Test public void testReferenceFinderAuthorNames() { CitationPositionFinder finder = new CitationPositionFinder(); List<Set<CitationPosition>> positions = finder.findReferences(DOCUMENT_TEXT5, Arrays.asList(CITATIONS)); assertEquals(5, positions.size()); List<CitationPosition> pos0 = toSortedList(positions.get(0)); assertEquals(1, pos0.size()); assertEquals(88, pos0.get(0).getStartRefPosition()); assertEquals(105, pos0.get(0).getEndRefPosition()); List<CitationPosition> pos1 = toSortedList(positions.get(1)); assertEquals(2, pos1.size()); assertEquals(122, pos1.get(0).getStartRefPosition()); assertEquals(153, pos1.get(0).getEndRefPosition()); assertEquals(181, pos1.get(1).getStartRefPosition()); assertEquals(249, pos1.get(1).getEndRefPosition()); List<CitationPosition> pos2 = toSortedList(positions.get(2)); assertEquals(1, pos2.size()); assertEquals(181, pos2.get(0).getStartRefPosition()); assertEquals(249, pos2.get(0).getEndRefPosition()); assertEquals(0, positions.get(3).size()); List<CitationPosition> pos4 = toSortedList(positions.get(4)); assertEquals(1, pos4.size()); assertEquals(181, pos4.get(0).getStartRefPosition()); assertEquals(249, pos4.get(0).getEndRefPosition()); } @Test public void testReferenceFinderRoundBrackets() { CitationPositionFinder finder = new CitationPositionFinder(); List<Set<CitationPosition>> positions = finder.findReferences(DOCUMENT_TEXT6, Arrays.asList(CITATIONS)); assertEquals(5, positions.size()); List<CitationPosition> pos0 = toSortedList(positions.get(0)); assertEquals(1, pos0.size()); assertEquals(121, pos0.get(0).getStartRefPosition()); assertEquals(132, pos0.get(0).getEndRefPosition()); List<CitationPosition> pos1 = toSortedList(positions.get(1)); assertEquals(4, pos1.size()); assertEquals(91, pos1.get(0).getStartRefPosition()); assertEquals(92, pos1.get(0).getEndRefPosition()); assertEquals(121, pos1.get(1).getStartRefPosition()); assertEquals(132, pos1.get(1).getEndRefPosition()); List<CitationPosition> pos2 = toSortedList(positions.get(2)); assertEquals(1, pos2.size()); assertEquals(245, pos2.get(0).getStartRefPosition()); assertEquals(251, pos2.get(0).getEndRefPosition()); List<CitationPosition> pos3 = toSortedList(positions.get(3)); assertEquals(3, pos3.size()); assertEquals(121, pos3.get(0).getStartRefPosition()); assertEquals(132, pos3.get(0).getEndRefPosition()); List<CitationPosition> pos4 = toSortedList(positions.get(4)); assertEquals(1, pos4.size()); assertEquals(245, pos4.get(0).getStartRefPosition()); assertEquals(251, pos4.get(0).getEndRefPosition()); } private List<CitationPosition> toSortedList(Set<CitationPosition> positions) { List<CitationPosition> list = new ArrayList<CitationPosition>(positions); Collections.sort(list, new Comparator<CitationPosition>() { @Override public int compare(CitationPosition o1, CitationPosition o2) { if (o1.getStartRefPosition() != o2.getStartRefPosition()) { return Integer.compare(o1.getStartRefPosition(), o2.getStartRefPosition()); } return Integer.compare(o1.getEndRefPosition(), o2.getEndRefPosition()); } }); return list; } }
13,427
48.918216
196
java
CERMINE
CERMINE-master/cermine-impl/src/test/java/pl/edu/icm/cermine/bibref/KMeansBibReferenceExtractorTest.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.bibref; import org.junit.Before; /** * @author Dominika Tkaczyk (d.tkaczyk@icm.edu.pl) */ public class KMeansBibReferenceExtractorTest extends AbstractBibReferenceExtractorTest { private BibReferenceExtractor extractor; @Before @Override public void setUp() { super.setUp(); extractor = new KMeansBibReferenceExtractor(); } @Override protected BibReferenceExtractor getExtractor() { return extractor; } }
1,240
27.860465
88
java
CERMINE
CERMINE-master/cermine-impl/src/test/java/pl/edu/icm/cermine/bibref/DOIExtractionTest.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.bibref; import pl.edu.icm.cermine.bibref.model.BibEntry; import pl.edu.icm.cermine.exception.AnalysisException; import org.junit.Test; import static org.junit.Assert.assertEquals; import pl.edu.icm.cermine.bibref.model.BibEntryFieldType; /** * @author Dominika Tkaczyk (d.tkaczyk@icm.edu.pl) */ public class DOIExtractionTest { private final CRFBibReferenceParser parser; public DOIExtractionTest() throws AnalysisException { this.parser = CRFBibReferenceParser.getInstance(); } @Test public void testDOIRegular() throws AnalysisException { String input = "Lu TK, Collins JJ. 2007 Dispersing biofilms. Proc. Natl Acad. Sci. USA 104, 11 197–11 202. doi:10.1073/pnas.0704624104"; BibEntry actual = parser.parseBibReference(input); assertEquals(input, actual.getText()); assertEquals("10.1073/pnas.0704624104", actual.getFirstFieldValue(BibEntryFieldType.DOI)); } @Test public void testDOIWithSuffix() throws AnalysisException { String input = "Lu TK, Collins JJ. 2007 Dispersing biofilms. Proc. Natl Acad. Sci. USA 104, 11 197–11 202. doi:10.1073/pnas.0704624104 http://address"; BibEntry actual = parser.parseBibReference(input); assertEquals(input, actual.getText()); assertEquals("10.1073/pnas.0704624104", actual.getFirstFieldValue(BibEntryFieldType.DOI)); } @Test public void testDOIInParentheses() throws AnalysisException { String input = "Lu TK, Collins JJ. 2007 Dispersing biofilms. Proc. Natl Acad. Sci. USA 104, 11 197–11 202. (doi:10.1073/pnas.0704624104)"; BibEntry actual = parser.parseBibReference(input); assertEquals(input, actual.getText()); assertEquals("10.1073/pnas.0704624104", actual.getFirstFieldValue(BibEntryFieldType.DOI)); } @Test public void testDOIInSquareBrackets() throws AnalysisException { String input = "Lu TK, Collins JJ. 2007 Dispersing biofilms. Proc. Natl Acad. Sci. USA 104, 11 197–11 202. [doi:10.1073/pnas.0704624104]"; BibEntry actual = parser.parseBibReference(input); assertEquals(input, actual.getText()); assertEquals("10.1073/pnas.0704624104", actual.getFirstFieldValue(BibEntryFieldType.DOI)); } @Test public void testDOIMoreDigits() throws AnalysisException { String input = "Lu TK, Collins JJ. 2007 Dispersing biofilms. Proc. Natl Acad. Sci. USA 104, 11 197–11 202. 10.1073309/pnas.0704624104"; BibEntry actual = parser.parseBibReference(input); assertEquals(input, actual.getText()); assertEquals("10.1073309/pnas.0704624104", actual.getFirstFieldValue(BibEntryFieldType.DOI)); } }
3,468
43.474359
159
java
CERMINE
CERMINE-master/cermine-impl/src/test/java/pl/edu/icm/cermine/bibref/AbstractBibReferenceParserTest.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.bibref; import static org.junit.Assert.assertTrue; import static org.junit.Assert.assertEquals; import org.junit.Test; import pl.edu.icm.cermine.bibref.model.BibEntry; import pl.edu.icm.cermine.bibref.model.BibEntryFieldType; import pl.edu.icm.cermine.bibref.model.BibEntryType; import pl.edu.icm.cermine.exception.AnalysisException; /** * @author Dominika Tkaczyk (d.tkaczyk@icm.edu.pl) */ public abstract class AbstractBibReferenceParserTest { private final BibEntry[] entries = { new BibEntry().setText("[6] W. Hoeffding, Probability inequalities for sums of bounded random variables, J. Amer. Statist. Assoc, 58 (1963) 13-30.") .addField(BibEntryFieldType.AUTHOR, "Hoeffding, W.") .addField(BibEntryFieldType.TITLE, "Probability inequalities for sums of bounded random variables") .addField(BibEntryFieldType.JOURNAL, "J. Amer. Statist. Assoc") .addField(BibEntryFieldType.VOLUME, "58") .addField(BibEntryFieldType.YEAR, "1963") .addField(BibEntryFieldType.PAGES, "13--30"), new BibEntry().setText(" [3] Agranovitch (M.S.) and Vishisk (M.I.). — Elliptic problems with a parameter and parabolic problems of general type, Russian Math. Surveys, 19, 1964, 53-157.") .addField(BibEntryFieldType.AUTHOR, "Agranovitch, M.S.") .addField(BibEntryFieldType.AUTHOR, "Vishisk, M.I.") .addField(BibEntryFieldType.TITLE, "Elliptic problems with a parameter and parabolic problems of general type") .addField(BibEntryFieldType.JOURNAL, "Russian Math. Surveys") .addField(BibEntryFieldType.VOLUME, "19") .addField(BibEntryFieldType.YEAR, "1964") .addField(BibEntryFieldType.PAGES, "53--157"), new BibEntry().setText("[27] M-Y. Wang, X. Wang and D. Guo, A level-set method for structural topology optimization. Comput. Methods Appl. Mech. Engrg, 192 (2003) 227–246.") .addField(BibEntryFieldType.AUTHOR, "Wang, M-Y.") .addField(BibEntryFieldType.AUTHOR, "Wang, X.") .addField(BibEntryFieldType.AUTHOR, "Guo, D.") .addField(BibEntryFieldType.TITLE, "A level-set method for structural topology optimization") .addField(BibEntryFieldType.JOURNAL, "Comput. Methods Appl. Mech. Engrg") .addField(BibEntryFieldType.VOLUME, "192") .addField(BibEntryFieldType.YEAR, "2003") .addField(BibEntryFieldType.PAGES, "227--246"), new BibEntry().setText(" [8] R. Kobayashi, Einstein-Kähler V metrics on open Satake V -surfaces with isolated quotient singularities, Math. Ann. 272 (1985), 385-398.") .addField(BibEntryFieldType.AUTHOR, "Kobayashi, R.") .addField(BibEntryFieldType.TITLE, "Einstein-Kähler V metrics on open Satake V -surfaces with isolated quotient singularities") .addField(BibEntryFieldType.JOURNAL, "Math. Ann") .addField(BibEntryFieldType.VOLUME, "272") .addField(BibEntryFieldType.YEAR, "1985") .addField(BibEntryFieldType.PAGES, "385--398"), new BibEntry(BibEntryType.ARTICLE) .setText("[4] W. C. Lee, Y. E. Chavez, T. Baker, and B. R. Luce, “Economic burden of heart failure: a summary of recent literature,” Heart and Lung, vol. 33, no. 6, pp. 362–371, 2004.") .addField(BibEntryFieldType.AUTHOR, "Lee, W. C.") .addField(BibEntryFieldType.AUTHOR, "Chavez, Y. E.") .addField(BibEntryFieldType.AUTHOR, "Baker, T.") .addField(BibEntryFieldType.AUTHOR, "Luce, B. R.") .addField(BibEntryFieldType.TITLE, "Economic burden of heart failure: a summary of recent literature") .addField(BibEntryFieldType.JOURNAL, "Heart and Lung") .addField(BibEntryFieldType.VOLUME, "33") .addField(BibEntryFieldType.NUMBER, "6") .addField(BibEntryFieldType.YEAR, "2004") .addField(BibEntryFieldType.PAGES, "362--371"), new BibEntry(BibEntryType.ARTICLE) .setText("[6] C. Chan, D. Tang, and A. Jones, “Clinical outcomes of a cardiac rehabilitation and maintenance program for Chinese patients with congestive heart failure,” Disability and Rehabilitation, vol. 30, no. 17, pp. 1245–1253, 2008.") .addField(BibEntryFieldType.AUTHOR, "Chan, C.") .addField(BibEntryFieldType.AUTHOR, "Tang, D.") .addField(BibEntryFieldType.AUTHOR, "Jones, A.") .addField(BibEntryFieldType.TITLE, "Clinical outcomes of a cardiac rehabilitation and maintenance program for Chinese patients with congestive heart failure") .addField(BibEntryFieldType.JOURNAL, "Disability and Rehabilitation") .addField(BibEntryFieldType.VOLUME, "30") .addField(BibEntryFieldType.NUMBER, "17") .addField(BibEntryFieldType.YEAR, "2008") .addField(BibEntryFieldType.PAGES, "1245--1253"), new BibEntry(BibEntryType.ARTICLE) .setText("[11] E. Rideout and M. Montemuro, “ Hope, morale and adapta- tion in patients with chronic heart failure,” Journal of Advanced Nursing, vol. 11, no. 4, pp. 429–438, 1986.") .addField(BibEntryFieldType.AUTHOR, "Rideout, E.") .addField(BibEntryFieldType.AUTHOR, "Montemuro, M.") .addField(BibEntryFieldType.TITLE, "Hope, morale and adapta- tion in patients with chronic heart failure") .addField(BibEntryFieldType.JOURNAL, "Journal of Advanced Nursing") .addField(BibEntryFieldType.VOLUME, "11") .addField(BibEntryFieldType.NUMBER, "4") .addField(BibEntryFieldType.YEAR, "1986") .addField(BibEntryFieldType.PAGES, "429--438"), new BibEntry(BibEntryType.ARTICLE) .setText("S.E. Fahlman and C. Lebiere. The cascade-correlation learn-ing architecture. In D.S. Touretzky, editor, Advances in Neural Information Processing Systems, volume 2, pages 524-532, San Mateo, 1990. Morgan Kaufmann.") .addField(BibEntryFieldType.AUTHOR, "Fahlman, S.E.") .addField(BibEntryFieldType.AUTHOR, "Lebiere, C.") .addField(BibEntryFieldType.TITLE, "The cascade-correlation learn-ing architecture") .addField(BibEntryFieldType.JOURNAL, "Advances in Neural Information Processing Systems") .addField(BibEntryFieldType.VOLUME, "2") .addField(BibEntryFieldType.YEAR, "1990") .addField(BibEntryFieldType.PAGES, "524--532"), new BibEntry(BibEntryType.ARTICLE) .setText("Sridhar Mahadevan and Jonathan Connell. >Scaling reinforcement learning to robotics by exploiting the subsumption architecture. In Proceedings of the Eighth International Workshop on Machine Learning, 1991.") .addField(BibEntryFieldType.AUTHOR, "Mahadevan, Sridhar") .addField(BibEntryFieldType.AUTHOR, "Connell, Jonathan") .addField(BibEntryFieldType.TITLE, "Scaling reinforcement learning to robotics by exploiting the subsumption architecture") .addField(BibEntryFieldType.JOURNAL, "Proceedings of the Eighth International Workshop on Machine Learning") .addField(BibEntryFieldType.YEAR, "1991"), new BibEntry(BibEntryType.ARTICLE) .setText("S.D. Whitehead and D. H. Ballard. Active perception and reinforcement learning. Neural Computation, 2 (4): 409-419, 1990.") .addField(BibEntryFieldType.AUTHOR, "Whitehead, S.D.") .addField(BibEntryFieldType.AUTHOR, "Ballard, D. H.") .addField(BibEntryFieldType.TITLE, "Active perception and reinforcement learning") .addField(BibEntryFieldType.JOURNAL, "Neural Computation") .addField(BibEntryFieldType.VOLUME, "2") .addField(BibEntryFieldType.NUMBER, "4") .addField(BibEntryFieldType.YEAR, "1990") .addField(BibEntryFieldType.PAGES, "409--419"), new BibEntry(BibEntryType.ARTICLE) .setText("Garijo, D., & Gil, Y. (2011). A new approach for publishing workflows: abstractions, standards, and linked data. In Proceedings of the 6th workshop on Workflows in support of large-scale science: 47–56. DOI: 10.1145/2110497.2110504") .addField(BibEntryFieldType.AUTHOR, "Garijo, D.") .addField(BibEntryFieldType.AUTHOR, "Gil, Y.") .addField(BibEntryFieldType.DOI, "10.1145/2110497.2110504") .addField(BibEntryFieldType.JOURNAL, "Proceedings of the 6th workshop on Workflows in support of large-scale science") .addField(BibEntryFieldType.PAGES, "47--56") .addField(BibEntryFieldType.TITLE, "A new approach for publishing workflows: abstractions, standards, and linked data") .addField(BibEntryFieldType.YEAR, "2011"), new BibEntry(BibEntryType.ARTICLE) .setText("Van Heuven WJB, Dijkstra T. Language comprehension in the bilingual brain: fMRI and ERP support for psycholinguistic models. Brain Res Rev. 2010; 64(1):104 – 22. doi: 10.1016/j.brainresrev.2010.03.002 PMID: 20227440") .addField(BibEntryFieldType.AUTHOR, "Van Heuven, WJB") .addField(BibEntryFieldType.AUTHOR, "Dijkstra, T.") .addField(BibEntryFieldType.DOI, "10.1016/j.brainresrev.2010.03.002") .addField(BibEntryFieldType.JOURNAL, "Brain Res Rev") .addField(BibEntryFieldType.NUMBER, "1") .addField(BibEntryFieldType.PAGES, "104--22") .addField(BibEntryFieldType.TITLE, "Language comprehension in the bilingual brain: fMRI and ERP support for psycholinguistic models") .addField(BibEntryFieldType.VOLUME, "64") .addField(BibEntryFieldType.YEAR, "2010"), }; @Test public void bibReferenceEmptyParserTest() throws AnalysisException { BibEntry be = getParser().parseBibReference(""); assertEquals("", be.getText()); assertTrue(be.getFieldKeys().isEmpty()); } @Test public void bibReferenceParserTest() throws AnalysisException { int allFields = 0; int parsedFields = 0; for (BibEntry entry : entries) { BibEntry testEntry = getParser().parseBibReference(entry.getText()); for (BibEntryFieldType key : entry.getFieldKeys()) { allFields++; if (entry.getAllFieldValues(key).equals(testEntry.getAllFieldValues(key))) { parsedFields++; } } } assertTrue((double) parsedFields / (double) allFields >= getMinPercentage()); } protected abstract BibReferenceParser<BibEntry> getParser(); protected abstract double getMinPercentage(); }
11,508
64.765714
255
java
CERMINE
CERMINE-master/cermine-impl/src/test/java/pl/edu/icm/cermine/bibref/CRFBibReferenceParserTest.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.bibref; import pl.edu.icm.cermine.bibref.model.BibEntry; import pl.edu.icm.cermine.exception.AnalysisException; import org.junit.Test; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertTrue; /** * @author Dominika Tkaczyk (d.tkaczyk@icm.edu.pl) */ public class CRFBibReferenceParserTest extends AbstractBibReferenceParserTest { private static final double MIN_PERCENTAGE = 0.8; private final CRFBibReferenceParser parser; public CRFBibReferenceParserTest() throws AnalysisException { this.parser = CRFBibReferenceParser.getInstance(); } @Override protected BibReferenceParser<BibEntry> getParser() { return parser; } @Override protected double getMinPercentage() { return MIN_PERCENTAGE; } @Test public void testTooLong() throws AnalysisException { StringBuilder inputSB = new StringBuilder(); for (int i = 0; i < 100; i++) { inputSB.append("Johnson J, Dutton S, Briffa E, "); } inputSB.append("Broadband learning for doctors. BMJ 2006, 332, 1403-1404."); String input = inputSB.toString(); BibEntry actual = parser.parseBibReference(input); assertEquals(input, actual.getText()); assertTrue(actual.getFieldKeys().isEmpty()); } }
2,105
31.90625
84
java
CERMINE
CERMINE-master/cermine-impl/src/test/java/pl/edu/icm/cermine/bibref/AbstractBibReferenceExtractorTest.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.bibref; import java.io.*; import java.net.URISyntaxException; import java.net.URL; import java.util.zip.ZipFile; import org.apache.commons.lang.StringUtils; import org.jdom.JDOMException; import static org.junit.Assert.assertEquals; import org.junit.Before; import org.junit.Test; import org.xml.sax.SAXException; 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.TrueVizToBxDocumentReader; /** * @author Dominika Tkaczyk (d.tkaczyk@icm.edu.pl) */ public abstract class AbstractBibReferenceExtractorTest { static final private String TEST_FILE = "/pl/edu/icm/cermine/bibref/refs.xml.zip"; static final private String EXP_FILE = "/pl/edu/icm/cermine/bibref/refs.txt"; private TrueVizToBxDocumentReader bxReader; @Before public void setUp() { bxReader = new TrueVizToBxDocumentReader(); } @Test public void metadataExtractionTest() throws AnalysisException, JDOMException, IOException, SAXException, TransformationException, URISyntaxException { InputStream expStream = AbstractBibReferenceExtractorTest.class.getResourceAsStream(EXP_FILE); BufferedReader expReader = null; StringBuilder sb = new StringBuilder(); try { expReader = new BufferedReader(new InputStreamReader(expStream, "UTF-8")); String line; while ((line = expReader.readLine()) != null) { sb.append(line); sb.append("\n"); } } finally { expStream.close(); if (expReader != null) { expReader.close(); } } URL url = AbstractBibReferenceExtractorTest.class.getResource(TEST_FILE); ZipFile zipFile = null; InputStream inputStream = null; String[] references = new String[]{}; try { zipFile = new ZipFile(new File(url.toURI())); inputStream = zipFile.getInputStream(zipFile.getEntry("out.xml")); BxDocument expDocument = new BxDocument().setPages(bxReader.read(new InputStreamReader(inputStream, "UTF-8"))); references = getExtractor().extractBibReferences(expDocument); } finally { if (zipFile != null) { zipFile.close(); } if (inputStream != null) { inputStream.close(); } } assertEquals(StringUtils.join(references, "\n"), sb.toString().trim()); } protected abstract BibReferenceExtractor getExtractor(); }
3,465
36.673913
154
java
CERMINE
CERMINE-master/cermine-impl/src/test/java/pl/edu/icm/cermine/bibref/transformers/BibEntryToNLMElementConverterTest.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.bibref.transformers; import java.io.IOException; import java.util.List; import org.custommonkey.xmlunit.Diff; import org.jdom.Element; import org.jdom.JDOMException; import org.jdom.output.XMLOutputter; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertTrue; import org.junit.Before; import org.junit.Test; import org.xml.sax.SAXException; import pl.edu.icm.cermine.StandardDataExamples; import pl.edu.icm.cermine.bibref.model.BibEntry; import pl.edu.icm.cermine.exception.TransformationException; /** * @author Dominika Tkaczyk (d.tkaczyk@icm.edu.pl) */ public class BibEntryToNLMElementConverterTest { private BibEntryToNLMConverter converter; private List<BibEntry> entries; private List<Element> elements; XMLOutputter xmlOutputter; @Before public void setUp() throws JDOMException, IOException { converter = new BibEntryToNLMConverter(); entries = StandardDataExamples.getReferencesAsBibEntry(); elements = StandardDataExamples.getReferencesAsNLMElement(); xmlOutputter = new XMLOutputter(); } @Test public void testConvert() throws TransformationException, SAXException, IOException { Element testElement = converter.convert(entries.get(0)); Diff diff = new Diff(xmlOutputter.outputString(elements.get(0)), xmlOutputter.outputString(testElement)); assertTrue(diff.similar()); } @Test public void testConvertAll() throws TransformationException, SAXException, IOException { assertEquals(entries.size(), elements.size()); List<Element> testElements = converter.convertAll(entries); for (int i = 0; i < elements.size(); i++) { Diff diff = new Diff(xmlOutputter.outputString(elements.get(i)), xmlOutputter.outputString(testElements.get(i))); assertTrue(diff.similar()); } } }
2,671
35.60274
125
java
CERMINE
CERMINE-master/cermine-impl/src/test/java/pl/edu/icm/cermine/bibref/transformers/NLMElementToBibEntryConverterTest.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.bibref.transformers; import java.io.IOException; import java.util.List; import org.jdom.Element; import org.jdom.JDOMException; import static org.junit.Assert.assertEquals; import org.junit.Before; import org.junit.Test; import pl.edu.icm.cermine.StandardDataExamples; import pl.edu.icm.cermine.bibref.model.BibEntry; import pl.edu.icm.cermine.exception.TransformationException; /** * @author Dominika Tkaczyk (d.tkaczyk@icm.edu.pl) */ public class NLMElementToBibEntryConverterTest { private final NLMToBibEntryConverter converter; private final List<BibEntry> entries; private final List<Element> elements; public NLMElementToBibEntryConverterTest() throws JDOMException, IOException { converter = new NLMToBibEntryConverter(); elements = StandardDataExamples.getReferencesAsNLMElement(); entries = StandardDataExamples.getReferencesAsBibEntry(); } @Test public void testConvert() throws TransformationException { assertEquals(entries.get(0), converter.convert(elements.get(0))); } @Test public void testConvertAll() throws TransformationException { assertEquals(entries, converter.convertAll(elements)); } }
1,983
33.807018
82
java
CERMINE
CERMINE-master/cermine-impl/src/test/java/pl/edu/icm/cermine/bibref/transformers/BibEntryToBibTeXWriterTest.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.bibref.transformers; import java.io.StringWriter; import java.util.List; import org.apache.commons.lang.StringUtils; import static org.junit.Assert.assertEquals; import org.junit.Test; import pl.edu.icm.cermine.StandardDataExamples; import pl.edu.icm.cermine.bibref.model.BibEntry; import pl.edu.icm.cermine.exception.TransformationException; import pl.edu.icm.cermine.tools.transformers.ModelToFormatWriter; /** * @author Dominika Tkaczyk (d.tkaczyk@icm.edu.pl) */ public class BibEntryToBibTeXWriterTest { private ModelToFormatWriter<BibEntry> writer = new BibEntryToBibTeXWriter(); private List<BibEntry> bibEntries = StandardDataExamples.getReferencesAsBibEntry(); private List<String> bibtexEntries = StandardDataExamples.getReferencesAsBibTeX(); @Test public void testWrite() throws TransformationException { assertEquals(bibtexEntries.get(0), writer.write(bibEntries.get(0))); StringWriter sw = new StringWriter(); writer.write(sw, bibEntries.get(0)); assertEquals(bibtexEntries.get(0), sw.toString()); } @Test public void testMultiple() throws TransformationException { assertEquals(StringUtils.join(bibtexEntries, "\n\n"), writer.writeAll(bibEntries)); StringWriter sw = new StringWriter(); writer.writeAll(sw, bibEntries); assertEquals(StringUtils.join(bibtexEntries, "\n\n"), sw.toString()); } }
2,210
35.85
91
java
CERMINE
CERMINE-master/cermine-impl/src/test/java/pl/edu/icm/cermine/bibref/transformers/BibTeXToBibEntryReaderTest.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.bibref.transformers; import java.io.StringReader; import java.util.List; import org.apache.commons.collections.Closure; import org.apache.commons.collections.CollectionUtils; import org.apache.commons.lang.StringUtils; import static org.junit.Assert.assertEquals; import org.junit.Before; import org.junit.Test; import pl.edu.icm.cermine.StandardDataExamples; import pl.edu.icm.cermine.bibref.model.BibEntry; import pl.edu.icm.cermine.bibref.model.BibEntryField; import pl.edu.icm.cermine.bibref.model.BibEntryFieldType; import pl.edu.icm.cermine.exception.TransformationException; /** * @author Ewa Stocka */ public class BibTeXToBibEntryReaderTest { private final BibTeXToBibEntryReader reader = new BibTeXToBibEntryReader(); private final List<String> bibtex = StandardDataExamples.getReferencesAsBibTeX(); private final List<BibEntry> entries = StandardDataExamples.getReferencesAsBibEntry(); @Before public void setUp() { CollectionUtils.forAllDo(entries, new Closure() { @Override public void execute(Object input) { removeTextAndIndexes((BibEntry) input); } }); } @Test public void testRead() throws TransformationException { assertEquals(entries.get(0), reader.read(bibtex.get(0))); StringReader sr = new StringReader(bibtex.get(0)); assertEquals(entries.get(0), reader.read(sr)); } @Test public void testReadAll() throws TransformationException { String allBibTex = StringUtils.join(bibtex, "\n\n"); assertEquals(entries, reader.readAll(allBibTex)); StringReader sr = new StringReader(allBibTex); assertEquals(entries, reader.readAll(sr)); } private void removeTextAndIndexes(BibEntry entry) { entry.setText(null); for (BibEntryFieldType key : entry.getFieldKeys()) { for (BibEntryField field : entry.getAllFields(key)) { field.setIndexes(-1, -1); } } } }
2,823
33.024096
90
java
CERMINE
CERMINE-master/cermine-impl/src/test/java/pl/edu/icm/cermine/metadata/tools/MetadataToolsTest.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.tools; import static org.junit.Assert.assertEquals; import org.junit.Test; /** * @author Bartosz Tarnawski */ public class MetadataToolsTest { @Test public void testClean() { char ci = 0x0107; // LATIN SMALL LETTER C WITH ACUTE char c = 0x63; // LATIN SMALL LETTER C char acute = 0x301; // COMBINING ACUTE ACCENT String input = Character.toString(ci); String expected = Character.toString(c) + Character.toString(acute); String actual = MetadataTools.cleanAndNormalize(input); assertEquals(expected, actual); char dash = 0x2014; // EM_DASH input = Character.toString(dash); expected = "-"; actual = MetadataTools.cleanAndNormalize(input); assertEquals(expected, actual); } }
1,561
33.711111
78
java
CERMINE
CERMINE-master/cermine-impl/src/test/java/pl/edu/icm/cermine/metadata/affiliation/AffiliationParserTest.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; import org.jdom.output.XMLOutputter; import static org.junit.Assert.assertEquals; import org.junit.Test; import pl.edu.icm.cermine.exception.AnalysisException; import pl.edu.icm.cermine.exception.TransformationException; /** * @author Bartosz Tarnawski */ public class AffiliationParserTest { @Test public void testEmpty() throws AnalysisException, TransformationException { CRFAffiliationParser parser = new CRFAffiliationParser(); XMLOutputter outputter = new XMLOutputter(); String input = ""; String expected = "<aff id=\"aff\"><label></label></aff>"; String actual = outputter.outputString(parser.parse(input)); assertEquals(expected, actual); } @Test public void testTooLong() throws AnalysisException, TransformationException { CRFAffiliationParser parser = new CRFAffiliationParser(); XMLOutputter outputter = new XMLOutputter(); StringBuilder inputSB = new StringBuilder(); for (int i = 0; i < 40; i++) { inputSB.append("Department of Oncology - Pathology, Karolinska Institutet, Stockholm, Sweden, "); } String input = inputSB.toString(); String expected = "<aff id=\"aff\"><label></label>" + input.trim() + "</aff>"; String actual = outputter.outputString(parser.parse(input)); assertEquals(expected, actual); } @Test public void testOriental() throws AnalysisException, TransformationException { CRFAffiliationParser parser = new CRFAffiliationParser(); XMLOutputter outputter = new XMLOutputter(); String input = "山梨大学大学院医学工学総合研究部 社会医学講座"; String expected = "<aff id=\"aff\"><label></label></aff>"; String actual = outputter.outputString(parser.parse(input)); assertEquals(expected, actual); } @Test public void testParseString() throws AnalysisException, TransformationException { CRFAffiliationParser parser = new CRFAffiliationParser(); XMLOutputter outputter = new XMLOutputter(); String input = "Department of Dinozauring, Dino Institute, Tyranosaurus Route 35, Boston, MA, USA"; String expected = "<aff id=\"aff\"><label></label>" + "<institution>Department of Dinozauring, Dino Institute</institution>" + ", " + "<addr-line>Tyranosaurus Route 35, Boston, MA</addr-line>" + ", " + "<country country=\"US\">USA</country>" + "</aff>"; String actual = outputter.outputString(parser.parse(input)); assertEquals(expected, actual); } @Test public void testParseStringWithAuthor() throws AnalysisException, TransformationException { CRFAffiliationParser parser = new CRFAffiliationParser( "common-words-affiliations-with-author.txt", "acrf-affiliations-with-author.ser.gz"); XMLOutputter outputter = new XMLOutputter(); String input = "Andrew McDino and Elizabeth Pterodactyl, Department of Dinozauring, Dino Institute, Tyranosaurus Route 35, Boston, MA, USA"; String expected = "<aff id=\"aff\"><label></label>" + // "<author>Andrew McDino and Elizabeth Pterodactyl</author>" + ", " + "<institution>Department of Dinozauring, Dino Institute</institution>" + ", " + "<addr-line>Tyranosaurus Route 35, Boston, MA</addr-line>" + ", " + "<country country=\"US\">USA</country>" + "</aff>"; String actual = outputter.outputString(parser.parse(input)); assertEquals(expected, actual); } }
4,489
43.019608
148
java
CERMINE
CERMINE-master/cermine-impl/src/test/java/pl/edu/icm/cermine/metadata/affiliation/tools/AffiliationCRFTokenClassifierTest.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.tools; import java.util.ArrayList; import java.util.Arrays; import java.util.List; import org.junit.Test; import pl.edu.icm.cermine.exception.AnalysisException; import pl.edu.icm.cermine.exception.TransformationException; import pl.edu.icm.cermine.metadata.model.AffiliationLabel; import pl.edu.icm.cermine.metadata.model.DocumentAffiliation; import pl.edu.icm.cermine.parsing.model.Token; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertNotNull; /** * @author Bartosz Tarnawski */ public class AffiliationCRFTokenClassifierTest { private static final AffiliationTokenizer TOKENIZER = new AffiliationTokenizer(); private static final AffiliationFeatureExtractor EXTRACTOR; static { try { EXTRACTOR = new AffiliationFeatureExtractor(); } catch (AnalysisException e) { throw new RuntimeException("Failed to initialize the feature extractor"); } } @Test public void testClassify() throws AnalysisException { List<Token<AffiliationLabel>> tokens = new ArrayList<Token<AffiliationLabel>>(); for (int i = 0; i < 5; i++) { tokens.add(new Token<AffiliationLabel>()); } tokens.get(0).setFeatures(Arrays.asList( "W=University", "IsUpperCase" )); tokens.get(1).setFeatures(Arrays.asList( "W=,", "IsSeparator" )); tokens.get(2).setFeatures(Arrays.asList( "W=Boston", "IsUpperCase", "KeywordCity" )); tokens.get(3).setFeatures(Arrays.asList( "W=,", "IsSeparator" )); tokens.get(4).setFeatures(Arrays.asList( "W=USA", "IsAllCapital", "KeywordCountry" )); new AffiliationCRFTokenClassifier().classify(tokens); for (Token<AffiliationLabel> token : tokens) { assertNotNull(token.getLabel()); } } @Test public void testClassifyWithDocumentAffiliation() throws AnalysisException, TransformationException { String text = "Department of Oncology, Radiology and Clinical Immunology, Akademiska " + "Sjukhuset, Uppsala, Sweden"; DocumentAffiliation instance = new DocumentAffiliation(text); instance.setTokens(TOKENIZER.tokenize(instance.getRawText())); EXTRACTOR.calculateFeatures(instance); new AffiliationCRFTokenClassifier().classify(instance.getTokens()); assertEquals(AffiliationLabel.INST, instance.getTokens().get(0).getLabel()); assertEquals(AffiliationLabel.INST, instance.getTokens().get(1).getLabel()); assertEquals(AffiliationLabel.ADDR, instance.getTokens().get(12).getLabel()); assertEquals(AffiliationLabel.COUN, instance.getTokens().get(14).getLabel()); } }
3,700
36.765306
105
java
CERMINE
CERMINE-master/cermine-impl/src/test/java/pl/edu/icm/cermine/metadata/affiliation/tools/AffiliationTokenizerTest.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.tools; import java.util.Arrays; import java.util.List; import org.junit.Test; import pl.edu.icm.cermine.metadata.model.AffiliationLabel; import pl.edu.icm.cermine.metadata.model.DocumentAffiliation; 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 AffiliationTokenizerTest { private final static AffiliationTokenizer TOKENIZER = new AffiliationTokenizer(); @Test public void testTokenizeAscii() { String input = "ko pi_es123_@@123Kot"; List<Token<AffiliationLabel>> expected = Arrays.asList( new Token<AffiliationLabel>("ko", 0, 2), new Token<AffiliationLabel>("pi", 4, 6), new Token<AffiliationLabel>("_", 6, 7), new Token<AffiliationLabel>("es", 7, 9), new Token<AffiliationLabel>("123", 9, 12), new Token<AffiliationLabel>("_", 12, 13), new Token<AffiliationLabel>("@", 13, 14), new Token<AffiliationLabel>("@", 14, 15), new Token<AffiliationLabel>("123", 15, 18), new Token<AffiliationLabel>("Kot", 18, 21) ); List<Token<AffiliationLabel>> actual = TOKENIZER.tokenize(input); assertEquals(expected, actual); } @Test public void testTokenizeNonAscii() { String input = "śćdź óó"; input = MetadataTools.cleanAndNormalize(input); List<Token<AffiliationLabel>> expected = Arrays.asList( new Token<AffiliationLabel>("scdz", 0, 7), new Token<AffiliationLabel>("oo", 8, 12) ); List<Token<AffiliationLabel>> actual = TOKENIZER.tokenize(input); assertEquals(expected, actual); } @Test public void testTokenizeWithDocumentAffiliation() { String text = "Cóż ro123bić?"; List<Token<AffiliationLabel>> expected = Arrays.asList( new Token<AffiliationLabel>("Coz", 0, 5), new Token<AffiliationLabel>("ro", 6, 8), new Token<AffiliationLabel>("123", 8, 11), new Token<AffiliationLabel>("bic", 11, 15), new Token<AffiliationLabel>("?", 15, 16) ); DocumentAffiliation instance = new DocumentAffiliation(text); List<Token<AffiliationLabel>> actual = TOKENIZER.tokenize(instance.getRawText()); assertEquals(expected, actual); } }
3,311
35
89
java
CERMINE
CERMINE-master/cermine-impl/src/test/java/pl/edu/icm/cermine/metadata/affiliation/tools/AffiliationFeatureExtractorTest.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.tools; import java.util.ArrayList; import java.util.Arrays; import java.util.Collections; import java.util.List; import org.junit.Test; import pl.edu.icm.cermine.exception.AnalysisException; import pl.edu.icm.cermine.metadata.affiliation.features.AffiliationDictionaryFeature; import pl.edu.icm.cermine.metadata.model.AffiliationLabel; import pl.edu.icm.cermine.metadata.model.DocumentAffiliation; import pl.edu.icm.cermine.parsing.features.*; import pl.edu.icm.cermine.parsing.model.Token; import static org.junit.Assert.assertEquals; /** * @author Bartosz Tarnawski */ public class AffiliationFeatureExtractorTest { private static final AffiliationTokenizer TOKENIZER = new AffiliationTokenizer(); private static final AffiliationFeatureExtractor EXTRACTOR; static { try { List<BinaryTokenFeatureCalculator> binaryFeatures = Arrays.<BinaryTokenFeatureCalculator>asList( new IsNumberFeature(), new IsUpperCaseFeature(), new IsAllUpperCaseFeature(), new IsSeparatorFeature(), new IsNonAlphanumFeature() ); @SuppressWarnings("unchecked") List<KeywordFeatureCalculator<Token<AffiliationLabel>>> keywordFeatures = Arrays.<KeywordFeatureCalculator<Token<AffiliationLabel>>>asList( new AffiliationDictionaryFeature("KeywordAddress", "/pl/edu/icm/cermine/metadata/affiliation/features/address_keywords.txt", false), new AffiliationDictionaryFeature("KeywordCity", "/pl/edu/icm/cermine/metadata/affiliation/features/cities.txt", true), new AffiliationDictionaryFeature("KeywordCountry", "/pl/edu/icm/cermine/metadata/affiliation/features/countries2.txt", true), new AffiliationDictionaryFeature("KeywordInstitution", "/pl/edu/icm/cermine/metadata/affiliation/features/institution_keywords.txt", false), new AffiliationDictionaryFeature("KeywordState", "/pl/edu/icm/cermine/metadata/affiliation/features/states.txt", true), new AffiliationDictionaryFeature("KeywordStateCode", "/pl/edu/icm/cermine/metadata/affiliation/features/state_codes.txt", true), new AffiliationDictionaryFeature("KeywordStopWord", "/pl/edu/icm/cermine/metadata/affiliation/features/stop_words_multilang.txt", false) ); WordFeatureCalculator wordFeature = new WordFeatureCalculator(Arrays.<BinaryTokenFeatureCalculator>asList( new IsNumberFeature()), false); EXTRACTOR = new AffiliationFeatureExtractor(binaryFeatures, keywordFeatures, wordFeature); } catch (AnalysisException e) { throw new RuntimeException("Failed to initialize the feature extractor"); } } static private class TokenContainer { public List<Token<AffiliationLabel>> tokens; public List<List<String>> features; public TokenContainer() { tokens = new ArrayList<Token<AffiliationLabel>>(); features = new ArrayList<List<String>>(); } public void add(String text, String... expectedFeatures) { tokens.add(new Token<AffiliationLabel>(text)); features.add(Arrays.asList(expectedFeatures)); } public void checkFeatures() { for (int i = 0; i < tokens.size(); i++) { List<String> expected = features.get(i); List<String> actual = tokens.get(i).getFeatures(); Collections.sort(expected); Collections.sort(actual); assertEquals(expected, actual); } } } @Test public void testExtractFeatures() { TokenContainer tc = new TokenContainer(); tc.add("word", "W=word"); tc.add("123", "IsNumber"); tc.add("Uppercaseword", "W=Uppercaseword", "IsUpperCase"); tc.add("ALLUPPERCASEWORD", "W=ALLUPPERCASEWORD", "IsAllUpperCase"); tc.add(",", "W=,", "IsSeparator"); tc.add("@", "W=@", "IsNonAlphanum"); tc.add("Maluwang", "W=Maluwang", "IsUpperCase"); tc.add("Maluwang", "W=Maluwang", "IsUpperCase", "KeywordAddress"); tc.add("na", "W=na", "KeywordAddress"); tc.add("lansangan", "W=lansangan", "KeywordAddress"); tc.add(".", "W=.", "IsSeparator"); tc.add("les", "W=les"); tc.add("escaldes", "W=escaldes"); tc.add("les", "W=les", "KeywordCity"); tc.add("Escaldes", "W=Escaldes", "KeywordCity", "IsUpperCase"); tc.add("mhm", "W=mhm"); tc.add("U", "W=U", "KeywordCountry", "IsUpperCase", "IsAllUpperCase"); tc.add(".", "W=.", "IsSeparator", "KeywordCountry"); tc.add("S", "W=S", "KeywordCountry", "IsUpperCase", "IsAllUpperCase"); tc.add(".", "W=.", "IsSeparator", "KeywordCountry"); tc.add("A", "W=A", "KeywordCountry", "IsUpperCase", "IsAllUpperCase"); tc.add(".", "W=.", "IsSeparator", "KeywordCountry"); tc.add("New", "W=New", "IsUpperCase", "KeywordState"); tc.add("Hampshire", "W=Hampshire", "IsUpperCase", "KeywordState"); tc.add("KS", "W=KS", "IsAllUpperCase", "KeywordStateCode"); // KS -- state code keyword tc.add("du", "W=du", "KeywordStopWord"); DocumentAffiliation instance = new DocumentAffiliation(""); instance.setTokens(tc.tokens); EXTRACTOR.calculateFeatures(instance); tc.checkFeatures(); } @Test public void testExtractFeaturesWithDocumentAffiliation() { String text = "Cóż ro123bić?"; List<List<String>> expectedFeatures = new ArrayList<List<String>>(); expectedFeatures.add(Arrays.asList("W=Coz", "IsUpperCase")); expectedFeatures.add(Arrays.asList("W=ro")); expectedFeatures.add(Arrays.asList("IsNumber")); expectedFeatures.add(Arrays.asList("W=bic")); expectedFeatures.add(Arrays.asList("W=?", "IsNonAlphanum")); DocumentAffiliation instance = new DocumentAffiliation(text); instance.setTokens(TOKENIZER.tokenize(instance.getRawText())); EXTRACTOR.calculateFeatures(instance); for (int i = 0; i < expectedFeatures.size(); i++) { List<String> expected = expectedFeatures.get(i); List<String> actual = instance.getTokens().get(i).getFeatures(); Collections.sort(expected); Collections.sort(actual); assertEquals(expected, actual); } } }
7,507
43.426036
168
java
CERMINE
CERMINE-master/cermine-impl/src/test/java/pl/edu/icm/cermine/metadata/affiliation/tools/NLMAffiliationExtractorTest.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.tools; import java.io.IOException; import java.util.List; import org.jdom.Element; import org.jdom.JDOMException; import org.jdom.output.XMLOutputter; import static org.junit.Assert.assertEquals; import org.junit.Test; import org.xml.sax.InputSource; import pl.edu.icm.cermine.exception.TransformationException; import pl.edu.icm.cermine.metadata.model.DocumentAffiliation; import pl.edu.icm.cermine.metadata.transformers.MetadataToNLMConverter; /** * @author Bartosz Tarnawski */ public class NLMAffiliationExtractorTest { private final NLMAffiliationExtractor instance = new NLMAffiliationExtractor(); @Test public void testExtractStrings() throws JDOMException, IOException, TransformationException { InputSource source = new InputSource(NLMAffiliationExtractor.class.getResourceAsStream( "test-nlm-extract-affs.xml")); String[] expectedString = { "<aff id=\"aff\"><label></label><institution>School</institution><institution>of</institution><institution>Biological</institution><institution>and</institution><institution>Chemical</institution><institution>Sciences</institution><institution>,</institution><institution>Queen</institution><institution>Mary</institution><institution>University</institution><institution>of</institution><institution>London</institution>,<addr-line>London</addr-line>,<country country=\"UK\">UK</country></aff>", "<aff id=\"aff\"><label></label><institution>Department</institution><institution>of</institution><institution>Pathology</institution><institution>,</institution><institution>University</institution><institution>of</institution><institution>Cincinnati</institution><institution>College</institution><institution>of</institution><institution>Medicine</institution>,<country country=\"US\">USA</country></aff>" }; MetadataToNLMConverter converter = new MetadataToNLMConverter(); XMLOutputter outputter = new XMLOutputter(); List<DocumentAffiliation> affs = instance.extractStrings(source); assertEquals(affs.size(), 2); for (int i = 0; i < 2; i++) { Element element = converter.convertAffiliation(affs.get(i)); String actual = outputter.outputString(element); String expected = expectedString[i]; assertEquals(expected, actual); } } }
3,149
50.639344
508
java