Search in sources :

Example 11 with ToneAnalysis

use of com.ibm.watson.tone_analyzer.v3.model.ToneAnalysis in project java-sdk by watson-developer-cloud.

the class ToneAnalyzerTest method testReadme.

/**
 * Test README.
 */
@Test
public void testReadme() throws InterruptedException, IOException {
    ToneAnalyzer service = new ToneAnalyzer(VERSION_DATE);
    service.setUsernameAndPassword("<username>", "<password>");
    // exclude
    service.setEndPoint(getMockWebServerUrl());
    // exclude
    ToneAnalysis mockResponse = loadFixture(FIXTURE, ToneAnalysis.class);
    // exclude
    server.enqueue(jsonResponse(mockResponse));
    String text = "I know the times are difficult! Our sales have been " + "disappointing for the past three quarters for our data analytics " + "product suite. We have a competitive data analytics product " + "suite in the industry. But we need to do our job selling it! " + "We need to acknowledge and fix our sales challenges. " + "We can’t blame the economy for our lack of execution! " + "We are missing critical sales opportunities. " + "Our product is in no way inferior to the competitor products. " + "Our clients are hungry for analytical tools to improve their " + "business outcomes. Economy has nothing to do with it.";
    // Call the service and get the tone
    ToneOptions toneOptions = new ToneOptions.Builder().html(text).build();
    ToneAnalysis tone = service.tone(toneOptions).execute();
    System.out.println(tone);
}
Also used : ToneAnalysis(com.ibm.watson.developer_cloud.tone_analyzer.v3.model.ToneAnalysis) ToneOptions(com.ibm.watson.developer_cloud.tone_analyzer.v3.model.ToneOptions) Test(org.junit.Test) WatsonServiceUnitTest(com.ibm.watson.developer_cloud.WatsonServiceUnitTest)

Example 12 with ToneAnalysis

use of com.ibm.watson.tone_analyzer.v3.model.ToneAnalysis in project java-sdk by watson-developer-cloud.

the class ToneAnalyzer method tone.

/**
 * Analyze general tone.
 *
 * <p>Use the general-purpose endpoint to analyze the tone of your input content. The service
 * analyzes the content for emotional and language tones. The method always analyzes the tone of
 * the full document; by default, it also analyzes the tone of each individual sentence of the
 * content.
 *
 * <p>You can submit no more than 128 KB of total input content and no more than 1000 individual
 * sentences in JSON, plain text, or HTML format. The service analyzes the first 1000 sentences
 * for document-level analysis and only the first 100 sentences for sentence-level analysis.
 *
 * <p>Per the JSON specification, the default character encoding for JSON content is effectively
 * always UTF-8; per the HTTP specification, the default encoding for plain text and HTML is
 * ISO-8859-1 (effectively, the ASCII character set). When specifying a content type of plain text
 * or HTML, include the `charset` parameter to indicate the character encoding of the input text;
 * for example: `Content-Type: text/plain;charset=utf-8`. For `text/html`, the service removes
 * HTML tags and analyzes only the textual content.
 *
 * <p>**See also:** [Using the general-purpose
 * endpoint](https://cloud.ibm.com/docs/tone-analyzer?topic=tone-analyzer-utgpe#utgpe).
 *
 * @param toneOptions the {@link ToneOptions} containing the options for the call
 * @return a {@link ServiceCall} with a result of type {@link ToneAnalysis}
 */
public ServiceCall<ToneAnalysis> tone(ToneOptions toneOptions) {
    com.ibm.cloud.sdk.core.util.Validator.notNull(toneOptions, "toneOptions cannot be null");
    RequestBuilder builder = RequestBuilder.post(RequestBuilder.resolveRequestUrl(getServiceUrl(), "/v3/tone"));
    Map<String, String> sdkHeaders = SdkCommon.getSdkHeaders("tone_analyzer", "v3", "tone");
    for (Entry<String, String> header : sdkHeaders.entrySet()) {
        builder.header(header.getKey(), header.getValue());
    }
    builder.header("Accept", "application/json");
    if (toneOptions.contentType() != null) {
        builder.header("Content-Type", toneOptions.contentType());
    }
    if (toneOptions.contentLanguage() != null) {
        builder.header("Content-Language", toneOptions.contentLanguage());
    }
    if (toneOptions.acceptLanguage() != null) {
        builder.header("Accept-Language", toneOptions.acceptLanguage());
    }
    builder.query("version", String.valueOf(this.version));
    if (toneOptions.sentences() != null) {
        builder.query("sentences", String.valueOf(toneOptions.sentences()));
    }
    if (toneOptions.tones() != null) {
        builder.query("tones", RequestUtils.join(toneOptions.tones(), ","));
    }
    builder.bodyContent(toneOptions.contentType(), toneOptions.toneInput(), null, toneOptions.body());
    ResponseConverter<ToneAnalysis> responseConverter = ResponseConverterUtils.getValue(new com.google.gson.reflect.TypeToken<ToneAnalysis>() {
    }.getType());
    return createServiceCall(builder.build(), responseConverter);
}
Also used : ToneAnalysis(com.ibm.watson.tone_analyzer.v3.model.ToneAnalysis) RequestBuilder(com.ibm.cloud.sdk.core.http.RequestBuilder)

Example 13 with ToneAnalysis

use of com.ibm.watson.tone_analyzer.v3.model.ToneAnalysis in project java-sdk by watson-developer-cloud.

the class AssistantToneAnalyzerIntegrationExample method main.

public static void main(String[] args) throws Exception {
    // instantiate the assistant service
    Authenticator assistantAuthenticator = new IamAuthenticator("<iam_api_key>");
    final Assistant assistantService = new Assistant("2019-02-28", assistantAuthenticator);
    // instantiate the tone analyzer service
    Authenticator toneAuthenticator = new IamAuthenticator("<iam_api_key>");
    ToneAnalyzer toneService = new ToneAnalyzer("2017-09-21", toneAuthenticator);
    // workspace id
    final String workspaceId = "<workspace-id>";
    // maintain history in the context variable - will add a history variable to
    // each of the emotion, social
    // and language tones
    final boolean maintainHistory = false;
    /**
     * Input for the Assistant service: text (String): an input string (the user's conversation
     * turn) and context (Context): any context that needs to be maintained - either added by the
     * client app or passed in the response from the Assistant service on the previous conversation
     * turn.
     */
    final String text = "I am happy";
    final Context context = new Context();
    // UPDATE CONTEXT HERE IF CONTINUING AN ONGOING CONVERSATION
    // set local context variable to the context from the last response from the
    // Assistant Service
    // (see the getContext() method of the MessageResponse class in
    // com.ibm.watson.assistant.v1.model)
    // async call to Tone Analyzer
    ToneOptions toneOptions = new ToneOptions.Builder().text(text).build();
    toneService.tone(toneOptions).enqueue(new ServiceCallback<ToneAnalysis>() {

        @Override
        public void onResponse(Response<ToneAnalysis> toneResponsePayload) {
            // update context with the tone data returned by the Tone Analyzer
            context.setSystem(ToneDetection.updateUserTone(context, toneResponsePayload.getResult(), maintainHistory));
            // create input for message
            MessageInput input = new MessageInput();
            input.setText(text);
            // call Assistant Service with the input and tone-aware context
            MessageOptions messageOptions = new MessageOptions.Builder(workspaceId).input(input).context(context).build();
            assistantService.message(messageOptions).enqueue(new ServiceCallback<MessageResponse>() {

                @Override
                public void onResponse(Response<MessageResponse> response) {
                    System.out.println(response.getResult());
                }

                @Override
                public void onFailure(Exception e) {
                }
            });
        }

        @Override
        public void onFailure(Exception e) {
        }
    });
}
Also used : Context(com.ibm.watson.assistant.v1.model.Context) ToneAnalysis(com.ibm.watson.tone_analyzer.v3.model.ToneAnalysis) IamAuthenticator(com.ibm.cloud.sdk.core.security.IamAuthenticator) MessageInput(com.ibm.watson.assistant.v1.model.MessageInput) ToneOptions(com.ibm.watson.tone_analyzer.v3.model.ToneOptions) MessageResponse(com.ibm.watson.assistant.v1.model.MessageResponse) Response(com.ibm.cloud.sdk.core.http.Response) ServiceCallback(com.ibm.cloud.sdk.core.http.ServiceCallback) ToneAnalyzer(com.ibm.watson.tone_analyzer.v3.ToneAnalyzer) MessageOptions(com.ibm.watson.assistant.v1.model.MessageOptions) Assistant(com.ibm.watson.assistant.v1.Assistant) Authenticator(com.ibm.cloud.sdk.core.security.Authenticator) IamAuthenticator(com.ibm.cloud.sdk.core.security.IamAuthenticator)

Example 14 with ToneAnalysis

use of com.ibm.watson.tone_analyzer.v3.model.ToneAnalysis in project java-sdk by watson-developer-cloud.

the class ToneDetection method updateUserTone.

/**
 * updateUserTone processes the Tone Analyzer payload to pull out the emotion, language and social
 * tones, and identify the meaningful tones (i.e., those tones that meet the specified
 * thresholds). The assistantPayload json object is updated to include these tones.
 *
 * @param context the context
 * @param toneAnalyzerPayload json object returned by the Watson Tone Analyzer Service
 * @param maintainHistory the maintain history
 * @return the map
 * @returns assistantPayload where the user object has been updated with tone information from the
 *     toneAnalyzerPayload
 */
public static Map<String, Object> updateUserTone(Context context, ToneAnalysis toneAnalyzerPayload, boolean maintainHistory) {
    List<ToneScore> emotionTone = new ArrayList<ToneScore>();
    List<ToneScore> languageTone = new ArrayList<ToneScore>();
    List<ToneScore> socialTone = new ArrayList<ToneScore>();
    // If the context doesn't already contain the user object, initialize it
    if (context.getSystem().containsKey("user")) {
        context.put("user", initUser());
    }
    // For convenience sake, define a variable for the user object to
    @SuppressWarnings("unchecked") Map<String, Object> user = (Map<String, Object>) context.get("user");
    if (toneAnalyzerPayload != null && toneAnalyzerPayload.getDocumentTone() != null) {
        List<ToneCategory> tones = toneAnalyzerPayload.getDocumentTone().getToneCategories();
        for (ToneCategory tone : tones) {
            if (tone.getCategoryId().equals(EMOTION_TONE_LABEL)) {
                emotionTone = tone.getTones();
            }
            if (tone.getCategoryId().equals(LANGUAGE_TONE_LABEL)) {
                languageTone = tone.getTones();
            }
            if (tone.getCategoryId().equals(SOCIAL_TONE_LABEL)) {
                socialTone = tone.getTones();
            }
        }
        updateEmotionTone(user, emotionTone, maintainHistory);
        updateLanguageTone(user, languageTone, maintainHistory);
        updateSocialTone(user, socialTone, maintainHistory);
    }
    context.put("user", user);
    return user;
}
Also used : ArrayList(java.util.ArrayList) Map(java.util.Map) HashMap(java.util.HashMap) ToneScore(com.ibm.watson.tone_analyzer.v3.model.ToneScore) ToneCategory(com.ibm.watson.tone_analyzer.v3.model.ToneCategory)

Example 15 with ToneAnalysis

use of com.ibm.watson.tone_analyzer.v3.model.ToneAnalysis in project java-sdk by watson-developer-cloud.

the class ToneAnalyzerExample method main.

public static void main(String[] args) {
    Authenticator authenticator = new IamAuthenticator("<iam_api_key>");
    ToneAnalyzer service = new ToneAnalyzer("2017-09-21", authenticator);
    String text = "I know the times are difficult! Our sales have been " + "disappointing for the past three quarters for our data analytics " + "product suite. We have a competitive data analytics product " + "suite in the industry. But we need to do our job selling it! " + "We need to acknowledge and fix our sales challenges. " + "We can’t blame the economy for our lack of execution! " + "We are missing critical sales opportunities. " + "Our product is in no way inferior to the competitor products. " + "Our clients are hungry for analytical tools to improve their " + "business outcomes. Economy has nothing to do with it.";
    // Call the service and get the tone
    ToneOptions toneOptions = new ToneOptions.Builder().text(text).build();
    ToneAnalysis tone = service.tone(toneOptions).execute().getResult();
    System.out.println(tone);
}
Also used : ToneAnalysis(com.ibm.watson.tone_analyzer.v3.model.ToneAnalysis) IamAuthenticator(com.ibm.cloud.sdk.core.security.IamAuthenticator) ToneOptions(com.ibm.watson.tone_analyzer.v3.model.ToneOptions) Authenticator(com.ibm.cloud.sdk.core.security.Authenticator) IamAuthenticator(com.ibm.cloud.sdk.core.security.IamAuthenticator)

Aggregations

ToneAnalysis (com.ibm.watson.developer_cloud.tone_analyzer.v3.model.ToneAnalysis)8 Test (org.junit.Test)8 ToneAnalysis (com.ibm.watson.tone_analyzer.v3.model.ToneAnalysis)7 ToneOptions (com.ibm.watson.developer_cloud.tone_analyzer.v3.model.ToneOptions)6 ToneOptions (com.ibm.watson.tone_analyzer.v3.model.ToneOptions)6 WatsonServiceTest (com.ibm.watson.common.WatsonServiceTest)3 WatsonServiceTest (com.ibm.watson.developer_cloud.WatsonServiceTest)3 Authenticator (com.ibm.cloud.sdk.core.security.Authenticator)2 IamAuthenticator (com.ibm.cloud.sdk.core.security.IamAuthenticator)2 WatsonServiceUnitTest (com.ibm.watson.developer_cloud.WatsonServiceUnitTest)2 HashMap (java.util.HashMap)2 RecordedRequest (okhttp3.mockwebserver.RecordedRequest)2 RequestBuilder (com.ibm.cloud.sdk.core.http.RequestBuilder)1 Response (com.ibm.cloud.sdk.core.http.Response)1 ServiceCallback (com.ibm.cloud.sdk.core.http.ServiceCallback)1 Assistant (com.ibm.watson.assistant.v1.Assistant)1 Context (com.ibm.watson.assistant.v1.model.Context)1 MessageInput (com.ibm.watson.assistant.v1.model.MessageInput)1 MessageOptions (com.ibm.watson.assistant.v1.model.MessageOptions)1 MessageResponse (com.ibm.watson.assistant.v1.model.MessageResponse)1