Getting error message as INVALID_ARGUMENT: Invalid recognition 'config': Invalid class id speech-to-text API - google-cloud-speech

we are using Google's speech-to-text API. We are trying to implement an adaptation model with the API. However, while doing so, we are getting an error message as 'INVALID_ARGUMENT: Invalid recognition 'config': Invalid class id {id}'. When I see whether CustomClass is available from cloud API, it shows it is available. However, still get the same error while using it in speech adaptation configuration. I am following this document https://github.com/googleapis/java-speech/blob/d1307be7e5510f4e5d9cf075a8efc3bd924d7bcf/samples/snippets/src/main/java/com/example/speech/SpeechModelAdaptationBeta.java. Any help would be greatly appreciated.
I tried using https://github.com/googleapis/java-speech/blob/d1307be7e5510f4e5d9cf075a8efc3bd924d7bcf/samples/snippets/src/main/java/com/example/speech/SpeechModelAdaptationBeta.java. But got exception only.
Below is the code which I am trying with:
`SpeechSettings speechSettings = SpeechSettings.newBuilder().setCredentialsProvider(credentialsProvider).build();
AdaptationSettings adaptationSettings = AdaptationSettings.newBuilder().setCredentialsProvider(credentialsProvider).build();
// Instantiates a client
SpeechClient speechClient = SpeechClient.create(speechSettings);
AdaptationClient adaptationClient = AdaptationClient.create(adaptationSettings);
String customClassUUID = UUID.randomUUID().toString().replace("-", "");
List<PhraseSet.Phrase> phraseArray = new ArrayList();
phraseArray.addAll(Phrase.newBuilder()
.setValue(
String.format("Visit restaurants like %s%n", customClassUUID)));
phraseArray.add(Phrase.newBuilder().setValue("Burger").build());
List classItemArray = new ArrayList();
classItemArray.add(ClassItem.newBuilder().setValue("Lettuce").build());
classItemArray.add(ClassItem.newBuilder().setValue("Burger").build());
CustomClass customClass = adaptationClient.createCustomClass(CreateCustomClassRequest.newBuilder().setParent(parent).setCustomClassId(customClassUUID).setCustomClass(CustomClass.newBuilder().addAllItems(classItemArray).build()).build());
String customClassName = parent+"/customClasses/"+customClassUUID;
String phraseSetUUID = UUID.randomUUID().toString().replace("-", "");
PhraseSet phraseSet = adaptationClient.createPhraseSet(CreatePhraseSetRequest.newBuilder().setParent(parent).setPhraseSetId(phraseSetUUID).setPhraseSet(PhraseSet.newBuilder().setBoost(10f).addPhrases(
Phrase.newBuilder()
.setValue(
String.format("Visit restaurants like %s%n", customClassUUID))).build()).build());
RecognitionConfig config =
RecognitionConfig.newBuilder()
.setEncoding(AudioEncoding.LINEAR16)
.setSampleRateHertz(8000)
.setLanguageCode("en-US")
.setUseEnhanced(true)
.setModel("phone_call")
.setAdaptation(SpeechAdaptation.newBuilder()
.addPhraseSets(adaptationClient.createPhraseSet(CreatePhraseSetRequest.newBuilder().setParent(parent).setPhraseSetId(phraseSetUUID).setPhraseSet(PhraseSet.newBuilder().setBoost(10f).addAllPhrases(phraseArray).build()).build()))
.addCustomClasses(adaptationClient.createCustomClass(CreateCustomClassRequest.newBuilder().setParent(parent).setCustomClassId(customClassUUID).setCustomClass(CustomClass.newBuilder().addAllItems(classItemArray).build()).build())).build())
.build();`

Related

Error with Microsoft graph, ODataType error with Sendmail

I have an error occurring that I can't seem to find anything about. When I run my code I get the following error. I am not setting oDataType so I assume this is something done by the api itself.
ServiceException: Code: RequestBodyRead Message: The property 'oDataType' does not exist on type microsoft.graph.itemBody'. Make sure to only use property names that are defined by the type or mark the type as open type.
My code is mostly copied from microsoft samples.
var confidentialClientApplication = ConfidentialClientApplicationBuilder
.Create(clientId)
.WithTenantId(tenantId)
.WithClientSecret(clientSecret)
.WithAuthority(new Uri(authority))
.Build();
ClientCredentialProvider authenticationProvider = new ClientCredentialProvider(confidentialClientApplication);
client = new GraphServiceClient(authenticationProvider);
var message = new Microsoft.Graph.Message()
{
Subject = "Test email",
Body = new ItemBody
{
ContentType = BodyType.Text,
Content = "Test email."
},
HasAttachments = false,
ToRecipients = new List<Recipient>()
{
new Recipient
{
EmailAddress = new EmailAddress
{
Address = "myemail#mydomain.com"
}
}
}
};
var saveToSentItems = false;
await client.Users[userID].SendMail(message, saveToSentItems).Request().PostAsync();
Any help would be greatly appreciated.
Thank you
I suspect, you're using a older library/build. I remember the related issue and it's fixed last year itself.
Please update it with the latest one , try testing the same and let us know if you can still repro the issue or not.

Google Machine Learning API Issue

I'm trying to use the Google Machine Learning API and I'm facing two problems.
In the API explorer I put the correct information and I get a response error:
Code 200
"error": "Missing \"instances\" field in request body: {\n \"httpBody\": \n
{\n \"data\": \"\\"instances\\" : \\"teste\\"\",\n
\"contentType\": \"application/json\"\n }\n}"
The request find my model (if I change the value in field name I get another error) but don't understand my json. That's the json:
{"instances" : [{"key":"0", "image_bytes": {"b64": "mybase64"} }]}
When I do the predict on the command line using gcloud, I get no errors and everything seems ok. The Json that I was create for gcloud is a little bit different:
{"key":"0", "image_bytes": {"b64": "mybase64"} }
I already tryied that one in the API explorer and no success.
So, I decided to use the .Net Api to try the predict and I get other situation: The Response is Empty (???).
Here is my code:
'get the service credential that I created
Dim credential = Await GetCredential()
Dim myService As New CloudMachineLearningEngineService(New BaseClientService.Initializer() With {
.ApplicationName = "my Project Name (Is That It???)",
.ApiKey = "my API Key",
.HttpClientInitializer = credential
})
Dim myBase64 As String = GetBase64("my image path to convert into a base64 String")
Dim myJsonRequest As String = "{""instances"" : [{""key"":""0"", ""image_bytes"": {""b64"": """ + myBase64 + """}}]}"
Dim myRequest = New GoogleCloudMlV1PredictRequest With {
.HttpBody = New GoogleApiHttpBody With {.Data = myJsonRequest,
.ContentType = "application/json"
}
}
'If I change the model name I get error
Dim myPredictRequest = myService.Projects.Predict(myRequest, "projects/myProject/models/myModel/versions/v1")
myPredictRequest.AccessToken = credential.Token.AccessToken
myPredictRequest.OauthToken = credential.Token.AccessToken
myPredictRequest.Key = "my API Key
'Execute the request
Dim myResponse = myPredictRequest.Execute()
'at this point, myResponse is Empty (myResponse.ContentType Is Nothing, myResponse.Data Is Nothing And myResponse.ETag Is Nothing)
If I change the model name I get a error informing that my model was not found, so my credentials are right.
I don't know what I'm doing wrong. Someboby can help with any of this issues?
Thanks!
UPDATE: --------------------------
I changed this Execute Command:
Dim myResponse = myPredictRequest.Execute()
To This One:
Dim s = StreamToString(myPredictRequest.ExecuteAsStream())
and Now I can get the same error with .Net API and google developers interface (Missing instances field...).
So If someboby just Know what is wrong with my Json request, It will help a lot.
The JSON you put in the API explorer is indeed correct (assuming, of course, your model has inputs key and image_bytes). This appears to be a bug with the explorer I will report.
The reason you are getting the error you are in the .NET code is because you are using an .HttpBody field. This code:
Dim myJsonRequest As String = "{""instances"" : [{""key"":""0"", ""image_bytes"": {""b64"": """ + myBase64 + """}}]}"
Dim myRequest = New GoogleCloudMlV1PredictRequest With {
.HttpBody = New GoogleApiHttpBody With {.Data = myJsonRequest,
.ContentType = "application/json"
}
}
Will produce a JSON request that looks like this:
{
"httpBody": {
"data": "{\"instances\" : [{\"key\":\"0\", \"image_bytes\": {\"b64\": \"mybase64\"} }]}",
"contentType": "application\/json"
}
}
When what you really need is:
{"instances" : [{"key":"0", "image_bytes": {"b64": "mybase64"} }]}
Hence the error message you see.
I don't know how to generate the correct response using the .NET library; based on the Python example in the docs, I would guess:
Dim myJsonRequest As String = "{""instances"" : [{""key"":""0"", ""image_bytes"": {""b64"": """ + myBase64 + """}}]}"
Dim myPredictRequest = myService.Projects.Predict(myJsonRequest, "projects/myProject/models/myModel/versions/v1")
But I don't have a good way of testing that. For reference, the Python equivalent is:
response = service.projects().predict(
name=name,
body=myJsonRequest
).execute()
I solved the problem with .Net API.
I created two new classes Inherits the Google API's classes.
Something like that:
Imports Google.Apis.CloudMachineLearningEngine.v1.Data
Imports Newtonsoft.Json
Public Class myGoogleCloudMlV1PredictRequest
Inherits GoogleCloudMlV1PredictRequest
<JsonProperty("instances")>
Public Property MyHttpBody As List(Of myGoogleApiHttpBody)
End Class
Imports Google.Apis.CloudMachineLearningEngine.v1.Data
Imports Newtonsoft.Json
Public Class myGoogleApiHttpBody
Inherits GoogleApiHttpBody
<JsonProperty("image_bytes")>
Public Property MyData As image_byte
<JsonProperty("key")>
Public Property key As String
End Class
So, in my original code I change this part:
Dim myBase64 As String = GetBase64("my_image_path_to_convert_into_a _base64_String")
Dim myJsonRequest As String = "{""instances"" : [{""key"":""0"", ""image_bytes"": {""b64"": """ + myBase64 + """}}]}"
Dim myRequest = New GoogleCloudMlV1PredictRequest With {
.HttpBody = New GoogleApiHttpBody With {.Data = myJsonRequest,
.ContentType = "application/json"
}
}
For this one:
Dim myBase64 As String = GetBase64("my_image_path_to_convert_into_a _base64_String")
Dim myRequest = New myGoogleCloudMlV1PredictRequest With {
.MyHttpBody = New List(Of myGoogleApiHttpBody)()
}
Dim item As myGoogleApiHttpBody = New myGoogleApiHttpBody With {
.key = "0",
.MyData = New image_byte With {
.b64 = myBase64
}
}
myRequest.MyHttpBody.Add(item)
And voilá, It's working!
Thanks for everyone!!
Github issue #1068 shows two work-arounds for this problem.
In summary, use service.ModifyRequest to insert the raw JSON content.
Or use service.HttpClient.PostAsync(...) directly.

How can i Pull Profile image from sharepoint

I'am new in API's & trying to pull user profile from sharepoint i use following code but don't know about servername? domainname? and username?
const string serverUrl = "http://sharepoint.com/";
const string targetUser = "ttgdev-my.sharepoint.com\\testuser1#ttgdev.guru";
// Connect to the client context.
ClientContext clientContext = new ClientContext(serverUrl);
// Get the PeopleManager object and then get the target user's properties.
PeopleManager peopleManager = new PeopleManager(clientContext);
PersonProperties personProperties = peopleManager.GetPropertiesFor(targetUser);
// Load the request and run it on the server.
// This example requests only the AccountName and UserProfileProperties
// properties of the personProperties object.
clientContext.Load(personProperties, p => p.AccountName, p => p.UserProfileProperties);
clientContext.ExecuteQuery();
foreach (var property in personProperties.UserProfileProperties)
{
Console.WriteLine(string.Format("{0}: {1}",
property.Key.ToString(), property.Value.ToString()));
}
Console.ReadKey(false);
Please guide me it will give me the error in
{"The property or field 'UserProfileProperties' has not been initialized. It has not been requested or the request has not been executed. It may need to be explicitly requested."}
in the following line
clientContext.ExecuteQuery();
Most likely it is related with the format of targetUser variable. PeopleManager.GetPropertiesFor method expects accountName parameter to be specified in the proper format, in case of SharePoint Online it should be specified in claims format, for example:
i:0#.f|membership|jdow#contoso.onmicrosoft.com
For more details about Claims format follow this article.
So, in your case targetUser value should be replaced from ttgdev-my.sharepoint.com\\testuser1#ttgdev.guru to i:0#.f|membership|testuser1#ttgdev.guru
The following example demonstrates how to retrieve user profile picture via CSOM API:
using (var ctx = TokenHelper.GetClientContextWithAccessToken(webUri.ToString(), accessToken))
{
// Get the PeopleManager object and then get the target user's properties.
var peopleManager = new PeopleManager(ctx);
PersonProperties personProperties = peopleManager.GetPropertiesFor(targetUser);
//Retrieve picture property
var result = peopleManager.GetUserProfilePropertyFor(accountName, "PictureURL");
ctx.ExecuteQuery();
Console.WriteLine("Picture Url: {0}",result.Value);
}

Mendeley Implicit auth type not returning full data

This question relates to the Mendeley API.
http://dev.mendeley.com/
When using the implicit auth type: http://dev.mendeley.com/reference/topics/authorization_overview.html
I seem to only receive a subset of data for a given document. For example, the 'websites' field seems to not come through even when it is populated.
I am only experiencing this issue using the implicit auth type and not other auth types.
Are any other Mendeley API users experiencing this? It seems like a bug.
Certain fields get returned depending on the document view that you specify. This was implemented to be able to support the needs of multiple clients e.g. mobile clients require smaller datasets than larger web clients
Please read - http://dev.mendeley.com/methods/#document-views
You need to specify 'view=bib' on your endpoint call.
Here is a very crude worked example just using Java
#Test
public void testImplicitGrantFlow() {
String random = RandomStringUtils.random(5);
String query = String.format(
"?client_id=%s&redirect_uri=%s&response_type=token&scope=all&state=%s", IMPLICIT_GRANT_FLOW_CLIENT_ID, "http://localhost:5000/callback", random);
ClientResponse authorise = jerseyClient.resource(AUTH_URL + query)
.accept(MediaType.APPLICATION_JSON)
.get(ClientResponse.class);
assertThat(authorise.getStatus()).isEqualTo(200);
ClientResponse postFormDataResponse = jerseyClient.resource(AUTH_URL + query)
.entity("username=joyce.stack#mendeley.com&password=spuds", MediaType.APPLICATION_FORM_URLENCODED_TYPE)
.accept(MediaType.APPLICATION_JSON)
.post(ClientResponse.class);
assertThat(postFormDataResponse.getStatus()).isEqualTo(302);
String queryString = postFormDataResponse.getHeaders().get("Location").get(0);
Matcher matcher = ACCESS_TOKEN_REGEX.matcher(queryString);
matcher.find();
String accessToken = matcher.group(1);
matcher = STATE_REGEX.matcher(queryString);
matcher.find();
String state = matcher.group(1);
assertNotNull(accessToken);
assertThat(queryString).contains(accessToken);
assertNotNull(state);
assertThat(queryString).contains(state);
ClientResponse response = jerseyClient.resource(OAuthBaseClass.DOCUMENTS_URL)
.header("Authorization", "Bearer " + accessToken)
.get(ClientResponse.class);
assertThat(response.getStatus()).isEqualTo(200);
List<Document> documents = response.getEntity(new GenericType<List<Document>>() {
});
assertThat(documents.size()).isGreaterThan(0);
ListIterator<Document> documentListIterator = documents.listIterator();
while (documentListIterator.hasNext()) {
Document next = documentListIterator.next();
System.out.println(next.getTitle());
System.out.println(next.getWebsites());
}
}

BillQuery for getting bills giving Unauthorized error in Intuit

I'm getting "Unauthorized" error while trying to use filter in Intuit:
Exception Details: Intuit.Ipp.Exception.InvalidTokenException: Unauthorized
The code below is used to setup the Service Context:
string AppToken = ConfigurationManager.AppSettings["applicationToken"].ToString(CultureInfo.InvariantCulture);
String realmId = HttpContext.Current.Session["realm"].ToString();
String accessToken = HttpContext.Current.Session["accessToken"].ToString();
String accessTokenSecret = HttpContext.Current.Session["accessTokenSecret"].ToString();
String consumerKey = ConfigurationManager.AppSettings["consumerKey"].ToString(CultureInfo.InvariantCulture);
String consumerSecret = ConfigurationManager.AppSettings["consumerSecret"].ToString(CultureInfo.InvariantCulture);
IntuitServicesType intuitServiceType = (IntuitServicesType)HttpContext.Current.Session["intuitServiceType"];
OAuthRequestValidator oauthValidator = new OAuthRequestValidator(accessToken, accessTokenSecret, consumerKey, consumerSecret);
context1 = new ServiceContext(oauthValidator, AppToken, realmId, IntuitServicesType.QBO);
Query for retrieving the last modified bills is as below:
List<Bill> CustomerBills = billQry.ExecuteQuery<Bill>(context1).ToList<Bill>();
Please let me know, which parameter value I'm passing incorrectly.
The following code .NET DevKit code sends a malformed request body and results in a OAuth signature error. This is a bug in the DevKit.
BillQuery billQry = new BillQuery();
billQry.LastUpdatedTime = DateTime.Now.AddDays(-20);
billQry.SpecifyOperatorOption(FilterProperty.LastUpdatedTime, FilterOperatorType.AFTER);
billQry.LastUpdatedTime = DateTime.Now;
billQry.SpecifyOperatorOption(FilterProperty.LastUpdatedTime, FilterOperatorType.BEFORE);
billQry.PageNumber = 1;
billQry.ResultsPerPage = 15;
billQry.SpecifySortOption(SortProperty.LastUpdatedTime, SortOrderOption.HighToLow);
List<Intuit.Ipp.Data.Qbo.Bill>CustomerBills =billQry.ExecuteQuery<Intuit.Ipp.Data.Qbo.Bill>(context).ToList();
The workaround is to modify the sample code below to make the request and deserialize the response into Bill objects.
Sample Code on Pastebin

Resources