-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathhandler.js
More file actions
87 lines (81 loc) · 2.17 KB
/
Copy pathhandler.js
File metadata and controls
87 lines (81 loc) · 2.17 KB
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
80
81
82
83
84
85
86
87
'use strict';
const use = require("@tensorflow-models/universal-sentence-encoder");
const similarity = require("compute-cosine-similarity");
/**
* Asynchronus function to generate the vector representation of a piece of text.
* @param {string} text
*/
async function encodeData (text) {
// const sentences = [text];
let model = await use.load();
let embeddings = await model.embed(text); // `embeddings` is a 2D tensor consisting of the 512-dimensional embeddings for each sentence.
let d = await embeddings.array();
return d[0]; // extract and return vector
}
/**
* Test endpoint.
*/
module.exports.home = async event => {
return {
statusCode: 200,
body: JSON.stringify(
{
message: 'Serverless v1.0! You can convert texts to vectors!',
input: event
},
null,
2
)
};
};
/**
* Vectorise text in request path.
*/
module.exports.vectoriseInPath = async event => {
const text = [event.pathParameters.text];
const vec = await encodeData(text);
return {
statusCode: 200,
body: JSON.stringify({
message: 'Vector representation using lite Universal Sentence Encoder',
inputText: text[0],
vectors: vec
})
};
};
/**
* Vectorise text in request body.
*/
module.exports.vectorise = async event => {
const data = JSON.parse(event.body);
const text = [data.text];
const vec = await encodeData(text);
return {
statusCode: 200,
body: JSON.stringify({
message: 'Vector representation using lite Universal Sentence Encoder',
inputText: text[0],
vectors: vec
})
};
};
/**
* Determine cosine similarity of two pieces of texts in request body.
*/
module.exports.similarity = async event => {
// const data = querystring.parse(event.body);
const data = JSON.parse(event.body);
const first = [data.first];
const second = [data.second];
const firstVec = await encodeData(first);
const secondVec = await encodeData(second);
const sim = similarity(firstVec, secondVec);
return {
statusCode: 200,
body: JSON.stringify({
message: 'Cosine similarity between vectorised input texts',
inputTexts: [first[0], second[0]],
similarity: sim
})
};
};