-
Notifications
You must be signed in to change notification settings - Fork 3
/
Copy pathindex.js
70 lines (61 loc) · 2.07 KB
/
index.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
import _ from 'lodash';
import path from 'path';
import grpc from 'grpc';
import B from 'bluebird';
const PROTO = path.resolve(__dirname, '..', 'proto', 'classifier.proto');
const DEF_HOST = "localhost";
const DEF_PORT = 50051;
const DEF_CONFIDENCE = 0.9;
const QUERY = "//body//*[not(self::script) and not(self::style) and not(child::*)]";
class ClassifierClient {
constructor ({host = DEF_HOST, port = DEF_PORT}) {
this.host = host;
this.port = port;
const protoLoader = require('@grpc/proto-loader');
const packageDef = protoLoader.loadSync(PROTO, {
keepCase: true,
defaults: true,
oneofs: true
});
const protoDesc = grpc.loadPackageDefinition(packageDef);
const client = new protoDesc.Classifier(`${this.host}:${this.port}`, grpc.credentials.createInsecure());
this._classifyElements = B.promisify(client.classifyElements, {context: client});
}
async classifyElements ({
labelHint,
elementImages,
confidenceThreshold = DEF_CONFIDENCE,
allowWeakerMatches = false
}) {
const res = await this._classifyElements({labelHint, elementImages, confidenceThreshold, allowWeakerMatches});
return res.classifications;
}
async findElementsMatchingLabel ({
driver,
labelHint,
confidenceThreshold = DEF_CONFIDENCE,
allowWeakerMatches = false
}) {
const els = await driver.$$(QUERY);
const elementImages = {};
for (const el of els) {
try {
const b64Screen = await el.takeElementScreenshot(el.elementId);
elementImages[el.elementId] = Buffer.from(b64Screen, 'base64');
} catch (ign) {}
}
if (_.size(elementImages) < 1) {
throw new Error('Could not find any screenshots for leaf node elements');
}
const matched = await this.classifyElements({
labelHint,
elementImages,
confidenceThreshold,
allowWeakerMatches,
});
// return only those elements whose ids ended up in our matched list
return els.filter(el => _.includes(_.keys(matched), el.elementId));
}
}
export default ClassifierClient;
export { ClassifierClient };