Search in sources :

Example 1 with DetectSentimentResult

use of com.amazonaws.services.comprehend.model.DetectSentimentResult in project amplify-android by aws-amplify.

the class AWSComprehendService method fetchSentiment.

private Sentiment fetchSentiment(String text, LanguageType language) throws PredictionsException {
    // Skip if configuration specifies NOT sentiment
    if (!isResourceConfigured(InterpretTextConfiguration.InterpretType.SENTIMENT)) {
        return null;
    }
    DetectSentimentRequest request = new DetectSentimentRequest().withText(text).withLanguageCode(language.getLanguageCode());
    // Detect sentiment from given text via AWS Comprehend
    final DetectSentimentResult result;
    try {
        result = comprehend.detectSentiment(request);
    } catch (AmazonClientException serviceException) {
        throw new PredictionsException("AWS Comprehend encountered an error while detecting sentiment.", serviceException, "See attached service exception for more details.");
    }
    // Convert AWS Comprehend's detection result to Amplify-compatible format
    String comprehendSentiment = result.getSentiment();
    SentimentScore sentimentScore = result.getSentimentScore();
    SentimentType predominantSentiment = SentimentTypeAdapter.fromComprehend(comprehendSentiment);
    final float score;
    switch(predominantSentiment) {
        case POSITIVE:
            score = sentimentScore.getPositive();
            break;
        case NEGATIVE:
            score = sentimentScore.getNegative();
            break;
        case NEUTRAL:
            score = sentimentScore.getNeutral();
            break;
        case MIXED:
            score = sentimentScore.getMixed();
            break;
        default:
            score = 0f;
    }
    return Sentiment.builder().value(predominantSentiment).confidence(score * PERCENT).build();
}
Also used : DetectSentimentResult(com.amazonaws.services.comprehend.model.DetectSentimentResult) DetectSentimentRequest(com.amazonaws.services.comprehend.model.DetectSentimentRequest) AmazonClientException(com.amazonaws.AmazonClientException) PredictionsException(com.amplifyframework.predictions.PredictionsException) SentimentScore(com.amazonaws.services.comprehend.model.SentimentScore) SentimentType(com.amplifyframework.predictions.models.SentimentType)

Aggregations

AmazonClientException (com.amazonaws.AmazonClientException)1 DetectSentimentRequest (com.amazonaws.services.comprehend.model.DetectSentimentRequest)1 DetectSentimentResult (com.amazonaws.services.comprehend.model.DetectSentimentResult)1 SentimentScore (com.amazonaws.services.comprehend.model.SentimentScore)1 PredictionsException (com.amplifyframework.predictions.PredictionsException)1 SentimentType (com.amplifyframework.predictions.models.SentimentType)1