Beispiel #1
0
VisualRecognitionV3.prototype.classify = function(params, callback) {

  try {
    verifyParams(params);
  } catch (e) {
    callback(e);
    return;
  }

  params = extend({
    classifier_ids: ['default'],
    owners: ['me','IBM']
  }, params);

  var parameters;

  if(params.images_file) {
    var stream = params.images_file || params.image_file;

    parameters = {
      options: {
        url: '/v3/classify',
        method: 'POST',
        formData: {
          images_file: stream,
          parameters: {
            value: JSON.stringify(pick(params, ['classifier_ids', 'owners', 'threshold'])),
            options: {
              contentType: 'application/json'
            }
          }
        },
        headers: pick(params, 'Accept-Language')
      },
      defaultOptions: this._options
    };
  } else {
    parameters = {
      options: {
        url: '/v3/classify',
        method: 'GET',
        json: true,
        qs: pick(params, ['url', 'classifier_ids', 'owners', 'threshold']),
        headers: pick(params, 'Accept-Language')
      },
      defaultOptions: this._options
    };
  }

  return requestFactory(parameters, callback);
};
Beispiel #2
0
SpeechToTextV1.prototype.trainCustomization = function(params, callback) {
  const parameters = {
    requiredParams: ['customization_id'],
    options: {
      method: 'POST',
      url: '/v1/customizations/{customization_id}/train',
      path: pick(params, ['customization_id']),
      qs: pick(params, ['word_type_to_add']),
      json: true
    },
    defaultOptions: this._options
  };
  return requestFactory(parameters, callback);
};
Beispiel #3
0
SpeechToTextV1.prototype.addWord = function(params, callback) {
  const parameters = {
    requiredParams: ['customization_id', 'word', 'sounds_like'],
    options: {
      method: 'PUT',
      url: '/v1/customizations/{customization_id}/words/{word}',
      path: pick(params, ['customization_id', 'word']),
      body: pick(params, ['sounds_like', 'display_as']),
      json: true
    },
    defaultOptions: this._options
  };
  return requestFactory(parameters, callback);
};
Beispiel #4
0
TextToSpeechV1.prototype.voice = function(params, callback) {
  var parameters = {
    requiredParams: ['voice'],
    options: {
      method: 'GET',
      url: '/v1/voices/{voice}',
      path: pick(params, ['voice']),
      qs: pick(params, ['customization_id']),
      json: true
    },
    defaultOptions: this._options
  };
  return requestFactory(parameters, callback);
};
Beispiel #5
0
SpeechToTextV1.prototype.addCorpus = function(params, callback) {
  const parameters = {
    requiredParams: ['customization_id', 'name', 'corpus'],
    originalParams: params,
    options: {
      method: 'POST', // shouldn't this be a PUT?
      url: '/v1/customizations/{customization_id}/corpora/{name}',
      path: pick(params, ['customization_id', 'name']),
      qs: pick(params, ['allow_overwrite']),
      body: params.corpus
    },
    defaultOptions: this._options
  };
  return requestFactory(parameters, callback);
};
Beispiel #6
0
SpeechToTextV1.prototype.recognize = function(params, callback) {

  var missingParams = helper.getMissingParams(params, ['audio', 'content_type']);
  if (missingParams) {
    callback(new Error('Missing required parameters: ' + missingParams.join(', ')));
    return;
  }
  if (!isStream(params.audio)) {
    callback(new Error('audio is not a standard Node.js Stream'));
    return;
  }

  var queryParams = pick(params, PARAMS_ALLOWED);

  var _url = '/v1';
  _url += (params.session_id) ? ('/sessions/' + params.session_id) : '';
  _url += '/recognize';

  var parameters = {
    options: {
      method: 'POST',
      url: _url,
      headers: {
        'Content-Type': params.content_type
      },
      json: true,
      qs: queryParams,
    },
    defaultOptions: this._options
  };
  return params.audio.on('response', function(response) {
    // Replace content-type
    response.headers['content-type'] = params.content_type;
  }).pipe(requestFactory(parameters, callback));
};
Beispiel #7
0
VisualRecognitionV3.prototype.createClassifier = function(params, callback) {
  params = params || {};

  var example_keys = Object.keys(params).filter(function(key) {
    return key === NEGATIVE_EXAMPLES || key.match(/^.+_positive_examples$/);
  });

  if (example_keys.length <2) {
    callback(new Error('Missing required parameters: either two *_positive_examples or one *_positive_examples and one negative_examples must be provided.'));
    return;
  }
  // todo: validate that all *_examples are streams or else objects with buffers and content-types



  var allowed_keys = ['name', NEGATIVE_EXAMPLES].concat(example_keys);

  var parameters = {
    options: {
      url: '/v3/classifiers',
      method: 'POST',
      json: true,
      formData: pick(params, allowed_keys)
    },
    requiredParams: ['name'],
    defaultOptions: this._options
  };
  return requestFactory(parameters, callback);
};
Beispiel #8
0
Conversation.prototype.message = function(params, callback) {
  params = params || {};

  var parameters = {
    options: {
      url: '/v1/workspaces/{workspace_id}/message',
      method: 'POST',
      json: true,
      body: pick(params, ['input', 'context', 'intents', 'entities']),
      path: pick(params, ['workspace_id'])
    },
    requiredParams: ['workspace_id'],
    defaultOptions: this._options
  };
  return requestFactory(parameters, callback);
};
Beispiel #9
0
Dialog.prototype.createDialog = function(params, callback) {
  params = params || {};

  if (!params.file) {
    callback(new Error('Missing required parameters: file'));
    return;
  }

  if (!isStream(params.file)) {
    callback(new Error('file is not a standard Node.js Stream'));
    return;
  }

  var parameters = {
    options: {
      url: '/v1/dialogs',
      method: 'POST',
      json: true,
      formData: pick(params,['name','file'])
    },
    requiredParams: ['name'],
    defaultOptions: this._options
  };
  return requestFactory(parameters, callback);
};
Beispiel #10
0
module.exports = function (opts) {
  if (typeof opts === 'function') {
    opts = { keys: opts }
  }

  opts = xtend(defaults, opts)

  var keyOpts    = pick(opts, ['defaultValue', 'bare'])
    , detectOpts = pick(opts, 'phpexcel')

  return pipeline (
    detect(detectOpts),
    keys(keyOpts, opts.keys),
    coerce()
  )
}
Beispiel #11
0
ToneAnalyzerV3.prototype.tone_chat = function(params, callback) {
  // For backward compatibility
  if (params && params.utterances && params.utterances.utterances) {
    params.utterances = params.utterances.utterances;
  }

  const parameters = {
    requiredParams: ['utterances'],
    originalParams: params,
    options: {
      url: '/v3/tone_chat',
      method: 'POST',
      json: true,
      body: pick(params, ['utterances'])
    },
    defaultOptions: extend(true, this._options, {
      headers: {
        accept: 'application/json',
        'content-type': 'application/json'
      }
    })
  };

  return requestFactory(parameters, callback);
};
Beispiel #12
0
ToneAnalyzerV3.prototype.tone = function(params, callback) {
  if (!params || !params.text) {
    callback(new Error('Missing required parameters: text'));
    return;
  }
  const contentType = params.isHTML ? 'text/html' : 'text/plain';

  const headers = {
    accept: 'application/json',
    'content-type': contentType
  };

  if (params.language) {
    headers['content-language'] = params.language;
  }

  const parameters = {
    options: {
      url: '/v3/tone',
      method: 'POST',
      body: params.text,
      qs: pick(params, ['tones', 'sentences'])
    },
    defaultOptions: extend(true, this._options, {
      headers: headers
    })
  };

  return requestFactory(parameters, callback);
};
Beispiel #13
0
QuestionAndAnswer.prototype.ask = function(_params, callback) {
  // If 'text' is specified, build POST body question using text
  if (_params && _params.text) {
    _params.question = toQuestion(_params);
    delete _params.text;
  }

  var params = extend(this._options, _params);

  if (!params.question) {
    callback(new Error('Missing required parameters: text or question'));
    return;
  }

  var parameters = {
    options: {
      url: '/v1/question/{dataset}',
      headers: {
        'X-Synctimeout': 30
      },
      method: 'POST',
      body: pick(params, ['question']),
      json: true,
      path: params
    },
    requiredParams: ['question', 'dataset'],
    defaultOptions: this._options
  };
  return requestFactory(parameters, callback);
};
Beispiel #14
0
RetrieveAndRank.prototype.rank = function(params, callback) {
  params = params || {};

  if (!params || !params.answer_data) {
    callback(new Error('Missing required parameters: answer_data'));
    return;
  }
  if ((typeof params.answer_data !== 'string') && (!isStream(params.answer_data))) {
    callback(new Error('answer_data needs to be a String or Stream'));
    return;
  }

  var parameters = {
    options: {
      url: '/v1/rankers/{ranker_id}/rank',
      method: 'POST',
      json: true,
      formData: {
        answer_data: params.answer_data,
        answer_metadata: JSON.stringify(omit(params, ['answer_data']))
      },
      path: pick(params, ['ranker_id'])
    },
    requiredParams: ['ranker_id'],
    defaultOptions: this._options
  };
  return requestFactory(parameters, callback);
};
    it('success 3', () => {
      let res = comments.parseComment('/** * @param {String=} [val=abc] some description */', {
        unwrap: true,
        strict: false
      });

      assert.deepEqual(pick(res, ['tags', 'description']), {
        description: '',
        tags: [
          {
            title: 'param',
            description: 'some description',
            inlineTags: [],
            type: {
              type: 'OptionalType',
              expression: {
                type: 'NameExpression',
                name: 'String'
              }
            },
            name: 'val',
            default: 'abc'
          }
        ]
      });
    });
    it('should preserve whitespace in default string', () => {
      let res = comments.parseComment(['/**', ' * @property {String} [val=   "   foo"  ] some description', ' */'].join('\n'), {
        unwrap: true,
        strict: false
      });

      assert.deepEqual(pick(res, ['tags', 'description']), {
        description: '',
        tags: [
          {
            title: 'property',
            description: 'some description',
            inlineTags: [],
            type: {
              type: 'OptionalType',
              expression: {
                type: 'NameExpression',
                name: 'String'
              }
            },
            name: 'val',
            default: '"   foo"'
          }
        ]
      });
    });
    it('default array within white spaces', () => {
      let res = comments.parseComment(['/**', " * @property {String} [val = [ 'foo' ]] some description", ' */'].join('\n'), {
        unwrap: true,
        strict: false
      });

      assert.deepEqual(pick(res, ['tags', 'description']), {
        description: '',
        tags: [
          {
            title: 'property',
            description: 'some description',
            inlineTags: [],
            type: {
              type: 'OptionalType',
              expression: {
                type: 'NameExpression',
                name: 'String'
              }
            },
            name: 'val',
            default: "[ 'foo' ]"
          }
        ]
      });
    });
Beispiel #18
0
RetrieveAndRank.prototype.deleteCollection = function(params, callback) {
  params = params || {};

  var missingParams = helper.getMissingParams(params, ['cluster_id', 'collection_name']);
  if (missingParams){
    callback(new Error('Missing required parameters: ' + missingParams.join(', ')));
    return;
  }

  var queryParams = {
    name: params.collection_name,
    wt: params.wt || 'json',
    action: 'DELETE'
  };

  var parameters = {
    options: {
      url: '/v1/solr_clusters/{cluster_id}/solr/admin/collections',
      method: 'POST',
      qs: queryParams,
      path: pick(params,['cluster_id']),
      json: true
    },
    defaultOptions: this._options
  };

  return requestFactory(parameters, callback);
};
    it('default string surrounded by whitespace', () => {
      let res = comments.parseComment(['/**', " * @param {String} [val=   'foo'  ] some description", ' */'].join('\n'), {
        unwrap: true,
        strict: false
      });

      assert.deepEqual(pick(res, ['tags', 'description']), {
        description: '',
        tags: [
          {
            title: 'param',
            description: 'some description',
            inlineTags: [],
            type: {
              type: 'OptionalType',
              expression: {
                type: 'NameExpression',
                name: 'String'
              }
            },
            name: 'val',
            default: "'foo'"
          }
        ]
      });
    });
Beispiel #20
0
TextToSpeech.prototype.createCustomizations = function(params, callback) {
  var parameters = {
    options: {
      method: 'POST',
      url: '/v1/customizations',
      body: JSON.stringify(pick(params, ['text'])),
      qs: pick(params, ['accept', 'voice']),
      headers: extend({
        'content-type': 'application/json'
      }, pick(params, ['X-Watson-Learning-Opt-Out'])),
      json: true
    },
    defaultOptions: this._options
  };
  return requestFactory(parameters, callback);
};
Beispiel #21
0
 PersonalityInsightsV2.prototype.profile = function (params, callback) {
     var _params = params || {};
     // support for the new snake_case
     if (_params['content_items']) {
         _params['contentItems'] = _params['content_items'];
     }
     if (!_params.text && !_params.contentItems) {
         callback(new Error('Missing required parameters: text or content_items'));
         return;
     }
     // Content-Type
     var content_type = null;
     if (_params.text) {
         content_type = helper_1.isHTML(_params.text) ? 'text/html' : 'text/plain';
     }
     else {
         content_type = 'application/json';
     }
     var headers = {
         'Content-type': content_type,
         'Accept-language': _params.accept_language || _params.acceptLanguage || 'en',
         Accept: undefined
     };
     // service bug: language in header overrides language in each JSON content item, so we can't set it on those requests
     // (also, content-language doesn't really make sense on JSON)
     if (_params.language || _params.text) {
         headers['Content-language'] = _params.language || 'en';
     }
     var parameters = {
         options: {
             method: 'POST',
             url: '/v2/profile',
             body: _params.text || pick(_params, ['contentItems']),
             json: true,
             qs: pick(_params, ['include_raw']),
             headers: headers
         },
         defaultOptions: this._options
     };
     if (_params.csv) {
         parameters.options.headers.Accept = 'text/csv';
         if (_params.csv_headers) {
             parameters.options.qs.headers = 'true';
         }
     }
     return requestwrapper_1.createRequest(parameters, callback);
 };
Beispiel #22
0
NaturalLanguageClassifier.prototype.classify = function(params, callback) {
  params = params || {};

  var parameters = {
    options: {
      url: '/v1/classifiers/{classifier}/classify',
      method: 'POST',
      json: true,
      path: pick(params, ['classifier']),
      body: pick(params, ['text'])
    },
    requiredParams: ['classifier', 'text'],
    defaultOptions: this._options
  };

  return requestFactory(parameters, callback);
};
Dialog.prototype.updateProfile = function(params, callback) {
  params = params || {};

  var parameters = {
    options: {
      url: '/v1/dialogs/{dialog_id}/profile',
      method: 'PUT',
      json: true,
      body: pick(params, ['name_values']),
      qs: pick(params, ['client_id']),
      path: params
    },
    requiredParams: ['dialog_id', 'client_id', 'name_values'],
    defaultOptions: this._options
  };
  return requestFactory(parameters, callback);
};
Beispiel #24
0
SpeechToTextV1.prototype.getWords = function(params, callback) {
  if (typeof params === 'function' && !callback) {
    callback = params;
    params = {};
  }
  const parameters = {
    requiredParams: ['customization_id'],
    options: {
      method: 'GET',
      url: '/v1/customizations/{customization_id}/words',
      path: pick(params, ['customization_id']),
      qs: pick(params, ['word_type', 'sort']),
      json: true
    },
    defaultOptions: this._options
  };
  return requestFactory(parameters, callback);
};
 it('should generate a valid payload', function() {
   const req = conversation.createCounterExample(params, noop);
   const body = Buffer.from(req.body).toString('ascii');
   assert.equal(
     req.uri.href,
     service.url + paths.counterexamples + '?version=' + service.version_date
   );
   assert.deepEqual(JSON.parse(body), pick(params, ['text']));
   assert.equal(req.method, 'POST');
 });
 it('failure 1', () => {
   let res = comments.parseComment(['/**', ' * @property [val', ' */'].join('\n'), {
     unwrap: true,
     strict: false
   });
   assert.deepEqual(pick(res, ['tags', 'description']), {
     'description': '',
     'tags': []
   });
 });
Beispiel #27
0
function defaultValue(file) {

	const vinylProps = ['cwd', 'base', 'contents', 'stat', 'history', 'path'];
	const customProps = Object.keys(file).filter(File.isCustomProp);

	// Convert from a File object (from vinyl) into a plain object
	return pick(file, [
		...vinylProps,
		...customProps
	]);
}
    it('failure 1', () => {
      let res = comments.parseComment('/** * @param [val */', {
        unwrap: true,
        strict: false
      });

      assert.deepEqual(pick(res, ['tags', 'description']), {
        'description': '',
        'tags': []
      });
    });
Beispiel #29
0
Elixir.extend('pug', function (options)
{
    options = Extend({
        blade: false,
        pretty: true,
        src: 'resources/assets/pug/',
        exclude: '_partials/**/*',
        search: '**/*.pug',
        dest: options.blade ? 'resources/views' : 'public/html',
        additional_watches: [],
        pugExtension: '.pug'
    }, options);

    var gulp_src = [
        options.src + options.search
    ];

    var pug_options = Pick(
        options,
        [
            'basedir',
            'doctype',
            'pretty',
            'filters',
            'self',
            'debug',
            'compileDebug',
            'locals',
            'globals',
            'cache',
            'inlineRuntimeFunctions',
            'name'
        ]
    );

    var watch = [options.src + options.search].concat(options.additional_watches);
    var extension = options.blade ? '.blade.php' : '.html';

    return new Task('pug_' + (pug_task_increment++), function ()
    {
        return Gulp
            .src(gulp_src)
            .pipe(Plumber())
            .pipe(Changed(options.dest, {extension: extension}))
            .pipe(PugInheritance({basedir: options.src, extension: options.pugExtension, skip: 'node_modules'}))
            .pipe(Ignore.exclude(options.exclude))
            .pipe(Pug(pug_options))
            .pipe(Rename(function (path)
            {
                path.extname = extension;
            }))
            .pipe(Gulp.dest(options.dest))
    }).watch(watch);
});
Beispiel #30
0
TextToSpeechV1.prototype.createCustomization = function(params, callback) {
  var parameters = {
    options: {
      method: 'POST',
      url: '/v1/customizations',
      body: pick(params, ['name', 'language', 'description']),
      json: true
    },
    defaultOptions: this._options
  };
  return requestFactory(parameters, callback);
};