You are viewing a plain text version of this content. The canonical link for it is here.
Posted to commits@opennlp.apache.org by kr...@apache.org on 2026/08/16 01:12:57 UTC

(opennlp) 04/06: OPENNLP-1897: Accept a plain per-token normalizer for term identity

This is an automated email from the ASF dual-hosted git repository.

krickert pushed a commit to branch OPENNLP-1897-term-vectors
in repository https://gitbox.apache.org/repos/asf/opennlp.git

commit 72889e74b2f4ee72ff59ef8b21237ea8aceb288f
Author: Kristian Rickert <kr...@gmail.com>
AuthorDate: Mon Aug 10 01:21:41 2026 -0400

    OPENNLP-1897: Accept a plain per-token normalizer for term identity
    
    The documented normalization workflow could not be built with any commonly
    wanted normalizer: TextNormalizer.Builder.buildAligned() rejects caseFold,
    nfc, nfkc, and accent folding, so the only OffsetAwareNormalizer chains the
    annotator accepted were the per-code-point folds. The restriction is
    unnecessary here because the occurrence spans the annotator emits are always
    the token's own span in the original text; the normalized text is used only
    as the term key.
    
    Add TermVectorAnnotator(CharSequenceNormalizer) and
    TermVectorAnnotator(CharSequenceNormalizer, Mode) as the general path: the
    normalizer is applied to each token's covered text to produce the term, the
    span stays the token's original span, and any normalizer works (case fold,
    NFC, accent fold, stemmer-backed). The OffsetAwareNormalizer constructors
    keep their whole-document aligned behavior unchanged; their javadoc now
    points at the plain-normalizer constructors as the general path. Tokens that
    normalize to the empty string still collapse into one empty term on both
    paths, pinned by matching tests.
    
    Red evidence: the new tests cannot compile against the old API (no suitable
    constructor found for TermVectorAnnotator(CharSequenceNormalizer)), so the
    tests and the fix land together in this commit. The negative pin that
    builder().caseFold().buildAligned() throws IllegalStateException already
    exists in AlignedNormalizerPipelineTest and is not duplicated.
---
 .../tools/termvector/TermVectorAnnotator.java      | 93 ++++++++++++++++++----
 .../tools/termvector/TermVectorAnnotatorTest.java  | 80 +++++++++++++++++++
 2 files changed, 157 insertions(+), 16 deletions(-)

diff --git a/opennlp-api/src/main/java/opennlp/tools/termvector/TermVectorAnnotator.java b/opennlp-api/src/main/java/opennlp/tools/termvector/TermVectorAnnotator.java
index e30dd6e7a..27282db16 100644
--- a/opennlp-api/src/main/java/opennlp/tools/termvector/TermVectorAnnotator.java
+++ b/opennlp-api/src/main/java/opennlp/tools/termvector/TermVectorAnnotator.java
@@ -30,6 +30,7 @@ import opennlp.tools.document.LayerKey;
 import opennlp.tools.document.Layers;
 import opennlp.tools.util.Span;
 import opennlp.tools.util.normalizer.AlignedText;
+import opennlp.tools.util.normalizer.CharSequenceNormalizer;
 import opennlp.tools.util.normalizer.OffsetAwareNormalizer;
 
 /**
@@ -39,15 +40,18 @@ import opennlp.tools.util.normalizer.OffsetAwareNormalizer;
  *
  * <p>Term identity comes from the annotator's inputs, not from logic of its own. Without
  * a normalizer, the term is the token layer's value as-is, that is, the token's covered
- * text in the original document. With an {@link OffsetAwareNormalizer}, the whole
- * document text is normalized once with its alignment recorded, each token span is
- * mapped forward to the normalized form, and the covered normalized text is the term, so
- * tokens that differ only by a normalization fold (case, an eszett expansion, collapsed
- * whitespace) group together. Either way, the occurrence spans emitted in
- * {@link Mode#FULL full mode} are the token layer's own spans and therefore always
- * point into the original text. A token whose normalized form is empty, for example one
- * the normalizer deleted entirely, groups under the empty string rather than being
- * dropped.</p>
+ * text in the original document. With a plain {@link CharSequenceNormalizer}, the general
+ * path, each token's covered text is normalized on its own to produce the term, so any
+ * normalizer works: case folding, NFC, accent folding, a stemmer-backed normalizer. With
+ * an {@link OffsetAwareNormalizer}, the whole document text is normalized once with its
+ * alignment recorded, each token span is mapped forward to the normalized form, and the
+ * covered normalized text is the term; this path can see across token boundaries but is
+ * limited to alignment-reporting normalizers. On every path, tokens that differ only by
+ * a normalization fold (case, an eszett expansion, collapsed whitespace) group together,
+ * and the occurrence spans emitted in {@link Mode#FULL full mode} are the token layer's
+ * own spans and therefore always point into the original text. A token whose normalized
+ * form is empty, for example one the normalizer deleted entirely, groups under the empty
+ * string rather than being dropped.</p>
  *
  * <p>The layer is {@link LayerKey.Scope#DOCUMENT document-scoped}: each {@link TermVector}
  * is a whole-document statistic, so the annotations carry no span of their own and the
@@ -82,6 +86,7 @@ public class TermVectorAnnotator implements DocumentAnnotator {
   }
 
   private final OffsetAwareNormalizer normalizer;
+  private final CharSequenceNormalizer tokenNormalizer;
   private final Mode mode;
 
   /**
@@ -103,12 +108,57 @@ public class TermVectorAnnotator implements DocumentAnnotator {
       throw new IllegalArgumentException("mode must not be null");
     }
     this.normalizer = null;
+    this.tokenNormalizer = null;
     this.mode = mode;
   }
 
   /**
    * Initializes a {@link Mode#FULL full mode} annotator that groups tokens by their
-   * normalized form.
+   * per-token normalized form. This is the general path: the normalizer is applied to
+   * each token's covered text on its own, so any {@link CharSequenceNormalizer} works,
+   * including the folds that cannot report an alignment (case folding, NFC, accent
+   * folding, stemmer-backed normalizers). The occurrence spans stay the tokens' own
+   * spans in the original text.
+   *
+   * @param normalizer The normalizer that defines term identity, applied to each token's
+   *                   covered text. Must not be {@code null}.
+   * @throws IllegalArgumentException Thrown if {@code normalizer} is {@code null}.
+   */
+  public TermVectorAnnotator(CharSequenceNormalizer normalizer) {
+    this(normalizer, Mode.FULL);
+  }
+
+  /**
+   * Initializes an annotator that groups tokens by their per-token normalized form. This
+   * is the general path: the normalizer is applied to each token's covered text on its
+   * own, so any {@link CharSequenceNormalizer} works, including the folds that cannot
+   * report an alignment (case folding, NFC, accent folding, stemmer-backed normalizers).
+   * The occurrence spans stay the tokens' own spans in the original text.
+   *
+   * @param normalizer The normalizer that defines term identity, applied to each token's
+   *                   covered text. Must not be {@code null}.
+   * @param mode How much each {@link TermVector} records. Must not be {@code null}.
+   * @throws IllegalArgumentException Thrown if {@code normalizer} or {@code mode} is
+   *         {@code null}.
+   */
+  public TermVectorAnnotator(CharSequenceNormalizer normalizer, Mode mode) {
+    if (normalizer == null) {
+      throw new IllegalArgumentException("normalizer must not be null");
+    }
+    if (mode == null) {
+      throw new IllegalArgumentException("mode must not be null");
+    }
+    this.normalizer = null;
+    this.tokenNormalizer = normalizer;
+    this.mode = mode;
+  }
+
+  /**
+   * Initializes a {@link Mode#FULL full mode} annotator that groups tokens by their
+   * normalized form through a whole-document alignment. Prefer the
+   * {@link #TermVectorAnnotator(CharSequenceNormalizer) plain-normalizer constructor}
+   * as the general path; this one only accepts alignment-reporting normalizers but can
+   * see across token boundaries, for example a whitespace collapse spanning two tokens.
    *
    * @param normalizer The normalizer that defines term identity, applied to the whole
    *                   document text so token spans can be mapped into the normalized
@@ -120,7 +170,12 @@ public class TermVectorAnnotator implements DocumentAnnotator {
   }
 
   /**
-   * Initializes an annotator that groups tokens by their normalized form.
+   * Initializes an annotator that groups tokens by their normalized form through a
+   * whole-document alignment. Prefer the
+   * {@link #TermVectorAnnotator(CharSequenceNormalizer, Mode) plain-normalizer
+   * constructor} as the general path; this one only accepts alignment-reporting
+   * normalizers but can see across token boundaries, for example a whitespace collapse
+   * spanning two tokens.
    *
    * @param normalizer The normalizer that defines term identity, applied to the whole
    *                   document text so token spans can be mapped into the normalized
@@ -137,6 +192,7 @@ public class TermVectorAnnotator implements DocumentAnnotator {
       throw new IllegalArgumentException("mode must not be null");
     }
     this.normalizer = normalizer;
+    this.tokenNormalizer = null;
     this.mode = mode;
   }
 
@@ -231,17 +287,22 @@ public class TermVectorAnnotator implements DocumentAnnotator {
   }
 
   /**
-   * Determines the term one token groups under: its covered text as-is, or the covered
-   * text of its span mapped into the normalized form when a normalizer is present.
+   * Determines the term one token groups under: its covered text as-is, its covered text
+   * normalized on its own when a plain per-token normalizer is present, or the covered
+   * text of its span mapped into the normalized form when an offset-aware normalizer is
+   * present.
    *
    * @param token The token annotation.
    * @param aligned The normalized document text with its alignment, or {@code null}
-   *                when no normalizer is present.
-   * @param normalized The normalized document text, or {@code null} when no normalizer is
-   *                   present.
+   *                when no offset-aware normalizer is present.
+   * @param normalized The normalized document text, or {@code null} when no offset-aware
+   *                   normalizer is present.
    * @return The term string. Never {@code null}, possibly empty.
    */
   private String termOf(Annotation<String> token, AlignedText aligned, String normalized) {
+    if (tokenNormalizer != null) {
+      return tokenNormalizer.normalize(token.value()).toString();
+    }
     if (aligned == null) {
       return token.value();
     }
diff --git a/opennlp-api/src/test/java/opennlp/tools/termvector/TermVectorAnnotatorTest.java b/opennlp-api/src/test/java/opennlp/tools/termvector/TermVectorAnnotatorTest.java
index ee6f852cd..03eeb130b 100644
--- a/opennlp-api/src/test/java/opennlp/tools/termvector/TermVectorAnnotatorTest.java
+++ b/opennlp-api/src/test/java/opennlp/tools/termvector/TermVectorAnnotatorTest.java
@@ -32,6 +32,7 @@ import opennlp.tools.document.Layers;
 import opennlp.tools.util.Span;
 import opennlp.tools.util.normalizer.AlignedText;
 import opennlp.tools.util.normalizer.Alignment;
+import opennlp.tools.util.normalizer.CharSequenceNormalizer;
 import opennlp.tools.util.normalizer.OffsetAwareNormalizer;
 
 import static org.junit.jupiter.api.Assertions.assertEquals;
@@ -135,6 +136,21 @@ public class TermVectorAnnotatorTest {
 
   private static final OffsetAwareNormalizer DROP_DIGITS = new DigitDeletingNormalizer();
 
+  /**
+   * A plain, alignment-free case folder for the per-token path: it stands in for the
+   * shipped normalizers (case fold, NFC, accent fold) that cannot report offsets and
+   * therefore cannot implement {@link OffsetAwareNormalizer}.
+   */
+  private static final CharSequenceNormalizer PLAIN_LOWER =
+      text -> text.toString().toLowerCase(Locale.ROOT);
+
+  /**
+   * A plain normalizer that deletes every digit, so a token made up of digits alone
+   * normalizes to the empty string on the per-token path.
+   */
+  private static final CharSequenceNormalizer PLAIN_DROP_DIGITS =
+      text -> text.toString().replaceAll("\\d", "");
+
   /**
    * Splits a text on single space characters into a token layer, skipping the empty
    * tokens a collapsed run would produce, so double spaces yield no tokens.
@@ -266,6 +282,70 @@ public class TermVectorAnnotatorTest {
     assertEquals(TermVector.count("gross", 3), vectors.get(0).value());
   }
 
+  /**
+   * The general per-token path: a plain {@link CharSequenceNormalizer} defines term
+   * identity by folding each token's covered text, no alignment involved, while every
+   * occurrence span stays the token's own span in the original text. This admits the
+   * folds {@code buildAligned()} rejects (case fold, NFC, accent fold).
+   */
+  @Test
+  void testPlainNormalizerGroupsFoldedTokensWithOriginalSpans() {
+    final String text = "Word word WORD";
+    final Document document = new TermVectorAnnotator(PLAIN_LOWER)
+        .annotate(documentWithTokens(text));
+
+    final List<Annotation<TermVector>> vectors =
+        document.get(TermVectorAnnotator.TERM_VECTORS);
+    assertEquals(1, vectors.size());
+    assertEquals(new TermVector("word", 3,
+        List.of(new Span(0, 4), new Span(5, 9), new Span(10, 14))), vectors.get(0).value());
+
+    // Every occurrence span covers the original surface form, not the folded one.
+    final List<String> surfaceForms = vectors.get(0).value().spans().stream()
+        .map(s -> s.getCoveredText(text).toString()).toList();
+    assertEquals(List.of("Word", "word", "WORD"), surfaceForms);
+  }
+
+  @Test
+  void testPlainNormalizerScoringOnlyModeCountsWithoutOffsets() {
+    final Document document = new TermVectorAnnotator(PLAIN_LOWER,
+        TermVectorAnnotator.Mode.SCORING_ONLY).annotate(documentWithTokens("Word word WORD"));
+
+    final List<Annotation<TermVector>> vectors =
+        document.get(TermVectorAnnotator.TERM_VECTORS);
+    assertEquals(1, vectors.size());
+    assertEquals(TermVector.count("word", 3), vectors.get(0).value());
+  }
+
+  /**
+   * The empty-term bucket behaves identically on the per-token path: tokens a plain
+   * normalizer folds to the empty string group under one {@code ""} term with their
+   * original spans, matching {@link #testTokensNormalizedAwayGroupUnderTheEmptyTerm()}.
+   */
+  @Test
+  void testPlainNormalizerFoldsDeletedTokensIntoTheEmptyTerm() {
+    final Document document = new TermVectorAnnotator(PLAIN_DROP_DIGITS)
+        .annotate(documentWithTokens("dog 42 dog 7"));
+
+    final List<Annotation<TermVector>> vectors =
+        document.get(TermVectorAnnotator.TERM_VECTORS);
+    assertEquals(2, vectors.size());
+    assertEquals(new TermVector("dog", 2, List.of(new Span(0, 3), new Span(7, 10))),
+        vectors.get(0).value());
+    assertEquals(new TermVector("", 2, List.of(new Span(4, 6), new Span(11, 12))),
+        vectors.get(1).value());
+  }
+
+  @Test
+  void testNullPlainNormalizerIsRejected() {
+    final CharSequenceNormalizer noNormalizer = null;
+    assertThrows(IllegalArgumentException.class, () -> new TermVectorAnnotator(noNormalizer));
+    assertThrows(IllegalArgumentException.class,
+        () -> new TermVectorAnnotator(noNormalizer, TermVectorAnnotator.Mode.FULL));
+    assertThrows(IllegalArgumentException.class,
+        () -> new TermVectorAnnotator(PLAIN_LOWER, null));
+  }
+
   /**
    * A token the normalizer deletes entirely groups under the empty string instead of
    * being dropped, so the term vector layer still accounts for every token.