-
Notifications
You must be signed in to change notification settings - Fork 0
/
index.js
151 lines (126 loc) · 4.32 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
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
const { Requester } = require("@chainlink/external-adapter");
const Vision = require("azure-cognitiveservices-vision");
const CognitiveServicesCredentials = require("ms-rest-azure")
.CognitiveServicesCredentials;
const Stream = require("stream").Transform;
const isSsl = !Boolean(
process.env.IPFS_GATEWAY_SSL &&
process.env.IPFS_GATEWAY_SSL.toLowerCase() === "false"
);
const httpProtocol = isSsl ? require("https") : require("http");
const createRequest = async (input, callback) => {
const credentials = new CognitiveServicesCredentials(
process.env.CONTENT_MODERATOR_SUBSCRIPTION_KEY
);
const contentModeratorApiClient = new Vision.ContentModeratorAPIClient(
credentials,
process.env.CONTENT_MODERATOR_ENDPOINT
);
return performRequest({
input,
callback,
contentModeratorApiClient,
isSsl,
httpProtocol
});
};
const performRequest = ({ input, callback, contentModeratorApiClient, ssl = false, httpProtocol = require("http") }) => {
const { data, id: jobRunID } = input;
if (!data) {
callback(500, Requester.errored(jobRunID, "No data"));
return;
}
const { hash } = data;
if (jobRunID === undefined) {
callback(500, Requester.errored(jobRunID, "Job run ID required"));
return;
}
if (hash === undefined) {
callback(500, Requester.errored(jobRunID, "Content hash required"));
} else {
const protocol = ssl ? "https" : "http";
const url = `${protocol}://${process.env.IPFS_GATEWAY_URL}/ipfs/${hash}`;
try {
httpProtocol
.request(url, function(response) {
var imgBytesStream = new Stream();
response.on("data", function(chunk) {
imgBytesStream.push(chunk);
});
response.on("end", function() {
requestModerationLabels(imgBytesStream.read());
});
})
.end();
const requestModerationLabels = async imgBytes => {
try {
const moderationLabels = await contentModeratorApiClient.imageModeration.evaluateFileInput(
imgBytes
);
const {
adultClassificationScore,
racyClassificationScore
} = moderationLabels;
const convertedResult = convertLabelsToTrueSightFormat({
adultScore: adultClassificationScore,
racyScore: racyClassificationScore
});
const response = {
data: moderationLabels
};
response.data.result = convertedResult;
callback(200, Requester.success(jobRunID, response));
} catch (error) {
console.error(error);
callback(500, Requester.errored(jobRunID, error));
}
};
} catch (error) {
console.error(error);
callback(500, Requester.errored(jobRunID, error));
}
}
};
const getConfidenceFromScore = decimalScore => {
const asPercentage = decimalScore * 100;
return Math.round(parseFloat(asPercentage));
};
/**
* Azure Cognitive Services provides results with decimal confidence scores between 0 and 1
* @param {number} adultScore The confidence score for adult content
* @param {number} racyScore The confidence score for racy content
*/
const convertLabelsToTrueSightFormat = ({ adultScore, racyScore }) => {
const adultConfidence = getConfidenceFromScore(adultScore);
const suggestiveConfidence = getConfidenceFromScore(racyScore);
return [adultConfidence, suggestiveConfidence, "", "", ""].join(",");
};
// This is a wrapper to allow the function to work with
// GCP Functions
exports.gcpservice = (req, res) => {
createRequest(req.body, (statusCode, data) => {
res.status(statusCode).send(data);
});
};
// This is a wrapper to allow the function to work with
// AWS Lambda
exports.handler = (event, context, callback) => {
createRequest(event, (statusCode, data) => {
callback(null, data);
});
};
// This is a wrapper to allow the function to work with
// newer AWS Lambda implementations
exports.handlerv2 = (event, context, callback) => {
createRequest(JSON.parse(event.body), (statusCode, data) => {
callback(null, {
statusCode: statusCode,
body: JSON.stringify(data),
isBase64Encoded: false
});
});
};
// This allows the function to be exported for testing
// or for running in express
module.exports.createRequest = createRequest;
module.exports.performRequest = performRequest;