com.autsia.socialboot.businesslogic.nlp.processors.NLPProcessor.java Source code

Java tutorial

Introduction

Here is the source code for com.autsia.socialboot.businesslogic.nlp.processors.NLPProcessor.java

Source

/*
 * Copyright 2015 Dmytro Titov
 *
 * Licensed 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 com.autsia.socialboot.businesslogic.nlp.processors;

import com.autsia.socialboot.businesslogic.nlp.model.Sentiment;
import edu.stanford.nlp.ling.CoreAnnotations;
import edu.stanford.nlp.neural.rnn.RNNCoreAnnotations;
import edu.stanford.nlp.pipeline.Annotation;
import edu.stanford.nlp.pipeline.StanfordCoreNLP;
import edu.stanford.nlp.sentiment.SentimentCoreAnnotations;
import edu.stanford.nlp.trees.Tree;
import edu.stanford.nlp.util.CoreMap;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

/**
 * Nature Language Processor
 */
@Component
public class NLPProcessor {

    @Autowired
    private StanfordCoreNLP pipeline;

    /**
     * Finds sentiment of a message
     *
     * @param text Input text
     * @return Class of Sentiment
     */
    public Sentiment findSentiment(String text) {
        int mainSentiment = 0;
        if (StringUtils.isNotEmpty(text)) {
            int longest = 0;
            Annotation annotation = pipeline.process(text);
            for (CoreMap sentence : annotation.get(CoreAnnotations.SentencesAnnotation.class)) {
                Tree tree = sentence.get(SentimentCoreAnnotations.SentimentAnnotatedTree.class);
                int sentiment = RNNCoreAnnotations.getPredictedClass(tree);
                String partText = sentence.toString();
                if (partText.length() > longest) {
                    mainSentiment = sentiment;
                    longest = partText.length();
                }

            }
        }
        return Sentiment.valueOf(mainSentiment);
    }

}