Search in sources :

Example 11 with PredictionsException

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

the class TextClassificationModel method loadModelFile.

// This code comes from the official TensorFlow Lite sample app
// https://github.com/tensorflow/examples/tree/master/lite/examples/text_classification/android
private synchronized MappedByteBuffer loadModelFile() throws PredictionsException {
    try (AssetFileDescriptor fileDescriptor = assets.openFd(MODEL_PATH);
        FileInputStream inputStream = new FileInputStream(fileDescriptor.getFileDescriptor())) {
        FileChannel fileChannel = inputStream.getChannel();
        long startOffset = fileDescriptor.getStartOffset();
        long declaredLength = fileDescriptor.getDeclaredLength();
        return fileChannel.map(FileChannel.MapMode.READ_ONLY, startOffset, declaredLength);
    } catch (IOException exception) {
        throw new PredictionsException("Error encountered while loading models.", exception, "Verify that " + MODEL_PATH + " is present inside the assets directory.");
    }
}
Also used : AssetFileDescriptor(android.content.res.AssetFileDescriptor) FileChannel(java.nio.channels.FileChannel) PredictionsException(com.amplifyframework.predictions.PredictionsException) IOException(java.io.IOException) FileInputStream(java.io.FileInputStream)

Example 12 with PredictionsException

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

the class InputTokenizerTest method testInputTextTokenizer.

/**
 * Test that text tokenizer converts input text into a 2-D
 * array of equivalent token values and pads the rest with 0's.
 * @throws Exception if dictionary fails to load
 */
@Test
// word tokens
@SuppressWarnings("MagicNumber")
public void testInputTextTokenizer() throws Exception {
    final String inputText = "Where is the bathroom?";
    final InputStream stream = new FileInputStream("src/test/resources/word-tokens.txt");
    // Make mock context return mock asset manager
    when(mockContext.getAssets()).thenReturn(mockAssets);
    // Make mock asset manager return pre-determined input stream
    when(mockAssets.open(anyString())).thenReturn(stream);
    // Load!! (from mock assets)
    TextClassificationDictionary dictionary = new TextClassificationDictionary(mockContext);
    Map<String, Integer> tokens = Await.<Map<String, Integer>, PredictionsException>result((onResult, onError) -> {
        dictionary.onLoaded(onResult, onError);
        dictionary.load();
    });
    // Assert that load was successful
    assertEquals(tokens, dictionary.getValue());
    // Tokenize input
    float[][] input = dictionary.tokenizeInputText(inputText);
    // 256 = Max sentence size
    float[][] expected = new float[1][256];
    // <START>
    expected[0][0] = 1;
    // Where (<UNKNOWN>)
    expected[0][1] = 2;
    // is
    expected[0][2] = 9;
    // the
    expected[0][3] = 4;
    // bathroom (<UNKNOWN>)
    expected[0][4] = 2;
    // Followed by 0's (<PAD>)
    assertArrayEquals(expected, input);
}
Also used : FileInputStream(java.io.FileInputStream) InputStream(java.io.InputStream) PredictionsException(com.amplifyframework.predictions.PredictionsException) ArgumentMatchers.anyString(org.mockito.ArgumentMatchers.anyString) Map(java.util.Map) FileInputStream(java.io.FileInputStream) Test(org.junit.Test)

Example 13 with PredictionsException

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

the class RxPredictionsBindingTest method testFailedTextToSpeechConversion.

/**
 * When the delegate behavior fails for the {@link RxPredictionsBinding#convertTextToSpeech(String)}
 * its emitted error should be propagated via the returned {@link Single}.
 * @throws InterruptedException If interrupted while test observer is awaiting terminal event
 */
@Test
public void testFailedTextToSpeechConversion() throws InterruptedException {
    String text = RandomString.string();
    PredictionsException predictionsException = new PredictionsException("Uh", "Oh!");
    doAnswer(invocation -> {
        // 0 = text, 1 = result, 2 = error
        final int indexOfFailureConsumer = 2;
        Consumer<PredictionsException> onFailure = invocation.getArgument(indexOfFailureConsumer);
        onFailure.accept(predictionsException);
        return mock(TextToSpeechOperation.class);
    }).when(delegate).convertTextToSpeech(eq(text), anyConsumer(), anyConsumer());
    TestObserver<TextToSpeechResult> observer = rxPredictions.convertTextToSpeech(text).test();
    observer.await(TIMEOUT_SECONDS, TimeUnit.SECONDS);
    observer.assertError(predictionsException);
}
Also used : TextToSpeechResult(com.amplifyframework.predictions.result.TextToSpeechResult) PredictionsException(com.amplifyframework.predictions.PredictionsException) RandomString(com.amplifyframework.testutils.random.RandomString) Test(org.junit.Test)

Example 14 with PredictionsException

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

the class RxPredictionsBindingTest method testFailedTextInterpretation.

/**
 * When the delegate of {@link RxPredictionsBinding#interpret(String)} emits a failure,
 * it should be propagated via the returned {@link Single}.
 * @throws InterruptedException If interrupted while test observer is awaiting terminal event
 */
@Test
public void testFailedTextInterpretation() throws InterruptedException {
    String text = RandomString.string();
    PredictionsException predictionsException = new PredictionsException("Uh", "Oh");
    doAnswer(invocation -> {
        // 0 = text, 1 = result, 2 = error
        final int indexOfFailureConsumer = 2;
        Consumer<PredictionsException> onFailure = invocation.getArgument(indexOfFailureConsumer);
        onFailure.accept(predictionsException);
        return mock(InterpretOperation.class);
    }).when(delegate).interpret(eq(text), anyConsumer(), anyConsumer());
    TestObserver<InterpretResult> observer = rxPredictions.interpret(text).test();
    observer.await(TIMEOUT_SECONDS, TimeUnit.SECONDS);
    observer.assertError(predictionsException);
}
Also used : PredictionsException(com.amplifyframework.predictions.PredictionsException) RandomString(com.amplifyframework.testutils.random.RandomString) InterpretResult(com.amplifyframework.predictions.result.InterpretResult) Test(org.junit.Test)

Example 15 with PredictionsException

use of com.amplifyframework.predictions.PredictionsException 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)

Aggregations

PredictionsException (com.amplifyframework.predictions.PredictionsException)32 AmazonClientException (com.amazonaws.AmazonClientException)15 ArrayList (java.util.ArrayList)9 Image (com.amazonaws.services.rekognition.model.Image)6 Test (org.junit.Test)5 RectF (android.graphics.RectF)4 IdentifyEntitiesConfiguration (com.amplifyframework.predictions.aws.configuration.IdentifyEntitiesConfiguration)3 Sentiment (com.amplifyframework.predictions.models.Sentiment)3 InputStream (java.io.InputStream)3 DominantLanguage (com.amazonaws.services.comprehend.model.DominantLanguage)2 ComparedFace (com.amazonaws.services.rekognition.model.ComparedFace)2 ModerationLabel (com.amazonaws.services.rekognition.model.ModerationLabel)2 Document (com.amazonaws.services.textract.model.Document)2 SpeechGeneratorConfiguration (com.amplifyframework.predictions.aws.configuration.SpeechGeneratorConfiguration)2 CelebrityDetails (com.amplifyframework.predictions.models.CelebrityDetails)2 KeyPhrase (com.amplifyframework.predictions.models.KeyPhrase)2 Landmark (com.amplifyframework.predictions.models.Landmark)2 LanguageType (com.amplifyframework.predictions.models.LanguageType)2 Pose (com.amplifyframework.predictions.models.Pose)2 Syntax (com.amplifyframework.predictions.models.Syntax)2