I am making an language app that needs audio as well as visual translations. I thought of using Google Translate API, but according to this SO post, it appears that "The explanation is that Google restricts the usage of this service."
But this SO post, Google Text-To-Speech API, says I can use tl and q params, like http://translate.google.com/translate_tts?tl=zh-CN&q=Hello to return audio. This gives me a weird transliteration in Chinese of "Hello", which says "Ha Low" instead of "Ni Hao".
The user also states that "it will automatically generate a wav file which you can easily get with an HTTP request". When I GET using jsonp (need to use this because $.get() or non-jsonp requests have origin blocked) I get the following unreadable error:
Code:
var theApp = angular.module('myApp', []);
theApp.controller('APICtrl', ['$scope', '$http',
function($scope, $http) {
var httpRequest = "http://translate.google.com/translate_tts?tl=" + "zh-CN" + "&q=" + "Hello";
$http.jsonp(httpRequest)
.success(function(data) {
console.log(data);
}
);
}
]);
So my question is... is there a standard endpoint for Google translate API to access audio files? If not, what is a good way to do this that works?
This is a late response...
I would suggest using Jquery (or vanilla JavaScript) to do this instead of putting it in your app's controller. The URL you provided is fine, but now you need to set the Referer and User-Agent headers before you make the request.
You can use Jquery.get() to download the mp3 from Google's TTS API (you have to set the headers!). Then, you can create an HTML5 Audio object out of the data returned by Jquery in the #success method, and play that.
The response size for one-word queries like Hello are around 2-3kb, plenty small enough. Google's API is also incredibly fast, so with those two factors combined I wouldn't worry about performance at all. Keep in mind that the browser will also cache the audio file, so any subsequent 'hovering over words' will use the cached version and not send another request.
Related
I am new to API usage. I have properly managed to utilize Google Page Insights V.5 API through javascript code, but I cannot for the life of me succeed in doing so for GTMetrix. It seems the only information relating to GTMetrix API & Javascript is a link to the RapidApi website. I simply wish to achieve the same simple retrieval of data from GTMetrix as I have from Google. Is this possible?
Am I simply structuring my request incorrectly when I set it as:
https://gtmetrix.com/api/0.1/?login-user=myemail#email.com&login-pass=MyRanDomApIKeY&location=2&url=https://sitetotest.com
Because when I set my Google Page Insights Request URL as the following it works.
https://www.googleapis.com/pagespeedonline/v5/runPagespeed?url=https://websitetotest.com&category=performance&strategy=desktop&key=MyRanDomApIKeY
The below code works for Google Page Insights and I am even able to retrieve JSON data in a browser window with a URL such as:
<div id="firstmetric"></div>
<br>
<div id="domSize"></div>
<button>Click Me</button>
<script>
$('button').click(function(){
var baseUrl = "https://www.googleapis.com/pagespeedonline/v5/runPagespeed?url=";
var fieldUrl = "https://websitetotest.com";
var trailing = "&category=performance&strategy=desktop&key=MyRanDomApIKeY";
$.getJSON(baseUrl + fieldUrl + trailing, function(data){
console.log(data);
var item = data.lighthouseResult.categories.performance.auditRefs[0].weight;
var domSize = data.lighthouseResult.audits['dom-size'].displayValue;
$("#firstmetric").html( item );
$("#domSize").html( domSize );
});
});
I truly need it spelled out for me because anything less is going to lead me to ask follow up questions and put us in a tail spin. :/
As a newbie, JSFiddle has been a life saving resource for testing and trying, breaking, and building in my learning process. If it wouldn't be too much to ask for, a fiddle would help me get my brain around things.
The parameters that you are using: login-user and login-pass refer to HTTP authentication on the page you are analyzing (as in, GTmetrix will pass these parameters on your analysis) not your GTmetrix API credentials.
The authentication used for the GTmetrix API is your e-mail for the username and your API key as the password, as pointed out by the API docs.
Another thing to keep in mind is that GTmetrix will not allow you to do API calls through your web application frontend, since they disallow CORS requests. If you do it through your Web application on a normal website, you would be exposing your GTmetrix API key, which is probably not a good idea.
So, you would then do it through your backend code. For example if done through Node JavaScript:
fetch("https://gtmetrix.com/api/0.1/locations", {
headers: new Headers({
"Authorization": 'Basic ' + btoa("[YOUR E-MAIL]" + ":" +"[YOUR API KEY]"),
}),
}).then(res => res.json())
.then(response => console.log(response));
would print me the array of locations.
Note that whichever backend code you choose, you need to add the basic authorization header request for you API call and encode it properly (that is what the btoa function call does).
I'm working on an AngularJS enhancement of a Wordpress website. I'm using the WP-API (v2) plugin to create custom endpoints and then consuming them on front end using Angular $http service.
Here's a code sample of the angular request:
function getData(slug) {
return $http.get(endpoints.specialData.replace(':slug', slug)).then(function (response) {
var data = response.data || {};
return data;
}, function (response) {
return response;
});
}
When I visit the page making this call I can see the time for this XHR (via Chrome dev tools) is about 4.5 seconds.
If I hit the same endpoint URL directly in the browser it returns the JSON result in 900ms. The endpoint URL is defined using a relative path (/path/relative/from/site/root) rather than the full http:// path, if that makes any difference.
Any ideas why it would take so much longer via Angular?
Debugging perf is quite particular, so all I can do is help you on your journey. You might want to take a look at troubleshooting the request using the Network tab in DevTools, and figure out what exactly is causing the slowdown. Read this article fully from Google: https://developers.google.com/web/tools/chrome-devtools/profile/evaluate-performance/timeline-tool
TL;DR If you see lot of green in your request, it's most likely a server issue, if it's blue, you're sending over too many bytes and need to optimize your JSON.
From there you can start narrowing it down.
Good luck!
I am trying to use Twitter Pin-based authorization in my Google Apps Script to eventually send tweets on behalf of other uses.
I freely admit that I don't relay know what I'm doing but I have read a lot of info on the internet and feel I have tried everything.
My current Google Apps Script JavaScript code:
var method = 'post';
var url = 'https://api.twitter.com/oauth/request_token';
var consumerKey = '[my consumer key]';
var ticks = '1422745454';
var nonce = '6826266';
var options = {
'method': method,
'oauth_callback': 'oob',
'oauth_consumer_key': consumerKey,
'oauth_nonce': nonce,
'oauth_signature': 'cIFeptE5HjHp7xrp%2BZt9xFhHox4%3D',
'oauth_signature_method': 'HMAC-SHA1',
'oauth_timestamp': ticks,
'oauth_version': '1.0'
};
var response = UrlFetchApp.fetch(url, options);
For testing I set the ticks just before each test run to the value here
The nonce is a random number between 111111 and 9999999 which is regenerated before each test run.
The oauth signature I have been generating with some c# code lifted from the linq2twitter project
I suspect the problem is the signature. I have read the twitter documentation on creating a signature and I think the C# code is doing it correctly but I am not sure.
The problem is that whatever I try I always get this error:
"Request failed for https://api.twitter.com/oauth/request_token returned code 401. Truncated server response: Failed to validate oauth signature and token (use muteHttpExceptions option to examine full response)"
I have been trying to find an example of Twitter Pin-based authorization in a Google Apps Script but have so far not found anything.
My attempts to translate examples in C#, PHP, etc. have also failed.
Please help.
Apps Script provides an Oauth API that works with UrlFetchApp, they even use twitter in their examples. Work with those if at all possible, troubleshooting signature generation is a real hassle.
https://developers.google.com/apps-script/reference/url-fetch/o-auth-config
https://developers.google.com/apps-script/articles/twitter_tutorial
If you absolutely must do it from scratch, the best approach is to get requests working with an existing library (like the c# one you mention), then work on getting your apps script to generate the exact same request.
I get the sense that is what you are doing now, so it may just be a matter of base64 encoding your Signature in the outgoing request:
https://developers.google.com/apps-script/reference/utilities/utilities#base64Encode(String)
Ultimately, it's very difficult to do the whole Oauth process manually in Apps Script. When I tried something like this from scratch about a year ago I ultimately gave up and used a Python application deployed to Google App Engine instead. I submit requests from Apps Script to the App Engine application, and the App Engine application handles Oauth and relays my requests on to the external service, before returning requests to my Apps Script. This approach comes with complications of it's own.
I'm building a prototype Angular app, using Parse as a temporary RESTful back end (Until the real restful backend is completed)
I've setup a Factory with $resource() but I'm constantly getting a 401 unauthorized.
Right now my factory looks like this (APPIDKEY AND APIKEY are redacted of course)
app.factory('eventFactory', ['$resource', function($resource){
return $resource('https://api.parse.com/1/classes/Events',{},
{headers:{"X-Parse-Application-Id": "APPIDKEY",
"X-Parse-REST-API-Key": "APIKEY"}});
}
]);
I've also tried writing the $resrouce like this.
$resource('https://myAppID:javascript-key=myJavaScriptKey#api.parse.com/1/classes/Events');
But that also returns a 401. however if I copy and paste that URL into my browser the screen prints out all the objects in the request.
I've done extensive googling and read the $resource docs many times but I still can't quite figure this out. I'm thinking it has to do with Cross-Origin policy but the parse documentation says
'For Javascript usage, the Parse Cloud supports cross-origin resource sharing, so that you can use these headers in conjunction with XMLHttpRequest.' So I'm kinda stumped.
Any help is much appreciated. Thanks!
Adding these two lines inside my module.config function fixed it.
$httpProvider.defaults.headers.common['X-Parse-Application-Id']="APPIDKEY"
$httpProvider.defaults.headers.common['X-Parse-REST-API-Key']="RESTAPIKEY"
where APPIDKEY and RESTAPIKEY equal the keys provided from Parse.com
I am working on html & js in which i display yahoo finance stock in table format. The data get in csv. I want js directly read data from url
The url is http://ichart.finance.yahoo.com/table.csv?s=RIL.BO
The code i try which i get from stackoverflow is working in localhost url.
var txtFile = new XMLHttpRequest();
txtFile.open("GET", "http://ichart.finance.yahoo.com/table.csv?s=RIL.BO", true);
txtFile.onreadystatechange = function() {
if (txtFile.readyState === 4) { // Makes sure the document is ready to parse.
if (txtFile.status === 200) { // Makes sure it's found the file.
allText = txtFile.responseText;
lines = txtFile.responseText.split("\n"); // Will separate each line into an array
alert(allText);
}
}
}
Thanks
In order to get around the Cross Domain request restrictions put in place by the Same Origin Policy, you need an endpoint that allows you to do a JSONP request or that has enabled CORS. Unfortunately, the Yahoo! Finance endpoint has neither.
So, as James mentioned, you ned a middle man.
Usually, my recommendation for this is to use YQL, which allows you to quickly and easily build a server that sits between you and the finance site. In fact, they already have a Yahoo! Finance endpoint for exactly the data you're trying to get: link
However, as that can be unreliable, I also have a website scraper that I've used in various projects. It's hosted on Heroku and allows you to fetch almost any content from any site. I don't recommend using it for high volume projects, but for occaisional data fetches it's great. In your case, you would use it like this:
http://websitescraper.herokuapp.com/?url=http://ichart.finance.yahoo.com/table.csv?s=RIL.BO&callback=jsCallback
Edit: ichart.finance.yahoo.com has been deprecated, so this fails. Keeping it here for reference
Now that you have that out of the way, I recommend using jQuery and the csv-to-array plugin:
jQuery.getJSON('http://websitescraper.herokuapp.com/?url=http://ichart.finance.yahoo.com/table.csv?s=RIL.BO&callback=?', function (csvdata) {
console.log(csvdata.csvToArray());
});
Also, if you want to launch your own middle man, you can use the website-scraper that I've built. The source code is on GitHub and it's released under the MIT license.
You are trying to do a cross domain request so its being blocked.
You will need to write a server side script to fetch the data for you.