diff options
Diffstat (limited to 'src/client/cognitive_services/CognitiveServices.ts')
-rw-r--r-- | src/client/cognitive_services/CognitiveServices.ts | 70 |
1 files changed, 35 insertions, 35 deletions
diff --git a/src/client/cognitive_services/CognitiveServices.ts b/src/client/cognitive_services/CognitiveServices.ts index 408903324..9808b6a01 100644 --- a/src/client/cognitive_services/CognitiveServices.ts +++ b/src/client/cognitive_services/CognitiveServices.ts @@ -1,18 +1,21 @@ -import * as request from 'request-promise'; -import { Doc, Field } from '../../fields/Doc'; -import { Cast } from '../../fields/Types'; -import { Utils } from '../../Utils'; +/* eslint-disable @typescript-eslint/no-unused-vars */ +/* eslint-disable camelcase */ +/* eslint-disable no-useless-catch */ +/* eslint-disable no-use-before-define */ +import * as rp from 'request-promise'; +import { Doc, FieldType } from '../../fields/Doc'; import { InkData } from '../../fields/InkField'; -import { UndoManager } from '../util/UndoManager'; -import requestPromise = require('request-promise'); import { List } from '../../fields/List'; +import { Cast } from '../../fields/Types'; +import { UndoManager } from '../util/UndoManager'; +import { ClientUtils } from '../../ClientUtils'; type APIManager<D> = { converter: BodyConverter<D>; requester: RequestExecutor }; type RequestExecutor = (apiKey: string, body: string, service: Service) => Promise<string>; type AnalysisApplier<D> = (target: Doc, relevantKeys: string[], data: D, ...args: any) => any; type BodyConverter<D> = (data: D) => string; -type Converter = (results: any) => Field; -type TextConverter = (results: any, data: string) => Promise<{ keyterms: Field; external_recommendations: any; kp_string: string[] }>; +type Converter = (results: any) => FieldType; +type TextConverter = (results: any, data: string) => Promise<{ keyterms: FieldType; external_recommendations: any; kp_string: string[] }>; type BingConverter = (results: any) => Promise<{ title_vals: string[]; url_vals: string[] }>; export type Tag = { name: string; confidence: number }; @@ -42,7 +45,7 @@ export enum Confidence { */ export namespace CognitiveServices { const ExecuteQuery = async <D>(service: Service, manager: APIManager<D>, data: D): Promise<any> => { - let apiKey = process.env[service.toUpperCase()]; + const apiKey = process.env[service.toUpperCase()]; if (!apiKey) { console.log(`No API key found for ${service}: ensure youe root directory has .env file with _CLIENT_${service.toUpperCase()}.`); return undefined; @@ -53,7 +56,6 @@ export namespace CognitiveServices { results = await manager.requester(apiKey, manager.converter(data), service).then(json => JSON.parse(json)); } catch (e) { throw e; - results = undefined; } return results; }; @@ -72,7 +74,7 @@ export namespace CognitiveServices { parameters = { returnFaceId: 'true', returnFaceLandmarks: 'false', - returnFaceAttributes: 'age,gender,headPose,smile,facialHair,glasses,' + 'emotion,hair,makeup,occlusion,accessories,blur,exposure,noise', + returnFaceAttributes: 'age,gender,headPose,smile,facialHair,glasses,emotion,hair,makeup,occlusion,accessories,blur,exposure,noise', }; break; case Service.ComputerVision: @@ -83,6 +85,7 @@ export namespace CognitiveServices { language: 'en', }; break; + default: } const options = { @@ -95,7 +98,7 @@ export namespace CognitiveServices { }, }; - return request.post(options); + return rp.post(options); }, }; @@ -111,12 +114,10 @@ export namespace CognitiveServices { const results = await ExecuteQuery(service, Manager, url); if (!results) { toStore = 'Cognitive Services could not process the given image URL.'; + } else if (!results.length) { + toStore = converter(results); } else { - if (!results.length) { - toStore = converter(results); - } else { - toStore = results.length > 0 ? converter(results) : 'Empty list returned.'; - } + toStore = results.length > 0 ? converter(results) : 'Empty list returned.'; } target[storageKey] = toStore; @@ -150,7 +151,7 @@ export namespace CognitiveServices { const endpoint = serverAddress + '/inkrecognizer/v1.0-preview/recognize'; return new Promise<string>((resolve, reject) => { - xhttp.onreadystatechange = function () { + xhttp.onreadystatechange = function (this: XMLHttpRequest) { if (this.readyState === 4) { const result = xhttp.responseText; switch (this.status) { @@ -161,6 +162,7 @@ export namespace CognitiveServices { return reject(result); } } + return undefined; }; xhttp.open('PUT', endpoint, true); @@ -213,15 +215,13 @@ export namespace CognitiveServices { export namespace BingSearch { export const Manager: APIManager<string> = { - converter: (data: string) => { - return data; - }, + converter: (data: string) => data, requester: async (apiKey: string, query: string) => { const xhttp = new XMLHttpRequest(); const serverAddress = 'https://api.cognitive.microsoft.com'; const endpoint = serverAddress + '/bing/v5.0/search?q=' + encodeURIComponent(query); const promisified = (resolve: any, reject: any) => { - xhttp.onreadystatechange = function () { + xhttp.onreadystatechange = function (this: XMLHttpRequest) { if (this.readyState === 4) { const result = xhttp.responseText; switch (this.status) { @@ -232,6 +232,7 @@ export namespace CognitiveServices { return reject(result); } } + return undefined; }; if (apiKey) { @@ -259,15 +260,13 @@ export namespace CognitiveServices { export namespace HathiTrust { export const Manager: APIManager<string> = { - converter: (data: string) => { - return data; - }, + converter: (data: string) => data, requester: async (apiKey: string, query: string) => { const xhttp = new XMLHttpRequest(); const serverAddress = 'https://babel.hathitrust.org/cgi/htd/'; const endpoint = serverAddress + '/bing/v5.0/search?q=' + encodeURIComponent(query); const promisified = (resolve: any, reject: any) => { - xhttp.onreadystatechange = function () { + xhttp.onreadystatechange = function (this: XMLHttpRequest) { if (this.readyState === 4) { const result = xhttp.responseText; switch (this.status) { @@ -278,6 +277,7 @@ export namespace CognitiveServices { return reject(result); } } + return undefined; }; if (apiKey) { @@ -305,8 +305,8 @@ export namespace CognitiveServices { export namespace Text { export const Manager: APIManager<string> = { - converter: (data: string) => { - return JSON.stringify({ + converter: (data: string) => + JSON.stringify({ documents: [ { id: 1, @@ -314,8 +314,7 @@ export namespace CognitiveServices { text: data, }, ], - }); - }, + }), requester: async (apiKey: string, body: string, service: Service) => { const serverAddress = 'https://eastus.api.cognitive.microsoft.com'; const endpoint = serverAddress + '/text/analytics/v2.1/keyPhrases'; @@ -344,10 +343,10 @@ export namespace CognitiveServices { export namespace Appliers { export async function vectorize(keyterms: any, dataDoc: Doc, mainDoc: boolean = false) { console.log('vectorizing...'); - //keyterms = ["father", "king"]; + // keyterms = ["father", "king"]; - const args = { method: 'POST', uri: Utils.prepend('/recommender'), body: { keyphrases: keyterms }, json: true }; - await requestPromise.post(args).then(async wordvecs => { + const args = { method: 'POST', uri: ClientUtils.prepend('/recommender'), body: { keyphrases: keyterms }, json: true }; + await rp.post(args).then(async wordvecs => { if (wordvecs) { const indices = Object.keys(wordvecs); console.log('successful vectorization!'); @@ -355,7 +354,7 @@ export namespace CognitiveServices { indices.forEach((ind: any) => { vectorValues.push(wordvecs[ind]); }); - //ClientRecommender.Instance.processVector(vectorValues, dataDoc, mainDoc); + // ClientRecommender.Instance.processVector(vectorValues, dataDoc, mainDoc); } // adds document to internal doc set else { console.log('unsuccessful :( word(s) not in vocabulary'); @@ -369,11 +368,12 @@ export namespace CognitiveServices { const { keyterms, external_recommendations, kp_string } = await converter(results, data); target[keys[0]] = keyterms; if (isInternal) { - //await vectorize([data], dataDoc, isMainDoc); + // await vectorize([data], dataDoc, isMainDoc); await vectorize(kp_string, dataDoc, isMainDoc); } else { return { recs: external_recommendations, keyterms: keyterms }; } + return undefined; }; // export async function countFrequencies() |