Skip to content

Commit

Permalink
OPENNLP-1539 - Introduce parameter for POSTaggerME to configure outpu…
Browse files Browse the repository at this point in the history
…t POS tag format (#601)
  • Loading branch information
rzo1 authored May 29, 2024
1 parent ffb015a commit 24e17f1
Show file tree
Hide file tree
Showing 7 changed files with 400 additions and 82 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -14,38 +14,14 @@
* See the License for the specific language governing permissions and
* limitations under the License.
*/

package opennlp.tools.postag;

import java.io.IOException;

import org.junit.jupiter.api.Assertions;
import org.junit.jupiter.api.BeforeAll;
import org.junit.jupiter.api.Test;

public class POSTaggerMEIT {

private static POSTagger tagger;

@BeforeAll
public static void prepare() throws IOException {
tagger = new POSTaggerME("en");
}

@Test
void testPOSTagger() {

String[] tags = tagger.tag(new String[] {
"The",
"driver",
"got",
"badly",
"injured",
"."});

// TODO OPENNLP-1539 Adjust this depending on the POSFormat
String[] expected = {"DET", "NOUN", "VERB", "ADV", "VERB", "PUNCT"};
Assertions.assertArrayEquals(expected, tags);
}
/**
* Defines the format for part-of-speech tagging, i.e.
* <a href="https://www.ling.upenn.edu/courses/Fall_2003/ling001/penn_treebank_pos.html">PENN</a>
* or <a href="https://universaldependencies.org/u/feat/index.html">UD</a> format.
*/
public enum POSTagFormat {

UD, PENN, UNKNOWN
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,209 @@
/*
* 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.postag;

import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Objects;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

/**
* A mapping implementation for converting between different POS tag formats.
* This class supports conversion between Penn Treebank (PENN) and Universal Dependencies (UD) formats.
* The conversion is based on the <a href="https://universaldependencies.org/tagset-conversion/en-penn-uposf.html">Universal Dependencies conversion table.</a>
* Please note that when converting from UD to Penn format, there may be ambiguity in some cases.
*/
public class POSTagFormatMapper {

private static final Logger logger = LoggerFactory.getLogger(POSTagFormatMapper.class);

private static final Map<String, String> CONVERSION_TABLE_PENN_TO_UD = new HashMap<>();
private static final Map<String, String> CONVERSION_TABLE_UD_TO_PENN = new HashMap<>();

static {

This comment has been minimized.

Copy link
@x-wing

x-wing Jul 22, 2024

When call class POSTagFormatMapper method
private POSTagFormat guessModelTagFormat(String[] outcomes) {...}
with outcomes=[``,VB,DT,,,'',NNP,VBZ,CC,NN,RB,.,UH,PRP,MD,PRP$,IN,VBP,NNS,WDT,VBN,JJR,:,WP,VBD,TO,JJ,WRB,VBG,EX,CD,RBR,RP,PDT,NNPS,POS,-LRB-,-RRB-,JJS,RBS,FW,WP$,$,SYM,LS,#]
udMatches=1 due to "SYM"
pennMatches=44
The above method returns POSTagFormat.PENN which is obviously wrong.
I think the CONVERSION_TABLE_PENN_TO_UD and CONVERSION_TABLE_UD_TO_PENN are wrongly reversed in the code.
@rzo1 After update the dependency opennlp-tools from 2.3.3 to the latest 2.4.0 , this caused my existing NLP logic to break until I did this change in my exsting logic: change new POSTaggerME(posModel) to new POSTaggerME(posModel, POSTagFormat.PENN)

This comment has been minimized.

Copy link
@rzo1

rzo1 Jul 23, 2024

Author Contributor

@x-wing Yep. The default was changed to UD tag style because all new OpenNLP models (provided by us) are build in UD style and mixing it resulted in wrong behaviour in some cases (as shown in the related Jira).

Previously, it just assumed, that everything is PENN. If it tries to interpret a PENN-based model as UD, it will obviously fail.

I will quote the original intention from Jira:

Classic (legacy) POS models output tags in the PENN Treebank POS tag format.

The modern UD-based models, however, differ in the longer output format, e.g. "VB" (Penn) vs. "VERB" (UD). Extended (UD) word features are covered here: https://universaldependencies.org/u/feat/index.html

This difference results in mismatches and will cause existing IT / tests to fail, if executed. Luckily, a mapping table is found here: https://universaldependencies.org/tagset-conversion/en-penn-uposf.html

To provide compatibility for existing applications and/or use-cases, we need to provide a way to retrieve both POS formats.

Aims:

Introduce a constructor parameter for POSTaggerME to configure tag format / style: Penn or UD style
Implement a mapping between both POS tag formats: UD <==> Penn
Update the OpenNLP Manual to explain differences of POS tag format and configuration parameter
Conceptual idea:

new POSTaggerME("en") => by default: UD format "as is"
new POSTaggerME("en", POSTagFormat.PENN) => by intention, here: Penn style

tl;dr: Your fix by specifying the format of your model is correct here.

This comment has been minimized.

Copy link
@x-wing

x-wing Jul 23, 2024

@rzo1 It makes sense with your explanation. Please help me clarify just one thing which I was puzzled by.
With the input [``,VB,DT,,,'',NNP,VBZ,CC,NN,RB,.,UH,PRP,MD,PRP$,IN,VBP,NNS,WDT,VBN,JJR,:,WP,VBD,TO,JJ,WRB,VBG,EX,CD,RBR,RP,PDT,NNPS,POS,-LRB-,-RRB-,JJS,RBS,FW,WP$,$,SYM,LS,#]
Why the logic identify it as PENN instead of UD? I can see 44 matches are UD but identified by the logic as PENN.
FYI I am using this model: en-pos-maxent.bin
Also a none related question, the doc says I can now use through maven instead of downloading directly but I couldn't find any document about how to use models through maven.

This comment has been minimized.

Copy link
@rzo1

rzo1 Jul 23, 2024

Author Contributor

This input

[``,VB,DT,,,'',NNP,VBZ,CC,NN,RB,.,UH,PRP,MD,PRP$,IN,VBP,NNS,WDT,VBN,JJR,:,WP,VBD,TO,JJ,WRB,VBG,EX,CD,RBR,RP,PDT,NNPS,POS,-LRB-,-RRB-,JJS,RBS,FW,WP$,$,SYM,LS,#]

has 43 PENN tags and 1 UD tag (which is SYM and therefore ambiqious because SYM <-> SYM in both formats). For example, NNPS doesn't exist in the UD tag set. It is PROPN in UD. Details here: https://universaldependencies.org/tagset-conversion/en-penn-uposf.html

Bildschirmfoto 2024-07-23 um 20 43 37

en-pos-maxent.bin is an old model, i.e. you need to instantiate the pos tagger with PENN.


To use a mavenized OpenNLP model, you need to add the related model to your Maven project, see https://github.com/apache/opennlp-models

To find these models, you need a https://github.com/apache/opennlp/blob/main/opennlp-tools-models/src/main/java/opennlp/tools/models/ClassPathModelFinder.java (either the simple implementation, which doesn't work in all edge cases or via an additional dependeny to classgraph). You can find some inspiration here: https://github.com/apache/opennlp/blob/main/opennlp-tools-models/src/test/java/opennlp/tools/models/AbstractModelUsageTest.java

I agree, that we need to update the docs / examples on how to actually use this mechanism ;-) - I created https://issues.apache.org/jira/browse/OPENNLP-1598 for it.

This comment has been minimized.

Copy link
@x-wing

x-wing Jul 23, 2024

@rzo1 Thank you so much for the information!

This comment has been minimized.

Copy link
@rzo1

rzo1 Jul 25, 2024

Author Contributor

@x-wing I posted some example code in my PR: #641

/*
* This is a conversion table to convert PENN to UD format as described in
* https://universaldependencies.org/tagset-conversion/en-penn-uposf.html
*/
CONVERSION_TABLE_PENN_TO_UD.put("#", "SYM");
CONVERSION_TABLE_PENN_TO_UD.put("$", "SYM");
CONVERSION_TABLE_PENN_TO_UD.put("''", "PUNCT");
CONVERSION_TABLE_PENN_TO_UD.put(",", "PUNCT");
CONVERSION_TABLE_PENN_TO_UD.put("-LRB-", "PUNCT");
CONVERSION_TABLE_PENN_TO_UD.put("-RRB-", "PUNCT");
CONVERSION_TABLE_PENN_TO_UD.put(".", "PUNCT");
CONVERSION_TABLE_PENN_TO_UD.put(":", "PUNCT");
CONVERSION_TABLE_PENN_TO_UD.put("AFX", "ADJ");
CONVERSION_TABLE_PENN_TO_UD.put("CC", "CCONJ");
CONVERSION_TABLE_PENN_TO_UD.put("CD", "NUM");
CONVERSION_TABLE_PENN_TO_UD.put("DT", "DET");
CONVERSION_TABLE_PENN_TO_UD.put("EX", "PRON");
CONVERSION_TABLE_PENN_TO_UD.put("FW", "X");
CONVERSION_TABLE_PENN_TO_UD.put("HYPH", "PUNCT");
CONVERSION_TABLE_PENN_TO_UD.put("IN", "ADP");
CONVERSION_TABLE_PENN_TO_UD.put("JJ", "ADJ");
CONVERSION_TABLE_PENN_TO_UD.put("JJR", "ADJ");
CONVERSION_TABLE_PENN_TO_UD.put("JJS", "ADJ");
CONVERSION_TABLE_PENN_TO_UD.put("LS", "X");
CONVERSION_TABLE_PENN_TO_UD.put("MD", "VERB");
CONVERSION_TABLE_PENN_TO_UD.put("NIL", "X");
CONVERSION_TABLE_PENN_TO_UD.put("NN", "NOUN");
CONVERSION_TABLE_PENN_TO_UD.put("NNP", "PROPN");
CONVERSION_TABLE_PENN_TO_UD.put("NNPS", "PROPN");
CONVERSION_TABLE_PENN_TO_UD.put("NNS", "NOUN");
CONVERSION_TABLE_PENN_TO_UD.put("PDT", "DET");
CONVERSION_TABLE_PENN_TO_UD.put("POS", "PART");
CONVERSION_TABLE_PENN_TO_UD.put("PRP", "PRON");
CONVERSION_TABLE_PENN_TO_UD.put("PRP$", "DET");
CONVERSION_TABLE_PENN_TO_UD.put("RB", "ADV");
CONVERSION_TABLE_PENN_TO_UD.put("RBR", "ADV");
CONVERSION_TABLE_PENN_TO_UD.put("RBS", "ADV");
CONVERSION_TABLE_PENN_TO_UD.put("RP", "ADP");
CONVERSION_TABLE_PENN_TO_UD.put("SYM", "SYM");
CONVERSION_TABLE_PENN_TO_UD.put("TO", "PART");
CONVERSION_TABLE_PENN_TO_UD.put("UH", "INTJ");
CONVERSION_TABLE_PENN_TO_UD.put("VB", "VERB");
CONVERSION_TABLE_PENN_TO_UD.put("VBD", "VERB");
CONVERSION_TABLE_PENN_TO_UD.put("VBG", "VERB");
CONVERSION_TABLE_PENN_TO_UD.put("VBN", "VERB");
CONVERSION_TABLE_PENN_TO_UD.put("VBP", "VERB");
CONVERSION_TABLE_PENN_TO_UD.put("VBZ", "VERB");
CONVERSION_TABLE_PENN_TO_UD.put("WDT", "DET");
CONVERSION_TABLE_PENN_TO_UD.put("WP", "PRON");
CONVERSION_TABLE_PENN_TO_UD.put("WP$", "DET");
CONVERSION_TABLE_PENN_TO_UD.put("WRB", "ADV");

/*
* Note: The back conversion might lose information.
*/
CONVERSION_TABLE_UD_TO_PENN.put("ADJ", "JJ");
CONVERSION_TABLE_UD_TO_PENN.put("ADP", "IN");
CONVERSION_TABLE_UD_TO_PENN.put("ADV", "RB");
CONVERSION_TABLE_UD_TO_PENN.put("AUX", "MD");
CONVERSION_TABLE_UD_TO_PENN.put("CCONJ", "CC");
CONVERSION_TABLE_UD_TO_PENN.put("DET", "DT");
CONVERSION_TABLE_UD_TO_PENN.put("INTJ", "UH");
CONVERSION_TABLE_UD_TO_PENN.put("NOUN", "NN");
CONVERSION_TABLE_UD_TO_PENN.put("NUM", "CD");
CONVERSION_TABLE_UD_TO_PENN.put("PART", "RP");
CONVERSION_TABLE_UD_TO_PENN.put("PRON", "PRP");
CONVERSION_TABLE_UD_TO_PENN.put("PROPN", "NNP");
CONVERSION_TABLE_UD_TO_PENN.put("PUNCT", ".");
CONVERSION_TABLE_UD_TO_PENN.put("SCONJ", "IN");
CONVERSION_TABLE_UD_TO_PENN.put("SYM", "SYM");
CONVERSION_TABLE_UD_TO_PENN.put("VERB", "VB");
CONVERSION_TABLE_UD_TO_PENN.put("X", "FW");
}

private final POSTagFormat modelFormat;

protected POSTagFormatMapper(final String[] possibleOutcomes) {
this.modelFormat = guessModelTagFormat(possibleOutcomes);
}

/**
* Converts a a list of tags to the specified format.
*
* @param tags a list of tags to be converted.
* @return an array containing the converted tags with the same order and size as the given input list.
* Note: A given tag might be {@code ?} if no mapping for the given {@code tag} could be found.
*/
public String[] convertTags(List<String> tags) {
Objects.requireNonNull(tags, "Supplied tags must not be NULL.");
return tags.stream()
.map(this::convertTag)
.toArray(String[]::new);
}

/**
* Converts a given tag to the specified format.
*
* @param tag no restrictions on this parameter.
* @return the converted tag form or {@code ?} if no mapping for {@code tag} could be found.
*/
public String convertTag(String tag) {
switch (modelFormat) {
case UD -> {
return CONVERSION_TABLE_UD_TO_PENN.getOrDefault(tag, "?");
}
case PENN -> {
if ("NOUN".equals(tag)) {
logger.warn("Ambiguity detected: NN can be 'NN' or 'NNS' depending on the number. " +
"Returning 'NN'.");
}
if ("PART".equals(tag)) {
logger.warn("Ambiguity detected: PART can be 'RP' or 'TO'. Returning 'RP'.");
}
if ("PROPN".equals(tag)) {
logger.warn("Ambiguity detected: Can be 'NNP' or 'NNPS. Returning 'NNP'");
}
if ("PUNCT".equals(tag)) {
logger.warn("Ambiguity detected: PUNCT needs specific punctuation mapping. Returning '.'");
}
if ("VERB".equals(tag)) {
logger.warn("Ambiguity detected: VERB can be 'VB', 'VBD', 'VBG', 'VBN', 'VBP', 'VBZ'. " +
"Returning 'VERB'.");
}
return CONVERSION_TABLE_PENN_TO_UD.getOrDefault(tag, "?");
}
default -> {
return tag;
}
}
}

/**
*
* @return The guessed {@link POSTagFormat}. Guaranteed to be not {@code null}.
*/
public POSTagFormat getGuessedFormat() {
return this.modelFormat;
}

/**
* Guesses the {@link POSTagFormat} by using majority quorum.
* @param outcomes must not be {@code null}.
* @return the guessed {@link POSTagFormat}.
* If the given input was empty, {@link POSTagFormat#UNKNOWN} is returned.
*/
private POSTagFormat guessModelTagFormat(final String[] outcomes) {
Objects.requireNonNull(outcomes, "Outcomes must not be NULL.");
int udMatches = 0;
int pennMatches = 0;

for (String outcome : outcomes) {
if (CONVERSION_TABLE_UD_TO_PENN.containsKey(outcome)) {
udMatches++;
}
if (CONVERSION_TABLE_PENN_TO_UD.containsKey(outcome)) {
pennMatches++;
}
}

if (udMatches > pennMatches) {
return POSTagFormat.UD;
} else if (pennMatches > udMatches) {
return POSTagFormat.PENN;
} else {
logger.warn("Detected an unknown POS format.");
return POSTagFormat.UNKNOWN;
}
}
}
Loading

0 comments on commit 24e17f1

Please sign in to comment.