You are viewing a plain text version of this content. The canonical link for it is here.
Posted to commits@opennlp.apache.org by "krickert (via GitHub)" <gi...@apache.org> on 2026/10/05 11:33:10 UTC

Re: [PR] GH-1388: Load bundled Unicode data through one recoverable loader (opennlp)

krickert commented on code in PR #1373:
URL: https://github.com/apache/opennlp/pull/1373#discussion_r4183386984


##########
opennlp-core/opennlp-runtime/src/main/java/opennlp/tools/tokenize/uax29/ExtendedPictographic.java:
##########
@@ -55,31 +53,23 @@ private ExtendedPictographic() {
    * @throws IllegalArgumentException Thrown if the bundled data is malformed.
    */
   static BitSet members() {
-    BitSet set = members;
-    if (set == null) {
-      synchronized (ExtendedPictographic.class) {
-        set = members;
-        if (set == null) {
-          set = load();
-          members = set;
-        }
-      }
-    }
-    return set;
+    return MEMBERS.get();
   }
 
+  /**
+   * {@return the member set parsed from the bundled {@code ExtendedPictographic.txt} resource}
+   *
+   * @throws IllegalStateException Thrown if the resource is missing.
+   * @throws UncheckedIOException Thrown if the resource cannot be read.
+   * @throws IllegalArgumentException Thrown if the data is malformed.
+   */
   private static BitSet load() {
-    final BitSet set = new BitSet();
-    try (InputStream in = ExtendedPictographic.class.getResourceAsStream(RESOURCE)) {
-      if (in == null) {
-        throw new IllegalStateException("Missing Extended_Pictographic data resource: " + RESOURCE);
-      }
-      parse(in, set);
-    } catch (IOException e) {
-      throw new UncheckedIOException(
-          "Unable to read Extended_Pictographic data resource " + RESOURCE, e);
-    }
-    return set;
+    return BundledUnicodeData.load(ExtendedPictographic.class, RESOURCE, "Extended_Pictographic",
+        in -> {

Review Comment:
   much better looking than the traditional java syntax.



##########
opennlp-core/opennlp-runtime/src/main/java/opennlp/tools/tokenize/uax29/ExtendedPictographic.java:
##########
@@ -16,32 +16,30 @@
  */
 package opennlp.tools.tokenize.uax29;
 
-import java.io.BufferedReader;
 import java.io.IOException;
 import java.io.InputStream;
-import java.io.InputStreamReader;
 import java.io.UncheckedIOException;
-import java.nio.charset.StandardCharsets;
 import java.util.BitSet;
 
+import opennlp.tools.util.normalizer.BundledUnicodeData;
 import opennlp.tools.util.normalizer.HexCodePoints;
 
 /**
  * Checks the Unicode {@code Extended_Pictographic} property of a code point.
  *
  * <p>This is the one extra property the word boundary algorithm needs (rule WB3c), to keep emoji
- * zero-width-joiner sequences together. The data is loaded once from the {@code emoji-data.txt}
- * derived resource of the Unicode Character Database and stored in a {@link BitSet}, so membership
- * is an O(1) bit check.</p>
+ * zero-width-joiner sequences together. The data is loaded on first use from the bundled
+ * {@code ExtendedPictographic.txt} resource, the {@code Extended_Pictographic} lines extracted
+ * from the Unicode <a href="https://www.unicode.org/Public/UCD/latest/ucd/emoji/emoji-data.txt">
+ * {@code emoji-data.txt}</a>, and stored in a {@link BitSet}, so membership is an O(1) bit
+ * check.</p>
  */
 public final class ExtendedPictographic {
 
   private static final String RESOURCE = "ExtendedPictographic.txt";
 
-  // Volatile so the lazily built set is safely published: the double-checked accessor reads the
-  // field once, and a fully populated BitSet becomes visible to every thread that observes the
-  // non-null reference.
-  private static volatile BitSet members;
+  private static final BundledUnicodeData.Lazy<BitSet> MEMBERS =
+      new BundledUnicodeData.Lazy<>(ExtendedPictographic::load);

Review Comment:
   I like how self-documented this line of code is, it is a good justification for removing the comment above.



##########
opennlp-core/opennlp-runtime/src/main/java/opennlp/tools/util/normalizer/BundledUnicodeData.java:
##########
@@ -0,0 +1,204 @@
+/*
+ * 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.util.normalizer;
+
+import java.io.BufferedReader;
+import java.io.IOException;
+import java.io.InputStream;
+import java.io.InputStreamReader;
+import java.io.UncheckedIOException;
+import java.nio.charset.Charset;
+import java.nio.charset.StandardCharsets;
+import java.util.function.Supplier;
+
+import opennlp.tools.commons.Internal;
+import opennlp.tools.util.ArgumentChecks;
+
+/**
+ * Loads the line-based data files bundled with OpenNLP, such as the Unicode Character Database
+ * extracts and the project-authored emoji tables.
+ *
+ * <p>A load failure surfaces from every accessor call that triggers a load: an
+ * {@link IllegalStateException} for a missing resource, an {@link UncheckedIOException} for a
+ * resource that cannot be read, and the parser's {@link IllegalArgumentException} for malformed
+ * data. A {@link Lazy} holder does not cache a failed load, so a later call tries again.</p>
+ */
+@Internal
+public final class BundledUnicodeData {
+
+  private BundledUnicodeData() {
+  }
+
+  /**
+   * Parses a bundled data stream.
+   *
+   * @param <T> The type of the parsed data.
+   */
+  @FunctionalInterface
+  public interface Parser<T> {
+
+    /**
+     * Parses {@code in}.
+     *
+     * @param in The resource stream. Closed by the caller.
+     * @return The parsed data.
+     * @throws IOException Thrown if reading {@code in} fails.
+     */
+    T parse(InputStream in) throws IOException;
+  }
+
+  /**
+   * Receives one line of a data file.
+   */
+  @FunctionalInterface
+  public interface LineConsumer {
+
+    /**
+     * Accepts one line.
+     *
+     * @param line The line, without its terminator.
+     * @param lineNumber The one-based number of the line in the file.
+     */
+    void accept(String line, int lineNumber);
+  }
+
+  /**
+   * Holds data that is loaded on the first call to {@link #get()}. A load that throws is not
+   * cached, so every call until one succeeds runs the loader and throws its exception.
+   *
+   * @param <T> The type of the data.
+   */
+  public static final class Lazy<T> {
+
+    private final Supplier<T> loader;
+
+    // Volatile so the loaded value is safely published to every thread that reads it.
+    private volatile T value;
+
+    /**
+     * Creates a holder that has not loaded yet.
+     *
+     * @param loader Loads the data. Must not be {@code null} and must not return {@code null}.
+     * @throws IllegalArgumentException Thrown if {@code loader} is {@code null}.
+     */
+    public Lazy(Supplier<T> loader) {
+      this.loader = ArgumentChecks.requireNonNullArg(loader, "loader");
+    }
+
+    /**
+     * Returns the data, loading it on the first successful call.
+     *
+     * @return The loaded data.
+     * @throws IllegalStateException Thrown if the loader returns {@code null}.
+     * @throws RuntimeException Thrown as is if the loader fails; the next call loads again.
+     */
+    public T get() {
+      T v = value;
+      if (v == null) {
+        synchronized (this) {
+          v = value;
+          if (v == null) {
+            v = loader.get();
+            if (v == null) {
+              throw new IllegalStateException("loader returned null");
+            }
+            value = v;
+          }
+        }
+      }
+      return v;
+    }
+  }
+
+  /**
+   * Opens a resource next to {@code owner} and parses it.
+   *
+   * @param <T> The type of the parsed data.
+   * @param owner The class the resource name is resolved against. Must not be {@code null}.
+   * @param resource The resource name. Must not be {@code null}.
+   * @param description The kind of data, used in error messages, for example
+   *     {@code "Word_Break"}. Must not be {@code null}.
+   * @param parser Parses the opened stream. Must not be {@code null}.
+   * @return The parsed data.
+   * @throws IllegalArgumentException Thrown if an argument is {@code null}, or rethrown from
+   *     {@code parser} for malformed data.
+   * @throws IllegalStateException Thrown if the resource is missing.
+   * @throws UncheckedIOException Thrown if the resource cannot be read.
+   */
+  public static <T> T load(Class<?> owner, String resource, String description,
+                           Parser<T> parser) {
+    ArgumentChecks.requireNonNullArg(owner, "owner");
+    ArgumentChecks.requireNonNullArg(resource, "resource");
+    ArgumentChecks.requireNonNullArg(description, "description");
+    ArgumentChecks.requireNonNullArg(parser, "parser");
+    try (InputStream in = owner.getResourceAsStream(resource)) {
+      if (in == null) {
+        throw new IllegalStateException("Missing " + description + " data resource: " + resource);
+      }
+      return parser.parse(in);
+    } catch (IOException e) {
+      throw new UncheckedIOException(
+          "Unable to read " + description + " data resource " + resource, e);
+    }
+  }
+
+  /**
+   * Reads every line of {@code in} and closes it.
+   *
+   * @param in The stream to read. Must not be {@code null}.
+   * @param charset The encoding of {@code in}. Must not be {@code null}.
+   * @param consumer Receives each line with its number. Must not be {@code null}.
+   * @throws IOException Thrown if reading {@code in} fails.
+   * @throws IllegalArgumentException Thrown if an argument is {@code null}.
+   */
+  public static void forEachLine(InputStream in, Charset charset, LineConsumer consumer)
+      throws IOException {
+    ArgumentChecks.requireNonNullArg(in, "in");
+    ArgumentChecks.requireNonNullArg(charset, "charset");
+    ArgumentChecks.requireNonNullArg(consumer, "consumer");
+    try (BufferedReader reader = new BufferedReader(new InputStreamReader(in, charset))) {
+      String line;
+      int lineNumber = 0;
+      while ((line = reader.readLine()) != null) {
+        lineNumber++;
+        consumer.accept(line, lineNumber);
+      }
+    }
+  }
+
+  /**
+   * Reads the content lines of a UTF-8 data file in the Unicode Character Database layout and
+   * closes the stream. Each line is passed without its {@code #} comment and surrounding
+   * whitespace; lines that are empty after that are skipped but still counted.
+   *
+   * @param in The stream to read. Must not be {@code null}.
+   * @param consumer Receives each non-empty content line with its number. Must not be
+   *     {@code null}.
+   * @throws IOException Thrown if reading {@code in} fails.
+   * @throws IllegalArgumentException Thrown if an argument is {@code null}.
+   */
+  public static void forEachContentLine(InputStream in, LineConsumer consumer)
+      throws IOException {
+    ArgumentChecks.requireNonNullArg(consumer, "consumer");
+    forEachLine(in, StandardCharsets.UTF_8, (line, lineNumber) -> {
+      final String content = HexCodePoints.stripComment(line).strip();
+      if (!content.isEmpty()) {
+        consumer.accept(content, lineNumber);
+      }
+    });
+  }
+}

Review Comment:
   This is a really clean interface and nice improvement!!



##########
opennlp-core/opennlp-runtime/src/main/java/opennlp/tools/tokenize/uax29/ExtendedPictographic.java:
##########
@@ -16,32 +16,30 @@
  */
 package opennlp.tools.tokenize.uax29;
 
-import java.io.BufferedReader;
 import java.io.IOException;
 import java.io.InputStream;
-import java.io.InputStreamReader;
 import java.io.UncheckedIOException;
-import java.nio.charset.StandardCharsets;
 import java.util.BitSet;
 
+import opennlp.tools.util.normalizer.BundledUnicodeData;
 import opennlp.tools.util.normalizer.HexCodePoints;
 
 /**
  * Checks the Unicode {@code Extended_Pictographic} property of a code point.
  *
  * <p>This is the one extra property the word boundary algorithm needs (rule WB3c), to keep emoji
- * zero-width-joiner sequences together. The data is loaded once from the {@code emoji-data.txt}
- * derived resource of the Unicode Character Database and stored in a {@link BitSet}, so membership
- * is an O(1) bit check.</p>
+ * zero-width-joiner sequences together. The data is loaded on first use from the bundled
+ * {@code ExtendedPictographic.txt} resource, the {@code Extended_Pictographic} lines extracted
+ * from the Unicode <a href="https://www.unicode.org/Public/UCD/latest/ucd/emoji/emoji-data.txt">

Review Comment:
   https://www.unicode.org/Public/UCD/latest/ucd/emoji/emoji-data.txt isn't accurate; it's already referenced in other files too.  We do have the v18 branch open, and this typically only updates 1x a year, but it's not yet merged - so we're on v17.  We'll also add some of our own data in other enhancements, so I'd just reference the file and not the URL.  We should at least not make it "latest"



##########
opennlp-core/opennlp-runtime/src/main/java/opennlp/tools/tokenize/uax29/ExtendedPictographic.java:
##########
@@ -92,30 +82,22 @@ private static BitSet load() {
    * @throws IllegalArgumentException Thrown if a definition line is malformed.
    */
   static void parse(InputStream in, BitSet set) throws IOException {
-    try (BufferedReader reader =
-             new BufferedReader(new InputStreamReader(in, StandardCharsets.UTF_8))) {
-      String line;
-      while ((line = reader.readLine()) != null) {
-        final String content = HexCodePoints.stripComment(line).strip();
-        if (content.isEmpty()) {
-          continue;
-        }
-        // Only the code-point column is needed; the property value after ';' is implicit (this is a
-        // filtered single-property file), so a line with no ';' is taken whole -- unlike
-        // WordBreakProperty, whose value column is required.
-        final int semicolon = content.indexOf(';');
-        final String codePoints = (semicolon < 0 ? content : content.substring(0, semicolon)).strip();
-        final int[] range;
-        try {
-          range = HexCodePoints.parseRange(codePoints);
-        } catch (IllegalArgumentException e) {
-          // Fail loud naming the bad line, the same way the sibling loaders do.
-          throw new IllegalArgumentException(
-              "Malformed Extended_Pictographic data in " + RESOURCE + ": " + content, e);
-        }
-        set.set(range[0], range[1] + 1);
+    BundledUnicodeData.forEachContentLine(in, (content, lineNumber) -> {
+      // Only the code-point column is needed; the property value after ';' is implicit (this is a
+      // filtered single-property file), so a line with no ';' is taken whole -- unlike
+      // WordBreakProperty, whose value column is required.
+      final int semicolon = content.indexOf(';');
+      final String codePoints = (semicolon < 0 ? content : content.substring(0, semicolon)).strip();

Review Comment:
   strip() is unicode aware, but not fully - but totally not a big deal for this ticket.  As a future enhancement, we should make this in StringUtil for the full unicode whitespace.  I'll file it.  it's a (very) minor bug for now but good to follow so we can eventually make a claim that we're fully unicode compliant. 



-- 
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.

To unsubscribe, e-mail: commits-unsubscribe@opennlp.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org