How to get Text response from DialogFlow agent in android? - android

How do I get this Default response in Android?
I want to get the same response as I get doing this CURL request in android. Is there a way to do this using API.AI SDK or otherwise?

You can use Dialogflow Android SDK. Check the documentation for integration and accessing the Dialogflow agent.
Get action
final Result result = response.getResult();
Log.i(TAG, "Action: " + result.getAction());
Get speech
final Result result = response.getResult();
final String speech = result.getFulfillment().getSpeech();
Log.i(TAG, "Speech: " + speech);
Get metadata
final Result result = response.getResult();
final Metadata metadata = result.getMetadata();
if (metadata != null) {
Log.i(TAG, "Intent id: " + metadata.getIntentId());
Log.i(TAG, "Intent name: " + metadata.getIntentName());
}
Get parameters
final Result result = response.getResult();
final HashMap<String, JsonElement> params = result.getParameters();
if (params != null && !params.isEmpty()) {
Log.i(TAG, "Parameters: ");
for (final Map.Entry<String, JsonElement> entry : params.entrySet()) {
Log.i(TAG, String.format("%s: %s", entry.getKey(), entry.getValue().toString()));
}
}

Related

Intent failed with Canceled on SpeechFactory.fromSubscription (LUIS azure, android sdk)

I am getting the following message when trying to analyze an utterance with LUIS using the cognitive service android SDK:
Final result received: Intent failed with Canceled. Did you enter your Language Understanding subscription? WebSocket Upgrade failed with an authentication error (403). Please check the subscription key or the authorization token, and the region name., intent:
I am able to get an utterance evaluation via REST using the same Subscription key , and App ID passed to the SpeechFactory methods.
Moreover, continuous recognition through the Android SDK works as well.
Anyone is getting my same issue ?
source available at https://github.com/Azure-Samples/cognitive-services-speech-sdk/blob/master/samples/java/android/sdkdemo/app/src/main/java/com/microsoft/cognitiveservices/speech/samples/sdkdemo/MainActivity.java .
Code here:
recognizeIntentButton.setOnClickListener(view -> {
final String logTag = "intent";
final ArrayList<String> content = new ArrayList<>();
disableButtons();
clearTextBox();
content.add("");
content.add("");
try {
final SpeechFactory intentFactory = SpeechFactory.fromSubscription(LanguageUnderstandingSubscriptionKey, LanguageUnderstandingServiceRegion);
final IntentRecognizer reco = intentFactory.createIntentRecognizerWithStream(createMicrophoneStream());
LanguageUnderstandingModel intentModel = LanguageUnderstandingModel.fromAppId(LanguageUnderstandingAppId);
for (Map.Entry<String, String> entry : intentIdMap.entrySet()) {
reco.addIntent(entry.getKey(), intentModel, entry.getValue());
}
reco.IntermediateResultReceived.addEventListener((o, intentRecognitionResultEventArgs) -> {
final String s = intentRecognitionResultEventArgs.getResult().getText();
Log.i(logTag, "Intermediate result received: " + s);
content.set(0, s);
setRecognizedText(TextUtils.join(System.lineSeparator(), content));
});
final Future<IntentRecognitionResult> task = reco.recognizeAsync();
setOnTaskCompletedListener(task, result -> {
Log.i(logTag, "Continuous recognition stopped.");
String s = result.getText();
if (result.getReason() != RecognitionStatus.Recognized) {
s = "Intent failed with " + result.getReason() + ". Did you enter your Language Understanding subscription?" + System.lineSeparator() + result.getErrorDetails();
}
String intentId = result.getIntentId();
String intent = "";
if (intentIdMap.containsKey(intentId)) {
intent = intentIdMap.get(intentId);
}
Log.i(logTag, "Final result received: " + s + ", intent: " + intent);
content.set(0, s);
content.set(1, " [intent: " + intent + "]");
setRecognizedText(TextUtils.join(System.lineSeparator(), content));
enableButtons();
});
} catch (Exception ex) {
System.out.println(ex.getMessage());
displayException(ex);
}
});
}

No description or tags returned using Microsoft Computer Vision API

I want to make an android app using Microsoft's computer vision API, and what I wanted to do is to capture an image and return tags or caption which describes the image.My problem is that it does return wrong json data. Here is so far what I have done...
process method under AnalyzeActivity.java
private String process() throws VisionServiceException, IOException {
Gson gson = new Gson();
String[] features = {"ImageType", "Color", "Faces", "Adult", "Categories"};
String[] details = {};
ByteArrayOutputStream output = new ByteArrayOutputStream();
bitmapPicture.compress(Bitmap.CompressFormat.JPEG, 100, output);
ByteArrayInputStream inputStream = new ByteArrayInputStream(output.toByteArray());
AnalysisResult v = this.client.analyzeImage(inputStream, features, details);
String result = gson.toJson(v);
Log.d("result", result);
return result;
}
onPostExecute method under AnalyzeActivity
#Override
protected void onPostExecute(String data) {
super.onPostExecute(data);
mEditText.setText("");
if (e != null) {
mEditText.setText("Error: " + e.getMessage());
this.e = null;
} else {
Gson gson = new Gson();
AnalysisResult result = gson.fromJson(data, AnalysisResult.class);
mEditText.append("Definition: ");
mEditText.append("Image format: " + result.metadata.format + "\n");
mEditText.append("Image width: " + result.metadata.width + ", height:" + result.metadata.height + "\n");
for (Category category: result.categories) {
mEditText.append("Category: " + category.name + ", score: " + category.score + "\n");
}
for (Caption caption: result.description.captions) {
mEditText.append("Caption: " + caption.text + ", confidence: " + caption.confidence + "\n");
}
mEditText.append("\n");
for (String tag: result.description.tags) {
mEditText.append("Tag: " + tag + "\n");
}
mEditText.append("\n");
}
}
Here is the error message from logcat
FATAL EXCEPTION: main
Process: myapp.capstone.com.lumineux, PID: 1693
java.lang.NullPointerException: Attempt to read from field
'java.util.List
com.microsoft.projectoxford.vision.contract.Description.captions' on a
null object reference
at
myapp.capstone.com.lumineux.AnalyzeActivity$doRequest.onPostExecute(AnalyzeActivity.java:152)
at
myapp.capstone.com.lumineux.AnalyzeActivity$doRequest.onPostExecute(AnalyzeActivity.java:91)
at android.os.AsyncTask.finish(AsyncTask.java:636)
at android.os.AsyncTask.access$500(AsyncTask.java:177)
at
android.os.AsyncTask$InternalHandler.handleMessage(AsyncTask.java:653)
at android.os.Handler.dispatchMessage(Handler.java:102)
at android.os.Looper.loop(Looper.java:135)
at android.app.ActivityThread.main(ActivityThread.java:5254)
at java.lang.reflect.Method.invoke(Native Method)
at java.lang.reflect.Method.invoke(Method.java:372)
atcom.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:902)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:697)
Thanks in advance.
Your response will not contain captions unless you request it. You have two options:
(1) Call the /analyze?visualFeatures=Description endpoint. In your example you would achive this by changing the one line to the following:
String[] features = {"Description"};
(2) Call the /describe endpoint. For the SDK in question you would invoke the DescribeActivity instead of the AnalyzeActivity. In other words you'd call:
AnalysisResult v = this.client.describe(inputStream, 1);
The second method is simpler, and will also give you the opportunity to get more than one candidate sentence (by changing the second argument.) The first is more convenient if you want some other feature in addition to the description, such as Faces.

AWS SignatureDoesNotMatch

Receiving:
SignatureDoesNotMatchThe request signature we calculated does not match the signature you provided. Check your AWS Secret Access Key and signing method. Consult the service documentation for details.
With the following:
String associateTag = "example-20";
String awsAccessKeyId = "accessKeyId";
String awsSecretKey = "secretKey";
String endpoint = "webservices.amazon.com";
String uri = "/onca/xml";
String charset = "UTF8";
private String buildQueryString(String keywords) {
Map<String,String> params = new ArrayMap<>();
List<String> pairs = new ArrayList<>();
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss.SSS'Z'", Locale.US);
sdf.setTimeZone(TimeZone.getTimeZone("UTC"));
params.put("Service","AWSECommerceService");
params.put("Operation","ItemSearch");
params.put("AWSAccessKeyId",awsAccessKeyId);
params.put("AssociateTag",associateTag);
params.put("SearchIndex","All");
params.put("ResponseGroup","Images,ItemAttributes");
params.put("Timestamp",sdf.format(new Date()));
params.put("Keywords", keywords);
Map<String, String> treeMap = new TreeMap<>(params);
try {
for (Map.Entry<String, String> param : treeMap.entrySet()) {
pairs.add(URLEncoder.encode(param.getKey(), charset) + "=" + URLEncoder.encode(param.getValue(), charset));
}
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
}
String queryString = "";
for (int i = 0; i < pairs.size(); i++) {
if (i != 0) {
queryString += "&";
}
queryString += pairs.get(i);
}
Log.d(TAG, "queryString: " + queryString);
return queryString;
}
private String buildSignature(String queryString) {
String hash = "";
try {
String message = "GET\n" + endpoint + "\n" + uri + "\n" + queryString;
Log.d(TAG, "message: " + message);
Mac sha_HMAC = Mac.getInstance("HmacSHA256");
SecretKeySpec secret_key = new SecretKeySpec(awsSecretKey.getBytes(charset), "HmacSHA256");
sha_HMAC.init(secret_key);
hash = Base64.encodeToString(sha_HMAC.doFinal(message.getBytes(charset)), Base64.DEFAULT);
}
catch (Exception e){
System.out.println("Error");
}
return hash;
}
public void searchProducts(String keywords) {
String requestUrl = "";
String queryString = buildQueryString(keywords);
String signature = buildSignature(queryString);
Log.d(TAG, "signature: " + signature);
try {
requestUrl = "http://" + endpoint + uri + "?" + queryString + "&Signature=" + URLEncoder.encode(signature, charset);
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
}
Log.d(TAG, "requestUrl: " + requestUrl);
Ion.with(context)
.load(requestUrl)
.asString()
.setCallback(new FutureCallback<String>() {
#Override
public void onCompleted(Exception e, String result) {
Log.d(TAG, "searchProducts result: " + result);
}
});
}
What could be the problem?
Make sure that your system clock is correct. It will be good idea to sync it using NTP. In the past I have seen signature errors when the time is out of sync.
What I've seen before is that this is normally down to permissions . Check access and secret key is correct and you have adequate permissions.
Changed:
Base64.DEFAULT;
To:
Base64.NO_WRAP;
It's hard to tell from the code. A few things to check:
Make sure the service you want to reach uses SigV2 signing (or query string signing). New services follow version 4 signing standard.
URLEncoder.encode doesn't meet AWS' encoding requirement RFC 3986. You need to apply some fixes to the encoded string.
Query strings should be sorted in a case insensitive way.
Your credentials are indeed correct.
It's a good idea to see how QueryStringSigner.java is implemented in the official SDK , and Signature Version 2 Signing Process.
PS: what's the reason of not using the offical SDK?
In the past when I have had this issue, it was to do with system time. Syncing time with NTP fix issue for me
Can be caused by
A space in the name (or path) of the file.
Characters that are not being properly encoded. Mostly / or +.
Generating new keys that does not contain these characters could help. More info on this issue or this one.

Play DRM protected video in android native player

I am developing a application based on drm player i am able to get drm info but i don't know how to integrate drm to android native player
for this i am using
mVideoView= (VideoView) findViewById(R.id.Trailer_VV);
String android_id = Secure.getString(getContentResolver(),Secure.ANDROID_ID);
url = "https://s3-us-west-2.amazonaws.com/amgo/SECOND.wvm";
System.out.println("Print android_id " + android_id);
DrmInfoRequest request = new DrmInfoRequest(DrmInfoRequest. TYPE_REGISTRATION_INFO, "video/wvm");
request.put("WVDRMServerKey", "http://widevine.ezdrm.com/widevine/cypherpc/cgi-bin/GetEMMs-ezdrm.cgi");
request.put("WVAssetURIKey", "https://s3-us-west-2.amazonaws.com/amgo/SECOND.wvm");
request.put("WVDeviceIDKey", "movidone");
request.put("WVPortalKey", "movidone");
request.put("WVCAUserDataKey", "ezE7B1D1");
client = new DrmManagerClient(VideoViewActivity.this);
client.acquireRights(request);
DrmInfo response = client.acquireDrmInfo(request);
if (response != null) {
System.out.println("DrmInfo " + response.getMimeType().toString());
//System.out.println("DrmInfo " + response.getData());
String drmInfoReqStatusKey = (String)response.get("WVDrmInfoRequestStatusKey");
if (null != drmInfoReqStatusKey && !drmInfoReqStatusKey.equals("")) {
long mWVDrmInfoReqStatusKey = Long.parseLong(drmInfoReqStatusKey);
System.out.println("mWVDrmInfoReqStatusKey: "+mWVDrmInfoReqStatusKey);
}
String mPluginVersion = (String)response.get("WVDrmInfoRequestVersionKey");
System.out.println("mPluginVersion: "+mPluginVersion);
} else {
System.out.println("no result");
}
mVideoView.setVideoURI(Uri.parse(url));
mVideoView.start();

Android: Google Data API - 401 Token Invalid Error

Well, I tried using Account Manager and I am getting "401 Token Invalid" error. What can be the reason.
Debug Log
Account name = xxxxxx#gmail.com
Token is : DQAAALIAAAAh-xxxxxxx
Starting Google DATA API loader-----------------
Inside Google Notebook loader-----------------
Setting Token : DQAAALIAAAAh-xxxxx
Url is : https://docs.google.com/feeds/default/private/full
Exception getting docs feed : 401 Token invalid
Done Google DATA API loader-----------------
Sample Code:
Log.d("Main","\tInside GoogleDATA API -----------------");
HttpTransport transport = new NetHttpTransport();
GoogleHeaders headers = new GoogleHeaders();
Log.d("Main","\tSetting Token : " + authToken);
headers.setGoogleLogin(authToken);
headers.gdataVersion="3.0";
transport.defaultHeaders = headers;
AtomParser parser = new AtomParser();
parser.namespaceDictionary = Namespace.DICTIONARY;
transport.addParser(parser);
try {
DocsUrl url = DocsUrl.forDefaultPrivateFull();
DocumentListFeed feed = DocumentListFeed.executeGet(transport,url);
List<DocumentListEntry> docs = feed.docs;
Log.d("Main","\tDocs count = " + docs.size());
for (Iterator iterator = docs.iterator(); iterator.hasNext();) {
DocumentListEntry documentListEntry = (DocumentListEntry) iterator
.next();
Log.d("Main","\t\tDocument title is : " + documentListEntry.title);
}
} catch (IOException e) {
Log.d("Main","Exception getting docs feed : " + e.getMessage());
//handleException(e);
}
Log.d("Main","\tDone GoogleDATA API -----------------");
you should see how it works on this website http://n01se.net/gmapez/start.html

Categories

Resources