Giter VIP home page Giter VIP logo

algorithmia-nodejs's Introduction

algorithmia-nodejs

A nodejs library for calling algorithms on Algorithmia.com with partial support for the DataAPI

npm

Getting started

The official Algorithmia nodejs client is available on NPM. Install it for your project by adding algorithmia to your package.json:

npm install --save algorithmia

Set runtime environment variables by creating .env file in the root directory with the following keys


Name Value Purpose
ALGORITHMIA_API_ADDRESS <key for Algorithmia api url> Optional, will default to https://api.algorithmia.com
ALGORITHMIA_DEFAULT_API_KEY <secret key to run Algorithmia api> Required for algorithmia client

Then instantiate an Algorithmia client using your API key environment variables:

const algorithmia = require('algorithmia');

let client: AlgorithmiaClient = algorithmia.getClient(process.env.ALGORITHMIA_DEFAULT_API_KEY);

Now you are ready to call algorithms.

Calling algorithms

The following examples of calling algorithms are organized by type of input/output which vary between algorithms.

Note: a single algorithm may have different input and output types, or accept multiple types of input, so consult the algorithm's description for usage examples specific to that algorithm.

Text input/output

Call an algorithm with text input by passing a string into the pipe method. The returned promise will be called with the response with the Algorithm completes (or when an error occurs). If the algorithm output is text, then the get() method on the response will return a string.

const response = await client.algo("algo://demo/Hello/0.1.1").pipe("HAL 9000");
// -> Hello HAL 9000

JSON input/output

Call an algorithm with JSON input by passing in a native JavaScript type; most of the time this will be an Object or an Array (though Boolean, Number, and Null are possible).

const response = await client.algo("algo://WebPredict/ListAnagrams/0.1.0").pipe(["transformer", "terraforms", "retransform"]);
// -> ["transformer","retransform"]

Binary input/output

Call an algorithm with binary input by passing a Buffer into the pipe method.

var buffer = fs.readFileSync("/path/to/bender.jpg");
const response = await client.algo("opencv/SmartThumbnail").pipe(buffer);
// -> Buffer(...)

Error handling

If an error occurs when calling an algorithm, the response will contain an error field that you can check:

const response = await client.algo('util/whoopsWrongAlgo').pipe('Hello, world!');

Request options

The Algorithmia API exposes parameters to configure algorithm requests including support for changing the timeout of indicating that the API should include stdout in the response. Currently, the node.js client exposes these as query paremeters to the algorithm URI:

client.algo("algo://demo/Hello/0.1.1?timeout=10&stdout=true").pipe("HAL 9000");

Note: stdout=true is only supported if you have access to the algorithm source.

Working with data

The Algorithmia client also provides a way to manage both Algorithmia hosted data and data from Dropbox or S3 accounts that you've connected to you Algorithmia account.

Create directories

Create directories by instantiating a DataDir object and calling create():

let dir: DataDir = Algorithmia.getClient(process.env.ALGORITHMIA_DEFAULT_API_KEY).dir('Insert directory path');
await dir.create('Insert directory path');

Upload files to a directory

Upload files by calling the file method a DataDir object or put on a DataFile object:

let file: DataFile = Algorithmia.getClient(process.env.ALGORITHMIA_DEFAULT_API_KEY).file('Insert file path');
await file.put('Insert your file body');

let dir: DataDir = Algorithmia.getClient(process.env.ALGORITHMIA_DEFAULT_API_KEY).dir('Insert directory path');
let file: DataFile = dir.file('Insert file path');
await dir.put(file.baseName(), 'Insert your file body');

let dir = Algorithmia.getClient(process.env.ALGORITHMIA_DEFAULT_API_KEY).dir('Insert directory path');
await dir.putFile(resolve('Insert local file path'));

Download content from files

Download files by calling get on a DataFile object:

let file: DataFile = Algorithmia.getClient(process.env.ALGORITHMIA_DEFAULT_API_KEY).file('Insert file path');
const response = await file.get();

let dir: DataDir = Algorithmia.getClient(process.env.ALGORITHMIA_DEFAULT_API_KEY).dir('Insert directory path');
const response = await dir.get();

Delete files and directories

Delete files by calling delete on their respective DataFile or DataDir object. When deleting directories, you may optionally specify a force argument that indicates whether or not a directory should be deleted if it contains files or other directories (default = false).

let file: DataFile = Algorithmia.getClient(process.env.ALGORITHMIA_DEFAULT_API_KEY).file('Insert file path');
const response = await file.delete();

let dir: DataDir = Algorithmia.getClient(process.env.ALGORITHMIA_DEFAULT_API_KEY).dir('Insert directory path');
const response = await dir.delete(true);

Algo API's

Name Parameters Example
Get Algorithm String userName - Your Algorithmia user name.
String algoName - The name address of the algorithm.
const algorithm: Algorithm = JSON.parse(await Algorithmia.getClient(key).getAlgo(userName, algoName));
List Algorithm Versions String userName - Your Algorithmia user name.
String algoName - The name address of the algorithm.
Boolean callable - Whether to return only public or private algorithm versions.
Integer limit - Items per page.
Boolean published - Whether to return only versions that have been published.
String marker - Marker for pagination.
const algorithmVersionsList: AlgorithmVersionsList = JSON.parse(await Algorithmia.getClient(key).listAlgoVersions(userName, algoName));
List Algorithm Builds String userName - Your Algorithmia user name.
String algoName - The name address of the algorithm.
Integer limit - Items per page.
String marker - Marker for pagination.
const algorithmBuildsList: AlgorithmBuildsList = JSON.parse(await Algorithmia.getClient(key).listAlgoBuilds(userName, algoName));
Get Algorithm Build Logs String userName - Your Algorithmia user name.
String algoName - The name address of the algorithm.
String buildId - The id of the build to retrieve logs.
const response: [] = JSON.parse(await Algorithmia.getClient(key).getAlgoBuildLogs(userName, algoName, buildId));
Delete Algorithm String userName - Your Algorithmia user name.
String algoName - The name address of the algorithm.
const response = await Algorithmia.getClient(key).deleteAlgo(userName, algoName);
Create Algorithm String userName - Your Algorithmia user name.
String requestString - JSON payload for the Algorithm you wish to create.
const algorithm: Algorithm = JSON.parse(await Algorithmia.getClient(key).createAlgo(userName, algoJson));
List Cluster SCM’s - const response: SCM[] = JSON.parse(await Algorithmia.getClient(key).listSCMs());
Get SCM String scmId - The id of scm to retrive const scm: SCM = JSON.parse(await Algorithmia.getClient(key).getSCM(scmId));
Query SCM Authorization Status String scmId - The id of scm status to retrive const scmAuth: AlgorithmSCMAuthorizationStatus = JSON.parse(await Algorithmia.getClient(key).querySCMStatus(scmId));

Building the client

This project uses typescript compile.

npm install typescript -g && npm install @types/node

tsc

Note: Don't edit the .js in the lib directory; they will get overwritten on subsequent compiles. Instead, modify .ts files in the src dir, and run tsc.

algorithmia-nodejs's People

Contributors

acanedo avatar anaimi avatar anowell avatar archr avatar daleherring avatar dependabot[bot] avatar jamesatha avatar kennydaniel avatar platypii avatar pmcq avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

algorithmia-nodejs's Issues

TypeError

No matter what algorithm I try to call from a nodejs app, I get the following TypeError.

error:

/XXXX/XXXXX/node_modules/algorithmia/lib/algorithmia.js:75
        if (ct.startsWith('application/json')) {
               ^
TypeError: undefined is not a function
    at IncomingMessage.<anonymous> (/XXXX/XXXXX/node_modules/algorithmia/lib/algorithmia.js:75:16)
    at IncomingMessage.emit (events.js:129:20)
    at _stream_readable.js:908:16
    at process._tickCallback (node.js:355:11)

call:

var algorithmia = require("algorithmia");
var client = algorithmia('API KEY');

client.algo("algo://demo/Hello/0.1.1")
    .pipe("HAL 9000")
    .then(function(response) {
    console.log(response.get());
    });

Have tried rotating API keys, spinning up a fresh node app, and trying a bunch of different algorithms, but no dice.

Use a promise library

Results with a .then are generally thought to be promises. The issue here is that the result isn't a real promise and doesn't conform the promises A+ spec.

This becomes a problem for example if you want to handle an exception you might assume that you can attach a .catch() to the result.

ReferenceError: headers is not defined in algorithmia/lib/data.js

While doing the algorithm DeepFilter

var client = algorithmia(process.env.ALGORITHMIA_API_KEY);
var input={ images: [ 'https://en.wikipedia.org/wiki/Nikola_Tesla#/media/File:N.Tesla.JPG' ],
  savePaths: [ 'data://.my/DeepFilterTest/stylized_image.jpg' ],
  filterName: 'space_pizza' }
client.dir('data://.my/DeepFilterTest/').create((res)=>console.log(res))

I get

ReferenceError: headers is not defined
    at Dir.create (/myProject/node_modules/algorithmia/lib/data.js:135:100)
    at repl:1:32
    at sigintHandlersWrap (vm.js:32:31)
    at sigintHandlersWrap (vm.js:96:12)
    at ContextifyScript.Script.runInContext (vm.js:31:12)
    at REPLServer.defaultEval (repl.js:308:29)
    at bound (domain.js:280:14)
    at REPLServer.runBound [as eval] (domain.js:293:12)
    at REPLServer.<anonymous> (repl.js:489:10)
    at emitOne (events.js:101:20)

Missing binary support for Data API

File has putString, putJson, getString and getJson methods, but no way to work with binary files. (The algorithm pipe method does support binary input/output)

IMO, we should add put that works with strings and byte Buffers like most other clients. I think putString and putJson should be deprecated in a future release. putString becomes redundant of put, and putJson is more confusing than helpful (if it takes JSON input, it's redundant of putString, if it takes an object, it's the opposite of the pipeJson method). In all cases, put(JSON.stringify(myobject)) is simple and obvious.

We could have separate getString and getBytes, but I'm inclined to push for future deprecation of those behind a get and probably getFile.

CORS issue when call algo nodejs api from ionic(angular) app (response for preflight has invalid HTTP 404) )

I am trying to make a mobile app with ionic3( based on angular4). it could also be a progressive web app (PWA). When call algo node api, I get following CORS error,

Response to preflight request doesn't pass access control check: No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'http://localhost:8100' is therefore not allowed access. The response had HTTP status code 404.

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.