Fail to detect the language of the content input.
I've double checked the API key and it's correct.
When I try to detect the language, it appears error 401.
// ***** DETECT LANGUAGE OF TEXT TO BE TRANSLATED
private string DetectLanguage(string text)
{
string uri = TEXT_ANALYTICS_API_ENDPOINT + "languages?numberOfLanguagesToDetect=1";
// create request to Text Analytics API
HttpWebRequest detectLanguageWebRequest = (HttpWebRequest)WebRequest.Create(uri);
detectLanguageWebRequest.Headers.Add("Ocp-Apim-Subscription-Key", TEXT_ANALYTICS_API_SUBSCRIPTION_KEY);
detectLanguageWebRequest.Method = "POST";
// create and send body of request
var serializer = new System.Web.Script.Serialization.JavaScriptSerializer();
string jsonText = serializer.Serialize(text);
string body = "{ \"documents\": [ { \"id\": \"0\", \"text\": " + jsonText + "} ] }";
byte[] data = Encoding.UTF8.GetBytes(body);
detectLanguageWebRequest.ContentLength = data.Length;
using (var requestStream = detectLanguageWebRequest.GetRequestStream())
requestStream.Write(data, 0, data.Length);
HttpWebResponse response = (HttpWebResponse)detectLanguageWebRequest.GetResponse();
// read and parse JSON response
var responseStream = response.GetResponseStream();
var jsonString = new StreamReader(responseStream, Encoding.GetEncoding("utf-8")).ReadToEnd();
dynamic jsonResponse = serializer.DeserializeObject(jsonString);
// fish out the detected language code
var languageInfo = jsonResponse["documents"][0]["detectedLanguages"][0];
if (languageInfo["score"] > (decimal)0.5)
return languageInfo["iso6391Name"];
else
return "";
}
Related
I need to read a value from HTTP response. Here is an example of the response in which I'm trying to fetch (description) value:
{
"result":{
"code":"200.300.404",
"description":"successful"
},
"buildNumber":"1f9#2021-12-23 09:56:49 +0000",
"timestamp":"2021-12-25 17:22:35+0000",
"ndc":"8976eaedf8da"
}
Here is my code
Dictionary<string, dynamic> responseData;
string data = "entityId=8a8294174d0595bb014d05d82e5b01d2";
string url = "https://test.oppwa.com/v1/checkouts/" + CheckoutId + "/payment?" + data;
HttpWebRequest request = (HttpWebRequest)HttpWebRequest.Create(url);
request.Method = "GET";
request.Headers["Authorization"] = "Bearer xxxx";
using (HttpWebResponse response = (HttpWebResponse)request.GetResponse())
{
Stream dataStream = response.GetResponseStream();
StreamReader reader = new StreamReader(dataStream);
// var s = new JavaScriptSerializer();
responseData = JsonSerializer.Deserialize<Dictionary<string, dynamic>>(reader.ReadToEnd());
reader.Close();
dataStream.Close();
}
// If responseDate.Description=success then enroll user and register the payment
var res = responseData["result"];
// I'm trying to do this but not working
var res = responseData["result"]["description"];
return responseData;
Any help is appreciated
Thanks
You can use JToken or JObject of Newtonsoft.Json.Linq.
For example, if your response format like as below:
{
"result":{
"code":"200.300.404",
"description":"successful"
},
"buildNumber":"1f9#2021-12-23 09:56:49 +0000",
"timestamp":"2021-12-25 17:22:35+0000",
"ndc":"8976eaedf8da"
}
You can use below code for this purpose:
...
string webResponseAsString = reader.ReadToEnd();
dynamic dynamicResult = JToken.Parse(webResponseAsString);
string description = dynamicResult.result.description
For more details, you can visit this links:
Using JSON.NET for dynamic JSON parsing
Querying JSON with dynamic
What is better to use when parsing dynamic JSON data: JToken or c# built in dynamic type
try this
StreamReader reader = new StreamReader(dataStream);
var json = reader.ReadToEnd();
...
var jsonObject=JObject.Parse(json);
var result=jsonObject["result"];
var description = jsonObject["result"]["description"];
// or
var description =result["description"];
description value
successful
responseData["result"].description
Will get you the JValue of "successful".
Although there are some other issues. Deserialize needs an instance of JsonSerializer, it is not a static method. Here is a full example without using a Dictionary.
var response = #"
{
""result"":{
""code"":""200.300.404"",
""description"":""successful""
},
""buildNumber"":""1f9#2021-12-23 09:56:49 +0000"",
""timestamp"":""2021-12-25 17:22:35+0000"",
""ndc"":""8976eaedf8da""
}
";
var responseData = new JsonSerializer()
.Deserialize<dynamic>(
new JsonTextReader(new StringReader(response)));
responseData.result.description; //successful
Here is my code below. Getting the token from shopify works fine. However while creating a new product it keeps giving me an error. I've tried everything possible and it still does not work. Any advice would be appreciated.
Here's how I call the CreateNewProduct method passing the access token from shopify and the shopname with the products endpoint.
CreateNewProduct(accessTokenDTO.access_token, "https://{myshopname}.myshopify.com/admin/api/2020-10/products.json");
Here's the method below.
public static void CreateNewProduct(string token, string Url)
{
Uri shopUri = new Uri(Url);
HttpWebRequest GETRequest = (HttpWebRequest)WebRequest.Create(shopUri);
GETRequest.ContentType = "application/json";
GETRequest.Headers.Add("X-Shopify-Access-Token", token);
GETRequest.PreAuthenticate = true;
GETRequest.Method = "PUT";
using (var streamWriter = new StreamWriter(GETRequest.GetRequestStream()))
{
string json = "{\"product\": { \"title\": \"Burton Custom Freestyle 151\", \"body_html\": \"<strong>Good snowboard!</strong>\", \"vendor\": \"Burton\", \"product_type\": \"Snowboard\", \"tags\": [ \"Barnes & Noble\", \"John's Fav\", \"\\Big Air\\]}";
streamWriter.Write(json);
streamWriter.Flush();
}
HttpWebResponse GETResponse = (HttpWebResponse)GETRequest.GetResponse();
var encoding = ASCIIEncoding.ASCII;
using (var reader = new System.IO.StreamReader(GETResponse.GetResponseStream(), encoding))
{
string responseText = reader.ReadToEnd();
Debug.WriteLine("Response Text: " + responseText);
}
GETResponse.Close();
}
400 BadRequest normally refers to the body you are sending with your request is not valid according to the api.
Wheni look at your string that is supposed to be a json, it shows invalid data at the end.
[ \"Barnes & Noble\", \"John's Fav\", \"\\Big Air\\]}";
You are missing closing quotes after Big Air. Also, not sure if those backslash are supposed to be there around Big Air but definitely the missing closing quotes would seem to be the issue
There was an issue with the json not being formatted correctly and method was a PUT instead of POST. See working code below.
public static void CreateNewProduct(string token, string Url)
{
Uri shopUri = new Uri(Url);
HttpWebRequest GETRequest = (HttpWebRequest)WebRequest.Create(shopUri);
GETRequest.ContentType = "application/json";
GETRequest.Headers.Add("X-Shopify-Access-Token", token);
GETRequest.PreAuthenticate = true;
GETRequest.Method = "POST";
using (var streamWriter = new StreamWriter(GETRequest.GetRequestStream()))
{
string json = "{\"product\": { \"title\": \"Burton Custom Freestyle 151\", \"body_html\": \"<strong>Good snowboard!</strong>\", \"vendor\": \"Burton\", \"product_type\": \"Snowboard\"} }";
streamWriter.Write(json);
streamWriter.Flush();
}
HttpWebResponse GETResponse = (HttpWebResponse)GETRequest.GetResponse();
var encoding = ASCIIEncoding.ASCII;
using (var reader = new System.IO.StreamReader(GETResponse.GetResponseStream(), encoding))
{
string responseText = reader.ReadToEnd();
Debug.WriteLine("Response Text: " + responseText);
}
GETResponse.Close();
}
I am trying to convert voice to text using Google Speech API. I have a sample code below. It was working fine, it stopped working suddenly and now it always throws the error - 400 bad request. I am using GOOGLE_SPEECH_KEY for authentication without OAuth2 token.
Not sure what exactly I'm missing. Do I need to create OAuth authentication or do I need to modify any console settings in google portal or need to modify the code itself ? Please help!
I used all the below api's and same 400 error:
1. url = "https://speech.googleapis.com/v1beta1/speech:syncrecognize?key=" + ACCESS_GOOGLE_SPEECH_KEY;
2. url = "https://speech.googleapis.com/v1/speech:recognize?key=" + ACCESS_GOOGLE_SPEECH_KEY;
3. url = "https://speech.googleapis.com/v1p1beta1/speech:recognize?key=" + ACCESS_GOOGLE_SPEECH_KEY;
public static string GoogleSpeechToTextApi(string flacUrl)
{
string pTranscriptText = "None", pTranscriptConfidence = "";
string appendText = "";
try
{
// Stream responseStream = imageResponse.GetResponseStream();
if (flacUrl != null)
{
string blobURI = flacUrl;
WebClient myWebClient = new WebClient();
Stream fileStream = myWebClient.OpenRead(blobURI);
byte[] BA_AudioFile = null;
using (var stream2 = new MemoryStream())
{
fileStream.CopyTo(stream2);
stream2.SetLength(stream2.Length);
stream2.Read(stream2.GetBuffer(), 0, (int)stream2.Length);
BA_AudioFile = stream2.GetBuffer();
}
string audioInput = Convert.ToBase64String(BA_AudioFile);
Config config = new Config();
config.encoding = "flac";
config.languageCode = "en";
config.sampleRate = "8000";
Audio audio = new Audio();
audio.content = audioInput;
JsonRequest request = new JsonRequest();
request.config = config;
request.audio = audio;
string json = JsonConvert.SerializeObject(request);
string url = "https://speech.googleapis.com/v1beta1/speech:syncrecognize?key=" + ACCESS_GOOGLE_SPEECH_KEY; // original api url
//url = "https://speech.googleapis.com/v1/speech:recognize?key=" + ACCESS_GOOGLE_SPEECH_KEY; // tested with this
//url = "https://speech.googleapis.com/v1p1beta1/speech:recognize?key=" + ACCESS_GOOGLE_SPEECH_KEY; // tested with this
WebRequest webRequest = WebRequest.Create(url);
webRequest.Method = "POST";
byte[] byteArray = Encoding.UTF8.GetBytes(json);
webRequest.ContentLength = byteArray.Length;
Stream dataStream = webRequest.GetRequestStream();
dataStream.Write(byteArray, 0, byteArray.Length);
dataStream.Close();
WebResponse response = webRequest.GetResponse();
dataStream = response.GetResponseStream();
StreamReader reader = new StreamReader(dataStream);
string responseFromServer = reader.ReadToEnd();
RootObject ro = JsonConvert.DeserializeObject<RootObject>(responseFromServer);
dynamic JsonArray = JsonConvert.DeserializeObject(responseFromServer);
var jsonResult = JsonArray["results"];
foreach (var item in jsonResult)
{
appendText += item.alternatives[0].transcript;
}
}
return appendText;
}
catch (Exception ex)
{
return appendText = "Error";
}
}
}
}
Error 400 means that your request is not correct. You can try encoding = linear16, audioChannelCount = 2 and sampleRateHertz = 16000 with file wav.
Btw, you can pass your key in header request instead in your url
Javacode here:
function sendTextMessage(sender, text) {
messageData = {
text:text
}
request({
url: 'https://graph.facebook.com/v2.6/me/messages',
qs: {access_token:token},
method: 'POST',
json: {
recipient: {id:sender},
message: messageData,
}
}, function(error, response, body) {
if (error) {
console.log('Error sending message: ', error);
} else if (response.body.error) {
console.log('Error: ', response.body.error);
}
});
}
And C# code, I want to replace "?access_token=dshfhsfhrthytrghfgbfhnytfht" by code, because the url use type POST. I find out that I can use WebRequest but i don't know how I use WebRequest to add Json data, so I use HttpWebrequest, Http Webrequest can add query string by StringBuilder , but how i Write post data and json? In this code I just Write json data
public void sendTextMessage(string sender, string text) {
string json = "{ recipient: {id:"+sender+ "} , message: {text: \""+text+"\"}";
var request = (HttpWebRequest)WebRequest.Create("https://graph.facebook.com/v2.6/me/messages?access_token=dshfhsfhrthytrghfgbfhnytfht");
request.ContentType = "application/json";
request.Method = "POST";
using (var streamWriter = new StreamWriter(request.GetRequestStream()))
{
streamWriter.Write(json);
streamWriter.Flush();
streamWriter.Close();
}
var httpResponse = (HttpWebResponse)request.GetResponse();
using (var streamReader = new StreamReader(httpResponse.GetResponseStream()))
{
var result = streamReader.ReadToEnd();
}
}
/* Write like this
You must add you variable as postdata
*/
var request = (HttpWebRequest)WebRequest.Create("http://www.example.com/recepticle.aspx");
var postData = "thing1=hello";
postData += "&thing2=world";
var data = Encoding.ASCII.GetBytes(postData);
request.Method = "POST";
request.ContentType = "application/x-www-form-urlencoded";
request.ContentLength = data.Length;
using (var stream = request.GetRequestStream())
{
stream.Write(data, 0, data.Length);
}
var response = (HttpWebResponse)request.GetResponse();
var responseString = new StreamReader(response.GetResponseStream()).ReadToEnd();
I'm trying to get Google APi's access_token using c# and always getting error message invalid_request. There is my code:
var Params = new Dictionary<string, string>();
Params["client_id"] = GoogleApplicationAPI.CLIENT_ID;
Params["client_secret"] = GoogleApplicationAPI.CLIENT_SECRET;
Params["code"] = "4/08Z_Us0a_blkMlXihlixR1579TYu.smV5ucbI8U4VOl05ti8ZT3ZD4CgMcgI";
Params["redirect_uri"] = GoogleApplicationAPI.RETURN_URL;
Params["grant_type"] = "authorization_code";
var RequestData = "";
foreach (var Item in Params)
{
RequestData += Item.Key + "=" + HttpUtility.UrlEncode(Item.Value) + "&";
}
string Url = "https://accounts.google.com/o/oauth2/token";
var request = (HttpWebRequest) WebRequest.Create(Url);
request.Method = HttpMethod.Post.ToString();
request.ContentType = "application/x-www-form-urlencoded";
var SendData = Encoding.UTF8.GetBytes(RequestData);
try
{
request.ContentLength = SendData.Length;
Stream OutputStream = request.GetRequestStream();
OutputStream.Write(SendData, 0, SendData.Length);
} catch {}
try
{
using (var response = (HttpWebResponse) request.GetResponse())
{
var stream = response.GetResponseStream();
var sr = new StreamReader(stream);
string JSON = sr.ReadToEnd();
}
} catch {}
I use https://developers.google.com/accounts/docs/OAuth2WebServer#offline
Try removing the call to HttpUtility.UrlEncode on each item in the request data. You shouldn't need to do this as the data is not going into the url it's being POSTed. This is no doubt diluting the information being sent which is resulting in your Invalid Request response.