Google speech to text API in C# stopped working - c#

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

Related

WEB API C# REPONSE HANGS (HttpWebResponse)http.GetResponse()

Am doing an WEB API .net 4.62 that /Token with username password and grant_type to get access token once its generated i woul like to get it value of access_token.This does not happen but when i take the same code to a windows form aplication I am able to get it what could be wrong. It hangs on using (HttpWebResponse response = (HttpWebResponse)http.GetResponse())
try
{
string myParameters = "username=value1&password=value2&grant_type=password";
string baseAddress = "http://localhost:50128/token";
var http = (HttpWebRequest)WebRequest.Create(new Uri(baseAddress));
http.Accept = "application/x-www-form-urlencoded";
http.ContentType = "application/x-www-form-urlencoded";
http.Method = "POST";
string parsedContent = myParameters;
ASCIIEncoding encoding = new ASCIIEncoding();
Byte[] bytes = encoding.GetBytes(parsedContent);
Stream newStream = http.GetRequestStream();
newStream.Write(bytes, 0, bytes.Length);
newStream.Close();
http.ServicePoint.Expect100Continue = false;
http.ProtocolVersion = HttpVersion.Version11;
http.Timeout = 2000;
using (HttpWebResponse response = (HttpWebResponse)http.GetResponse())
{
var stream = response.GetResponseStream();
var sr = new StreamReader(stream);
var content = sr.ReadToEnd();
JObject json = JObject.Parse(content);
var message = json.SelectToken("access_token").ToString();
Console.Write(message);
}
}
catch (Exception ex)
{
//Handle the exceptions that could appear
}
change the using block like this and also convert your function to "async".
using (HttpWebResponse response = (HttpWebResponse)await Task.Factory.FromAsync(http.BeginGetResponse, http.EndGetResponse, null).ConfigureAwait(false))
let me know if it works.

UnSupported Media Type when Calling REST Web Service

I am calling a REST web service which has given me this documentation
HTTP Method: POST
Path: /commit/{path}/add-node
Response Status 200, 302, 403, 404, 409, 503
Form Parameters
- name : attribute name
- message : commit message
Based on this documentation. I have written following C# code.
string restUrl = webServiceurl + "/commit/" + path + "/add-node";
restUrl = restUrl + "?name=" + nodeName + "&message=" + commitMessage;
HttpWebRequest request = (HttpWebRequest)WebRequest.Create(restUrl);
request.Method = "POST";
request.ContentType = #"application/json";
using (WebResponse response = request.GetResponse()) {
using (StreamReader reader = new StreamReader(response.GetResponseStream())) {
output = reader.ReadToEnd();
}
}
I also tried
string restUrl = webServiceurl + "/commit/" + path + "/add-node";
HttpWebRequest request = (HttpWebRequest)WebRequest.Create(restUrl);
request.Method = "POST";
request.ContentType = #"application/json";
var param = new { name = nodeName, message = commitMessage };
Stream reqStream = null;
string output = null;
try {
byte[] buffer = Encoding.GetEncoding("UTF-8").GetBytes(
JsonConvert.SerializeObject(param)
);
request.ContentLength = buffer.Length;
reqStream = request.GetRequestStream();
reqStream.Write(buffer, 0, buffer.Length);
using (WebResponse response = request.GetResponse()) {
using (StreamReader reader = new StreamReader(response.GetResponseStream())) {
output = reader.ReadToEnd();
}
}
} catch (Exception ex) {
.....
}
Unfortunately in both cases, I get 415 Unsupported Media Type in both cases. What is wrong with my code?
The web Services is a REST based web service written in Java.
According to this forum post the ContentType property may not be supported from the Java web service. Are you sure it accepts application/json?

Google Api get token request returns invalid_request

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.

How to upload video on Dailymotion with c# ?? Is somebody has a complete code?

I wish upload a video on dailymotion with c# code , but dailymotion doesn't provide c# code to upload video with c#.
I search on dailymotion documentation api and i found this not explicit curl code :
curl -F 'access_token=...' \
-F 'url=http://upload-02.dailymotion.com/files/5ccb48b8e8aef3fcb8959739f993e1b9.3gp' \
https://api.dailymotion.com/me/videos
and i tryed to transpose but it's not working:
string contentFile = "c:\name_of_my_video_file.flv";
byte[] byteArray = Encoding.ASCII.GetBytes(contentFile);
MemoryStream fs = new MemoryStream(byteArray);
// Provide the WebPermission Credintials
// Create a request using a URL that can receive a post.
string uri = "https://api.dailymotion.com/me/videos";
WebRequest request = WebRequest.Create(uri);
// Set the Method property of the request to POST.
request.Method = "POST";
request.Credentials = new NetworkCredential("logindailymotion","passworddailymotion");
// Create POST data and convert it to a byte array.
string postData = "access_token=my_api_key&url=http://upload-02.dailymotion.com/files/name_of_my_video_file.flv";
byte[] byteArray = Encoding.UTF8.GetBytes(postData);
// Set the ContentType property of the WebRequest.
request.ContentType = "application/x-www-form-urlencoded";
// Set the ContentLength property of the WebRequest.
request.ContentLength = byteArray.Length;
// Get the request stream.
// Notify the server about the size of the uploaded file
request.ContentLength = fs.Length;
// The buffer size is set to 2kb
int buffLength = 2048;
byte[] buff = new byte[buffLength];
int contentLen;
// Opens a file stream (System.IO.FileStream) to read the file to be uploaded
//FileStream fs = fileInf.OpenRead();
try
{
// Stream to which the file to be upload is written
Stream strm = request.GetRequestStream();
// Read from the file stream 2kb at a time
contentLen = fs.Read(buff, 0, buffLength);
// Till Stream content ends
while (contentLen != 0)
{
// Write Content from the file stream to the FTP Upload Stream
strm.Write(buff, 0, contentLen);
contentLen = fs.Read(buff, 0, buffLength);
}
// Close the file stream and the Request Stream
strm.Close();
fs.Close();
}
catch (Exception ex)
{
throw ex;
}
}
Is there a better documentation for c# code ?
Is somebody has the correct code ?
I created a complete example to answer your question and upload a video. It is available on GitHub now.
Edit: I used API information available explaining how to do their OAuth Authentication and Video Publishing.
Here is all the code except for the objects that are deserialized from JSON:
Code
static void Main(string[] args)
{
var accessToken = GetAccessToken();
Authorize(accessToken);
Console.WriteLine("Access token is " + accessToken);
var fileToUpload = #"C:\Program Files\Common Files\Microsoft Shared\ink\en-US\join.avi";
Console.WriteLine("File to upload is " + fileToUpload);
var uploadUrl = GetFileUploadUrl(accessToken);
Console.WriteLine("Posting to " + uploadUrl);
var response = GetFileUploadResponse(fileToUpload, accessToken, uploadUrl);
Console.WriteLine("Response:\n");
Console.WriteLine(response + "\n");
Console.WriteLine("Publishing video.\n");
var uploadedResponse = PublishVideo(response, accessToken);
Console.WriteLine(uploadedResponse);
Console.WriteLine("Done. Press enter to exit.");
Console.ReadLine();
}
private static UploadResponse GetFileUploadResponse(string fileToUpload, string accessToken, string uploadUrl)
{
var client = new WebClient();
client.Headers.Add("Authorization", "OAuth " + accessToken);
var responseBytes = client.UploadFile(uploadUrl, fileToUpload);
var responseString = Encoding.UTF8.GetString(responseBytes);
var response = JsonConvert.DeserializeObject<UploadResponse>(responseString);
return response;
}
private static UploadedResponse PublishVideo(UploadResponse uploadResponse, string accessToken)
{
var request = WebRequest.Create("https://api.dailymotion.com/me/videos?url=" + HttpUtility.UrlEncode(uploadResponse.url));
request.Method = "POST";
request.ContentType = "application/x-www-form-urlencoded";
request.Headers.Add("Authorization", "OAuth " + accessToken);
var requestString = String.Format("title={0}&tags={1}&channel={2}&published={3}",
HttpUtility.UrlEncode("some title"),
HttpUtility.UrlEncode("tag1"),
HttpUtility.UrlEncode("news"),
HttpUtility.UrlEncode("true"));
var requestBytes = Encoding.UTF8.GetBytes(requestString);
var requestStream = request.GetRequestStream();
requestStream.Write(requestBytes, 0, requestBytes.Length);
var response = request.GetResponse();
var responseStream = response.GetResponseStream();
string responseString;
using (var reader = new StreamReader(responseStream))
{
responseString = reader.ReadToEnd();
}
var uploadedResponse = JsonConvert.DeserializeObject<UploadedResponse>(responseString);
return uploadedResponse;
}
private static string GetAccessToken()
{
var request = WebRequest.Create("https://api.dailymotion.com/oauth/token");
request.Method = "POST";
request.ContentType = "application/x-www-form-urlencoded";
var requestString = String.Format("grant_type=password&client_id={0}&client_secret={1}&username={2}&password={3}",
HttpUtility.UrlEncode(SettingsProvider.Key),
HttpUtility.UrlEncode(SettingsProvider.Secret),
HttpUtility.UrlEncode(SettingsProvider.Username),
HttpUtility.UrlEncode(SettingsProvider.Password));
var requestBytes = Encoding.UTF8.GetBytes(requestString);
var requestStream = request.GetRequestStream();
requestStream.Write(requestBytes, 0, requestBytes.Length);
var response = request.GetResponse();
var responseStream = response.GetResponseStream();
string responseString;
using (var reader = new StreamReader(responseStream))
{
responseString = reader.ReadToEnd();
}
var oauthResponse = JsonConvert.DeserializeObject<OAuthResponse>(responseString);
return oauthResponse.access_token;
}
private static void Authorize(string accessToken)
{
var authorizeUrl = String.Format("https://api.dailymotion.com/oauth/authorize?response_type=code&client_id={0}&scope=read+write+manage_videos+delete&redirect_uri={1}",
HttpUtility.UrlEncode(SettingsProvider.Key),
HttpUtility.UrlEncode(SettingsProvider.CallbackUrl));
Console.WriteLine("We need permissions to upload. Press enter to open web browser.");
Console.ReadLine();
Process.Start(authorizeUrl);
var client = new WebClient();
client.Headers.Add("Authorization", "OAuth " + accessToken);
Console.WriteLine("Press enter once you have authenticated and been redirected to your callback URL");
Console.ReadLine();
}
private static string GetFileUploadUrl(string accessToken)
{
var client = new WebClient();
client.Headers.Add("Authorization", "OAuth " + accessToken);
var urlResponse = client.DownloadString("https://api.dailymotion.com/file/upload");
var response = JsonConvert.DeserializeObject<UploadRequestResponse>(urlResponse).upload_url;
return response;
}
Again, I put it on GitHub.

Uploading to imgur.com

Imgur is a image uploading website who offers an API to upload
My code looks exactly like the PHP code they provide as an example. however, in their php code they are http_build_query($pvars);
It seems like they are URLEncoding their query before posting it. edit: Note that I have changed to full .NET 3.5 rather then the client profile. This gave me access to system.web so I used httputliity.urlencode(). This made the api return a "fail" with a "no image was sent". If I don't encode then the API returns an "okay" with a link to the picture, however no picture is uploaded (like a blank file).
How can I fix my code to work properly against their API?
Image image = Image.FromFile("C:\\Users\\Affan\\Pictures\\1509310.jpg");
MemoryStream ms = new MemoryStream();
// Convert Image to byte[]
image.Save(ms, System.Drawing.Imaging.ImageFormat.Jpeg);
byte[] imageBytes = ms.ToArray();
WebRequest wb = WebRequest.Create(new Uri("http://imgur.com/api/upload.xml"));
wb.ContentType = "application/x-www-form-urlencoded";
wb.Method = "POST";
wb.Timeout = 10000;
Console.WriteLine(imageBytes.Length);
string parameters = "key=433a1bf4743dd8d7845629b95b5ca1b4&image=" + Convert.ToBase64String(imageBytes);
Console.WriteLine("parameters: " + parameters.Length);
System.Text.UTF8Encoding encoding = new System.Text.UTF8Encoding();
byte[] bytes = encoding.GetBytes(parameters);
// byte[] bytes = Convert.FromBase64String(parameters);
System.IO.Stream os = null;
try { // send the Post
wb.ContentLength = bytes.Length; //Count bytes to send
os = wb.GetRequestStream();
os.Write(bytes, 0, bytes.Length); //Send it
} catch (WebException ex) {
MessageBox.Show(ex.Message, "HttpPost: Request error");
Console.WriteLine(ex.Message);
} finally {
if (os != null) {
// os.Close();
}
}
try { // get the response
WebResponse webResponse = wb.GetResponse();
StreamReader sr = new StreamReader(webResponse.GetResponseStream());
//MessageBox.Show(sr.ReadToEnd().Trim());
Console.WriteLine(sr.ReadToEnd().Trim());
} catch (WebException ex) {
MessageBox.Show(ex.Message, "HttpPost: Response error");
}
I've just uploaded this image
using this code:
using (var w = new WebClient())
{
var values = new NameValueCollection
{
{ "key", "433a1bf4743dd8d7845629b95b5ca1b4" },
{ "image", Convert.ToBase64String(File.ReadAllBytes(#"hello.png")) }
};
byte[] response = w.UploadValues("http://imgur.com/api/upload.xml", values);
Console.WriteLine(XDocument.Load(new MemoryStream(response)));
}
You might want to change your API key now :-)
The output was:
<rsp stat="ok">
<image_hash>IWg2O</image_hash>
<delete_hash>fQAXiR2Fdq</delete_hash>
<original_image>http://i.imgur.com/IWg2O.png</original_image>
<large_thumbnail>http://i.imgur.com/IWg2Ol.jpg</large_thumbnail>
<small_thumbnail>http://i.imgur.com/IWg2Os.jpg</small_thumbnail>
<imgur_page>http://imgur.com/IWg2O</imgur_page>
<delete_page>http://imgur.com/delete/fQAXiR2Fdq</delete_page>
</rsp>
Here's an updated version of dtb's answer for the v3 API using anonymous uploading (you need to register your app at http://api.imgur.com/ to get your client ID):
using (var w = new WebClient())
{
string clientID = "<<INSERT YOUR ID HERE>>";
w.Headers.Add("Authorization", "Client-ID " + clientID);
var values = new NameValueCollection
{
{ "image", Convert.ToBase64String(File.ReadAllBytes(#"hello.png")) }
};
byte[] response = w.UploadValues("https://api.imgur.com/3/upload.xml", values);
Console.WriteLine(XDocument.Load(new MemoryStream(response)));
}
And the response is now like this (see http://api.imgur.com/models/image):
<data success="1" status="200">
<id>SbBGk</id>
<title/>
<description/>
<datetime>1341533193</datetime>
<type>image/jpeg</type>
<animated>false</animated>
<width>2559</width>
<height>1439</height>
<size>521916</size>
<views>1</views>
<bandwidth>521916</bandwidth>
<deletehash>eYZd3NNJHsbreD1</deletehash>
<section/>
<link>http://i.imgur.com/SbBGk.jpg</link>
</data>
I Guess that the dtb solution is deprecated
using (var w = new WebClient())
{
var values = new NameValueCollection
{
{"image", Convert.ToBase64String(imageData)},
{"type", "base64"}
};
w.Headers.Add("Authorization", "Client-ID xxxxxxxxx");
var response = w.UploadValues("https://api.imgur.com/3/image", values);
}
another way to do:
HttpWebRequest request = (HttpWebRequest)WebRequest.Create("https://api.imgur.com/3/image");
request.Headers.Add("Authorization", "Client-ID xxxxxxx");
request.Method = "POST";
ASCIIEncoding enc = new ASCIIEncoding();
string postData = Convert.ToBase64String(imageData);
byte[] bytes = enc.GetBytes(postData);
request.ContentType = "application/x-www-form-urlencoded";
request.ContentLength = bytes.Length;
Stream writer = request.GetRequestStream();
writer.Write(bytes, 0, bytes.Length);
HttpWebResponse response = (HttpWebResponse)request.GetResponse();

Categories

Resources