Search in sources :

Example 1 with Sentiment

use of com.amplifyframework.predictions.models.Sentiment in project amplify-android by aws-amplify.

the class AWSPredictionsInterpretTest method testNegativeSentimentDetection.

/**
 * Assert that unhappy review is detected as negative.
 * @throws Exception if prediction fails
 */
@Test
public void testNegativeSentimentDetection() throws Exception {
    // Interpret negative text and assert non-null result
    final String negativeReview = Assets.readAsString("negative-review.txt");
    InterpretResult result = predictions.interpret(negativeReview);
    assertNotNull(result);
    // Assert detected sentiment is negative
    Sentiment sentiment = result.getSentiment();
    FeatureAssert.assertMatches(SentimentType.NEGATIVE, sentiment);
}
Also used : InterpretResult(com.amplifyframework.predictions.result.InterpretResult) Sentiment(com.amplifyframework.predictions.models.Sentiment) Test(org.junit.Test)

Example 2 with Sentiment

use of com.amplifyframework.predictions.models.Sentiment in project amplify-android by aws-amplify.

the class AWSComprehendService method comprehend.

void comprehend(@NonNull String text, @NonNull Consumer<InterpretResult> onSuccess, @NonNull Consumer<PredictionsException> onError) {
    try {
        // First obtain the dominant language to begin analysis
        final Language dominantLanguage = fetchPredominantLanguage(text);
        final LanguageType language = dominantLanguage.getValue();
        // Actually analyze text in the context of dominant language
        final Sentiment sentiment = fetchSentiment(text, language);
        final List<KeyPhrase> keyPhrases = fetchKeyPhrases(text, language);
        final List<Entity> entities = fetchEntities(text, language);
        final List<Syntax> syntax = fetchSyntax(text, language);
        onSuccess.accept(InterpretResult.builder().language(dominantLanguage).sentiment(sentiment).keyPhrases(keyPhrases).entities(entities).syntax(syntax).build());
    } catch (PredictionsException exception) {
        onError.accept(exception);
    }
}
Also used : Entity(com.amplifyframework.predictions.models.Entity) DominantLanguage(com.amazonaws.services.comprehend.model.DominantLanguage) Language(com.amplifyframework.predictions.models.Language) PredictionsException(com.amplifyframework.predictions.PredictionsException) Syntax(com.amplifyframework.predictions.models.Syntax) LanguageType(com.amplifyframework.predictions.models.LanguageType) Sentiment(com.amplifyframework.predictions.models.Sentiment) KeyPhrase(com.amplifyframework.predictions.models.KeyPhrase)

Example 3 with Sentiment

use of com.amplifyframework.predictions.models.Sentiment in project amplify-android by aws-amplify.

the class AWSPredictionsInterpretTest method testPositiveSentimentDetection.

/**
 * Assert that happy review is detected as positive.
 * @throws Exception if prediction fails
 */
@Test
public void testPositiveSentimentDetection() throws Exception {
    // Interpret positive text and assert non-null result
    final String positiveReview = Assets.readAsString("positive-review.txt");
    InterpretResult result = predictions.interpret(positiveReview);
    assertNotNull(result);
    // Assert detected sentiment is positive
    Sentiment sentiment = result.getSentiment();
    FeatureAssert.assertMatches(SentimentType.POSITIVE, sentiment);
}
Also used : InterpretResult(com.amplifyframework.predictions.result.InterpretResult) Sentiment(com.amplifyframework.predictions.models.Sentiment) Test(org.junit.Test)

Example 4 with Sentiment

use of com.amplifyframework.predictions.models.Sentiment in project amplify-android by aws-amplify.

the class TensorFlowTextClassificationService method classify.

/**
 * Classifies text to analyze associated sentiments.
 * @param text the text to classify
 * @param onSuccess notified when classification succeeds
 * @param onError notified when classification fails
 */
void classify(@NonNull String text, @NonNull Consumer<InterpretResult> onSuccess, @NonNull Consumer<PredictionsException> onError) {
    // Escape early if the initialization failed
    if (loadingError != null) {
        onError.accept(loadingError);
        return;
    }
    // Wait for initialization to complete
    // TODO: encapsulate blocking logic elsewhere
    boolean didLoad = false;
    try {
        didLoad = loaded.await(LOAD_TIMEOUT_MS, TimeUnit.MILLISECONDS);
    } catch (InterruptedException exception) {
        onError.accept(new PredictionsException("Text classification service initialization was interrupted.", "Please wait for the required assets to be fully loaded."));
        return;
    }
    if (!didLoad) {
        onError.accept(new PredictionsException("Text classification service timed out while awaiting load.", "Your classification data may be too resource intensive?"));
    }
    try {
        final Sentiment sentiment = fetchSentiment(text);
        onSuccess.accept(InterpretResult.builder().sentiment(sentiment).build());
    } catch (PredictionsException exception) {
        onError.accept(exception);
    }
}
Also used : PredictionsException(com.amplifyframework.predictions.PredictionsException) Sentiment(com.amplifyframework.predictions.models.Sentiment)

Example 5 with Sentiment

use of com.amplifyframework.predictions.models.Sentiment in project amplify-android by aws-amplify.

the class TensorFlowTextClassificationService method fetchSentiment.

@VisibleForTesting
Sentiment fetchSentiment(String text) throws PredictionsException {
    float[][] input;
    float[][] output;
    try {
        // Pre-process input text
        input = dictionary.tokenizeInputText(text);
        output = new float[1][labels.size()];
        // Run inference.
        interpreter.run(input, output);
    } catch (IllegalArgumentException exception) {
        throw new PredictionsException("TensorFlow Lite failed to make an inference.", exception, "Verify that the label size matches the output size of the model.");
    }
    // Find the predominant sentiment
    Sentiment sentiment = null;
    for (int i = 0; i < labels.size(); i++) {
        SentimentType sentimentType = SentimentTypeAdapter.fromTensorFlow(labels.get(i));
        float confidenceScore = output[0][i] * PERCENT;
        if (sentiment == null || sentiment.getConfidence() < confidenceScore) {
            sentiment = Sentiment.builder().value(sentimentType).confidence(confidenceScore).build();
        }
    }
    return sentiment;
}
Also used : PredictionsException(com.amplifyframework.predictions.PredictionsException) SentimentType(com.amplifyframework.predictions.models.SentimentType) Sentiment(com.amplifyframework.predictions.models.Sentiment) VisibleForTesting(androidx.annotation.VisibleForTesting)

Aggregations

Sentiment (com.amplifyframework.predictions.models.Sentiment)6 PredictionsException (com.amplifyframework.predictions.PredictionsException)3 Test (org.junit.Test)3 InterpretResult (com.amplifyframework.predictions.result.InterpretResult)2 VisibleForTesting (androidx.annotation.VisibleForTesting)1 DominantLanguage (com.amazonaws.services.comprehend.model.DominantLanguage)1 Entity (com.amplifyframework.predictions.models.Entity)1 KeyPhrase (com.amplifyframework.predictions.models.KeyPhrase)1 Language (com.amplifyframework.predictions.models.Language)1 LanguageType (com.amplifyframework.predictions.models.LanguageType)1 SentimentType (com.amplifyframework.predictions.models.SentimentType)1 Syntax (com.amplifyframework.predictions.models.Syntax)1 RandomString (com.amplifyframework.testutils.random.RandomString)1 Random (java.util.Random)1 ArgumentMatchers.anyString (org.mockito.ArgumentMatchers.anyString)1