Skip to content

Commit f80a364

Browse files
Added Tone Analyzer support, #11
1 parent f82c273 commit f80a364

File tree

9 files changed

+1153
-0
lines changed

9 files changed

+1153
-0
lines changed
Lines changed: 182 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,182 @@
1+
/**
2+
* Copyright 2015 IBM Corp. All Rights Reserved.
3+
*
4+
* Licensed under the Apache License, Version 2.0 (the "License");
5+
* you may not use this file except in compliance with the License.
6+
* You may obtain a copy of the License at
7+
*
8+
* http://www.apache.org/licenses/LICENSE-2.0
9+
*
10+
* Unless required by applicable law or agreed to in writing, software
11+
* distributed under the License is distributed on an "AS IS" BASIS,
12+
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13+
* See the License for the specific language governing permissions and
14+
* limitations under the License.
15+
*/
16+
package com.ibm.watson.developer_cloud.tone_analyzer.v1;
17+
18+
import java.io.IOException;
19+
import java.lang.reflect.Type;
20+
import java.util.List;
21+
import java.util.Map;
22+
import java.util.logging.Logger;
23+
24+
import org.apache.http.HttpResponse;
25+
import org.apache.http.client.methods.HttpRequestBase;
26+
27+
import com.google.gson.Gson;
28+
import com.google.gson.JsonObject;
29+
import com.google.gson.reflect.TypeToken;
30+
import com.ibm.watson.developer_cloud.service.Request;
31+
import com.ibm.watson.developer_cloud.service.WatsonService;
32+
import com.ibm.watson.developer_cloud.tone_analyzer.v1.model.Scorecard;
33+
import com.ibm.watson.developer_cloud.tone_analyzer.v1.model.SynonymResult;
34+
import com.ibm.watson.developer_cloud.tone_analyzer.v1.model.Tone;
35+
import com.ibm.watson.developer_cloud.util.ResponseUtil;
36+
37+
/**
38+
* The IBM Watson The Tone Analyzer service uses linguistic analysis to detect
39+
* emotional tones, social propensities, and writing styles in written
40+
* communication. Then it offers suggestions to help the writer improve their
41+
* intended language tones.
42+
*
43+
* @author German Attanasio Ruiz (germanatt@us.ibm.com)
44+
* @version v1
45+
* @see <a
46+
* href="http://www.ibm.com/smarterplanet/us/en/ibmwatson/developercloud/tone-analyzer.html">
47+
* Tone Analyzer</a>
48+
*/
49+
public class ToneAnalyzer extends WatsonService {
50+
51+
// parameters
52+
public static final String TEXT = null;
53+
public static final String SCORECARD = null;
54+
55+
private static final Logger log = Logger.getLogger(ToneAnalyzer.class
56+
.getName());
57+
private static final String URL = "https://gateway.watsonplatform.net/tone-analyzer-beta/api";
58+
59+
private static final Type listScorecardsType = new TypeToken<List<Scorecard>>() {
60+
}.getType();
61+
62+
/**
63+
* Instantiates a new Tone Analyzer service with the default url
64+
*/
65+
public ToneAnalyzer() {
66+
setEndPoint(URL);
67+
}
68+
69+
/**
70+
* Analyzes the "tone" of a piece of text. The message is analyzed from
71+
* several tones (social tone, emotional tone, writing tone), and for each
72+
* of them various traits are derived (such as conscientiousness,
73+
* agreeableness, openness).
74+
*
75+
* @param text
76+
* The text to analyze
77+
* @param scorecard
78+
* Name of the scorecard used to compute the tone. (business
79+
* messages by default)
80+
* @return the {@link Tone} with the response
81+
*
82+
*/
83+
public Tone getTone(final String text, final String scorecard) {
84+
85+
if (text == null || text.isEmpty())
86+
throw new IllegalArgumentException("text can not be null or empty");
87+
88+
JsonObject contentJson = new JsonObject();
89+
contentJson.addProperty(TEXT, text);
90+
contentJson.addProperty(SCORECARD, text);
91+
92+
HttpRequestBase request = Request.Post("/v1/tone")
93+
.withContent(contentJson).build();
94+
95+
try {
96+
HttpResponse response = execute(request);
97+
String toneAsJson = ResponseUtil.getString(response);
98+
Tone tone = getGson().fromJson(toneAsJson, Tone.class);
99+
return tone;
100+
} catch (IOException e) {
101+
throw new RuntimeException(e);
102+
}
103+
}
104+
105+
/**
106+
* Starts or continue conversations.
107+
*
108+
* @param words
109+
* (string[]),
110+
* @param traits
111+
* (string[], optional),
112+
* @param limit
113+
* (long, optional) Limits the number of words to return on each
114+
* trait. The most heavily correlated (positive and negative) to
115+
* each trait are returned; approximately limit/2 each of
116+
* positively correlated words negatively correlated words if
117+
* there are enough available.
118+
* @param hops
119+
* (long, optional): The number of 'hops' to explore for synonyms
120+
* or related words: 0 indicates words directly related to the
121+
* input; 1 gives words related to them, and so on. The greater
122+
* this number, the richer the word set returned (but at the same
123+
* time, less tightly related to the input).
124+
* @param context
125+
* (string[], optional)
126+
* @param index
127+
* (long, optional): The position (0-based) in `context`
128+
* parameter where the requested word appears. This parameter can
129+
* only be passed when `context` is also present and there is
130+
* only one word requested (length(`words`)=0), and it makes
131+
* sense only if `context[index]` is equal to `words[0]`.
132+
*
133+
* @param params
134+
* The map with the parameters described above
135+
*
136+
* @return {@link SynonymResult}
137+
*/
138+
public SynonymResult getSynynyms(Map<String, Object> params) {
139+
String[] words = (String[]) params.get("words");
140+
String[] traits = (String[]) params.get("traits");
141+
String[] context = (String[]) params.get("context");
142+
143+
if (words == null || words.length == 0)
144+
throw new IllegalArgumentException("words can not be null or empty");
145+
146+
JsonObject jsonObject = new JsonObject();
147+
// TODO: add all the properties to the json object
148+
HttpRequestBase request = Request.Post("/v1/synonym")
149+
.withContent(jsonObject).build();
150+
151+
HttpResponse response = execute(request);
152+
try {
153+
String synonymResultJson = ResponseUtil.getString(response);
154+
SynonymResult synonymResult = getGson().fromJson(synonymResultJson,
155+
SynonymResult.class);
156+
return synonymResult;
157+
} catch (IOException e) {
158+
throw new RuntimeException(e);
159+
}
160+
}
161+
162+
/**
163+
* Returns a list of available scorecards. Scorecards are implementations of
164+
* Tone evaluations for different domains.
165+
*
166+
* @return A list of {@link Scorecard }
167+
*/
168+
public List<Scorecard> getScorecards() {
169+
HttpRequestBase request = Request.Get("/v1/scorecards").build();
170+
HttpResponse response = execute(request);
171+
172+
try {
173+
JsonObject jsonObject = ResponseUtil.getJsonObject(response);
174+
List<Scorecard> scorecards = new Gson().fromJson(
175+
jsonObject.get("scorecards"), listScorecardsType);
176+
return scorecards;
177+
} catch (IOException e) {
178+
throw new RuntimeException(e);
179+
}
180+
}
181+
182+
}
Lines changed: 162 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,162 @@
1+
/**
2+
* Copyright 2015 IBM Corp. All Rights Reserved.
3+
*
4+
* Licensed under the Apache License, Version 2.0 (the "License");
5+
* you may not use this file except in compliance with the License.
6+
* You may obtain a copy of the License at
7+
*
8+
* http://www.apache.org/licenses/LICENSE-2.0
9+
*
10+
* Unless required by applicable law or agreed to in writing, software
11+
* distributed under the License is distributed on an "AS IS" BASIS,
12+
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13+
* See the License for the specific language governing permissions and
14+
* limitations under the License.
15+
*/
16+
17+
package com.ibm.watson.developer_cloud.tone_analyzer.v1.model;
18+
19+
import java.util.ArrayList;
20+
import java.util.List;
21+
22+
import com.google.gson.annotations.Expose;
23+
import com.google.gson.annotations.SerializedName;
24+
25+
/**
26+
* The Class LinguisticEvidence.
27+
*/
28+
public class LinguisticEvidence {
29+
30+
/** A score telling how much this evidence contributes to the trait */
31+
@SerializedName("evidence_score")
32+
private Integer evidenceScore;
33+
34+
/** Number of words found to show evidence with this trait, */
35+
@SerializedName("word_count")
36+
private Integer wordCount;
37+
38+
/** The words. */
39+
@Expose
40+
private List<String> words = new ArrayList<String>();
41+
42+
/** Either "positive" or "negative", telling if this linguistic evidence is showing positive (resp. negative) correlation with the trait */
43+
@Expose
44+
private String correlation;
45+
46+
/**
47+
* Gets the evidence score.
48+
*
49+
* @return The evidenceScore
50+
*/
51+
public Integer getEvidenceScore() {
52+
return evidenceScore;
53+
}
54+
55+
/**
56+
* Sets the evidence score.
57+
*
58+
* @param evidenceScore The evidence_score
59+
*/
60+
public void setEvidenceScore(final Integer evidenceScore) {
61+
this.evidenceScore = evidenceScore;
62+
}
63+
64+
/**
65+
* With evidence score.
66+
*
67+
* @param evidenceScore the evidence score
68+
* @return the linguistic evidence
69+
*/
70+
public LinguisticEvidence withEvidenceScore(final Integer evidenceScore) {
71+
this.evidenceScore = evidenceScore;
72+
return this;
73+
}
74+
75+
/**
76+
* Gets the word count.
77+
*
78+
* @return The wordCount
79+
*/
80+
public Integer getWordCount() {
81+
return wordCount;
82+
}
83+
84+
/**
85+
* Sets the word count.
86+
*
87+
* @param wordCount The word count
88+
*/
89+
public void setWordCount(final Integer wordCount) {
90+
this.wordCount = wordCount;
91+
}
92+
93+
/**
94+
* With word count.
95+
*
96+
* @param wordCount the word count
97+
* @return the linguistic evidence
98+
*/
99+
public LinguisticEvidence withWordCount(final Integer wordCount) {
100+
this.wordCount = wordCount;
101+
return this;
102+
}
103+
104+
/**
105+
* Gets the words.
106+
*
107+
* @return The words
108+
*/
109+
public List<String> getWords() {
110+
return words;
111+
}
112+
113+
/**
114+
* Sets the words.
115+
*
116+
* @param words The words
117+
*/
118+
public void setWords(final List<String> words) {
119+
this.words = words;
120+
}
121+
122+
/**
123+
* With words.
124+
*
125+
* @param words the words
126+
* @return the linguistic evidence
127+
*/
128+
public LinguisticEvidence withWords(final List<String> words) {
129+
this.words = words;
130+
return this;
131+
}
132+
133+
/**
134+
* Gets the correlation.
135+
*
136+
* @return The correlation
137+
*/
138+
public String getCorrelation() {
139+
return correlation;
140+
}
141+
142+
/**
143+
* Sets the correlation.
144+
*
145+
* @param correlation The correlation
146+
*/
147+
public void setCorrelation(final String correlation) {
148+
this.correlation = correlation;
149+
}
150+
151+
/**
152+
* With correlation.
153+
*
154+
* @param correlation the correlation
155+
* @return the linguistic evidence
156+
*/
157+
public LinguisticEvidence withCorrelation(final String correlation) {
158+
this.correlation = correlation;
159+
return this;
160+
}
161+
162+
}

0 commit comments

Comments
 (0)