You are viewing a plain text version of this content. The canonical link for it is here.
Posted to commits@opennlp.apache.org by jo...@apache.org on 2010/12/15 00:59:04 UTC
svn commit: r1049347 [3/5] - in
/incubator/opennlp/tags/asf_migration/opennlp-uima/trunk: ./ descriptors/
docs/ metadata/ src/ src/main/ src/main/assembly/ src/main/java/
src/main/java/opennlp/ src/main/java/opennlp/uima/
src/main/java/opennlp/uima/chu...
Added: incubator/opennlp/tags/asf_migration/opennlp-uima/trunk/src/main/java/opennlp/uima/doccat/DocumentCategorizerTrainer.java
URL: http://svn.apache.org/viewvc/incubator/opennlp/tags/asf_migration/opennlp-uima/trunk/src/main/java/opennlp/uima/doccat/DocumentCategorizerTrainer.java?rev=1049347&view=auto
==============================================================================
--- incubator/opennlp/tags/asf_migration/opennlp-uima/trunk/src/main/java/opennlp/uima/doccat/DocumentCategorizerTrainer.java (added)
+++ incubator/opennlp/tags/asf_migration/opennlp-uima/trunk/src/main/java/opennlp/uima/doccat/DocumentCategorizerTrainer.java Tue Dec 14 23:59:00 2010
@@ -0,0 +1,155 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one or more
+ * contributor license agreemnets. 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.uima.doccat;
+
+import java.io.File;
+import java.io.IOException;
+import java.util.List;
+
+import opennlp.maxent.GIS;
+import opennlp.tools.doccat.DoccatModel;
+import opennlp.tools.doccat.DocumentCategorizerME;
+import opennlp.tools.doccat.DocumentSample;
+import opennlp.tools.util.ObjectStreamUtils;
+import opennlp.uima.util.CasConsumerUtil;
+import opennlp.uima.util.OpennlpUtil;
+import opennlp.uima.util.UimaUtil;
+
+import org.apache.uima.UimaContext;
+import org.apache.uima.cas.CAS;
+import org.apache.uima.cas.FSIndex;
+import org.apache.uima.cas.Feature;
+import org.apache.uima.cas.Type;
+import org.apache.uima.cas.TypeSystem;
+import org.apache.uima.cas.text.AnnotationFS;
+import org.apache.uima.collection.CasConsumer_ImplBase;
+import org.apache.uima.resource.ResourceInitializationException;
+import org.apache.uima.resource.ResourceProcessException;
+import org.apache.uima.util.Level;
+import org.apache.uima.util.Logger;
+import org.apache.uima.util.ProcessTrace;
+
+/**
+ * OpenNLP NameFinder trainer.
+ *
+ * Mandatory parameters:
+ *
+ */
+public class DocumentCategorizerTrainer extends CasConsumer_ImplBase {
+
+ private UimaContext mContext;
+
+ private Logger mLogger;
+
+ private String mModelName;
+
+ private List<DocumentSample> documentSamples;
+
+ private Type mTokenType;
+
+ private Type mCategoryType;
+
+ private Feature mCategoryFeature;
+
+ private String language;
+
+ public void initialize() throws ResourceInitializationException {
+
+ super.initialize();
+
+ mContext = getUimaContext();
+
+ mLogger = mContext.getLogger();
+
+ if (mLogger.isLoggable(Level.INFO)) {
+ mLogger.log(Level.INFO, "Initializing the OpenNLP Doccat Trainer.");
+ }
+
+ mModelName = CasConsumerUtil.getRequiredStringParameter(mContext,
+ UimaUtil.MODEL_PARAMETER);
+
+ language = CasConsumerUtil.getRequiredStringParameter(mContext,
+ UimaUtil.LANGUAGE_PARAMETER);
+ }
+
+ public void typeSystemInit(TypeSystem typeSystem)
+ throws ResourceInitializationException {
+
+ String tokenTypeName = CasConsumerUtil.getRequiredStringParameter(mContext,
+ UimaUtil.SENTENCE_TYPE_PARAMETER);
+
+ mTokenType = CasConsumerUtil.getType(typeSystem, tokenTypeName);
+
+ String categoryTypeName = CasConsumerUtil.getRequiredStringParameter(mContext,
+ "opennlp.uima.doccat.CategoryType");
+
+ mCategoryType = CasConsumerUtil.getType(typeSystem, categoryTypeName);
+
+ // get feature name
+ String categoryFeatureName = CasConsumerUtil.getRequiredStringParameter(mContext,
+ "opennlp.uima.doccat.CategoryFeature");
+
+ mCategoryFeature = mCategoryType.getFeatureByBaseName(categoryFeatureName);
+ }
+
+ public void processCas(CAS cas) throws ResourceProcessException {
+
+ FSIndex categoryIndex = cas.getAnnotationIndex(mCategoryType);
+
+ if (categoryIndex.size() > 0) {
+ AnnotationFS categoryAnnotation =
+ (AnnotationFS) categoryIndex.iterator().next();
+
+ // add to event collection
+
+ DocumentSample sample = new DocumentSample(
+ categoryAnnotation.getStringValue(mCategoryFeature),
+ cas.getDocumentText());
+
+ documentSamples.add(sample);
+ }
+ }
+
+ public void collectionProcessComplete(ProcessTrace trace)
+ throws ResourceProcessException, IOException {
+
+ GIS.PRINT_MESSAGES = false;
+
+ DoccatModel categoryModel = DocumentCategorizerME.train(language, ObjectStreamUtils.createObjectStream(documentSamples));
+
+ File modelFile = new File(getUimaContextAdmin().getResourceManager()
+ .getDataPath() + File.separatorChar + mModelName);
+
+ OpennlpUtil.serialize(categoryModel, modelFile);
+ }
+
+ /**
+ * The trainer is not stateless.
+ */
+ public boolean isStateless() {
+ return false;
+ }
+
+ /**
+ * Destroys the current instance.
+ */
+ public void destroy() {
+ // dereference to allow garbage collection
+ documentSamples = null;
+ }
+}
\ No newline at end of file
Added: incubator/opennlp/tags/asf_migration/opennlp-uima/trunk/src/main/java/opennlp/uima/namefind/.cvsignore
URL: http://svn.apache.org/viewvc/incubator/opennlp/tags/asf_migration/opennlp-uima/trunk/src/main/java/opennlp/uima/namefind/.cvsignore?rev=1049347&view=auto
==============================================================================
--- incubator/opennlp/tags/asf_migration/opennlp-uima/trunk/src/main/java/opennlp/uima/namefind/.cvsignore (added)
+++ incubator/opennlp/tags/asf_migration/opennlp-uima/trunk/src/main/java/opennlp/uima/namefind/.cvsignore Tue Dec 14 23:59:00 2010
@@ -0,0 +1 @@
+CharacterNgramFeatureGenerator.java
Added: incubator/opennlp/tags/asf_migration/opennlp-uima/trunk/src/main/java/opennlp/uima/namefind/AbstractNameFinder.java
URL: http://svn.apache.org/viewvc/incubator/opennlp/tags/asf_migration/opennlp-uima/trunk/src/main/java/opennlp/uima/namefind/AbstractNameFinder.java?rev=1049347&view=auto
==============================================================================
--- incubator/opennlp/tags/asf_migration/opennlp-uima/trunk/src/main/java/opennlp/uima/namefind/AbstractNameFinder.java (added)
+++ incubator/opennlp/tags/asf_migration/opennlp-uima/trunk/src/main/java/opennlp/uima/namefind/AbstractNameFinder.java Tue Dec 14 23:59:00 2010
@@ -0,0 +1,177 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one or more
+ * contributor license agreemnets. 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.uima.namefind;
+
+import java.util.ArrayList;
+import java.util.Iterator;
+import java.util.List;
+
+import opennlp.tools.util.Span;
+import opennlp.uima.util.AnnotatorUtil;
+import opennlp.uima.util.ContainingConstraint;
+import opennlp.uima.util.UimaUtil;
+
+import org.apache.uima.UimaContext;
+import org.apache.uima.analysis_component.CasAnnotator_ImplBase;
+import org.apache.uima.analysis_engine.AnalysisEngineProcessException;
+import org.apache.uima.cas.CAS;
+import org.apache.uima.cas.FSIndex;
+import org.apache.uima.cas.Type;
+import org.apache.uima.cas.TypeSystem;
+import org.apache.uima.cas.text.AnnotationFS;
+import org.apache.uima.resource.ResourceInitializationException;
+import org.apache.uima.util.Level;
+import org.apache.uima.util.Logger;
+
+abstract class AbstractNameFinder extends CasAnnotator_ImplBase {
+
+ protected final String name;
+
+ protected Type mSentenceType;
+
+ protected Type mTokenType;
+
+ protected Type mNameType;
+
+ protected UimaContext context;
+
+ protected Logger mLogger;
+
+ private Boolean isRemoveExistingAnnotations;
+
+ AbstractNameFinder(String name) {
+ this.name = name;
+ }
+
+ protected void initialize() throws ResourceInitializationException {
+ }
+
+ public final void initialize(UimaContext context) throws ResourceInitializationException {
+
+ this.context = context;
+
+ mLogger = context.getLogger();
+
+ if (mLogger.isLoggable(Level.INFO)) {
+ mLogger.log(Level.INFO,
+ "Initializing the " + name + ".");
+ }
+
+ isRemoveExistingAnnotations = AnnotatorUtil.getOptionalBooleanParameter(
+ context, UimaUtil.IS_REMOVE_EXISTINGS_ANNOTAIONS);
+
+ if (isRemoveExistingAnnotations == null) {
+ isRemoveExistingAnnotations = false;
+ }
+
+ initialize();
+ }
+
+ /**
+ * Initializes the type system.
+ */
+ public void typeSystemInit(TypeSystem typeSystem)
+ throws AnalysisEngineProcessException {
+
+ // sentence type
+ mSentenceType = AnnotatorUtil.getRequiredTypeParameter(context, typeSystem,
+ UimaUtil.SENTENCE_TYPE_PARAMETER);
+
+ // token type
+ mTokenType = AnnotatorUtil.getRequiredTypeParameter(context, typeSystem,
+ UimaUtil.TOKEN_TYPE_PARAMETER);
+
+ // name type
+ mNameType = AnnotatorUtil.getRequiredTypeParameter(context, typeSystem,
+ NameFinder.NAME_TYPE_PARAMETER);
+ }
+
+ protected void postProcessAnnotations(Span detectedNames[],
+ AnnotationFS[] nameAnnotations) {
+ }
+
+ /**
+ * Called if the current document is completely processed.
+ */
+ protected void documentDone(CAS cas) {
+ }
+
+ protected abstract Span[] find(CAS cas, AnnotationFS sentence, List<AnnotationFS> tokenAnnotations,
+ String[] tokens);
+
+ /**
+ * Performs name finding on the given cas object.
+ */
+ public final void process(CAS cas) {
+
+ FSIndex<AnnotationFS> sentenceIndex = cas.getAnnotationIndex(mSentenceType);
+
+ for (Iterator<AnnotationFS> sentenceIterator = sentenceIndex.iterator();
+ sentenceIterator.hasNext();) {
+ AnnotationFS sentenceAnnotation = (AnnotationFS) sentenceIterator.next();
+
+ if (isRemoveExistingAnnotations)
+ UimaUtil.removeAnnotations(cas, sentenceAnnotation, mNameType);
+
+ ContainingConstraint containingConstraint =
+ new ContainingConstraint(sentenceAnnotation);
+
+ Iterator<AnnotationFS> tokenIterator = cas.createFilteredIterator(
+ cas.getAnnotationIndex(mTokenType).iterator(), containingConstraint);
+
+ List<AnnotationFS> tokenAnnotationList = new ArrayList<AnnotationFS>();
+
+ List<String> tokenList = new ArrayList<String>();
+
+ while (tokenIterator.hasNext()) {
+
+ AnnotationFS tokenAnnotation = (AnnotationFS) tokenIterator
+ .next();
+
+ tokenAnnotationList.add(tokenAnnotation);
+
+ tokenList.add(tokenAnnotation.getCoveredText());
+ }
+
+ Span[] names = find(cas, sentenceAnnotation, tokenAnnotationList,
+ (String[]) tokenList.toArray(new String[tokenList.size()]));
+
+ // TODO: log names, maybe with NameSample class
+
+ AnnotationFS nameAnnotations[] = new AnnotationFS[names.length];
+
+ for (int i = 0; i < names.length; i++) {
+
+ int startIndex = ((AnnotationFS) tokenAnnotationList.get(
+ names[i].getStart())).getBegin();
+
+ int endIndex = ((AnnotationFS) tokenAnnotationList.get(
+ names[i].getEnd() - 1)).getEnd();
+
+ nameAnnotations[i] =
+ cas.createAnnotation(mNameType, startIndex, endIndex);
+
+ cas.getIndexRepository().addFS(nameAnnotations[i]);
+ }
+
+ postProcessAnnotations(names, nameAnnotations);
+ }
+
+ documentDone(cas);
+ }
+}
\ No newline at end of file
Added: incubator/opennlp/tags/asf_migration/opennlp-uima/trunk/src/main/java/opennlp/uima/namefind/DictionaryNameFinder.java
URL: http://svn.apache.org/viewvc/incubator/opennlp/tags/asf_migration/opennlp-uima/trunk/src/main/java/opennlp/uima/namefind/DictionaryNameFinder.java?rev=1049347&view=auto
==============================================================================
--- incubator/opennlp/tags/asf_migration/opennlp-uima/trunk/src/main/java/opennlp/uima/namefind/DictionaryNameFinder.java (added)
+++ incubator/opennlp/tags/asf_migration/opennlp-uima/trunk/src/main/java/opennlp/uima/namefind/DictionaryNameFinder.java Tue Dec 14 23:59:00 2010
@@ -0,0 +1,88 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one or more
+ * contributor license agreemnets. 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.uima.namefind;
+
+import java.io.IOException;
+import java.io.InputStream;
+import java.util.List;
+
+import opennlp.tools.dictionary.Dictionary;
+import opennlp.tools.util.Span;
+import opennlp.uima.util.AnnotatorUtil;
+import opennlp.uima.util.ExceptionMessages;
+import opennlp.uima.util.UimaUtil;
+
+import org.apache.uima.cas.CAS;
+import org.apache.uima.cas.text.AnnotationFS;
+import org.apache.uima.resource.ResourceInitializationException;
+
+public class DictionaryNameFinder extends AbstractNameFinder {
+
+ private opennlp.tools.namefind.TokenNameFinder mNameFinder;
+
+ /**
+ * Initializes a new instance.
+ *
+ * Note: Use {@link #initialize() } to initialize
+ * this instance. Not use the constructor.
+ */
+ public DictionaryNameFinder() {
+ super("OpenNLP Dictionary Name annotator");
+ }
+
+ /**
+ * Initializes the current instance with the given context.
+ *
+ * Note: Do all initialization in this method, do not use the constructor.
+ */
+ public void initialize()
+ throws ResourceInitializationException {
+
+ Dictionary nameFinderDictionary;
+
+ try {
+ String modelName = AnnotatorUtil.getRequiredStringParameter(context,
+ UimaUtil.DICTIONARY_PARAMETER);
+
+ InputStream inModel = AnnotatorUtil
+ .getResourceAsStream(context, modelName);
+
+ nameFinderDictionary = new Dictionary(inModel);
+
+ } catch (IOException e) {
+ throw new ResourceInitializationException(
+ ExceptionMessages.MESSAGE_CATALOG,
+ ExceptionMessages.IO_ERROR_DICTIONARY_READING,
+ new Object[] {e.getMessage()});
+ }
+
+ mNameFinder =
+ new opennlp.tools.namefind.DictionaryNameFinder(nameFinderDictionary);
+ }
+
+ protected Span[] find(CAS cas, AnnotationFS sentence, List<AnnotationFS> tokenAnnotations, String[] tokens) {
+ return mNameFinder.find(tokens);
+ }
+
+ /**
+ * Releases allocated resources.
+ */
+ public void destroy() {
+ mNameFinder = null;
+ }
+}
\ No newline at end of file
Added: incubator/opennlp/tags/asf_migration/opennlp-uima/trunk/src/main/java/opennlp/uima/namefind/NameFinder.java
URL: http://svn.apache.org/viewvc/incubator/opennlp/tags/asf_migration/opennlp-uima/trunk/src/main/java/opennlp/uima/namefind/NameFinder.java?rev=1049347&view=auto
==============================================================================
--- incubator/opennlp/tags/asf_migration/opennlp-uima/trunk/src/main/java/opennlp/uima/namefind/NameFinder.java (added)
+++ incubator/opennlp/tags/asf_migration/opennlp-uima/trunk/src/main/java/opennlp/uima/namefind/NameFinder.java Tue Dec 14 23:59:00 2010
@@ -0,0 +1,222 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one or more
+ * contributor license agreemnets. 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.uima.namefind;
+
+import java.util.ArrayList;
+import java.util.Collection;
+import java.util.List;
+
+import opennlp.tools.namefind.NameFinderME;
+import opennlp.tools.namefind.TokenNameFinderModel;
+import opennlp.tools.util.Span;
+import opennlp.tools.util.eval.Mean;
+import opennlp.tools.util.featuregen.AdaptiveFeatureGenerator;
+import opennlp.tools.util.featuregen.AggregatedFeatureGenerator;
+import opennlp.tools.util.featuregen.TokenClassFeatureGenerator;
+import opennlp.tools.util.featuregen.TokenFeatureGenerator;
+import opennlp.tools.util.featuregen.TokenPatternFeatureGenerator;
+import opennlp.tools.util.featuregen.WindowFeatureGenerator;
+import opennlp.uima.util.AnnotatorUtil;
+import opennlp.uima.util.UimaUtil;
+
+import org.apache.uima.UimaContext;
+import org.apache.uima.analysis_engine.AnalysisEngineProcessException;
+import org.apache.uima.cas.CAS;
+import org.apache.uima.cas.Feature;
+import org.apache.uima.cas.FeatureStructure;
+import org.apache.uima.cas.Type;
+import org.apache.uima.cas.TypeSystem;
+import org.apache.uima.cas.text.AnnotationFS;
+import org.apache.uima.resource.ResourceAccessException;
+import org.apache.uima.resource.ResourceInitializationException;
+
+/**
+ * OpenNLP Name annotator.
+ * <p>
+ * Mandatory parameters
+ * <table border=1>
+ * <tr><th>Type</th> <th>Name</th> <th>Description</th></tr>
+ * <tr><td>String</td> <td>opennlp.uima.ModelName</td> <td>The name of the model file</td></tr>
+ * <tr><td>String</td> <td>opennlp.uima.SentenceType</td> <td>The full name of the sentence type</td></tr>
+ * <tr><td>String</td> <td>opennlp.uima.TokenType</td> <td>The full name of the token type</td></tr>
+ * <tr><td>String</td> <td>opennlp.uima.NameType</td> <td>The full name of the name type</td></tr>
+ * </table>
+ * <p>
+ * Optional parameters
+ * <table border=1>
+ * <tr><th>Type</th> <th>Name</th> <th>Description</th></tr>
+ * <tr><td>String</td> <td>opennlp.uima.ProbabilityFeature</td> <td>The name of the double
+ * probability feature (not set by default)</td></tr>
+ * <tr><td>Integer</td> <td>opennlp.uima.BeamSize</td></tr>
+ * <tr><td>String</td> <td>opennlp.uima.DocumentConfidenceType</td></tr>
+ * <tr><td>String</td> <td>opennlp.uima.DocumentConfidenceType</td></tr>
+ *
+ * </table>
+ */
+public final class NameFinder extends AbstractNameFinder {
+
+ public static final String NAME_TYPE_PARAMETER = "opennlp.uima.NameType";
+
+ public static final String TOKEN_PATTERN_OPTIMIZATION =
+ "opennlp.uima.TokenPatternOptimization";
+
+ // Token feature
+ public static final String TOKEN_FEATURE_PARAMETER =
+ "opennlp.uima.namefinder.TokenFeature";
+
+ public static final String TOKEN_FEATURE_PREV_WINDOW_SIZE_PARAMETER =
+ TOKEN_FEATURE_PARAMETER + ".previousWindowSize";
+
+ public static final String TOKEN_FEATURE_NEXT_WINDOW_SIZE_PARAMETER =
+ TOKEN_FEATURE_PARAMETER + ".nextWindowSize";
+
+ // Token class feature
+ public static final String TOKEN_CLASS_FEATURE_PARAMETER =
+ "opennlp.uima.namefinder.TokenClassFeature";
+
+ public static final String TOKEN_CLASS_FEATURE_PREV_WINDOW_SIZE_PARAMETER =
+ TOKEN_CLASS_FEATURE_PARAMETER + ".previousWindowSize";
+
+ public static final String TOKEN_CLASS_FEATURE_NEXT_WINDOW_SIZE_PARAMETER =
+ TOKEN_CLASS_FEATURE_PARAMETER + ".nextWindowSize";
+
+ private NameFinderME mNameFinder;
+
+ private Feature probabilityFeature;
+
+ private Type documentConfidenceType;
+ private Feature documentConfidenceNameTypeFeature;
+ private Feature documentConfidenceFeature;
+
+ private Mean documentConfidence = new Mean();
+
+ /**
+ * Initializes a new instance.
+ *
+ * Note: Use {@link #initialize(UimaContext) } to initialize
+ * this instance. Not use the constructor.
+ */
+ public NameFinder() {
+ super("OpenNLP Maxent Name annotator");
+ }
+
+ /**
+ * Initializes the current instance with the given context.
+ *
+ * Note: Do all initialization in this method, do not use the constructor.
+ */
+ public void initialize()
+ throws ResourceInitializationException {
+
+ super.initialize();
+
+ TokenNameFinderModel model;
+
+ try {
+ TokenNameFinderModelResource modelResource =
+ (TokenNameFinderModelResource) context.getResourceObject(UimaUtil.MODEL_PARAMETER);
+
+ model = modelResource.getModel();
+ }
+ catch (ResourceAccessException e) {
+ throw new ResourceInitializationException(e);
+ }
+
+ Integer beamSize = AnnotatorUtil.getOptionalIntegerParameter(context,
+ UimaUtil.BEAM_SIZE_PARAMETER);
+
+ if (beamSize == null)
+ beamSize = NameFinderME.DEFAULT_BEAM_SIZE;
+
+ mNameFinder = new NameFinderME(model, beamSize);
+ }
+
+ /**
+ * Initializes the type system.
+ */
+ public void typeSystemInit(TypeSystem typeSystem)
+ throws AnalysisEngineProcessException {
+
+ super.typeSystemInit(typeSystem);
+
+ probabilityFeature = AnnotatorUtil.getOptionalFeatureParameter(context, mNameType,
+ UimaUtil.PROBABILITY_FEATURE_PARAMETER, CAS.TYPE_NAME_DOUBLE);
+
+ documentConfidenceType = AnnotatorUtil.getOptionalTypeParameter(context, typeSystem,
+ "opennlp.uima.DocumentConfidenceType");
+ if (documentConfidenceType != null) {
+ documentConfidenceNameTypeFeature = AnnotatorUtil.getRequiredFeature(
+ documentConfidenceType, "nameType");
+ documentConfidenceFeature = AnnotatorUtil.getRequiredFeature(
+ documentConfidenceType, "confidence");
+ }
+ }
+
+ protected Span[] find(CAS cas, AnnotationFS sentence,
+ List<AnnotationFS> tokenAnnotations, String[] tokens) {
+
+ Span names[] = mNameFinder.find(tokens);
+
+ double probs[] = mNameFinder.probs();
+
+ for (int i = 0; i < probs.length; i++) {
+ documentConfidence.add(probs[i]);
+ }
+
+ return names;
+ }
+
+ protected void postProcessAnnotations(Span detectedNames[],
+ AnnotationFS[] nameAnnotations) {
+
+ if (probabilityFeature != null) {
+ double[] probs = mNameFinder.probs(detectedNames);
+
+ for (int i = 0; i < nameAnnotations.length; i++) {
+ nameAnnotations[i].setDoubleValue(probabilityFeature, probs[i]);
+ }
+ }
+ }
+
+ protected void documentDone(CAS cas) {
+
+ // TODO: Create confidence FS
+ // contains String name type
+ // contains Double prob
+ if (documentConfidenceType != null) {
+ FeatureStructure confidenceFS = cas.createFS(documentConfidenceType);
+ confidenceFS.setDoubleValue(documentConfidenceFeature,
+ documentConfidence.mean());
+ confidenceFS.setStringValue(documentConfidenceNameTypeFeature,
+ mNameType.getName());
+ cas.addFsToIndexes(confidenceFS);
+ }
+
+ // Clears the adaptive data which was created for the current document
+ mNameFinder.clearAdaptiveData();
+
+ documentConfidence = new Mean();
+ }
+
+ /**
+ * Releases allocated resources.
+ */
+ public void destroy() {
+ mNameFinder = null;
+ }
+}
\ No newline at end of file
Added: incubator/opennlp/tags/asf_migration/opennlp-uima/trunk/src/main/java/opennlp/uima/namefind/NameFinderTrainer.java
URL: http://svn.apache.org/viewvc/incubator/opennlp/tags/asf_migration/opennlp-uima/trunk/src/main/java/opennlp/uima/namefind/NameFinderTrainer.java?rev=1049347&view=auto
==============================================================================
--- incubator/opennlp/tags/asf_migration/opennlp-uima/trunk/src/main/java/opennlp/uima/namefind/NameFinderTrainer.java (added)
+++ incubator/opennlp/tags/asf_migration/opennlp-uima/trunk/src/main/java/opennlp/uima/namefind/NameFinderTrainer.java Tue Dec 14 23:59:00 2010
@@ -0,0 +1,375 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one or more
+ * contributor license agreemnets. 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.uima.namefind;
+
+import java.io.File;
+import java.io.FileInputStream;
+import java.io.IOException;
+import java.io.InputStream;
+import java.io.InputStreamReader;
+import java.util.ArrayList;
+import java.util.Collections;
+import java.util.Iterator;
+import java.util.LinkedList;
+import java.util.List;
+
+import opennlp.maxent.GIS;
+import opennlp.tools.namefind.NameFinderME;
+import opennlp.tools.namefind.NameSample;
+import opennlp.tools.namefind.NameSampleDataStream;
+import opennlp.tools.namefind.TokenNameFinderModel;
+import opennlp.tools.util.ObjectStream;
+import opennlp.tools.util.ObjectStreamUtils;
+import opennlp.tools.util.PlainTextByLineStream;
+import opennlp.tools.util.Span;
+import opennlp.uima.util.CasConsumerUtil;
+import opennlp.uima.util.ContainingConstraint;
+import opennlp.uima.util.OpennlpUtil;
+import opennlp.uima.util.UimaUtil;
+
+import org.apache.uima.UimaContext;
+import org.apache.uima.cas.CAS;
+import org.apache.uima.cas.FSIndex;
+import org.apache.uima.cas.Type;
+import org.apache.uima.cas.TypeSystem;
+import org.apache.uima.cas.text.AnnotationFS;
+import org.apache.uima.collection.CasConsumer_ImplBase;
+import org.apache.uima.resource.ResourceInitializationException;
+import org.apache.uima.resource.ResourceProcessException;
+import org.apache.uima.util.Level;
+import org.apache.uima.util.Logger;
+import org.apache.uima.util.ProcessTrace;
+
+/**
+ * OpenNLP NameFinder trainer.
+ * <p>
+ * Mandatory parameters
+ * <table border=1>
+ * <tr><th>Type</th> <th>Name</th> <th>Description</th></tr>
+ * <tr><td>String</td> <td>opennlp.uima.ModelName</td> <td>The name of the model file</td></tr>
+ * <tr><td>String</td> <td>opennlp.uima.Language</td> <td>The language code</td></tr>
+ * <tr><td>String</td> <td>opennlp.uima.SentenceType</td> <td>The full name of the sentence type</td></tr>
+ * <tr><td>String</td> <td>opennlp.uima.TokenType</td> <td>The full name of the token type</td></tr>
+ * <tr><td>String</td> <td>opennlp.uima.NameType</td> <td>The full name of the name type</td></tr>
+ * </table>
+ *
+ * Optional parameters
+ * <table border=1>
+ * <tr><th>Type</th> <th>Name</th> <th>Description</th></tr>
+ * <tr><td>String</td> <td>opennlp.uima.AdditionalTrainingDataFile</td> <td>Training file which contains additional data in the OpenNLP format</td></tr>
+ * <tr><td>String</td> <td>opennlp.uima.AdditionalTrainingDataEncoding</td> <td>Encoding of the additional training data</td></tr>
+ * <tr><td>Integer</td> <td>opennlp.uima.Cutoff</td> <td>(default=5)</td></tr>
+ * <tr><td>Integer</td> <td>opennlp.uima.Iterations</td> <td>(default=100)</td></tr>
+ * </table>
+ * <p>
+ */
+public final class NameFinderTrainer extends CasConsumer_ImplBase {
+
+ private Logger logger;
+
+ private String modelPath;
+
+ private String additionalTrainingDataFile;
+
+ private String additionalTrainingDataEncoding;
+
+ private Type sentenceType;
+
+ private Type tokenType;
+
+ private Type nameType;
+
+ private String language;
+
+ private int cutoff;
+
+ private int iterations;
+
+ // TODO: Keeping all events in memory limits the size of the training corpus
+ // Possible solutions:
+ // - Write all events to disk
+ // - Directly start indexing with a blocking sample stream, the indexer will then write everything
+ // to disk or could store the events much more space efficient in memory
+
+ private List<NameSample> nameFinderSamples = new ArrayList<NameSample>();
+
+ /**
+ * Initializes the current instance.
+ */
+ public void initialize() throws ResourceInitializationException {
+
+ super.initialize();
+
+ logger = getUimaContext().getLogger();
+
+ if (logger.isLoggable(Level.INFO)) {
+ logger.log(Level.INFO, "Initializing the OpenNLP Name Trainer.");
+ }
+
+ modelPath = CasConsumerUtil.getRequiredStringParameter(getUimaContext(),
+ UimaUtil.MODEL_PARAMETER);
+
+ language = CasConsumerUtil.getRequiredStringParameter(getUimaContext(),
+ UimaUtil.LANGUAGE_PARAMETER);
+
+ cutoff = CasConsumerUtil.getOptionalIntegerParameter(getUimaContext(), UimaUtil.CUTOFF_PARAMETER, 5);
+ iterations = CasConsumerUtil.getOptionalIntegerParameter(getUimaContext(), UimaUtil.ITERATIONS_PARAMETER, 100);
+
+ additionalTrainingDataFile = CasConsumerUtil.getOptionalStringParameter(
+ getUimaContext(), "opennlp.uima.AdditionalTrainingDataFile");
+
+ // If the additional training data is specified, the encoding must be provided!
+ if (additionalTrainingDataFile != null) {
+ additionalTrainingDataEncoding = CasConsumerUtil.getRequiredStringParameter(
+ getUimaContext(), "opennlp.uima.AdditionalTrainingDataEncoding");
+ }
+ }
+
+ /**
+ * Initialize the current instance with the given type system.
+ */
+ public void typeSystemInit(TypeSystem typeSystem)
+ throws ResourceInitializationException {
+
+ String sentenceTypeName =
+ CasConsumerUtil.getRequiredStringParameter(getUimaContext(),
+ UimaUtil.SENTENCE_TYPE_PARAMETER);
+
+ sentenceType = CasConsumerUtil.getType(typeSystem, sentenceTypeName);
+
+ String tokenTypeName = CasConsumerUtil.getRequiredStringParameter(getUimaContext(),
+ UimaUtil.TOKEN_TYPE_PARAMETER);
+
+ tokenType = CasConsumerUtil.getType(typeSystem, tokenTypeName);
+
+ String nameTypeName = CasConsumerUtil.getRequiredStringParameter(getUimaContext(),
+ NameFinder.NAME_TYPE_PARAMETER);
+
+ nameType = CasConsumerUtil.getType(typeSystem, nameTypeName);
+ }
+
+ /**
+ * Creates a {@link List} from an {@link Iterator}.
+ *
+ * @param <T>
+ * @param it
+ * @return
+ */
+ private static <T> List<T> iteratorToList(Iterator<T> it) {
+ List<T> list = new LinkedList<T>();
+
+ while (it.hasNext()) {
+ list.add(it.next());
+ }
+
+ return list;
+ }
+
+ private static boolean isContaining(AnnotationFS annotation,
+ AnnotationFS containtedAnnotation) {
+ boolean isStartContaining = annotation.getBegin() <= containtedAnnotation
+ .getBegin();
+ if (!isStartContaining) {
+ return false;
+ }
+
+ boolean isEndContaining = annotation.getEnd() >= containtedAnnotation
+ .getEnd();
+ if (!isEndContaining) {
+ return false;
+ }
+
+ return true;
+ }
+
+ /**
+ * Creates the name spans out of a list of token annotations and a list of entity annotations.
+ * <p>
+ * The name spans for the name finder use a token index and not on a character index which
+ * is used by the entity annotations.
+ *
+ * @param tokenList
+ * @param entityAnnotations
+ * @return
+ */
+ private static Span[] createNames(List<AnnotationFS> tokenList, List<AnnotationFS> entityAnnotations) {
+
+ List<Span> nameList = new LinkedList<Span>();
+
+ AnnotationFS currentEntity = null;
+
+ int startIndex = -1;
+ int index = 0;
+ for (Iterator<AnnotationFS> tokenIterator = tokenList.iterator(); tokenIterator.hasNext();) {
+ AnnotationFS token = (AnnotationFS) tokenIterator.next();
+
+ for (Iterator<AnnotationFS> it = entityAnnotations.iterator(); it.hasNext();) {
+
+ AnnotationFS entity = (AnnotationFS) it.next();
+
+ if (!isContaining(entity, token)) {
+ // ... end of an entity
+ if (currentEntity == entity) {
+ nameList.add(new Span(startIndex, index));
+
+ startIndex = -1;
+ currentEntity = null;
+ // break;
+ } else {
+ continue;
+ }
+ }
+
+ // is this token start of new entity
+ if (currentEntity == null && isContaining(entity, token)) {
+ startIndex = index;
+
+ currentEntity = entity;
+ }
+ }
+
+ index++;
+ }
+
+ if (currentEntity != null) {
+ Span name = new Span(startIndex, index);
+ nameList.add(name);
+ }
+
+ return nameList.toArray(new Span[nameList.size()]);
+ }
+
+ /**
+ * Process the given CAS object.
+ */
+ public void processCas(CAS cas) {
+ FSIndex<AnnotationFS> sentenceIndex = cas.getAnnotationIndex(sentenceType);
+
+ Iterator<AnnotationFS> sentenceIterator = sentenceIndex.iterator();
+ while (sentenceIterator.hasNext()) {
+ AnnotationFS sentenceAnnotation = sentenceIterator.next();
+
+ ContainingConstraint sentenceContainingConstraint = new ContainingConstraint(
+ sentenceAnnotation);
+
+ FSIndex<AnnotationFS> tokenAnnotations = cas.getAnnotationIndex(tokenType);
+
+ Iterator<AnnotationFS> containingTokens = cas.createFilteredIterator(tokenAnnotations
+ .iterator(), sentenceContainingConstraint);
+
+ FSIndex<AnnotationFS> allNames = cas.getAnnotationIndex(nameType);
+
+ Iterator<AnnotationFS> containingNames = cas.createFilteredIterator(allNames.iterator(),
+ sentenceContainingConstraint);
+
+ List<AnnotationFS> tokenList = iteratorToList(containingTokens);
+
+ Span names[] = createNames(tokenList, iteratorToList(containingNames));
+
+ // create token array
+ String tokenArray[] = new String[tokenList.size()];
+
+ for (int i = 0; i < tokenArray.length; i++) {
+ tokenArray[i] = ((AnnotationFS) tokenList.get(i))
+ .getCoveredText();
+ }
+
+ NameSample traingSentence = new NameSample(tokenArray, names, null, false);
+
+ if (traingSentence.getSentence().length != 0) {
+ nameFinderSamples.add(traingSentence);
+ }
+ else {
+ if (logger.isLoggable(Level.INFO)) {
+ logger.log(Level.INFO, "Sentence without tokens: " +
+ sentenceAnnotation.getCoveredText());
+ }
+ }
+ }
+ }
+
+ /**
+ * Called if the processing is finished, this method
+ * does the training.
+ */
+ public void collectionProcessComplete(ProcessTrace trace)
+ throws ResourceProcessException, IOException {
+
+ if (logger.isLoggable(Level.INFO)) {
+ logger.log(Level.INFO, "Collected " + nameFinderSamples.size() +
+ " name samples.");
+ }
+
+ GIS.PRINT_MESSAGES = false;
+
+ // create training stream ...
+ ObjectStream<NameSample> samples = ObjectStreamUtils.createObjectStream(nameFinderSamples);
+
+ InputStream additionalTrainingDataIn = null;
+ TokenNameFinderModel nameModel;
+ try {
+ if (additionalTrainingDataFile != null) {
+
+ additionalTrainingDataIn = new FileInputStream(additionalTrainingDataFile);
+
+ // TODO: Make encoding configurable, otherwise use UTF-8 as default!
+ ObjectStream<NameSample> additionalSamples = new NameSampleDataStream(
+ new PlainTextByLineStream(new InputStreamReader(additionalTrainingDataIn, additionalTrainingDataEncoding)));
+
+ samples = ObjectStreamUtils.createObjectStream(samples, additionalSamples);
+ }
+
+ // TODO: Make sure its possible to pass custom feature generator
+ // User could subclass this trainer to provide a custom feature generator
+ nameModel = NameFinderME.train(language, null,
+ samples, Collections.EMPTY_MAP, iterations, cutoff);
+
+ }
+ finally {
+ if (additionalTrainingDataIn != null)
+ additionalTrainingDataIn.close();
+ }
+
+ // dereference to allow garbage collection
+ nameFinderSamples = null;
+
+ File modelFile = new File(getUimaContextAdmin().getResourceManager()
+ .getDataPath() + File.separatorChar + modelPath);
+
+ OpennlpUtil.serialize(nameModel, modelFile);
+
+ if (logger.isLoggable(Level.INFO)) {
+ logger.log(Level.INFO, "Model was written to: " + modelFile.getAbsolutePath());
+ }
+ }
+
+ /**
+ * The trainer is not stateless.
+ */
+ public boolean isStateless() {
+ return false;
+ }
+
+ /**
+ * Destroys the current instance.
+ */
+ public void destroy() {
+ // dereference to allow garbage collection
+ nameFinderSamples = null;
+ }
+}
\ No newline at end of file
Added: incubator/opennlp/tags/asf_migration/opennlp-uima/trunk/src/main/java/opennlp/uima/namefind/TokenNameFinderModelResource.java
URL: http://svn.apache.org/viewvc/incubator/opennlp/tags/asf_migration/opennlp-uima/trunk/src/main/java/opennlp/uima/namefind/TokenNameFinderModelResource.java?rev=1049347&view=auto
==============================================================================
--- incubator/opennlp/tags/asf_migration/opennlp-uima/trunk/src/main/java/opennlp/uima/namefind/TokenNameFinderModelResource.java (added)
+++ incubator/opennlp/tags/asf_migration/opennlp-uima/trunk/src/main/java/opennlp/uima/namefind/TokenNameFinderModelResource.java Tue Dec 14 23:59:00 2010
@@ -0,0 +1,24 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one or more
+ * contributor license agreemnets. 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.uima.namefind;
+
+import opennlp.tools.namefind.TokenNameFinderModel;
+
+public interface TokenNameFinderModelResource {
+ TokenNameFinderModel getModel();
+}
Added: incubator/opennlp/tags/asf_migration/opennlp-uima/trunk/src/main/java/opennlp/uima/namefind/TokenNameFinderModelResourceImpl.java
URL: http://svn.apache.org/viewvc/incubator/opennlp/tags/asf_migration/opennlp-uima/trunk/src/main/java/opennlp/uima/namefind/TokenNameFinderModelResourceImpl.java?rev=1049347&view=auto
==============================================================================
--- incubator/opennlp/tags/asf_migration/opennlp-uima/trunk/src/main/java/opennlp/uima/namefind/TokenNameFinderModelResourceImpl.java (added)
+++ incubator/opennlp/tags/asf_migration/opennlp-uima/trunk/src/main/java/opennlp/uima/namefind/TokenNameFinderModelResourceImpl.java Tue Dec 14 23:59:00 2010
@@ -0,0 +1,38 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one or more
+ * contributor license agreemnets. 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.uima.namefind;
+
+import java.io.IOException;
+import java.io.InputStream;
+
+import opennlp.tools.namefind.TokenNameFinderModel;
+import opennlp.uima.util.AbstractModelResource;
+
+public class TokenNameFinderModelResourceImpl extends AbstractModelResource<TokenNameFinderModel>
+ implements TokenNameFinderModelResource {
+
+ public TokenNameFinderModel getModel() {
+ return model;
+ }
+
+ @Override
+ protected TokenNameFinderModel loadModel(InputStream in) throws IOException {
+ return new TokenNameFinderModel(in);
+ }
+
+}
Added: incubator/opennlp/tags/asf_migration/opennlp-uima/trunk/src/main/java/opennlp/uima/namefind/package.html
URL: http://svn.apache.org/viewvc/incubator/opennlp/tags/asf_migration/opennlp-uima/trunk/src/main/java/opennlp/uima/namefind/package.html?rev=1049347&view=auto
==============================================================================
--- incubator/opennlp/tags/asf_migration/opennlp-uima/trunk/src/main/java/opennlp/uima/namefind/package.html (added)
+++ incubator/opennlp/tags/asf_migration/opennlp-uima/trunk/src/main/java/opennlp/uima/namefind/package.html Tue Dec 14 23:59:00 2010
@@ -0,0 +1,12 @@
+<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 3.2 Final//EN">
+<html>
+<head>
+<!--
+
+-->
+</head>
+<body bgcolor="white">
+
+Package related to finding proper names and numeric amounts.
+</body>
+</html>
Added: incubator/opennlp/tags/asf_migration/opennlp-uima/trunk/src/main/java/opennlp/uima/normalizer/Normalizer.java
URL: http://svn.apache.org/viewvc/incubator/opennlp/tags/asf_migration/opennlp-uima/trunk/src/main/java/opennlp/uima/normalizer/Normalizer.java?rev=1049347&view=auto
==============================================================================
--- incubator/opennlp/tags/asf_migration/opennlp-uima/trunk/src/main/java/opennlp/uima/normalizer/Normalizer.java (added)
+++ incubator/opennlp/tags/asf_migration/opennlp-uima/trunk/src/main/java/opennlp/uima/normalizer/Normalizer.java Tue Dec 14 23:59:00 2010
@@ -0,0 +1,247 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one or more
+ * contributor license agreemnets. 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.uima.normalizer;
+
+import java.io.IOException;
+import java.io.InputStream;
+import java.text.ParseException;
+import java.util.Collections;
+import java.util.HashSet;
+import java.util.Iterator;
+import java.util.Set;
+
+import opennlp.tools.util.StringList;
+import opennlp.uima.namefind.NameFinder;
+import opennlp.uima.util.AnnotatorUtil;
+import opennlp.uima.util.ExceptionMessages;
+import opennlp.uima.util.UimaUtil;
+
+import org.apache.uima.UimaContext;
+import org.apache.uima.analysis_component.CasAnnotator_ImplBase;
+import org.apache.uima.analysis_engine.AnalysisEngineProcessException;
+import org.apache.uima.cas.CAS;
+import org.apache.uima.cas.FSIndex;
+import org.apache.uima.cas.Feature;
+import org.apache.uima.cas.Type;
+import org.apache.uima.cas.TypeSystem;
+import org.apache.uima.cas.text.AnnotationFS;
+import org.apache.uima.resource.ResourceInitializationException;
+import org.apache.uima.util.Level;
+import org.apache.uima.util.Logger;
+
+/**
+ * The Normalizer tries the structure annotations. The structured value
+ * is than assigned to a field of the annotation.
+ *
+ * The process depends on the
+ *
+ * string Tokens must be (fuzzy) mapped to categories eg. a month, a day or a
+ * year (use dictionary) integer, float tokens must be parsed eg. for percentage
+ * or period boolean tokens must be parsed eg is there any ???
+ *
+ *
+ * restricted set of outcomes throw error if not matched or silently fail
+ * unrestricted set of outcomes
+ */
+public class Normalizer extends CasAnnotator_ImplBase {
+
+ /**
+ * This set contains all supported range types.
+ */
+ private static final Set<String> SUPPORTED_TYPES;
+
+ static {
+ Set<String> supportedTypes = new HashSet<String>();
+
+ supportedTypes.add(CAS.TYPE_NAME_STRING);
+ supportedTypes.add(CAS.TYPE_NAME_BYTE);
+ supportedTypes.add(CAS.TYPE_NAME_SHORT);
+ supportedTypes.add(CAS.TYPE_NAME_INTEGER);
+ supportedTypes.add(CAS.TYPE_NAME_LONG);
+ supportedTypes.add(CAS.TYPE_NAME_FLOAT);
+ supportedTypes.add(CAS.TYPE_NAME_DOUBLE);
+
+ SUPPORTED_TYPES = Collections.unmodifiableSet(supportedTypes);
+ }
+
+ private UimaContext context;
+
+ private Logger mLogger;
+
+ /**
+ * The annotation marks the text to structure.
+ */
+ private Type mNameType;
+
+ /**
+ * The target type which the text should have. This type must be primitive.
+ *
+ * It should not be possible to assign something to this feature with is not
+ * structured. The feature should define allowed values.
+ */
+ private Feature mStructureFeature;
+
+ // private Type mSentenceType;
+
+ private StringDictionary mLookupDictionary;
+
+ /**
+ * Initializes a new instance.
+ *
+ * Note: Use {@link #initialize(UimaContext) } to initialize this instance. Not
+ * use the constructor.
+ */
+ public Normalizer() {
+ // must not be implemented !
+ }
+
+ /**
+ * Initializes the current instance with the given context.
+ *
+ * Note: Do all initialization in this method, do not use the constructor.
+ */
+ public void initialize(UimaContext context)
+ throws ResourceInitializationException {
+
+ super.initialize(context);
+
+ this.context = context;
+
+ mLogger = context.getLogger();
+
+ if (mLogger.isLoggable(Level.INFO)) {
+ mLogger.log(Level.INFO, "Initializing the OpenNLP Normalizer annotator.");
+ }
+
+ try {
+ String modelName = AnnotatorUtil.getOptionalStringParameter(context,
+ UimaUtil.DICTIONARY_PARAMETER);
+
+ if (modelName != null) {
+ InputStream inModel = AnnotatorUtil.getResourceAsStream(context,
+ modelName);
+
+ mLookupDictionary = new StringDictionary(inModel);
+ }
+ } catch (IOException e) {
+ throw new ResourceInitializationException(
+ ExceptionMessages.MESSAGE_CATALOG, "io_error_model_reading",
+ new Object[] {});
+ }
+ }
+
+ /**
+ * Initializes the type system.
+ */
+ public void typeSystemInit(TypeSystem typeSystem)
+ throws AnalysisEngineProcessException {
+
+ // sentence type
+ // String sentenceTypeName =
+ // AnnotatorUtil.getRequiredStringParameter(mContext,
+ // UimaUtil.SENTENCE_TYPE_PARAMETER);
+
+ // mSentenceType = AnnotatorUtil.getType(typeSystem, sentenceTypeName);
+
+ // name type
+ mNameType = AnnotatorUtil.getRequiredTypeParameter(context, typeSystem,
+ NameFinder.NAME_TYPE_PARAMETER);
+
+ mStructureFeature = AnnotatorUtil.getRequiredFeatureParameter(context,
+ mNameType, "opennlp.uima.normalizer.StructureFeature");
+
+ if (!SUPPORTED_TYPES.contains(mStructureFeature.getRange().getName())) {
+ throw new AnalysisEngineProcessException(
+ ExceptionMessages.MESSAGE_CATALOG, "range_type_unsupported",
+ new Object[] { mStructureFeature.getRange().getName() });
+ }
+ }
+
+ public void process(CAS tcas) {
+
+ FSIndex<AnnotationFS> sentenceIndex = tcas.getAnnotationIndex(mNameType);
+
+ for (Iterator<AnnotationFS> sentenceIterator = sentenceIndex.iterator(); sentenceIterator
+ .hasNext();) {
+
+ AnnotationFS nameAnnotation = (AnnotationFS) sentenceIterator.next();
+
+ // check if the document language is supported
+ String language = tcas.getDocumentLanguage();
+
+ if (!NumberUtil.isLanguageSupported(language)) {
+ if (mLogger.isLoggable(Level.INFO)) {
+ mLogger.log(Level.INFO, "Unsupported language: " + language);
+ }
+ continue;
+ }
+
+ String text = nameAnnotation.getCoveredText();
+
+ // if possible replace text with normalization from dictionary
+ if (mLookupDictionary != null) {
+
+ StringList tokens = new StringList(text);
+
+ String normalizedText = mLookupDictionary.get(tokens);
+
+ if (normalizedText != null) {
+ text = normalizedText;
+ }
+ }
+
+ if (CAS.TYPE_NAME_STRING.equals(mStructureFeature.getRange().getName())) {
+ nameAnnotation.setStringValue(mStructureFeature, text);
+ } else {
+
+ Number number;
+ try {
+ number = NumberUtil.parse(text, language);
+ } catch (ParseException e) {
+ if (mLogger.isLoggable(Level.INFO)) {
+ mLogger.log(Level.INFO, "Invalid number format: " + text);
+ }
+ continue;
+ }
+
+ if (CAS.TYPE_NAME_BYTE.equals(mStructureFeature.getRange().getName())) {
+ nameAnnotation.setByteValue(mStructureFeature, number.byteValue());
+ } else if (CAS.TYPE_NAME_SHORT.equals(mStructureFeature.getRange()
+ .getName())) {
+ nameAnnotation.setShortValue(mStructureFeature, number.shortValue());
+ } else if (CAS.TYPE_NAME_INTEGER.equals(mStructureFeature.getRange()
+ .getName())) {
+ nameAnnotation.setIntValue(mStructureFeature, number.intValue());
+ } else if (CAS.TYPE_NAME_LONG.equals(mStructureFeature.getRange()
+ .getName())) {
+ nameAnnotation.setLongValue(mStructureFeature, number.longValue());
+ } else if (CAS.TYPE_NAME_FLOAT.equals(mStructureFeature.getRange()
+ .getName())) {
+ nameAnnotation.setFloatValue(mStructureFeature, number.floatValue());
+ } else if (CAS.TYPE_NAME_DOUBLE.equals(mStructureFeature.getRange()
+ .getName())) {
+ nameAnnotation
+ .setDoubleValue(mStructureFeature, number.doubleValue());
+ } else {
+ // assert false : mStructureFeature.getRange().getName()
+ // + " is not supported!";
+ }
+ }
+ }
+ }
+}
\ No newline at end of file
Added: incubator/opennlp/tags/asf_migration/opennlp-uima/trunk/src/main/java/opennlp/uima/normalizer/NumberUtil.java
URL: http://svn.apache.org/viewvc/incubator/opennlp/tags/asf_migration/opennlp-uima/trunk/src/main/java/opennlp/uima/normalizer/NumberUtil.java?rev=1049347&view=auto
==============================================================================
--- incubator/opennlp/tags/asf_migration/opennlp-uima/trunk/src/main/java/opennlp/uima/normalizer/NumberUtil.java (added)
+++ incubator/opennlp/tags/asf_migration/opennlp-uima/trunk/src/main/java/opennlp/uima/normalizer/NumberUtil.java Tue Dec 14 23:59:00 2010
@@ -0,0 +1,97 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one or more
+ * contributor license agreemnets. 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.uima.normalizer;
+
+import java.text.NumberFormat;
+import java.text.ParseException;
+import java.util.Locale;
+
+/**
+ * This class contains methods to parse numbers which occur
+ * in natural language texts.
+ */
+public final class NumberUtil {
+
+ /**
+ * Checks if the language is supported.
+ *
+ * @param languageCode
+ * @return
+ */
+ public static boolean isLanguageSupported(String languageCode) {
+ Locale locale = new Locale(languageCode);
+
+ Locale possibleLocales[] = NumberFormat.getAvailableLocales();
+
+ boolean isLocaleSupported = false;
+
+ for (int i = 0; i < possibleLocales.length; i++) {
+ // search if local is contained
+ if (possibleLocales[i].equals(locale)) {
+ isLocaleSupported = true;
+ break;
+ }
+ }
+
+ return isLocaleSupported;
+ }
+
+ /**
+ * Removes trailing and containing space.
+ */
+ private static String removeChar(String string, char remove) {
+
+ StringBuilder result = new StringBuilder();
+
+ int lastPosition = 0;
+ int position = 0;
+ while ((position = string.indexOf(remove, lastPosition)) != -1) {
+ result.append(string.substring(lastPosition, position));
+ lastPosition = position + 1;
+ }
+
+ result.append(string.substring(lastPosition, string.length()));
+
+ return result.toString();
+ }
+
+ /**
+ * Gives its best to parse the provided number.
+ *
+ * @param number
+ * @param languageCode
+ * @return
+ * @throws ParseException
+ */
+ public static Number parse(String number, String languageCode)
+ throws ParseException {
+
+ if (!isLanguageSupported(languageCode)) {
+ throw new IllegalArgumentException("Language is not supported!");
+ }
+
+ Locale locale = new Locale(languageCode);
+
+ NumberFormat numberFormat = NumberFormat.getInstance(locale);
+
+ number = number.trim();
+ number = removeChar(number, ' ');
+
+ return numberFormat.parse(number);
+ }
+}
\ No newline at end of file
Added: incubator/opennlp/tags/asf_migration/opennlp-uima/trunk/src/main/java/opennlp/uima/normalizer/StringDictionary.java
URL: http://svn.apache.org/viewvc/incubator/opennlp/tags/asf_migration/opennlp-uima/trunk/src/main/java/opennlp/uima/normalizer/StringDictionary.java?rev=1049347&view=auto
==============================================================================
--- incubator/opennlp/tags/asf_migration/opennlp-uima/trunk/src/main/java/opennlp/uima/normalizer/StringDictionary.java (added)
+++ incubator/opennlp/tags/asf_migration/opennlp-uima/trunk/src/main/java/opennlp/uima/normalizer/StringDictionary.java Tue Dec 14 23:59:00 2010
@@ -0,0 +1,104 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one or more
+ * contributor license agreemnets. 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.uima.normalizer;
+
+import java.io.IOException;
+import java.io.InputStream;
+import java.io.OutputStream;
+import java.util.HashMap;
+import java.util.Iterator;
+import java.util.Map;
+
+import opennlp.tools.dictionary.serializer.Attributes;
+import opennlp.tools.dictionary.serializer.DictionarySerializer;
+import opennlp.tools.dictionary.serializer.Entry;
+import opennlp.tools.dictionary.serializer.EntryInserter;
+import opennlp.tools.util.InvalidFormatException;
+import opennlp.tools.util.StringList;
+
+// lookup a string for given token list
+public class StringDictionary {
+
+ private Map<StringList, String> entries = new HashMap<StringList, String>();
+
+ public StringDictionary() {
+ }
+
+ /**
+ * Initializes the current instance.
+ *
+ * @param in
+ * @throws IOException
+ * @throws InvalidFormatException
+ */
+ public StringDictionary(InputStream in) throws IOException,
+ InvalidFormatException {
+ DictionarySerializer.create(in, new EntryInserter() {
+ public void insert(Entry entry) throws InvalidFormatException {
+ String valueString = entry.getAttributes().getValue("value");
+ put(entry.getTokens(), valueString);
+ }
+ });
+ }
+
+ public String get(StringList key) {
+ return (String) entries.get(key);
+ }
+
+ public void put(StringList key, String value) {
+ entries.put(key, value);
+ }
+
+ Iterator<StringList> iterator() {
+ return entries.keySet().iterator();
+ }
+
+ /**
+ * Writes the ngram instance to the given {@link OutputStream}.
+ *
+ * @param out
+ * @throws IOException
+ * if an I/O Error during writing occures
+ */
+ public void serialize(OutputStream out) throws IOException {
+ Iterator<Entry> entryIterator = new Iterator<Entry>() {
+ private Iterator<StringList> mDictionaryIterator = StringDictionary.this.iterator();
+
+ public boolean hasNext() {
+ return mDictionaryIterator.hasNext();
+ }
+
+ public Entry next() {
+
+ StringList tokens = mDictionaryIterator.next();
+
+ Attributes attributes = new Attributes();
+
+ attributes.setValue("value", get(tokens));
+
+ return new Entry(tokens, attributes);
+ }
+
+ public void remove() {
+ throw new UnsupportedOperationException();
+ }
+ };
+
+ DictionarySerializer.serialize(out, entryIterator);
+ }
+}
\ No newline at end of file
Added: incubator/opennlp/tags/asf_migration/opennlp-uima/trunk/src/main/java/opennlp/uima/parser/Parser.java
URL: http://svn.apache.org/viewvc/incubator/opennlp/tags/asf_migration/opennlp-uima/trunk/src/main/java/opennlp/uima/parser/Parser.java?rev=1049347&view=auto
==============================================================================
--- incubator/opennlp/tags/asf_migration/opennlp-uima/trunk/src/main/java/opennlp/uima/parser/Parser.java (added)
+++ incubator/opennlp/tags/asf_migration/opennlp-uima/trunk/src/main/java/opennlp/uima/parser/Parser.java Tue Dec 14 23:59:00 2010
@@ -0,0 +1,348 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one or more
+ * contributor license agreemnets. 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.uima.parser;
+
+import java.util.HashMap;
+import java.util.Iterator;
+import java.util.LinkedList;
+import java.util.List;
+import java.util.Map;
+
+import opennlp.tools.parser.Parse;
+import opennlp.tools.parser.ParserFactory;
+import opennlp.tools.parser.ParserModel;
+import opennlp.tools.util.Span;
+import opennlp.uima.util.AnnotatorUtil;
+import opennlp.uima.util.ContainingConstraint;
+import opennlp.uima.util.UimaUtil;
+
+import org.apache.uima.UimaContext;
+import org.apache.uima.analysis_component.CasAnnotator_ImplBase;
+import org.apache.uima.analysis_engine.AnalysisEngineProcessException;
+import org.apache.uima.cas.CAS;
+import org.apache.uima.cas.FSIndex;
+import org.apache.uima.cas.Feature;
+import org.apache.uima.cas.Type;
+import org.apache.uima.cas.TypeSystem;
+import org.apache.uima.cas.text.AnnotationFS;
+import org.apache.uima.resource.ResourceAccessException;
+import org.apache.uima.resource.ResourceInitializationException;
+import org.apache.uima.util.Level;
+import org.apache.uima.util.Logger;
+
+/**
+ * Abstract base class for OpenNLP Parser annotators.
+ * <p>
+ * Mandatory parameters
+ * <table border=1>
+ * <tr><th>Type</th> <th>Name</th> <th>Description</th></tr>
+ * <tr><td>String</td> <td>opennlp.uima.ModelName</td> <td>The name of the model file</td></tr>
+ * <tr><td>String</td> <td>opennlp.uima.SentenceType</td> <td>The full name of the sentence type</td></tr>
+ * <tr><td>String</td> <td>opennlp.uima.TokenType</td> <td>The full name of the token type</td></tr>
+ * <tr><td>String</td> <td>opennlp.uima.ParseType</td> <td>The full name of the parse type</td></tr>
+ * <tr><td>String</td> <td>opennlp.uima.TypeFeature</td> <td>The name of the type feature</td></tr>
+ * </table>
+ * <p>
+ * Optional parameters
+ * <table border=1>
+ * <tr><th>Type</th> <th>Name</th> <th>Description</th></tr>
+ * <tr><td>Integer</td> <td>opennlp.uima.BeamSize</td></tr>
+ * </table>
+ */
+public class Parser extends CasAnnotator_ImplBase {
+
+ private static class ParseConverter {
+ private Map<Integer, Integer> mIndexMap = new HashMap<Integer, Integer>();
+
+ private Parse mParseForTagger;
+
+ private String mSentence;
+
+ /**
+ * Initializes a new instance.
+ *
+ * @param sentence
+ * @param tokens
+ */
+ public ParseConverter(String sentence, Span tokens[]) {
+
+ mSentence = sentence;
+
+ StringBuilder sentenceStringBuilder = new StringBuilder();
+
+ String tokenList[] = new String[tokens.length];
+
+ for (int i = 0; i < tokens.length; i++) {
+ String tokenString = tokens[i].getCoveredText(sentence).toString();
+ String escapedToken = escape(tokenString);
+ tokenList[i] = escapedToken;
+
+ int escapedStart = sentenceStringBuilder.length();
+ int start = tokens[i].getStart();
+ mIndexMap.put(new Integer(escapedStart), new Integer(start));
+
+ int escapedEnd = escapedStart + escapedToken.length();
+ int end = tokens[i].getEnd();
+ mIndexMap.put(new Integer(escapedEnd), new Integer(end));
+
+ sentenceStringBuilder.append(tokenList[i]);
+
+ sentenceStringBuilder.append(' ');
+ }
+
+ // remove last space
+ sentenceStringBuilder.setLength(sentenceStringBuilder.length() - 1);
+
+ String tokenizedSentence = sentenceStringBuilder.toString();
+
+ mParseForTagger = new Parse(tokenizedSentence,
+ new Span(0, tokenizedSentence.length()), "INC", 1, null);
+
+ int start = 0;
+
+ for (int i = 0; i < tokenList.length; i++) {
+
+ mParseForTagger.insert(new Parse(tokenizedSentence, new Span(start,
+ start + tokenList[i].length()),
+ opennlp.tools.parser.chunking.Parser.TOK_NODE, 0f, 0));
+
+ start += tokenList[i].length() + 1;
+ }
+ }
+
+ private static String escape(String text) {
+ return text;
+ }
+
+ /**
+ * Creates the parse for the tagger.
+ *
+ * @return the parse which can be passed to the tagger
+ */
+ Parse getParseForTagger() {
+ return mParseForTagger;
+ }
+
+ /**
+ * Converts the parse from the tagger back.
+ *
+ * @param parseFromTagger
+ * @return the final parse
+ */
+ Parse transformParseFromTagger(Parse parseFromTagger) {
+ int start = parseFromTagger.getSpan().getStart();
+ int end = parseFromTagger.getSpan().getEnd();
+
+
+ Parse transformedParse = new Parse(mSentence,
+ new Span(((Integer) mIndexMap.get(new Integer(start))).intValue(),
+ ((Integer) mIndexMap.get(new Integer(end))).intValue()),
+ parseFromTagger.getType(),
+ parseFromTagger.getProb(), parseFromTagger.getHeadIndex());
+
+
+ Parse[] parseFromTaggerChildrens = parseFromTagger.getChildren();
+
+ // call this method for all childs ...
+ for (int i = 0; i < parseFromTaggerChildrens.length; i++) {
+
+ Parse child = parseFromTaggerChildrens[i];
+
+ if (!child.getType().equals(
+ opennlp.tools.parser.chunking.Parser.TOK_NODE)) {
+
+ // only insert if it has childs
+ if (child.getChildCount() > 0 &&
+ !child.getChildren()[0].getType().equals(opennlp.tools.parser.chunking.Parser.TOK_NODE)) {
+ transformedParse.insert(transformParseFromTagger(child));
+ }
+ }
+ }
+
+ if (parseFromTagger.getType().equals("TOP")) {
+ return transformedParse.getChildren()[0];
+ }
+ else {
+ return transformedParse;
+ }
+ }
+
+ }
+
+ private static final String PARSE_TYPE_PARAMETER = "opennlp.uima.ParseType";
+
+ public static final String TYPE_FEATURE_PARAMETER =
+ "opennlp.uima.TypeFeature";
+
+ protected UimaContext context;
+
+ protected Logger mLogger;
+
+ private Type mSentenceType;
+
+ private Type mTokenType;
+
+ protected opennlp.tools.parser.Parser mParser;
+
+ private Type mParseType;
+
+ private Feature mTypeFeature;
+
+ /**
+ * Initializes the current instance with the given context.
+ */
+ public void initialize(UimaContext context)
+ throws ResourceInitializationException {
+
+ super.initialize(context);
+
+ this.context = context;
+
+ mLogger = context.getLogger();
+
+ if (mLogger.isLoggable(Level.INFO)) {
+ mLogger.log(Level.INFO, "Initializing the OpenNLP Parser.");
+ }
+
+ ParserModel model;
+
+ try {
+ ParserModelResource modelResource =
+ (ParserModelResource) context.getResourceObject(UimaUtil.MODEL_PARAMETER);
+
+ model = modelResource.getModel();
+ }
+ catch (ResourceAccessException e) {
+ throw new ResourceInitializationException(e);
+ }
+
+ mParser = ParserFactory.create(model);
+ }
+
+ /**
+ * Initializes the type system.
+ */
+ public void typeSystemInit(TypeSystem typeSystem)
+ throws AnalysisEngineProcessException {
+
+ mSentenceType = AnnotatorUtil.getRequiredTypeParameter(context, typeSystem,
+ UimaUtil.SENTENCE_TYPE_PARAMETER);
+
+ mTokenType = AnnotatorUtil.getRequiredTypeParameter(context, typeSystem,
+ UimaUtil.TOKEN_TYPE_PARAMETER);
+
+ mParseType = AnnotatorUtil.getRequiredTypeParameter(context, typeSystem,
+ PARSE_TYPE_PARAMETER);
+
+ mTypeFeature = AnnotatorUtil.getRequiredFeatureParameter(context, mParseType, TYPE_FEATURE_PARAMETER,
+ CAS.TYPE_NAME_STRING);
+ }
+
+ /**
+ * Performs parsing on the given {@link CAS} object.
+ */
+ public void process(CAS cas) {
+ FSIndex<AnnotationFS> sentences = cas.getAnnotationIndex(mSentenceType);
+
+ Iterator<AnnotationFS> sentencesIterator = sentences.iterator();
+
+ while (sentencesIterator.hasNext()) {
+ AnnotationFS sentence = (AnnotationFS) sentencesIterator.next();
+
+ process(cas, sentence);
+ }
+ }
+
+ protected void process(CAS cas, AnnotationFS sentenceAnnotation) {
+ FSIndex<AnnotationFS> allTokens = cas.getAnnotationIndex(mTokenType);
+
+ ContainingConstraint containingConstraint =
+ new ContainingConstraint(sentenceAnnotation);
+
+ Iterator<AnnotationFS> containingTokens = cas.createFilteredIterator(
+ allTokens.iterator(), containingConstraint);
+
+ StringBuilder sentenceStringBuilder = new StringBuilder();
+
+ while (containingTokens.hasNext())
+ {
+ AnnotationFS token = (AnnotationFS) containingTokens.next();
+
+ sentenceStringBuilder.append(token.getCoveredText());
+
+ // attention the offsets moves inside the sentence...
+ sentenceStringBuilder.append(' ');
+ }
+
+ String sentence = sentenceStringBuilder.toString();
+ sentence = sentenceAnnotation.getCoveredText();
+
+ containingTokens = cas.createFilteredIterator(
+ allTokens.iterator(), containingConstraint);
+
+ List<Span> tokenSpans = new LinkedList<Span>();
+
+ while(containingTokens.hasNext()) {
+ AnnotationFS token = (AnnotationFS) containingTokens.next();
+
+ tokenSpans.add(new Span(token.getBegin() - sentenceAnnotation.getBegin(),
+ token.getEnd() - sentenceAnnotation.getBegin()));
+ }
+
+ ParseConverter converter = new ParseConverter(sentence,(Span[])
+ tokenSpans.toArray(new Span[tokenSpans.size()]));
+
+ Parse parse = mParser.parse(converter.getParseForTagger());
+
+ parse = converter.transformParseFromTagger(parse);
+
+ if (mLogger.isLoggable(Level.INFO)) {
+ StringBuffer parseString = new StringBuffer();
+ parse.show(parseString);
+
+ mLogger.log(Level.INFO, parseString.toString());
+ }
+
+ createAnnotation(cas, sentenceAnnotation.getBegin(), parse);
+ }
+
+ protected void createAnnotation(CAS cas, int offset, Parse parse) {
+
+ Parse parseChildrens[] = parse.getChildren();
+
+ // do this for all children
+ for (int i = 0; i < parseChildrens.length; i++) {
+ Parse child = parseChildrens[i];
+ createAnnotation(cas, offset, child);
+ }
+
+ AnnotationFS parseAnnotation = cas.createAnnotation(mParseType, offset +
+ parse.getSpan().getStart(), offset + parse.getSpan().getEnd());
+
+ parseAnnotation.setStringValue(mTypeFeature, parse.getType());
+
+ cas.getIndexRepository().addFS(parseAnnotation);
+ }
+
+ /**
+ * Releases allocated resources.
+ */
+ public void destroy() {
+ mParser = null;
+ }
+}
Added: incubator/opennlp/tags/asf_migration/opennlp-uima/trunk/src/main/java/opennlp/uima/parser/ParserModelResource.java
URL: http://svn.apache.org/viewvc/incubator/opennlp/tags/asf_migration/opennlp-uima/trunk/src/main/java/opennlp/uima/parser/ParserModelResource.java?rev=1049347&view=auto
==============================================================================
--- incubator/opennlp/tags/asf_migration/opennlp-uima/trunk/src/main/java/opennlp/uima/parser/ParserModelResource.java (added)
+++ incubator/opennlp/tags/asf_migration/opennlp-uima/trunk/src/main/java/opennlp/uima/parser/ParserModelResource.java Tue Dec 14 23:59:00 2010
@@ -0,0 +1,24 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one or more
+ * contributor license agreemnets. 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.uima.parser;
+
+import opennlp.tools.parser.ParserModel;
+
+public interface ParserModelResource {
+ ParserModel getModel();
+}
Added: incubator/opennlp/tags/asf_migration/opennlp-uima/trunk/src/main/java/opennlp/uima/parser/ParserModelResourceImpl.java
URL: http://svn.apache.org/viewvc/incubator/opennlp/tags/asf_migration/opennlp-uima/trunk/src/main/java/opennlp/uima/parser/ParserModelResourceImpl.java?rev=1049347&view=auto
==============================================================================
--- incubator/opennlp/tags/asf_migration/opennlp-uima/trunk/src/main/java/opennlp/uima/parser/ParserModelResourceImpl.java (added)
+++ incubator/opennlp/tags/asf_migration/opennlp-uima/trunk/src/main/java/opennlp/uima/parser/ParserModelResourceImpl.java Tue Dec 14 23:59:00 2010
@@ -0,0 +1,37 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one or more
+ * contributor license agreemnets. 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.uima.parser;
+
+import java.io.IOException;
+import java.io.InputStream;
+
+import opennlp.tools.parser.ParserModel;
+import opennlp.uima.util.AbstractModelResource;
+
+public class ParserModelResourceImpl extends AbstractModelResource<ParserModel> implements
+ ParserModelResource {
+
+ public ParserModel getModel() {
+ return model;
+ }
+
+ @Override
+ protected ParserModel loadModel(InputStream in) throws IOException {
+ return new ParserModel(in);
+ }
+}
Added: incubator/opennlp/tags/asf_migration/opennlp-uima/trunk/src/main/java/opennlp/uima/postag/POSModelResource.java
URL: http://svn.apache.org/viewvc/incubator/opennlp/tags/asf_migration/opennlp-uima/trunk/src/main/java/opennlp/uima/postag/POSModelResource.java?rev=1049347&view=auto
==============================================================================
--- incubator/opennlp/tags/asf_migration/opennlp-uima/trunk/src/main/java/opennlp/uima/postag/POSModelResource.java (added)
+++ incubator/opennlp/tags/asf_migration/opennlp-uima/trunk/src/main/java/opennlp/uima/postag/POSModelResource.java Tue Dec 14 23:59:00 2010
@@ -0,0 +1,24 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one or more
+ * contributor license agreemnets. 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.uima.postag;
+
+import opennlp.tools.postag.POSModel;
+
+public interface POSModelResource {
+ POSModel getModel();
+}
Added: incubator/opennlp/tags/asf_migration/opennlp-uima/trunk/src/main/java/opennlp/uima/postag/POSModelResourceImpl.java
URL: http://svn.apache.org/viewvc/incubator/opennlp/tags/asf_migration/opennlp-uima/trunk/src/main/java/opennlp/uima/postag/POSModelResourceImpl.java?rev=1049347&view=auto
==============================================================================
--- incubator/opennlp/tags/asf_migration/opennlp-uima/trunk/src/main/java/opennlp/uima/postag/POSModelResourceImpl.java (added)
+++ incubator/opennlp/tags/asf_migration/opennlp-uima/trunk/src/main/java/opennlp/uima/postag/POSModelResourceImpl.java Tue Dec 14 23:59:00 2010
@@ -0,0 +1,37 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one or more
+ * contributor license agreemnets. 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.uima.postag;
+
+import java.io.IOException;
+import java.io.InputStream;
+
+import opennlp.tools.postag.POSModel;
+import opennlp.uima.util.AbstractModelResource;
+
+public class POSModelResourceImpl extends AbstractModelResource<POSModel>
+ implements POSModelResource {
+
+ public POSModel getModel() {
+ return model;
+ }
+
+ @Override
+ protected POSModel loadModel(InputStream in) throws IOException {
+ return new POSModel(in);
+ }
+}
Added: incubator/opennlp/tags/asf_migration/opennlp-uima/trunk/src/main/java/opennlp/uima/postag/POSTagger.java
URL: http://svn.apache.org/viewvc/incubator/opennlp/tags/asf_migration/opennlp-uima/trunk/src/main/java/opennlp/uima/postag/POSTagger.java?rev=1049347&view=auto
==============================================================================
--- incubator/opennlp/tags/asf_migration/opennlp-uima/trunk/src/main/java/opennlp/uima/postag/POSTagger.java (added)
+++ incubator/opennlp/tags/asf_migration/opennlp-uima/trunk/src/main/java/opennlp/uima/postag/POSTagger.java Tue Dec 14 23:59:00 2010
@@ -0,0 +1,233 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one or more
+ * contributor license agreemnets. 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.uima.postag;
+
+import java.util.Iterator;
+import java.util.LinkedList;
+import java.util.List;
+
+import opennlp.tools.postag.POSModel;
+import opennlp.tools.postag.POSTaggerME;
+import opennlp.uima.util.AnnotationComboIterator;
+import opennlp.uima.util.AnnotationIteratorPair;
+import opennlp.uima.util.AnnotatorUtil;
+import opennlp.uima.util.UimaUtil;
+
+import org.apache.uima.UimaContext;
+import org.apache.uima.analysis_component.CasAnnotator_ImplBase;
+import org.apache.uima.analysis_engine.AnalysisEngineProcessException;
+import org.apache.uima.cas.CAS;
+import org.apache.uima.cas.Feature;
+import org.apache.uima.cas.Type;
+import org.apache.uima.cas.TypeSystem;
+import org.apache.uima.cas.text.AnnotationFS;
+import org.apache.uima.resource.ResourceAccessException;
+import org.apache.uima.resource.ResourceInitializationException;
+import org.apache.uima.util.Level;
+import org.apache.uima.util.Logger;
+
+/**
+ * OpenNLP Part Of Speech annotator.
+ * <p>
+ * Mandatory parameters
+ * <table border=1>
+ * <tr><th>Type</th> <th>Name</th> <th>Description</th></tr>
+ * <tr><td>String</td> <td>opennlp.uima.ModelName</td> <td>The name of the model file</td></tr>
+ * <tr><td>String</td> <td>opennlp.uima.SentenceType</td> <td>The full name of the sentence type</td></tr>
+ * <tr><td>String</td> <td>opennlp.uima.TokenType</td> <td>The full name of the token type</td></tr>
+ * <tr><td>String</td> <td>opennlp.uima.POSFeature</td> <td>The name of the token pos feature,
+ * the feature must be of type String</td></tr>
+ * </table>
+ * <p>
+ * Optional parameters
+ * <table border=1>
+ * <tr><th>Type</th> <th>Name</th> <th>Description</th></tr>
+ * <tr><td>String</td> <td>opennlp.uima.ProbabilityFeature</td> <td>The name of the double probability feature (not set by default)</td></tr>
+ * <tr><td>Integer</td> <td>opennlp.uima.BeamSize</td>
+ * <tr><td>String</td> <td>opennlp.uima.DictionaryName</td> <td>The name of the dictionary file</td></tr>
+ * </table>
+ */
+public final class POSTagger extends CasAnnotator_ImplBase {
+
+ private POSTaggerME posTagger;
+
+ private Type sentenceType;
+
+ private Type tokenType;
+
+ private Feature posFeature;
+
+ private Feature probabilityFeature;
+
+ private UimaContext context;
+
+ private Logger logger;
+
+ /**
+ * Initializes a new instance.
+ *
+ * Note: Use {@link #initialize(UimaContext) } to initialize this instance. Not use the
+ * constructor.
+ */
+ public POSTagger() {
+ // must not be implemented !
+ }
+
+ /**
+ * Initializes the current instance with the given context.
+ *
+ * Note: Do all initialization in this method, do not use the constructor.
+ */
+ @Override
+ public void initialize(UimaContext context)
+ throws ResourceInitializationException {
+
+ super.initialize(context);
+
+ this.context = context;
+
+ this.logger = context.getLogger();
+
+ if (this.logger.isLoggable(Level.INFO)) {
+ this.logger.log(Level.INFO, "Initializing the OpenNLP "
+ + "Part of Speech annotator.");
+ }
+
+ POSModel model;
+
+ try {
+ POSModelResource modelResource = (POSModelResource) context
+ .getResourceObject(UimaUtil.MODEL_PARAMETER);
+
+ model = modelResource.getModel();
+ } catch (ResourceAccessException e) {
+ throw new ResourceInitializationException(e);
+ }
+
+ Integer beamSize = AnnotatorUtil.getOptionalIntegerParameter(context,
+ UimaUtil.BEAM_SIZE_PARAMETER);
+
+ if (beamSize == null)
+ beamSize = POSTaggerME.DEFAULT_BEAM_SIZE;
+
+ this.posTagger = new POSTaggerME(model, beamSize, 0);
+ }
+
+ /**
+ * Initializes the type system.
+ */
+ @Override
+ public void typeSystemInit(TypeSystem typeSystem) throws AnalysisEngineProcessException {
+
+ // sentence type
+ this.sentenceType = AnnotatorUtil.getRequiredTypeParameter(this.context, typeSystem,
+ UimaUtil.SENTENCE_TYPE_PARAMETER);
+
+ // token type
+ this.tokenType = AnnotatorUtil.getRequiredTypeParameter(this.context, typeSystem,
+ UimaUtil.TOKEN_TYPE_PARAMETER);
+
+ // pos feature
+ this.posFeature = AnnotatorUtil.getRequiredFeatureParameter(this.context, this.tokenType,
+ UimaUtil.POS_FEATURE_PARAMETER, CAS.TYPE_NAME_STRING);
+
+ this.probabilityFeature = AnnotatorUtil.getOptionalFeatureParameter(this.context,
+ this.tokenType, UimaUtil.PROBABILITY_FEATURE_PARAMETER, CAS.TYPE_NAME_DOUBLE);
+ }
+
+ /**
+ * Performs pos-tagging on the given tcas object.
+ */
+ @Override
+ public void process(CAS tcas) {
+
+ final AnnotationComboIterator comboIterator = new AnnotationComboIterator(tcas,
+ this.sentenceType, this.tokenType);
+
+ for (AnnotationIteratorPair annotationIteratorPair : comboIterator) {
+
+ final List<AnnotationFS> sentenceTokenAnnotationList = new LinkedList<AnnotationFS>();
+
+ final List<String> sentenceTokenList = new LinkedList<String>();
+
+ for (AnnotationFS tokenAnnotation : annotationIteratorPair.getSubIterator()) {
+
+ sentenceTokenAnnotationList.add(tokenAnnotation);
+
+ sentenceTokenList.add(tokenAnnotation.getCoveredText());
+ }
+
+ final List<String> posTags = this.posTagger.tag(sentenceTokenList);
+
+ double posProbabilities[] = null;
+
+ if (this.probabilityFeature != null) {
+ posProbabilities = this.posTagger.probs();
+ }
+
+ final Iterator<String> posTagIterator = posTags.iterator();
+ final Iterator<AnnotationFS> sentenceTokenIterator = sentenceTokenAnnotationList.iterator();
+
+ int index = 0;
+ while (posTagIterator.hasNext() && sentenceTokenIterator.hasNext()) {
+ final String posTag = posTagIterator.next();
+ final AnnotationFS tokenAnnotation = sentenceTokenIterator.next();
+
+ tokenAnnotation.setStringValue(this.posFeature, posTag);
+
+ if (posProbabilities != null) {
+ tokenAnnotation.setDoubleValue(this.posFeature, posProbabilities[index]);
+ }
+
+ index++;
+ }
+
+ // log tokens with pos
+ if (this.logger.isLoggable(Level.FINER)) {
+
+ final StringBuilder sentenceWithPos = new StringBuilder();
+
+ sentenceWithPos.append("\"");
+
+ for (final Iterator<AnnotationFS> it = sentenceTokenAnnotationList.iterator(); it.hasNext();) {
+ final AnnotationFS token = it.next();
+ sentenceWithPos.append(token.getCoveredText());
+ sentenceWithPos.append('\\');
+ sentenceWithPos.append(token.getStringValue(this.posFeature));
+ sentenceWithPos.append(' ');
+ }
+
+ // delete last whitespace
+ if (sentenceWithPos.length() > 1) // not 0 because it contains already the " char
+ sentenceWithPos.setLength(sentenceWithPos.length() - 1);
+
+ sentenceWithPos.append("\"");
+
+ this.logger.log(Level.FINER, sentenceWithPos.toString());
+ }
+ }
+ }
+
+ /**
+ * Releases allocated resources.
+ */
+ @Override
+ public void destroy() {
+ this.posTagger = null;
+ }
+}
\ No newline at end of file