index
int64
repo_id
string
file_path
string
content
string
0
java-sources/ai/idylnlp/idylnlp-opennlp-tools-1.8.3/1.1.0/opennlp/tools/cmdline
java-sources/ai/idylnlp/idylnlp-opennlp-tools-1.8.3/1.1.0/opennlp/tools/cmdline/params/EncodingParameter.java
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package opennlp.tools.cmdline.params; import java.nio.charset.Charset; import opennlp.tools.cmdline.ArgumentParser.OptionalParameter; import opennlp.tools.cmdline.ArgumentParser.ParameterDescription; /** * Encoding parameter. The DEFAULT_CHARSET is handled by ArgumentParser.Parse(). * * Note: Do not use this class, internal use only! */ public interface EncodingParameter { @ParameterDescription(valueName = "charsetName", description = "encoding for reading and writing text, if absent the system default is used.") @OptionalParameter(defaultValue = OptionalParameter.DEFAULT_CHARSET) Charset getEncoding(); }
0
java-sources/ai/idylnlp/idylnlp-opennlp-tools-1.8.3/1.1.0/opennlp/tools/cmdline
java-sources/ai/idylnlp/idylnlp-opennlp-tools-1.8.3/1.1.0/opennlp/tools/cmdline/params/EvaluatorParams.java
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package opennlp.tools.cmdline.params; import java.io.File; import opennlp.tools.cmdline.ArgumentParser.OptionalParameter; import opennlp.tools.cmdline.ArgumentParser.ParameterDescription; /** * Common evaluation parameters. * * Note: Do not use this class, internal use only! */ public interface EvaluatorParams { @ParameterDescription(valueName = "model", description = "the model file to be evaluated.") File getModel(); @ParameterDescription(valueName = "true|false", description = "if true will print false negatives and false positives.") @OptionalParameter(defaultValue = "false") Boolean getMisclassified(); }
0
java-sources/ai/idylnlp/idylnlp-opennlp-tools-1.8.3/1.1.0/opennlp/tools/cmdline
java-sources/ai/idylnlp/idylnlp-opennlp-tools-1.8.3/1.1.0/opennlp/tools/cmdline/params/FineGrainedEvaluatorParams.java
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package opennlp.tools.cmdline.params; import java.io.File; import opennlp.tools.cmdline.ArgumentParser; /** * Common evaluation parameters. * * Note: Do not use this class, internal use only! */ public interface FineGrainedEvaluatorParams { @ArgumentParser.ParameterDescription(valueName = "outputFile", description = "the path of the fine-grained report file.") @ArgumentParser.OptionalParameter File getReportOutputFile(); }
0
java-sources/ai/idylnlp/idylnlp-opennlp-tools-1.8.3/1.1.0/opennlp/tools/cmdline
java-sources/ai/idylnlp/idylnlp-opennlp-tools-1.8.3/1.1.0/opennlp/tools/cmdline/params/LanguageParams.java
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package opennlp.tools.cmdline.params; import opennlp.tools.cmdline.ArgumentParser.ParameterDescription; public interface LanguageParams { @ParameterDescription(valueName = "language", description = "language which is being processed.") String getLang(); }
0
java-sources/ai/idylnlp/idylnlp-opennlp-tools-1.8.3/1.1.0/opennlp/tools/cmdline
java-sources/ai/idylnlp/idylnlp-opennlp-tools-1.8.3/1.1.0/opennlp/tools/cmdline/params/TrainingToolParams.java
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package opennlp.tools.cmdline.params; import java.io.File; import opennlp.tools.cmdline.ArgumentParser.ParameterDescription; /** * Common training parameters. * * Note: Do not use this class, internal use only! */ public interface TrainingToolParams extends BasicTrainingParams { @ParameterDescription(valueName = "modelFile", description = "output model file.") File getModel(); }
0
java-sources/ai/idylnlp/idylnlp-opennlp-tools-1.8.3/1.1.0/opennlp/tools/cmdline
java-sources/ai/idylnlp/idylnlp-opennlp-tools-1.8.3/1.1.0/opennlp/tools/cmdline/parser/BuildModelUpdaterTool.java
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package opennlp.tools.cmdline.parser; import java.io.IOException; import opennlp.tools.dictionary.Dictionary; import opennlp.tools.ml.EventTrainer; import opennlp.tools.ml.TrainerFactory; import opennlp.tools.ml.model.Event; import opennlp.tools.ml.model.MaxentModel; import opennlp.tools.parser.Parse; import opennlp.tools.parser.ParserEventTypeEnum; import opennlp.tools.parser.ParserModel; import opennlp.tools.parser.chunking.ParserEventStream; import opennlp.tools.util.ObjectStream; import opennlp.tools.util.model.ModelUtil; public final class BuildModelUpdaterTool extends ModelUpdaterTool { public String getShortDescription() { return "trains and updates the build model in a parser model"; } @Override protected ParserModel trainAndUpdate(ParserModel originalModel, ObjectStream<Parse> parseSamples, ModelUpdaterParams parameters) throws IOException { Dictionary mdict = ParserTrainerTool.buildDictionary(parseSamples, originalModel.getHeadRules(), 5); parseSamples.reset(); // TODO: training individual models should be in the chunking parser, not here // Training build System.out.println("Training builder"); ObjectStream<Event> bes = new ParserEventStream(parseSamples, originalModel.getHeadRules(), ParserEventTypeEnum.BUILD, mdict); EventTrainer trainer = TrainerFactory.getEventTrainer( ModelUtil.createDefaultTrainingParameters(), null); MaxentModel buildModel = trainer.train(bes); parseSamples.close(); return originalModel.updateBuildModel(buildModel); } }
0
java-sources/ai/idylnlp/idylnlp-opennlp-tools-1.8.3/1.1.0/opennlp/tools/cmdline
java-sources/ai/idylnlp/idylnlp-opennlp-tools-1.8.3/1.1.0/opennlp/tools/cmdline/parser/CheckModelUpdaterTool.java
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package opennlp.tools.cmdline.parser; import java.io.IOException; import opennlp.tools.dictionary.Dictionary; import opennlp.tools.ml.EventTrainer; import opennlp.tools.ml.TrainerFactory; import opennlp.tools.ml.model.Event; import opennlp.tools.ml.model.MaxentModel; import opennlp.tools.parser.Parse; import opennlp.tools.parser.ParserEventTypeEnum; import opennlp.tools.parser.ParserModel; import opennlp.tools.parser.chunking.ParserEventStream; import opennlp.tools.util.ObjectStream; import opennlp.tools.util.model.ModelUtil; // trains a new check model ... public final class CheckModelUpdaterTool extends ModelUpdaterTool { public String getShortDescription() { return "trains and updates the check model in a parser model"; } @Override protected ParserModel trainAndUpdate(ParserModel originalModel, ObjectStream<Parse> parseSamples, ModelUpdaterParams parameters) throws IOException { Dictionary mdict = ParserTrainerTool.buildDictionary(parseSamples, originalModel.getHeadRules(), 5); parseSamples.reset(); // TODO: Maybe that should be part of the ChunkingParser ... // Training build System.out.println("Training check model"); ObjectStream<Event> bes = new ParserEventStream(parseSamples, originalModel.getHeadRules(), ParserEventTypeEnum.CHECK, mdict); EventTrainer trainer = TrainerFactory.getEventTrainer( ModelUtil.createDefaultTrainingParameters(), null); MaxentModel checkModel = trainer.train(bes); parseSamples.close(); return originalModel.updateCheckModel(checkModel); } }
0
java-sources/ai/idylnlp/idylnlp-opennlp-tools-1.8.3/1.1.0/opennlp/tools/cmdline
java-sources/ai/idylnlp/idylnlp-opennlp-tools-1.8.3/1.1.0/opennlp/tools/cmdline/parser/ModelUpdaterTool.java
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package opennlp.tools.cmdline.parser; import java.io.File; import java.io.IOException; import opennlp.tools.cmdline.AbstractTypedParamTool; import opennlp.tools.cmdline.ArgumentParser; import opennlp.tools.cmdline.CmdLineUtil; import opennlp.tools.cmdline.ObjectStreamFactory; import opennlp.tools.cmdline.TerminateToolException; import opennlp.tools.cmdline.params.TrainingToolParams; import opennlp.tools.parser.Parse; import opennlp.tools.parser.ParserModel; import opennlp.tools.util.ObjectStream; /** * Abstract base class for tools which update the parser model. */ abstract class ModelUpdaterTool extends AbstractTypedParamTool<Parse, ModelUpdaterTool.ModelUpdaterParams> { interface ModelUpdaterParams extends TrainingToolParams { } protected ModelUpdaterTool() { super(Parse.class, ModelUpdaterParams.class); } protected abstract ParserModel trainAndUpdate(ParserModel originalModel, ObjectStream<Parse> parseSamples, ModelUpdaterParams parameters) throws IOException; public final void run(String format, String[] args) { ModelUpdaterParams params = validateAndParseParams( ArgumentParser.filter(args, ModelUpdaterParams.class), ModelUpdaterParams.class); // Load model to be updated File modelFile = params.getModel(); ParserModel originalParserModel = new ParserModelLoader().load(modelFile); ObjectStreamFactory<Parse> factory = getStreamFactory(format); String[] fargs = ArgumentParser.filter(args, factory.getParameters()); validateFactoryArgs(factory, fargs); ObjectStream<Parse> sampleStream = factory.create(fargs); ParserModel updatedParserModel; try { updatedParserModel = trainAndUpdate(originalParserModel, sampleStream, params); } catch (IOException e) { throw new TerminateToolException(-1, "IO error while reading training data or indexing data: " + e.getMessage(), e); } finally { try { sampleStream.close(); } catch (IOException e) { // sorry that this can fail } } CmdLineUtil.writeModel("parser", modelFile, updatedParserModel); } }
0
java-sources/ai/idylnlp/idylnlp-opennlp-tools-1.8.3/1.1.0/opennlp/tools/cmdline
java-sources/ai/idylnlp/idylnlp-opennlp-tools-1.8.3/1.1.0/opennlp/tools/cmdline/parser/ParserConverterTool.java
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package opennlp.tools.cmdline.parser; import opennlp.tools.cmdline.AbstractConverterTool; import opennlp.tools.parser.Parse; public class ParserConverterTool extends AbstractConverterTool<Parse> { public ParserConverterTool() { super(Parse.class); } }
0
java-sources/ai/idylnlp/idylnlp-opennlp-tools-1.8.3/1.1.0/opennlp/tools/cmdline
java-sources/ai/idylnlp/idylnlp-opennlp-tools-1.8.3/1.1.0/opennlp/tools/cmdline/parser/ParserEvaluatorTool.java
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package opennlp.tools.cmdline.parser; import java.io.IOException; import opennlp.tools.cmdline.AbstractEvaluatorTool; import opennlp.tools.cmdline.TerminateToolException; import opennlp.tools.cmdline.params.EvaluatorParams; import opennlp.tools.parser.Parse; import opennlp.tools.parser.Parser; import opennlp.tools.parser.ParserEvaluator; import opennlp.tools.parser.ParserFactory; import opennlp.tools.parser.ParserModel; public class ParserEvaluatorTool extends AbstractEvaluatorTool<Parse, EvaluatorParams> { public ParserEvaluatorTool() { super(Parse.class, EvaluatorParams.class); } public String getShortDescription() { return "Measures the performance of the Parser model with the reference data"; } @Override public void run(String format, String[] args) { super.run(format, args); ParserModel model = new ParserModelLoader().load(params.getModel()); Parser parser = ParserFactory.create(model); ParserEvaluator evaluator = new ParserEvaluator(parser); System.out.print("Evaluating ... "); try { evaluator.evaluate(sampleStream); } catch (IOException e) { System.err.println("failed"); throw new TerminateToolException(-1, "IO error while reading test data: " + e.getMessage(), e); } finally { try { sampleStream.close(); } catch (IOException e) { // sorry that this can fail } } System.out.println("done"); System.out.println(); System.out.println(evaluator.getFMeasure()); } }
0
java-sources/ai/idylnlp/idylnlp-opennlp-tools-1.8.3/1.1.0/opennlp/tools/cmdline
java-sources/ai/idylnlp/idylnlp-opennlp-tools-1.8.3/1.1.0/opennlp/tools/cmdline/parser/ParserModelLoader.java
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package opennlp.tools.cmdline.parser; import java.io.IOException; import java.io.InputStream; import opennlp.tools.cmdline.ModelLoader; import opennlp.tools.parser.ParserModel; import opennlp.tools.util.InvalidFormatException; /** * Loads a Parser Model for the command line tools. * <p> * <b>Note:</b> Do not use this class, internal use only! */ public final class ParserModelLoader extends ModelLoader<ParserModel> { public ParserModelLoader() { super("Parser"); } @Override protected ParserModel loadModel(InputStream modelIn) throws IOException, InvalidFormatException { return new ParserModel(modelIn); } }
0
java-sources/ai/idylnlp/idylnlp-opennlp-tools-1.8.3/1.1.0/opennlp/tools/cmdline
java-sources/ai/idylnlp/idylnlp-opennlp-tools-1.8.3/1.1.0/opennlp/tools/cmdline/parser/ParserTool.java
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package opennlp.tools.cmdline.parser; import java.io.File; import java.io.IOException; import java.util.Arrays; import java.util.Iterator; import java.util.List; import java.util.regex.Pattern; import opennlp.tools.cmdline.BasicCmdLineTool; import opennlp.tools.cmdline.CLI; import opennlp.tools.cmdline.CmdLineUtil; import opennlp.tools.cmdline.PerformanceMonitor; import opennlp.tools.cmdline.SystemInputStreamFactory; import opennlp.tools.cmdline.tokenizer.TokenizerModelLoader; import opennlp.tools.parser.AbstractBottomUpParser; import opennlp.tools.parser.Parse; import opennlp.tools.parser.Parser; import opennlp.tools.parser.ParserFactory; import opennlp.tools.parser.ParserModel; import opennlp.tools.tokenize.Tokenizer; import opennlp.tools.tokenize.TokenizerME; import opennlp.tools.tokenize.TokenizerModel; import opennlp.tools.tokenize.WhitespaceTokenizer; import opennlp.tools.util.ObjectStream; import opennlp.tools.util.PlainTextByLineStream; import opennlp.tools.util.Span; public final class ParserTool extends BasicCmdLineTool { public String getShortDescription() { return "performs full syntactic parsing"; } public String getHelp() { return "Usage: " + CLI.CMD + " " + getName() + " [-bs n -ap n -k n -tk tok_model] model < sentences \n" + "-bs n: Use a beam size of n.\n" + "-ap f: Advance outcomes in with at least f% of the probability mass.\n" + "-k n: Show the top n parses. This will also display their log-probablities.\n" + "-tk tok_model: Use the specified tokenizer model to tokenize the sentences. " + "Defaults to a WhitespaceTokenizer."; } private static Pattern untokenizedParenPattern1 = Pattern.compile("([^ ])([({)}])"); private static Pattern untokenizedParenPattern2 = Pattern.compile("([({)}])([^ ])"); public static Parse[] parseLine(String line, Parser parser, int numParses) { return parseLine( line, parser, WhitespaceTokenizer.INSTANCE, numParses ); } public static Parse[] parseLine(String line, Parser parser, Tokenizer tokenizer, int numParses) { // fix some parens patterns line = untokenizedParenPattern1.matcher(line).replaceAll("$1 $2"); line = untokenizedParenPattern2.matcher(line).replaceAll("$1 $2"); // tokenize List<String> tokens = Arrays.asList( tokenizer.tokenize(line)); String text = String.join(" ", tokens); Parse p = new Parse(text, new Span(0, text.length()), AbstractBottomUpParser.INC_NODE, 0, 0); int start = 0; int i = 0; for (Iterator<String> ti = tokens.iterator(); ti.hasNext(); i++) { String tok = ti.next(); p.insert(new Parse(text, new Span(start, start + tok.length()), AbstractBottomUpParser.TOK_NODE, 0, i)); start += tok.length() + 1; } Parse[] parses; if (numParses == 1) { parses = new Parse[]{parser.parse(p)}; } else { parses = parser.parse(p, numParses); } return parses; } public void run(String[] args) { if (args.length < 1) { System.out.println(getHelp()); } else { ParserModel model = new ParserModelLoader().load(new File(args[args.length - 1])); Integer beamSize = CmdLineUtil.getIntParameter("-bs", args); if (beamSize == null) { beamSize = AbstractBottomUpParser.defaultBeamSize; } Integer numParses = CmdLineUtil.getIntParameter("-k", args); boolean showTopK; if (numParses == null) { numParses = 1; showTopK = false; } else { showTopK = true; } Double advancePercentage = CmdLineUtil.getDoubleParameter("-ap", args); if (advancePercentage == null) { advancePercentage = AbstractBottomUpParser.defaultAdvancePercentage; } Tokenizer tokenizer = WhitespaceTokenizer.INSTANCE; String tokenizerModelName = CmdLineUtil.getParameter( "-tk", args ); if (tokenizerModelName != null ) { TokenizerModel tokenizerModel = new TokenizerModelLoader().load(new File(tokenizerModelName)); tokenizer = new TokenizerME( tokenizerModel ); } Parser parser = ParserFactory.create(model, beamSize, advancePercentage); ObjectStream<String> lineStream = null; PerformanceMonitor perfMon = null; try { lineStream = new PlainTextByLineStream(new SystemInputStreamFactory(), SystemInputStreamFactory.encoding()); perfMon = new PerformanceMonitor(System.err, "sent"); perfMon.start(); String line; while ((line = lineStream.read()) != null) { if (line.trim().length() == 0) { System.out.println(); } else { Parse[] parses = parseLine(line, parser, tokenizer, numParses); for (int pi = 0, pn = parses.length; pi < pn; pi++) { if (showTopK) { System.out.print(pi + " " + parses[pi].getProb() + " "); } parses[pi].show(); perfMon.incrementCounter(); } } } } catch (IOException e) { CmdLineUtil.handleStdinIoError(e); } perfMon.stopAndPrintFinalResult(); } } }
0
java-sources/ai/idylnlp/idylnlp-opennlp-tools-1.8.3/1.1.0/opennlp/tools/cmdline
java-sources/ai/idylnlp/idylnlp-opennlp-tools-1.8.3/1.1.0/opennlp/tools/cmdline/parser/ParserTrainerTool.java
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package opennlp.tools.cmdline.parser; import java.io.File; import java.io.FileInputStream; import java.io.IOException; import opennlp.tools.cmdline.AbstractTrainerTool; import opennlp.tools.cmdline.CmdLineUtil; import opennlp.tools.cmdline.TerminateToolException; import opennlp.tools.cmdline.params.EncodingParameter; import opennlp.tools.cmdline.params.TrainingToolParams; import opennlp.tools.cmdline.parser.ParserTrainerTool.TrainerToolParams; import opennlp.tools.dictionary.Dictionary; import opennlp.tools.ml.TrainerFactory; import opennlp.tools.parser.HeadRules; import opennlp.tools.parser.Parse; import opennlp.tools.parser.ParserModel; import opennlp.tools.parser.ParserType; import opennlp.tools.parser.chunking.Parser; import opennlp.tools.util.ObjectStream; import opennlp.tools.util.ext.ExtensionLoader; import opennlp.tools.util.model.ArtifactSerializer; import opennlp.tools.util.model.ModelUtil; public final class ParserTrainerTool extends AbstractTrainerTool<Parse, TrainerToolParams> { interface TrainerToolParams extends TrainingParams, TrainingToolParams, EncodingParameter { } public ParserTrainerTool() { super(Parse.class, TrainerToolParams.class); } public String getShortDescription() { return "trains the learnable parser"; } static Dictionary buildDictionary(ObjectStream<Parse> parseSamples, HeadRules headRules, int cutoff) { System.err.print("Building dictionary ..."); Dictionary mdict; try { mdict = Parser. buildDictionary(parseSamples, headRules, cutoff); } catch (IOException e) { System.err.println("Error while building dictionary: " + e.getMessage()); mdict = null; } System.err.println("done"); return mdict; } static ParserType parseParserType(String typeAsString) { ParserType type = null; if (typeAsString != null && typeAsString.length() > 0) { type = ParserType.parse(typeAsString); if (type == null) { throw new TerminateToolException(1, "ParserType training parameter '" + typeAsString + "' is invalid!"); } } return type; } static HeadRules creaeHeadRules(TrainerToolParams params) throws IOException { ArtifactSerializer headRulesSerializer; if (params.getHeadRulesSerializerImpl() != null) { headRulesSerializer = ExtensionLoader.instantiateExtension(ArtifactSerializer.class, params.getHeadRulesSerializerImpl()); } else { if ("en".equals(params.getLang()) || "eng".equals(params.getLang())) { headRulesSerializer = new opennlp.tools.parser.lang.en.HeadRules.HeadRulesSerializer(); } else if ("es".equals(params.getLang()) || "spa".equals(params.getLang())) { headRulesSerializer = new opennlp.tools.parser.lang.es.AncoraSpanishHeadRules.HeadRulesSerializer(); } else { // default for now, this case should probably cause an error ... headRulesSerializer = new opennlp.tools.parser.lang.en.HeadRules.HeadRulesSerializer(); } } Object headRulesObject = headRulesSerializer.create(new FileInputStream(params.getHeadRules())); if (headRulesObject instanceof HeadRules) { return (HeadRules) headRulesObject; } else { throw new TerminateToolException(-1, "HeadRules Artifact Serializer must create an object of type HeadRules!"); } } // TODO: Add param to train tree insert parser public void run(String format, String[] args) { super.run(format, args); mlParams = CmdLineUtil.loadTrainingParameters(params.getParams(), true); if (mlParams != null) { if (!TrainerFactory.isValid(mlParams.getParameters("build"))) { throw new TerminateToolException(1, "Build training parameters are invalid!"); } if (!TrainerFactory.isValid(mlParams.getParameters("check"))) { throw new TerminateToolException(1, "Check training parameters are invalid!"); } if (!TrainerFactory.isValid(mlParams.getParameters("attach"))) { throw new TerminateToolException(1, "Attach training parameters are invalid!"); } if (!TrainerFactory.isValid(mlParams.getParameters("tagger"))) { throw new TerminateToolException(1, "Tagger training parameters are invalid!"); } if (!TrainerFactory.isValid(mlParams.getParameters("chunker"))) { throw new TerminateToolException(1, "Chunker training parameters are invalid!"); } } if (mlParams == null) { mlParams = ModelUtil.createDefaultTrainingParameters(); } File modelOutFile = params.getModel(); CmdLineUtil.checkOutputFile("parser model", modelOutFile); ParserModel model; try { HeadRules rules = creaeHeadRules(params); ParserType type = parseParserType(params.getParserType()); if (params.getFun()) { Parse.useFunctionTags(true); } if (ParserType.CHUNKING.equals(type)) { model = opennlp.tools.parser.chunking.Parser.train( params.getLang(), sampleStream, rules, mlParams); } else if (ParserType.TREEINSERT.equals(type)) { model = opennlp.tools.parser.treeinsert.Parser.train(params.getLang(), sampleStream, rules, mlParams); } else { throw new IllegalStateException(); } } catch (IOException e) { throw createTerminationIOException(e); } finally { try { sampleStream.close(); } catch (IOException e) { // sorry that this can fail } } CmdLineUtil.writeModel("parser", modelOutFile, model); } }
0
java-sources/ai/idylnlp/idylnlp-opennlp-tools-1.8.3/1.1.0/opennlp/tools/cmdline
java-sources/ai/idylnlp/idylnlp-opennlp-tools-1.8.3/1.1.0/opennlp/tools/cmdline/parser/TaggerModelReplacerTool.java
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package opennlp.tools.cmdline.parser; import java.io.File; import opennlp.tools.cmdline.BasicCmdLineTool; import opennlp.tools.cmdline.CLI; import opennlp.tools.cmdline.CmdLineUtil; import opennlp.tools.cmdline.postag.POSModelLoader; import opennlp.tools.parser.ParserModel; import opennlp.tools.postag.POSModel; // user should train with the POS tool public final class TaggerModelReplacerTool extends BasicCmdLineTool { public String getShortDescription() { return "replaces the tagger model in a parser model"; } public String getHelp() { return "Usage: " + CLI.CMD + " " + getName() + " parser.model tagger.model"; } public void run(String[] args) { if (args.length != 2) { System.out.println(getHelp()); } else { File parserModelInFile = new File(args[0]); ParserModel parserModel = new ParserModelLoader().load(parserModelInFile); File taggerModelInFile = new File(args[1]); POSModel taggerModel = new POSModelLoader().load(taggerModelInFile); ParserModel updatedParserModel = parserModel.updateTaggerModel(taggerModel); CmdLineUtil.writeModel("parser", parserModelInFile, updatedParserModel); } } }
0
java-sources/ai/idylnlp/idylnlp-opennlp-tools-1.8.3/1.1.0/opennlp/tools/cmdline
java-sources/ai/idylnlp/idylnlp-opennlp-tools-1.8.3/1.1.0/opennlp/tools/cmdline/parser/TrainingParams.java
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package opennlp.tools.cmdline.parser; import java.io.File; import opennlp.tools.cmdline.ArgumentParser.OptionalParameter; import opennlp.tools.cmdline.ArgumentParser.ParameterDescription; import opennlp.tools.cmdline.params.BasicTrainingParams; /** * TrainingParams for Parser. * * Note: Do not use this class, internal use only! */ interface TrainingParams extends BasicTrainingParams { @ParameterDescription(valueName = "CHUNKING|TREEINSERT", description = "one of CHUNKING or TREEINSERT, default is CHUNKING.") @OptionalParameter(defaultValue = "CHUNKING") String getParserType(); @ParameterDescription(valueName = "className", description = "head rules artifact serializer class name") @OptionalParameter String getHeadRulesSerializerImpl(); @ParameterDescription(valueName = "headRulesFile", description = "head rules file.") File getHeadRules(); @ParameterDescription(valueName = "true|false", description = "Learn to generate function tags.") @OptionalParameter(defaultValue = "false") Boolean getFun(); }
0
java-sources/ai/idylnlp/idylnlp-opennlp-tools-1.8.3/1.1.0/opennlp/tools/cmdline
java-sources/ai/idylnlp/idylnlp-opennlp-tools-1.8.3/1.1.0/opennlp/tools/cmdline/postag/POSEvaluationErrorListener.java
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package opennlp.tools.cmdline.postag; import java.io.OutputStream; import opennlp.tools.cmdline.EvaluationErrorPrinter; import opennlp.tools.postag.POSSample; import opennlp.tools.postag.POSTaggerEvaluationMonitor; import opennlp.tools.util.eval.EvaluationMonitor; /** * A default implementation of {@link EvaluationMonitor} that prints * to an output stream. * */ public class POSEvaluationErrorListener extends EvaluationErrorPrinter<POSSample> implements POSTaggerEvaluationMonitor { /** * Creates a listener that will print to System.err */ public POSEvaluationErrorListener() { super(System.err); } /** * Creates a listener that will print to a given {@link OutputStream} */ public POSEvaluationErrorListener(OutputStream outputStream) { super(outputStream); } @Override public void missclassified(POSSample reference, POSSample prediction) { printError(reference.getTags(), prediction.getTags(), reference, prediction, reference.getSentence()); } }
0
java-sources/ai/idylnlp/idylnlp-opennlp-tools-1.8.3/1.1.0/opennlp/tools/cmdline
java-sources/ai/idylnlp/idylnlp-opennlp-tools-1.8.3/1.1.0/opennlp/tools/cmdline/postag/POSModelLoader.java
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package opennlp.tools.cmdline.postag; import java.io.IOException; import java.io.InputStream; import opennlp.tools.cmdline.ModelLoader; import opennlp.tools.postag.POSModel; /** * Loads a POS Tagger Model for the command line tools. * <p> * <b>Note:</b> Do not use this class, internal use only! */ public final class POSModelLoader extends ModelLoader<POSModel> { public POSModelLoader() { super("POS Tagger"); } @Override protected POSModel loadModel(InputStream modelIn) throws IOException { return new POSModel(modelIn); } }
0
java-sources/ai/idylnlp/idylnlp-opennlp-tools-1.8.3/1.1.0/opennlp/tools/cmdline
java-sources/ai/idylnlp/idylnlp-opennlp-tools-1.8.3/1.1.0/opennlp/tools/cmdline/postag/POSTaggerConverterTool.java
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package opennlp.tools.cmdline.postag; import opennlp.tools.cmdline.AbstractConverterTool; import opennlp.tools.postag.POSSample; public class POSTaggerConverterTool extends AbstractConverterTool<POSSample> { public POSTaggerConverterTool() { super(POSSample.class); } }
0
java-sources/ai/idylnlp/idylnlp-opennlp-tools-1.8.3/1.1.0/opennlp/tools/cmdline
java-sources/ai/idylnlp/idylnlp-opennlp-tools-1.8.3/1.1.0/opennlp/tools/cmdline/postag/POSTaggerCrossValidatorTool.java
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package opennlp.tools.cmdline.postag; import java.io.File; import java.io.FileNotFoundException; import java.io.FileOutputStream; import java.io.IOException; import java.io.OutputStream; import java.util.Map; import opennlp.tools.cmdline.AbstractCrossValidatorTool; import opennlp.tools.cmdline.CmdLineUtil; import opennlp.tools.cmdline.TerminateToolException; import opennlp.tools.cmdline.namefind.TokenNameFinderTrainerTool; import opennlp.tools.cmdline.params.CVParams; import opennlp.tools.cmdline.params.FineGrainedEvaluatorParams; import opennlp.tools.cmdline.postag.POSTaggerCrossValidatorTool.CVToolParams; import opennlp.tools.postag.POSSample; import opennlp.tools.postag.POSTaggerCrossValidator; import opennlp.tools.postag.POSTaggerEvaluationMonitor; import opennlp.tools.util.model.ModelUtil; public final class POSTaggerCrossValidatorTool extends AbstractCrossValidatorTool<POSSample, CVToolParams> { interface CVToolParams extends CVParams, TrainingParams, FineGrainedEvaluatorParams { } public POSTaggerCrossValidatorTool() { super(POSSample.class, CVToolParams.class); } public String getShortDescription() { return "K-fold cross validator for the learnable POS tagger"; } public void run(String format, String[] args) { super.run(format, args); mlParams = CmdLineUtil.loadTrainingParameters(params.getParams(), false); if (mlParams == null) { mlParams = ModelUtil.createDefaultTrainingParameters(); } POSTaggerEvaluationMonitor missclassifiedListener = null; if (params.getMisclassified()) { missclassifiedListener = new POSEvaluationErrorListener(); } POSTaggerFineGrainedReportListener reportListener = null; File reportFile = params.getReportOutputFile(); OutputStream reportOutputStream = null; if (reportFile != null) { CmdLineUtil.checkOutputFile("Report Output File", reportFile); try { reportOutputStream = new FileOutputStream(reportFile); reportListener = new POSTaggerFineGrainedReportListener( reportOutputStream); } catch (FileNotFoundException e) { throw createTerminationIOException(e); } } Map<String, Object> resources; try { resources = TokenNameFinderTrainerTool.loadResources(params.getResources(), params.getFeaturegen()); } catch (IOException e) { throw new TerminateToolException(-1,"IO error while loading resources", e); } byte[] featureGeneratorBytes = TokenNameFinderTrainerTool.openFeatureGeneratorBytes(params.getFeaturegen()); POSTaggerCrossValidator validator; try { validator = new POSTaggerCrossValidator(params.getLang(), mlParams, params.getDict(), featureGeneratorBytes, resources, params.getTagDictCutoff(), params.getFactory(), missclassifiedListener, reportListener); validator.evaluate(sampleStream, params.getFolds()); } catch (IOException e) { throw new TerminateToolException(-1, "IO error while reading training data or indexing data: " + e.getMessage(), e); } finally { try { sampleStream.close(); } catch (IOException e) { // sorry that this can fail } } System.out.println("done"); if (reportListener != null) { System.out.println("Writing fine-grained report to " + params.getReportOutputFile().getAbsolutePath()); reportListener.writeReport(); try { // TODO: is it a problem to close the stream now? reportOutputStream.close(); } catch (IOException e) { // nothing to do } } System.out.println(); System.out.println("Accuracy: " + validator.getWordAccuracy()); } }
0
java-sources/ai/idylnlp/idylnlp-opennlp-tools-1.8.3/1.1.0/opennlp/tools/cmdline
java-sources/ai/idylnlp/idylnlp-opennlp-tools-1.8.3/1.1.0/opennlp/tools/cmdline/postag/POSTaggerEvaluatorTool.java
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package opennlp.tools.cmdline.postag; import java.io.File; import java.io.FileNotFoundException; import java.io.FileOutputStream; import java.io.IOException; import java.io.OutputStream; import opennlp.tools.cmdline.AbstractEvaluatorTool; import opennlp.tools.cmdline.CmdLineUtil; import opennlp.tools.cmdline.TerminateToolException; import opennlp.tools.cmdline.params.EvaluatorParams; import opennlp.tools.cmdline.params.FineGrainedEvaluatorParams; import opennlp.tools.cmdline.postag.POSTaggerEvaluatorTool.EvalToolParams; import opennlp.tools.postag.POSEvaluator; import opennlp.tools.postag.POSModel; import opennlp.tools.postag.POSSample; import opennlp.tools.postag.POSTaggerEvaluationMonitor; public final class POSTaggerEvaluatorTool extends AbstractEvaluatorTool<POSSample, EvalToolParams> { interface EvalToolParams extends EvaluatorParams, FineGrainedEvaluatorParams { } public POSTaggerEvaluatorTool() { super(POSSample.class, EvalToolParams.class); } public String getShortDescription() { return "Measures the performance of the POS tagger model with the reference data"; } public void run(String format, String[] args) { super.run(format, args); POSModel model = new POSModelLoader().load(params.getModel()); POSTaggerEvaluationMonitor missclassifiedListener = null; if (params.getMisclassified()) { missclassifiedListener = new POSEvaluationErrorListener(); } POSTaggerFineGrainedReportListener reportListener = null; File reportFile = params.getReportOutputFile(); OutputStream reportOutputStream = null; if (reportFile != null) { CmdLineUtil.checkOutputFile("Report Output File", reportFile); try { reportOutputStream = new FileOutputStream(reportFile); reportListener = new POSTaggerFineGrainedReportListener( reportOutputStream); } catch (FileNotFoundException e) { throw new TerminateToolException(-1, "IO error while creating POS Tagger fine-grained report file: " + e.getMessage()); } } POSEvaluator evaluator = new POSEvaluator( new opennlp.tools.postag.POSTaggerME(model), missclassifiedListener, reportListener); System.out.print("Evaluating ... "); try { evaluator.evaluate(sampleStream); } catch (IOException e) { System.err.println("failed"); throw new TerminateToolException(-1, "IO error while reading test data: " + e.getMessage(), e); } finally { try { sampleStream.close(); } catch (IOException e) { // sorry that this can fail } } System.out.println("done"); if (reportListener != null) { System.out.println("Writing fine-grained report to " + params.getReportOutputFile().getAbsolutePath()); reportListener.writeReport(); try { // TODO: is it a problem to close the stream now? reportOutputStream.close(); } catch (IOException e) { // nothing to do } } System.out.println(); System.out.println("Accuracy: " + evaluator.getWordAccuracy()); } }
0
java-sources/ai/idylnlp/idylnlp-opennlp-tools-1.8.3/1.1.0/opennlp/tools/cmdline
java-sources/ai/idylnlp/idylnlp-opennlp-tools-1.8.3/1.1.0/opennlp/tools/cmdline/postag/POSTaggerFineGrainedReportListener.java
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package opennlp.tools.cmdline.postag; import java.io.OutputStream; import opennlp.tools.cmdline.FineGrainedReportListener; import opennlp.tools.postag.POSSample; import opennlp.tools.postag.POSTaggerEvaluationMonitor; /** * Generates a detailed report for the POS Tagger. * <p> * It is possible to use it from an API and access the statistics using the * provided getters * */ public class POSTaggerFineGrainedReportListener extends FineGrainedReportListener implements POSTaggerEvaluationMonitor { /** * Creates a listener that will print to {@link System#err} */ public POSTaggerFineGrainedReportListener() { this(System.err); } /** * Creates a listener that prints to a given {@link OutputStream} */ public POSTaggerFineGrainedReportListener(OutputStream outputStream) { super(outputStream); } // methods inherited from EvaluationMonitor public void missclassified(POSSample reference, POSSample prediction) { statsAdd(reference, prediction); } public void correctlyClassified(POSSample reference, POSSample prediction) { statsAdd(reference, prediction); } private void statsAdd(POSSample reference, POSSample prediction) { getStats().add(reference.getSentence(), reference.getTags(), prediction.getTags()); } public void writeReport() { printGeneralStatistics(); // token stats printTokenErrorRank(); printTokenOcurrenciesRank(); // tag stats printTagsErrorRank(); // confusion tables printGeneralConfusionTable(); printDetailedConfusionMatrix(); } }
0
java-sources/ai/idylnlp/idylnlp-opennlp-tools-1.8.3/1.1.0/opennlp/tools/cmdline
java-sources/ai/idylnlp/idylnlp-opennlp-tools-1.8.3/1.1.0/opennlp/tools/cmdline/postag/POSTaggerTool.java
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package opennlp.tools.cmdline.postag; import java.io.File; import java.io.IOException; import opennlp.tools.cmdline.BasicCmdLineTool; import opennlp.tools.cmdline.CLI; import opennlp.tools.cmdline.CmdLineUtil; import opennlp.tools.cmdline.PerformanceMonitor; import opennlp.tools.cmdline.SystemInputStreamFactory; import opennlp.tools.postag.POSModel; import opennlp.tools.postag.POSSample; import opennlp.tools.postag.POSTaggerME; import opennlp.tools.tokenize.WhitespaceTokenizer; import opennlp.tools.util.ObjectStream; import opennlp.tools.util.PlainTextByLineStream; public final class POSTaggerTool extends BasicCmdLineTool { public String getShortDescription() { return "learnable part of speech tagger"; } public String getHelp() { return "Usage: " + CLI.CMD + " " + getName() + " model < sentences"; } public void run(String[] args) { if (args.length != 1) { System.out.println(getHelp()); } else { POSModel model = new POSModelLoader().load(new File(args[0])); POSTaggerME tagger = new POSTaggerME(model); ObjectStream<String> lineStream; PerformanceMonitor perfMon = null; try { lineStream = new PlainTextByLineStream(new SystemInputStreamFactory(), SystemInputStreamFactory.encoding()); perfMon = new PerformanceMonitor(System.err, "sent"); perfMon.start(); String line; while ((line = lineStream.read()) != null) { String[] whitespaceTokenizerLine = WhitespaceTokenizer.INSTANCE.tokenize(line); String[] tags = tagger.tag(whitespaceTokenizerLine); POSSample sample = new POSSample(whitespaceTokenizerLine, tags); System.out.println(sample.toString()); perfMon.incrementCounter(); } } catch (IOException e) { CmdLineUtil.handleStdinIoError(e); } perfMon.stopAndPrintFinalResult(); } } }
0
java-sources/ai/idylnlp/idylnlp-opennlp-tools-1.8.3/1.1.0/opennlp/tools/cmdline
java-sources/ai/idylnlp/idylnlp-opennlp-tools-1.8.3/1.1.0/opennlp/tools/cmdline/postag/POSTaggerTrainerTool.java
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package opennlp.tools.cmdline.postag; import java.io.File; import java.io.IOException; import java.util.Map; import opennlp.tools.cmdline.AbstractTrainerTool; import opennlp.tools.cmdline.CmdLineUtil; import opennlp.tools.cmdline.TerminateToolException; import opennlp.tools.cmdline.namefind.TokenNameFinderTrainerTool; import opennlp.tools.cmdline.params.TrainingToolParams; import opennlp.tools.cmdline.postag.POSTaggerTrainerTool.TrainerToolParams; import opennlp.tools.ml.TrainerFactory; import opennlp.tools.postag.MutableTagDictionary; import opennlp.tools.postag.POSModel; import opennlp.tools.postag.POSSample; import opennlp.tools.postag.POSTaggerFactory; import opennlp.tools.postag.POSTaggerME; import opennlp.tools.postag.TagDictionary; import opennlp.tools.util.InvalidFormatException; import opennlp.tools.util.model.ModelUtil; public final class POSTaggerTrainerTool extends AbstractTrainerTool<POSSample, TrainerToolParams> { interface TrainerToolParams extends TrainingParams, TrainingToolParams { } public POSTaggerTrainerTool() { super(POSSample.class, TrainerToolParams.class); } public String getShortDescription() { return "trains a model for the part-of-speech tagger"; } public void run(String format, String[] args) { super.run(format, args); mlParams = CmdLineUtil.loadTrainingParameters(params.getParams(), true); if (mlParams != null && !TrainerFactory.isValid(mlParams)) { throw new TerminateToolException(1, "Training parameters file '" + params.getParams() + "' is invalid!"); } if (mlParams == null) { mlParams = ModelUtil.createDefaultTrainingParameters(); } File modelOutFile = params.getModel(); CmdLineUtil.checkOutputFile("pos tagger model", modelOutFile); Map<String, Object> resources; try { resources = TokenNameFinderTrainerTool.loadResources( params.getResources(), params.getFeaturegen()); } catch (IOException e) { throw new TerminateToolException(-1,"IO error while loading resources", e); } byte[] featureGeneratorBytes = TokenNameFinderTrainerTool.openFeatureGeneratorBytes(params.getFeaturegen()); POSTaggerFactory postaggerFactory; try { postaggerFactory = POSTaggerFactory.create(params.getFactory(), featureGeneratorBytes, resources, null); } catch (InvalidFormatException e) { throw new TerminateToolException(-1, e.getMessage(), e); } if (params.getDict() != null) { try { postaggerFactory.setTagDictionary(postaggerFactory .createTagDictionary(params.getDict())); } catch (IOException e) { throw new TerminateToolException(-1, "IO error while loading POS Dictionary", e); } } if (params.getTagDictCutoff() != null) { try { TagDictionary dict = postaggerFactory.getTagDictionary(); if (dict == null) { dict = postaggerFactory.createEmptyTagDictionary(); postaggerFactory.setTagDictionary(dict); } if (dict instanceof MutableTagDictionary) { POSTaggerME.populatePOSDictionary(sampleStream, (MutableTagDictionary)dict, params.getTagDictCutoff()); } else { throw new IllegalArgumentException( "Can't extend a POSDictionary that does not implement MutableTagDictionary."); } sampleStream.reset(); } catch (IOException e) { throw new TerminateToolException(-1, "IO error while creating/extending POS Dictionary: " + e.getMessage(), e); } } POSModel model; try { model = opennlp.tools.postag.POSTaggerME.train(params.getLang(), sampleStream, mlParams, postaggerFactory); } catch (IOException e) { throw createTerminationIOException(e); } finally { try { sampleStream.close(); } catch (IOException e) { // sorry that this can fail } } CmdLineUtil.writeModel("pos tagger", modelOutFile, model); } }
0
java-sources/ai/idylnlp/idylnlp-opennlp-tools-1.8.3/1.1.0/opennlp/tools/cmdline
java-sources/ai/idylnlp/idylnlp-opennlp-tools-1.8.3/1.1.0/opennlp/tools/cmdline/postag/TrainingParams.java
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package opennlp.tools.cmdline.postag; import java.io.File; import opennlp.tools.cmdline.ArgumentParser.OptionalParameter; import opennlp.tools.cmdline.ArgumentParser.ParameterDescription; import opennlp.tools.cmdline.params.BasicTrainingParams; /** * TrainingParameters for Name Finder. * * Note: Do not use this class, internal use only! */ interface TrainingParams extends BasicTrainingParams { @ParameterDescription(valueName = "featuregenFile", description = "The feature generator descriptor file") @OptionalParameter File getFeaturegen(); @ParameterDescription(valueName = "resourcesDir", description = "The resources directory") @OptionalParameter File getResources(); @ParameterDescription(valueName = "dictionaryPath", description = "The XML tag dictionary file") @OptionalParameter File getDict(); @ParameterDescription(valueName = "tagDictCutoff", description = "TagDictionary cutoff. If specified will create/expand a mutable TagDictionary") @OptionalParameter Integer getTagDictCutoff(); @ParameterDescription(valueName = "factoryName", description = "A sub-class of POSTaggerFactory where to get implementation and resources.") @OptionalParameter String getFactory(); }
0
java-sources/ai/idylnlp/idylnlp-opennlp-tools-1.8.3/1.1.0/opennlp/tools/cmdline
java-sources/ai/idylnlp/idylnlp-opennlp-tools-1.8.3/1.1.0/opennlp/tools/cmdline/sentdetect/SentenceDetectorConverterTool.java
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package opennlp.tools.cmdline.sentdetect; import opennlp.tools.cmdline.AbstractConverterTool; import opennlp.tools.sentdetect.SentenceSample; public class SentenceDetectorConverterTool extends AbstractConverterTool<SentenceSample> { public SentenceDetectorConverterTool() { super(SentenceSample.class); } }
0
java-sources/ai/idylnlp/idylnlp-opennlp-tools-1.8.3/1.1.0/opennlp/tools/cmdline
java-sources/ai/idylnlp/idylnlp-opennlp-tools-1.8.3/1.1.0/opennlp/tools/cmdline/sentdetect/SentenceDetectorCrossValidatorTool.java
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package opennlp.tools.cmdline.sentdetect; import java.io.IOException; import opennlp.tools.cmdline.AbstractCrossValidatorTool; import opennlp.tools.cmdline.CmdLineUtil; import opennlp.tools.cmdline.params.CVParams; import opennlp.tools.cmdline.sentdetect.SentenceDetectorCrossValidatorTool.CVToolParams; import opennlp.tools.dictionary.Dictionary; import opennlp.tools.sentdetect.SDCrossValidator; import opennlp.tools.sentdetect.SentenceDetectorEvaluationMonitor; import opennlp.tools.sentdetect.SentenceDetectorFactory; import opennlp.tools.sentdetect.SentenceSample; import opennlp.tools.sentdetect.SentenceSampleStream; import opennlp.tools.util.eval.FMeasure; import opennlp.tools.util.model.ModelUtil; public final class SentenceDetectorCrossValidatorTool extends AbstractCrossValidatorTool<SentenceSample, CVToolParams> { interface CVToolParams extends TrainingParams, CVParams { } public SentenceDetectorCrossValidatorTool() { super(SentenceSample.class, CVToolParams.class); } public String getShortDescription() { return "K-fold cross validator for the learnable sentence detector"; } public void run(String format, String[] args) { super.run(format, args); mlParams = CmdLineUtil.loadTrainingParameters(params.getParams(), false); if (mlParams == null) { mlParams = ModelUtil.createDefaultTrainingParameters(); } SDCrossValidator validator; SentenceDetectorEvaluationMonitor errorListener = null; if (params.getMisclassified()) { errorListener = new SentenceEvaluationErrorListener(); } char[] eos = null; if (params.getEosChars() != null) { String eosString = SentenceSampleStream.replaceNewLineEscapeTags(params.getEosChars()); eos = eosString.toCharArray(); } try { Dictionary abbreviations = SentenceDetectorTrainerTool.loadDict(params.getAbbDict()); SentenceDetectorFactory sdFactory = SentenceDetectorFactory.create( params.getFactory(), params.getLang(), true, abbreviations, eos); validator = new SDCrossValidator(params.getLang(), mlParams, sdFactory, errorListener); validator.evaluate(sampleStream, params.getFolds()); } catch (IOException e) { throw createTerminationIOException(e); } finally { try { sampleStream.close(); } catch (IOException e) { // sorry that this can fail } } FMeasure result = validator.getFMeasure(); System.out.println(result.toString()); } }
0
java-sources/ai/idylnlp/idylnlp-opennlp-tools-1.8.3/1.1.0/opennlp/tools/cmdline
java-sources/ai/idylnlp/idylnlp-opennlp-tools-1.8.3/1.1.0/opennlp/tools/cmdline/sentdetect/SentenceDetectorEvaluatorTool.java
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package opennlp.tools.cmdline.sentdetect; import java.io.IOException; import opennlp.tools.cmdline.AbstractEvaluatorTool; import opennlp.tools.cmdline.TerminateToolException; import opennlp.tools.cmdline.params.EvaluatorParams; import opennlp.tools.cmdline.sentdetect.SentenceDetectorEvaluatorTool.EvalToolParams; import opennlp.tools.sentdetect.SentenceDetectorEvaluationMonitor; import opennlp.tools.sentdetect.SentenceDetectorEvaluator; import opennlp.tools.sentdetect.SentenceDetectorME; import opennlp.tools.sentdetect.SentenceModel; import opennlp.tools.sentdetect.SentenceSample; public final class SentenceDetectorEvaluatorTool extends AbstractEvaluatorTool<SentenceSample, EvalToolParams> { interface EvalToolParams extends EvaluatorParams { } public SentenceDetectorEvaluatorTool() { super(SentenceSample.class, EvalToolParams.class); } public String getShortDescription() { return "evaluator for the learnable sentence detector"; } public void run(String format, String[] args) { super.run(format, args); SentenceModel model = new SentenceModelLoader().load(params.getModel()); SentenceDetectorEvaluationMonitor errorListener = null; if (params.getMisclassified()) { errorListener = new SentenceEvaluationErrorListener(); } SentenceDetectorEvaluator evaluator = new SentenceDetectorEvaluator( new SentenceDetectorME(model), errorListener); System.out.print("Evaluating ... "); try { evaluator.evaluate(sampleStream); } catch (IOException e) { throw new TerminateToolException(-1, "IO error while reading training data or indexing data: " + e.getMessage(), e); } finally { try { sampleStream.close(); } catch (IOException e) { // sorry that this can fail } } System.err.println("done"); System.out.println(); System.out.println(evaluator.getFMeasure()); } }
0
java-sources/ai/idylnlp/idylnlp-opennlp-tools-1.8.3/1.1.0/opennlp/tools/cmdline
java-sources/ai/idylnlp/idylnlp-opennlp-tools-1.8.3/1.1.0/opennlp/tools/cmdline/sentdetect/SentenceDetectorTool.java
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package opennlp.tools.cmdline.sentdetect; import java.io.File; import java.io.IOException; import opennlp.tools.cmdline.BasicCmdLineTool; import opennlp.tools.cmdline.CLI; import opennlp.tools.cmdline.CmdLineUtil; import opennlp.tools.cmdline.PerformanceMonitor; import opennlp.tools.cmdline.SystemInputStreamFactory; import opennlp.tools.sentdetect.SentenceDetectorME; import opennlp.tools.sentdetect.SentenceModel; import opennlp.tools.util.ObjectStream; import opennlp.tools.util.ParagraphStream; import opennlp.tools.util.PlainTextByLineStream; /** * A sentence detector which uses a maxent model to predict the sentences. */ public final class SentenceDetectorTool extends BasicCmdLineTool { public String getShortDescription() { return "learnable sentence detector"; } public String getHelp() { return "Usage: " + CLI.CMD + " " + getName() + " model < sentences"; } /** * Perform sentence detection the input stream. * * A newline will be treated as a paragraph boundary. */ public void run(String[] args) { if (args.length != 1) { System.out.println(getHelp()); } else { SentenceModel model = new SentenceModelLoader().load(new File(args[0])); SentenceDetectorME sdetector = new SentenceDetectorME(model); PerformanceMonitor perfMon = new PerformanceMonitor(System.err, "sent"); perfMon.start(); try (ObjectStream<String> paraStream = new ParagraphStream(new PlainTextByLineStream( new SystemInputStreamFactory(), SystemInputStreamFactory.encoding()))) { String para; while ((para = paraStream.read()) != null) { String[] sents = sdetector.sentDetect(para); for (String sentence : sents) { System.out.println(sentence); } perfMon.incrementCounter(sents.length); System.out.println(); } } catch (IOException e) { CmdLineUtil.handleStdinIoError(e); } perfMon.stopAndPrintFinalResult(); } } }
0
java-sources/ai/idylnlp/idylnlp-opennlp-tools-1.8.3/1.1.0/opennlp/tools/cmdline
java-sources/ai/idylnlp/idylnlp-opennlp-tools-1.8.3/1.1.0/opennlp/tools/cmdline/sentdetect/SentenceDetectorTrainerTool.java
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package opennlp.tools.cmdline.sentdetect; import java.io.File; import java.io.FileInputStream; import java.io.IOException; import opennlp.tools.cmdline.AbstractTrainerTool; import opennlp.tools.cmdline.CmdLineUtil; import opennlp.tools.cmdline.TerminateToolException; import opennlp.tools.cmdline.params.TrainingToolParams; import opennlp.tools.cmdline.sentdetect.SentenceDetectorTrainerTool.TrainerToolParams; import opennlp.tools.dictionary.Dictionary; import opennlp.tools.ml.TrainerFactory; import opennlp.tools.ml.TrainerFactory.TrainerType; import opennlp.tools.sentdetect.SentenceDetectorFactory; import opennlp.tools.sentdetect.SentenceDetectorME; import opennlp.tools.sentdetect.SentenceModel; import opennlp.tools.sentdetect.SentenceSample; import opennlp.tools.sentdetect.SentenceSampleStream; import opennlp.tools.util.model.ModelUtil; public final class SentenceDetectorTrainerTool extends AbstractTrainerTool<SentenceSample, TrainerToolParams> { interface TrainerToolParams extends TrainingParams, TrainingToolParams { } public SentenceDetectorTrainerTool() { super(SentenceSample.class, TrainerToolParams.class); } public String getShortDescription() { return "trainer for the learnable sentence detector"; } static Dictionary loadDict(File f) throws IOException { Dictionary dict = null; if (f != null) { CmdLineUtil.checkInputFile("abb dict", f); dict = new Dictionary(new FileInputStream(f)); } return dict; } public void run(String format, String[] args) { super.run(format, args); mlParams = CmdLineUtil.loadTrainingParameters(params.getParams(), false); if (mlParams != null) { if (!TrainerType.EVENT_MODEL_TRAINER.equals(TrainerFactory.getTrainerType(mlParams))) { throw new TerminateToolException(1, "Sequence training is not supported!"); } } if (mlParams == null) { mlParams = ModelUtil.createDefaultTrainingParameters(); } File modelOutFile = params.getModel(); CmdLineUtil.checkOutputFile("sentence detector model", modelOutFile); char[] eos = null; if (params.getEosChars() != null) { String eosString = SentenceSampleStream.replaceNewLineEscapeTags( params.getEosChars()); eos = eosString.toCharArray(); } SentenceModel model; try { Dictionary dict = loadDict(params.getAbbDict()); SentenceDetectorFactory sdFactory = SentenceDetectorFactory.create( params.getFactory(), params.getLang(), true, dict, eos); model = SentenceDetectorME.train(params.getLang(), sampleStream, sdFactory, mlParams); } catch (IOException e) { throw createTerminationIOException(e); } finally { try { sampleStream.close(); } catch (IOException e) { // sorry that this can fail } } CmdLineUtil.writeModel("sentence detector", modelOutFile, model); } }
0
java-sources/ai/idylnlp/idylnlp-opennlp-tools-1.8.3/1.1.0/opennlp/tools/cmdline
java-sources/ai/idylnlp/idylnlp-opennlp-tools-1.8.3/1.1.0/opennlp/tools/cmdline/sentdetect/SentenceEvaluationErrorListener.java
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package opennlp.tools.cmdline.sentdetect; import java.io.OutputStream; import opennlp.tools.cmdline.EvaluationErrorPrinter; import opennlp.tools.sentdetect.SentenceDetectorEvaluationMonitor; import opennlp.tools.sentdetect.SentenceSample; import opennlp.tools.util.eval.EvaluationMonitor; /** * A default implementation of {@link EvaluationMonitor} that prints * to an output stream. * */ public class SentenceEvaluationErrorListener extends EvaluationErrorPrinter<SentenceSample> implements SentenceDetectorEvaluationMonitor { /** * Creates a listener that will print to System.err */ public SentenceEvaluationErrorListener() { super(System.err); } /** * Creates a listener that will print to a given {@link OutputStream} */ public SentenceEvaluationErrorListener(OutputStream outputStream) { super(outputStream); } @Override public void missclassified(SentenceSample reference, SentenceSample prediction) { printError(reference.getSentences(), prediction.getSentences(), reference, prediction, reference.getDocument()); } }
0
java-sources/ai/idylnlp/idylnlp-opennlp-tools-1.8.3/1.1.0/opennlp/tools/cmdline
java-sources/ai/idylnlp/idylnlp-opennlp-tools-1.8.3/1.1.0/opennlp/tools/cmdline/sentdetect/SentenceModelLoader.java
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package opennlp.tools.cmdline.sentdetect; import java.io.IOException; import java.io.InputStream; import opennlp.tools.cmdline.ModelLoader; import opennlp.tools.sentdetect.SentenceModel; import opennlp.tools.util.InvalidFormatException; /** * Loads a Tokenizer Model for the command line tools. * <p> * <b>Note:</b> Do not use this class, internal use only! */ public final class SentenceModelLoader extends ModelLoader<SentenceModel> { public SentenceModelLoader() { super("Sentence Detector"); } @Override protected SentenceModel loadModel(InputStream modelIn) throws IOException, InvalidFormatException { return new SentenceModel(modelIn); } }
0
java-sources/ai/idylnlp/idylnlp-opennlp-tools-1.8.3/1.1.0/opennlp/tools/cmdline
java-sources/ai/idylnlp/idylnlp-opennlp-tools-1.8.3/1.1.0/opennlp/tools/cmdline/sentdetect/TrainingParams.java
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package opennlp.tools.cmdline.sentdetect; import java.io.File; import opennlp.tools.cmdline.ArgumentParser.OptionalParameter; import opennlp.tools.cmdline.ArgumentParser.ParameterDescription; import opennlp.tools.cmdline.params.BasicTrainingParams; /** * TrainingParams for Sentence Detector. * * Note: Do not use this class, internal use only! */ interface TrainingParams extends BasicTrainingParams { @ParameterDescription(valueName = "path", description = "abbreviation dictionary in XML format.") @OptionalParameter File getAbbDict(); @ParameterDescription(valueName = "string", description = "EOS characters.") @OptionalParameter String getEosChars(); @ParameterDescription(valueName = "factoryName", description = "A sub-class of SentenceDetectorFactory where to get implementation and resources.") @OptionalParameter String getFactory(); }
0
java-sources/ai/idylnlp/idylnlp-opennlp-tools-1.8.3/1.1.0/opennlp/tools/cmdline
java-sources/ai/idylnlp/idylnlp-opennlp-tools-1.8.3/1.1.0/opennlp/tools/cmdline/tokenizer/CommandLineTokenizer.java
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package opennlp.tools.cmdline.tokenizer; import java.io.IOException; import opennlp.tools.cmdline.CmdLineUtil; import opennlp.tools.cmdline.PerformanceMonitor; import opennlp.tools.cmdline.SystemInputStreamFactory; import opennlp.tools.tokenize.Tokenizer; import opennlp.tools.tokenize.TokenizerStream; import opennlp.tools.tokenize.WhitespaceTokenStream; import opennlp.tools.util.ObjectStream; import opennlp.tools.util.PlainTextByLineStream; final class CommandLineTokenizer { private final Tokenizer tokenizer; CommandLineTokenizer(Tokenizer tokenizer) { this.tokenizer = tokenizer; } void process() { ObjectStream<String> untokenizedLineStream; ObjectStream<String> tokenizedLineStream; PerformanceMonitor perfMon = null; try { untokenizedLineStream = new PlainTextByLineStream(new SystemInputStreamFactory(), SystemInputStreamFactory.encoding()); tokenizedLineStream = new WhitespaceTokenStream( new TokenizerStream(tokenizer, untokenizedLineStream)); perfMon = new PerformanceMonitor(System.err, "sent"); perfMon.start(); String tokenizedLine; while ((tokenizedLine = tokenizedLineStream.read()) != null) { System.out.println(tokenizedLine); perfMon.incrementCounter(); } } catch (IOException e) { CmdLineUtil.handleStdinIoError(e); } perfMon.stopAndPrintFinalResult(); } }
0
java-sources/ai/idylnlp/idylnlp-opennlp-tools-1.8.3/1.1.0/opennlp/tools/cmdline
java-sources/ai/idylnlp/idylnlp-opennlp-tools-1.8.3/1.1.0/opennlp/tools/cmdline/tokenizer/DetokenizationDictionaryLoader.java
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package opennlp.tools.cmdline.tokenizer; import java.io.IOException; import java.io.InputStream; import opennlp.tools.cmdline.ModelLoader; import opennlp.tools.tokenize.DetokenizationDictionary; final class DetokenizationDictionaryLoader extends ModelLoader<DetokenizationDictionary> { DetokenizationDictionaryLoader() { super("detokenizer dictionary"); } @Override protected DetokenizationDictionary loadModel(InputStream modelIn) throws IOException { return new DetokenizationDictionary(modelIn); } }
0
java-sources/ai/idylnlp/idylnlp-opennlp-tools-1.8.3/1.1.0/opennlp/tools/cmdline
java-sources/ai/idylnlp/idylnlp-opennlp-tools-1.8.3/1.1.0/opennlp/tools/cmdline/tokenizer/DictionaryDetokenizerTool.java
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package opennlp.tools.cmdline.tokenizer; import java.io.File; import java.io.IOException; import opennlp.tools.cmdline.BasicCmdLineTool; import opennlp.tools.cmdline.CLI; import opennlp.tools.cmdline.CmdLineUtil; import opennlp.tools.cmdline.PerformanceMonitor; import opennlp.tools.cmdline.SystemInputStreamFactory; import opennlp.tools.tokenize.Detokenizer; import opennlp.tools.tokenize.DictionaryDetokenizer; import opennlp.tools.tokenize.WhitespaceTokenizer; import opennlp.tools.util.ObjectStream; import opennlp.tools.util.PlainTextByLineStream; public final class DictionaryDetokenizerTool extends BasicCmdLineTool { public String getHelp() { return "Usage: " + CLI.CMD + " " + getName() + " detokenizerDictionary"; } public void run(String[] args) { if (args.length != 1) { System.out.println(getHelp()); } else { try { Detokenizer detokenizer = new DictionaryDetokenizer( new DetokenizationDictionaryLoader().load(new File(args[0]))); try (ObjectStream<String> tokenizedLineStream = new PlainTextByLineStream(new SystemInputStreamFactory(), SystemInputStreamFactory.encoding())) { PerformanceMonitor perfMon = new PerformanceMonitor(System.err, "sent"); perfMon.start(); String tokenizedLine; while ((tokenizedLine = tokenizedLineStream.read()) != null) { // white space tokenize line String[] tokens = WhitespaceTokenizer.INSTANCE.tokenize(tokenizedLine); System.out.println(detokenizer.detokenize(tokens, null)); perfMon.incrementCounter(); } perfMon.stopAndPrintFinalResult(); } } catch (IOException e) { CmdLineUtil.handleStdinIoError(e); } } } }
0
java-sources/ai/idylnlp/idylnlp-opennlp-tools-1.8.3/1.1.0/opennlp/tools/cmdline
java-sources/ai/idylnlp/idylnlp-opennlp-tools-1.8.3/1.1.0/opennlp/tools/cmdline/tokenizer/SimpleTokenizerTool.java
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package opennlp.tools.cmdline.tokenizer; import opennlp.tools.cmdline.BasicCmdLineTool; import opennlp.tools.cmdline.CLI; public final class SimpleTokenizerTool extends BasicCmdLineTool { public String getShortDescription() { return "character class tokenizer"; } public String getHelp() { return "Usage: " + CLI.CMD + " " + getName() + " < sentences"; } @Override public boolean hasParams() { return false; } public void run(String[] args) { if (args.length != 0) { System.out.println(getHelp()); } else { CommandLineTokenizer tokenizer = new CommandLineTokenizer(opennlp.tools.tokenize.SimpleTokenizer.INSTANCE); tokenizer.process(); } } }
0
java-sources/ai/idylnlp/idylnlp-opennlp-tools-1.8.3/1.1.0/opennlp/tools/cmdline
java-sources/ai/idylnlp/idylnlp-opennlp-tools-1.8.3/1.1.0/opennlp/tools/cmdline/tokenizer/TokenEvaluationErrorListener.java
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package opennlp.tools.cmdline.tokenizer; import java.io.OutputStream; import opennlp.tools.cmdline.EvaluationErrorPrinter; import opennlp.tools.tokenize.TokenSample; import opennlp.tools.tokenize.TokenizerEvaluationMonitor; import opennlp.tools.util.eval.EvaluationMonitor; /** * A default implementation of {@link EvaluationMonitor} that prints * to an output stream. * */ public class TokenEvaluationErrorListener extends EvaluationErrorPrinter<TokenSample> implements TokenizerEvaluationMonitor { /** * Creates a listener that will print to System.err */ public TokenEvaluationErrorListener() { super(System.err); } /** * Creates a listener that will print to a given {@link OutputStream} */ public TokenEvaluationErrorListener(OutputStream outputStream) { super(outputStream); } @Override public void missclassified(TokenSample reference, TokenSample prediction) { printError(reference.getTokenSpans(), prediction.getTokenSpans(), reference, prediction, reference.getText()); } }
0
java-sources/ai/idylnlp/idylnlp-opennlp-tools-1.8.3/1.1.0/opennlp/tools/cmdline
java-sources/ai/idylnlp/idylnlp-opennlp-tools-1.8.3/1.1.0/opennlp/tools/cmdline/tokenizer/TokenizerConverterTool.java
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package opennlp.tools.cmdline.tokenizer; import opennlp.tools.cmdline.AbstractConverterTool; import opennlp.tools.tokenize.TokenSample; public class TokenizerConverterTool extends AbstractConverterTool<TokenSample> { public TokenizerConverterTool() { super(TokenSample.class); } }
0
java-sources/ai/idylnlp/idylnlp-opennlp-tools-1.8.3/1.1.0/opennlp/tools/cmdline
java-sources/ai/idylnlp/idylnlp-opennlp-tools-1.8.3/1.1.0/opennlp/tools/cmdline/tokenizer/TokenizerCrossValidatorTool.java
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package opennlp.tools.cmdline.tokenizer; import java.io.IOException; import opennlp.tools.cmdline.AbstractCrossValidatorTool; import opennlp.tools.cmdline.CmdLineUtil; import opennlp.tools.cmdline.params.CVParams; import opennlp.tools.cmdline.tokenizer.TokenizerCrossValidatorTool.CVToolParams; import opennlp.tools.dictionary.Dictionary; import opennlp.tools.tokenize.TokenSample; import opennlp.tools.tokenize.TokenizerCrossValidator; import opennlp.tools.tokenize.TokenizerEvaluationMonitor; import opennlp.tools.tokenize.TokenizerFactory; import opennlp.tools.util.eval.FMeasure; import opennlp.tools.util.model.ModelUtil; public final class TokenizerCrossValidatorTool extends AbstractCrossValidatorTool<TokenSample, CVToolParams> { interface CVToolParams extends CVParams, TrainingParams { } public TokenizerCrossValidatorTool() { super(TokenSample.class, CVToolParams.class); } public String getShortDescription() { return "K-fold cross validator for the learnable tokenizer"; } public void run(String format, String[] args) { super.run(format, args); mlParams = CmdLineUtil.loadTrainingParameters(params.getParams(), false); if (mlParams == null) { mlParams = ModelUtil.createDefaultTrainingParameters(); } TokenizerCrossValidator validator; TokenizerEvaluationMonitor listener = null; if (params.getMisclassified()) { listener = new TokenEvaluationErrorListener(); } try { Dictionary dict = TokenizerTrainerTool.loadDict(params.getAbbDict()); TokenizerFactory tokFactory = TokenizerFactory.create( params.getFactory(), params.getLang(), dict, params.getAlphaNumOpt(), null); validator = new opennlp.tools.tokenize.TokenizerCrossValidator(mlParams, tokFactory, listener); validator.evaluate(sampleStream, params.getFolds()); } catch (IOException e) { throw createTerminationIOException(e); } finally { try { sampleStream.close(); } catch (IOException e) { // sorry that this can fail } } FMeasure result = validator.getFMeasure(); System.out.println(result.toString()); } }
0
java-sources/ai/idylnlp/idylnlp-opennlp-tools-1.8.3/1.1.0/opennlp/tools/cmdline
java-sources/ai/idylnlp/idylnlp-opennlp-tools-1.8.3/1.1.0/opennlp/tools/cmdline/tokenizer/TokenizerMEEvaluatorTool.java
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package opennlp.tools.cmdline.tokenizer; import java.io.IOException; import opennlp.tools.cmdline.AbstractEvaluatorTool; import opennlp.tools.cmdline.TerminateToolException; import opennlp.tools.cmdline.params.EvaluatorParams; import opennlp.tools.cmdline.tokenizer.TokenizerMEEvaluatorTool.EvalToolParams; import opennlp.tools.tokenize.TokenSample; import opennlp.tools.tokenize.TokenizerEvaluationMonitor; import opennlp.tools.tokenize.TokenizerEvaluator; import opennlp.tools.tokenize.TokenizerModel; public final class TokenizerMEEvaluatorTool extends AbstractEvaluatorTool<TokenSample, EvalToolParams> { interface EvalToolParams extends EvaluatorParams { } public TokenizerMEEvaluatorTool() { super(TokenSample.class, EvalToolParams.class); } public String getShortDescription() { return "evaluator for the learnable tokenizer"; } public void run(String format, String[] args) { super.run(format, args); TokenizerModel model = new TokenizerModelLoader().load(params.getModel()); TokenizerEvaluationMonitor misclassifiedListener = null; if (params.getMisclassified()) { misclassifiedListener = new TokenEvaluationErrorListener(); } TokenizerEvaluator evaluator = new TokenizerEvaluator( new opennlp.tools.tokenize.TokenizerME(model), misclassifiedListener); System.out.print("Evaluating ... "); try { evaluator.evaluate(sampleStream); } catch (IOException e) { System.err.println("failed"); throw new TerminateToolException(-1, "IO error while reading test data: " + e.getMessage(), e); } finally { try { sampleStream.close(); } catch (IOException e) { // sorry that this can fail } } System.out.println("done"); System.out.println(); System.out.println(evaluator.getFMeasure()); } }
0
java-sources/ai/idylnlp/idylnlp-opennlp-tools-1.8.3/1.1.0/opennlp/tools/cmdline
java-sources/ai/idylnlp/idylnlp-opennlp-tools-1.8.3/1.1.0/opennlp/tools/cmdline/tokenizer/TokenizerMETool.java
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package opennlp.tools.cmdline.tokenizer; import java.io.File; import opennlp.tools.cmdline.BasicCmdLineTool; import opennlp.tools.cmdline.CLI; import opennlp.tools.tokenize.TokenizerModel; public final class TokenizerMETool extends BasicCmdLineTool { public String getShortDescription() { return "learnable tokenizer"; } public String getHelp() { return "Usage: " + CLI.CMD + " " + getName() + " model < sentences"; } public void run(String[] args) { if (args.length != 1) { System.out.println(getHelp()); } else { TokenizerModel model = new TokenizerModelLoader().load(new File(args[0])); CommandLineTokenizer tokenizer = new CommandLineTokenizer(new opennlp.tools.tokenize.TokenizerME(model)); tokenizer.process(); } } }
0
java-sources/ai/idylnlp/idylnlp-opennlp-tools-1.8.3/1.1.0/opennlp/tools/cmdline
java-sources/ai/idylnlp/idylnlp-opennlp-tools-1.8.3/1.1.0/opennlp/tools/cmdline/tokenizer/TokenizerModelLoader.java
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package opennlp.tools.cmdline.tokenizer; import java.io.IOException; import java.io.InputStream; import opennlp.tools.cmdline.ModelLoader; import opennlp.tools.tokenize.TokenizerModel; /** * Loads a Tokenizer Model for the command line tools. * <p> * <b>Note:</b> Do not use this class, internal use only! */ public final class TokenizerModelLoader extends ModelLoader<TokenizerModel> { public TokenizerModelLoader() { super("Tokenizer"); } @Override protected TokenizerModel loadModel(InputStream modelIn) throws IOException { return new TokenizerModel(modelIn); } }
0
java-sources/ai/idylnlp/idylnlp-opennlp-tools-1.8.3/1.1.0/opennlp/tools/cmdline
java-sources/ai/idylnlp/idylnlp-opennlp-tools-1.8.3/1.1.0/opennlp/tools/cmdline/tokenizer/TokenizerTrainerTool.java
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package opennlp.tools.cmdline.tokenizer; import java.io.File; import java.io.FileInputStream; import java.io.IOException; import opennlp.tools.cmdline.AbstractTrainerTool; import opennlp.tools.cmdline.CmdLineUtil; import opennlp.tools.cmdline.TerminateToolException; import opennlp.tools.cmdline.params.TrainingToolParams; import opennlp.tools.cmdline.tokenizer.TokenizerTrainerTool.TrainerToolParams; import opennlp.tools.dictionary.Dictionary; import opennlp.tools.ml.TrainerFactory; import opennlp.tools.ml.TrainerFactory.TrainerType; import opennlp.tools.tokenize.TokenSample; import opennlp.tools.tokenize.TokenizerFactory; import opennlp.tools.tokenize.TokenizerModel; import opennlp.tools.util.model.ModelUtil; public final class TokenizerTrainerTool extends AbstractTrainerTool<TokenSample, TrainerToolParams> { interface TrainerToolParams extends TrainingParams, TrainingToolParams { } public TokenizerTrainerTool() { super(TokenSample.class, TrainerToolParams.class); } public String getShortDescription() { return "trainer for the learnable tokenizer"; } static Dictionary loadDict(File f) throws IOException { Dictionary dict = null; if (f != null) { CmdLineUtil.checkInputFile("abb dict", f); dict = new Dictionary(new FileInputStream(f)); } return dict; } public void run(String format, String[] args) { super.run(format, args); mlParams = CmdLineUtil.loadTrainingParameters(params.getParams(), false); if (mlParams != null) { if (!TrainerFactory.isValid(mlParams)) { throw new TerminateToolException(1, "Training parameters file '" + params.getParams() + "' is invalid!"); } if (!TrainerType.EVENT_MODEL_TRAINER.equals(TrainerFactory.getTrainerType(mlParams))) { throw new TerminateToolException(1, "Sequence training is not supported!"); } } if (mlParams == null) { mlParams = ModelUtil.createDefaultTrainingParameters(); } File modelOutFile = params.getModel(); CmdLineUtil.checkOutputFile("tokenizer model", modelOutFile); TokenizerModel model; try { Dictionary dict = loadDict(params.getAbbDict()); TokenizerFactory tokFactory = TokenizerFactory.create( params.getFactory(), params.getLang(), dict, params.getAlphaNumOpt(), null); model = opennlp.tools.tokenize.TokenizerME.train(sampleStream, tokFactory, mlParams); } catch (IOException e) { throw createTerminationIOException(e); } finally { try { sampleStream.close(); } catch (IOException e) { // sorry that this can fail } } CmdLineUtil.writeModel("tokenizer", modelOutFile, model); } }
0
java-sources/ai/idylnlp/idylnlp-opennlp-tools-1.8.3/1.1.0/opennlp/tools/cmdline
java-sources/ai/idylnlp/idylnlp-opennlp-tools-1.8.3/1.1.0/opennlp/tools/cmdline/tokenizer/TrainingParams.java
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package opennlp.tools.cmdline.tokenizer; import java.io.File; import opennlp.tools.cmdline.ArgumentParser.OptionalParameter; import opennlp.tools.cmdline.ArgumentParser.ParameterDescription; import opennlp.tools.cmdline.params.BasicTrainingParams; /** * TrainingParameters for Tokenizer. * * Note: Do not use this class, internal use only! */ interface TrainingParams extends BasicTrainingParams { @ParameterDescription(valueName = "isAlphaNumOpt", description = "Optimization flag to skip alpha numeric tokens for further tokenization") @OptionalParameter(defaultValue = "false") Boolean getAlphaNumOpt(); @ParameterDescription(valueName = "path", description = "abbreviation dictionary in XML format.") @OptionalParameter File getAbbDict(); @ParameterDescription(valueName = "factoryName", description = "A sub-class of TokenizerFactory where to get implementation and resources.") @OptionalParameter String getFactory(); }
0
java-sources/ai/idylnlp/idylnlp-opennlp-tools-1.8.3/1.1.0/opennlp/tools
java-sources/ai/idylnlp/idylnlp-opennlp-tools-1.8.3/1.1.0/opennlp/tools/dictionary/Dictionary.java
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package opennlp.tools.dictionary; import java.io.BufferedReader; import java.io.IOException; import java.io.InputStream; import java.io.OutputStream; import java.io.Reader; import java.util.AbstractSet; import java.util.HashSet; import java.util.Iterator; import java.util.Set; import java.util.StringTokenizer; import opennlp.tools.dictionary.serializer.Attributes; import opennlp.tools.dictionary.serializer.DictionaryEntryPersistor; import opennlp.tools.dictionary.serializer.Entry; import opennlp.tools.util.StringList; import opennlp.tools.util.StringUtil; import opennlp.tools.util.model.DictionarySerializer; import opennlp.tools.util.model.SerializableArtifact; /** * This class is a dictionary. */ public class Dictionary implements Iterable<StringList>, SerializableArtifact { private class StringListWrapper { private final StringList stringList; private StringListWrapper(StringList stringList) { this.stringList = stringList; } private StringList getStringList() { return stringList; } @Override public boolean equals(Object obj) { boolean result; if (obj == this) { result = true; } else if (obj instanceof StringListWrapper) { StringListWrapper other = (StringListWrapper) obj; if (isCaseSensitive) { result = this.stringList.equals(other.getStringList()); } else { result = this.stringList.compareToIgnoreCase(other.getStringList()); } } else { result = false; } return result; } @Override public int hashCode() { // if lookup is too slow optimize this return StringUtil.toLowerCase(this.stringList.toString()).hashCode(); } @Override public String toString() { return this.stringList.toString(); } } private Set<StringListWrapper> entrySet = new HashSet<>(); private final boolean isCaseSensitive; private int minTokenCount = 99999; private int maxTokenCount = 0; /** * Initializes an empty {@link Dictionary}. */ public Dictionary() { this(false); } public Dictionary(boolean caseSensitive) { isCaseSensitive = caseSensitive; } /** * Initializes the {@link Dictionary} from an existing dictionary resource. * * @param in {@link InputStream} * @throws IOException */ public Dictionary(InputStream in) throws IOException { isCaseSensitive = DictionaryEntryPersistor.create(in, entry -> put(entry.getTokens())); } /** * Adds the tokens to the dictionary as one new entry. * * @param tokens the new entry */ public void put(StringList tokens) { entrySet.add(new StringListWrapper(tokens)); minTokenCount = Math.min(minTokenCount, tokens.size()); maxTokenCount = Math.max(maxTokenCount, tokens.size()); } /** * * @return minimum token count in the dictionary */ public int getMinTokenCount() { return minTokenCount; } /** * * @return maximum token count in the dictionary */ public int getMaxTokenCount() { return maxTokenCount; } /** * Checks if this dictionary has the given entry. * * @param tokens query * @return true if it contains the entry otherwise false */ public boolean contains(StringList tokens) { return entrySet.contains(new StringListWrapper(tokens)); } /** * Removes the given tokens form the current instance. * * @param tokens filter tokens */ public void remove(StringList tokens) { entrySet.remove(new StringListWrapper(tokens)); } /** * Retrieves an Iterator over all tokens. * * @return token-{@link Iterator} */ public Iterator<StringList> iterator() { final Iterator<StringListWrapper> entries = entrySet.iterator(); return new Iterator<StringList>() { public boolean hasNext() { return entries.hasNext(); } public StringList next() { return entries.next().getStringList(); } public void remove() { entries.remove(); } }; } /** * Retrieves the number of tokens in the current instance. * * @return number of tokens */ public int size() { return entrySet.size(); } /** * Writes the current instance to the given {@link OutputStream}. * * @param out {@link OutputStream} * @throws IOException */ public void serialize(OutputStream out) throws IOException { Iterator<Entry> entryIterator = new Iterator<Entry>() { private Iterator<StringList> dictionaryIterator = Dictionary.this.iterator(); public boolean hasNext() { return dictionaryIterator.hasNext(); } public Entry next() { StringList tokens = dictionaryIterator.next(); return new Entry(tokens, new Attributes()); } public void remove() { throw new UnsupportedOperationException(); } }; DictionaryEntryPersistor.serialize(out, entryIterator, isCaseSensitive); } @Override public boolean equals(Object obj) { boolean result; if (obj == this) { result = true; } else if (obj instanceof Dictionary) { Dictionary dictionary = (Dictionary) obj; result = entrySet.equals(dictionary.entrySet); } else { result = false; } return result; } @Override public int hashCode() { return entrySet.hashCode(); } @Override public String toString() { return entrySet.toString(); } /** * Reads a dictionary which has one entry per line. The tokens inside an * entry are whitespace delimited. * * @param in {@link Reader} * @return the parsed dictionary * @throws IOException */ public static Dictionary parseOneEntryPerLine(Reader in) throws IOException { BufferedReader lineReader = new BufferedReader(in); Dictionary dictionary = new Dictionary(); String line; while ((line = lineReader.readLine()) != null) { StringTokenizer whiteSpaceTokenizer = new StringTokenizer(line, " "); String[] tokens = new String[whiteSpaceTokenizer.countTokens()]; if (tokens.length > 0) { int tokenIndex = 0; while (whiteSpaceTokenizer.hasMoreTokens()) { tokens[tokenIndex++] = whiteSpaceTokenizer.nextToken(); } dictionary.put(new StringList(tokens)); } } return dictionary; } /** * Gets this dictionary as a {@code Set<String>}. Only {@code iterator()}, * {@code size()} and {@code contains(Object)} methods are implemented. * * If this dictionary entries are multi tokens only the first token of the * entry will be part of the Set. * * @return a Set containing the entries of this dictionary */ public Set<String> asStringSet() { return new AbstractSet<String>() { @Override public Iterator<String> iterator() { final Iterator<StringListWrapper> entries = entrySet.iterator(); return new Iterator<String>() { public boolean hasNext() { return entries.hasNext(); } public String next() { return entries.next().getStringList().getToken(0); } public void remove() { throw new UnsupportedOperationException(); } }; } @Override public int size() { return entrySet.size(); } @Override public boolean contains(Object obj) { boolean result = false; if (obj instanceof String) { String str = (String) obj; result = entrySet.contains(new StringListWrapper(new StringList(str))); } return result; } }; } /** * Gets the Serializer Class for {@link Dictionary} * @return {@link DictionarySerializer} */ @Override public Class<?> getArtifactSerializerClass() { return DictionarySerializer.class; } }
0
java-sources/ai/idylnlp/idylnlp-opennlp-tools-1.8.3/1.1.0/opennlp/tools
java-sources/ai/idylnlp/idylnlp-opennlp-tools-1.8.3/1.1.0/opennlp/tools/dictionary/Index.java
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package opennlp.tools.dictionary; import java.util.HashSet; import java.util.Iterator; import java.util.Set; import opennlp.tools.util.StringList; /** * This classes indexes {@link StringList}s. This makes it possible * to check if a certain token is contained in at least one of the * {@link StringList}s. */ public class Index { private Set<String> tokens = new HashSet<>(); /** * Initializes the current instance with the given * {@link StringList} {@link Iterator}. * * @param tokenLists */ public Index(Iterator<StringList> tokenLists) { while (tokenLists.hasNext()) { StringList tokens = tokenLists.next(); for (int i = 0; i < tokens.size(); i++) { this.tokens.add(tokens.getToken(i)); } } } /** * Checks if at leat one {@link StringList} contains the * given token. * * @param token * * @return true if the token is contained otherwise false. */ public boolean contains(String token) { return tokens.contains(token); } }
0
java-sources/ai/idylnlp/idylnlp-opennlp-tools-1.8.3/1.1.0/opennlp/tools
java-sources/ai/idylnlp/idylnlp-opennlp-tools-1.8.3/1.1.0/opennlp/tools/dictionary/package-info.java
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ /** * Package related to parsing and storing dictionaries. */ package opennlp.tools.dictionary;
0
java-sources/ai/idylnlp/idylnlp-opennlp-tools-1.8.3/1.1.0/opennlp/tools/dictionary
java-sources/ai/idylnlp/idylnlp-opennlp-tools-1.8.3/1.1.0/opennlp/tools/dictionary/serializer/Attributes.java
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package opennlp.tools.dictionary.serializer; import java.util.HashMap; import java.util.Iterator; import java.util.Map; import java.util.Objects; /** * The {@link Attributes} class stores name value pairs. * * Problem: The HashMap for storing the name value pairs has a very high * memory footprint, replace it. */ public class Attributes { private Map<String, String> mNameValueMap = new HashMap<>(); /** * Retrieves the value for the given key or null if attribute it not set. * * @param key * * @return the value */ public String getValue(String key) { return mNameValueMap.get(key); } /** * Sets a key/value pair. * * @param key * @param value */ public void setValue(String key, String value) { Objects.requireNonNull(key, "key must not be null"); Objects.requireNonNull(value, "value must not be null"); mNameValueMap.put(key, value); } /** * Iterates over the keys. * * @return key-{@link Iterator} */ public Iterator<String> iterator() { return mNameValueMap.keySet().iterator(); } }
0
java-sources/ai/idylnlp/idylnlp-opennlp-tools-1.8.3/1.1.0/opennlp/tools/dictionary
java-sources/ai/idylnlp/idylnlp-opennlp-tools-1.8.3/1.1.0/opennlp/tools/dictionary/serializer/DictionaryEntryPersistor.java
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package opennlp.tools.dictionary.serializer; import java.io.IOException; import java.io.InputStream; import java.io.OutputStream; import java.util.Iterator; import java.util.LinkedList; import java.util.List; import javax.xml.transform.OutputKeys; import javax.xml.transform.Transformer; import javax.xml.transform.TransformerConfigurationException; import javax.xml.transform.sax.SAXTransformerFactory; import javax.xml.transform.sax.TransformerHandler; import javax.xml.transform.stream.StreamResult; import org.xml.sax.ContentHandler; import org.xml.sax.InputSource; import org.xml.sax.Locator; import org.xml.sax.SAXException; import org.xml.sax.XMLReader; import org.xml.sax.helpers.AttributesImpl; import org.xml.sax.helpers.XMLReaderFactory; import opennlp.tools.util.InvalidFormatException; import opennlp.tools.util.StringList; import opennlp.tools.util.model.UncloseableInputStream; /** * This class is used by for reading and writing dictionaries of all kinds. */ public class DictionaryEntryPersistor { // TODO: should check for invalid format, make it save private static class DictionaryContenthandler implements ContentHandler { private EntryInserter mInserter; // private boolean mIsInsideDictionaryElement; // private boolean mIsInsideEntryElement; private boolean mIsInsideTokenElement; private boolean mIsCaseSensitiveDictionary; private List<String> mTokenList = new LinkedList<>(); private StringBuilder token = new StringBuilder(); private Attributes mAttributes; private DictionaryContenthandler(EntryInserter inserter) { mInserter = inserter; mIsCaseSensitiveDictionary = true; } /** * Not implemented. */ public void processingInstruction(String target, String data) throws SAXException { } /** * Not implemented. */ public void startDocument() throws SAXException { } public void startElement(String uri, String localName, String qName, org.xml.sax.Attributes atts) throws SAXException { if (DICTIONARY_ELEMENT.equals(localName)) { mAttributes = new Attributes(); for (int i = 0; i < atts.getLength(); i++) { mAttributes.setValue(atts.getLocalName(i), atts.getValue(i)); } /* get the attribute here ... */ if (mAttributes.getValue(ATTRIBUTE_CASE_SENSITIVE) != null) { mIsCaseSensitiveDictionary = Boolean.valueOf(mAttributes.getValue(ATTRIBUTE_CASE_SENSITIVE)); } mAttributes = null; } else if (ENTRY_ELEMENT.equals(localName)) { mAttributes = new Attributes(); for (int i = 0; i < atts.getLength(); i++) { mAttributes.setValue(atts.getLocalName(i), atts.getValue(i)); } } else if (TOKEN_ELEMENT.equals(localName)) { mIsInsideTokenElement = true; } } public void characters(char[] ch, int start, int length) throws SAXException { if (mIsInsideTokenElement) { token.append(ch, start, length); } } /** * Creates the Profile object after processing is complete * and switches mIsInsideNgramElement flag. */ public void endElement(String uri, String localName, String qName) throws SAXException { if (TOKEN_ELEMENT.equals(localName)) { mTokenList.add(token.toString().trim()); token.setLength(0); mIsInsideTokenElement = false; } else if (ENTRY_ELEMENT.equals(localName)) { String[] tokens = mTokenList.toArray( new String[mTokenList.size()]); Entry entry = new Entry(new StringList(tokens), mAttributes); try { mInserter.insert(entry); } catch (InvalidFormatException e) { throw new SAXException("Invalid dictionary format!", e); } mTokenList.clear(); mAttributes = null; } } /** * Not implemented. */ public void endDocument() throws SAXException { } /** * Not implemented. */ public void endPrefixMapping(String prefix) throws SAXException { } /** * Not implemented. */ public void ignorableWhitespace(char[] ch, int start, int length) throws SAXException { } /** * Not implemented. */ public void setDocumentLocator(Locator locator) { } /** * Not implemented. */ public void skippedEntity(String name) throws SAXException { } /** * Not implemented. */ public void startPrefixMapping(String prefix, String uri) throws SAXException { } } private static final String CHARSET = "UTF-8"; private static final String DICTIONARY_ELEMENT = "dictionary"; private static final String ENTRY_ELEMENT = "entry"; private static final String TOKEN_ELEMENT = "token"; private static final String ATTRIBUTE_CASE_SENSITIVE = "case_sensitive"; /** * Creates {@link Entry}s from the given {@link InputStream} and * forwards these {@link Entry}s to the {@link EntryInserter}. * * After creation is finished the provided {@link InputStream} is closed. * * @param in stream to read entries from * @param inserter inserter to forward entries to * * @return isCaseSensitive attribute for Dictionary * * @throws IOException * @throws InvalidFormatException */ public static boolean create(InputStream in, EntryInserter inserter) throws IOException { DictionaryContenthandler profileContentHandler = new DictionaryContenthandler(inserter); XMLReader xmlReader; try { xmlReader = XMLReaderFactory.createXMLReader(); xmlReader.setContentHandler(profileContentHandler); xmlReader.parse(new InputSource(new UncloseableInputStream(in))); } catch (SAXException e) { throw new InvalidFormatException("The profile data stream has " + "an invalid format!", e); } return profileContentHandler.mIsCaseSensitiveDictionary; } /** * Serializes the given entries to the given {@link OutputStream}. * * After the serialization is finished the provided * {@link OutputStream} remains open. * * @param out stream to serialize to * @param entries entries to serialize * * @throws IOException If an I/O error occurs * @deprecated Use * {@link DictionaryEntryPersistor#serialize(java.io.OutputStream, java.util.Iterator, boolean)} instead */ @Deprecated public static void serialize(OutputStream out, Iterator<Entry> entries) throws IOException { DictionaryEntryPersistor.serialize(out, entries, true); } /** * Serializes the given entries to the given {@link OutputStream}. * * After the serialization is finished the provided * {@link OutputStream} remains open. * * @param out stream to serialize to * @param entries entries to serialize * @param casesensitive indicates if the written dictionary * should be case sensitive or case insensitive. * * @throws IOException If an I/O error occurs */ public static void serialize(OutputStream out, Iterator<Entry> entries, boolean casesensitive) throws IOException { StreamResult streamResult = new StreamResult(out); SAXTransformerFactory tf = (SAXTransformerFactory) SAXTransformerFactory.newInstance(); TransformerHandler hd; try { hd = tf.newTransformerHandler(); } catch (TransformerConfigurationException e) { throw new AssertionError("The Transformer configuration must be valid!"); } Transformer serializer = hd.getTransformer(); serializer.setOutputProperty(OutputKeys.ENCODING, CHARSET); serializer.setOutputProperty(OutputKeys.INDENT, "yes"); hd.setResult(streamResult); try { hd.startDocument(); AttributesImpl dictionaryAttributes = new AttributesImpl(); dictionaryAttributes.addAttribute("", "", ATTRIBUTE_CASE_SENSITIVE, "", String.valueOf(casesensitive)); hd.startElement("", "", DICTIONARY_ELEMENT, dictionaryAttributes); while (entries.hasNext()) { Entry entry = entries.next(); serializeEntry(hd, entry); } hd.endElement("", "", DICTIONARY_ELEMENT); hd.endDocument(); } catch (SAXException e) { throw new IOException("Error during serialization: " + e.getMessage(), e); } } private static void serializeEntry(TransformerHandler hd, Entry entry) throws SAXException { AttributesImpl entryAttributes = new AttributesImpl(); for (Iterator<String> it = entry.getAttributes().iterator(); it.hasNext();) { String key = it.next(); entryAttributes.addAttribute("", "", key, "", entry.getAttributes().getValue(key)); } hd.startElement("", "", ENTRY_ELEMENT, entryAttributes); StringList tokens = entry.getTokens(); for (String token : tokens) { hd.startElement("", "", TOKEN_ELEMENT, new AttributesImpl()); hd.characters(token.toCharArray(), 0, token.length()); hd.endElement("", "", TOKEN_ELEMENT); } hd.endElement("", "", ENTRY_ELEMENT); } }
0
java-sources/ai/idylnlp/idylnlp-opennlp-tools-1.8.3/1.1.0/opennlp/tools/dictionary
java-sources/ai/idylnlp/idylnlp-opennlp-tools-1.8.3/1.1.0/opennlp/tools/dictionary/serializer/Entry.java
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package opennlp.tools.dictionary.serializer; import opennlp.tools.util.StringList; /** * An {@link Entry} is a {@link StringList} which can * optionally be mapped to attributes. * * {@link Entry}s is a read and written by the {@link DictionaryEntryPersistor}. * * @see DictionaryEntryPersistor * @see Attributes */ public class Entry { private StringList tokens; private Attributes attributes; /** * Initializes the current instance. * * @param tokens * @param attributes */ public Entry(StringList tokens, Attributes attributes) { this.tokens = tokens; this.attributes = attributes; } /** * Retrieves the tokens. * * @return the tokens */ public StringList getTokens() { return tokens; } /** * Retrieves the {@link Attributes}. * * @return the {@link Attributes} */ public Attributes getAttributes() { return attributes; } }
0
java-sources/ai/idylnlp/idylnlp-opennlp-tools-1.8.3/1.1.0/opennlp/tools/dictionary
java-sources/ai/idylnlp/idylnlp-opennlp-tools-1.8.3/1.1.0/opennlp/tools/dictionary/serializer/EntryInserter.java
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package opennlp.tools.dictionary.serializer; import opennlp.tools.util.InvalidFormatException; public interface EntryInserter { /** * * @param entry * @throws InvalidFormatException */ void insert(Entry entry) throws InvalidFormatException; }
0
java-sources/ai/idylnlp/idylnlp-opennlp-tools-1.8.3/1.1.0/opennlp/tools
java-sources/ai/idylnlp/idylnlp-opennlp-tools-1.8.3/1.1.0/opennlp/tools/doccat/BagOfWordsFeatureGenerator.java
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package opennlp.tools.doccat; import java.util.ArrayList; import java.util.Collection; import java.util.Map; import java.util.Objects; import opennlp.tools.util.featuregen.StringPattern; /** * Generates a feature for each word in a document. */ public class BagOfWordsFeatureGenerator implements FeatureGenerator { private final boolean useOnlyAllLetterTokens; public BagOfWordsFeatureGenerator() { this(false); } BagOfWordsFeatureGenerator(boolean useOnlyAllLetterTokens) { this.useOnlyAllLetterTokens = useOnlyAllLetterTokens; } @Override public Collection<String> extractFeatures(String[] text, Map<String, Object> extraInformation) { Objects.requireNonNull(text, "text must not be null"); Collection<String> bagOfWords = new ArrayList<>(text.length); for (String word : text) { if (useOnlyAllLetterTokens) { StringPattern pattern = StringPattern.recognize(word); if (pattern.isAllLetter()) bagOfWords.add("bow=" + word); } else { bagOfWords.add("bow=" + word); } } return bagOfWords; } }
0
java-sources/ai/idylnlp/idylnlp-opennlp-tools-1.8.3/1.1.0/opennlp/tools
java-sources/ai/idylnlp/idylnlp-opennlp-tools-1.8.3/1.1.0/opennlp/tools/doccat/DoccatCrossValidator.java
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package opennlp.tools.doccat; import java.io.IOException; import opennlp.tools.util.ObjectStream; import opennlp.tools.util.TrainingParameters; import opennlp.tools.util.eval.CrossValidationPartitioner; import opennlp.tools.util.eval.Mean; /** * Cross validator for document categorization */ public class DoccatCrossValidator { private final String languageCode; private final TrainingParameters params; private Mean documentAccuracy = new Mean(); private DoccatEvaluationMonitor[] listeners; private DoccatFactory factory; /** * Creates a {@link DoccatCrossValidator} with the given * {@link FeatureGenerator}s. */ public DoccatCrossValidator(String languageCode, TrainingParameters mlParams, DoccatFactory factory, DoccatEvaluationMonitor ... listeners) { this.languageCode = languageCode; this.params = mlParams; this.listeners = listeners; this.factory = factory; } /** * Starts the evaluation. * * @param samples * the data to train and test * @param nFolds * number of folds * * @throws IOException */ public void evaluate(ObjectStream<DocumentSample> samples, int nFolds) throws IOException { CrossValidationPartitioner<DocumentSample> partitioner = new CrossValidationPartitioner<>( samples, nFolds); while (partitioner.hasNext()) { CrossValidationPartitioner.TrainingSampleStream<DocumentSample> trainingSampleStream = partitioner .next(); DoccatModel model = DocumentCategorizerME.train(languageCode, trainingSampleStream, params, factory); DocumentCategorizerEvaluator evaluator = new DocumentCategorizerEvaluator( new DocumentCategorizerME(model), listeners); evaluator.evaluate(trainingSampleStream.getTestSampleStream()); documentAccuracy.add(evaluator.getAccuracy(), evaluator.getDocumentCount()); } } /** * Retrieves the accuracy for all iterations. * * @return the word accuracy */ public double getDocumentAccuracy() { return documentAccuracy.mean(); } /** * Retrieves the number of words which where validated over all iterations. * The result is the amount of folds multiplied by the total number of words. * * @return the word count */ public long getDocumentCount() { return documentAccuracy.count(); } }
0
java-sources/ai/idylnlp/idylnlp-opennlp-tools-1.8.3/1.1.0/opennlp/tools
java-sources/ai/idylnlp/idylnlp-opennlp-tools-1.8.3/1.1.0/opennlp/tools/doccat/DoccatEvaluationMonitor.java
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package opennlp.tools.doccat; import opennlp.tools.util.eval.EvaluationMonitor; /** * {@link EvaluationMonitor} for doccat. */ public interface DoccatEvaluationMonitor extends EvaluationMonitor<DocumentSample> { }
0
java-sources/ai/idylnlp/idylnlp-opennlp-tools-1.8.3/1.1.0/opennlp/tools
java-sources/ai/idylnlp/idylnlp-opennlp-tools-1.8.3/1.1.0/opennlp/tools/doccat/DoccatFactory.java
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package opennlp.tools.doccat; import java.util.Arrays; import java.util.Iterator; import java.util.List; import java.util.Map; import opennlp.tools.util.BaseToolFactory; import opennlp.tools.util.InvalidFormatException; import opennlp.tools.util.ext.ExtensionLoader; /** * The factory that provides Doccat default implementations and resources */ public class DoccatFactory extends BaseToolFactory { private static final String FEATURE_GENERATORS = "doccat.featureGenerators"; private FeatureGenerator[] featureGenerators; /** * Creates a {@link DoccatFactory} that provides the default implementation of * the resources. */ public DoccatFactory() {} public DoccatFactory(final FeatureGenerator[] featureGenerators) { this.featureGenerators = featureGenerators; } protected void init(FeatureGenerator[] featureGenerators) { this.featureGenerators = featureGenerators; } @Override public Map<String, String> createManifestEntries() { Map<String, String> manifestEntries = super.createManifestEntries(); if (getFeatureGenerators() != null) { manifestEntries.put(FEATURE_GENERATORS, featureGeneratorsAsString()); } return manifestEntries; } private String featureGeneratorsAsString() { List<FeatureGenerator> fgs = Arrays.asList(getFeatureGenerators()); Iterator<FeatureGenerator> iter = fgs.iterator(); StringBuilder sb = new StringBuilder(); if (iter.hasNext()) { sb.append(iter.next().getClass().getCanonicalName()); while (iter.hasNext()) { sb.append(',').append(iter.next().getClass().getCanonicalName()); } } return sb.toString(); } @Override public void validateArtifactMap() throws InvalidFormatException { // nothing to validate } public static DoccatFactory create(String subclassName, FeatureGenerator[] featureGenerators) throws InvalidFormatException { if (subclassName == null) { // will create the default factory return new DoccatFactory(featureGenerators); } try { DoccatFactory theFactory = ExtensionLoader.instantiateExtension( DoccatFactory.class, subclassName); theFactory.init(featureGenerators); return theFactory; } catch (Exception e) { String msg = "Could not instantiate the " + subclassName + ". The initialization throw an exception."; System.err.println(msg); e.printStackTrace(); throw new InvalidFormatException(msg, e); } } private FeatureGenerator[] loadFeatureGenerators(String classNames) { String[] classes = classNames.split(","); FeatureGenerator[] fgs = new FeatureGenerator[classes.length]; for (int i = 0; i < classes.length; i++) { fgs[i] = ExtensionLoader.instantiateExtension(FeatureGenerator.class, classes[i]); } return fgs; } public FeatureGenerator[] getFeatureGenerators() { if (featureGenerators == null) { if (artifactProvider != null) { String classNames = artifactProvider .getManifestProperty(FEATURE_GENERATORS); if (classNames != null) { this.featureGenerators = loadFeatureGenerators(classNames); } } if (featureGenerators == null) { // could not load using artifact provider // load bag of words as default this.featureGenerators = new FeatureGenerator[]{new BagOfWordsFeatureGenerator()}; } } return featureGenerators; } public void setFeatureGenerators(FeatureGenerator[] featureGenerators) { this.featureGenerators = featureGenerators; } }
0
java-sources/ai/idylnlp/idylnlp-opennlp-tools-1.8.3/1.1.0/opennlp/tools
java-sources/ai/idylnlp/idylnlp-opennlp-tools-1.8.3/1.1.0/opennlp/tools/doccat/DoccatModel.java
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package opennlp.tools.doccat; import java.io.File; import java.io.IOException; import java.io.InputStream; import java.net.URL; import java.nio.file.Path; import java.util.Map; import opennlp.tools.ml.model.AbstractModel; import opennlp.tools.ml.model.MaxentModel; import opennlp.tools.util.BaseToolFactory; import opennlp.tools.util.InvalidFormatException; import opennlp.tools.util.model.BaseModel; /** * A model for document categorization */ public class DoccatModel extends BaseModel { private static final String COMPONENT_NAME = "DocumentCategorizerME"; private static final String DOCCAT_MODEL_ENTRY_NAME = "doccat.model"; public DoccatModel(String languageCode, MaxentModel doccatModel, Map<String, String> manifestInfoEntries, DoccatFactory factory) { super(COMPONENT_NAME, languageCode, manifestInfoEntries, factory); artifactMap.put(DOCCAT_MODEL_ENTRY_NAME, doccatModel); checkArtifactMap(); } public DoccatModel(InputStream in) throws IOException { super(COMPONENT_NAME, in); } public DoccatModel(File modelFile) throws IOException { super(COMPONENT_NAME, modelFile); } public DoccatModel(Path modelPath) throws IOException { this(modelPath.toFile()); } public DoccatModel(URL modelURL) throws IOException { super(COMPONENT_NAME, modelURL); } @Override protected void validateArtifactMap() throws InvalidFormatException { super.validateArtifactMap(); if (!(artifactMap.get(DOCCAT_MODEL_ENTRY_NAME) instanceof AbstractModel)) { throw new InvalidFormatException("Doccat model is incomplete!"); } } public DoccatFactory getFactory() { return (DoccatFactory) this.toolFactory; } @Override protected Class<? extends BaseToolFactory> getDefaultFactory() { return DoccatFactory.class; } public MaxentModel getMaxentModel() { return (MaxentModel) artifactMap.get(DOCCAT_MODEL_ENTRY_NAME); } }
0
java-sources/ai/idylnlp/idylnlp-opennlp-tools-1.8.3/1.1.0/opennlp/tools
java-sources/ai/idylnlp/idylnlp-opennlp-tools-1.8.3/1.1.0/opennlp/tools/doccat/DocumentCategorizer.java
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package opennlp.tools.doccat; import java.util.Map; import java.util.Set; import java.util.SortedMap; /** * Interface for classes which categorize documents. */ public interface DocumentCategorizer { /** * Categorize the given text provided as tokens along with * the provided extra information * * @param text the tokens of text to categorize * @param extraInformation extra information * @return per category probabilities */ double[] categorize(String[] text, Map<String, Object> extraInformation); /** * Categorizes the given text, provided in separate tokens. * @param text the tokens of text to categorize * @return per category probabilities */ double[] categorize(String[] text); /** * get the best category from previously generated outcome probabilities * * @param outcome a vector of outcome probabilities * @return the best category String */ String getBestCategory(double[] outcome); /** * get the index of a certain category * * @param category the category * @return an index */ int getIndex(String category); /** * get the category at a given index * * @param index the index * @return a category */ String getCategory(int index); /** * get the number of categories * * @return the no. of categories */ int getNumberOfCategories(); /** * get the name of the category associated with the given probabilties * * @param results the probabilities of each category * @return the name of the outcome */ String getAllResults(double[] results); /** * Returns a map in which the key is the category name and the value is the score * * @param text the input text to classify * @return a map with the score as a key. The value is a Set of categories with the score. */ Map<String, Double> scoreMap(String[] text); /** * Get a map of the scores sorted in ascending aorder together with their associated categories. * Many categories can have the same score, hence the Set as value * * @param text the input text to classify * @return a map with the score as a key. The value is a Set of categories with the score. */ SortedMap<Double, Set<String>> sortedScoreMap(String[] text); }
0
java-sources/ai/idylnlp/idylnlp-opennlp-tools-1.8.3/1.1.0/opennlp/tools
java-sources/ai/idylnlp/idylnlp-opennlp-tools-1.8.3/1.1.0/opennlp/tools/doccat/DocumentCategorizerContextGenerator.java
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package opennlp.tools.doccat; import java.util.Collection; import java.util.LinkedList; import java.util.Map; /** * Context generator for document categorizer */ class DocumentCategorizerContextGenerator { private FeatureGenerator[] mFeatureGenerators; DocumentCategorizerContextGenerator(FeatureGenerator... featureGenerators) { mFeatureGenerators = featureGenerators; } public String[] getContext(String[] text, Map<String, Object> extraInformation) { Collection<String> context = new LinkedList<>(); for (FeatureGenerator mFeatureGenerator : mFeatureGenerators) { Collection<String> extractedFeatures = mFeatureGenerator.extractFeatures(text, extraInformation); context.addAll(extractedFeatures); } return context.toArray(new String[context.size()]); } }
0
java-sources/ai/idylnlp/idylnlp-opennlp-tools-1.8.3/1.1.0/opennlp/tools
java-sources/ai/idylnlp/idylnlp-opennlp-tools-1.8.3/1.1.0/opennlp/tools/doccat/DocumentCategorizerEvaluator.java
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package opennlp.tools.doccat; import opennlp.tools.tokenize.TokenSample; import opennlp.tools.util.eval.Evaluator; import opennlp.tools.util.eval.Mean; /** * The {@link DocumentCategorizerEvaluator} measures the performance of * the given {@link DocumentCategorizer} with the provided reference * {@link DocumentSample}s. * * @see DocumentCategorizer * @see DocumentSample */ public class DocumentCategorizerEvaluator extends Evaluator<DocumentSample> { private DocumentCategorizer categorizer; private Mean accuracy = new Mean(); /** * Initializes the current instance. * * @param categorizer the document categorizer instance */ public DocumentCategorizerEvaluator(DocumentCategorizer categorizer, DoccatEvaluationMonitor ... listeners) { super(listeners); this.categorizer = categorizer; } /** * Evaluates the given reference {@link DocumentSample} object. * * This is done by categorizing the document from the provided * {@link DocumentSample}. The detected category is then used * to calculate and update the score. * * @param sample the reference {@link TokenSample}. */ public DocumentSample processSample(DocumentSample sample) { String[] document = sample.getText(); double[] probs = categorizer.categorize(document); String cat = categorizer.getBestCategory(probs); if (sample.getCategory().equals(cat)) { accuracy.add(1); } else { accuracy.add(0); } return new DocumentSample(cat, sample.getText()); } /** * Retrieves the accuracy of provided {@link DocumentCategorizer}. * * accuracy = correctly categorized documents / total documents * * @return the accuracy */ public double getAccuracy() { return accuracy.mean(); } public long getDocumentCount() { return accuracy.count(); } /** * Represents this objects as human readable {@link String}. */ @Override public String toString() { return "Accuracy: " + accuracy.mean() + "\n" + "Number of documents: " + accuracy.count(); } }
0
java-sources/ai/idylnlp/idylnlp-opennlp-tools-1.8.3/1.1.0/opennlp/tools
java-sources/ai/idylnlp/idylnlp-opennlp-tools-1.8.3/1.1.0/opennlp/tools/doccat/DocumentCategorizerEventStream.java
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package opennlp.tools.doccat; import java.util.Iterator; import opennlp.tools.ml.model.Event; import opennlp.tools.util.AbstractEventStream; import opennlp.tools.util.ObjectStream; /** * Iterator-like class for modeling document classification events. */ public class DocumentCategorizerEventStream extends AbstractEventStream<DocumentSample> { private DocumentCategorizerContextGenerator mContextGenerator; /** * Initializes the current instance via samples and feature generators. * * @param data {@link ObjectStream} of {@link DocumentSample}s * * @param featureGenerators the feature generators */ public DocumentCategorizerEventStream(ObjectStream<DocumentSample> data, FeatureGenerator... featureGenerators) { super(data); mContextGenerator = new DocumentCategorizerContextGenerator(featureGenerators); } /** * Initializes the current instance. * * @param samples {@link ObjectStream} of {@link DocumentSample}s */ public DocumentCategorizerEventStream(ObjectStream<DocumentSample> samples) { super(samples); mContextGenerator = new DocumentCategorizerContextGenerator(new BagOfWordsFeatureGenerator()); } @Override protected Iterator<Event> createEvents(final DocumentSample sample) { return new Iterator<Event>() { private boolean isVirgin = true; public boolean hasNext() { return isVirgin; } public Event next() { isVirgin = false; return new Event(sample.getCategory(), mContextGenerator.getContext(sample.getText(), sample.getExtraInformation())); } public void remove() { throw new UnsupportedOperationException(); } }; } }
0
java-sources/ai/idylnlp/idylnlp-opennlp-tools-1.8.3/1.1.0/opennlp/tools
java-sources/ai/idylnlp/idylnlp-opennlp-tools-1.8.3/1.1.0/opennlp/tools/doccat/DocumentCategorizerME.java
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package opennlp.tools.doccat; import java.io.IOException; import java.util.Collections; import java.util.HashMap; import java.util.HashSet; import java.util.Map; import java.util.Set; import java.util.SortedMap; import java.util.TreeMap; import opennlp.tools.ml.EventTrainer; import opennlp.tools.ml.TrainerFactory; import opennlp.tools.ml.model.MaxentModel; import opennlp.tools.util.ObjectStream; import opennlp.tools.util.TrainingParameters; /** * Maxent implementation of {@link DocumentCategorizer}. */ public class DocumentCategorizerME implements DocumentCategorizer { /** * Shared default thread safe feature generator. */ private static FeatureGenerator defaultFeatureGenerator = new BagOfWordsFeatureGenerator(); private DoccatModel model; private DocumentCategorizerContextGenerator mContextGenerator; /** * Initializes the current instance with a doccat model. Default feature * generation is used. * * @param model the doccat model */ public DocumentCategorizerME(DoccatModel model) { this.model = model; this.mContextGenerator = new DocumentCategorizerContextGenerator(this.model .getFactory().getFeatureGenerators()); } /** * Categorize the given text provided as tokens along with * the provided extra information * * @param text text tokens to categorize * @param extraInformation additional information */ @Override public double[] categorize(String[] text, Map<String, Object> extraInformation) { return model.getMaxentModel().eval( mContextGenerator.getContext(text, extraInformation)); } /** * Categorizes the given text. * * @param text the text to categorize */ @Override public double[] categorize(String[] text) { return this.categorize(text, Collections.emptyMap()); } /** * Returns a map in which the key is the category name and the value is the score * * @param text the input text to classify * @return the score map */ @Override public Map<String, Double> scoreMap(String[] text) { Map<String, Double> probDist = new HashMap<>(); double[] categorize = categorize(text); int catSize = getNumberOfCategories(); for (int i = 0; i < catSize; i++) { String category = getCategory(i); probDist.put(category, categorize[getIndex(category)]); } return probDist; } /** * Returns a map with the score as a key in ascending order. * The value is a Set of categories with the score. * Many categories can have the same score, hence the Set as value * * @param text the input text to classify * @return the sorted score map */ @Override public SortedMap<Double, Set<String>> sortedScoreMap(String[] text) { SortedMap<Double, Set<String>> descendingMap = new TreeMap<>(); double[] categorize = categorize(text); int catSize = getNumberOfCategories(); for (int i = 0; i < catSize; i++) { String category = getCategory(i); double score = categorize[getIndex(category)]; if (descendingMap.containsKey(score)) { descendingMap.get(score).add(category); } else { Set<String> newset = new HashSet<>(); newset.add(category); descendingMap.put(score, newset); } } return descendingMap; } public String getBestCategory(double[] outcome) { return model.getMaxentModel().getBestOutcome(outcome); } public int getIndex(String category) { return model.getMaxentModel().getIndex(category); } public String getCategory(int index) { return model.getMaxentModel().getOutcome(index); } public int getNumberOfCategories() { return model.getMaxentModel().getNumOutcomes(); } public String getAllResults(double[] results) { return model.getMaxentModel().getAllOutcomes(results); } public static DoccatModel train(String languageCode, ObjectStream<DocumentSample> samples, TrainingParameters mlParams, DoccatFactory factory) throws IOException { Map<String, String> manifestInfoEntries = new HashMap<>(); EventTrainer trainer = TrainerFactory.getEventTrainer( mlParams, manifestInfoEntries); MaxentModel model = trainer.train( new DocumentCategorizerEventStream(samples, factory.getFeatureGenerators())); return new DoccatModel(languageCode, model, manifestInfoEntries, factory); } }
0
java-sources/ai/idylnlp/idylnlp-opennlp-tools-1.8.3/1.1.0/opennlp/tools
java-sources/ai/idylnlp/idylnlp-opennlp-tools-1.8.3/1.1.0/opennlp/tools/doccat/DocumentSample.java
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package opennlp.tools.doccat; import java.io.Serializable; import java.util.ArrayList; import java.util.Arrays; import java.util.Collections; import java.util.List; import java.util.Map; import java.util.Objects; /** * Class which holds a classified document and its category. */ public class DocumentSample implements Serializable { private final String category; private final List<String> text; private final Map<String, Object> extraInformation; public DocumentSample(String category, String[] text) { this(category, text, null); } public DocumentSample(String category, String[] text, Map<String, Object> extraInformation) { Objects.requireNonNull(text, "text must not be null"); this.category = Objects.requireNonNull(category, "category must not be null"); this.text = Collections.unmodifiableList(new ArrayList<>(Arrays.asList(text))); if (extraInformation == null) { this.extraInformation = Collections.emptyMap(); } else { this.extraInformation = extraInformation; } } public String getCategory() { return category; } public String[] getText() { return text.toArray(new String[text.size()]); } public Map<String, Object> getExtraInformation() { return extraInformation; } @Override public String toString() { StringBuilder sampleString = new StringBuilder(); sampleString.append(category).append('\t'); for (String s : text) { sampleString.append(s).append(' '); } if (sampleString.length() > 0) { // remove last space sampleString.setLength(sampleString.length() - 1); } return sampleString.toString(); } @Override public int hashCode() { return Objects.hash(getCategory(), Arrays.hashCode(getText())); } @Override public boolean equals(Object obj) { if (this == obj) { return true; } if (obj instanceof DocumentSample) { DocumentSample a = (DocumentSample) obj; return getCategory().equals(a.getCategory()) && Arrays.equals(getText(), a.getText()); } return false; } }
0
java-sources/ai/idylnlp/idylnlp-opennlp-tools-1.8.3/1.1.0/opennlp/tools
java-sources/ai/idylnlp/idylnlp-opennlp-tools-1.8.3/1.1.0/opennlp/tools/doccat/DocumentSampleStream.java
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package opennlp.tools.doccat; import java.io.IOException; import opennlp.tools.tokenize.WhitespaceTokenizer; import opennlp.tools.util.FilterObjectStream; import opennlp.tools.util.ObjectStream; /** * This class reads in string encoded training samples, parses them and * outputs {@link DocumentSample} objects. * <p> * Format:<br> * Each line contains one sample document.<br> * The category is the first string in the line followed by a tab and whitespace * separated document tokens.<br> * Sample line: category-string tab-char whitespace-separated-tokens line-break-char(s)<br> */ public class DocumentSampleStream extends FilterObjectStream<String, DocumentSample> { public DocumentSampleStream(ObjectStream<String> samples) { super(samples); } public DocumentSample read() throws IOException { String sampleString = samples.read(); if (sampleString != null) { // Whitespace tokenize entire string String[] tokens = WhitespaceTokenizer.INSTANCE.tokenize(sampleString); DocumentSample sample; if (tokens.length > 1) { String category = tokens[0]; String[] docTokens = new String[tokens.length - 1]; System.arraycopy(tokens, 1, docTokens, 0, tokens.length - 1); sample = new DocumentSample(category, docTokens); } else { throw new IOException("Empty lines, or lines with only a category string are not allowed!"); } return sample; } return null; } }
0
java-sources/ai/idylnlp/idylnlp-opennlp-tools-1.8.3/1.1.0/opennlp/tools
java-sources/ai/idylnlp/idylnlp-opennlp-tools-1.8.3/1.1.0/opennlp/tools/doccat/FeatureGenerator.java
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package opennlp.tools.doccat; import java.util.Collection; import java.util.Map; /** * Interface for generating features for document categorization. */ public interface FeatureGenerator { /** * Extract features from given text fragments * * @param text the text fragments to extract features from * @param extraInformation optional extra information to be used by the feature generator * @return a collection of features */ Collection<String> extractFeatures(String[] text, Map<String, Object> extraInformation); }
0
java-sources/ai/idylnlp/idylnlp-opennlp-tools-1.8.3/1.1.0/opennlp/tools
java-sources/ai/idylnlp/idylnlp-opennlp-tools-1.8.3/1.1.0/opennlp/tools/doccat/NGramFeatureGenerator.java
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package opennlp.tools.doccat; import java.util.ArrayList; import java.util.Collection; import java.util.List; import java.util.Map; import java.util.Objects; import opennlp.tools.util.InvalidFormatException; /** * Generates ngram features for a document. * n-gram {@link FeatureGenerator} */ public class NGramFeatureGenerator implements FeatureGenerator { private final int minGram; private final int maxGram; /** * Constructor for ngrams. * * @param minGram minGram value - which means minimum words in ngram features * @param maxGram maxGram value - which means maximum words in ngram features * @throws InvalidFormatException */ public NGramFeatureGenerator(int minGram, int maxGram) throws InvalidFormatException { if (minGram > 0 && maxGram > 0) { if (minGram <= maxGram) { this.minGram = minGram; this.maxGram = maxGram; } else { throw new InvalidFormatException( "Minimum range value (minGram) should be less than or equal to maximum range value (maxGram)!"); } } else { throw new InvalidFormatException("Both minimum range value (minGram) & maximum " + "range value (maxGram) should be greater than or equal to 1!"); } } /** * Default constructor for Bi grams */ public NGramFeatureGenerator() throws InvalidFormatException { this(2, 2); } /** * Extract ngram features from given text fragments * * @param text the text fragments to extract features from * @param extraInfo optional extra information * @return a collection of n gram features */ public Collection<String> extractFeatures(String[] text, Map<String, Object> extraInfo) { Objects.requireNonNull(text, "text must not be null"); List<String> features = new ArrayList<>(); for (int i = 0; i <= text.length - minGram; i++) { final StringBuilder sb = new StringBuilder(); sb.append("ng="); for (int y = 0; y < maxGram && i + y < text.length; y++) { sb.append(":"); sb.append(text[i + y]); int gramCount = y + 1; if (maxGram >= gramCount && gramCount >= minGram) { features.add(sb.toString()); } } } return features; } }
0
java-sources/ai/idylnlp/idylnlp-opennlp-tools-1.8.3/1.1.0/opennlp/tools
java-sources/ai/idylnlp/idylnlp-opennlp-tools-1.8.3/1.1.0/opennlp/tools/doccat/package-info.java
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ /** * Package for classifying a document into a category. */ package opennlp.tools.doccat;
0
java-sources/ai/idylnlp/idylnlp-opennlp-tools-1.8.3/1.1.0/opennlp/tools
java-sources/ai/idylnlp/idylnlp-opennlp-tools-1.8.3/1.1.0/opennlp/tools/entitylinker/BaseLink.java
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package opennlp.tools.entitylinker; import java.util.HashMap; import java.util.Objects; /** * Stores a minimal tuple of information. Intended to be used with LinkedSpan * * */ public abstract class BaseLink { private String itemParentID; private String itemID; private String itemName; private String itemType; private HashMap<String, Double> scoreMap = new HashMap<>(); public BaseLink() { } public BaseLink(String itemParentID, String itemID, String itemName, String itemType) { this.itemParentID = itemParentID; this.itemID = itemID; this.itemName = itemName; this.itemType = itemType; } /** * Any parent ID for the linked item * @return */ public String getItemParentID() { return itemParentID; } /** * returns the parent ID of the linked item * @param itemParentID */ public void setItemParentID(String itemParentID) { this.itemParentID = itemParentID; } /** * returns the itemid * * @return */ public String getItemID() { return itemID; } /** * sets the item id. This field can store, for example, the primary key of a * row in an external/linked database * * @param itemID */ public void setItemID(String itemID) { this.itemID = itemID; } /** * returns the name * * @return */ public String getItemName() { return itemName; } /** * Sets the item name. An item name can be the native name (often a normalized * version of something) from an external linked database * * @param itemName */ public void setItemName(String itemName) { this.itemName = itemName; } /** * returns the type * * @return */ public String getItemType() { return itemType; } /** * sets the item type. An item type can be the native type from an external * linked database. For instance, a product type or code * * @param itemType */ public void setItemType(String itemType) { this.itemType = itemType; } public HashMap<String, Double> getScoreMap() { return scoreMap; } public void setScoreMap(HashMap<String, Double> scoreMap) { this.scoreMap = scoreMap; } @Override public String toString() { return "\tBaseLink" + "\n\titemParentID=" + itemParentID + ", \n\titemID=" + itemID + ", \n\titemName=" + itemName + ", \n\titemType=" + itemType + ", \n\tscoreMap=" + scoreMap + "\n"; } @Override public int hashCode() { return Objects.hash(itemParentID, itemID, itemName, itemType); } @Override public boolean equals(Object obj) { if (obj == this) { return true; } if (obj instanceof BaseLink) { BaseLink other = (BaseLink) obj; return Objects.equals(itemParentID, other.itemParentID) && Objects.equals(itemID, other.itemID) && Objects.equals(itemName, other.itemName) && Objects.equals(itemType, other.itemType); } return false; } }
0
java-sources/ai/idylnlp/idylnlp-opennlp-tools-1.8.3/1.1.0/opennlp/tools
java-sources/ai/idylnlp/idylnlp-opennlp-tools-1.8.3/1.1.0/opennlp/tools/entitylinker/EntityLinker.java
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package opennlp.tools.entitylinker; import java.io.IOException; import java.util.List; import opennlp.tools.util.Span; /** * EntityLinkers establish connections to external data to enrich extracted * entities. For instance, for Location entities a linker can be developed to * lookup each found location in a geonames gazateer. Another example may be to * find peoples' names and look them up in a database or active directory. * Intended to return n best matches for any give search, but can also be * implemented as deterministic * * @param <T> A type that extends Span. LinkedSpan and BaseLink are provided to * provide this signature: EntityLinker&lt;LinkedSpan&lt;BaseLink&gt;&gt; as a * default */ public interface EntityLinker<T extends Span> { /** * allows for passing properties through the EntityLinkerFactory into all * impls dynamically. EntityLinker impls should initialize reusable objects * used by the impl in this method. If this is done, any errors will be * captured and thrown by the EntityLinkerFactory. * * @param initializationData the EntityLinkerProperties object that contains * properties needed by the impl, as well as any * other objects required for the impl * @throws java.io.IOException */ void init(EntityLinkerProperties initializationData) throws IOException; /** * Links an entire document of named entities to an external source * * @param doctext the full text of the document * @param tokensBySentence a list of tokens spans that correspond to each sentence. * The outer array refers to the sentence, the inner * array is the tokens for the outer sentence. Similar * in nature to Map of SentenceIndex keys to Listof * tokens as values * @param namesBySentence a list of name spans that correspond to each * sentence. The outer array refers to the sentence, * the inner array refers to the tokens that for the * same sentence.Similar in nature to * Map&lt;SentenceIndex,List&lt;Name Spans For This * Sentence's Tokens&gt;&gt; @ return * @return */ List<T> find(String doctext, Span[] sentences, Span[][] tokensBySentence, Span[][] namesBySentence); /** * Links the names that correspond to the tokens[] spans. The sentenceindex * can be used to get the sentence text and tokens from the text based on the * sentence and token spans. The text is available for additional context. * * @param doctext the full text of the document * @param tokensBySentence a list of tokens spans that correspond to each sentence. * The outer array refers to the sentence, the inner * array is the tokens for the outer sentence. Similar * in nature to Map of SentenceIndex keys to Listof * tokens as values * @param namesBySentence a list of name spans that correspond to each * sentence. The outer array refers to the sentence, * the inner array refers to the tokens that for the * same sentence.Similar in nature to * Map&lt;SentenceIndex,List&lt;Name Spans For This * Sentence's Tokens&gt;&gt; @ return * @param sentenceIndex the index to the sentence span that the tokens[] * Span[] corresponds to * @return */ List<T> find(String doctext, Span[] sentences, Span[][] tokensBySentence, Span[][] namesBySentence, int sentenceIndex); }
0
java-sources/ai/idylnlp/idylnlp-opennlp-tools-1.8.3/1.1.0/opennlp/tools
java-sources/ai/idylnlp/idylnlp-opennlp-tools-1.8.3/1.1.0/opennlp/tools/entitylinker/EntityLinkerFactory.java
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package opennlp.tools.entitylinker; import java.io.IOException; import java.util.Objects; import opennlp.tools.util.ext.ExtensionLoader; /** * Generates an EntityLinker implementation via properties file configuration * */ public class EntityLinkerFactory { /** * * * @param entityType The type of entity being linked to. This value is used to * retrieve the implementation of the entitylinker from the * entitylinker properties file. * @param properties An object that extends EntityLinkerProperties. This * object will be passed into the implemented EntityLinker * init(..) method, so it is an appropriate place to put * additional resources. * @return an EntityLinker impl * @throws java.io.IOException */ public static synchronized EntityLinker<?> getLinker(String entityType, EntityLinkerProperties properties) throws IOException { if (entityType == null || properties == null) { throw new IllegalArgumentException("Null argument in entityLinkerFactory"); } String linkerImplFullName = properties.getProperty("linker." + entityType, ""); if (linkerImplFullName == null || linkerImplFullName.equals("")) { throw new IllegalArgumentException("linker." + entityType + " property must be set!"); } EntityLinker<?> linker = ExtensionLoader.instantiateExtension(EntityLinker.class, linkerImplFullName); linker.init(properties); return linker; } /** * * * * @param properties An object that extends EntityLinkerProperties. This * object will be passed into the implemented EntityLinker * init(..) method, so it is an appropriate place to put * additional resources. In the properties file, the linker implementation must be * provided using "linker" as the properties key, and the * full class name as value * @return an EntityLinker impl * @throws java.io.IOException */ public static synchronized EntityLinker<?> getLinker(EntityLinkerProperties properties) throws IOException { Objects.requireNonNull(properties, "properties argument must not be null"); String linkerImplFullName = properties.getProperty("linker", ""); if (linkerImplFullName == null || linkerImplFullName.equals("")) { throw new IllegalArgumentException("\"linker\" property must be set!"); } EntityLinker<?> linker = ExtensionLoader.instantiateExtension(EntityLinker.class, linkerImplFullName); linker.init(properties); return linker; } }
0
java-sources/ai/idylnlp/idylnlp-opennlp-tools-1.8.3/1.1.0/opennlp/tools
java-sources/ai/idylnlp/idylnlp-opennlp-tools-1.8.3/1.1.0/opennlp/tools/entitylinker/EntityLinkerProperties.java
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package opennlp.tools.entitylinker; import java.io.File; import java.io.FileInputStream; import java.io.IOException; import java.io.InputStream; import java.util.Properties; /** * Properties wrapper for the EntityLinker framework * */ public class EntityLinkerProperties { private Properties props; /** * Constructor takes location of properties file as arg * * @param propertiesfile the properties file * @throws IOException */ public EntityLinkerProperties(File propertiesfile) throws IOException { InputStream stream = null; try { stream = new FileInputStream(propertiesfile); init(stream); } finally { if (stream != null) { stream.close(); } } } /** * * @param propertiesIn inputstream of properties file. Stream will not be * closed * @throws IOException * */ public EntityLinkerProperties(InputStream propertiesIn) throws IOException { init(propertiesIn); } private void init(InputStream propertiesIn) throws IOException { props = new Properties(); props.load(propertiesIn); } /** * Gets a property from the props file. * * @param key the key to the desired item in the properties file * (key=value) * @param defaultValue a default value in case the key, or the value are * missing * @return a property value in the form of a string * @throws IOException when the properties object was somehow not initialized properly */ public String getProperty(String key, String defaultValue) throws IOException { if (props != null) { return props.getProperty(key, defaultValue); } else { throw new IOException("EntityLinkerProperties was not successfully initialized"); } } }
0
java-sources/ai/idylnlp/idylnlp-opennlp-tools-1.8.3/1.1.0/opennlp/tools
java-sources/ai/idylnlp/idylnlp-opennlp-tools-1.8.3/1.1.0/opennlp/tools/entitylinker/LinkedSpan.java
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package opennlp.tools.entitylinker; import java.util.ArrayList; import java.util.Objects; import opennlp.tools.util.Span; /** * An "default" extended span that holds additional information about the Span * * * @param <T> */ public class LinkedSpan<T extends BaseLink> extends Span { private ArrayList<T> linkedEntries; private int sentenceid = 0; private String searchTerm; public LinkedSpan(ArrayList<T> linkedEntries, int s, int e, String type) { super(s, e, type); this.linkedEntries = linkedEntries; } public LinkedSpan(ArrayList<T> linkedEntries, int s, int e, String type, double prob) { super(s, e, type, prob); this.linkedEntries = linkedEntries; } public LinkedSpan(ArrayList<T> linkedEntries, int s, int e) { super(s, e); this.linkedEntries = linkedEntries; } public LinkedSpan(ArrayList<T> linkedEntries, Span span, int offset) { super(span, offset); this.linkedEntries = linkedEntries; } /** * Returns the n best linked entries from an external data source. For * instance, this will hold gazateer entries for a search into a geonames * gazateer * * @return */ public ArrayList<T> getLinkedEntries() { return linkedEntries; } /** * Sets the n best linked entries from an external data source. For instance, * this will hold gazateer entries for a search into a geonames gazateer * */ public void setLinkedEntries(ArrayList<T> linkedEntries) { this.linkedEntries = linkedEntries; } /** * Returns the id or index of the sentence from which this span was extracted * * @return */ public int getSentenceid() { return sentenceid; } /** * sets the id or index of the sentence from which this span was extracted * * @param sentenceid */ public void setSentenceid(int sentenceid) { this.sentenceid = sentenceid; } /** * Returns the search term that was used to link this span to an external data * source * * @return searchTerm */ public String getSearchTerm() { return searchTerm; } /** * sets the search term that is used to link this span to an external data * source * * @param searchTerm */ public void setSearchTerm(String searchTerm) { this.searchTerm = searchTerm; } @Override public String toString() { return "LinkedSpan\nsentenceid=" + sentenceid + "\nsearchTerm=" + searchTerm + "\nlinkedEntries=\n" + linkedEntries + "\n"; } @Override public int hashCode() { return Objects.hash(linkedEntries, sentenceid, searchTerm); } @Override public boolean equals(Object obj) { if (obj == null) { return false; } if (obj instanceof LinkedSpan) { final LinkedSpan<T> other = (LinkedSpan<T>) obj; return Objects.equals(this.linkedEntries, other.linkedEntries) && this.sentenceid == other.sentenceid && Objects.equals(this.searchTerm, other.searchTerm); } return false; } }
0
java-sources/ai/idylnlp/idylnlp-opennlp-tools-1.8.3/1.1.0/opennlp/tools
java-sources/ai/idylnlp/idylnlp-opennlp-tools-1.8.3/1.1.0/opennlp/tools/formats/AbstractSampleStreamFactory.java
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package opennlp.tools.formats; import opennlp.tools.cmdline.ObjectStreamFactory; /** * Base class for sample stream factories. */ public abstract class AbstractSampleStreamFactory<T> implements ObjectStreamFactory<T> { protected Class params; private AbstractSampleStreamFactory() { } protected <P> AbstractSampleStreamFactory(Class<P> params) { this.params = params; } public String getLang() { return "eng"; } @SuppressWarnings({"unchecked"}) public <P> Class<P> getParameters() { return params; } }
0
java-sources/ai/idylnlp/idylnlp-opennlp-tools-1.8.3/1.1.0/opennlp/tools
java-sources/ai/idylnlp/idylnlp-opennlp-tools-1.8.3/1.1.0/opennlp/tools/formats/BioNLP2004NameSampleStream.java
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package opennlp.tools.formats; import java.io.IOException; import java.io.PrintStream; import java.io.UnsupportedEncodingException; import java.nio.charset.StandardCharsets; import java.util.ArrayList; import java.util.List; import opennlp.tools.namefind.NameSample; import opennlp.tools.util.InputStreamFactory; import opennlp.tools.util.ObjectStream; import opennlp.tools.util.PlainTextByLineStream; import opennlp.tools.util.Span; import opennlp.tools.util.StringUtil; /** * Parser for the training files of the BioNLP/NLPBA 2004 shared task. * <p> * The data contains five named entity types: DNA, RNA, protein, cell_type and cell_line.<br> * <p> * Data can be found on this web site:<br> * http://www-tsujii.is.s.u-tokyo.ac.jp/GENIA/ERtask/report.html * <p> * <b>Note:</b> Do not use this class, internal use only! */ public class BioNLP2004NameSampleStream implements ObjectStream<NameSample> { public static final int GENERATE_DNA_ENTITIES = 0x01; public static final int GENERATE_PROTEIN_ENTITIES = 0x01 << 1; public static final int GENERATE_CELLTYPE_ENTITIES = 0x01 << 2; public static final int GENERATE_CELLLINE_ENTITIES = 0x01 << 3; public static final int GENERATE_RNA_ENTITIES = 0x01 << 4; private final int types; private final ObjectStream<String> lineStream; public BioNLP2004NameSampleStream(InputStreamFactory in, int types) throws IOException { try { this.lineStream = new PlainTextByLineStream(in, StandardCharsets.UTF_8); System.setOut(new PrintStream(System.out, true, "UTF-8")); } catch (UnsupportedEncodingException e) { // UTF-8 is available on all JVMs, will never happen throw new IllegalStateException(e); } this.types = types; } public NameSample read() throws IOException { List<String> sentence = new ArrayList<>(); List<String> tags = new ArrayList<>(); boolean isClearAdaptiveData = false; // Empty line indicates end of sentence String line; while ((line = lineStream.read()) != null && !StringUtil.isEmpty(line.trim())) { if (line.startsWith("###MEDLINE:")) { isClearAdaptiveData = true; lineStream.read(); continue; } if (line.contains("ABSTRACT TRUNCATED")) continue; String[] fields = line.split("\t"); if (fields.length == 2) { sentence.add(fields[0]); tags.add(fields[1]); } else { throw new IOException("Expected two fields per line in training data, got " + fields.length + " for line '" + line + "'!"); } } if (sentence.size() > 0) { // convert name tags into spans List<Span> names = new ArrayList<>(); int beginIndex = -1; int endIndex = -1; for (int i = 0; i < tags.size(); i++) { String tag = tags.get(i); if (tag.endsWith("DNA") && (types & GENERATE_DNA_ENTITIES) == 0) tag = "O"; if (tag.endsWith("protein") && (types & GENERATE_PROTEIN_ENTITIES) == 0) tag = "O"; if (tag.endsWith("cell_type") && (types & GENERATE_CELLTYPE_ENTITIES) == 0) tag = "O"; if (tag.endsWith("cell_line") && (types & GENERATE_CELLTYPE_ENTITIES) == 0) tag = "O"; if (tag.endsWith("RNA") && (types & GENERATE_RNA_ENTITIES) == 0) tag = "O"; if (tag.startsWith("B-")) { if (beginIndex != -1) { names.add(new Span(beginIndex, endIndex, tags.get(beginIndex).substring(2))); beginIndex = -1; endIndex = -1; } beginIndex = i; endIndex = i + 1; } else if (tag.startsWith("I-")) { endIndex++; } else if (tag.equals("O")) { if (beginIndex != -1) { names.add(new Span(beginIndex, endIndex, tags.get(beginIndex).substring(2))); beginIndex = -1; endIndex = -1; } } else { throw new IOException("Invalid tag: " + tag); } } // if one span remains, create it here if (beginIndex != -1) names.add(new Span(beginIndex, endIndex, tags.get(beginIndex).substring(2))); return new NameSample(sentence.toArray(new String[sentence.size()]), names.toArray(new Span[names.size()]), isClearAdaptiveData); } else if (line != null) { // Just filter out empty events, if two lines in a row are empty return read(); } else { // source stream is not returning anymore lines return null; } } public void reset() throws IOException, UnsupportedOperationException { lineStream.reset(); } public void close() throws IOException { lineStream.close(); } }
0
java-sources/ai/idylnlp/idylnlp-opennlp-tools-1.8.3/1.1.0/opennlp/tools
java-sources/ai/idylnlp/idylnlp-opennlp-tools-1.8.3/1.1.0/opennlp/tools/formats/BioNLP2004NameSampleStreamFactory.java
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package opennlp.tools.formats; import java.io.IOException; import opennlp.tools.cmdline.ArgumentParser; import opennlp.tools.cmdline.ArgumentParser.ParameterDescription; import opennlp.tools.cmdline.CmdLineUtil; import opennlp.tools.cmdline.StreamFactoryRegistry; import opennlp.tools.cmdline.params.BasicFormatParams; import opennlp.tools.namefind.NameSample; import opennlp.tools.util.ObjectStream; public class BioNLP2004NameSampleStreamFactory extends AbstractSampleStreamFactory<NameSample> { interface Parameters extends BasicFormatParams { @ParameterDescription(valueName = "DNA,protein,cell_type,cell_line,RNA") String getTypes(); } public static void registerFactory() { StreamFactoryRegistry.registerFactory(NameSample.class, "bionlp2004", new BioNLP2004NameSampleStreamFactory(Parameters.class)); } protected <P> BioNLP2004NameSampleStreamFactory(Class<P> params) { super(params); } public ObjectStream<NameSample> create(String[] args) { Parameters params = ArgumentParser.parse(args, Parameters.class); int typesToGenerate = 0; if (params.getTypes().contains("DNA")) { typesToGenerate = typesToGenerate | BioNLP2004NameSampleStream.GENERATE_DNA_ENTITIES; } else if (params.getTypes().contains("protein")) { typesToGenerate = typesToGenerate | BioNLP2004NameSampleStream.GENERATE_PROTEIN_ENTITIES; } else if (params.getTypes().contains("cell_type")) { typesToGenerate = typesToGenerate | BioNLP2004NameSampleStream.GENERATE_CELLTYPE_ENTITIES; } else if (params.getTypes().contains("cell_line")) { typesToGenerate = typesToGenerate | BioNLP2004NameSampleStream.GENERATE_CELLLINE_ENTITIES; } else if (params.getTypes().contains("RNA")) { typesToGenerate = typesToGenerate | BioNLP2004NameSampleStream.GENERATE_RNA_ENTITIES; } try { return new BioNLP2004NameSampleStream( CmdLineUtil.createInputStreamFactory(params.getData()), typesToGenerate); } catch (IOException e) { throw new IllegalStateException(e); } } }
0
java-sources/ai/idylnlp/idylnlp-opennlp-tools-1.8.3/1.1.0/opennlp/tools
java-sources/ai/idylnlp/idylnlp-opennlp-tools-1.8.3/1.1.0/opennlp/tools/formats/ChunkerSampleStreamFactory.java
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package opennlp.tools.formats; import java.io.IOException; import opennlp.tools.chunker.ChunkSample; import opennlp.tools.chunker.ChunkSampleStream; import opennlp.tools.cmdline.ArgumentParser; import opennlp.tools.cmdline.CmdLineUtil; import opennlp.tools.cmdline.StreamFactoryRegistry; import opennlp.tools.cmdline.params.BasicFormatParams; import opennlp.tools.util.InputStreamFactory; import opennlp.tools.util.ObjectStream; import opennlp.tools.util.PlainTextByLineStream; /** * Factory producing OpenNLP {@link ChunkSampleStream}s. */ public class ChunkerSampleStreamFactory extends AbstractSampleStreamFactory<ChunkSample> { interface Parameters extends BasicFormatParams { } public static void registerFactory() { StreamFactoryRegistry.registerFactory(ChunkSample.class, StreamFactoryRegistry.DEFAULT_FORMAT, new ChunkerSampleStreamFactory(Parameters.class)); } protected <P> ChunkerSampleStreamFactory(Class<P> params) { super(params); } public ObjectStream<ChunkSample> create(String[] args) { Parameters params = ArgumentParser.parse(args, Parameters.class); CmdLineUtil.checkInputFile("Data", params.getData()); InputStreamFactory sampleDataIn = CmdLineUtil.createInputStreamFactory(params.getData()); ObjectStream<String> lineStream = null; try { lineStream = new PlainTextByLineStream(sampleDataIn, params.getEncoding()); } catch (IOException ex) { CmdLineUtil.handleCreateObjectStreamError(ex); } return new ChunkSampleStream(lineStream); } }
0
java-sources/ai/idylnlp/idylnlp-opennlp-tools-1.8.3/1.1.0/opennlp/tools
java-sources/ai/idylnlp/idylnlp-opennlp-tools-1.8.3/1.1.0/opennlp/tools/formats/Conll02NameSampleStream.java
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package opennlp.tools.formats; import java.io.IOException; import java.io.PrintStream; import java.io.UnsupportedEncodingException; import java.nio.charset.StandardCharsets; import java.util.ArrayList; import java.util.List; import opennlp.tools.namefind.NameSample; import opennlp.tools.util.InputStreamFactory; import opennlp.tools.util.InvalidFormatException; import opennlp.tools.util.ObjectStream; import opennlp.tools.util.PlainTextByLineStream; import opennlp.tools.util.Span; import opennlp.tools.util.StringUtil; /** * Parser for the dutch and spanish ner training files of the CONLL 2002 shared task. * <p> * The dutch data has a -DOCSTART- tag to mark article boundaries, * adaptive data in the feature generators will be cleared before every article.<br> * The spanish data does not contain article boundaries, * adaptive data will be cleared for every sentence. * <p> * The data contains four named entity types: Person, Organization, Location and Misc.<br> * <p> * Data can be found on this web site:<br> * http://www.cnts.ua.ac.be/conll2002/ner/ * <p> * <b>Note:</b> Do not use this class, internal use only! */ public class Conll02NameSampleStream implements ObjectStream<NameSample> { public enum LANGUAGE { NLD, SPA } public static final int GENERATE_PERSON_ENTITIES = 0x01; public static final int GENERATE_ORGANIZATION_ENTITIES = 0x01 << 1; public static final int GENERATE_LOCATION_ENTITIES = 0x01 << 2; public static final int GENERATE_MISC_ENTITIES = 0x01 << 3; public static final String DOCSTART = "-DOCSTART-"; private final LANGUAGE lang; private final ObjectStream<String> lineStream; private final int types; public Conll02NameSampleStream(LANGUAGE lang, ObjectStream<String> lineStream, int types) { this.lang = lang; this.lineStream = lineStream; this.types = types; } public Conll02NameSampleStream(LANGUAGE lang, InputStreamFactory in, int types) throws IOException { this.lang = lang; try { this.lineStream = new PlainTextByLineStream(in, StandardCharsets.UTF_8); System.setOut(new PrintStream(System.out, true, "UTF-8")); } catch (UnsupportedEncodingException e) { // UTF-8 is available on all JVMs, will never happen throw new IllegalStateException(e); } this.types = types; } static Span extract(int begin, int end, String beginTag) throws InvalidFormatException { String type = beginTag.substring(2); if ("PER".equals(type)) { type = "person"; } else if ("LOC".equals(type)) { type = "location"; } else if ("MISC".equals(type)) { type = "misc"; } else if ("ORG".equals(type)) { type = "organization"; } else { throw new InvalidFormatException("Unknown type: " + type); } return new Span(begin, end, type); } public NameSample read() throws IOException { List<String> sentence = new ArrayList<>(); List<String> tags = new ArrayList<>(); boolean isClearAdaptiveData = false; // Empty line indicates end of sentence String line; while ((line = lineStream.read()) != null && !StringUtil.isEmpty(line)) { if (LANGUAGE.NLD.equals(lang) && line.startsWith(DOCSTART)) { isClearAdaptiveData = true; continue; } String[] fields = line.split(" "); if (fields.length == 3) { sentence.add(fields[0]); tags.add(fields[2]); } else { throw new IOException("Expected three fields per line in training data, got " + fields.length + " for line '" + line + "'!"); } } // Always clear adaptive data for spanish if (LANGUAGE.SPA.equals(lang)) isClearAdaptiveData = true; if (sentence.size() > 0) { // convert name tags into spans List<Span> names = new ArrayList<>(); int beginIndex = -1; int endIndex = -1; for (int i = 0; i < tags.size(); i++) { String tag = tags.get(i); if (tag.endsWith("PER") && (types & GENERATE_PERSON_ENTITIES) == 0) tag = "O"; if (tag.endsWith("ORG") && (types & GENERATE_ORGANIZATION_ENTITIES) == 0) tag = "O"; if (tag.endsWith("LOC") && (types & GENERATE_LOCATION_ENTITIES) == 0) tag = "O"; if (tag.endsWith("MISC") && (types & GENERATE_MISC_ENTITIES) == 0) tag = "O"; if (tag.startsWith("B-")) { if (beginIndex != -1) { names.add(extract(beginIndex, endIndex, tags.get(beginIndex))); beginIndex = -1; endIndex = -1; } beginIndex = i; endIndex = i + 1; } else if (tag.startsWith("I-")) { endIndex++; } else if (tag.equals("O")) { if (beginIndex != -1) { names.add(extract(beginIndex, endIndex, tags.get(beginIndex))); beginIndex = -1; endIndex = -1; } } else { throw new IOException("Invalid tag: " + tag); } } // if one span remains, create it here if (beginIndex != -1) names.add(extract(beginIndex, endIndex, tags.get(beginIndex))); return new NameSample(sentence.toArray(new String[sentence.size()]), names.toArray(new Span[names.size()]), isClearAdaptiveData); } else if (line != null) { // Just filter out empty events, if two lines in a row are empty return read(); } else { // source stream is not returning anymore lines return null; } } public void reset() throws IOException, UnsupportedOperationException { lineStream.reset(); } public void close() throws IOException { lineStream.close(); } }
0
java-sources/ai/idylnlp/idylnlp-opennlp-tools-1.8.3/1.1.0/opennlp/tools
java-sources/ai/idylnlp/idylnlp-opennlp-tools-1.8.3/1.1.0/opennlp/tools/formats/Conll02NameSampleStreamFactory.java
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package opennlp.tools.formats; import java.io.IOException; import opennlp.tools.cmdline.ArgumentParser; import opennlp.tools.cmdline.ArgumentParser.ParameterDescription; import opennlp.tools.cmdline.CmdLineUtil; import opennlp.tools.cmdline.StreamFactoryRegistry; import opennlp.tools.cmdline.TerminateToolException; import opennlp.tools.cmdline.params.BasicFormatParams; import opennlp.tools.formats.Conll02NameSampleStream.LANGUAGE; import opennlp.tools.namefind.NameSample; import opennlp.tools.util.ObjectStream; /** * <b>Note:</b> Do not use this class, internal use only! */ public class Conll02NameSampleStreamFactory extends LanguageSampleStreamFactory<NameSample> { interface Parameters extends BasicFormatParams { @ParameterDescription(valueName = "spa|nld") String getLang(); @ParameterDescription(valueName = "per,loc,org,misc") String getTypes(); } public static void registerFactory() { StreamFactoryRegistry.registerFactory(NameSample.class, "conll02", new Conll02NameSampleStreamFactory(Parameters.class)); } protected <P> Conll02NameSampleStreamFactory(Class<P> params) { super(params); } public ObjectStream<NameSample> create(String[] args) { Parameters params = ArgumentParser.parse(args, Parameters.class); LANGUAGE lang; if ("nl".equals(params.getLang()) || "nld".equals(params.getLang())) { lang = LANGUAGE.NLD; language = params.getLang(); } else if ("es".equals(params.getLang()) || "spa".equals(params.getLang())) { lang = LANGUAGE.SPA; language = params.getLang(); } else { throw new TerminateToolException(1, "Unsupported language: " + params.getLang()); } int typesToGenerate = 0; if (params.getTypes().contains("per")) { typesToGenerate = typesToGenerate | Conll02NameSampleStream.GENERATE_PERSON_ENTITIES; } if (params.getTypes().contains("org")) { typesToGenerate = typesToGenerate | Conll02NameSampleStream.GENERATE_ORGANIZATION_ENTITIES; } if (params.getTypes().contains("loc")) { typesToGenerate = typesToGenerate | Conll02NameSampleStream.GENERATE_LOCATION_ENTITIES; } if (params.getTypes().contains("misc")) { typesToGenerate = typesToGenerate | Conll02NameSampleStream.GENERATE_MISC_ENTITIES; } try { return new Conll02NameSampleStream(lang, CmdLineUtil.createInputStreamFactory(params.getData()), typesToGenerate); } catch (IOException e) { throw CmdLineUtil.createObjectStreamError(e); } } }
0
java-sources/ai/idylnlp/idylnlp-opennlp-tools-1.8.3/1.1.0/opennlp/tools
java-sources/ai/idylnlp/idylnlp-opennlp-tools-1.8.3/1.1.0/opennlp/tools/formats/Conll03NameSampleStream.java
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package opennlp.tools.formats; import java.io.IOException; import java.io.PrintStream; import java.io.UnsupportedEncodingException; import java.nio.charset.StandardCharsets; import java.util.ArrayList; import java.util.List; import opennlp.tools.namefind.NameSample; import opennlp.tools.util.InputStreamFactory; import opennlp.tools.util.ObjectStream; import opennlp.tools.util.PlainTextByLineStream; import opennlp.tools.util.Span; import opennlp.tools.util.StringUtil; /** * An import stream which can parse the CONLL03 data. */ public class Conll03NameSampleStream implements ObjectStream<NameSample> { public enum LANGUAGE { EN, DE } private final LANGUAGE lang; private final ObjectStream<String> lineStream; private final int types; /** * * @param lang the language of the CONLL 03 data * @param lineStream an Object Stream over the lines in the CONLL 03 data file * @param types the entity types to include in the Name Sample object stream */ public Conll03NameSampleStream(LANGUAGE lang, ObjectStream<String> lineStream, int types) { this.lang = lang; this.lineStream = lineStream; this.types = types; } public Conll03NameSampleStream(LANGUAGE lang, InputStreamFactory in, int types) throws IOException { this.lang = lang; try { this.lineStream = new PlainTextByLineStream(in, StandardCharsets.UTF_8); System.setOut(new PrintStream(System.out, true, "UTF-8")); } catch (UnsupportedEncodingException e) { // UTF-8 is available on all JVMs, will never happen throw new IllegalStateException(e); } this.types = types; } public NameSample read() throws IOException { List<String> sentence = new ArrayList<>(); List<String> tags = new ArrayList<>(); boolean isClearAdaptiveData = false; // Empty line indicates end of sentence String line; while ((line = lineStream.read()) != null && !StringUtil.isEmpty(line)) { if (line.startsWith(Conll02NameSampleStream.DOCSTART)) { isClearAdaptiveData = true; String emptyLine = lineStream.read(); if (!StringUtil.isEmpty(emptyLine)) throw new IOException("Empty line after -DOCSTART- not empty: '" + emptyLine + "'!"); continue; } String[] fields = line.split(" "); // For English: WORD POS-TAG SC-TAG NE-TAG if (LANGUAGE.EN.equals(lang) && fields.length == 4) { sentence.add(fields[0]); tags.add(fields[3]); // 3 is NE-TAG } // For German: WORD LEMA-TAG POS-TAG SC-TAG NE-TAG else if (LANGUAGE.DE.equals(lang) && fields.length == 5) { sentence.add(fields[0]); tags.add(fields[4]); // 4 is NE-TAG } else { throw new IOException("Incorrect number of fields per line for language: '" + line + "'!"); } } if (sentence.size() > 0) { // convert name tags into spans List<Span> names = new ArrayList<>(); int beginIndex = -1; int endIndex = -1; for (int i = 0; i < tags.size(); i++) { String tag = tags.get(i); if (tag.endsWith("PER") && (types & Conll02NameSampleStream.GENERATE_PERSON_ENTITIES) == 0) tag = "O"; if (tag.endsWith("ORG") && (types & Conll02NameSampleStream.GENERATE_ORGANIZATION_ENTITIES) == 0) tag = "O"; if (tag.endsWith("LOC") && (types & Conll02NameSampleStream.GENERATE_LOCATION_ENTITIES) == 0) tag = "O"; if (tag.endsWith("MISC") && (types & Conll02NameSampleStream.GENERATE_MISC_ENTITIES) == 0) tag = "O"; if (tag.equals("O")) { // O means we don't have anything this round. if (beginIndex != -1) { names.add(Conll02NameSampleStream.extract(beginIndex, endIndex, tags.get(beginIndex))); beginIndex = -1; endIndex = -1; } } else if (tag.startsWith("B-")) { // B- prefix means we have two same entities next to each other if (beginIndex != -1) { names.add(Conll02NameSampleStream.extract(beginIndex, endIndex, tags.get(beginIndex))); } beginIndex = i; endIndex = i + 1; } else if (tag.startsWith("I-")) { // I- starts or continues a current name entity if (beginIndex == -1) { beginIndex = i; endIndex = i + 1; } else if (!tag.endsWith(tags.get(beginIndex).substring(1))) { // we have a new tag type following a tagged word series // also may not have the same I- starting the previous! names.add(Conll02NameSampleStream.extract(beginIndex, endIndex, tags.get(beginIndex))); beginIndex = i; endIndex = i + 1; } else { endIndex ++; } } else { throw new IOException("Invalid tag: " + tag); } } // if one span remains, create it here if (beginIndex != -1) names.add(Conll02NameSampleStream.extract(beginIndex, endIndex, tags.get(beginIndex))); return new NameSample(sentence.toArray(new String[sentence.size()]), names.toArray(new Span[names.size()]), isClearAdaptiveData); } else if (line != null) { // Just filter out empty events, if two lines in a row are empty return read(); } else { // source stream is not returning anymore lines return null; } } public void reset() throws IOException, UnsupportedOperationException { lineStream.reset(); } public void close() throws IOException { lineStream.close(); } }
0
java-sources/ai/idylnlp/idylnlp-opennlp-tools-1.8.3/1.1.0/opennlp/tools
java-sources/ai/idylnlp/idylnlp-opennlp-tools-1.8.3/1.1.0/opennlp/tools/formats/Conll03NameSampleStreamFactory.java
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package opennlp.tools.formats; import java.io.IOException; import opennlp.tools.cmdline.ArgumentParser; import opennlp.tools.cmdline.ArgumentParser.ParameterDescription; import opennlp.tools.cmdline.CmdLineUtil; import opennlp.tools.cmdline.StreamFactoryRegistry; import opennlp.tools.cmdline.TerminateToolException; import opennlp.tools.cmdline.params.BasicFormatParams; import opennlp.tools.formats.Conll03NameSampleStream.LANGUAGE; import opennlp.tools.namefind.NameSample; import opennlp.tools.util.ObjectStream; public class Conll03NameSampleStreamFactory extends LanguageSampleStreamFactory<NameSample> { interface Parameters extends BasicFormatParams { @ParameterDescription(valueName = "eng|deu") String getLang(); @ParameterDescription(valueName = "per,loc,org,misc") String getTypes(); } public static void registerFactory() { StreamFactoryRegistry.registerFactory(NameSample.class, "conll03", new Conll03NameSampleStreamFactory(Parameters.class)); } protected <P> Conll03NameSampleStreamFactory(Class<P> params) { super(params); } public ObjectStream<NameSample> create(String[] args) { Parameters params = ArgumentParser.parse(args, Parameters.class); // TODO: support the other languages with this CoNLL. LANGUAGE lang; if ("eng".equals(params.getLang())) { lang = LANGUAGE.EN; language = params.getLang(); } else if ("deu".equals(params.getLang())) { lang = LANGUAGE.DE; language = params.getLang(); } else { throw new TerminateToolException(1, "Unsupported language: " + params.getLang()); } int typesToGenerate = 0; if (params.getTypes().contains("per")) { typesToGenerate = typesToGenerate | Conll02NameSampleStream.GENERATE_PERSON_ENTITIES; } if (params.getTypes().contains("org")) { typesToGenerate = typesToGenerate | Conll02NameSampleStream.GENERATE_ORGANIZATION_ENTITIES; } if (params.getTypes().contains("loc")) { typesToGenerate = typesToGenerate | Conll02NameSampleStream.GENERATE_LOCATION_ENTITIES; } if (params.getTypes().contains("misc")) { typesToGenerate = typesToGenerate | Conll02NameSampleStream.GENERATE_MISC_ENTITIES; } try { return new Conll03NameSampleStream(lang, CmdLineUtil.createInputStreamFactory(params.getData()), typesToGenerate); } catch (IOException e) { throw CmdLineUtil.createObjectStreamError(e); } } }
0
java-sources/ai/idylnlp/idylnlp-opennlp-tools-1.8.3/1.1.0/opennlp/tools
java-sources/ai/idylnlp/idylnlp-opennlp-tools-1.8.3/1.1.0/opennlp/tools/formats/ConllXPOSSampleStream.java
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package opennlp.tools.formats; import java.io.BufferedReader; import java.io.IOException; import java.io.StringReader; import java.nio.charset.Charset; import java.util.ArrayList; import java.util.List; import opennlp.tools.postag.POSSample; import opennlp.tools.util.FilterObjectStream; import opennlp.tools.util.InputStreamFactory; import opennlp.tools.util.InvalidFormatException; import opennlp.tools.util.ObjectStream; import opennlp.tools.util.ParagraphStream; import opennlp.tools.util.PlainTextByLineStream; /** * Parses the data from the CONLL 06 shared task into POS Samples. * <p> * More information about the data format can be found here:<br> * http://www.cnts.ua.ac.be/conll2006/ * <p> * <b>Note:</b> Do not use this class, internal use only! */ public class ConllXPOSSampleStream extends FilterObjectStream<String, POSSample> { public ConllXPOSSampleStream(ObjectStream<String> lineStream) { super(new ParagraphStream(lineStream)); } public ConllXPOSSampleStream(InputStreamFactory in, Charset charset) throws IOException { super(new ParagraphStream(new PlainTextByLineStream(in, charset))); } public POSSample read() throws IOException { // The CONLL-X data has a word per line and each line is tab separated // in the following format: // ID, FORM, LEMMA, CPOSTAG, POSTAG, ... (max 10 fields) // One paragraph contains a whole sentence and, the token // and tag will be read from the FORM and POSTAG field. String paragraph = samples.read(); POSSample sample = null; if (paragraph != null) { // paragraph get lines BufferedReader reader = new BufferedReader(new StringReader(paragraph)); List<String> tokens = new ArrayList<>(100); List<String> tags = new ArrayList<>(100); String line; while ((line = reader.readLine()) != null) { final int minNumberOfFields = 5; String[] parts = line.split("\t"); if (parts.length >= minNumberOfFields) { tokens.add(parts[1]); tags.add(parts[4]); } else { throw new InvalidFormatException("Every non-empty line must have at least " + minNumberOfFields + " fields: '" + line + "'!"); } } // just skip empty samples and read next sample if (tokens.size() == 0) sample = read(); sample = new POSSample(tokens.toArray(new String[tokens.size()]), tags.toArray(new String[tags.size()])); } return sample; } }
0
java-sources/ai/idylnlp/idylnlp-opennlp-tools-1.8.3/1.1.0/opennlp/tools
java-sources/ai/idylnlp/idylnlp-opennlp-tools-1.8.3/1.1.0/opennlp/tools/formats/ConllXPOSSampleStreamFactory.java
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package opennlp.tools.formats; import java.io.IOException; import java.io.PrintStream; import java.io.UnsupportedEncodingException; import java.nio.charset.StandardCharsets; import opennlp.tools.cmdline.ArgumentParser; import opennlp.tools.cmdline.CmdLineUtil; import opennlp.tools.cmdline.StreamFactoryRegistry; import opennlp.tools.cmdline.TerminateToolException; import opennlp.tools.cmdline.params.BasicFormatParams; import opennlp.tools.postag.POSSample; import opennlp.tools.util.InputStreamFactory; import opennlp.tools.util.ObjectStream; /** * <b>Note:</b> Do not use this class, internal use only! */ public class ConllXPOSSampleStreamFactory extends AbstractSampleStreamFactory<POSSample> { public static final String CONLLX_FORMAT = "conllx"; interface Parameters extends BasicFormatParams { } public static void registerFactory() { StreamFactoryRegistry.registerFactory(POSSample.class, CONLLX_FORMAT, new ConllXPOSSampleStreamFactory(Parameters.class)); } protected <P> ConllXPOSSampleStreamFactory(Class<P> params) { super(params); } public ObjectStream<POSSample> create(String[] args) { Parameters params = ArgumentParser.parse(args, Parameters.class); InputStreamFactory inFactory = CmdLineUtil.createInputStreamFactory(params.getData()); try { System.setOut(new PrintStream(System.out, true, "UTF-8")); return new ConllXPOSSampleStream(inFactory, StandardCharsets.UTF_8); } catch (UnsupportedEncodingException e) { // this shouldn't happen throw new TerminateToolException(-1, "UTF-8 encoding is not supported: " + e.getMessage(), e); } catch (IOException e) { // That will throw an exception CmdLineUtil.handleCreateObjectStreamError(e); return null; } } }
0
java-sources/ai/idylnlp/idylnlp-opennlp-tools-1.8.3/1.1.0/opennlp/tools
java-sources/ai/idylnlp/idylnlp-opennlp-tools-1.8.3/1.1.0/opennlp/tools/formats/ConllXSentenceSampleStreamFactory.java
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package opennlp.tools.formats; import opennlp.tools.cmdline.ArgumentParser; import opennlp.tools.cmdline.StreamFactoryRegistry; import opennlp.tools.cmdline.params.DetokenizerParameter; import opennlp.tools.formats.convert.POSToSentenceSampleStream; import opennlp.tools.postag.POSSample; import opennlp.tools.sentdetect.SentenceSample; import opennlp.tools.util.ObjectStream; /** * <b>Note:</b> Do not use this class, internal use only! */ public class ConllXSentenceSampleStreamFactory extends DetokenizerSampleStreamFactory<SentenceSample> { interface Parameters extends ConllXPOSSampleStreamFactory.Parameters, DetokenizerParameter { // TODO: make chunk size configurable } public static void registerFactory() { StreamFactoryRegistry.registerFactory(SentenceSample.class, ConllXPOSSampleStreamFactory.CONLLX_FORMAT, new ConllXSentenceSampleStreamFactory(Parameters.class)); } protected <P> ConllXSentenceSampleStreamFactory(Class<P> params) { super(params); } public ObjectStream<SentenceSample> create(String[] args) { Parameters params = ArgumentParser.parse(args, Parameters.class); ObjectStream<POSSample> posSampleStream = StreamFactoryRegistry.getFactory(POSSample.class, ConllXPOSSampleStreamFactory.CONLLX_FORMAT).create( ArgumentParser.filter(args, ConllXPOSSampleStreamFactory.Parameters.class)); return new POSToSentenceSampleStream(createDetokenizer(params), posSampleStream, 30); } }
0
java-sources/ai/idylnlp/idylnlp-opennlp-tools-1.8.3/1.1.0/opennlp/tools
java-sources/ai/idylnlp/idylnlp-opennlp-tools-1.8.3/1.1.0/opennlp/tools/formats/ConllXTokenSampleStreamFactory.java
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package opennlp.tools.formats; import opennlp.tools.cmdline.ArgumentParser; import opennlp.tools.cmdline.StreamFactoryRegistry; import opennlp.tools.cmdline.params.DetokenizerParameter; import opennlp.tools.formats.convert.POSToTokenSampleStream; import opennlp.tools.postag.POSSample; import opennlp.tools.tokenize.TokenSample; import opennlp.tools.util.ObjectStream; /** * <b>Note:</b> Do not use this class, internal use only! */ public class ConllXTokenSampleStreamFactory extends DetokenizerSampleStreamFactory<TokenSample> { interface Parameters extends ConllXPOSSampleStreamFactory.Parameters, DetokenizerParameter { } public static void registerFactory() { StreamFactoryRegistry.registerFactory(TokenSample.class, ConllXPOSSampleStreamFactory.CONLLX_FORMAT, new ConllXTokenSampleStreamFactory(Parameters.class)); } protected <P> ConllXTokenSampleStreamFactory(Class<P> params) { super(params); } public ObjectStream<TokenSample> create(String[] args) { Parameters params = ArgumentParser.parse(args, Parameters.class); ObjectStream<POSSample> samples = StreamFactoryRegistry.getFactory(POSSample.class, ConllXPOSSampleStreamFactory.CONLLX_FORMAT).create( ArgumentParser.filter(args, ConllXPOSSampleStreamFactory.Parameters.class)); return new POSToTokenSampleStream(createDetokenizer(params), samples); } }
0
java-sources/ai/idylnlp/idylnlp-opennlp-tools-1.8.3/1.1.0/opennlp/tools
java-sources/ai/idylnlp/idylnlp-opennlp-tools-1.8.3/1.1.0/opennlp/tools/formats/DetokenizerSampleStreamFactory.java
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package opennlp.tools.formats; import java.io.File; import java.io.FileInputStream; import java.io.IOException; import opennlp.tools.cmdline.TerminateToolException; import opennlp.tools.cmdline.params.DetokenizerParameter; import opennlp.tools.tokenize.DetokenizationDictionary; import opennlp.tools.tokenize.Detokenizer; import opennlp.tools.tokenize.DictionaryDetokenizer; /** * Base class for factories which need detokenizer. */ public abstract class DetokenizerSampleStreamFactory<T> extends AbstractSampleStreamFactory<T> { protected <P> DetokenizerSampleStreamFactory(Class<P> params) { super(params); } protected Detokenizer createDetokenizer(DetokenizerParameter p) { try { return new DictionaryDetokenizer(new DetokenizationDictionary( new FileInputStream(new File(p.getDetokenizer())))); } catch (IOException e) { throw new TerminateToolException(-1, "IO error while loading detokenizer dict: " + e.getMessage(), e); } } }
0
java-sources/ai/idylnlp/idylnlp-opennlp-tools-1.8.3/1.1.0/opennlp/tools
java-sources/ai/idylnlp/idylnlp-opennlp-tools-1.8.3/1.1.0/opennlp/tools/formats/DirectorySampleStream.java
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package opennlp.tools.formats; import java.io.File; import java.io.FileFilter; import java.io.IOException; import java.util.ArrayList; import java.util.Arrays; import java.util.Collections; import java.util.List; import java.util.Stack; import opennlp.tools.util.ObjectStream; /** * The directory sample stream allows for creating a stream * from a directory listing of files. */ public class DirectorySampleStream implements ObjectStream<File> { private final List<File> inputDirectories; private final boolean recursive; private final FileFilter fileFilter; private Stack<File> directories = new Stack<>(); private Stack<File> textFiles = new Stack<>(); /** * Creates a new directory sample stream. * @param dirs The directories to read. * @param fileFilter The {@link FileFilter filter} to apply while enumerating files. * @param recursive Enables or disables recursive file listing. */ public DirectorySampleStream(File[] dirs, FileFilter fileFilter, boolean recursive) { this.fileFilter = fileFilter; this.recursive = recursive; List<File> inputDirectoryList = new ArrayList<>(dirs.length); for (File dir : dirs) { if (!dir.isDirectory()) { throw new IllegalArgumentException( "All passed in directories must be directories, but \"" + dir.toString() + "\" is not!"); } inputDirectoryList.add(dir); } inputDirectories = Collections.unmodifiableList(inputDirectoryList); directories.addAll(inputDirectories); } /** * Creates a new directory sample stream. * @param dir The {@link File directory}. * @param fileFilter The {@link FileFilter filter} to apply while enumerating files. * @param recursive Enables or disables recursive file listing. */ public DirectorySampleStream(File dir, FileFilter fileFilter, boolean recursive) { this(new File[]{dir}, fileFilter, recursive); } @Override public File read() throws IOException { while (textFiles.isEmpty() && !directories.isEmpty()) { File dir = directories.pop(); File[] files; if (fileFilter != null) { files = dir.listFiles(fileFilter); } else { files = dir.listFiles(); } Arrays.sort(files); for (File file : files) { if (file.isFile()) { textFiles.push(file); } else if (recursive && file.isDirectory()) { directories.push(file); } } } if (!textFiles.isEmpty()) { return textFiles.pop(); } else { return null; } } @Override public void reset() { directories.clear(); textFiles.clear(); directories.addAll(inputDirectories); } /** * {@inheritDoc} * Calling this function has no effect on * the stream. */ @Override public void close() throws IOException { } }
0
java-sources/ai/idylnlp/idylnlp-opennlp-tools-1.8.3/1.1.0/opennlp/tools
java-sources/ai/idylnlp/idylnlp-opennlp-tools-1.8.3/1.1.0/opennlp/tools/formats/DocumentSampleStreamFactory.java
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package opennlp.tools.formats; import java.io.IOException; import opennlp.tools.cmdline.ArgumentParser; import opennlp.tools.cmdline.CmdLineUtil; import opennlp.tools.cmdline.StreamFactoryRegistry; import opennlp.tools.cmdline.params.BasicFormatParams; import opennlp.tools.doccat.DocumentSample; import opennlp.tools.doccat.DocumentSampleStream; import opennlp.tools.util.InputStreamFactory; import opennlp.tools.util.ObjectStream; import opennlp.tools.util.PlainTextByLineStream; /** * Factory producing OpenNLP {@link DocumentSampleStream}s. */ public class DocumentSampleStreamFactory extends AbstractSampleStreamFactory<DocumentSample> { interface Parameters extends BasicFormatParams { } public static void registerFactory() { StreamFactoryRegistry.registerFactory(DocumentSample.class, StreamFactoryRegistry.DEFAULT_FORMAT, new DocumentSampleStreamFactory(Parameters.class)); } protected <P> DocumentSampleStreamFactory(Class<P> params) { super(params); } public ObjectStream<DocumentSample> create(String[] args) { Parameters params = ArgumentParser.parse(args, Parameters.class); CmdLineUtil.checkInputFile("Data", params.getData()); InputStreamFactory sampleDataIn = CmdLineUtil.createInputStreamFactory(params.getData()); ObjectStream<String> lineStream = null; try { lineStream = new PlainTextByLineStream(sampleDataIn, params.getEncoding()); } catch (IOException ex) { CmdLineUtil.handleCreateObjectStreamError(ex); } return new DocumentSampleStream(lineStream); } }
0
java-sources/ai/idylnlp/idylnlp-opennlp-tools-1.8.3/1.1.0/opennlp/tools
java-sources/ai/idylnlp/idylnlp-opennlp-tools-1.8.3/1.1.0/opennlp/tools/formats/EvalitaNameSampleStream.java
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package opennlp.tools.formats; import java.io.IOException; import java.io.PrintStream; import java.io.UnsupportedEncodingException; import java.nio.charset.StandardCharsets; import java.util.ArrayList; import java.util.List; import opennlp.tools.namefind.NameSample; import opennlp.tools.util.InputStreamFactory; import opennlp.tools.util.InvalidFormatException; import opennlp.tools.util.ObjectStream; import opennlp.tools.util.PlainTextByLineStream; import opennlp.tools.util.Span; import opennlp.tools.util.StringUtil; /** * Parser for the Italian NER training files of the Evalita 2007 and 2009 NER shared tasks. * <p> * The data does not contain article boundaries, * adaptive data will be cleared for every sentence. * <p> * Named Entities are annotated in the IOB2 format (as used in CoNLL 2002 shared task) * <p> * The Named Entity tag consists of two parts: * 1. The IOB2 tag: 'B' (for 'begin') denotes the first token of a * Named Entity, I (for 'inside') is used for all other tokens in a * Named Entity, and 'O' (for 'outside') is used for all other words; * 2. The Entity type tag: PER (for Person), ORG (for Organization), * GPE (for Geo-Political Entity), or LOC (for Location). * <p> * Each file consists of four columns separated by a blank, containing * respectively the token, the Elsnet PoS-tag, the Adige news story to * which the token belongs, and the Named Entity tag. * <p> * Data can be found on this web site:<br> * http://www.evalita.it * <p> * <b>Note:</b> Do not use this class, internal use only! */ public class EvalitaNameSampleStream implements ObjectStream<NameSample> { public enum LANGUAGE { IT } public static final int GENERATE_PERSON_ENTITIES = 0x01; public static final int GENERATE_ORGANIZATION_ENTITIES = 0x01 << 1; public static final int GENERATE_LOCATION_ENTITIES = 0x01 << 2; public static final int GENERATE_GPE_ENTITIES = 0x01 << 3; public static final String DOCSTART = "-DOCSTART-"; private final LANGUAGE lang; private final ObjectStream<String> lineStream; private final int types; public EvalitaNameSampleStream(LANGUAGE lang, ObjectStream<String> lineStream, int types) { this.lang = lang; this.lineStream = lineStream; this.types = types; } public EvalitaNameSampleStream(LANGUAGE lang, InputStreamFactory in, int types) throws IOException { this.lang = lang; try { this.lineStream = new PlainTextByLineStream(in, StandardCharsets.UTF_8); System.setOut(new PrintStream(System.out, true, "UTF-8")); } catch (UnsupportedEncodingException e) { // UTF-8 is available on all JVMs, will never happen throw new IllegalStateException(e); } this.types = types; } private static Span extract(int begin, int end, String beginTag) throws InvalidFormatException { String type = beginTag.substring(2); if ("PER".equals(type)) { type = "person"; } else if ("LOC".equals(type)) { type = "location"; } else if ("GPE".equals(type)) { type = "gpe"; } else if ("ORG".equals(type)) { type = "organization"; } else { throw new InvalidFormatException("Unknown type: " + type); } return new Span(begin, end, type); } public NameSample read() throws IOException { List<String> sentence = new ArrayList<>(); List<String> tags = new ArrayList<>(); boolean isClearAdaptiveData = false; // Empty line indicates end of sentence String line; while ((line = lineStream.read()) != null && !StringUtil.isEmpty(line)) { if (line.startsWith(DOCSTART)) { isClearAdaptiveData = true; String emptyLine = lineStream.read(); if (!StringUtil.isEmpty(emptyLine)) throw new IOException("Empty line after -DOCSTART- not empty: '" + emptyLine + "'!"); continue; } String[] fields = line.split(" "); // For Italian: WORD POS-TAG SC-TAG NE-TAG if (LANGUAGE.IT.equals(lang) && fields.length == 4) { sentence.add(fields[0]); tags.add(fields[3]); // 3 is NE-TAG } else { throw new IOException("Incorrect number of fields per line for language: '" + line + "'!"); } } // Always clear adaptive data for Italian if (LANGUAGE.IT.equals(lang)) isClearAdaptiveData = true; if (sentence.size() > 0) { // convert name tags into spans List<Span> names = new ArrayList<>(); int beginIndex = -1; int endIndex = -1; for (int i = 0; i < tags.size(); i++) { String tag = tags.get(i); if (tag.endsWith("PER") && (types & GENERATE_PERSON_ENTITIES) == 0) tag = "O"; if (tag.endsWith("ORG") && (types & GENERATE_ORGANIZATION_ENTITIES) == 0) tag = "O"; if (tag.endsWith("LOC") && (types & GENERATE_LOCATION_ENTITIES) == 0) tag = "O"; if (tag.endsWith("GPE") && (types & GENERATE_GPE_ENTITIES) == 0) tag = "O"; if (tag.startsWith("B-")) { if (beginIndex != -1) { names.add(extract(beginIndex, endIndex, tags.get(beginIndex))); beginIndex = -1; endIndex = -1; } beginIndex = i; endIndex = i + 1; } else if (tag.startsWith("I-")) { endIndex++; } else if (tag.equals("O")) { if (beginIndex != -1) { names.add(extract(beginIndex, endIndex, tags.get(beginIndex))); beginIndex = -1; endIndex = -1; } } else { throw new IOException("Invalid tag: " + tag); } } // if one span remains, create it here if (beginIndex != -1) names.add(extract(beginIndex, endIndex, tags.get(beginIndex))); return new NameSample(sentence.toArray(new String[sentence.size()]), names.toArray(new Span[names.size()]), isClearAdaptiveData); } else if (line != null) { // Just filter out empty events, if two lines in a row are empty return read(); } else { // source stream is not returning anymore lines return null; } } public void reset() throws IOException, UnsupportedOperationException { lineStream.reset(); } public void close() throws IOException { lineStream.close(); } }
0
java-sources/ai/idylnlp/idylnlp-opennlp-tools-1.8.3/1.1.0/opennlp/tools
java-sources/ai/idylnlp/idylnlp-opennlp-tools-1.8.3/1.1.0/opennlp/tools/formats/EvalitaNameSampleStreamFactory.java
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package opennlp.tools.formats; import java.io.IOException; import opennlp.tools.cmdline.ArgumentParser; import opennlp.tools.cmdline.ArgumentParser.ParameterDescription; import opennlp.tools.cmdline.CmdLineUtil; import opennlp.tools.cmdline.StreamFactoryRegistry; import opennlp.tools.cmdline.TerminateToolException; import opennlp.tools.cmdline.params.BasicFormatParams; import opennlp.tools.formats.EvalitaNameSampleStream.LANGUAGE; import opennlp.tools.namefind.NameSample; import opennlp.tools.util.ObjectStream; /** * <b>Note:</b> Do not use this class, internal use only! */ public class EvalitaNameSampleStreamFactory extends LanguageSampleStreamFactory<NameSample> { interface Parameters extends BasicFormatParams { @ParameterDescription(valueName = "it") String getLang(); @ParameterDescription(valueName = "per,loc,org,gpe") String getTypes(); } public static void registerFactory() { StreamFactoryRegistry.registerFactory(NameSample.class, "evalita", new EvalitaNameSampleStreamFactory(Parameters.class)); } protected <P> EvalitaNameSampleStreamFactory(Class<P> params) { super(params); } public ObjectStream<NameSample> create(String[] args) { Parameters params = ArgumentParser.parse(args, Parameters.class); LANGUAGE lang; if ("it".equals(params.getLang())) { lang = LANGUAGE.IT; language = params.getLang(); } else { throw new TerminateToolException(1, "Unsupported language: " + params.getLang()); } int typesToGenerate = 0; if (params.getTypes().contains("per")) { typesToGenerate = typesToGenerate | EvalitaNameSampleStream.GENERATE_PERSON_ENTITIES; } if (params.getTypes().contains("org")) { typesToGenerate = typesToGenerate | EvalitaNameSampleStream.GENERATE_ORGANIZATION_ENTITIES; } if (params.getTypes().contains("loc")) { typesToGenerate = typesToGenerate | EvalitaNameSampleStream.GENERATE_LOCATION_ENTITIES; } if (params.getTypes().contains("gpe")) { typesToGenerate = typesToGenerate | EvalitaNameSampleStream.GENERATE_GPE_ENTITIES; } try { return new EvalitaNameSampleStream(lang, CmdLineUtil.createInputStreamFactory(params.getData()), typesToGenerate); } catch (IOException e) { throw CmdLineUtil.createObjectStreamError(e); } } }
0
java-sources/ai/idylnlp/idylnlp-opennlp-tools-1.8.3/1.1.0/opennlp/tools
java-sources/ai/idylnlp/idylnlp-opennlp-tools-1.8.3/1.1.0/opennlp/tools/formats/LanguageDetectorSampleStreamFactory.java
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package opennlp.tools.formats; import java.io.IOException; import opennlp.tools.cmdline.ArgumentParser; import opennlp.tools.cmdline.CmdLineUtil; import opennlp.tools.cmdline.StreamFactoryRegistry; import opennlp.tools.cmdline.params.BasicFormatParams; import opennlp.tools.doccat.DocumentSampleStream; import opennlp.tools.langdetect.LanguageDetectorSampleStream; import opennlp.tools.langdetect.LanguageSample; import opennlp.tools.util.InputStreamFactory; import opennlp.tools.util.ObjectStream; import opennlp.tools.util.PlainTextByLineStream; /** * Factory producing OpenNLP {@link DocumentSampleStream}s. */ public class LanguageDetectorSampleStreamFactory extends AbstractSampleStreamFactory<LanguageSample> { interface Parameters extends BasicFormatParams { } public static void registerFactory() { StreamFactoryRegistry.registerFactory(LanguageSample.class, StreamFactoryRegistry.DEFAULT_FORMAT, new LanguageDetectorSampleStreamFactory(Parameters.class)); } protected <P> LanguageDetectorSampleStreamFactory(Class<P> params) { super(params); } public ObjectStream<LanguageSample> create(String[] args) { Parameters params = ArgumentParser.parse(args, Parameters.class); CmdLineUtil.checkInputFile("Data", params.getData()); InputStreamFactory sampleDataIn = CmdLineUtil.createInputStreamFactory(params.getData()); ObjectStream<String> lineStream = null; try { lineStream = new PlainTextByLineStream(sampleDataIn, params.getEncoding()); } catch (IOException ex) { CmdLineUtil.handleCreateObjectStreamError(ex); } return new LanguageDetectorSampleStream(lineStream); } }
0
java-sources/ai/idylnlp/idylnlp-opennlp-tools-1.8.3/1.1.0/opennlp/tools
java-sources/ai/idylnlp/idylnlp-opennlp-tools-1.8.3/1.1.0/opennlp/tools/formats/LanguageSampleStreamFactory.java
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package opennlp.tools.formats; /** * Stream factory for those streams which carry language. */ public abstract class LanguageSampleStreamFactory<T> extends AbstractSampleStreamFactory<T> { protected String language; protected <P> LanguageSampleStreamFactory(Class<P> params) { super(params); } @Override public String getLang() { return language; } }
0
java-sources/ai/idylnlp/idylnlp-opennlp-tools-1.8.3/1.1.0/opennlp/tools
java-sources/ai/idylnlp/idylnlp-opennlp-tools-1.8.3/1.1.0/opennlp/tools/formats/LeipzigDoccatSampleStream.java
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package opennlp.tools.formats; import java.io.IOException; import java.io.PrintStream; import java.nio.charset.StandardCharsets; import java.util.ArrayList; import java.util.Arrays; import java.util.List; import opennlp.tools.doccat.DocumentSample; import opennlp.tools.tokenize.SimpleTokenizer; import opennlp.tools.tokenize.Tokenizer; import opennlp.tools.util.FilterObjectStream; import opennlp.tools.util.InputStreamFactory; import opennlp.tools.util.PlainTextByLineStream; /** * Stream filter to produce document samples out of a Leipzig sentences.txt file. * In the Leipzig corpus the encoding of the various sentences.txt file is defined by * the language. The language must be specified to produce the category tags and is used * to determine the correct input encoding. * <p> * The input text is tokenized with the {@link SimpleTokenizer}. The input text classified * by the language model must also be tokenized by the {@link SimpleTokenizer} to produce * exactly the same tokenization during testing and training. * * @deprecated will be removed, use the language detector instead */ @Deprecated public class LeipzigDoccatSampleStream extends FilterObjectStream<String, DocumentSample> { private final Tokenizer tokenizer; private final String language; private final int sentencesPerDocument; /** * Creates a new LeipzigDoccatSampleStream with the specified parameters. * * @param language the Leipzig input sentences.txt file * @param sentencesPerDocument the number of sentences which * should be grouped into once {@link DocumentSample} * @param in the InputStream pointing to the contents of the sentences.txt input file * @throws IOException IOException */ public LeipzigDoccatSampleStream(String language, int sentencesPerDocument, Tokenizer tokenizer, InputStreamFactory in) throws IOException { super(new PlainTextByLineStream(in, StandardCharsets.UTF_8)); System.setOut(new PrintStream(System.out, true, "UTF-8")); this.language = language; this.sentencesPerDocument = sentencesPerDocument; this.tokenizer = tokenizer; } /** * Creates a new LeipzigDoccatSampleStream with the specified parameters. * * @param language the Leipzig input sentences.txt file * @param sentencesPerDocument the number of sentences which should be * grouped into once {@link DocumentSample} * @param in the InputStream pointing to the contents of the sentences.txt input file * @throws IOException IOException */ public LeipzigDoccatSampleStream(String language, int sentencesPerDocument, InputStreamFactory in) throws IOException { this(language, sentencesPerDocument, SimpleTokenizer.INSTANCE, in); } public DocumentSample read() throws IOException { int count = 0; List<String> tokensList = new ArrayList<>(); String line; while (count < sentencesPerDocument && (line = samples.read()) != null) { String[] tokens = tokenizer.tokenize(line); if (tokens.length == 0) { throw new IOException("Empty lines are not allowed!"); } // Always skip first token, that is the sentence number! tokensList.addAll(Arrays.asList(tokens).subList(1, tokens.length)); count++; } if (tokensList.size() > 0) { return new DocumentSample(language, tokensList.toArray(new String[tokensList.size()])); } return null; } }
0
java-sources/ai/idylnlp/idylnlp-opennlp-tools-1.8.3/1.1.0/opennlp/tools
java-sources/ai/idylnlp/idylnlp-opennlp-tools-1.8.3/1.1.0/opennlp/tools/formats/LeipzigDocumentSampleStreamFactory.java
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package opennlp.tools.formats; import java.io.File; import java.io.FilenameFilter; import java.io.IOException; import opennlp.tools.cmdline.ArgumentParser; import opennlp.tools.cmdline.ArgumentParser.ParameterDescription; import opennlp.tools.cmdline.CmdLineUtil; import opennlp.tools.cmdline.StreamFactoryRegistry; import opennlp.tools.cmdline.TerminateToolException; import opennlp.tools.cmdline.params.EncodingParameter; import opennlp.tools.doccat.DocumentSample; import opennlp.tools.util.ObjectStream; import opennlp.tools.util.ObjectStreamUtils; /** * <b>Note:</b> Do not use this class, internal use only! * * @deprecated will be removed, use the language detector instead */ @Deprecated public class LeipzigDocumentSampleStreamFactory extends AbstractSampleStreamFactory<DocumentSample> { protected <P> LeipzigDocumentSampleStreamFactory(Class<P> params) { super(params); } public static void registerFactory() { StreamFactoryRegistry.registerFactory(DocumentSample.class, "leipzig", new LeipzigDocumentSampleStreamFactory(Parameters.class)); } public ObjectStream<DocumentSample> create(String[] args) { Parameters params = ArgumentParser.parse(args, Parameters.class); File sentencesFileDir = params.getSentencesDir(); File[] sentencesFiles = sentencesFileDir.listFiles(new FilenameFilter() { @Override public boolean accept(File dir, String name) { return name.contains("sentences") && name.endsWith(".txt"); } }); @SuppressWarnings("unchecked") ObjectStream<DocumentSample>[] sampleStreams = new ObjectStream[sentencesFiles.length]; for (int i = 0; i < sentencesFiles.length; i++) { try { sampleStreams[i] = new LeipzigDoccatSampleStream( sentencesFiles[i].getName().substring(0, 3), 20, CmdLineUtil.createInputStreamFactory(sentencesFiles[i])); } catch (IOException e) { throw new TerminateToolException(-1, "IO error while opening sample data: " + e.getMessage(), e); } } return ObjectStreamUtils.concatenateObjectStream(sampleStreams); } interface Parameters extends EncodingParameter { @ParameterDescription(valueName = "sentencesDir", description = "dir with Leipig sentences to be used") File getSentencesDir(); } }
0
java-sources/ai/idylnlp/idylnlp-opennlp-tools-1.8.3/1.1.0/opennlp/tools
java-sources/ai/idylnlp/idylnlp-opennlp-tools-1.8.3/1.1.0/opennlp/tools/formats/LemmatizerSampleStreamFactory.java
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package opennlp.tools.formats; import java.io.IOException; import opennlp.tools.cmdline.ArgumentParser; import opennlp.tools.cmdline.CmdLineUtil; import opennlp.tools.cmdline.StreamFactoryRegistry; import opennlp.tools.cmdline.params.BasicFormatParams; import opennlp.tools.lemmatizer.LemmaSample; import opennlp.tools.lemmatizer.LemmaSampleStream; import opennlp.tools.util.InputStreamFactory; import opennlp.tools.util.ObjectStream; import opennlp.tools.util.PlainTextByLineStream; /** * Factory producing OpenNLP {@link LemmaSampleStream}s. */ public class LemmatizerSampleStreamFactory extends AbstractSampleStreamFactory<LemmaSample> { interface Parameters extends BasicFormatParams { } public static void registerFactory() { StreamFactoryRegistry.registerFactory(LemmaSample.class, StreamFactoryRegistry.DEFAULT_FORMAT, new LemmatizerSampleStreamFactory(Parameters.class)); } protected <P> LemmatizerSampleStreamFactory(Class<P> params) { super(params); } public ObjectStream<LemmaSample> create(String[] args) { Parameters params = ArgumentParser.parse(args, Parameters.class); CmdLineUtil.checkInputFile("Data", params.getData()); InputStreamFactory sampleDataIn = CmdLineUtil.createInputStreamFactory(params.getData()); ObjectStream<String> lineStream = null; try { lineStream = new PlainTextByLineStream(sampleDataIn, params.getEncoding()); } catch (IOException ex) { CmdLineUtil.handleCreateObjectStreamError(ex); } return new LemmaSampleStream(lineStream); } }
0
java-sources/ai/idylnlp/idylnlp-opennlp-tools-1.8.3/1.1.0/opennlp/tools
java-sources/ai/idylnlp/idylnlp-opennlp-tools-1.8.3/1.1.0/opennlp/tools/formats/NameFinderCensus90NameStream.java
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package opennlp.tools.formats; import java.io.IOException; import java.nio.charset.Charset; import java.util.Locale; import opennlp.tools.util.InputStreamFactory; import opennlp.tools.util.ObjectStream; import opennlp.tools.util.PlainTextByLineStream; import opennlp.tools.util.StringList; import opennlp.tools.util.StringUtil; /** * This class helps to read the US Census data from the files to build a * StringList for each dictionary entry in the name-finder dictionary. * The entries in the source file are as follows: * <p> * SMITH 1.006 1.006 1 * <ul> * <li>The first field is the name (in ALL CAPS). * <li>The next field is a frequency in percent. * <li>The next is a cumulative frequency in percent. * <li>The last is a ranking. * </ul> * <p> * <b>Note:</b> Do not use this class, internal use only! */ public class NameFinderCensus90NameStream implements ObjectStream<StringList> { private final Locale locale; private final Charset encoding; private final ObjectStream<String> lineStream; /** * This constructor takes an ObjectStream and initializes the class to handle * the stream. * * @param lineStream an <code>ObjectSteam&lt;String&gt;</code> that represents the * input file to be attached to this class. */ public NameFinderCensus90NameStream(ObjectStream<String> lineStream) { this.locale = new Locale("en"); // locale is English this.encoding = Charset.defaultCharset(); // todo how do we find the encoding for an already open ObjectStream() ? this.lineStream = lineStream; } /** * This constructor takes an <code>InputStream</code> and a <code>Charset</code> * and opens an associated stream object with the specified encoding specified. * * @param in an <code>InputStreamFactory</code> for the input file. * @param encoding the <code>Charset</code> to apply to the input stream. * @throws IOException */ public NameFinderCensus90NameStream(InputStreamFactory in, Charset encoding) throws IOException { this.locale = new Locale("en"); // locale is English this.encoding = encoding; this.lineStream = new PlainTextByLineStream(in, this.encoding); } public StringList read() throws IOException { String line = lineStream.read(); StringList name = null; if ((line != null) && (!StringUtil.isEmpty(line))) { String name2; // find the location of the name separator in the line of data. int pos = line.indexOf(' '); if ((pos != -1)) { String parsed = line.substring(0, pos); // the data is in ALL CAPS ... so the easiest way is to convert // back to standard mixed case. if ((parsed.length() > 2) && (parsed.startsWith("MC"))) { name2 = parsed.substring(0,1).toUpperCase(locale) + parsed.substring(1,2).toLowerCase(locale) + parsed.substring(2,3).toUpperCase(locale) + parsed.substring(3).toLowerCase(locale); } else { name2 = parsed.substring(0,1).toUpperCase(locale) + parsed.substring(1).toLowerCase(locale); } name = new StringList(new String[]{name2}); } } return name; } public void reset() throws IOException, UnsupportedOperationException { lineStream.reset(); } public void close() throws IOException { lineStream.close(); } }
0
java-sources/ai/idylnlp/idylnlp-opennlp-tools-1.8.3/1.1.0/opennlp/tools
java-sources/ai/idylnlp/idylnlp-opennlp-tools-1.8.3/1.1.0/opennlp/tools/formats/NameSampleDataStreamFactory.java
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package opennlp.tools.formats; import java.io.IOException; import opennlp.tools.cmdline.ArgumentParser; import opennlp.tools.cmdline.CmdLineUtil; import opennlp.tools.cmdline.StreamFactoryRegistry; import opennlp.tools.cmdline.params.BasicFormatParams; import opennlp.tools.namefind.NameSample; import opennlp.tools.namefind.NameSampleDataStream; import opennlp.tools.util.InputStreamFactory; import opennlp.tools.util.ObjectStream; import opennlp.tools.util.PlainTextByLineStream; /** * Factory producing OpenNLP {@link NameSampleDataStream}s. */ public class NameSampleDataStreamFactory extends AbstractSampleStreamFactory<NameSample> { public static interface Parameters extends BasicFormatParams { } public static void registerFactory() { StreamFactoryRegistry.registerFactory(NameSample.class, StreamFactoryRegistry.DEFAULT_FORMAT, new NameSampleDataStreamFactory(Parameters.class)); } protected <P> NameSampleDataStreamFactory(Class<P> params) { super(params); } public ObjectStream<NameSample> create(String[] args) { Parameters params = ArgumentParser.parse(args, Parameters.class); CmdLineUtil.checkInputFile("Data", params.getData()); InputStreamFactory sampleDataIn = CmdLineUtil.createInputStreamFactory(params.getData()); ObjectStream<String> lineStream = null; try { lineStream = new PlainTextByLineStream(sampleDataIn, params.getEncoding()); } catch (IOException ex) { CmdLineUtil.handleCreateObjectStreamError(ex); } return new NameSampleDataStream(lineStream); } }
0
java-sources/ai/idylnlp/idylnlp-opennlp-tools-1.8.3/1.1.0/opennlp/tools
java-sources/ai/idylnlp/idylnlp-opennlp-tools-1.8.3/1.1.0/opennlp/tools/formats/ParseSampleStreamFactory.java
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package opennlp.tools.formats; import java.io.IOException; import opennlp.tools.cmdline.ArgumentParser; import opennlp.tools.cmdline.CmdLineUtil; import opennlp.tools.cmdline.StreamFactoryRegistry; import opennlp.tools.cmdline.params.BasicFormatParams; import opennlp.tools.parser.Parse; import opennlp.tools.parser.ParseSampleStream; import opennlp.tools.util.InputStreamFactory; import opennlp.tools.util.ObjectStream; import opennlp.tools.util.PlainTextByLineStream; /** * Factory producing OpenNLP {@link ParseSampleStream}s. */ public class ParseSampleStreamFactory extends AbstractSampleStreamFactory<Parse> { public interface Parameters extends BasicFormatParams { } public static void registerFactory() { StreamFactoryRegistry.registerFactory(Parse.class, StreamFactoryRegistry.DEFAULT_FORMAT, new ParseSampleStreamFactory(Parameters.class)); } protected <P> ParseSampleStreamFactory(Class<P> params) { super(params); } public ObjectStream<Parse> create(String[] args) { Parameters params = ArgumentParser.parse(args, Parameters.class); CmdLineUtil.checkInputFile("Data", params.getData()); InputStreamFactory sampleDataIn = CmdLineUtil.createInputStreamFactory(params.getData()); ObjectStream<String> lineStream = null; try { lineStream = new PlainTextByLineStream(sampleDataIn, params.getEncoding()); } catch (IOException ex) { CmdLineUtil.handleCreateObjectStreamError(ex); } return new ParseSampleStream(lineStream); } }
0
java-sources/ai/idylnlp/idylnlp-opennlp-tools-1.8.3/1.1.0/opennlp/tools
java-sources/ai/idylnlp/idylnlp-opennlp-tools-1.8.3/1.1.0/opennlp/tools/formats/SentenceSampleStreamFactory.java
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package opennlp.tools.formats; import java.io.IOException; import opennlp.tools.cmdline.ArgumentParser; import opennlp.tools.cmdline.CmdLineUtil; import opennlp.tools.cmdline.StreamFactoryRegistry; import opennlp.tools.cmdline.params.BasicFormatParams; import opennlp.tools.sentdetect.SentenceSample; import opennlp.tools.sentdetect.SentenceSampleStream; import opennlp.tools.util.InputStreamFactory; import opennlp.tools.util.ObjectStream; import opennlp.tools.util.PlainTextByLineStream; /** * Factory producing OpenNLP {@link SentenceSampleStream}s. */ public class SentenceSampleStreamFactory extends AbstractSampleStreamFactory<SentenceSample> { interface Parameters extends BasicFormatParams { } public static void registerFactory() { StreamFactoryRegistry.registerFactory(SentenceSample.class, StreamFactoryRegistry.DEFAULT_FORMAT, new SentenceSampleStreamFactory(Parameters.class)); } protected <P> SentenceSampleStreamFactory(Class<P> params) { super(params); } public ObjectStream<SentenceSample> create(String[] args) { Parameters params = ArgumentParser.parse(args, Parameters.class); CmdLineUtil.checkInputFile("Data", params.getData()); InputStreamFactory sampleDataIn = CmdLineUtil.createInputStreamFactory(params.getData()); ObjectStream<String> lineStream = null; try { lineStream = new PlainTextByLineStream(sampleDataIn, params.getEncoding()); } catch (IOException ex) { CmdLineUtil.handleCreateObjectStreamError(ex); } return new SentenceSampleStream(lineStream); } }
0
java-sources/ai/idylnlp/idylnlp-opennlp-tools-1.8.3/1.1.0/opennlp/tools
java-sources/ai/idylnlp/idylnlp-opennlp-tools-1.8.3/1.1.0/opennlp/tools/formats/TokenSampleStreamFactory.java
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package opennlp.tools.formats; import java.io.IOException; import opennlp.tools.cmdline.ArgumentParser; import opennlp.tools.cmdline.CmdLineUtil; import opennlp.tools.cmdline.StreamFactoryRegistry; import opennlp.tools.cmdline.params.BasicFormatParams; import opennlp.tools.tokenize.TokenSample; import opennlp.tools.tokenize.TokenSampleStream; import opennlp.tools.util.InputStreamFactory; import opennlp.tools.util.ObjectStream; import opennlp.tools.util.PlainTextByLineStream; /** * Factory producing OpenNLP {@link TokenSampleStream}s. */ public class TokenSampleStreamFactory extends LanguageSampleStreamFactory<TokenSample> { interface Parameters extends BasicFormatParams { } public static void registerFactory() { StreamFactoryRegistry.registerFactory(TokenSample.class, StreamFactoryRegistry.DEFAULT_FORMAT, new TokenSampleStreamFactory(Parameters.class)); } protected <P> TokenSampleStreamFactory(Class<P> params) { super(params); } public ObjectStream<TokenSample> create(String[] args) { Parameters params = ArgumentParser.parse(args, Parameters.class); CmdLineUtil.checkInputFile("Data", params.getData()); InputStreamFactory sampleDataIn = CmdLineUtil.createInputStreamFactory(params.getData()); ObjectStream<String> lineStream = null; try { lineStream = new PlainTextByLineStream(sampleDataIn, params.getEncoding()); } catch (IOException ex) { CmdLineUtil.handleCreateObjectStreamError(ex); } return new TokenSampleStream(lineStream); } }
0
java-sources/ai/idylnlp/idylnlp-opennlp-tools-1.8.3/1.1.0/opennlp/tools
java-sources/ai/idylnlp/idylnlp-opennlp-tools-1.8.3/1.1.0/opennlp/tools/formats/WordTagSampleStreamFactory.java
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package opennlp.tools.formats; import java.io.IOException; import opennlp.tools.cmdline.ArgumentParser; import opennlp.tools.cmdline.CmdLineUtil; import opennlp.tools.cmdline.StreamFactoryRegistry; import opennlp.tools.cmdline.params.BasicFormatParams; import opennlp.tools.postag.POSSample; import opennlp.tools.postag.WordTagSampleStream; import opennlp.tools.util.InputStreamFactory; import opennlp.tools.util.ObjectStream; import opennlp.tools.util.PlainTextByLineStream; /** * <b>Note:</b> Do not use this class, internal use only! */ public class WordTagSampleStreamFactory extends AbstractSampleStreamFactory<POSSample> { public static interface Parameters extends BasicFormatParams { } public static void registerFactory() { StreamFactoryRegistry.registerFactory(POSSample.class, StreamFactoryRegistry.DEFAULT_FORMAT, new WordTagSampleStreamFactory(Parameters.class)); } protected <P> WordTagSampleStreamFactory(Class<P> params) { super(params); } public ObjectStream<POSSample> create(String[] args) { Parameters params = ArgumentParser.parse(args, Parameters.class); CmdLineUtil.checkInputFile("Data", params.getData()); InputStreamFactory sampleDataIn = CmdLineUtil.createInputStreamFactory(params.getData()); ObjectStream<String> lineStream = null; try { lineStream = new PlainTextByLineStream(sampleDataIn, params.getEncoding()); } catch (IOException ex) { CmdLineUtil.handleCreateObjectStreamError(ex); } return new WordTagSampleStream(lineStream); } }
0
java-sources/ai/idylnlp/idylnlp-opennlp-tools-1.8.3/1.1.0/opennlp/tools
java-sources/ai/idylnlp/idylnlp-opennlp-tools-1.8.3/1.1.0/opennlp/tools/formats/package-info.java
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ /** * Experimental package related to converting various corpora to OpenNLP Format. */ package opennlp.tools.formats;