use of com.amplifyframework.predictions.models.SentimentType 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();
}
use of com.amplifyframework.predictions.models.SentimentType 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;
}
Aggregations