|
| 1 | +/* |
| 2 | + * Copyright 2017 Google Inc. |
| 3 | + * |
| 4 | + * Licensed under the Apache License, Version 2.0 (the "License"); |
| 5 | + * you may not use this file except in compliance with the License. |
| 6 | + * You may obtain a copy of the License at |
| 7 | + * |
| 8 | + * http://www.apache.org/licenses/LICENSE-2.0 |
| 9 | + * |
| 10 | + * Unless required by applicable law or agreed to in writing, software |
| 11 | + * distributed under the License is distributed on an "AS IS" BASIS, |
| 12 | + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. |
| 13 | + * See the License for the specific language governing permissions and |
| 14 | + * limitations under the License. |
| 15 | + */ |
| 16 | + |
| 17 | +package com.google.cloud.language.samples; |
| 18 | + |
| 19 | +import com.google.cloud.language.spi.v1beta2.LanguageServiceClient; |
| 20 | + |
| 21 | +import com.google.cloud.language.v1beta2.AnalyzeEntitySentimentRequest; |
| 22 | +import com.google.cloud.language.v1beta2.AnalyzeEntitySentimentResponse; |
| 23 | +import com.google.cloud.language.v1beta2.AnalyzeSentimentResponse; |
| 24 | +import com.google.cloud.language.v1beta2.Document; |
| 25 | +import com.google.cloud.language.v1beta2.Document.Type; |
| 26 | +import com.google.cloud.language.v1beta2.EncodingType; |
| 27 | +import com.google.cloud.language.v1beta2.Entity; |
| 28 | +import com.google.cloud.language.v1beta2.EntityMention; |
| 29 | +import com.google.cloud.language.v1beta2.Sentiment; |
| 30 | +import com.google.cloud.language.v1beta2.Token; |
| 31 | +import com.google.protobuf.Descriptors; |
| 32 | + |
| 33 | +import java.io.IOException; |
| 34 | +import java.io.PrintStream; |
| 35 | +import java.security.GeneralSecurityException; |
| 36 | +import java.util.List; |
| 37 | +import java.util.Map; |
| 38 | + |
| 39 | +/** |
| 40 | + * A sample application that uses the Natural Language API to perform |
| 41 | + * entity, sentiment and syntax analysis. |
| 42 | + */ |
| 43 | +public class AnalyzeBeta { |
| 44 | + private final LanguageServiceClient languageApi; |
| 45 | + |
| 46 | + /** |
| 47 | + * Constructs a {@link Analyze} which connects to the Cloud Natural Language API. |
| 48 | + */ |
| 49 | + public AnalyzeBeta(LanguageServiceClient languageApi) { |
| 50 | + this.languageApi = languageApi; |
| 51 | + } |
| 52 | + |
| 53 | + |
| 54 | + /** |
| 55 | + * Detects entities,sentiment and syntax in a document using the Natural Language API. |
| 56 | + */ |
| 57 | + public static void main(String[] args) throws IOException, GeneralSecurityException { |
| 58 | + if (args.length < 2 || args.length > 4) { |
| 59 | + System.err.println("Usage:"); |
| 60 | + System.err.printf( |
| 61 | + "\tjava %s \"command\" \"text to analyze\" \"language\" \n", |
| 62 | + Analyze.class.getCanonicalName()); |
| 63 | + System.exit(1); |
| 64 | + } |
| 65 | + String command = args[0]; |
| 66 | + String text = args[1]; |
| 67 | + String lang = null; |
| 68 | + if (args.length > 2) { |
| 69 | + lang = args[2]; |
| 70 | + } |
| 71 | + |
| 72 | + AnalyzeBeta app = new AnalyzeBeta(LanguageServiceClient.create()); |
| 73 | + |
| 74 | + if (command.equals("entities-sentiment")) { |
| 75 | + if (text.startsWith("gs://")) { |
| 76 | + printEntities(System.out, app.entitySentimentFile(text)); |
| 77 | + } else { |
| 78 | + printEntities(System.out, app.entitySentimentText(text)); |
| 79 | + } |
| 80 | + } else if (command.equals("sentiment")) { |
| 81 | + printSentiment(System.out, app.analyzeSentimentText(text, lang)); |
| 82 | + } |
| 83 | + } |
| 84 | + |
| 85 | + /** |
| 86 | + * Print the Sentiment {@code sentiment}. |
| 87 | + */ |
| 88 | + public static void printSentiment(PrintStream out, Sentiment sentiment) { |
| 89 | + if (sentiment == null) { |
| 90 | + out.println("No sentiment found"); |
| 91 | + return; |
| 92 | + } |
| 93 | + out.println("Found sentiment."); |
| 94 | + out.printf("\tMagnitude: %.3f\n", sentiment.getMagnitude()); |
| 95 | + out.printf("\tScore: %.3f\n", sentiment.getScore()); |
| 96 | + } |
| 97 | + |
| 98 | + /** |
| 99 | + * Print a list of {@code entities}. |
| 100 | + */ |
| 101 | + public static void printEntities(PrintStream out, List<Entity> entities) { |
| 102 | + if (entities == null || entities.size() == 0) { |
| 103 | + out.println("No entities found."); |
| 104 | + return; |
| 105 | + } |
| 106 | + out.printf("Found %d entit%s.\n", entities.size(), entities.size() == 1 ? "y" : "ies"); |
| 107 | + for (Entity entity : entities) { |
| 108 | + out.printf("----\n\"%s\"\n", entity.getName()); |
| 109 | + out.printf("\tSalience: %.3f\n", entity.getSalience()); |
| 110 | + out.printf("\tSentiment Magnitude: %.3f\n", entity.getSentiment().getMagnitude()); |
| 111 | + out.printf("\tSentiment Score: %.3f\n", entity.getSentiment().getScore()); |
| 112 | + out.printf("\tType: %s\n", entity.getType()); |
| 113 | + if (entity.getMetadataMap() != null) { |
| 114 | + for (Map.Entry<String, String> metadata : entity.getMetadataMap().entrySet()) { |
| 115 | + out.printf("\tMetadata: %s = %s\n", metadata.getKey(), metadata.getValue()); |
| 116 | + } |
| 117 | + } |
| 118 | + if (entity.getMentionsList() != null) { |
| 119 | + for (EntityMention mention : entity.getMentionsList()) { |
| 120 | + for (Map.Entry<Descriptors.FieldDescriptor, Object> mentionSetMember : |
| 121 | + mention.getAllFields().entrySet()) { |
| 122 | + out.printf("\tMention: %s = %s\n", mentionSetMember.getKey(), |
| 123 | + mentionSetMember.getValue()); |
| 124 | + } |
| 125 | + } |
| 126 | + } |
| 127 | + } |
| 128 | + } |
| 129 | + |
| 130 | + /** |
| 131 | + * Gets {@link Sentiment} from the string {@code text}. |
| 132 | + */ |
| 133 | + public Sentiment analyzeSentimentText(String text, String lang) throws IOException { |
| 134 | + if (lang == null || lang.length() < 2) { |
| 135 | + lang = "EN"; |
| 136 | + } |
| 137 | + |
| 138 | + // Note: This does not work on App Engine standard. |
| 139 | + Document doc = Document.newBuilder() |
| 140 | + .setLanguage(lang) |
| 141 | + .setContent(text).setType(Type.PLAIN_TEXT).build(); |
| 142 | + AnalyzeSentimentResponse response = languageApi.analyzeSentiment(doc); |
| 143 | + return response.getDocumentSentiment(); |
| 144 | + } |
| 145 | + |
| 146 | + /** |
| 147 | + * Gets {@link Entity}s from the string {@code text} with sentiment. |
| 148 | + */ |
| 149 | + public List<Entity> entitySentimentText(String text) throws IOException { |
| 150 | + // Note: This does not work on App Engine standard. |
| 151 | + Document doc = Document.newBuilder() |
| 152 | + .setContent(text).setType(Type.PLAIN_TEXT).build(); |
| 153 | + AnalyzeEntitySentimentRequest request = AnalyzeEntitySentimentRequest.newBuilder() |
| 154 | + .setDocument(doc) |
| 155 | + .setEncodingType(EncodingType.UTF16).build(); |
| 156 | + AnalyzeEntitySentimentResponse response = languageApi.analyzeEntitySentiment(request); |
| 157 | + return response.getEntitiesList(); |
| 158 | + } |
| 159 | + |
| 160 | + /** |
| 161 | + * Gets {@link Entity}s from the contents of the object at the given GCS {@code path} |
| 162 | + * with sentiment. |
| 163 | + */ |
| 164 | + public List<Entity> entitySentimentFile(String path) throws IOException { |
| 165 | + // Note: This does not work on App Engine standard. |
| 166 | + Document doc = Document.newBuilder() |
| 167 | + .setGcsContentUri(path).setType(Type.PLAIN_TEXT).build(); |
| 168 | + AnalyzeEntitySentimentRequest request = AnalyzeEntitySentimentRequest.newBuilder() |
| 169 | + .setDocument(doc) |
| 170 | + .setEncodingType(EncodingType.UTF16).build(); |
| 171 | + AnalyzeEntitySentimentResponse response = languageApi.analyzeEntitySentiment(request); |
| 172 | + return response.getEntitiesList(); |
| 173 | + } |
| 174 | +} |
0 commit comments