Loading model in tensorflowjs from string - javascript

I have a json string representing a model stored in a js variable. I created it using a gui that generates this json. I would like to load it to tensorflow using tf.loadModel, but the API only accepts url or localstorage. Is there any way to do it directly from string?

Unfortunately Tensorflow.js doesn't provide any way to do this currently.
However, if you need to do it with a string, a possible workaround is to save the string directly to localStorage and retrieve it from there with the URI.
Something like this (untested):
var modelJson = { ... }
localStorage.setItem('model', JSON.stringify(modelJson))
const model = await tf.loadModel('localstorage://model');

Related

JAX-RS JSON object to JavaScript

I am new to JAX-RS and trying to build a simple website interface.
So I have written a function returning a JSON object
like this:
#GET
#Path("/mypath")
#Produces (Mediatype.APPLICATION_JSON)
public String returnJson() {
String json = //.... fill String
return json;
}
which works well when browsing to this path.
On the other hand I have a UI page like this:
#GET
Produces(MediaType.TEXT_HTML)
public InputStream viewUI() throws FileNotFoundException {
File page = new File("page.html");
return new FileInputStream(page);
}
which works also.
Next thing I want to do is filling a dropdown list in my page.html with JavaScript, which also should not be a problem.
But I dont know how to get the JSON object to the JavaScript array (in page.html).
First of all, when using jaxrs, you don't need to convert objects to json. This is done automatically by jaxrs. Your method should return an object. As you asking to convert json into array, I assume, your method should return a List. Regarding of how to call and consume results from the rest service, as per Luts Horn comment, you need to use some sort of client side library, for example jquery.
You can look here http://www.tutorialspoint.com/jquery/jquery-ajax.htm

Better way to de/serialize an Thrift object from/to JSON using the pure Javascript library?

I have a web server returning an thrift object serialized used the JSON protocol to a client html page using the pure Javascript Thrift library (thrift.js).
The server for example:
from MyThriftFile.ttypes import ThriftClass
from thrift import TSerialization
from thrift.protocol import TJSONProtocol
thrift_obj = new ThriftClass()
result = TSerialization.serialize(
thrift_obj,
protocol_factory=TJSONProtocol.TJSONProtocolFactory())
return result
Now in the C#, Python, Java, and even the node.js Thrift libraries there is some form of this generic TSerialization or TDeserialization utlity and its more or less implemented like so:
def deserialize(base,
buf,
protocol_factory=TBinaryProtocol.TBinaryProtocolFactory()):
transport = TTransport.TMemoryBuffer(buf)
protocol = protocol_factory.getProtocol(transport)
base.read(protocol)
return base
So it gets it data, loads it up into a throw away transport (because we are not going to send this information anywhere), creates a new protocol object for encoding this data, and finally the actual thrift object reads this data to populate itself.
The pure javacript library however seems to lack this functionality. I understand why the client library only support the JSON protocol (web pages don't deal in raw binary data) but why not method for de/serialization from/to JSON?
I made my own method for doing the job but it seems hacky. Anyone have a better trick?
$(document).ready(function() {
$.get("www.mysite.com/thrift_object_i_want/", function(data, status) {
var transport = new Thrift.Transport();
var protocol = new Thrift.Protocol(transport);
// Sets the data we are going to read from.
transport.setRecvBuffer(data);
// This is basically equal to
// rawd = data
rawd = transport.readAll();
// The following is lifited from
// readMessageBegin().
// These params I am setting are private memeber
// vars that protocol needs set in order to read
// data set in setRevBuff()
obj = $.parseJSON(rawd);
protocol.rpos = []
protocol.rstack = []
protocol.rstack.push(obj)
// Now that the protocl has been hacked to function
// populate our object from it
tc = new ThriftClass();
tc.read(protocol);
// u is now a js object equal to the python object
});
});
I haven't tried your code but I assume it is working.
It seems correct and is essentially what the TSerializer et al classes do in those other languages. Granted, it could be wrapped in a more friendly way for the vanilla JS library.
The only thing that I might recommend to make it less "hacky" would be to just create a Thrift service method that returns the object(s) you need... then the serialization/deserialization logic will be automatically wrapped up nicely for you in the generated service client.

Read JSON String Shown In URL Using Javascript

i am trying to create a simple web app that gets the latitude and longitude stored in a JSON string and uses them to place markers on a google map. Currently, I have a program on a server which retrieves a JSON string with data when a URL is entered into a web browser. The JSON string produced is as follows:-
{"employees":[{"email":"bones93#hotmail.co.uk","lat":"53","lon":"-3","alt":"0","date":"unknown","time":"unknown"},{"email":"unknown","lat":"0","lon":"0","alt":"0","date":"unknown","time":"unknown"},{"email":"unknown","lat":"0","lon":"0","alt":"0","date":"unknown","time":"unknown"}]}
What method could i use in JavaScript that would allow me to get the JSON string that is produced?
P.S I know I will need to parse the text afterwards to make a JSON Object, this is something that can be done afterwards.
Use the Jquery library's get method to request the data from the server. Here is a link to a simple W3 tutorial : http://www.w3schools.com/jquery/ajax_get.asp
Your code will look something like this:
$("button").click(function(){
$.get("/your/server/url",function(data){
var result = JSON.parse(data);
// Process result.employees
});
});
You could use
var x = JSON.parse('{"employees":[{"email":"bones93#hotmail.co.uk","lat":"53","lon":"-3","alt":"0","date":"unknown","time":"unknown"},{"email":"unknown","lat":"0","lon":"0","alt":"0","date":"unknown","time":"unknown"},{"email":"unknown","lat":"0","lon":"0","alt":"0","date":"unknown","time":"unknown"}]}');
and then access it with:
x["employees"][0]["lat"];
try this for normal strings:
JSON.parse(str)
or if you're using AJAX to get that Json you can use as following:
$.get(..,'json')
OR
$.post(..,'json')

JSON in Google Apps Script

I am trying to validate a webhook with Podio (https://developers.podio.com/doc/hooks/validate-hook-verificated-215241) using google apps script.
Currently I have the following script successfully writing data to a document (after the Podio Post is activated):
function doPost(l) {
var doc = DocumentApp.openById('1to3-JzhE27-LK0Zw7hEsdYgiSd7xQq7jjp13m6YwRh0');
var jstring = Utilities.jsonStringify(l);
doc.appendParagraph(jstring);
}
With the data appearing as follows:
{"queryString":null,"parameter":{"hook_id":"38035","code":"a92e06a2","type":"hook.verify"},"contextPath":"","parameters":{"hook_id":["38035"],"code":["a92e06a2"],"type":["hook.verify"]},"contentLength":44}
For some reason, google apps script won't let me take this data and access the properties like this:
jstring.parameter.code;
If I copy the (seemingly) JSON string into a separate script under a new variable, I can then access the data within the JSON.
What am I doing wrong here?
It looks like you have a JavaScript object that you convert to a JSON string, jstring. It is just a string. If you want to access the properties represented in the string, use the original object, l. Ie, l.parameter.code
function doPost(l) {
var doc = DocumentApp.openById('1to3-JzhE27-LK0Zw7hEsdYgiSd7xQq7jjp13m6YwRh0');
var jstring = Utilities.jsonStringify(l);
doc.appendParagraph(jstring);
dosomething(l.parameter.code);
}

How to store CSV with JavaScript?

I'm going to write currency converter with JavaScript. Currency will be updated daily in CSV files. I want to figure out how to get values from CSV and the best (efficient) way to store them in application. Thank you!
A simple way is to do:
<script type="text/javascript" src="conversion_table.js"></script>
<script type="text/javascript" src="converter.js"></script>
The conversion table is just a JavaScript file defining a single object:
var conversion_table =
{
"USD-GBP": 1.2,
:
:
};
It is more efficient to use JavaScript objects instead of having to parse a CSV file whenever your user loads your page.
Use the jQuery-CSV plugin
With jquery-csv, transforming CSV to JavaScript data structure becomes very simple.
Using the data:
val1,"value 2",val3,val4
"val,1",val2,val3,
Do:
var array = $.csv.toArray(csv);
Outputs:
[
["val1","value 2","val3","val4"],
["val,1","val2","val3",""]
]
If you want the entries mapped to key:value pairs, just call the toObjects() function instead.
Using the data:
foo,bar,baz,fuzz
val1,"value 2",val3,val4
"val,1",val2,val3,
Do:
var dict = $.csv.toObjects(csv);
Outputs:
[
{foo:"val1",bar:"value 2",baz:"val3",fuzz:"val4"},
{foo:"val,1",bar:"val2",baz:"val3",fuzz:""}
]
If you need to allow cross-domain requests, this library will also work in Node.js. After the data is converted, assign it to a variable and send a response with the data encoded as 'text/javascript' (Ie JSONP).
Disclaimer: I'm the author of jquery-csv.
I'd suggest using a JQuery plugin to convert your CSV data into an array.
This one seems like it ought to do the trick: http://plugins.jquery.com/project/csv

Categories