Calculate speaker ratio from AWS Transcribe JSON output - json

How can I parse the JSON output from AWS Transcribe and identify the ratio of how much each speaker is speaking within a given conversation?
Below is a program I coded to find the speaker ratio. However, I have been getting many syntax errors regarding the JSON input.
Also, I don't know how I can automatically bring the JSON file output into the program I created below.
Here is the link to the JSON output.
https://drive.google.com/file/d/1CrjgMU2-INrrXqlfYKQeoZ8WndI2BzUF/view?usp=sharing
const json = '{"start_time":"9.44","speaker_label":"spk_0","end_time":"9.665"}';
const obj = JSON.parse(json);
let total_time_0 = 0;
let total_time_1 = 0;
function calculateRatio(num_1, num_2) {
for(num=num_2; num>1; num--) {
if((num_1 % num) == 0 && (num_2 % num) == 0) {
num_1=num_1/num;
num_2=num_2/num;
}
}
var ratio = num_1+":"+num_2;
return ratio;
}
for (let i = 0; i < obj.length; i++) {
if (obj.speaker_label == "spk_0") {
total_time_0 += obj.end_time - obj.start_time;
} else if (speaker_label == 'spk_1') {
total_time_1 += obj.end_time - obj.start_time;
}
}
console.log(calculateRatio(total_time_0, total_time_1));

Related

Google Elevation API - splitting multiple elevation requests

I'm trying to split a big request for elevation into multiple requests to avoid the 1sec/request and 512 coords limit in each request.
The problem I face is that the reply of my requests are not always received in the good order. Is using setInterval reliable enough?
Here is an example of response received in the wrong order that cause a problem (before using setInterval):
https://www.dropbox.com/s/x00jdnprj6w7lga/correctMap.png?dl=0
Here is my latest code:
function getCourseElevationData() {
var path = bikePathCoordinates; //Bunch of lat,long coords
// numberRequestToDo = Math.ceil(path.length/512); //TODO: split request in multiple 512 pack (google quotas)
numberRequestToDo = 2; //Temporary for testing
currentRequestNumber = -1; //will be at 0 on first call to get512Elevation
arrayOfRequest = [];
//1
var ptrStart= 0;
var pathSliced = path.slice(ptrStart, ptrStart+512);
arrayOfRequest.push(pathSliced);
//2
ptrStart += 512;
pathSliced = path.slice(ptrStart, ptrStart+512);
arrayOfRequest.push(pathSliced);
timerElevation = setInterval(request512Elevation, 1000); //1sec
}
//---------------------------------------------------------
function request512Elevation() {
alert("request512Elevation");
// Still has request to be done
if (currentRequestNumber+1 < numberRequestToDo) {
if (!lastRequestElevationFailed) {
currentRequestNumber++;
}
get512Elevation(arrayOfRequest[currentRequestNumber], currentRequestNumber);
}
// All request completed!
else {
clearInterval(timerElevation);
}
}
//------------------------------------------------------------------------------------------------
function get512Elevation(pathSliced, requestNumber) {
alert("get512PointsElevation" + requestNumber);
var locationElevationRequest = {
'locations': pathSliced
}
elevator.getElevationForLocations(locationElevationRequest, function (results, status) {
alert("ResponseReceived for request:" + requestNumber + ", status" + status + " result length:" + results.length);
if (status != google.maps.ElevationStatus.OK) {
lastRequestElevationFailed = true;
return;
}
lastRequestElevationFailed = false;
var elevations = results;
// Extract the elevation samples from the returned results
for (var i = 0; i < results.length; i++) {
elevationPath.push(elevations[i].location);
}
for (var i = 0; i < results.length; i++) {
dataElevation.addRow(['', elevations[i].elevation]);
}
//last reply received? if yes, we can display the elevation graph
if (currentRequestNumber+1 == numberRequestToDo) {
chart.draw(dataElevation, chartOptions);
}
//TODO: how to make sure response are received in correct order (1,2,3)? setInterval reliable enough?
});
}

How to handle blank returned JSON data from an AJAX request in AJAX

I have a $.ajax function that is calling an asp.net Webmethod.
When no data is returned I want to alert the user with a window.
This is the returned JSON string I see in FireBug:
{"d": "[]"}
The following is a snipet of the function -
success: function (msg) {
var data = eval(msg.d);
var i = 0;
var Name;
for (i = 0; i < data.length; i++) {
if (data.length == 0) {
alert('oops no data has been returned sorry.');
} else {
//do the good stuff
}
}
},
Move the if-else statement outside the for loop and the for loop inside the else branch:
if (data.length == 0) {
alert('oops no data has been returned sorry.');
} else {
for (i = 0; i < data.length; i++) {
//do the good stuff
}
}
In your code, the if statement will never be executed if data is empty since the for loop body is never executed (0 < 0 is false).
Other issues:
I recommend to fix your JSON generation process. If msg.d is supposed to contain array, then don't assign it a string. Your JSON should look like
{"d": []}
It seems like you double-encode the data somehow.
If you don't do this, I would at least use JSON.parse instead of eval.
function webMethodCall(){
return $.getJSON('myURL',{/*my data*/}).done(function(msg){
if(!msg || !msg.d.length){
alert('Emptydata!')
}
});
};

How to pass a whole dojox.grid.DataGrid store(items json data) to servlet?

I have a button on page - when clicked, it passes all the data to the servlet that could update each row data. My question is how to pass the whole store to the servlet as json data? Is there any easy way? Thanks
Here is some code I wrote to get the store to an object. Then it can be converted to JSON using dojo.toJson(obj);. I learned about this from the dojotoolkit website originally. (Give credit where credit is due). I realize this code is huge and nasty. When I looked for a better way about a year back I could not find one.
JsonHelper.storeToObject = function(store) {
var object = [];
var index = -1;
store.fetch({
onItem : function(item, request) {
object[++index] = JsonHelper.itemToObject(store, item);
}
});
return object;
};
JsonHelper.itemToObject = function(store, item) {
// store:
// The datastore the item came from.
// item:
// The item in question.
var obj = {};
if (item && store) {
// Determine the attributes we need to process.
var attributes = store.getAttributes(item);
if (attributes && attributes.length > 0) {
var i;
for (i = 0; i < attributes.length; i++) {
var values = store.getValues(item, attributes[i]);
if (values) {
// Handle multivalued and single-valued attributes.
if (values.length > 1) {
var j;
obj[attributes[i]] = [];
for (j = 0; j < values.length; j++) {
var value = values[j];
// Check that the value isn't another item. If
// it is, process it as an item.
if (store.isItem(value)) {
obj[attributes[i]].push(itemToObject(store,
value));
} else {
obj[attributes[i]].push(value);
}
}
} else {
if (store.isItem(values[0])) {
obj[attributes[i]] = itemToObject(store,
values[0]);
} else {
obj[attributes[i]] = values[0];
}
}
}
}
}
}
return obj;
};

Can't find a match

I have a nested arrays with pairs of numbers:
_open = [[8,15], [9,16]];
from which i want to find a match using ArrayUtilities.findMatchIndex but it always returns -1 when looking for an element array. For example:
ArrayUtilities.findMatchIndex(_open, [8, 15])
I'm wondering if it is possible for AS3 to compare arrays, because comparing other types (strings, numbers, etc) just work fine
Here's findMatchIndex():
public static function findMatchIndex(aArray:Array, oElement:Object, ...rest):Number {
var nStartingIndex:Number = 0;
var bPartialMatch:Boolean = false;
if(typeof rest[0] == "number") {
nStartingIndex = rest[0];
}
else if(typeof rest[1] == "number") {
nStartingIndex = rest[1];
}
if(typeof rest[0] == "boolean") {
bPartialMatch = rest[0];
}
var bMatch:Boolean = false;
for(var i:Number = nStartingIndex; i < aArray.length; i++) {
if(bPartialMatch) {
bMatch = (aArray[i].indexOf(oElement) != -1);
}
else {
bMatch = (aArray[i] == oElement);
}
if(bMatch) {
return i;
}
}
return -1;
}
Comparing other types (strings, numbers, etc) works fine, because they are so-called primitives, and are compared by values. Arrays, though, are objects, therefore they are compared by reference. Basically it means that [8,15] != [8,15].
One way around it is replacing this line...
else {
bMatch = (aArray[i] == oElement);
}
... with something like this ...
else {
bMatch = compareElements(aArray[i], oElement);
}
... where compareElements will try to check its arguments' types first, and if they're objects, will compare their values.

Trying to create a function which extracts a URL from an array. JavaScript

So basically I would like to create a function that when alerted, returns the URL from an array (in this case the array is declared as 'websites'). The function has two parameters 'websites' and 'searchTerm'.
I'm struggling to make the function behave, so that when i type yahoo or google or bing in the searchTerm parameter for the function; I want it to return the corresponding URL.
Any help or support would be greatly appreciated.
Sorry if I have not made myself clear in my explanation, if this is the case, let me know and I will try and be clearer in my explanation.
Thanks in advance!
Try something more like:
var websites = {google: 'www.google.com', yahoo: 'www.yahoo.com'};
function filterURL(websites,searchTerm)
{
return websites[searchTerm] || 'www.defaultsearchwebstirehere.com';
}
** Update following comment **
Build up your websites object like so (where input is your array of key values seperated by pipe characters):
var websites = {};
for (var i = 0; i < input.length; i++) {
var siteToSearchTerm = input[i].split('|');
websites[siteToSearchTerm[1]] = siteToSearchTerm[0];
}
Here is how:
var websites = ["www.google.com|Google" , "www.yahoo.com|Yahoo" , "www.bing.com|Bing"];
function filterURL(websites,searchTerm)
{
for (var i = 0; i < websites.length; i++) {
if (websites[i].split('|')[1] === searchTerm) {
return websites[i].split('|')[0];
}
}
}
Working Example
You can also validate and improve function:
function filterURL(websites,searchTerm)
{
if (typeof websites != 'Array' || ! searchTerm) return false;
for (var i = 0; i < websites.length; i++) {
if (websites[i].split('|')[1] === searchTerm) {
return websites[i].split('|')[0];
}
}
return false;
}
Why not just use an object?
var websites = {
Google: 'www.google.com',
Yahoo: 'www.yahoo.com'
};
function filterURL(sites, searchTerm) {
if (sites[searchTerm]) {
return sites[searchTerm];
} else {
// What do you want to do when it can't be found?
}
}
alert(filterURL(websites, 'Google')); // alerts 'www.google.com'
You should really be using a hash-table like structure so that you don't have to search through the whole array every time. Something like this:
var websites = {
"Google": "www.google.com",
"Yahoo": "www.yahoo.com",
"Bing": "www.bing.com"
};
function filterURL(websites, searchTerm) {
if (websites[searchTerm] !== undefined)
return websites[searchTerm];
else
return null;
}
I'm not sure why you want to use an array for this, as what you're really doing fits a key-value pair better; however, here's how I'd do it:
function filterURL(websites, searchTerm) {
var i = 0,
parts;
for (i = 0; i < websites.length; i++) {
parts = websites[i].split("|");
if (parts[1].toLowerCase() === searchTerm) {
return parts[0];
}
}
}
But consider if you used a proper JavaScript Object instead:
var websites = {
Google: "www.google.com",
Yahoo: "www.yahoo.com",
Bing: "www.bing.com"
}
// Now it's much simpler:
function filterURL(websites, searchTerm) {
// key has first letter capitalized…
return websites[searchTerm.charAt(0).toUpperCase() + searchTerm.slice(1).toLowerCase()];
}