diff --git a/README.md b/README.md index 8b15d371b33..8eca47aee19 100644 --- a/README.md +++ b/README.md @@ -74,7 +74,7 @@ All the services: Only Assistant: ```gradle -'com.ibm.watson.developer_cloud:assistant:5.0.1' +'com.ibm.watson.developer_cloud:assistant:5.1.1' ``` ##### Development Snapshots @@ -97,7 +97,7 @@ And then reference the snapshot version on your app module gradle Only Speech to Text: ```gradle -'com.ibm.watson.developer_cloud:speech-to-text:5.1.1-SNAPSHOT' +'com.ibm.watson.developer_cloud:speech-to-text:5.1.2-SNAPSHOT' ``` ##### JAR diff --git a/assistant/README.md b/assistant/README.md index cdbdd3ae467..fcc4c5e6d0b 100644 --- a/assistant/README.md +++ b/assistant/README.md @@ -5,9 +5,9 @@ ##### Maven ```xml - com.ibm.watson.developer_cloud - assistant - 5.0.0 + com.ibm.watson.developer_cloud + assistant + 5.1.1 ``` @@ -25,7 +25,9 @@ Assistant service = new Assistant("2018-02-16"); service.setUsernameAndPassword("", ""); InputData input = new InputData.Builder("Hi").build(); -MessageOptions options = new MessageOptions.Builder(workspaceId).input(input).build(); +MessageOptions options = new MessageOptions.Builder(workspaceId) + .input(input) + .build(); MessageResponse response = service.message(options).execute(); System.out.println(response); ``` @@ -37,19 +39,19 @@ Context context = null; // first message MessageOptions newMessageOptions = new MessageOptions.Builder() - .workspaceId("") - .input(new InputData.Builder("First message").build()) - .context(context) - .build(); + .workspaceId("") + .input(new InputData.Builder("First message").build()) + .context(context) + .build(); MessageResponse response = service.message(newMessageOptions).execute(); // second message newMessageOptions = new MessageOptions.Builder() - .workspaceId("") - .input(new InputData.Builder("Second message").build()) - .context(response.getContext()) // output context from the first message - .build(); + .workspaceId("") + .input(new InputData.Builder("Second message").build()) + .context(response.getContext()) // output context from the first message + .build(); response = service.message(newMessageOptions).execute(); diff --git a/config.properties.enc b/config.properties.enc index 67c33f77a15..82f1693e7e4 100644 Binary files a/config.properties.enc and b/config.properties.enc differ diff --git a/conversation/README.md b/conversation/README.md index 7125bd79273..778492cdfe3 100644 --- a/conversation/README.md +++ b/conversation/README.md @@ -5,9 +5,9 @@ ##### Maven ```xml - com.ibm.watson.developer_cloud - conversation - 5.1.1 + com.ibm.watson.developer_cloud + conversation + 5.1.1 ``` @@ -25,7 +25,9 @@ Conversation service = new Conversation("2018-02-16"); service.setUsernameAndPassword("", ""); InputData input = new InputData.Builder("Hi").build(); -MessageOptions options = new MessageOptions.Builder(workspaceId).input(input).build(); +MessageOptions options = new MessageOptions.Builder(workspaceId) + .input(input) + .build(); MessageResponse response = service.message(options).execute(); System.out.println(response); ``` @@ -37,19 +39,19 @@ Context context = null; // first message MessageOptions newMessageOptions = new MessageOptions.Builder() - .workspaceId("") - .input(new InputData.Builder("First message").build()) - .context(context) - .build(); + .workspaceId("") + .input(new InputData.Builder("First message").build()) + .context(context) + .build(); MessageResponse response = service.message(newMessageOptions).execute(); // second message newMessageOptions = new MessageOptions.Builder() - .workspaceId("") - .input(new InputData.Builder("Second message").build()) - .context(response.getContext()) // output context from the first message - .build(); + .workspaceId("") + .input(new InputData.Builder("Second message").build()) + .context(response.getContext()) // output context from the first message + .build(); response = service.message(newMessageOptions).execute(); diff --git a/core/src/test/java/com/ibm/watson/developer_cloud/util/CredentialUtilsTest.java b/core/src/test/java/com/ibm/watson/developer_cloud/util/CredentialUtilsTest.java index 445d344d1b4..5a2d6ff8e29 100644 --- a/core/src/test/java/com/ibm/watson/developer_cloud/util/CredentialUtilsTest.java +++ b/core/src/test/java/com/ibm/watson/developer_cloud/util/CredentialUtilsTest.java @@ -21,6 +21,7 @@ import org.junit.Assert; import org.junit.Before; +import org.junit.Ignore; import org.junit.Test; import com.ibm.watson.developer_cloud.WatsonServiceTest; @@ -129,6 +130,7 @@ public void testGetUserCredentialsWithPlan() { * it always fails there. */ @Test + @Ignore public void testGetAPIUrlFromJDNI() { assertEquals(CredentialUtils.getAPIUrlTest(SERVICE_NAME), PERSONALITY_INSIGHTS_URL); } diff --git a/examples/build.gradle b/examples/build.gradle index 6c78533e37a..a683a0af5b4 100644 --- a/examples/build.gradle +++ b/examples/build.gradle @@ -33,5 +33,5 @@ checkstyle { } dependencies { - compile group: 'com.ibm.watson.developer_cloud', name: 'java-sdk', version: '3.7.2' + compile group: 'com.ibm.watson.developer_cloud', name: 'java-sdk', version: '5.1.1' } diff --git a/examples/conversation_tone_analyzer_integration/README.md b/examples/conversation_tone_analyzer_integration/README.md deleted file mode 100644 index 48c280d1b66..00000000000 --- a/examples/conversation_tone_analyzer_integration/README.md +++ /dev/null @@ -1,36 +0,0 @@ -# Conversation and Tone Analyzer Integration Example - -This example provides sample code for integrating [Tone Analyzer][tone_analyzer] and [Conversation][conversation]. - - * [ToneDetection.java][tone_conversation_integration_example_tone_detection] - sample code to initialize a user object in the conversation payload's context (initUser), to call Tone Analyzer to retrieve tone for a user's input (invokeToneAsync), and to update tone in the user object in the conversation payload's context (updateUserTone). - - * [ToneConversationIntegrationV1.java][tone_conversation_integration_example] - sample code to use ToneDetection.java to add tone to the payload and send a request to the Conversation Service's message endpoint in an asynchronous manner. - - -Requirements to run the sample code - - * [Tone Analyzer Service credentials][bluemix_tone_analyzer_service] - * [Conversation Service credentials][bluemix_conversation_service] - * [Conversation Workspace ID][conversation_simple_workspace] - -Credentials & the Workspace ID can be set in a properties, tone_conversation_integration.properties, or directly in the code. - -Dependencies provided in -`build.gradle` - -## To run the example - -To run the code, use the provided [gradle](http://gradle.org/) build file and wrapper configuration. - -On Mac or Linux: - - ./gradlew run - - -[conversation]: https://console.bluemix.net/docs/services/conversation/index.html -[tone_analyzer]: https://console.bluemix.net/docs/services/tone-analyzer/index.html -[bluemix_conversation_service]: https://console.ng.bluemix.net/catalog/services/conversation/ -[bluemix_tone_analyzer_service]: https://console.ng.bluemix.net/catalog/services/tone-analyzer/ -[conversation_simple_workspace]: https://github.com/watson-developer-cloud/conversation-simple#workspace -[tone_conversation_integration_example]: https://github.com/aprilwebster/java-sdk/blob/master/examples/java/com/ibm/watson/developer_cloud/conversation_tone_analyzer_integration/src/main/java/com/ibm/watson/developer_cloud/conversation_tone_analyzer_integration/v1/ToneConversationIntegrationV1.java -[tone_conversation_integration_example_tone_detection]: https://github.com/aprilwebster/java-sdk/blob/master/examples/java/com/ibm/watson/developer_cloud/conversation_tone_analyzer_integration/src/main/java/com/ibm/watson/developer_cloud/conversation_tone_analyzer_integration/v1/ToneDetection.java \ No newline at end of file diff --git a/examples/conversation_tone_analyzer_integration/build.gradle b/examples/conversation_tone_analyzer_integration/build.gradle deleted file mode 100644 index abd84df1e77..00000000000 --- a/examples/conversation_tone_analyzer_integration/build.gradle +++ /dev/null @@ -1,28 +0,0 @@ -apply plugin: 'java' -apply plugin: 'eclipse' -apply plugin: 'application' - - -mainClassName = "com.ibm.watson.developer_cloud.conversation_tone_analyzer_integration.v1.ToneConversationIntegrationV1" - -repositories { - mavenCentral() -} - -jar { - baseName = 'conversation_tone_analyzer_integration' - version = '0.1.0' - manifest { - attributes 'Main-Class': "com.ibm.watson.developer_cloud.conversation_tone_analyzer_integration.v1.ToneConversationIntegrationV1" - } -} - - - -sourceCompatibility = 1.7 -targetCompatibility = 1.7 - -dependencies { - compile "com.ibm.watson.developer_cloud:java-sdk:3.5.0" - compile "commons-io:commons-io:2.4" -} \ No newline at end of file diff --git a/examples/conversation_tone_analyzer_integration/src/main/java/com/ibm/watson/developer_cloud/conversation_tone_analyzer_integration/v1/ToneConversationIntegrationV1.java b/examples/conversation_tone_analyzer_integration/src/main/java/com/ibm/watson/developer_cloud/conversation_tone_analyzer_integration/v1/ToneConversationIntegrationV1.java deleted file mode 100644 index 69cef2a9f14..00000000000 --- a/examples/conversation_tone_analyzer_integration/src/main/java/com/ibm/watson/developer_cloud/conversation_tone_analyzer_integration/v1/ToneConversationIntegrationV1.java +++ /dev/null @@ -1,103 +0,0 @@ -/** - * Copyright 2017 IBM Corp. All Rights Reserved. - * - * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with - * the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on - * an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the - * specific language governing permissions and limitations under the License. - */ -package com.ibm.watson.developer_cloud.conversation_tone_analyzer_integration.v1; - -import java.io.File; -import java.util.HashMap; -import java.util.Map; -import java.util.Properties; -import org.apache.commons.io.FileUtils; - -import com.ibm.watson.developer_cloud.conversation.v1.ConversationService; -import com.ibm.watson.developer_cloud.conversation.v1.model.MessageRequest; -import com.ibm.watson.developer_cloud.conversation.v1.model.MessageResponse; -import com.ibm.watson.developer_cloud.http.ServiceCallback; -import com.ibm.watson.developer_cloud.tone_analyzer.v3.ToneAnalyzer; -import com.ibm.watson.developer_cloud.tone_analyzer.v3.model.ToneAnalysis; - -/** - * Example of how to call the {@link ConversationService#message(String, MessageRequest)} - * method asynchronously. - * - * @version v1 - */ -public class ToneConversationIntegrationV1 { - - public static void main(String[] args) throws Exception { - - // load the properties file - Properties props = new Properties(); - props.load(FileUtils.openInputStream(new File("tone_conversation_integration.properties.example"))); - - // instantiate the conversation service - final ConversationService conversationService = new ConversationService(ConversationService - .VERSION_DATE_2016_07_11); - conversationService.setUsernameAndPassword( - props.getProperty("CONVERSATION_USERNAME", ""), - props.getProperty("CONVERSATION_PASSWORD", "") - ); - - // instantiate the tone analyzer service - ToneAnalyzer toneService = new ToneAnalyzer(ToneAnalyzer.VERSION_DATE_2016_05_19); - toneService.setUsernameAndPassword( - props.getProperty("TONE_ANALYZER_USERNAME", ""), - props.getProperty("TONE_ANALYZER_PASSWORD", "") - ); - - // workspace id - final String workspaceId = props.getProperty("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 conversation service: input (String): an input string (the user's conversation turn) and context - * (Map: any context that needs to be maintained - either added by the client app or passed in the - * response from the conversation service on the previous conversation turn. - */ - final String input = "I am happy"; - final Map context = new HashMap(); - - // UPDATE CONTEXT HERE IF CONTINUING AN ONGOING CONVERSATION - // set local context variable to the context from the last response from the - // Conversation Service - // (see the getContext() method of the MessageResponse class in - // com.ibm.watson.developer_cloud.conversation.v1.model) - - // async call to Tone Analyzer - toneService.getTone(input, null).enqueue(new ServiceCallback() { - @Override - public void onResponse(ToneAnalysis toneResponsePayload) { - - // update context with the tone data returned by the Tone Analyzer - ToneDetection.updateUserTone(context, toneResponsePayload, maintainHistory); - - // call Conversation Service with the input and tone-aware context - MessageRequest newMessage = new MessageRequest.Builder().inputText(input).context(context).build(); - conversationService.message(workspaceId, newMessage).enqueue(new ServiceCallback() { - @Override - public void onResponse(MessageResponse response) { - System.out.println(response); - } - - @Override - public void onFailure(Exception e) { } - }); - } - - @Override - public void onFailure(Exception e) { } - }); - } -} diff --git a/examples/conversation_tone_analyzer_integration/src/main/java/com/ibm/watson/developer_cloud/conversation_tone_analyzer_integration/v1/ToneDetection.java b/examples/conversation_tone_analyzer_integration/src/main/java/com/ibm/watson/developer_cloud/conversation_tone_analyzer_integration/v1/ToneDetection.java deleted file mode 100644 index 60d4029ae3c..00000000000 --- a/examples/conversation_tone_analyzer_integration/src/main/java/com/ibm/watson/developer_cloud/conversation_tone_analyzer_integration/v1/ToneDetection.java +++ /dev/null @@ -1,279 +0,0 @@ -/** - * Copyright 2017 IBM Corp. All Rights Reserved. - * - * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with - * the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on - * an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the - * specific language governing permissions and limitations under the License. - */ -package com.ibm.watson.developer_cloud.conversation_tone_analyzer_integration.v1; - -import java.util.ArrayList; -import java.util.HashMap; -import java.util.List; -import java.util.Map; - -import com.ibm.watson.developer_cloud.tone_analyzer.v3.model.ToneAnalysis; -import com.ibm.watson.developer_cloud.tone_analyzer.v3.model.ToneCategory; -import com.ibm.watson.developer_cloud.tone_analyzer.v3.model.ToneScore; - -/** - * ToneDetection. - */ -public class ToneDetection { - - /** - * Thresholds for identifying meaningful tones returned by the Watson Tone Analyzer. Current values are based on the - * recommendations made by the Watson Tone Analyzer at - * https://console.bluemix.net/docs/services/tone-analyzer/using-tone.html These thresholds can be - * adjusted to client/domain requirements. - */ - private static final Double PRIMARY_EMOTION_SCORE_THRESHOLD = 0.5; - private static final Double LANGUAGE_HIGH_SCORE_THRESHOLD = 0.75; - private static final Double LANGUAGE_NO_SCORE_THRESHOLD = 0.0; - private static final Double SOCIAL_HIGH_SCORE_THRESHOLD = 0.75; - private static final Double SOCIAL_LOW_SCORE_THRESHOLD = 0.25; - - /** - * Instantiates a new tone detection. - */ - private ToneDetection() { } - - /** - * Labels for the tone categories returned by the Watson Tone Analyzer. - */ - private static final String EMOTION_TONE_LABEL = "emotion_tone"; - private static final String LANGUAGE_TONE_LABEL = "language_tone"; - private static final String SOCIAL_TONE_LABEL = "social_tone"; - - /** - * 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 conversationPayload 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 conversationPayload where the user object has been updated with tone information from the - * toneAnalyzerPayload - */ - public static Map updateUserTone(Map context, ToneAnalysis toneAnalyzerPayload, - Boolean maintainHistory) { - - List emotionTone = new ArrayList(); - List languageTone = new ArrayList(); - List socialTone = new ArrayList(); - - // If the context doesn't already contain the user object, initialize it - if (!context.containsKey("user")) { - context.put("user", initUser()); - } - - // For convenience sake, define a variable for the user object to - @SuppressWarnings("unchecked") - Map user = (Map) context.get("user"); - - if (toneAnalyzerPayload != null && toneAnalyzerPayload.getDocumentTone() != null) { - List tones = toneAnalyzerPayload.getDocumentTone().getTones(); - for (ToneCategory tone : tones) { - if (tone.getId().equals(EMOTION_TONE_LABEL)) { - emotionTone = tone.getTones(); - } - if (tone.getId().equals(LANGUAGE_TONE_LABEL)) { - languageTone = tone.getTones(); - } - if (tone.getId().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; - } - - /** - * initUser initializes a user containing tone data (from the Watson Tone Analyzer). - * - * @return the map - * @returns user with the emotion, language and social tones. The current tone identifies the tone for a specific - * conversation turn, and the history provides the conversation for all tones up to the current tone for a - * conversation instance with a user. - */ - public static Map initUser() { - - Map user = new HashMap(); - Map tone = new HashMap(); - - Map emotionTone = new HashMap(); - emotionTone.put("current", null); - - Map socialTone = new HashMap(); - socialTone.put("current", null); - - Map languageTone = new HashMap(); - languageTone.put("current", null); - - tone.put("emotion", emotionTone); - tone.put("social", socialTone); - tone.put("language", languageTone); - - user.put("tone", tone); - - return user; - } - - /** - * updateEmotionTone updates the user emotion tone with the primary emotion - the emotion tone that has a score - * greater than or equal to the EMOTION_SCORE_THRESHOLD; otherwise primary emotion will be 'neutral'. - * - * @param user a json object representing user information (tone) to be used in conversing with the Conversation - * Service - * @param emotionTone a json object containing the emotion tones in the payload returned by the Tone Analyzer - */ - @SuppressWarnings("unchecked") - private static void updateEmotionTone(Map user, List emotionTone, - Boolean maintainHistory) { - - Double maxScore = 0.0; - String primaryEmotion = null; - Double primaryEmotionScore = null; - - for (ToneScore tone : emotionTone) { - if (tone.getScore() > maxScore) { - maxScore = tone.getScore(); - primaryEmotion = tone.getName().toLowerCase(); - primaryEmotionScore = tone.getScore(); - } - } - - if (maxScore <= PRIMARY_EMOTION_SCORE_THRESHOLD) { - primaryEmotion = "neutral"; - primaryEmotionScore = null; - } - - // update user emotion tone - Map emotion = (Map) ((Map) (user.get("tone"))).get("emotion"); - emotion.put("current", primaryEmotion); - - if (maintainHistory) { - List> history = new ArrayList>(); - if (emotion.get("history") != null) { - history = (List>) emotion.get("history"); - } - - Map emotionHistoryObject = new HashMap(); - emotionHistoryObject.put("tone_name", primaryEmotion); - emotionHistoryObject.put("score", primaryEmotionScore); - history.add(emotionHistoryObject); - - emotion.put("history", history); - } - } - - /** - * updateLanguageTone updates the user with the language tones interpreted based on the specified thresholds. - * - * @param user a json object representing user information (tone) to be used in conversing with the Conversation - * Service - * @param languageTone a json object containing the language tones in the payload returned by the Tone Analyzer - */ - @SuppressWarnings("unchecked") - private static void updateLanguageTone(Map user, List languageTone, - Boolean maintainHistory) { - - List currentLanguage = new ArrayList(); - Map currentLanguageObject = new HashMap(); - - // Process each language tone and determine if it is high or low - for (ToneScore tone : languageTone) { - if (tone.getScore() >= LANGUAGE_HIGH_SCORE_THRESHOLD) { - currentLanguage.add(tone.getName().toLowerCase() + "_high"); - currentLanguageObject.put("tone_name", tone.getName().toLowerCase()); - currentLanguageObject.put("score", tone.getScore()); - currentLanguageObject.put("interpretation", "likely high"); - } else if (tone.getScore() <= LANGUAGE_NO_SCORE_THRESHOLD) { - currentLanguageObject.put("tone_name", tone.getName().toLowerCase()); - currentLanguageObject.put("score", tone.getScore()); - currentLanguageObject.put("interpretation", "no evidence"); - } else { - currentLanguageObject.put("tone_name", tone.getName().toLowerCase()); - currentLanguageObject.put("score", tone.getScore()); - currentLanguageObject.put("interpretation", "likely medium"); - } - } - - // update user language tone - Map language = (Map) ((Map) user.get("tone")).get("language"); - - // the current language pulled from tone - language.put("current", currentLanguage); - - // if history needs to be maintained - if (maintainHistory) { - List> history = new ArrayList>(); - if (language.get("history") != null) { - history = (List>) language.get("history"); - } - history.add(currentLanguageObject); - language.put("history", history); - } - } - - /** - * updateSocialTone updates the user with the social tones interpreted based on the specified thresholds. - * - * @param user a json object representing user information (tone) to be used in conversing with the Conversation - * Service - * @param socialTone a json object containing the social tones in the payload returned by the Tone Analyzer - * @param maintainHistory the maintain history - */ - @SuppressWarnings("unchecked") - public static void updateSocialTone(Map user, List socialTone, Boolean maintainHistory) { - - List currentSocial = new ArrayList(); - Map currentSocialObject = new HashMap(); - - for (ToneScore tone : socialTone) { - if (tone.getScore() >= SOCIAL_HIGH_SCORE_THRESHOLD) { - currentSocial.add(tone.getName().toLowerCase() + "_high"); - currentSocialObject.put("tone_name", tone.getName().toLowerCase()); - currentSocialObject.put("score", tone.getScore()); - currentSocialObject.put("interpretation", "likely high"); - } else if (tone.getScore() <= SOCIAL_LOW_SCORE_THRESHOLD) { - currentSocial.add(tone.getName().toLowerCase() + "_low"); - currentSocialObject.put("tone_name", tone.getName().toLowerCase()); - currentSocialObject.put("score", tone.getScore()); - currentSocialObject.put("interpretation", "likely low"); - } else { - currentSocialObject.put("tone_name", tone.getName().toLowerCase()); - currentSocialObject.put("score", tone.getScore()); - currentSocialObject.put("interpretation", "likely medium"); - } - } - - // update user language tone - Map social = (Map) ((Map) user.get("tone")).get("social"); - social.put("current", currentSocial); - - // if history needs to be maintained - if (maintainHistory) { - List> history = new ArrayList>(); - if (social.get("history") != null) { - history = (List>) social.get("history"); - } - history.add(currentSocialObject); - social.put("history", history); - } - } -} diff --git a/examples/conversation_tone_analyzer_integration/tone_conversation_integration.properties.example b/examples/conversation_tone_analyzer_integration/tone_conversation_integration.properties.example deleted file mode 100644 index 92424c13a52..00000000000 --- a/examples/conversation_tone_analyzer_integration/tone_conversation_integration.properties.example +++ /dev/null @@ -1,8 +0,0 @@ -# Watson service environment variables - -CONVERSATION_USERNAME= -CONVERSATION_PASSWORD= -WORKSPACE_ID= - -TONE_ANALYZER_USERNAME= -TONE_ANALYZER_PASSWORD= diff --git a/examples/src/main/java/com/ibm/watson/developer_cloud/alchemy_data_news/v1/GetNewsDocumentExample.java b/examples/src/main/java/com/ibm/watson/developer_cloud/alchemy_data_news/v1/GetNewsDocumentExample.java deleted file mode 100644 index 1034a5621c1..00000000000 --- a/examples/src/main/java/com/ibm/watson/developer_cloud/alchemy_data_news/v1/GetNewsDocumentExample.java +++ /dev/null @@ -1,57 +0,0 @@ -/** - * Copyright 2017 IBM Corp. All Rights Reserved. - * - * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with - * the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on - * an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the - * specific language governing permissions and limitations under the License. - */ -package com.ibm.watson.developer_cloud.alchemy_data_news.v1; - - -import java.util.HashMap; -import java.util.Map; - -import org.apache.commons.lang3.StringUtils; - -import com.ibm.watson.developer_cloud.alchemy.v1.AlchemyDataNews; -import com.ibm.watson.developer_cloud.alchemy.v1.model.DocumentsResult; - - -/** - * Getting 7 documents between Friday 28th August 2015 and Friday 4th September 2015 using the {@link AlchemyDataNews} - * API. - * - * Example from java-sdk: https://github.com/watson-developer-cloud/java-sdk - */ -public class GetNewsDocumentExample { - - public static void main(String[] args) { - AlchemyDataNews service = new AlchemyDataNews(); - service.setApiKey(""); - - Map params = new HashMap(); - - String[] fields = - new String[] { "enriched.url.title", "enriched.url.url", "enriched.url.author", "enriched.url.publicationDate", - "enriched.url.enrichedTitle.entities", "enriched.url.enrichedTitle.docSentiment"}; - params.put(AlchemyDataNews.RETURN, StringUtils.join(fields, ",")); - params.put(AlchemyDataNews.START, "1440720000"); - params.put(AlchemyDataNews.END, "1441407600"); - params.put(AlchemyDataNews.COUNT, 7); - - // Query on adjacent nested fields: - params.put("q.enriched.url.enrichedTitle.entities.entity", "|text=IBM,type=company|"); - params.put("q.enriched.url.enrichedTitle.docSentiment.type", "positive"); - params.put("q.enriched.url.enrichedTitle.taxonomy.taxonomy_.label", "technology and computing"); - - DocumentsResult result = service.getNewsDocuments(params).execute(); - - System.out.println(result); - } - -} diff --git a/examples/src/main/java/com/ibm/watson/developer_cloud/alchemy_data_news/v1/GetVolumeExample.java b/examples/src/main/java/com/ibm/watson/developer_cloud/alchemy_data_news/v1/GetVolumeExample.java deleted file mode 100644 index c6a02ea18c7..00000000000 --- a/examples/src/main/java/com/ibm/watson/developer_cloud/alchemy_data_news/v1/GetVolumeExample.java +++ /dev/null @@ -1,35 +0,0 @@ -/** - * Copyright 2017 IBM Corp. All Rights Reserved. - * - * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with - * the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on - * an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the - * specific language governing permissions and limitations under the License. - */ -package com.ibm.watson.developer_cloud.alchemy_data_news.v1; - - -import com.ibm.watson.developer_cloud.alchemy.v1.AlchemyDataNews; -import com.ibm.watson.developer_cloud.alchemy.v1.model.VolumeResult; - -/** - * Getting The number for ingested documents in the last 7 days with a 12 hour period using the {@link AlchemyDataNews} - * API. - * - */ -public class GetVolumeExample { - - public static void main(String[] args) { - AlchemyDataNews service = new AlchemyDataNews(); - service.setApiKey(""); - - VolumeResult result = service.getVolume("now-7d", "now", "12h").execute(); - - System.out.println(result); - } - -} diff --git a/examples/src/main/java/com/ibm/watson/developer_cloud/alchemy_language/v1/AlchemyLanguageExample.java b/examples/src/main/java/com/ibm/watson/developer_cloud/alchemy_language/v1/AlchemyLanguageExample.java deleted file mode 100644 index 06d6e68b1a5..00000000000 --- a/examples/src/main/java/com/ibm/watson/developer_cloud/alchemy_language/v1/AlchemyLanguageExample.java +++ /dev/null @@ -1,47 +0,0 @@ -/** - * Copyright 2017 IBM Corp. All Rights Reserved. - * - * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with - * the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on - * an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the - * specific language governing permissions and limitations under the License. - */ -package com.ibm.watson.developer_cloud.alchemy_language.v1; - - -import java.util.HashMap; -import java.util.Map; - -import com.ibm.watson.developer_cloud.alchemy.v1.AlchemyLanguage; -import com.ibm.watson.developer_cloud.alchemy.v1.model.DocumentSentiment; -import com.ibm.watson.developer_cloud.alchemy.v1.model.Entities; -import com.ibm.watson.developer_cloud.alchemy.v1.model.TypedRelations; - -public class AlchemyLanguageExample { - - public static void main(String[] args) { - AlchemyLanguage service = new AlchemyLanguage(); - service.setApiKey(""); - - Map params = new HashMap(); - params.put(AlchemyLanguage.TEXT, "IBM Watson won the Jeopardy television show hosted by Alex Trebek"); - - // get sentiment - DocumentSentiment sentiment = service.getSentiment(params).execute(); - System.out.println("Sentiment: " + sentiment); - - // get entities - Entities entities = service.getEntities(params).execute(); - System.out.println("Entities: " + entities); - - // get typed relations - TypedRelations relations = service.getTypedRelations(params).execute(); - System.out.println("Relations: " + relations); - - } - -} diff --git a/examples/src/main/java/com/ibm/watson/developer_cloud/alchemy_vision/v1/ImageKeywordsExample.java b/examples/src/main/java/com/ibm/watson/developer_cloud/alchemy_vision/v1/ImageKeywordsExample.java deleted file mode 100644 index ba9d2e7454a..00000000000 --- a/examples/src/main/java/com/ibm/watson/developer_cloud/alchemy_vision/v1/ImageKeywordsExample.java +++ /dev/null @@ -1,33 +0,0 @@ -/** - * Copyright 2017 IBM Corp. All Rights Reserved. - * - * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with - * the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on - * an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the - * specific language governing permissions and limitations under the License. - */ -package com.ibm.watson.developer_cloud.alchemy_vision.v1; - - -import java.io.File; - -import com.ibm.watson.developer_cloud.alchemy.v1.AlchemyVision; -import com.ibm.watson.developer_cloud.alchemy.v1.model.ImageKeywords; - -public class ImageKeywordsExample { - - public static void main(String[] args) { - AlchemyVision service = new AlchemyVision(); - service.setApiKey(""); - - File image = new File("src/test/resources/alchemy/obama.jpg"); - ImageKeywords keywords = service.getImageKeywords(image, true, true).execute(); - - System.out.println(keywords); - } - -} diff --git a/examples/src/main/java/com/ibm/watson/developer_cloud/alchemy_vision/v1/RecognizeFacesExample.java b/examples/src/main/java/com/ibm/watson/developer_cloud/alchemy_vision/v1/RecognizeFacesExample.java deleted file mode 100644 index b9b444c3664..00000000000 --- a/examples/src/main/java/com/ibm/watson/developer_cloud/alchemy_vision/v1/RecognizeFacesExample.java +++ /dev/null @@ -1,33 +0,0 @@ -/** - * Copyright 2017 IBM Corp. All Rights Reserved. - * - * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with - * the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on - * an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the - * specific language governing permissions and limitations under the License. - */ -package com.ibm.watson.developer_cloud.alchemy_vision.v1; - - -import java.io.File; - -import com.ibm.watson.developer_cloud.alchemy.v1.AlchemyVision; -import com.ibm.watson.developer_cloud.alchemy.v1.model.ImageFaces; - -public class RecognizeFacesExample { - - public static void main(String[] args) { - AlchemyVision service = new AlchemyVision(); - service.setApiKey(""); - - File image = new File("src/test/resources/alchemy/obama.jpg"); - ImageFaces faces = service.recognizeFaces(image, true).execute(); - - System.out.println(faces); - } - -} diff --git a/examples/src/main/java/com/ibm/watson/developer_cloud/conversation/v1/ConversationExample.java b/examples/src/main/java/com/ibm/watson/developer_cloud/assistant/v1/AssistantExample.java similarity index 79% rename from examples/src/main/java/com/ibm/watson/developer_cloud/conversation/v1/ConversationExample.java rename to examples/src/main/java/com/ibm/watson/developer_cloud/assistant/v1/AssistantExample.java index 0ddc19d62f2..f29e48a70e6 100644 --- a/examples/src/main/java/com/ibm/watson/developer_cloud/conversation/v1/ConversationExample.java +++ b/examples/src/main/java/com/ibm/watson/developer_cloud/assistant/v1/AssistantExample.java @@ -10,31 +10,34 @@ * an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the * specific language governing permissions and limitations under the License. */ -package com.ibm.watson.developer_cloud.conversation.v1; +package com.ibm.watson.developer_cloud.assistant.v1; import java.util.Map; -import com.ibm.watson.developer_cloud.conversation.v1.model.MessageRequest; -import com.ibm.watson.developer_cloud.conversation.v1.model.MessageResponse; -import com.ibm.watson.developer_cloud.conversation.v1.model.OutputData; +import com.ibm.watson.developer_cloud.assistant.v1.Assistant; +import com.ibm.watson.developer_cloud.assistant.v1.model.MessageOptions; +import com.ibm.watson.developer_cloud.assistant.v1.model.MessageResponse; +import com.ibm.watson.developer_cloud.assistant.v1.model.OutputData; import com.ibm.watson.developer_cloud.http.ServiceCallback; import jersey.repackaged.jsr166e.CompletableFuture; /** - * Example of how to call the {@link ConversationService#message(String, MessageRequest)} method synchronous, - * asynchronous, and using react. + * Example of how to call the Assisant message method synchronously, + * asynchronously, and using react. * * @version v1-experimental */ -public class ConversationExample { +public class AssistantExample { public static void main(String[] args) throws Exception { - ConversationService service = new ConversationService(ConversationService.VERSION_DATE_2017_05_26); + Assistant service = new Assistant("2018-02-16"); service.setUsernameAndPassword("", ""); InputData input = new InputData.Builder("Hi").build(); - MessageOptions options = new MessageOptions.Builder(workspaceId).input(input).build(); + MessageOptions options = new MessageOptions.Builder("") + .input(input) + .build(); // sync MessageResponse response = service.message(options).execute(); diff --git a/examples/src/main/java/com/ibm/watson/developer_cloud/conversation/v1/tone_analyzer_integration/ConversationToneAnalyzerIntegrationExample.java b/examples/src/main/java/com/ibm/watson/developer_cloud/assistant/v1/tone_analyzer_integration/AssistantToneAnalyzerIntegrationExample.java similarity index 57% rename from examples/src/main/java/com/ibm/watson/developer_cloud/conversation/v1/tone_analyzer_integration/ConversationToneAnalyzerIntegrationExample.java rename to examples/src/main/java/com/ibm/watson/developer_cloud/assistant/v1/tone_analyzer_integration/AssistantToneAnalyzerIntegrationExample.java index 8452655e247..256c18702ee 100644 --- a/examples/src/main/java/com/ibm/watson/developer_cloud/conversation/v1/tone_analyzer_integration/ConversationToneAnalyzerIntegrationExample.java +++ b/examples/src/main/java/com/ibm/watson/developer_cloud/assistant/v1/tone_analyzer_integration/AssistantToneAnalyzerIntegrationExample.java @@ -10,32 +10,31 @@ * an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the * specific language governing permissions and limitations under the License. */ -package com.ibm.watson.developer_cloud.conversation.v1.tone_analyzer_integration; +package com.ibm.watson.developer_cloud.assistant.v1.tone_analyzer_integration; import java.util.HashMap; import java.util.Map; -import com.ibm.watson.developer_cloud.conversation.v1.ConversationService; -import com.ibm.watson.developer_cloud.conversation.v1.model.MessageRequest; -import com.ibm.watson.developer_cloud.conversation.v1.model.MessageResponse; +import com.ibm.watson.developer_cloud.assistant.v1.Assistant; +import com.ibm.watson.developer_cloud.assistant.v1.model.MessageOptions; +import com.ibm.watson.developer_cloud.assistant.v1.model.MessageResponse; import com.ibm.watson.developer_cloud.http.ServiceCallback; import com.ibm.watson.developer_cloud.tone_analyzer.v3.ToneAnalyzer; import com.ibm.watson.developer_cloud.tone_analyzer.v3.model.ToneAnalysis; /** - * Example of how to call the {@link ConversationService#message(String, MessageRequest)} method synchronous, - * asynchronous, and using react. + * Example of how to integrate the Watson Assistant and Tone Analyzer services. */ -public class ConversationToneAnalyzerIntegrationExample { +public class AssistantToneAnalyzerIntegrationExample { public static void main(String[] args) throws Exception { - // instantiate the conversation service - ConversationService conversationService = new ConversationService(ConversationService.VERSION_DATE_2016_07_11); - conversationService.setUsernameAndPassword("", ""); + // instantiate the assistant service + Assistant assistantService = new Assistant("2018-02-16"); + assistantService.setUsernameAndPassword("", ""); // instantiate the tone analyzer service - ToneAnalyzer toneService = new ToneAnalyzer(ToneAnalyzer.VERSION_DATE_2016_05_19); + ToneAnalyzer toneService = new ToneAnalyzer("2017-09-21"); toneService.setUsernameAndPassword("", ""); // workspace id @@ -44,33 +43,39 @@ public static void main(String[] args) throws Exception { // maintain history in the context variable - will add a history variable to // each of the emotion, social // and language tones - Boolean maintainHistory = false; + boolean maintainHistory = false; /** - * Input for the conversation service: input (String): an input string (the user's conversation turn) and context + * Input for the Assistant service: input (String): an input string (the user's conversation turn) and context * (Map: any context that needs to be maintained - either added by the client app or passed in the - * response from the conversation service on the previous conversation turn. + * response from the Assistant service on the previous conversation turn. */ String input = "I am happy"; - Map context = new HashMap(); + Map context = new HashMap<>(); // UPDATE CONTEXT HERE IF CONTINUING AN ONGOING CONVERSATION // set local context variable to the context from the last response from the - // Conversation Service + // Assistant Service // (see the getContext() method of the MessageResponse class in - // com.ibm.watson.developer_cloud.conversation.v1.model) + // com.ibm.watson.developer_cloud.assistant.v1.model) // async call to Tone Analyzer - toneService.getTone(input, null).enqueue(new ServiceCallback() { + ToneOptions toneOptions = new ToneOptions.Builder() + .text(input) + .build(); + toneService.tone(toneOptions).enqueue(new ServiceCallback() { @Override public void onResponse(ToneAnalysis toneResponsePayload) { // update context with the tone data returned by the Tone Analyzer ToneDetection.updateUserTone(context, toneResponsePayload, maintainHistory); - // call Conversation Service with the input and tone-aware context - MessageRequest newMessage = new MessageRequest.Builder().inputText(input).context(context).build(); - conversationService.message(workspaceId, newMessage).enqueue(new ServiceCallback() { + // call Assistant Service with the input and tone-aware context + MessageOptions messageOptions = new MessageOptions.Builder(workspaceId) + .input(new InputData.Builder(input).build()) + .context(context) + .build(); + assistantService.message(messageOptions).enqueue(new ServiceCallback() { @Override public void onResponse(MessageResponse response) { System.out.println(response); diff --git a/examples/src/main/java/com/ibm/watson/developer_cloud/conversation/v1/tone_analyzer_integration/ToneDetection.java b/examples/src/main/java/com/ibm/watson/developer_cloud/assistant/v1/tone_analyzer_integration/ToneDetection.java similarity index 86% rename from examples/src/main/java/com/ibm/watson/developer_cloud/conversation/v1/tone_analyzer_integration/ToneDetection.java rename to examples/src/main/java/com/ibm/watson/developer_cloud/assistant/v1/tone_analyzer_integration/ToneDetection.java index faf3ce0cbb7..021a7cecba0 100644 --- a/examples/src/main/java/com/ibm/watson/developer_cloud/conversation/v1/tone_analyzer_integration/ToneDetection.java +++ b/examples/src/main/java/com/ibm/watson/developer_cloud/assistant/v1/tone_analyzer_integration/ToneDetection.java @@ -10,7 +10,7 @@ * an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the * specific language governing permissions and limitations under the License. */ -package com.ibm.watson.developer_cloud.conversation.v1.tone_analyzer_integration; +package com.ibm.watson.developer_cloud.assistant.v1.tone_analyzer_integration; import java.util.ArrayList; import java.util.HashMap; @@ -52,18 +52,18 @@ private ToneDetection() { } /** * 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 conversationPayload json object is + * 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 conversationPayload where the user object has been updated with tone information from the + * @returns assistantPayload where the user object has been updated with tone information from the * toneAnalyzerPayload */ public static Map updateUserTone(Map context, ToneAnalysis toneAnalyzerPayload, - Boolean maintainHistory) { + boolean maintainHistory) { List emotionTone = new ArrayList(); List languageTone = new ArrayList(); @@ -79,15 +79,15 @@ public static Map updateUserTone(Map context, To Map user = (Map) context.get("user"); if (toneAnalyzerPayload != null && toneAnalyzerPayload.getDocumentTone() != null) { - List tones = toneAnalyzerPayload.getDocumentTone().getTones(); + List tones = toneAnalyzerPayload.getDocumentTone().getToneCategories(); for (ToneCategory tone : tones) { - if (tone.getId().equals(EMOTION_TONE_LABEL)) { + if (tone.getCategoryId().equals(EMOTION_TONE_LABEL)) { emotionTone = tone.getTones(); } - if (tone.getId().equals(LANGUAGE_TONE_LABEL)) { + if (tone.getCategoryId().equals(LANGUAGE_TONE_LABEL)) { languageTone = tone.getTones(); } - if (tone.getId().equals(SOCIAL_TONE_LABEL)) { + if (tone.getCategoryId().equals(SOCIAL_TONE_LABEL)) { socialTone = tone.getTones(); } } @@ -107,8 +107,8 @@ public static Map updateUserTone(Map context, To * * @return the map * @returns user with the emotion, language and social tones. The current tone identifies the tone for a specific - * conversation turn, and the history provides the conversation for all tones up to the current tone for a - * conversation instance with a user. + * conversation turn, and the history provides the conversation for all tones up to the current tone for + * an assistant instance with a user. */ public static Map initUser() { @@ -137,13 +137,13 @@ public static Map initUser() { * updateEmotionTone updates the user emotion tone with the primary emotion - the emotion tone that has a score * greater than or equal to the EMOTION_SCORE_THRESHOLD; otherwise primary emotion will be 'neutral'. * - * @param user a json object representing user information (tone) to be used in conversing with the Conversation + * @param user a json object representing user information (tone) to be used in conversing with the Assistant * Service * @param emotionTone a json object containing the emotion tones in the payload returned by the Tone Analyzer */ @SuppressWarnings("unchecked") private static void updateEmotionTone(Map user, List emotionTone, - Boolean maintainHistory) { + boolean maintainHistory) { Double maxScore = 0.0; String primaryEmotion = null; @@ -152,7 +152,7 @@ private static void updateEmotionTone(Map user, List for (ToneScore tone : emotionTone) { if (tone.getScore() > maxScore) { maxScore = tone.getScore(); - primaryEmotion = tone.getName().toLowerCase(); + primaryEmotion = tone.getToneName().toLowerCase(); primaryEmotionScore = tone.getScore(); } } @@ -184,13 +184,13 @@ private static void updateEmotionTone(Map user, List /** * updateLanguageTone updates the user with the language tones interpreted based on the specified thresholds. * - * @param user a json object representing user information (tone) to be used in conversing with the Conversation + * @param user a json object representing user information (tone) to be used in conversing with the Assistant * Service * @param languageTone a json object containing the language tones in the payload returned by the Tone Analyzer */ @SuppressWarnings("unchecked") private static void updateLanguageTone(Map user, List languageTone, - Boolean maintainHistory) { + boolean maintainHistory) { List currentLanguage = new ArrayList(); Map currentLanguageObject = new HashMap(); @@ -198,16 +198,16 @@ private static void updateLanguageTone(Map user, List // Process each language tone and determine if it is high or low for (ToneScore tone : languageTone) { if (tone.getScore() >= LANGUAGE_HIGH_SCORE_THRESHOLD) { - currentLanguage.add(tone.getName().toLowerCase() + "_high"); - currentLanguageObject.put("tone_name", tone.getName().toLowerCase()); + currentLanguage.add(tone.getToneName().toLowerCase() + "_high"); + currentLanguageObject.put("tone_name", tone.getToneName().toLowerCase()); currentLanguageObject.put("score", tone.getScore()); currentLanguageObject.put("interpretation", "likely high"); } else if (tone.getScore() <= LANGUAGE_NO_SCORE_THRESHOLD) { - currentLanguageObject.put("tone_name", tone.getName().toLowerCase()); + currentLanguageObject.put("tone_name", tone.getToneName().toLowerCase()); currentLanguageObject.put("score", tone.getScore()); currentLanguageObject.put("interpretation", "no evidence"); } else { - currentLanguageObject.put("tone_name", tone.getName().toLowerCase()); + currentLanguageObject.put("tone_name", tone.getToneName().toLowerCase()); currentLanguageObject.put("score", tone.getScore()); currentLanguageObject.put("interpretation", "likely medium"); } @@ -233,30 +233,30 @@ private static void updateLanguageTone(Map user, List /** * updateSocialTone updates the user with the social tones interpreted based on the specified thresholds. * - * @param user a json object representing user information (tone) to be used in conversing with the Conversation + * @param user a json object representing user information (tone) to be used in conversing with the Assistant * Service * @param socialTone a json object containing the social tones in the payload returned by the Tone Analyzer * @param maintainHistory the maintain history */ @SuppressWarnings("unchecked") - public static void updateSocialTone(Map user, List socialTone, Boolean maintainHistory) { + public static void updateSocialTone(Map user, List socialTone, boolean maintainHistory) { List currentSocial = new ArrayList(); Map currentSocialObject = new HashMap(); for (ToneScore tone : socialTone) { if (tone.getScore() >= SOCIAL_HIGH_SCORE_THRESHOLD) { - currentSocial.add(tone.getName().toLowerCase() + "_high"); - currentSocialObject.put("tone_name", tone.getName().toLowerCase()); + currentSocial.add(tone.getToneName().toLowerCase() + "_high"); + currentSocialObject.put("tone_name", tone.getToneName().toLowerCase()); currentSocialObject.put("score", tone.getScore()); currentSocialObject.put("interpretation", "likely high"); } else if (tone.getScore() <= SOCIAL_LOW_SCORE_THRESHOLD) { - currentSocial.add(tone.getName().toLowerCase() + "_low"); - currentSocialObject.put("tone_name", tone.getName().toLowerCase()); + currentSocial.add(tone.getToneName().toLowerCase() + "_low"); + currentSocialObject.put("tone_name", tone.getToneName().toLowerCase()); currentSocialObject.put("score", tone.getScore()); currentSocialObject.put("interpretation", "likely low"); } else { - currentSocialObject.put("tone_name", tone.getName().toLowerCase()); + currentSocialObject.put("tone_name", tone.getToneName().toLowerCase()); currentSocialObject.put("score", tone.getScore()); currentSocialObject.put("interpretation", "likely medium"); } diff --git a/examples/src/main/java/com/ibm/watson/developer_cloud/dialog/v1/DialogServiceExample.java b/examples/src/main/java/com/ibm/watson/developer_cloud/dialog/v1/DialogServiceExample.java deleted file mode 100644 index bb8bd5efe6d..00000000000 --- a/examples/src/main/java/com/ibm/watson/developer_cloud/dialog/v1/DialogServiceExample.java +++ /dev/null @@ -1,74 +0,0 @@ -/** - * Copyright 2017 IBM Corp. All Rights Reserved. - * - * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with - * the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on - * an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the - * specific language governing permissions and limitations under the License. - */ -package com.ibm.watson.developer_cloud.dialog.v1; - -import java.util.List; - -import com.ibm.watson.developer_cloud.dialog.v1.model.Dialog; -import com.ibm.watson.developer_cloud.http.ServiceCallback; - -import jersey.repackaged.jsr166e.CompletableFuture; - -public class DialogServiceExample { - public static void main(String[] args) throws Exception { - DialogService service = new DialogService(); - service.setUsernameAndPassword("", ""); - - // sync - List dialogs = service.getDialogs().execute(); - System.out.println(dialogs); - - - // async - service.getDialogs().enqueue(new ServiceCallback>() { - @Override - public void onResponse(List response) { - System.out.println(response); - } - - @Override - public void onFailure(Exception e) { } - }); - - // rx callback - service.getDialogs().rx().thenApply(new CompletableFuture.Fun, Integer>() { - @Override - public Integer apply(List dialogs) { - return dialogs.size(); - } - }).thenAccept(new CompletableFuture.Action() { - @Override - public void accept(Integer integer) { - System.out.println(integer); - } - }); - - // rx async callback - service.getDialogs().rx().thenApplyAsync(new CompletableFuture.Fun, Integer>() { - @Override - public Integer apply(List dialogs) { - return dialogs.size(); - } - }).thenAccept(new CompletableFuture.Action() { - @Override - public void accept(Integer size) { - System.out.println(size); - } - }); - - // rx sync - Integer size = service.getDialogs().rx().get().size(); - System.out.println(size); - } - -} diff --git a/examples/src/main/java/com/ibm/watson/developer_cloud/discovery/v1/DiscoveryQueryExample.java b/examples/src/main/java/com/ibm/watson/developer_cloud/discovery/v1/DiscoveryQueryExample.java index 11c42d2026a..9aed5812053 100644 --- a/examples/src/main/java/com/ibm/watson/developer_cloud/discovery/v1/DiscoveryQueryExample.java +++ b/examples/src/main/java/com/ibm/watson/developer_cloud/discovery/v1/DiscoveryQueryExample.java @@ -45,146 +45,148 @@ * End-to-end example for querying Discovery. */ public class DiscoveryQueryExample { - private static final String DEFAULT_CONFIG_NAME = "Default Configuration"; - - public static void main(String[] args) { - Discovery discovery = new Discovery("2016-12-15"); - discovery.setEndPoint("https://gateway.watsonplatform.net/discovery/api"); - discovery.setUsernameAndPassword("", "", "", ""); - - final File html = new File("src/test/resources/document_conversion/html-with-extra-content-input.htm"); - - // Run a conversion with no configuration specified. The Document Conversion service will use - // its default configuration when no configuration is specified. For this example, the - // Document Conversion service will section a HTML document by h1, h2, h3, h4, h5, and h6 tags. - // Those sections will be returned as Answers - System.out.println("Convert html document to Answer Units using default configuration"); - final Answers htmlToAnswersWithDefaultConfig = - service.convertDocumentToAnswer(html, HttpMediaType.TEXT_HTML).execute(); - System.out.println(htmlToAnswersWithDefaultConfig); - - System.out.println("=================================================="); - - // Run a conversion with a custom configuration. The next example shows how to convert this same - // document with a custom configuration. Instead of sectioning by the default settings (h1, h2, - // h3, h4, h5, and h6), the following example shows how to section a HTML document by only the - // h1 tag. This will result in Answers that are sectioned by h1 tags. - String configAsString = - "{\n" + " \"answer_units\": {\n" + " \"selector_tags\": [\"h1\"]\n" + " }\n" + "}"; - JsonParser jsonParser = new JsonParser(); - JsonObject customConfig = jsonParser.parse(configAsString).getAsJsonObject(); - - System.out.println("Convert html document to Answer Units using custom configuration"); - final Answers htmlToAnswersWithCustomConfig = - service.convertDocumentToAnswer(html, HttpMediaType.TEXT_HTML, customConfig).execute(); - System.out.println(htmlToAnswersWithCustomConfig); - - System.out.println("=================================================="); - - // Run a conversion with a custom configuration that is loaded from a file. This example is - // similar - // to the previous one above. The custom configuration from the file will section a HTML - // document - // by only the h2 tag. This will result in Answers that are sectioned by h2 tags. - System.out.println("Convert html document to Answer Units using custom configuration loaded from a file"); - String customConfigFilePath = "src/test/resources/document_conversion/answer_unit_config_selector_h2.json"; - JsonObject customConfigFromFile = null; - try { - customConfigFromFile = ConversionUtils.loadCustomConfig(new FileInputStream(customConfigFilePath)); - } catch (FileNotFoundException e) { - e.printStackTrace(); - } - - if (customConfigFromFile == null) { - System.err.println("ERROR - Unable to load custom config from file " + customConfigFilePath); - return; - } - - final Answers htmlToAnswersWithCustomConfigFromFile = - service.convertDocumentToAnswer(html, HttpMediaType.TEXT_HTML, customConfigFromFile).execute(); - System.out.println(htmlToAnswersWithCustomConfigFromFile); - } -} diff --git a/examples/src/main/java/com/ibm/watson/developer_cloud/document_conversion/v1/DocumentConversionExample.java b/examples/src/main/java/com/ibm/watson/developer_cloud/document_conversion/v1/DocumentConversionExample.java deleted file mode 100644 index 6dfba516a4f..00000000000 --- a/examples/src/main/java/com/ibm/watson/developer_cloud/document_conversion/v1/DocumentConversionExample.java +++ /dev/null @@ -1,45 +0,0 @@ -/** - * Copyright 2017 IBM Corp. All Rights Reserved. - * - * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with - * the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on - * an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the - * specific language governing permissions and limitations under the License. - */ -package com.ibm.watson.developer_cloud.document_conversion.v1; - -import java.io.File; - -import com.ibm.watson.developer_cloud.document_conversion.v1.model.Answers; - -/** - * Example class that shows the various usage scenario's of the Document Conversion service. - */ -public class DocumentConversionExample { - - public static void main(String[] args) { - DocumentConversion service = new DocumentConversion(DocumentConversion.VERSION_DATE_2015_12_01); - service.setUsernameAndPassword("", ""); - - File html = new File("src/test/resources/document_conversion/html-with-extra-content-input.htm"); - File pdf = new File("src/test/resources/document_conversion/pdf-with-sections-input.pdf"); - File doc = new File("src/test/resources/document_conversion/word-document-heading-input.doc"); - - System.out.println("Convert html document to Answers"); - Answers htmlToAnswers = service.convertDocumentToAnswer(html).execute(); - System.out.println(htmlToAnswers); - - System.out.println("Convert pdf document to Normalized HTML"); - String normalizedHTML = service.convertDocumentToHTML(pdf).execute(); - System.out.println(normalizedHTML); - - System.out.println("Convert html document to Normalized Text"); - String normalizedText = service.convertDocumentToText(doc).execute(); - System.out.println(normalizedText); - - } -} diff --git a/examples/src/main/java/com/ibm/watson/developer_cloud/document_conversion/v1/DocumentConversionIndexDocumentExample.java b/examples/src/main/java/com/ibm/watson/developer_cloud/document_conversion/v1/DocumentConversionIndexDocumentExample.java deleted file mode 100644 index 6f8592fd36c..00000000000 --- a/examples/src/main/java/com/ibm/watson/developer_cloud/document_conversion/v1/DocumentConversionIndexDocumentExample.java +++ /dev/null @@ -1,141 +0,0 @@ -/* - * Copyright 2017 IBM Corp. All Rights Reserved. - * - * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with - * the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on - * an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the - * specific language governing permissions and limitations under the License. - */ -package com.ibm.watson.developer_cloud.document_conversion.v1; - -import java.io.ByteArrayInputStream; -import java.io.File; -import java.io.InputStream; -import java.util.HashMap; -import java.util.Map; - -import com.google.gson.JsonObject; -import com.google.gson.JsonParser; -import com.ibm.watson.developer_cloud.document_conversion.v1.model.IndexConfiguration; -import com.ibm.watson.developer_cloud.document_conversion.v1.model.IndexDocumentOptions; -import com.ibm.watson.developer_cloud.document_conversion.v1.model.IndexFields; -import com.ibm.watson.developer_cloud.http.HttpMediaType; - -/** - * Example class that shows the index document usage of the Document Conversion service. - */ -public class DocumentConversionIndexDocumentExample { - - public static void main(String[] args) { - DocumentConversion service = new DocumentConversion(DocumentConversion.VERSION_DATE_2015_12_01); - service.setUsernameAndPassword("", ""); - - // ----- Global Values ----- - IndexConfiguration indexConfiguration = - new IndexConfiguration("", "", ""); - - // Create an index configuration with the fields object (field mappings, fields to include, fields to exclude) - IndexFields fields = new IndexFields.Builder().mappings("Author", "Created By") - .mappings("Date Created", "Created On").include("SomeMetadataName").include("id").include("Created By") - .include("Created On").exclude("Category").build(); - IndexConfiguration indexConfigurationWithFields = - new IndexConfiguration("", "", "", fields); - - // Create some metadata for indexing - final Map metadata = new HashMap(); - metadata.put("id", "1"); - metadata.put("SomeMetadataName", "SomeMetadataValue"); - - // Create a convert document configuration that will exclude all anchor tags () from the input HTML file - String convertDocumentConfigAsString = "{ \"normalized_html\" : { \"exclude_tags_completely\":[\"a\"] } }"; - JsonParser jsonParser = new JsonParser(); - JsonObject convertDocumentConfig = jsonParser.parse(convertDocumentConfigAsString).getAsJsonObject(); - - // Sample file to index - File document = new File("src/test/resources/document_conversion/html-with-extra-content-input.htm"); - String html = "Sample HTML

Intro

Some content!

"; - InputStream documentInputStream = new ByteArrayInputStream(html.getBytes()); - - // ----- Examples for performing a dry run of the index document API ----- - printHeaderForExample("Dry run for indexing a document"); - IndexDocumentOptions indexDocumentOptions1 = - new IndexDocumentOptions.Builder().document(document).dryRun(true).build(); - String indexDocumentDryRun = service.indexDocument(indexDocumentOptions1).execute(); - System.out.println(indexDocumentDryRun); - - printHeaderForExample("Dry run for indexing a document (using input stream)"); - IndexDocumentOptions indexDocumentOptions2 = - new IndexDocumentOptions.Builder().document(documentInputStream, HttpMediaType.TEXT_HTML).dryRun(true).build(); - String indexDocumentInputStreamDryRun = service.indexDocument(indexDocumentOptions2).execute(); - System.out.println(indexDocumentInputStreamDryRun); - - printHeaderForExample("Dry run for indexing metadata"); - IndexDocumentOptions indexDocumentOptions3 = - new IndexDocumentOptions.Builder().metadata(metadata).dryRun(true).build(); - String indexMetadataDryRun = service.indexDocument(indexDocumentOptions3).execute(); - System.out.println(indexMetadataDryRun); - - printHeaderForExample("Dry run for indexing document and metadata"); - IndexDocumentOptions indexDocumentOptions4 = - new IndexDocumentOptions.Builder().document(document).metadata(metadata).dryRun(true).build(); - String indexDocumentAndMetadataDryRun = service.indexDocument(indexDocumentOptions4).execute(); - System.out.println(indexDocumentAndMetadataDryRun); - - printHeaderForExample("Dry run for indexing document with provided media type and metadata"); - IndexDocumentOptions indexDocumentOptions5 = new IndexDocumentOptions.Builder().document(document) - .metadata(metadata).mediaType(HttpMediaType.TEXT_HTML).dryRun(true).build(); - String indexDocumentWithMediaTypeAndMetadataDryRun = service.indexDocument(indexDocumentOptions5).execute(); - System.out.println(indexDocumentWithMediaTypeAndMetadataDryRun); - - printHeaderForExample( - "Dry run for indexing document with provided media type, metadata, and convert document config"); - IndexDocumentOptions indexDocumentOptions6 = - new IndexDocumentOptions.Builder().document(document).metadata(metadata).mediaType(HttpMediaType.TEXT_HTML) - .convertDocumentConfig(convertDocumentConfig).dryRun(true).build(); - String indexDocumentWithMediaTypeAndMetadataAndConfigDryRun = - service.indexDocument(indexDocumentOptions6).execute(); - System.out.println(indexDocumentWithMediaTypeAndMetadataAndConfigDryRun); - - printHeaderForExample("Index metadata"); - IndexDocumentOptions indexDocumentOptions7 = new IndexDocumentOptions.Builder().metadata(metadata) - .indexConfiguration(indexConfiguration).dryRun(false).build(); - String indexMetadata = service.indexDocument(indexDocumentOptions7).execute(); - System.out.println(indexMetadata); - - printHeaderForExample("Index a document and metadata"); - IndexDocumentOptions indexDocumentOptions8 = new IndexDocumentOptions.Builder().document(document) - .metadata(metadata).indexConfiguration(indexConfiguration).dryRun(false).build(); - String indexDocumentAndMetadata = service.indexDocument(indexDocumentOptions8).execute(); - System.out.println(indexDocumentAndMetadata); - - printHeaderForExample("Index document with provided media type and metadata"); - IndexDocumentOptions indexDocumentOptions9 = new IndexDocumentOptions.Builder().document(document) - .metadata(metadata).mediaType(HttpMediaType.TEXT_HTML).indexConfiguration(indexConfiguration).build(); - String indexDocumentWithMediaTypeAndMetadata = service.indexDocument(indexDocumentOptions9).execute(); - System.out.println(indexDocumentWithMediaTypeAndMetadata); - - printHeaderForExample("Index document with provided media type, metadata, and convert document config"); - IndexDocumentOptions indexDocumentOptions10 = - new IndexDocumentOptions.Builder().document(document).metadata(metadata).mediaType(HttpMediaType.TEXT_HTML) - .convertDocumentConfig(convertDocumentConfig).indexConfiguration(indexConfiguration).dryRun(false).build(); - String indexDocumentWithMediaTypeAndMetadataAndConfig = service.indexDocument(indexDocumentOptions10).execute(); - System.out.println(indexDocumentWithMediaTypeAndMetadataAndConfig); - - printHeaderForExample("Index document with provided media type, metadata, convert document config, and fields"); - IndexDocumentOptions indexDocumentOptions11 = new IndexDocumentOptions.Builder().document(document) - .metadata(metadata).mediaType(HttpMediaType.TEXT_HTML).convertDocumentConfig(convertDocumentConfig) - .indexConfiguration(indexConfigurationWithFields).dryRun(false).build(); - String indexDocumentWithMediaTypeAndMetadataConfigAndFields = - service.indexDocument(indexDocumentOptions11).execute(); - System.out.println(indexDocumentWithMediaTypeAndMetadataConfigAndFields); - } - - private static void printHeaderForExample(String message) { - System.out.println("\n================================================================================\n" + message - + "\n================================================================================\n"); - } -} diff --git a/examples/src/main/java/com/ibm/watson/developer_cloud/language_translator/v2/LanguageTranslatorExample.java b/examples/src/main/java/com/ibm/watson/developer_cloud/language_translator/v2/LanguageTranslatorExample.java index fb7b5901ded..69070b56281 100644 --- a/examples/src/main/java/com/ibm/watson/developer_cloud/language_translator/v2/LanguageTranslatorExample.java +++ b/examples/src/main/java/com/ibm/watson/developer_cloud/language_translator/v2/LanguageTranslatorExample.java @@ -27,7 +27,10 @@ public static void main(String[] args) { service.setUsernameAndPassword("", ""); TranslateOptions translateOptions = new TranslateOptions.Builder() - .addText("hello").source(Language.ENGLISH).target(Language.SPANISH).build(); + .addText("hello") + .source(Language.ENGLISH) + .target(Language.SPANISH) + .build(); TranslationResult translationResult = service.translate(translateOptions).execute(); System.out.println(translationResult); diff --git a/examples/src/main/java/com/ibm/watson/developer_cloud/natural_language_classifier/v1/NaturalLanguageClassifierExample.java b/examples/src/main/java/com/ibm/watson/developer_cloud/natural_language_classifier/v1/NaturalLanguageClassifierExample.java index 8e5854912e7..e6b433a0a4b 100644 --- a/examples/src/main/java/com/ibm/watson/developer_cloud/natural_language_classifier/v1/NaturalLanguageClassifierExample.java +++ b/examples/src/main/java/com/ibm/watson/developer_cloud/natural_language_classifier/v1/NaturalLanguageClassifierExample.java @@ -12,6 +12,7 @@ */ package com.ibm.watson.developer_cloud.natural_language_classifier.v1; +import com.ibm.watson.developer_cloud.natural_language_classifier.v1.model.ClassifyOptions; import com.ibm.watson.developer_cloud.natural_language_classifier.v1.model.Classification; public class NaturalLanguageClassifierExample { @@ -20,7 +21,11 @@ public static void main(String[] args) { NaturalLanguageClassifier service = new NaturalLanguageClassifier(); service.setUsernameAndPassword("", ""); - Classification classification = service.classify("", "Is it sunny?").execute(); + ClassifyOptions classifyOptions = new ClassifyOptions.Builder() + .classifierId("") + .text("Is it sunny?") + .build(); + Classification classification = service.classify(classifyOptions).execute(); System.out.println(classification); } diff --git a/examples/src/main/java/com/ibm/watson/developer_cloud/personality_insights/v2/PersonalityInsightsExample.java b/examples/src/main/java/com/ibm/watson/developer_cloud/personality_insights/v2/PersonalityInsightsExample.java deleted file mode 100644 index fcc30a29c28..00000000000 --- a/examples/src/main/java/com/ibm/watson/developer_cloud/personality_insights/v2/PersonalityInsightsExample.java +++ /dev/null @@ -1,40 +0,0 @@ -/** - * Copyright 2017 IBM Corp. All Rights Reserved. - * - * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with - * the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on - * an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the - * specific language governing permissions and limitations under the License. - */ -package com.ibm.watson.developer_cloud.personality_insights.v2; - -import com.ibm.watson.developer_cloud.personality_insights.v2.model.Profile; - -public class PersonalityInsightsExample { - - public static void main(String[] args) { - PersonalityInsights service = new PersonalityInsights(); - service.setUsernameAndPassword("", ""); - - String text = "Call me Ishmael. Some years ago-never mind how long " - + "precisely-having little or no money in my purse, and nothing " - + "particular to interest me on shore, I thought I would sail about " - + "a little and see the watery part of the world. It is a way " - + "I have of driving off the spleen and regulating the circulation. " - + "Whenever I find myself growing grim about the mouth; whenever it " - + "is a damp, drizzly November in my soul; whenever I find myself " - + "involuntarily pausing before coffin warehouses, and bringing up " - + "the rear of every funeral I meet; and especially whenever my " - + "hypos get such an upper hand of me, that it requires a strong " - + "moral principle to prevent me from deliberately stepping into " - + "the street, and methodically knocking people's hats off-then, " - + "I account it high time to get to sea as soon as I can."; - - Profile profile = service.getProfile(text).execute(); - System.out.println(profile); - } -} diff --git a/examples/src/main/java/com/ibm/watson/developer_cloud/personality_insights/v3/PersonalityInsightsExample.java b/examples/src/main/java/com/ibm/watson/developer_cloud/personality_insights/v3/PersonalityInsightsExample.java index b48267565f4..6dec3bd8a39 100644 --- a/examples/src/main/java/com/ibm/watson/developer_cloud/personality_insights/v3/PersonalityInsightsExample.java +++ b/examples/src/main/java/com/ibm/watson/developer_cloud/personality_insights/v3/PersonalityInsightsExample.java @@ -36,7 +36,9 @@ public static void main(String[] args) { + "the street, and methodically knocking people's hats off-then, " + "I account it high time to get to sea as soon as I can."; - ProfileOptions options = new ProfileOptions.Builder().text(text).build(); + ProfileOptions options = new ProfileOptions.Builder() + .text(text) + .build(); Profile profile = service.profile(options).execute(); System.out.println(profile); diff --git a/examples/src/main/java/com/ibm/watson/developer_cloud/retrieve_and_rank/v1/CreateARankerExample.java b/examples/src/main/java/com/ibm/watson/developer_cloud/retrieve_and_rank/v1/CreateARankerExample.java deleted file mode 100644 index 9ac0fc3d2a1..00000000000 --- a/examples/src/main/java/com/ibm/watson/developer_cloud/retrieve_and_rank/v1/CreateARankerExample.java +++ /dev/null @@ -1,50 +0,0 @@ -/** - * Copyright 2017 IBM Corp. All Rights Reserved. - * - * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with - * the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on - * an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the - * specific language governing permissions and limitations under the License. - */ -package com.ibm.watson.developer_cloud.retrieve_and_rank.v1; - -import java.io.File; - -import com.ibm.watson.developer_cloud.retrieve_and_rank.v1.model.Ranker; -import com.ibm.watson.developer_cloud.retrieve_and_rank.v1.model.Ranker.Status; -import com.ibm.watson.developer_cloud.retrieve_and_rank.v1.model.Ranking; - -/** - * Example of how to create a {@link Ranking} with {@link RetrieveAndRank}. - */ -public class CreateARankerExample { - - public static void main(String[] args) throws InterruptedException { - // 1 create the service - RetrieveAndRank service = new RetrieveAndRank(); - service.setUsernameAndPassword("", ""); - - // 2 create a ranker - Ranker ranker = service.createRanker("example-ranker-1", new File("")).execute(); - System.out.println("ranker: " + ranker); - - // 3 wait until is trained - while (ranker.getStatus() == Status.TRAINING) { - Thread.sleep(4000); // sleep 4 seconds - ranker = service.getRankerStatus(ranker.getId()).execute(); - System.out.println("ranker status: " + ranker.getStatus()); - } - - // 4 rank answers - Ranking ranking = service.rank(ranker.getId(), new File(""), 5).execute(); - System.out.println("ranking: " + ranking); - - // 5 delete ranker - service.deleteRanker(ranker.getId()); - - } -} diff --git a/examples/src/main/java/com/ibm/watson/developer_cloud/retrieve_and_rank/v1/CreateASolrClusterExample.java b/examples/src/main/java/com/ibm/watson/developer_cloud/retrieve_and_rank/v1/CreateASolrClusterExample.java deleted file mode 100644 index 59a96a88775..00000000000 --- a/examples/src/main/java/com/ibm/watson/developer_cloud/retrieve_and_rank/v1/CreateASolrClusterExample.java +++ /dev/null @@ -1,45 +0,0 @@ -/** - * Copyright 2017 IBM Corp. All Rights Reserved. - * - * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with - * the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on - * an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the - * specific language governing permissions and limitations under the License. - */ -package com.ibm.watson.developer_cloud.retrieve_and_rank.v1; - -import com.ibm.watson.developer_cloud.retrieve_and_rank.v1.model.SolrCluster; -import com.ibm.watson.developer_cloud.retrieve_and_rank.v1.model.SolrCluster.Status; -import com.ibm.watson.developer_cloud.retrieve_and_rank.v1.model.SolrClusterOptions; - -/** - * Example of how to create a {@link SolrCluster} with {@link RetrieveAndRank}. - */ -public class CreateASolrClusterExample { - public static void main(String[] args) throws InterruptedException { - - // 1 create the service - RetrieveAndRank service = new RetrieveAndRank(); - service.setUsernameAndPassword("", ""); - - // 2 create the Solr Cluster - SolrClusterOptions options = new SolrClusterOptions("", 1); - SolrCluster cluster = service.createSolrCluster(options).execute(); - System.out.println("SolrCluster: " + cluster); - - // 2 wait until the Solr Cluster is available - while (cluster.getStatus() == Status.NOT_AVAILABLE) { - Thread.sleep(10000); // sleep 10 seconds - cluster = service.getSolrCluster(cluster.getId()).execute(); - System.out.println("SolrCluster status: " + cluster.getStatus()); - } - - // 3 list Solr Clusters - System.out.println("Solr clusters: " + service.getSolrClusters().execute()); - - } -} diff --git a/examples/src/main/java/com/ibm/watson/developer_cloud/retrieve_and_rank/v1/ResizeASolrClusterExample.java b/examples/src/main/java/com/ibm/watson/developer_cloud/retrieve_and_rank/v1/ResizeASolrClusterExample.java deleted file mode 100644 index 6c135c67275..00000000000 --- a/examples/src/main/java/com/ibm/watson/developer_cloud/retrieve_and_rank/v1/ResizeASolrClusterExample.java +++ /dev/null @@ -1,58 +0,0 @@ -/* - * Copyright 2017 IBM Corp. All Rights Reserved. - * - * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with - * the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on - * an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the - * specific language governing permissions and limitations under the License. - */ -package com.ibm.watson.developer_cloud.retrieve_and_rank.v1; - -import com.ibm.watson.developer_cloud.retrieve_and_rank.v1.model.SolrCluster; -import com.ibm.watson.developer_cloud.retrieve_and_rank.v1.model.SolrCluster.Status; -import com.ibm.watson.developer_cloud.retrieve_and_rank.v1.model.SolrClusterOptions; -import com.ibm.watson.developer_cloud.retrieve_and_rank.v1.model.SolrClusterSizeResponse; - -/** - * Example of how to create and resize a {@link SolrCluster} with {@link RetrieveAndRank}. - */ -public class ResizeASolrClusterExample { - public static void main(String[] args) throws InterruptedException { - - // 1 create the service - final RetrieveAndRank service = new RetrieveAndRank(); - service.setUsernameAndPassword("", ""); - // 2 create the Solr Cluster of size 1 - final SolrClusterOptions options = new SolrClusterOptions("", 1); - SolrCluster cluster = service.createSolrCluster(options).execute(); - System.out.println("SolrCluster: " + cluster); - final String solrClusterId = cluster.getId(); - // 2 wait until the Solr Cluster is available - while (cluster.getStatus() == Status.NOT_AVAILABLE) { - Thread.sleep(10000); // sleep 10 seconds - cluster = service.getSolrCluster(solrClusterId).execute(); - System.out.println("SolrCluster status: " + cluster.getStatus()); - } - // 3 resize the cluster form size 1 to size 2 - final int desiredClusterSize = 2; - SolrClusterSizeResponse response = service.resizeSolrCluster(solrClusterId, desiredClusterSize).execute(); - System.out.println(response.toString()); - - // 4 wait until the resize processs is complete - while (response.getCurrentSize() != desiredClusterSize) { - if (response.getStatus() == SolrClusterSizeResponse.Status.ERROR) { - System.out.println(response.getMessage()); - return; - } - System.out.println("Resize status: " + response.getStatus()); - Thread.sleep(10000); - response = service.getSolrClusterResizeStatus(solrClusterId).execute(); - } - System.out.println(response.getMessage()); - System.out.println("resize completed"); - } -} diff --git a/examples/src/main/java/com/ibm/watson/developer_cloud/retrieve_and_rank/v1/UploadSolrConfigurationExample.java b/examples/src/main/java/com/ibm/watson/developer_cloud/retrieve_and_rank/v1/UploadSolrConfigurationExample.java deleted file mode 100644 index 9fe88bb3461..00000000000 --- a/examples/src/main/java/com/ibm/watson/developer_cloud/retrieve_and_rank/v1/UploadSolrConfigurationExample.java +++ /dev/null @@ -1,45 +0,0 @@ -/** - * Copyright 2017 IBM Corp. All Rights Reserved. - * - * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with - * the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on - * an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the - * specific language governing permissions and limitations under the License. - */ -package com.ibm.watson.developer_cloud.retrieve_and_rank.v1; - -import java.io.File; -import java.util.List; - -import com.ibm.watson.developer_cloud.retrieve_and_rank.v1.model.SolrCluster; - -/** - * Creates a SolrClusterConfiguration using the {@link RetrieveAndRank} service. - *

- * You must first create a Solr cluster and specify its ID here. A Solr cluster can be created with the - * {@link CreateASolrClusterExample}. - */ -public class UploadSolrConfigurationExample { - - public static void main(String[] args) { - // 1 create the service - RetrieveAndRank service = new RetrieveAndRank(); - service.setUsernameAndPassword("", ""); - - // 2 return the existing SolrCluster using the id - SolrCluster cluster = service.getSolrCluster("").execute(); - System.out.println("SolrCluster: " + cluster); - - // 3 upload the Solr configuration directory - File directory = new File("src/test/resources/retrieve_and_rank"); - service.uploadSolrClusterConfigurationDirectory(cluster.getId(), "", directory); - - // 4 list the existing solr configurations - List configs = service.getSolrClusterConfigurations(cluster.getId()).execute().getSolrConfigs(); - System.out.println("Solr configurations: " + configs); - } -} diff --git a/examples/src/main/java/com/ibm/watson/developer_cloud/speech_to_text/v1/CustomizationExample.java b/examples/src/main/java/com/ibm/watson/developer_cloud/speech_to_text/v1/CustomizationExample.java index 451fddffde0..15d36c81619 100755 --- a/examples/src/main/java/com/ibm/watson/developer_cloud/speech_to_text/v1/CustomizationExample.java +++ b/examples/src/main/java/com/ibm/watson/developer_cloud/speech_to_text/v1/CustomizationExample.java @@ -15,17 +15,24 @@ import java.io.File; import java.util.List; +import com.ibm.watson.developer_cloud.speech_to_text.v1.model.AddCorpusOptions; +import com.ibm.watson.developer_cloud.speech_to_text.v1.model.AddWordOptions; +import com.ibm.watson.developer_cloud.speech_to_text.v1.model.Corpora; import com.ibm.watson.developer_cloud.speech_to_text.v1.model.Corpus; -import com.ibm.watson.developer_cloud.speech_to_text.v1.model.Corpus.Status; -import com.ibm.watson.developer_cloud.speech_to_text.v1.model.Customization; +import com.ibm.watson.developer_cloud.speech_to_text.v1.model.CreateLanguageModelOptions; +import com.ibm.watson.developer_cloud.speech_to_text.v1.model.DeleteLanguageModelOptions; +import com.ibm.watson.developer_cloud.speech_to_text.v1.model.GetCorpusOptions; +import com.ibm.watson.developer_cloud.speech_to_text.v1.model.GetLanguageModelOptions; +import com.ibm.watson.developer_cloud.speech_to_text.v1.model.LanguageModel; +import com.ibm.watson.developer_cloud.speech_to_text.v1.model.ListCorporaOptions; +import com.ibm.watson.developer_cloud.speech_to_text.v1.model.ListWordsOptions; import com.ibm.watson.developer_cloud.speech_to_text.v1.model.RecognizeOptions; -import com.ibm.watson.developer_cloud.speech_to_text.v1.model.SpeechModel; -import com.ibm.watson.developer_cloud.speech_to_text.v1.model.SpeechResults; -import com.ibm.watson.developer_cloud.speech_to_text.v1.model.Word; -import com.ibm.watson.developer_cloud.speech_to_text.v1.model.WordData; +import com.ibm.watson.developer_cloud.speech_to_text.v1.model.SpeechRecognitionResults; +import com.ibm.watson.developer_cloud.speech_to_text.v1.model.TrainLanguageModelOptions; +import com.ibm.watson.developer_cloud.speech_to_text.v1.model.Words; /** - * Example of how to create and use a customization model. + * Example of how to create and use a custom language model. */ public class CustomizationExample { @@ -42,65 +49,124 @@ public static void main(String[] args) throws InterruptedException { SpeechToText service = new SpeechToText(); service.setUsernameAndPassword("", ""); - // Create customization - Customization myCustomization = - service.createCustomization("IEEE-permanent", SpeechModel.EN_US_BROADBANDMODEL, "My customization").execute(); - String id = myCustomization.getId(); + // Create language model + CreateLanguageModelOptions createOptions = new CreateLanguageModelOptions.Builder() + .name("IEEE-permanent") + .baseModelName("en-US_BroadbandModel") + .description("My customization") + .build(); + LanguageModel myModel = service.createLanguageModel(createOptions).execute(); + String id = myModel.getCustomizationId(); try { - // Add a corpus file to the model: - service.addCorpus(id, "corpus-1", new File(CORPUS_FILE), false).execute(); + // Add a corpus file to the model + AddCorpusOptions addOptions = new AddCorpusOptions.Builder() + .customizationId(id) + .corpusName("corpus-1") + .corpusFile(new File(CORPUS_FILE)) + .corpusFileContentType(HttpMediaType.TEXT_PLAIN) + .allowOverwrite(false) + .build(); + service.addCorpus(addOptions).execute(); // Get corpus status - for (int x = 0; x < 30 && (service.getCorpus(id, "corpus-1").execute()).getStatus() != Status.ANALYZED; x++) { + GetCorpusOptions getOptions = new GetCorpusOptions.Builder() + .customizationId(id) + .corpusName("corpus-1") + .build(); + for (int x = 0; x < 30 && (service.getCorpus(getOptions).execute()).getStatus() != Status.ANALYZED; x++) { Thread.sleep(5000); } // Get all corpora - List corpora = service.getCorpora(id).execute(); + ListCorporaOptions listCorporaOptions = new ListCorporaOptions.Builder() + .customizationId(id) + .build(); + Corpora corpora = service.listCorpora(listCorporaOptions).execute(); System.out.println(corpora); // Get specific corpus - Corpus corpus = service.getCorpus(id, "corpus-1").execute(); + Corpus corpus = service.getCorpus(getOptions).execute(); System.out.println(corpus); // Now add some user words to the custom model - service.addWord(id, new Word("IEEE", "IEEE", "I. triple E.")).execute(); - service.addWord(id, new Word("hhonors", "IEEE", "H. honors", "Hilton honors")).execute(); + service.addWord(new AddWordOptions.Builder() + .customizationId(id) + .wordName("IEEE") + .word("IEEE") + .displayAs("IEEE") + .addSoundsLike("I. triple E.") + .build()).execute(); + service.addWord(new AddWordOptions.Builder() + .customizationId(id) + .wordName("hhonors") + .word("hhonors") + .displayAs("IEEE") + .addSoundsLike("H. honors") + .addSoundsLike("Hilton honors") + .build()).execute(); // Display all words in the words resource (OOVs from the corpus and // new words just added) in ascending alphabetical order - List result = service.getWords(id, Word.Type.ALL).execute(); + ListWordsOptions listWordsAlphabeticalOptions = new ListWordsOptions.Builder() + .customizationId(id) + .wordType(ListWordsOptions.WordType.ALL) + .build(); + Words words = service.listWords(listWordsAlphabeticalOptions).execute(); System.out.println("\nASCENDING ALPHABETICAL ORDER:"); - System.out.println(result); + System.out.println(words); // Then display all words in the words resource in descending order // by count - result = service.getWords(id, Word.Type.ALL, Word.Sort.MINUS_COUNT).execute(); + ListWordsOptions listWordsCountOptions = new ListWordsOptions.Builder() + .customizationId(id) + .wordType(ListWordsOptions.WordType.ALL) + .sort("-" + ListWordsOptions.Sort.COUNT) + .build(); + words = service.listWords(listWordsCountOptions).execute(); System.out.println("\nDESCENDING ORDER BY COUNT:"); - System.out.println(result); + System.out.println(words); // Now start training of the model - service.trainCustomization(id, Customization.WordTypeToAdd.ALL).execute(); - - for (int x = 0; x < 30 && myCustomization.getStatus() != Customization.Status.AVAILABLE; x++) { - myCustomization = service.getCustomization(id).execute(); + TrainLanguageModelOptions trainOptions = new TrainLanguageModelOptions.Builder() + .customizationId(id) + .wordTypeToAdd(TrainLanguageModelOptions.WordTypeToAdd.ALL) + .build(); + service.trainLanguageModel(trainOptions).execute(); + + for (int x = 0; x < 30 && myModel.getStatus() != LanguageModel.Status.AVAILABLE; x++) { + GetLanguageModelOptions getOptions = new GetLanguageModelOptions.Builder() + .customizationId(id) + .build(); + myModel = service.getLanguageModel(getOptions).execute(); Thread.sleep(10000); } File audio = new File(AUDIO_FILE); - RecognizeOptions options = new RecognizeOptions.Builder().continuous(true) - .model(SpeechModel.EN_US_BROADBANDMODEL.getName()).customizationId(id).build(); + RecognizeOptions recognizeOptionsWithModel = new RecognizeOptions.Builder() + .model(RecognizeOptions.EN_US_BROADBANDMODEL) + .customizationId(id) + .audio(audio) + .contentType(HttpMediaType.AUDIO_WAV) + .build(); + RecognizeOptions recognizeOptionsWithoutModel = new RecognizeOptions.Builder() + .model(RecognizeOptions.EN_US_BROADBANDMODEL) + .audio(audio) + .contentType(HttpMediaType.AUDIO_WAV) + .build(); // First decode WITHOUT the custom model - SpeechResults transcript = service.recognize(audio).execute(); + SpeechRecognitionResults transcript = service.recognize(recognizeOptionsWithoutModel).execute(); System.out.println(transcript); // Now decode with the custom model - transcript = service.recognize(audio, options).execute(); + transcript = service.recognize(recognizeOptionsWithModel).execute(); System.out.println(transcript); } finally { - service.deleteCustomization(id); + DeleteLanguageModelOptions deleteOptions = new DeleteLanguageModelOptions.Builder() + .customizationId(id) + .build(); + service.deleteLanguageModel(deleteOptions).execute(); } } diff --git a/examples/src/main/java/com/ibm/watson/developer_cloud/speech_to_text/v1/MicrophoneWithWebSocketsExample.java b/examples/src/main/java/com/ibm/watson/developer_cloud/speech_to_text/v1/MicrophoneWithWebSocketsExample.java index 9cc722133ad..9984c852668 100644 --- a/examples/src/main/java/com/ibm/watson/developer_cloud/speech_to_text/v1/MicrophoneWithWebSocketsExample.java +++ b/examples/src/main/java/com/ibm/watson/developer_cloud/speech_to_text/v1/MicrophoneWithWebSocketsExample.java @@ -20,7 +20,7 @@ import com.ibm.watson.developer_cloud.http.HttpMediaType; import com.ibm.watson.developer_cloud.speech_to_text.v1.model.RecognizeOptions; -import com.ibm.watson.developer_cloud.speech_to_text.v1.model.SpeechResults; +import com.ibm.watson.developer_cloud.speech_to_text.v1.model.SpeechRecognitionResults; import com.ibm.watson.developer_cloud.speech_to_text.v1.websocket.BaseRecognizeCallback; /** @@ -54,14 +54,18 @@ public static void main(final String[] args) throws Exception { AudioInputStream audio = new AudioInputStream(line); - RecognizeOptions options = - new RecognizeOptions.Builder().continuous(true).interimResults(true).timestamps(true).wordConfidence(true) - // .inactivityTimeout(5) // use this to stop listening when the speaker pauses, i.e. for 5s - .contentType(HttpMediaType.AUDIO_RAW + "; rate=" + sampleRate).build(); + RecognizeOptions options = new RecognizeOptions.Builder() + .audio(audio) + .interimResults(true) + .timestamps(true) + .wordConfidence(true) + //.inactivityTimeout(5) // use this to stop listening when the speaker pauses, i.e. for 5s + .contentType(HttpMediaType.AUDIO_RAW + ";rate=" + sampleRate) + .build(); - service.recognizeUsingWebSocket(audio, options, new BaseRecognizeCallback() { + service.recognizeUsingWebSocket(options, new BaseRecognizeCallback() { @Override - public void onTranscription(SpeechResults speechResults) { + public void onTranscription(SpeechRecognitionResults speechResults) { System.out.println(speechResults); } }); diff --git a/examples/src/main/java/com/ibm/watson/developer_cloud/speech_to_text/v1/RecognizeUsingWebSocketsExample.java b/examples/src/main/java/com/ibm/watson/developer_cloud/speech_to_text/v1/RecognizeUsingWebSocketsExample.java index aad12e89261..efb7357dfd9 100644 --- a/examples/src/main/java/com/ibm/watson/developer_cloud/speech_to_text/v1/RecognizeUsingWebSocketsExample.java +++ b/examples/src/main/java/com/ibm/watson/developer_cloud/speech_to_text/v1/RecognizeUsingWebSocketsExample.java @@ -19,7 +19,7 @@ import com.ibm.watson.developer_cloud.http.HttpMediaType; import com.ibm.watson.developer_cloud.speech_to_text.v1.model.RecognizeOptions; -import com.ibm.watson.developer_cloud.speech_to_text.v1.model.SpeechResults; +import com.ibm.watson.developer_cloud.speech_to_text.v1.model.SpeechRecognitionResults; import com.ibm.watson.developer_cloud.speech_to_text.v1.websocket.BaseRecognizeCallback; /** @@ -34,12 +34,15 @@ public static void main(String[] args) throws FileNotFoundException, Interrupted FileInputStream audio = new FileInputStream("src/test/resources/speech_to_text/sample1.wav"); - RecognizeOptions options = new RecognizeOptions.Builder().continuous(true).interimResults(true) - .contentType(HttpMediaType.AUDIO_WAV).build(); + RecognizeOptions options = new RecognizeOptions.Builder() + .audio(audio) + .interimResults(true) + .contentType(HttpMediaType.AUDIO_WAV) + .build(); - service.recognizeUsingWebSocket(audio, options, new BaseRecognizeCallback() { + service.recognizeUsingWebSocket(options, new BaseRecognizeCallback() { @Override - public void onTranscription(SpeechResults speechResults) { + public void onTranscription(SpeechRecognitionResults speechResults) { System.out.println(speechResults); } diff --git a/examples/src/main/java/com/ibm/watson/developer_cloud/speech_to_text/v1/RecognizeUsingWebSocketsWithSpeakerLabelsExample.java b/examples/src/main/java/com/ibm/watson/developer_cloud/speech_to_text/v1/RecognizeUsingWebSocketsWithSpeakerLabelsExample.java index a5a0ee99f35..25dc2b39ca3 100644 --- a/examples/src/main/java/com/ibm/watson/developer_cloud/speech_to_text/v1/RecognizeUsingWebSocketsWithSpeakerLabelsExample.java +++ b/examples/src/main/java/com/ibm/watson/developer_cloud/speech_to_text/v1/RecognizeUsingWebSocketsWithSpeakerLabelsExample.java @@ -26,10 +26,9 @@ import com.ibm.watson.developer_cloud.speech_to_text.v1.model.RecognizeOptions; import com.ibm.watson.developer_cloud.speech_to_text.v1.model.SpeakerLabel; import com.ibm.watson.developer_cloud.speech_to_text.v1.model.SpeechAlternative; -import com.ibm.watson.developer_cloud.speech_to_text.v1.model.SpeechModel; -import com.ibm.watson.developer_cloud.speech_to_text.v1.model.SpeechResults; +import com.ibm.watson.developer_cloud.speech_to_text.v1.model.SpeechRecognitionResult; +import com.ibm.watson.developer_cloud.speech_to_text.v1.model.SpeechRecognitionResults; import com.ibm.watson.developer_cloud.speech_to_text.v1.model.SpeechTimestamp; -import com.ibm.watson.developer_cloud.speech_to_text.v1.model.Transcript; import com.ibm.watson.developer_cloud.speech_to_text.v1.websocket.BaseRecognizeCallback; import com.ibm.watson.developer_cloud.util.GsonSingleton; @@ -38,7 +37,7 @@ public class RecognizeUsingWebSocketsWithSpeakerLabelsExample { public static class RecoToken { private Double startTime; private Double endTime; - private Integer speaker; + private Long speaker; private String word; private Boolean spLabelIsFinal; @@ -58,9 +57,9 @@ public static class RecoToken { * * @param speakerLabel the speaker label */ - RecoToken(SpeakerLabel speakerLabel) { - startTime = speakerLabel.getFrom(); - endTime = speakerLabel.getTo(); + RecoToken(SpeakerLabelsResult speakerLabel) { + startTime = (Double) speakerLabel.getFrom(); + endTime = (Double) speakerLabel.getTo(); speaker = speakerLabel.getSpeaker(); } @@ -78,7 +77,7 @@ void updateFrom(SpeechTimestamp speechTimestamp) { * * @param speakerLabel the speaker label */ - void updateFrom(SpeakerLabel speakerLabel) { + void updateFrom(SpeakerLabelsResult speakerLabel) { speaker = speakerLabel.getSpeaker(); } } @@ -121,12 +120,12 @@ public RecoTokens() { * * @param speechResults the speech results */ - public void add(SpeechResults speechResults) { + public void add(SpeechRecognitionResults speechResults) { if (speechResults.getResults() != null) for (int i = 0; i < speechResults.getResults().size(); i++) { - Transcript transcript = speechResults.getResults().get(i); - if (transcript.isFinal()) { - SpeechAlternative speechAlternative = transcript.getAlternatives().get(0); + SpeechRecognitionResult transcript = speechResults.getResults().get(i); + if (transcript.isFinalResults()) { + SpeechRecognitionAlternative speechAlternative = transcript.getAlternatives().get(0); for (int ts = 0; ts < speechAlternative.getTimestamps().size(); ts++) { SpeechTimestamp speechTimestamp = speechAlternative.getTimestamps().get(ts); @@ -161,7 +160,7 @@ public void add(SpeechTimestamp speechTimestamp) { * * @param speakerLabel the speaker label */ - public void add(SpeakerLabel speakerLabel) { + public void add(SpeakerLabelsResult speakerLabel) { RecoToken recoToken = recoTokenMap.get(speakerLabel.getFrom()); if (recoToken == null) { recoToken = new RecoToken(speakerLabel); @@ -170,14 +169,14 @@ public void add(SpeakerLabel speakerLabel) { recoToken.updateFrom(speakerLabel); } - if (speakerLabel.isFinal()) { + if (speakerLabel.isFinalResults()) { markTokensBeforeAsFinal(speakerLabel.getFrom()); report(); cleanFinal(); } } - private void markTokensBeforeAsFinal(Double from) { + private void markTokensBeforeAsFinal(Float from) { Map recoTokenMap = new LinkedHashMap<>(); for (RecoToken rt : recoTokenMap.values()) { @@ -233,13 +232,18 @@ public static void main(String[] args) throws FileNotFoundException, Interrupted SpeechToText service = new SpeechToText(); service.setUsernameAndPassword("", ""); - RecognizeOptions options = new RecognizeOptions.Builder().continuous(true).interimResults(true).speakerLabels(true) - .model(SpeechModel.EN_US_NARROWBANDMODEL.getName()).contentType(HttpMediaType.AUDIO_WAV).build(); + RecognizeOptions options = new RecognizeOptions.Builder() + .audio(audio) + .interimResults(true) + .speakerLabels(true) + .model(RecognizeOptions.EN_US_NARROWBANDMODEL) + .contentType(HttpMediaType.AUDIO_WAV) + .build(); RecoTokens recoTokens = new RecoTokens(); - service.recognizeUsingWebSocket(audio, options, new BaseRecognizeCallback() { + service.recognizeUsingWebSocket(options, new BaseRecognizeCallback() { @Override - public void onTranscription(SpeechResults speechResults) { + public void onTranscription(SpeechRecognitionResults speechResults) { recoTokens.add(speechResults); } diff --git a/examples/src/main/java/com/ibm/watson/developer_cloud/speech_to_text/v1/SpeechToTextExample.java b/examples/src/main/java/com/ibm/watson/developer_cloud/speech_to_text/v1/SpeechToTextExample.java index dca000e4095..926d48c4668 100644 --- a/examples/src/main/java/com/ibm/watson/developer_cloud/speech_to_text/v1/SpeechToTextExample.java +++ b/examples/src/main/java/com/ibm/watson/developer_cloud/speech_to_text/v1/SpeechToTextExample.java @@ -14,8 +14,8 @@ import java.io.File; -import com.ibm.watson.developer_cloud.speech_to_text.v1.model.SpeechResults; - +import com.ibm.watson.developer_cloud.speech_to_text.v1.model.RecognizeOptions; +import com.ibm.watson.developer_cloud.speech_to_text.v1.model.SpeechRecognitionResults; /** * Recognize a sample wav file and print the transcript into the console output. Make sure you are using UTF-8 to print @@ -28,7 +28,11 @@ public static void main(String[] args) { service.setUsernameAndPassword("", ""); File audio = new File("src/test/resources/speech_to_text/sample1.wav"); - SpeechResults transcript = service.recognize(audio).execute(); + RecognizeOptions options = new RecognizeOptions.Builder() + .audio(audio) + .contentType(RecognizeOptions.ContentType.AUDIO_WAV) + .build(); + SpeechRecognitionResults transcript = service.recognize(options).execute(); System.out.println(transcript); } diff --git a/examples/src/main/java/com/ibm/watson/developer_cloud/text_to_speech/v1/CustomizationExample.java b/examples/src/main/java/com/ibm/watson/developer_cloud/text_to_speech/v1/CustomizationExample.java index cd0e4f3c146..aeff9ab8a76 100755 --- a/examples/src/main/java/com/ibm/watson/developer_cloud/text_to_speech/v1/CustomizationExample.java +++ b/examples/src/main/java/com/ibm/watson/developer_cloud/text_to_speech/v1/CustomizationExample.java @@ -12,6 +12,7 @@ */ package com.ibm.watson.developer_cloud.text_to_speech.v1; +import java.util.Arrays; import java.io.File; import java.io.FileOutputStream; import java.io.IOException; @@ -19,11 +20,25 @@ import java.io.OutputStream; import java.util.List; -import com.ibm.watson.developer_cloud.text_to_speech.v1.model.AudioFormat; -import com.ibm.watson.developer_cloud.text_to_speech.v1.model.CustomTranslation; -import com.ibm.watson.developer_cloud.text_to_speech.v1.model.CustomVoiceModel; +import com.ibm.watson.developer_cloud.text_to_speech.v1.model.AddWordOptions; +import com.ibm.watson.developer_cloud.text_to_speech.v1.model.AddWordsOptions; +import com.ibm.watson.developer_cloud.text_to_speech.v1.model.CreateVoiceModelOptions; +import com.ibm.watson.developer_cloud.text_to_speech.v1.model.DeleteVoiceModelOptions; +import com.ibm.watson.developer_cloud.text_to_speech.v1.model.DeleteWordOptions; +import com.ibm.watson.developer_cloud.text_to_speech.v1.model.GetVoiceModelOptions; +import com.ibm.watson.developer_cloud.text_to_speech.v1.model.GetVoiceOptions; +import com.ibm.watson.developer_cloud.text_to_speech.v1.model.GetWordOptions; +import com.ibm.watson.developer_cloud.text_to_speech.v1.model.ListVoiceModelsOptions; +import com.ibm.watson.developer_cloud.text_to_speech.v1.model.ListWordsOptions; +import com.ibm.watson.developer_cloud.text_to_speech.v1.model.SynthesizeOptions; +import com.ibm.watson.developer_cloud.text_to_speech.v1.model.Translation; +import com.ibm.watson.developer_cloud.text_to_speech.v1.model.UpdateVoiceModelOptions; import com.ibm.watson.developer_cloud.text_to_speech.v1.model.Voice; +import com.ibm.watson.developer_cloud.text_to_speech.v1.model.VoiceModel; +import com.ibm.watson.developer_cloud.text_to_speech.v1.model.VoiceModels; import com.ibm.watson.developer_cloud.text_to_speech.v1.util.WaveUtils; +import com.ibm.watson.developer_cloud.text_to_speech.v1.model.Word; +import com.ibm.watson.developer_cloud.text_to_speech.v1.model.Words; public class CustomizationExample { @@ -31,53 +46,101 @@ public static void main(String[] args) throws IOException { TextToSpeech service = new TextToSpeech("", ""); // create custom voice model. - CustomVoiceModel customVoiceModel = service.createCustomVoiceModel("my model", "en-US", "the model for testing") - .execute(); + CreateVoiceModelOptions createOptions = new CreateVoiceModelOptions.Builder() + .name("my model") + .language("en-US") + .description("the model for testing") + .build(); + VoiceModel customVoiceModel = service.createVoiceModel(createOptions).execute(); System.out.println(customVoiceModel); // list custom voice models for US English. - List customVoiceModels = service.getCustomVoiceModels("en-US").execute(); + ListVoiceModelsOptions listOptions = new ListVoiceModelsOptions.Builder() + .language("en-US") + .build(); + VoiceModels customVoiceModels = service.listVoiceModels(listOptions); System.out.println(customVoiceModels); // update custom voice model. - customVoiceModel.setName("my updated model"); - customVoiceModel.setDescription("the updated model for testing"); - service.updateCustomVoiceModel(customVoiceModel).execute(); + UpdateVoiceModelOptions updateOptions = new UpdateVoiceModelOptions.Builder() + .customizationId(customVoiceModel.getCustomizationId()) + .name(newName) + .description("the updated model for testing") + .build(); + service.updateVoiceModel(updateOptions).execute(); // list custom voice models regardless of language. - customVoiceModels = service.getCustomVoiceModels(null).execute(); + customVoiceModels = service.listVoiceModels().execute(); System.out.println(customVoiceModels); // create multiple custom word translations - CustomTranslation customTranslation1 = new CustomTranslation("hodor", "hold the door"); - CustomTranslation customTranslation2 = new CustomTranslation("plz", "please"); - service.addWords(customVoiceModel, customTranslation1, customTranslation2).execute(); + Word word1 = new Word(); + word1.setWord("hodor"); + word1.setTranslation("hold the door"); + Word word2 = new Word(); + word2.setWord("plz"); + word2.setTranslation("please"); + List words = Arrays.asList(word1, word2); + AddWordsOptions addOptions = new AddWordsOptions.Builder() + .customizationId(customVoiceModel.getCustomizationId()) + .words(words) + .build(); + service.addWords(addOptions).execute(); // create a single custom word translation - service.addWord(customVoiceModel, new CustomTranslation("nat", "and that")).execute(); + AddWordOptions addOptions = new AddWordOptions.Builder() + .word("nat") + .translation("and that") + .customizationId(customVoiceModel.getCustomizationId()) + .build(); + service.addWord(addOptions).execute(); // get custom word translations - List words = service.getWords(customVoiceModel).execute(); + ListWordsOptions listOptions = new ListWordsOptions.Builder() + .customizationId(customVoiceModel.getCustomizationId()) + .build(); + Words words = service.listWords(listOptions).execute(); System.out.println(words); // get custom word translation - CustomTranslation translation = service.getWord(customVoiceModel, "hodor").execute(); + GetWordOptions getOptions = new GetWordOptions.Builder() + .customizationId(customVoiceModel.getCustomizationId()) + .word("hodor") + .build(); + Translation translation = service.getWord(getOptions).execute(); System.out.println(translation); // synthesize with custom voice model String text = "plz hodor"; - InputStream in = service.synthesize(text, Voice.EN_MICHAEL, AudioFormat.WAV, customVoiceModel.getId()).execute(); + SynthesizeOptions synthesizeOptions = new SynthesizeOptions.Builder() + .text(text) + .voice(SynthesizeOptions.Voice.EN_US_MICHAELVOICE) + .accept(SynthesizeOptions.Accept.AUDIO_WAV) + .customizationId(customVoiceModel.getCustomizationId()) + .build(); + InputStream in = service.synthesize(synthesizeOptions).execute(); writeToFile(WaveUtils.reWriteWaveHeader(in), new File("output.wav")); // delete custom words with object and string - service.deleteWord(customVoiceModel, customTranslation1); - service.deleteWord(customVoiceModel, customTranslation2.getWord()); + DeleteWordOptions deleteOptions1 = new DeleteWordOptions.Builder() + .customizationId(customVoiceModel.getCustomizationId()) + .word(word1.getWord()) + .build(); + service.deleteWord(deleteOptions1).execute(); + DeleteWordOptions deleteOptions2 = new DeleteWordOptions.Builder() + .customizationId(customVoiceModel.getCustomizationId()) + .word(word2.getWord()) + .build(); + service.deleteWord(deleteOptions2).execute(); // delete custom voice model - service.deleteCustomVoiceModel(customVoiceModel).execute(); + DeleteVoiceModelOptions deleteOptions = new DeleteVoiceModelOptions.Builder() + .customizationId(customVoiceModel.getCustomizationId()) + .build(); + service.deleteVoiceModel(deleteOptions).execute(); // list custom voice models regardless of language. - customVoiceModels = service.getCustomVoiceModels(null).execute(); + customVoiceModels = service.listVoiceModels().execute(); System.out.println(customVoiceModels); } diff --git a/examples/src/main/java/com/ibm/watson/developer_cloud/text_to_speech/v1/TextToSpeechExample.java b/examples/src/main/java/com/ibm/watson/developer_cloud/text_to_speech/v1/TextToSpeechExample.java index dfa938a9bbf..ed72b9e81a2 100644 --- a/examples/src/main/java/com/ibm/watson/developer_cloud/text_to_speech/v1/TextToSpeechExample.java +++ b/examples/src/main/java/com/ibm/watson/developer_cloud/text_to_speech/v1/TextToSpeechExample.java @@ -12,18 +12,15 @@ */ package com.ibm.watson.developer_cloud.text_to_speech.v1; -import java.util.List; - -import com.ibm.watson.developer_cloud.text_to_speech.v1.model.Voice; +import com.ibm.watson.developer_cloud.text_to_speech.v1.model.Voices; public class TextToSpeechExample { - public static void main(String[] args) { TextToSpeech service = new TextToSpeech(); service.setUsernameAndPassword("", ""); - List voices = service.getVoices().execute(); + Voices voices = service.listVoices().execute(); System.out.println(voices); } diff --git a/examples/src/main/java/com/ibm/watson/developer_cloud/text_to_speech/v1/TranslateAndSynthesizeExample.java b/examples/src/main/java/com/ibm/watson/developer_cloud/text_to_speech/v1/TranslateAndSynthesizeExample.java index 04e16be32b8..4c5792e6389 100644 --- a/examples/src/main/java/com/ibm/watson/developer_cloud/text_to_speech/v1/TranslateAndSynthesizeExample.java +++ b/examples/src/main/java/com/ibm/watson/developer_cloud/text_to_speech/v1/TranslateAndSynthesizeExample.java @@ -20,9 +20,10 @@ import com.ibm.watson.developer_cloud.language_translation.v2.LanguageTranslation; import com.ibm.watson.developer_cloud.language_translation.v2.model.Language; +import com.ibm.watson.developer_cloud.text_to_speech.v1.model.SynthesizeOptions; +import com.ibm.watson.developer_cloud.language_translator.v2.model.TranslateOptions; import com.ibm.watson.developer_cloud.language_translation.v2.model.TranslationResult; import com.ibm.watson.developer_cloud.text_to_speech.v1.model.AudioFormat; -import com.ibm.watson.developer_cloud.text_to_speech.v1.model.Voice; import com.ibm.watson.developer_cloud.text_to_speech.v1.util.WaveUtils; /** @@ -31,20 +32,30 @@ public class TranslateAndSynthesizeExample { public static void main(String[] args) throws IOException { - LanguageTranslation translator = new LanguageTranslation(); + LanguageTranslator translator = new LanguageTranslator(); translator.setUsernameAndPassword("username", "password"); TextToSpeech synthesizer = new TextToSpeech(); synthesizer.setUsernameAndPassword("username", "password"); - String text = "Greetings from Watson Developer Cloudl"; + String text = "Greetings from Watson Developer Cloud"; // translate - TranslationResult translationResult = translator.translate(text, Language.ENGLISH, Language.SPANISH).execute(); + TranslateOptions translateOptions = new TranslateOptions.Builder() + .addText(text) + .source(Language.ENGLISH) + .target(Language.SPANISH) + .build(); + TranslationResult translationResult = service.translate(translateOptions).execute(); String translation = translationResult.getTranslations().get(0).getTranslation(); // synthesize - InputStream in = synthesizer.synthesize(translation, Voice.ES_LAURA, AudioFormat.WAV).execute(); + SynthesizeOptions synthesizeOptions = new SynthesizeOptions.Builder() + .text(translation) + .voice(SynthesizeOptions.Voice.EN_US_LISAVOICE) + .accept(SynthesizeOptions.Accept.AUDIO_WAV) + .build(); + InputStream in = service.synthesize(synthesizeOptions).execute(); writeToFile(WaveUtils.reWriteWaveHeader(in), new File("output.wav")); } diff --git a/examples/src/main/java/com/ibm/watson/developer_cloud/tone_analyzer/v3/ToneAnalyzerChatExample.java b/examples/src/main/java/com/ibm/watson/developer_cloud/tone_analyzer/v3/ToneAnalyzerChatExample.java index c0a12f7d72c..5c3cd9f0bc2 100644 --- a/examples/src/main/java/com/ibm/watson/developer_cloud/tone_analyzer/v3/ToneAnalyzerChatExample.java +++ b/examples/src/main/java/com/ibm/watson/developer_cloud/tone_analyzer/v3/ToneAnalyzerChatExample.java @@ -21,36 +21,33 @@ public class ToneAnalyzerExample { - - public static void main(String[] args) { - final String VERSION_DATE = "2016-05-19"; - ToneAnalyzer service = new ToneAnalyzer(VERSION_DATE); - service.setUsernameAndPassword("", ""); - - String[] texts = { - "My charger isn't working.", - "Thanks for reaching out. Can you give me some more detail about the issue?", - "I put my charger in my tablet to charge it up last night and it keeps saying it isn't" - + " charging. The charging icon comes on, but it stays on even when I take the charger out. " - + "Which is ridiculous, it's brand new.", - "I'm sorry you're having issues with charging. What kind of charger are you using?" - }; - - List utterances = new ArrayList<>(); - for (int i = 0; i < texts.length; i++) { - Utterance utterance = new Utterance.Builder() - .text(texts[i]) - .user(users[i]) - .build(); - utterances.add(utterance); - } - ToneChatOptions toneChatOptions = new ToneChatOptions.Builder() - .utterances(utterances) + public static void main(String[] args) { + ToneAnalyzer service = new ToneAnalyzer("2017-09-21"); + service.setUsernameAndPassword("", ""); + + String[] texts = { + "My charger isn't working.", + "Thanks for reaching out. Can you give me some more detail about the issue?", + "I put my charger in my tablet to charge it up last night and it keeps saying it isn't" + + " charging. The charging icon comes on, but it stays on even when I take the charger out. " + + "Which is ridiculous, it's brand new.", + "I'm sorry you're having issues with charging. What kind of charger are you using?" + }; + + List utterances = new ArrayList<>(); + for (int i = 0; i < texts.length; i++) { + Utterance utterance = new Utterance.Builder() + .text(texts[i]) + .user(users[i]) .build(); - - // Call the service - UtteranceAnalyses utterancesTone = service.toneChat(toneChatOptions).execute(); - System.out.println(utterancesTone); - + utterances.add(utterance); } + ToneChatOptions toneChatOptions = new ToneChatOptions.Builder() + .utterances(utterances) + .build(); + + // Call the service + UtteranceAnalyses utterancesTone = service.toneChat(toneChatOptions).execute(); + System.out.println(utterancesTone); + } } \ No newline at end of file diff --git a/examples/src/main/java/com/ibm/watson/developer_cloud/tone_analyzer/v3/ToneAnalyzerExample.java b/examples/src/main/java/com/ibm/watson/developer_cloud/tone_analyzer/v3/ToneAnalyzerExample.java index 14f3c2c1554..d987e96953c 100644 --- a/examples/src/main/java/com/ibm/watson/developer_cloud/tone_analyzer/v3/ToneAnalyzerExample.java +++ b/examples/src/main/java/com/ibm/watson/developer_cloud/tone_analyzer/v3/ToneAnalyzerExample.java @@ -13,13 +13,13 @@ package com.ibm.watson.developer_cloud.tone_analyzer.v3; import com.ibm.watson.developer_cloud.tone_analyzer.v3.model.ToneAnalysis; +import com.ibm.watson.developer_cloud.tone_analyzer.v3.model.ToneOptions; public class ToneAnalyzerExample { public static void main(String[] args) { - final String VERSION_DATE = "2016-05-19"; - ToneAnalyzer service = new ToneAnalyzer(VERSION_DATE); + ToneAnalyzer service = new ToneAnalyzer("2017-09-21"); service.setUsernameAndPassword("", ""); String text = "I know the times are difficult! Our sales have been " @@ -33,8 +33,10 @@ public static void main(String[] args) { + "business outcomes. Economy has nothing to do with it."; // Call the service and get the tone - ToneOptions tonOptions = new ToneOptions.Builder().text(text).build(); - ToneAnalysis tone = service.tone(tonOptions).execute(); + ToneOptions toneOptions = new ToneOptions.Builder() + .text(text) + .build(); + ToneAnalysis tone = service.tone(toneOptions).execute(); System.out.println(tone); } diff --git a/examples/src/main/java/com/ibm/watson/developer_cloud/tradeoff_analytics/v1/TradeoffAnalyticsExample.java b/examples/src/main/java/com/ibm/watson/developer_cloud/tradeoff_analytics/v1/TradeoffAnalyticsExample.java deleted file mode 100644 index 05c6ad7529b..00000000000 --- a/examples/src/main/java/com/ibm/watson/developer_cloud/tradeoff_analytics/v1/TradeoffAnalyticsExample.java +++ /dev/null @@ -1,73 +0,0 @@ -/** - * Copyright 2017 IBM Corp. All Rights Reserved. - * - * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with - * the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on - * an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the - * specific language governing permissions and limitations under the License. - */ -package com.ibm.watson.developer_cloud.tradeoff_analytics.v1; - -import java.util.ArrayList; -import java.util.HashMap; -import java.util.List; - -import com.ibm.watson.developer_cloud.tradeoff_analytics.v1.model.Dilemma; -import com.ibm.watson.developer_cloud.tradeoff_analytics.v1.model.Option; -import com.ibm.watson.developer_cloud.tradeoff_analytics.v1.model.Problem; -import com.ibm.watson.developer_cloud.tradeoff_analytics.v1.model.column.Column; -import com.ibm.watson.developer_cloud.tradeoff_analytics.v1.model.column.Column.Goal; -import com.ibm.watson.developer_cloud.tradeoff_analytics.v1.model.column.NumericColumn; - -public class TradeoffAnalyticsExample { - - public static void main(String[] args) { - TradeoffAnalytics service = new TradeoffAnalytics(); - service.setUsernameAndPassword("", ""); - - Problem problem = new Problem("phone"); - - String price = "price"; - String ram = "ram"; - String screen = "screen"; - - // Define the objectives - List columns = new ArrayList(); - problem.setColumns(columns); - - columns.add(new NumericColumn().range(0, 100).key(price).goal(Goal.MIN).objective(true)); - columns.add(new NumericColumn().key(screen).goal(Goal.MAX).objective(true)); - columns.add(new NumericColumn().key(ram).goal(Goal.MAX)); - - // Define the options to choose - ListVisual Recognition */ @@ -169,9 +164,14 @@ public ServiceCall classify() { /** * Detect faces in images. * - * Analyze and get data about faces in images. Responses can include estimated age and gender, and the service can - * identify celebrities. This feature uses a built-in classifier, so you do not train it on custom classifiers. The - * Detect faces method does not support general biometric facial recognition. + * **Important:** On April 2, 2018, the identity information in the response to calls to the Face model was removed. + * The identity information refers to the `name` of the person, `score`, and `type_hierarchy` knowledge graph. For + * details about the enhanced Face model, see the [Release + * notes](https://console.bluemix.net/docs/services/visual-recognition/release-notes.html#2april2018). Analyze and get + * data about faces in images. Responses can include estimated age and gender. This feature uses a built-in model, so + * no training is necessary. The Detect faces method does not support general biometric facial recognition. Supported + * image formats include .gif, .jpg, .png, and .tif. The maximum image size is 10 MB. The minimum recommended pixel + * density is 32X32 pixels per inch. * * @param detectFacesOptions the {@link DetectFacesOptions} containing the options for the call * @return a {@link ServiceCall} with a response type of {@link DetectedFaces} @@ -202,19 +202,6 @@ public ServiceCall detectFaces(DetectFacesOptions detectFacesOpti return createServiceCall(builder.build(), ResponseConverterUtils.getObject(DetectedFaces.class)); } - /** - * Detect faces in images. - * - * Analyze and get data about faces in images. Responses can include estimated age and gender, and the service can - * identify celebrities. This feature uses a built-in classifier, so you do not train it on custom classifiers. The - * Detect faces method does not support general biometric facial recognition. - * - * @return a {@link ServiceCall} with a response type of {@link DetectedFaces} - */ - public ServiceCall detectFaces() { - return detectFaces(null); - } - /** * Create a classifier. * @@ -287,7 +274,7 @@ public ServiceCall getClassifier(GetClassifierOptions getClassifierO } /** - * Retrieve a list of custom classifiers. + * Retrieve a list of classifiers. * * @param listClassifiersOptions the {@link ListClassifiersOptions} containing the options for the call * @return a {@link ServiceCall} with a response type of {@link Classifiers} @@ -305,7 +292,7 @@ public ServiceCall listClassifiers(ListClassifiersOptions listClass } /** - * Retrieve a list of custom classifiers. + * Retrieve a list of classifiers. * * @return a {@link ServiceCall} with a response type of {@link Classifiers} */ @@ -323,7 +310,7 @@ public ServiceCall listClassifiers() { * (https://console.bluemix.net/docs/services/visual-recognition/customizing.html#updating-custom-classifiers). * Encode all names in UTF-8 if they contain non-ASCII characters (.zip and image file names, and classifier and class * names). The service assumes UTF-8 encoding if it encounters non-ASCII characters. **Important:** You can't update a - * custom classifier with an API key for a Lite plan. To update a custom classifer on a Lite plan, create another + * custom classifier with an API key for a Lite plan. To update a custom classifier on a Lite plan, create another * service instance on a Standard plan and re-create your custom classifier. **Tip:** Don't make retraining calls on a * classifier until the status is ready. When you submit retraining requests in parallel, the last request overwrites * the previous requests. The retrained property shows the last time the classifier retraining finished. @@ -360,4 +347,23 @@ public ServiceCall updateClassifier(UpdateClassifierOptions updateCl return createServiceCall(builder.build(), ResponseConverterUtils.getObject(Classifier.class)); } + /** + * Retrieve a Core ML model of a classifier. + * + * Download a Core ML model file (.mlmodel) of a custom classifier that returns \"core_ml_enabled\": true in + * the classifier details. + * + * @param getCoreMlModelOptions the {@link GetCoreMlModelOptions} containing the options for the call + * @return a {@link ServiceCall} with a response type of {@link InputStream} + */ + public ServiceCall getCoreMlModel(GetCoreMlModelOptions getCoreMlModelOptions) { + Validator.notNull(getCoreMlModelOptions, "getCoreMlModelOptions cannot be null"); + String[] pathSegments = { "v3/classifiers", "core_ml_model" }; + String[] pathParameters = { getCoreMlModelOptions.classifierId() }; + RequestBuilder builder = RequestBuilder.get(RequestBuilder.constructHttpUrl(getEndPoint(), pathSegments, + pathParameters)); + builder.query(VERSION, versionDate); + return createServiceCall(builder.build(), ResponseConverterUtils.getInputStream()); + } + } diff --git a/visual-recognition/src/main/java/com/ibm/watson/developer_cloud/visual_recognition/v3/model/ClassResult.java b/visual-recognition/src/main/java/com/ibm/watson/developer_cloud/visual_recognition/v3/model/ClassResult.java index 1468c162137..c24b1111369 100644 --- a/visual-recognition/src/main/java/com/ibm/watson/developer_cloud/visual_recognition/v3/model/ClassResult.java +++ b/visual-recognition/src/main/java/com/ibm/watson/developer_cloud/visual_recognition/v3/model/ClassResult.java @@ -52,7 +52,7 @@ public Float getScore() { /** * Gets the typeHierarchy. * - * Knowledge graph of the property. For example, `People/Leaders/Presidents/USA/Barack Obama`. Included only if + * Knowledge graph of the property. For example, `/fruit/pome/apple/eating apple/Granny Smith`. Included only if * identified. * * @return the typeHierarchy diff --git a/visual-recognition/src/main/java/com/ibm/watson/developer_cloud/visual_recognition/v3/model/Classifier.java b/visual-recognition/src/main/java/com/ibm/watson/developer_cloud/visual_recognition/v3/model/Classifier.java index a3a3f5d0063..36469d65ff8 100644 --- a/visual-recognition/src/main/java/com/ibm/watson/developer_cloud/visual_recognition/v3/model/Classifier.java +++ b/visual-recognition/src/main/java/com/ibm/watson/developer_cloud/visual_recognition/v3/model/Classifier.java @@ -42,10 +42,13 @@ public interface Status { private String name; private String owner; private String status; + @SerializedName("core_ml_enabled") + private Boolean coreMlEnabled; private String explanation; private Date created; private List classes; private Date retrained; + private Date updated; /** * Gets the classifierId. @@ -92,6 +95,17 @@ public String getStatus() { return status; } + /** + * Gets the coreMlEnabled. + * + * Whether the classifier can be downloaded as a Core ML model after the training status is `ready`. + * + * @return the coreMlEnabled + */ + public Boolean isCoreMlEnabled() { + return coreMlEnabled; + } + /** * Gets the explanation. * @@ -106,7 +120,7 @@ public String getExplanation() { /** * Gets the created. * - * Date and time in Coordinated Universal Time that the classifier was created. + * Date and time in Coordinated Universal Time (UTC) that the classifier was created. * * @return the created */ @@ -128,12 +142,24 @@ public List getClasses() { /** * Gets the retrained. * - * Date and time in Coordinated Universal Time that the classifier was updated. Returned when verbose=`true`. Might - * not be returned by some requests. + * Date and time in Coordinated Universal Time (UTC) that the classifier was updated. Returned when verbose=`true`. + * Might not be returned by some requests. Identical to `updated` and retained for backward compatibility. * * @return the retrained */ public Date getRetrained() { return retrained; } + + /** + * Gets the updated. + * + * Date and time in Coordinated Universal Time (UTC) that the classifier was most recently updated. The field matches + * either `retrained` or `created`. Returned when verbose=`true`. Might not be returned by some requests. + * + * @return the updated + */ + public Date getUpdated() { + return updated; + } } diff --git a/visual-recognition/src/main/java/com/ibm/watson/developer_cloud/visual_recognition/v3/model/Classifiers.java b/visual-recognition/src/main/java/com/ibm/watson/developer_cloud/visual_recognition/v3/model/Classifiers.java index 153558069d8..6b139bb4911 100644 --- a/visual-recognition/src/main/java/com/ibm/watson/developer_cloud/visual_recognition/v3/model/Classifiers.java +++ b/visual-recognition/src/main/java/com/ibm/watson/developer_cloud/visual_recognition/v3/model/Classifiers.java @@ -17,7 +17,7 @@ import com.ibm.watson.developer_cloud.service.model.GenericModel; /** - * Verbose list of classifiers retrieved in the GET v2/classifiers call. + * List of classifiers. */ public class Classifiers extends GenericModel { diff --git a/visual-recognition/src/main/java/com/ibm/watson/developer_cloud/visual_recognition/v3/model/ClassifyOptions.java b/visual-recognition/src/main/java/com/ibm/watson/developer_cloud/visual_recognition/v3/model/ClassifyOptions.java index 3f233f16fe2..5018db8e40d 100644 --- a/visual-recognition/src/main/java/com/ibm/watson/developer_cloud/visual_recognition/v3/model/ClassifyOptions.java +++ b/visual-recognition/src/main/java/com/ibm/watson/developer_cloud/visual_recognition/v3/model/ClassifyOptions.java @@ -12,9 +12,6 @@ */ package com.ibm.watson.developer_cloud.visual_recognition.v3.model; -import com.ibm.watson.developer_cloud.service.model.GenericModel; -import com.ibm.watson.developer_cloud.util.Validator; - import java.io.File; import java.io.FileInputStream; import java.io.FileNotFoundException; @@ -22,17 +19,18 @@ import java.util.ArrayList; import java.util.List; +import com.ibm.watson.developer_cloud.service.model.GenericModel; +import com.ibm.watson.developer_cloud.util.Validator; + /** * The classify options. */ public class ClassifyOptions extends GenericModel { /** - * Specifies the language of the output class names. Can be `en` (English), `ar` (Arabic), `de` (German), `es` - * (Spanish), `it` (Italian), `ja` (Japanese), or `ko` (Korean). Classes for which no translation is available are - * omitted. The response might not be in the specified language under these conditions: - English is returned when the - * requested language is not supported. - Classes are not returned when there is no translation for them. - Custom - * classifiers returned with this method return tags in the language of the custom classifier. + * The language of the output class names. The full set of languages is supported only for the built-in `default` + * classifier ID. The class names of custom classifiers are not translated. The response might not be in the specified + * language when the requested language is not supported or when there is no translation for the class name. */ public interface AcceptLanguage { /** en. */ @@ -43,6 +41,8 @@ public interface AcceptLanguage { String DE = "de"; /** es. */ String ES = "es"; + /** fr. */ + String FR = "fr"; /** it. */ String IT = "it"; /** ja. */ @@ -277,8 +277,8 @@ public Builder newBuilder() { * * An image file (.jpg, .png) or .zip file with images. Maximum image size is 10 MB. Include no more than 20 images * and limit the .zip file to 100 MB. Encode the image and .zip file names in UTF-8 if they contain non-ASCII - * characters. The service assumes UTF-8 encoding if it encounters non-ASCII characters. You can also include images - * with the `url` property in the **parameters** object. + * characters. The service assumes UTF-8 encoding if it encounters non-ASCII characters. You can also include an image + * with the **url** parameter. * * @return the imagesFile */ @@ -300,11 +300,9 @@ public String imagesFilename() { /** * Gets the acceptLanguage. * - * Specifies the language of the output class names. Can be `en` (English), `ar` (Arabic), `de` (German), `es` - * (Spanish), `it` (Italian), `ja` (Japanese), or `ko` (Korean). Classes for which no translation is available are - * omitted. The response might not be in the specified language under these conditions: - English is returned when the - * requested language is not supported. - Classes are not returned when there is no translation for them. - Custom - * classifiers returned with this method return tags in the language of the custom classifier. + * The language of the output class names. The full set of languages is supported only for the built-in `default` + * classifier ID. The class names of custom classifiers are not translated. The response might not be in the specified + * language when the requested language is not supported or when there is no translation for the class name. * * @return the acceptLanguage */ @@ -315,8 +313,8 @@ public String acceptLanguage() { /** * Gets the url. * - * A string with the image URL to analyze. Must be in .jpg, or .png format. The minimum recommended pixel density is - * 32X32 pixels per inch, and the maximum image size is 10 MB. You can also include images in the **images_file** + * The URL of an image to analyze. Must be in .jpg, or .png format. The minimum recommended pixel density is 32X32 + * pixels per inch, and the maximum image size is 10 MB. You can also include images with the **images_file** * parameter. * * @return the url @@ -328,8 +326,7 @@ public String url() { /** * Gets the threshold. * - * A floating point value that specifies the minimum score a class must have to be displayed in the response. The - * default threshold for returning scores from a classifier is `0.5`. Set the threshold to `0.0` to ignore the + * The minimum score a class must have to be displayed in the response. Set the threshold to `0.0` to ignore the * classification score and return all values. * * @return the threshold @@ -341,11 +338,11 @@ public Float threshold() { /** * Gets the owners. * - * An array of the categories of classifiers to apply. Use `IBM` to classify against the `default` general classifier, - * and use `me` to classify against your custom classifiers. To analyze the image against both classifier categories, - * set the value to both `IBM` and `me`. The built-in `default` classifier is used if both **classifier_ids** and - * **owners** parameters are empty. The **classifier_ids** parameter overrides **owners**, so make sure that - * **classifier_ids** is empty. + * The categories of classifiers to apply. Use `IBM` to classify against the `default` general classifier, and use + * `me` to classify against your custom classifiers. To analyze the image against both classifier categories, set the + * value to both `IBM` and `me`. The built-in `default` classifier is used if both **classifier_ids** and **owners** + * parameters are empty. The **classifier_ids** parameter overrides **owners**, so make sure that **classifier_ids** + * is empty. * * @return the owners */ @@ -356,13 +353,11 @@ public List owners() { /** * Gets the classifierIds. * - * The **classifier_ids** parameter overrides **owners**, so make sure that **classifier_ids** is empty. - - * **classifier_ids**: Specifies which classifiers to apply and overrides the **owners** parameter. You can specify - * both custom and built-in classifiers. The built-in `default` classifier is used if both **classifier_ids** and - * **owners** parameters are empty. The following built-in classifier IDs require no training: - `default`: Returns - * classes from thousands of general tags. - `food`: (Beta) Enhances specificity and accuracy for images of food - * items. - `explicit`: (Beta) Evaluates whether the image might be pornographic. Example: - * `"classifier_ids="CarsvsTrucks_1479118188","explicit"`. + * Which classifiers to apply. Overrides the **owners** parameter. You can specify both custom and built-in classifier + * IDs. The built-in `default` classifier is used if both **classifier_ids** and **owners** parameters are empty. The + * following built-in classifier IDs require no training: - `default`: Returns classes from thousands of general tags. + * - `food`: (Beta) Enhances specificity and accuracy for images of food items. - `explicit`: (Beta) Evaluates whether + * the image might be pornographic. * * @return the classifierIds */ diff --git a/visual-recognition/src/main/java/com/ibm/watson/developer_cloud/visual_recognition/v3/model/CreateClassifierOptions.java b/visual-recognition/src/main/java/com/ibm/watson/developer_cloud/visual_recognition/v3/model/CreateClassifierOptions.java index 17db9ac33db..0f36a45102a 100644 --- a/visual-recognition/src/main/java/com/ibm/watson/developer_cloud/visual_recognition/v3/model/CreateClassifierOptions.java +++ b/visual-recognition/src/main/java/com/ibm/watson/developer_cloud/visual_recognition/v3/model/CreateClassifierOptions.java @@ -172,11 +172,10 @@ public String name() { * Gets the class names. * * A .zip file of images that depict the visual subject of a class in the new classifier. You can include more than - * one positive example file in a call. Append `_positive_examples` to the form name. The prefix is used as the class + * one positive example file in a call. Specify the parameter name by appending `_positive_examples` to the class * name. For example, `goldenretriever_positive_examples` creates the class **goldenretriever**. Include at least 10 * images in .jpg or .png format. The minimum recommended image resolution is 32X32 pixels. The maximum number of - * images is 10,000 images or 100 MB per .zip file. Encode special characters in the file name in UTF-8. The API - * explorer limits you to training only one class. To train more classes, use the API functionality. + * images is 10,000 images or 100 MB per .zip file. Encode special characters in the file name in UTF-8. * * @return the classNames */ @@ -197,8 +196,8 @@ public File positiveExamplesByClassName(String className) { /** * Gets the negativeExamples. * - * A compressed (.zip) file of images that do not depict the visual subject of any of the classes of the new - * classifier. Must contain a minimum of 10 images. Encode special characters in the file name in UTF-8. + * A .zip file of images that do not depict the visual subject of any of the classes of the new classifier. Must + * contain a minimum of 10 images. Encode special characters in the file name in UTF-8. * * @return the negativeExamples */ diff --git a/visual-recognition/src/main/java/com/ibm/watson/developer_cloud/visual_recognition/v3/model/DetectFacesOptions.java b/visual-recognition/src/main/java/com/ibm/watson/developer_cloud/visual_recognition/v3/model/DetectFacesOptions.java index 75362787b60..fea0f2f9a27 100644 --- a/visual-recognition/src/main/java/com/ibm/watson/developer_cloud/visual_recognition/v3/model/DetectFacesOptions.java +++ b/visual-recognition/src/main/java/com/ibm/watson/developer_cloud/visual_recognition/v3/model/DetectFacesOptions.java @@ -12,13 +12,13 @@ */ package com.ibm.watson.developer_cloud.visual_recognition.v3.model; -import com.ibm.watson.developer_cloud.service.model.GenericModel; - import java.io.File; import java.io.FileInputStream; import java.io.FileNotFoundException; import java.io.InputStream; +import com.ibm.watson.developer_cloud.service.model.GenericModel; + /** * The detectFaces options. */ @@ -156,9 +156,10 @@ public Builder newBuilder() { /** * Gets the imagesFile. * - * An image file (.jpg, .png) or .zip file with images. Include no more than 15 images. You can also include an image - * with the**url** parameter. All faces are detected, but if there are more than 10 faces in an image, age and gender - * confidence scores might return scores of 0. + * An image file (gif, .jpg, .png, .tif.) or .zip file with images. Limit the .zip file to 100 MB. You can include a + * maximum of 15 images in a request. Encode the image and .zip file names in UTF-8 if they contain non-ASCII + * characters. The service assumes UTF-8 encoding if it encounters non-ASCII characters. You can also include an + * image with the **url** parameter. * * @return the imagesFile */ @@ -180,7 +181,9 @@ public String imagesFilename() { /** * Gets the url. * - * A string with the image URL to analyze. + * The URL of an image to analyze. Must be in .gif, .jpg, .png, or .tif format. The minimum recommended pixel density + * is 32X32 pixels per inch, and the maximum image size is 10 MB. Redirects are followed, so you can use a shortened + * URL. You can also include images with the **images_file** parameter. * * @return the url */ diff --git a/visual-recognition/src/main/java/com/ibm/watson/developer_cloud/visual_recognition/v3/model/Face.java b/visual-recognition/src/main/java/com/ibm/watson/developer_cloud/visual_recognition/v3/model/Face.java index c12eb9a4bac..22dd1218fe3 100644 --- a/visual-recognition/src/main/java/com/ibm/watson/developer_cloud/visual_recognition/v3/model/Face.java +++ b/visual-recognition/src/main/java/com/ibm/watson/developer_cloud/visual_recognition/v3/model/Face.java @@ -24,7 +24,6 @@ public class Face extends GenericModel { private FaceGender gender; @SerializedName("face_location") private FaceLocation faceLocation; - private FaceIdentity identity; /** * Gets the age. @@ -52,13 +51,4 @@ public FaceGender getGender() { public FaceLocation getFaceLocation() { return faceLocation; } - - /** - * Gets the identity. - * - * @return the identity - */ - public FaceIdentity getIdentity() { - return identity; - } } diff --git a/visual-recognition/src/main/java/com/ibm/watson/developer_cloud/visual_recognition/v3/model/FaceAge.java b/visual-recognition/src/main/java/com/ibm/watson/developer_cloud/visual_recognition/v3/model/FaceAge.java index 0eeac44b686..a0de0913a77 100644 --- a/visual-recognition/src/main/java/com/ibm/watson/developer_cloud/visual_recognition/v3/model/FaceAge.java +++ b/visual-recognition/src/main/java/com/ibm/watson/developer_cloud/visual_recognition/v3/model/FaceAge.java @@ -15,8 +15,7 @@ import com.ibm.watson.developer_cloud.service.model.GenericModel; /** - * Provides age information about a face. If there are more than 10 faces in an image, the response might return the - * confidence score `0g. + * Provides age information about a face. */ public class FaceAge extends GenericModel { @@ -49,8 +48,8 @@ public Long getMax() { /** * Gets the score. * - * Confidence score for the property in the range of 0 to 1. A higher score indicates greater likelihood that the - * class is depicted in the image. The default threshold for returning scores from a classifier is 0.5. + * Confidence score in the range of 0 to 1. A higher score indicates greater confidence in the estimated value for the + * property. * * @return the score */ diff --git a/visual-recognition/src/main/java/com/ibm/watson/developer_cloud/visual_recognition/v3/model/FaceGender.java b/visual-recognition/src/main/java/com/ibm/watson/developer_cloud/visual_recognition/v3/model/FaceGender.java index eca3ae32277..0a15c91e53f 100644 --- a/visual-recognition/src/main/java/com/ibm/watson/developer_cloud/visual_recognition/v3/model/FaceGender.java +++ b/visual-recognition/src/main/java/com/ibm/watson/developer_cloud/visual_recognition/v3/model/FaceGender.java @@ -15,8 +15,7 @@ import com.ibm.watson.developer_cloud.service.model.GenericModel; /** - * Provides information about the gender of the face. If there are more than 10 faces in an image, the response might - * return the confidence score 0. + * Provides information about the gender of the face. */ public class FaceGender extends GenericModel { @@ -37,8 +36,8 @@ public String getGender() { /** * Gets the score. * - * Confidence score for the property in the range of 0 to 1. A higher score indicates greater likelihood that the - * class is depicted in the image. The default threshold for returning scores from a classifier is 0.5. + * Confidence score in the range of 0 to 1. A higher score indicates greater confidence in the estimated value for the + * property. * * @return the score */ diff --git a/visual-recognition/src/main/java/com/ibm/watson/developer_cloud/visual_recognition/v3/model/FaceIdentity.java b/visual-recognition/src/main/java/com/ibm/watson/developer_cloud/visual_recognition/v3/model/FaceIdentity.java deleted file mode 100644 index 73e5afcbb5b..00000000000 --- a/visual-recognition/src/main/java/com/ibm/watson/developer_cloud/visual_recognition/v3/model/FaceIdentity.java +++ /dev/null @@ -1,62 +0,0 @@ -/* - * Copyright 2018 IBM Corp. All Rights Reserved. - * - * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with - * the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on - * an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the - * specific language governing permissions and limitations under the License. - */ -package com.ibm.watson.developer_cloud.visual_recognition.v3.model; - -import com.google.gson.annotations.SerializedName; -import com.ibm.watson.developer_cloud.service.model.GenericModel; - -/** - * Provides information about a celebrity who is detected in the image. Not returned when a celebrity is not detected. - */ -public class FaceIdentity extends GenericModel { - - private String name; - private Float score; - @SerializedName("type_hierarchy") - private String typeHierarchy; - - /** - * Gets the name. - * - * Name of the person. - * - * @return the name - */ - public String getName() { - return name; - } - - /** - * Gets the score. - * - * Confidence score for the property in the range of 0 to 1. A higher score indicates greater likelihood that the - * class is depicted in the image. The default threshold for returning scores from a classifier is 0.5. - * - * @return the score - */ - public Float getScore() { - return score; - } - - /** - * Gets the typeHierarchy. - * - * Knowledge graph of the property. For example, `People/Leaders/Presidents/USA/Barack Obama`. Included only if - * identified. - * - * @return the typeHierarchy - */ - public String getTypeHierarchy() { - return typeHierarchy; - } -} diff --git a/visual-recognition/src/main/java/com/ibm/watson/developer_cloud/visual_recognition/v3/model/GetCoreMlModelOptions.java b/visual-recognition/src/main/java/com/ibm/watson/developer_cloud/visual_recognition/v3/model/GetCoreMlModelOptions.java new file mode 100644 index 00000000000..e3576823a01 --- /dev/null +++ b/visual-recognition/src/main/java/com/ibm/watson/developer_cloud/visual_recognition/v3/model/GetCoreMlModelOptions.java @@ -0,0 +1,95 @@ +/* + * Copyright 2018 IBM Corp. All Rights Reserved. + * + * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with + * the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on + * an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the + * specific language governing permissions and limitations under the License. + */ +package com.ibm.watson.developer_cloud.visual_recognition.v3.model; + +import com.ibm.watson.developer_cloud.service.model.GenericModel; +import com.ibm.watson.developer_cloud.util.Validator; + +/** + * The getCoreMlModel options. + */ +public class GetCoreMlModelOptions extends GenericModel { + + private String classifierId; + + /** + * Builder. + */ + public static class Builder { + private String classifierId; + + private Builder(GetCoreMlModelOptions getCoreMlModelOptions) { + classifierId = getCoreMlModelOptions.classifierId; + } + + /** + * Instantiates a new builder. + */ + public Builder() { + } + + /** + * Instantiates a new builder with required properties. + * + * @param classifierId the classifierId + */ + public Builder(String classifierId) { + this.classifierId = classifierId; + } + + /** + * Builds a GetCoreMlModelOptions. + * + * @return the getCoreMlModelOptions + */ + public GetCoreMlModelOptions build() { + return new GetCoreMlModelOptions(this); + } + + /** + * Set the classifierId. + * + * @param classifierId the classifierId + * @return the GetCoreMlModelOptions builder + */ + public Builder classifierId(String classifierId) { + this.classifierId = classifierId; + return this; + } + } + + private GetCoreMlModelOptions(Builder builder) { + Validator.notEmpty(builder.classifierId, "classifierId cannot be empty"); + classifierId = builder.classifierId; + } + + /** + * New builder. + * + * @return a GetCoreMlModelOptions builder + */ + public Builder newBuilder() { + return new Builder(this); + } + + /** + * Gets the classifierId. + * + * The ID of the classifier. + * + * @return the classifierId + */ + public String classifierId() { + return classifierId; + } +} diff --git a/visual-recognition/src/main/java/com/ibm/watson/developer_cloud/visual_recognition/v3/model/UpdateClassifierOptions.java b/visual-recognition/src/main/java/com/ibm/watson/developer_cloud/visual_recognition/v3/model/UpdateClassifierOptions.java index a811b09cbb7..df92108754e 100644 --- a/visual-recognition/src/main/java/com/ibm/watson/developer_cloud/visual_recognition/v3/model/UpdateClassifierOptions.java +++ b/visual-recognition/src/main/java/com/ibm/watson/developer_cloud/visual_recognition/v3/model/UpdateClassifierOptions.java @@ -174,8 +174,8 @@ public String classifierId() { * Gets the class names. * * A .zip file of images that depict the visual subject of a class in the classifier. The positive examples create or - * update classes in the classifier. You can include more than one positive example file in a call. Append - * `_positive_examples` to the form name. The prefix is used to name the class. For example, + * update classes in the classifier. You can include more than one positive example file in a call. Specify the + * parameter name by appending `_positive_examples` to the class name. For example, * `goldenretriever_positive_examples` creates the class `goldenretriever`. Include at least 10 images in .jpg or .png * format. The minimum recommended image resolution is 32X32 pixels. The maximum number of images is 10,000 images or * 100 MB per .zip file. Encode special characters in the file name in UTF-8. @@ -199,8 +199,8 @@ public File positiveExamplesByClassName(String className) { /** * Gets the negativeExamples. * - * A compressed (.zip) file of images that do not depict the visual subject of any of the classes of the new - * classifier. Must contain a minimum of 10 images. Encode special characters in the file name in UTF-8. + * A .zip file of images that do not depict the visual subject of any of the classes of the new classifier. Must + * contain a minimum of 10 images. Encode special characters in the file name in UTF-8. * * @return the negativeExamples */ diff --git a/visual-recognition/src/test/java/com/ibm/watson/developer_cloud/visual_recognition/v3/VisualRecognitionIT.java b/visual-recognition/src/test/java/com/ibm/watson/developer_cloud/visual_recognition/v3/VisualRecognitionIT.java index dcec4a13e18..4fa0115aa54 100644 --- a/visual-recognition/src/test/java/com/ibm/watson/developer_cloud/visual_recognition/v3/VisualRecognitionIT.java +++ b/visual-recognition/src/test/java/com/ibm/watson/developer_cloud/visual_recognition/v3/VisualRecognitionIT.java @@ -23,6 +23,7 @@ import com.ibm.watson.developer_cloud.visual_recognition.v3.model.DetectFacesOptions; import com.ibm.watson.developer_cloud.visual_recognition.v3.model.DetectedFaces; import com.ibm.watson.developer_cloud.visual_recognition.v3.model.GetClassifierOptions; +import com.ibm.watson.developer_cloud.visual_recognition.v3.model.GetCoreMlModelOptions; import com.ibm.watson.developer_cloud.visual_recognition.v3.model.ListClassifiersOptions; import org.junit.Assume; import org.junit.Before; @@ -55,6 +56,7 @@ public class VisualRecognitionIT extends WatsonServiceTest { private static final String IMAGE_URL = "https://watson-test-resources.mybluemix.net/resources/car.png"; private static final String SINGLE_IMAGE_FILE = "src/test/resources/visual_recognition/car.png"; + private String classifierId; private VisualRecognition service; private void assertClassifyImage(ClassifiedImages result, ClassifyOptions options) { @@ -106,6 +108,8 @@ public void setUp() throws Exception { Assume.assumeFalse("config.properties doesn't have valid credentials.", (apiKey == null) || apiKey.equals("API_KEY")); + classifierId = getProperty("visual_recognition.v3.classifier_id"); + service = new VisualRecognition("2016-05-20"); service.setApiKey(apiKey); service.setDefaultHeaders(getDefaultHeaders()); @@ -258,8 +262,11 @@ public void testCreateClassifier() throws FileNotFoundException, InterruptedExce public void testDeleteAllClassifiers() { List classifiers = service.listClassifiers(null).execute().getClassifiers(); for (Classifier classifier : classifiers) { - DeleteClassifierOptions deleteOptions = new DeleteClassifierOptions.Builder(classifier.getClassifierId()).build(); - service.deleteClassifier(deleteOptions).execute(); + if (!classifier.getClassifierId().equals(classifierId)) { + DeleteClassifierOptions deleteOptions = new DeleteClassifierOptions.Builder(classifier.getClassifierId()) + .build(); + service.deleteClassifier(deleteOptions).execute(); + } } } @@ -337,4 +344,25 @@ public void testListClassifiers() { assertNotNull(classifier.getClasses()); assertNotNull(classifier.getCreated()); } + + /** + * Test getting the Core ML file for a classifier. + */ + @Ignore + @Test + public void testGetCoreMlModel() { + ListClassifiersOptions options = new ListClassifiersOptions.Builder().verbose(true).build(); + List classifiers = service.listClassifiers(options).execute().getClassifiers(); + + for (Classifier classifier : classifiers) { + if (classifier.isCoreMlEnabled()) { + GetCoreMlModelOptions getCoreMlModelOptions = new GetCoreMlModelOptions.Builder() + .classifierId(classifier.getClassifierId()) + .build(); + InputStream coreMlFile = service.getCoreMlModel(getCoreMlModelOptions).execute(); + assertNotNull(coreMlFile); + break; + } + } + } } diff --git a/visual-recognition/src/test/java/com/ibm/watson/developer_cloud/visual_recognition/v3/VisualRecognitionTest.java b/visual-recognition/src/test/java/com/ibm/watson/developer_cloud/visual_recognition/v3/VisualRecognitionTest.java index 09cec42ccd5..03a6b820757 100644 --- a/visual-recognition/src/test/java/com/ibm/watson/developer_cloud/visual_recognition/v3/VisualRecognitionTest.java +++ b/visual-recognition/src/test/java/com/ibm/watson/developer_cloud/visual_recognition/v3/VisualRecognitionTest.java @@ -12,9 +12,11 @@ */ package com.ibm.watson.developer_cloud.visual_recognition.v3; +import com.google.common.io.Files; import com.google.gson.Gson; import com.google.gson.JsonObject; import com.ibm.watson.developer_cloud.WatsonServiceUnitTest; +import com.ibm.watson.developer_cloud.http.HttpMediaType; import com.ibm.watson.developer_cloud.visual_recognition.v3.model.ClassifiedImages; import com.ibm.watson.developer_cloud.visual_recognition.v3.model.Classifier; import com.ibm.watson.developer_cloud.visual_recognition.v3.model.ClassifyOptions; @@ -23,10 +25,12 @@ import com.ibm.watson.developer_cloud.visual_recognition.v3.model.DetectFacesOptions; import com.ibm.watson.developer_cloud.visual_recognition.v3.model.DetectedFaces; import com.ibm.watson.developer_cloud.visual_recognition.v3.model.GetClassifierOptions; +import com.ibm.watson.developer_cloud.visual_recognition.v3.model.GetCoreMlModelOptions; import com.ibm.watson.developer_cloud.visual_recognition.v3.model.ListClassifiersOptions; import com.ibm.watson.developer_cloud.visual_recognition.v3.model.UpdateClassifierOptions; import okhttp3.mockwebserver.MockResponse; import okhttp3.mockwebserver.RecordedRequest; +import okio.Buffer; import org.junit.Before; import org.junit.Test; @@ -58,6 +62,7 @@ public class VisualRecognitionTest extends WatsonServiceUnitTest { private static final String PATH_CLASSIFIERS = "/v3/classifiers"; private static final String PATH_CLASSIFIER = "/v3/classifiers/%s"; private static final String PATH_DETECT_FACES = "/v3/detect_faces"; + private static final String PATH_CORE_ML = "/v3/classifiers/%s/core_ml_model"; private VisualRecognition service; @@ -328,4 +333,26 @@ public void testGetClassifiers() throws InterruptedException, IOException { assertEquals("GET", request.getMethod()); assertEquals(serviceResponse, classifiers); } + + @Test + public void testGetCoreMlModel() throws IOException, InterruptedException { + final File model = new File("src/test/resources/visual_recognition/custom_model.mlmodel"); + final Buffer buffer = new Buffer().write(Files.toByteArray(model)); + + server.enqueue(new MockResponse().addHeader(CONTENT_TYPE, HttpMediaType.APPLICATION_OCTET_STREAM).setBody(buffer)); + + String classifierId = "classifier_id"; + GetCoreMlModelOptions options = new GetCoreMlModelOptions.Builder() + .classifierId(classifierId) + .build(); + + InputStream modelFile = service.getCoreMlModel(options).execute(); + + RecordedRequest request = server.takeRequest(); + String path = String.format(PATH_CORE_ML, classifierId) + "?" + VERSION_DATE + "=2016-05-20&api_key=" + API_KEY; + + assertEquals(path, request.getPath()); + assertEquals("GET", request.getMethod()); + writeInputStreamToFile(modelFile, new File("build/model_result.mlmodel")); + } } diff --git a/visual-recognition/src/test/resources/visual_recognition/custom_model.mlmodel b/visual-recognition/src/test/resources/visual_recognition/custom_model.mlmodel new file mode 100644 index 00000000000..35611c91142 Binary files /dev/null and b/visual-recognition/src/test/resources/visual_recognition/custom_model.mlmodel differ