-
Notifications
You must be signed in to change notification settings - Fork 4
/
Copy pathIdentifyTranslate.js
79 lines (79 loc) · 2.46 KB
/
IdentifyTranslate.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
/**
*
* main() will be run when you invoke this action
*
* @param Cloud Functions actions accept a single parameter, which must be a JSON object.
*
* @return The output of this action, which must be a JSON object.
*
*/
let rp = require("request-promise");
let _ = require("lodash");
function main(params) {
if (params.payload.input.text !== "") {
const options = {
method: "POST",
url:
"https://<WATSON_LANGUAGE_TRANSLATOR_URL>/instances/<YOUR_INSTANCE_ID>/v3/identify?version=2018-05-01",
auth: {
username: "apikey",
password: "<WATSON_LANGUAGE_TRANSLATOR_APIKEY>",
},
headers: {
"Content-Type": "text/plain",
},
body: [params.payload.input.text],
json: true,
};
return rp(options).then((res) => {
var defaultDialogLanguageCode = "en";
const confidence = _.get(res, "languages[0].confidence");
console.log("confidence " + confidence);
const language =
confidence > 0.5 ? _.get(res, "languages[0].language") : defaultDialogLanguageCode;
_.set(params, 'payload.context.skills["main skill"].user_defined["language"]', language);
if (res.languages[0].language !== defaultDialogLanguageCode) {
const options = {
method: "POST",
url:
"https://<WATSON_LANGUAGE_TRANSLATOR_URL>/instances/<YOUR_INSTANCE_ID>/v3/translate?version=2018-05-01",
auth: {
username: "apikey",
password: "<WATSON_LANGUAGE_TRANSLATOR_APIKEY>",
},
body: {
text: [params.payload.input.text],
target: defaultDialogLanguageCode,
},
json: true,
};
return rp(options).then((res) => {
console.log("PRE-Translate - translating");
params.payload.context.skills["main skill"].user_defined["original_input"] =
params.payload.input.text;
params.payload.input.text = res.translations[0].translation;
console.log(JSON.stringify(params));
// const result = {
// body: params,
// };
return { params };
});
} else {
console.log(JSON.stringify(params));
// const result = {
// body: params,
// };
return { params };
}
});
} else {
params.payload.context.skills["main skill"].user_defined["language"] = "none";
// const result = {
// body: params,
// };
return { params };
}
}