-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathMainActivity.java
More file actions
436 lines (362 loc) · 15.9 KB
/
MainActivity.java
File metadata and controls
436 lines (362 loc) · 15.9 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
package com.example.vmac.WatBot;
import android.Manifest;
import android.content.Context;
import android.content.pm.PackageManager;
import android.graphics.Typeface;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.os.Bundle;
import android.support.annotation.NonNull;
import android.support.v4.app.ActivityCompat;
import android.support.v4.content.ContextCompat;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.DefaultItemAnimator;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.util.Log;
import android.view.View;
import android.widget.EditText;
import android.widget.ImageButton;
import android.widget.Toast;
import com.ibm.watson.developer_cloud.android.library.audio.MicrophoneInputStream;
import com.ibm.watson.developer_cloud.android.library.audio.StreamPlayer;
import com.ibm.watson.developer_cloud.android.library.audio.utils.ContentType;
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.speech_to_text.v1.SpeechToText;
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.websocket.RecognizeCallback;
import com.ibm.watson.developer_cloud.text_to_speech.v1.TextToSpeech;
import com.ibm.watson.developer_cloud.text_to_speech.v1.model.Voice;
import com.ibm.mobilefirstplatform.clientsdk.android.core.api.*;
import com.ibm.mobilefirstplatform.clientsdk.android.analytics.api.*;
import com.ibm.mobilefirstplatform.clientsdk.android.logger.api.*;
import org.json.JSONObject;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Map;
public class MainActivity extends AppCompatActivity {
private RecyclerView recyclerView;
private ChatAdapter mAdapter;
private ArrayList messageArrayList;
private EditText inputMessage;
private ImageButton btnSend;
private ImageButton btnRecord;
private Map<String,Object> context = new HashMap<>();
StreamPlayer streamPlayer;
private boolean initialRequest;
private boolean permissionToRecordAccepted = false;
private static final int REQUEST_RECORD_AUDIO_PERMISSION = 200;
private static String TAG = "MainActivity";
private static final int RECORD_REQUEST_CODE = 101;
private boolean listening = false;
private SpeechToText speechService;
private MicrophoneInputStream capture;
private Logger myLogger;
private Context mContext;
private String workspace_id;
private String conversation_username;
private String conversation_password;
private String STT_username;
private String STT_password;
private String TTS_username;
private String TTS_password;
private String analytics_APIKEY;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
mContext = getApplicationContext();
conversation_username = mContext.getString(R.string.conversation_username);
conversation_password = mContext.getString(R.string.conversation_password);
workspace_id = mContext.getString(R.string.workspace_id);
STT_username = mContext.getString(R.string.STT_username);
STT_password = mContext.getString(R.string.STT_password);
TTS_username = mContext.getString(R.string.TTS_username);
TTS_password = mContext.getString(R.string.TTS_password);
//analytics_APIKEY = mContext.getString(R.string.mobileanalytics_apikey);
/*//Bluemix Mobile Analytics
BMSClient.getInstance().initialize(getApplicationContext(), BMSClient.REGION_US_SOUTH);
//Analytics is configured to record lifecycle events.
Analytics.init(getApplication(), "WatBot", analytics_APIKEY, false, Analytics.DeviceEvent.ALL);
//Analytics.send();
myLogger = Logger.getLogger("myLogger");
// Send recorded usage analytics to the Mobile Analytics Service
Analytics.send(new ResponseListener() {
@Override
public void onSuccess(Response response) {
// Handle Analytics send success here.
}
@Override
public void onFailure(Response response, Throwable throwable, JSONObject jsonObject) {
// Handle Analytics send failure here.
}
});
// Send logs to the Mobile Analytics Service
Logger.send(new ResponseListener() {
@Override
public void onSuccess(Response response) {
// Handle Logger send success here.
}
@Override
public void onFailure(Response response, Throwable throwable, JSONObject jsonObject) {
// Handle Logger send failure here.
}
});
*/
inputMessage = (EditText) findViewById(R.id.message);
btnSend = (ImageButton) findViewById(R.id.btn_send);
btnRecord= (ImageButton) findViewById(R.id.btn_record);
String customFont = "Montserrat-Regular.ttf";
Typeface typeface = Typeface.createFromAsset(getAssets(), customFont);
inputMessage.setTypeface(typeface);
recyclerView = (RecyclerView) findViewById(R.id.recycler_view);
messageArrayList = new ArrayList<>();
mAdapter = new ChatAdapter(messageArrayList);
LinearLayoutManager layoutManager = new LinearLayoutManager(this);
layoutManager.setStackFromEnd(true);
recyclerView.setLayoutManager(layoutManager);
recyclerView.setItemAnimator(new DefaultItemAnimator());
recyclerView.setAdapter(mAdapter);
this.inputMessage.setText("");
this.initialRequest = true;
sendMessage();
//Watson Text-to-Speech Service on Bluemix
final TextToSpeech service = new TextToSpeech();
service.setUsernameAndPassword(TTS_username, TTS_password);
int permission = ContextCompat.checkSelfPermission(this,
Manifest.permission.RECORD_AUDIO);
if (permission != PackageManager.PERMISSION_GRANTED) {
Log.i(TAG, "Permission to record denied");
makeRequest();
}
recyclerView.addOnItemTouchListener(new RecyclerTouchListener(getApplicationContext(), recyclerView, new ClickListener() {
@Override
public void onClick(View view, final int position) {
Thread thread = new Thread(new Runnable() {
public void run() {
Message audioMessage;
try {
audioMessage =(Message) messageArrayList.get(position);
streamPlayer = new StreamPlayer();
if(audioMessage != null && !audioMessage.getMessage().isEmpty())
//Change the Voice format and choose from the available choices
streamPlayer.playStream(service.synthesize(audioMessage.getMessage(), Voice.EN_LISA).execute());
else
streamPlayer.playStream(service.synthesize("No Text Specified", Voice.EN_LISA).execute());
} catch (Exception e) {
e.printStackTrace();
}
}
});
thread.start();
}
@Override
public void onLongClick(View view, int position) {
recordMessage();
}
}));
btnSend.setOnClickListener(new View.OnClickListener(){
@Override
public void onClick(View v) {
if(checkInternetConnection()) {
sendMessage();
}
}
});
btnRecord.setOnClickListener(new View.OnClickListener() {
@Override public void onClick(View v) {
recordMessage();
}
});
};
// Speech-to-Text Record Audio permission
@Override
public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
super.onRequestPermissionsResult(requestCode, permissions, grantResults);
switch (requestCode){
case REQUEST_RECORD_AUDIO_PERMISSION:
permissionToRecordAccepted = grantResults[0] == PackageManager.PERMISSION_GRANTED;
break;
case RECORD_REQUEST_CODE: {
if (grantResults.length == 0
|| grantResults[0] !=
PackageManager.PERMISSION_GRANTED) {
Log.i(TAG, "Permission has been denied by user");
} else {
Log.i(TAG, "Permission has been granted by user");
}
return;
}
}
if (!permissionToRecordAccepted ) finish();
}
protected void makeRequest() {
ActivityCompat.requestPermissions(this,
new String[]{Manifest.permission.RECORD_AUDIO},
RECORD_REQUEST_CODE);
}
// Sending a message to Watson Conversation Service
private void sendMessage() {
final String inputmessage = this.inputMessage.getText().toString().trim();
if(!this.initialRequest) {
Message inputMessage = new Message();
inputMessage.setMessage(inputmessage);
inputMessage.setId("1");
messageArrayList.add(inputMessage);
myLogger.info("Sending a message to Watson Conversation Service");
}
else
{
Message inputMessage = new Message();
inputMessage.setMessage(inputmessage);
inputMessage.setId("100");
this.initialRequest = false;
Toast.makeText(getApplicationContext(),"Tap on the message for Voice",Toast.LENGTH_LONG).show();
}
this.inputMessage.setText("");
mAdapter.notifyDataSetChanged();
Thread thread = new Thread(new Runnable(){
public void run() {
try {
ConversationService service = new ConversationService(ConversationService.VERSION_DATE_2016_07_11);
service.setUsernameAndPassword(conversation_username, conversation_password);
MessageRequest newMessage = new MessageRequest.Builder().inputText(inputmessage).context(context).build();
MessageResponse response = service.message(workspace_id, newMessage).execute();
//Passing Context of last conversation
if(response.getContext() !=null)
{
context.clear();
context = response.getContext();
}
Message outMessage=new Message();
if(response!=null)
{
if(response.getOutput()!=null && response.getOutput().containsKey("text"))
{
ArrayList responseList = (ArrayList) response.getOutput().get("text");
if(null !=responseList && responseList.size()>0){
outMessage.setMessage((String)responseList.get(0));
outMessage.setId("2");
}
messageArrayList.add(outMessage);
}
runOnUiThread(new Runnable() {
public void run() {
mAdapter.notifyDataSetChanged();
if (mAdapter.getItemCount() > 1) {
recyclerView.getLayoutManager().smoothScrollToPosition(recyclerView, null, mAdapter.getItemCount()-1);
}
}
});
}
} catch (Exception e) {
e.printStackTrace();
}
}
});
thread.start();
}
//Record a message via Watson Speech to Text
private void recordMessage() {
//mic.setEnabled(false);
speechService = new SpeechToText();
speechService.setUsernameAndPassword(STT_username, STT_password);
if(listening != true) {
capture = new MicrophoneInputStream(true);
new Thread(new Runnable() {
@Override public void run() {
try {
speechService.recognizeUsingWebSocket(capture, getRecognizeOptions(), new MicrophoneRecognizeDelegate());
} catch (Exception e) {
showError(e);
}
}
}).start();
listening = true;
Toast.makeText(MainActivity.this,"Listening....Click to Stop", Toast.LENGTH_LONG).show();
} else {
try {
capture.close();
listening = false;
Toast.makeText(MainActivity.this,"Stopped Listening....Click to Start", Toast.LENGTH_LONG).show();
} catch (Exception e) {
e.printStackTrace();
}
}
}
/**
* Check Internet Connection
* @return
*/
private boolean checkInternetConnection() {
// get Connectivity Manager object to check connection
ConnectivityManager cm =
(ConnectivityManager)getSystemService(Context.CONNECTIVITY_SERVICE);
NetworkInfo activeNetwork = cm.getActiveNetworkInfo();
boolean isConnected = activeNetwork != null &&
activeNetwork.isConnectedOrConnecting();
// Check for network connections
if (isConnected){
return true;
}
else {
Toast.makeText(this, " No Internet Connection available ", Toast.LENGTH_LONG).show();
return false;
}
}
//Private Methods - Speech to Text
private RecognizeOptions getRecognizeOptions() {
return new RecognizeOptions.Builder()
.continuous(true)
.contentType(ContentType.OPUS.toString())
//.model("en-UK_NarrowbandModel")
.interimResults(true)
.inactivityTimeout(2000)
.build();
}
//Watson Speech to Text Methods.
private class MicrophoneRecognizeDelegate implements RecognizeCallback {
@Override
public void onTranscription(SpeechResults speechResults) {
System.out.println(speechResults);
if(speechResults.getResults() != null && !speechResults.getResults().isEmpty()) {
String text = speechResults.getResults().get(0).getAlternatives().get(0).getTranscript();
showMicText(text);
}
}
@Override public void onConnected() {
}
@Override public void onError(Exception e) {
showError(e);
enableMicButton();
}
@Override public void onDisconnected() {
enableMicButton();
}
}
private void showMicText(final String text) {
runOnUiThread(new Runnable() {
@Override public void run() {
inputMessage.setText(text);
}
});
}
private void enableMicButton() {
runOnUiThread(new Runnable() {
@Override public void run() {
btnRecord.setEnabled(true);
}
});
}
private void showError(final Exception e) {
runOnUiThread(new Runnable() {
@Override public void run() {
Toast.makeText(MainActivity.this, e.getMessage(), Toast.LENGTH_SHORT).show();
e.printStackTrace();
}
});
}
}