NLP4J Java Library
repository·master·Indexed 41 days ago
https://github.com/emorynlp/nlp4jA Java-based Natural Language Processing library providing tools for dependency parsing via DEPParser, model size reduction with ModelReduce, and various CLI utilities including NLPDecode, DEPEvaluate, and AmbiguityClassGenerator. It includes the NLPSocketServer for exposing NLP services over a network using a specific message protocol.
What's inside NLP4J
- NLP4J is a Java-based Natural Language Processing (NLP) library. It provides tools for various NLP tasks, designed to be used within the Java ecosystem. For more detailed information, visit the official webpage: https://emorynlp.github.io/nlp4j
Protocol for communicating with NLPSocketServer
masterTo interact with the
NLPSocketServer, clients must follow a specific message format. The server reads input until it encounters the end-of-message delimiter!E@N#D$.Message Format:
[format]:[data_string]!E@N#D$format: A string indicating the encoding or format of the data (passed todecoder.decodeByteArray).data_string: The actual content to be processed by the NLP decoder.!E@N#D$: The required terminator constantNLPSocketServer.END.
Upon receiving a complete message, the server processes the data using the configured
NLPDecoderand writes the resulting byte array back to the client's output stream.static public final String END = "!E@N#D$";Use NLPDemo for command-line NLP decoding
masterThe
NLPDemoclass serves as a demonstration entrypoint for using the NLP4J decoding capabilities. It demonstrates two primary ways to use theNLPDecoder:- Decoding a single string: Pass a raw string to the
decode(String sentence)method to receive an array ofNLPNodeobjects representing the linguistic structure. - Decoding a file to an output stream: Use
decode(InputStream inputStream, PrintStream printStream, String format)to process an entire file and stream the results directly to a destination (likeSystem.out).
Note that the decoder requires a configuration file (typically an XML file) to initialize the linguistic models and pipeline.
// Initialize decoder with a configuration file NLPDecoder nlp4j = new NLPDecoder(IOUtils.createFileInputStream("path/to/config-decode-en.xml")); // Option 1: Decode a single sentence NLPNode[] nodes = nlp4j.decode("John bought a car for Mary."); // Option 2: Decode an entire file to standard output using a specific format nlp4j.decode(IOUtils.createFileInputStream("path/to/input.txt"), System.out, AbstractNLPDecoder.FORMAT_RAW);- Decoding a single string: Pass a raw string to the
Use RadiologyDecode to process radiology data
masterThe
RadiologyDecodeclass serves as a programmatic entry point for decoding radiology-specific data using theNLPDecoder. It iterates through a directory of input files (e.g.,.txt) and applies decoding logic to produce output files (e.g.,.tsv) in a specified format.To use this logic, you need:
- A configuration file (XML format) passed to the
NLPDecoderconstructor. - An input directory containing the files to be processed.
- An input file extension to filter files.
- An output file extension for the results.
- An output format, such as
AbstractNLPDecoder.FORMAT_LINE.
// Configuration and paths final String configFile = "/path/to/config-decode-deident.xml"; final String inputDir = "/path/to/radiology/input"; final String inputExt = "txt"; final String outputExt = "tsv"; final String outputFormat = AbstractNLPDecoder.FORMAT_LINE; // Initialize the decoder with the config file NLPDecoder nlp4j = new NLPDecoder(IOUtils.createFileInputStream(configFile)); // Process files in the input directory for (String inputFile : FileUtils.getFileList(inputDir, inputExt)) { String outputFile = inputFile + "." + outputExt; nlp4j.decode( IOUtils.createFileInputStream(inputFile), IOUtils.createFileOutputStream(outputFile), outputFormat ); }- A configuration file (XML format) passed to the
Extract Brown clusters programmatically with getBrownClusters()
masterIf you are working within the Java environment, you can use the
getBrownClusters(InputStream in)method to parse Brown cluster data from an input stream.This method reads tab-separated lines where:
- The first column contains the cluster hierarchy string.
- The second column contains the cluster identifier.
The method iterates through the hierarchy string to extract all prefix substrings (at even intervals) and maps the identifier to the set of these prefixes.
Returns: A
Map<String, Set<String>>where the key is the cluster identifier (from the second column) and the value is aSet<String>containing the hierarchical prefixes extracted from the first column.Map<String, Set<String>> tree = BrownClusterExtract.getBrownClusters(new FileInputStream(INPUT_FILE));Decode files with NLPDecoder.decode()
masterThe
NLPDecoder.decodemethod is the core operation for transforming input text into decoded output. It requires an input stream, an output stream, and a specified output format.Method Signature (Inferred):
void decode(InputStream inputStream, OutputStream outputStream, String outputFormat)Parameters:
inputStream: The source stream containing the text to be decoded.outputStream: The destination stream where the decoded results will be written.outputFormat: A string representing the desired output format (e.g.,AbstractNLPDecoder.FORMAT_LINE).
Use TokenizeIt for specialized tokenization and decoding
masterThe
TokenizeItclass is a utility designed to process TSV files containing tokens and their features. It uses anEnglishTokenizerto segmentize tokens and anNLPDecoderto decode them into anNLPNodearray based on a provided configuration file.Key Functionalities:
- Batch Conversion: The
convert(String inputDir, String outputDir)method processes all.tsvfiles in a specified input directory and saves the results to the output directory. - Stream Processing: The
convert(InputStream in, OutputStream out)method allows for processing individual input streams. - Validation: The
check(NLPNode[] nodes)method performs a specific validation check on the decoded nodes, looking for inconsistencies between the lemma (e.g., "it" or "its") and the associated features.
Input Format
The input TSV files are expected to have a format where each line contains a token form and its features separated by a tab:
[token_form]\t[features]// Example of manual instantiation and batch conversion String configFile = "path/to/config-decode-en.xml"; String inputDir = "/path/to/input_tsv_dir"; String outputDir = "/path/to/output_dir"; TokenizeIt tokenizer = new TokenizeIt(configFile); tokenizer.convert(inputDir, outputDir);- Batch Conversion: The
Use CSVSentiment for sentiment data processing
masterThe
CSVSentimentclass provides utilities for processing sentiment-labeled CSV files. It can convert CSV data into different formats (TSV or TXT) or perform NLP decoding to categorize sentiment.Input CSV Format Requirements: Based on the implementation, the class expects a CSV where:
- The first column (index 0) contains the sentiment label (e.g.,
positive,negative, orobjective). - The seventh column (index 6) contains the text content to be processed.
- The first row is treated as a header and is skipped.
Available Methods:
toTSV(String inputFile): Converts the CSV to a Tab-Separated Values format. Each line in the output follows the pattern:[integer_label]\t[tokenized_text]. Labels are mapped as follows:positive$\rightarrow$0negative$\rightarrow$1objective$\rightarrow$2
toTXT(String inputFile): Extracts only the text content (column 6) from the CSV and saves it to a.txtfile.categorize(String inputFile): Uses anNLPDecoderto process the text. It attaches the sentiment label as a feature (sent) to the NLP nodes and saves the decoded structure to individual.nlpfiles for each record.
// Example: Converting a CSV to TSV format CSVSentiment cvs = new CSVSentiment(); cvs.toTSV("path/to/input.csv"); // Example: Categorizing sentiment using a configuration file CSVSentiment cvs = new CSVSentiment("path/to/config-decode-en.xml"); cvs.categorize("path/to/input.csv");- The first column (index 0) contains the sentiment label (e.g.,
Tokenize radiology CSV data with CSVRadiology
masterThe
tokenizemethod processes a radiology CSV file by segmenting the text in the first column of each record using anEnglishTokenizer.Key behaviors:
- Input Format: Expects a CSV file where the first column (index 0) contains the text to be tokenized.
- Output Generation: For each record in the CSV, a new
.txtfile is created in the same directory as the input file. The files are zero-padded (e.g.,0001.txt,0100.txt) based on theoutputStartindex. - Text Normalization: During the printing process, the tool applies regex patterns to specific radiology headers (defined in
BEFOREandAFTERarrays) to ensure consistent newline placement. It also trims whitespace and removes empty lines. - Parameters:
inputFile: The path to the source CSV file.outputStart: An integer used to offset the starting filename index for the generated text files.
CSVRadiology cvs = new CSVRadiology(); // Tokenizes the CSV and starts naming output files from index 500 cvs.tokenize("/path/to/radiology_reports.csv", 500);AmbiguityClassGenerator API Reference
masterThe
AmbiguityClassGeneratorclass provides methods for reading training data and exporting the resulting ambiguity vocabulary.readTrain(Bigram<String,String> bigram, String dirpath, boolean uncaptialized)Reads training files from the specified directory and populates the provided
bigramobject.- dirpath: Directory containing training files. Files are processed using
FileUtils.getFileList(dirpath, "*"). - uncaptialized: If true, words are converted to a simplified form using
StringUtils.toSimplifiedForm. - File Format: Expects tab-separated files where the word is at index 1 (
t[1]) and the tag is at index 3 (t[3]). - Filtering: Automatically skips forms containing underscores (
_) or non-ASCII characters (>= 128).
printVocab(Bigram<String,String> bigram, String outputFile, int cutoff, double threshold)Processes the collected bigrams to generate a vocabulary map and writes it to a file.
- cutoff: Only words with a total unigram count $\ge$
cutoffare considered. - threshold: Uses
unigram.toList(threshold)to filter associated tags. - Exclusion Rule: If a word has only one tag and that tag is
NNPorNNPS, it is excluded from the output. - Output Format: A serialized
Map<String, List<String>>where the key is the word and the value is a list of its possible tags, sorted by frequency. The file is written usingIOUtils.createObjectXZBufferedOutputStream.
- dirpath: Directory containing training files. Files are processed using
Decode text using NLPDecoder
masterThe
NLPDecoderis the primary class for performing linguistic analysis. It is initialized using anInputStreampointing to a configuration XML file.Methods
decode(String sentence): Takes a single sentence as input and returns an array ofNLPNodeobjects.decode(InputStream inputStream, PrintStream printStream, String format): Processes an input stream and writes the decoded results to the providedPrintStreamusing the specified format (e.g.,AbstractNLPDecoder.FORMAT_RAW).
Use DEPParser for dependency parsing
masterThe
DEPParser<N>class is a component used to perform dependency parsing on a sequence of nodes. It extendsOnlineComponentand operates on nodes of typeNwhich must extendAbstractNLPNode<N>.It can be initialized using a default constructor or by providing an
InputStreamfor configuration.Key behaviors:
- Initialization: Use
new DEPParser()for default settings ornew DEPParser(InputStream configuration)to load specific configurations. - Evaluation: The parser uses
DEPEvalas its evaluator, which can be retrieved viacreateEvaluator(). - State Management: It manages parsing state via
DEPState<N>, which tracks the stack and input during the parsing process.
// Example initialization DEPParser<MyNLPNode> parser = new DEPParser<>(); // Or with configuration DEPParser<MyNLPNode> parserWithConfig = new DEPParser(configInputStream);- Initialization: Use