-
Notifications
You must be signed in to change notification settings - Fork 5.8k
Expand file tree
/
Copy pathindex.js
More file actions
246 lines (230 loc) · 7.1 KB
/
index.js
File metadata and controls
246 lines (230 loc) · 7.1 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
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
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
// SPDX-License-Identifier: Apache-2.0
import {
DetectLabelsCommand,
RekognitionClient,
} from "@aws-sdk/client-rekognition";
import {
ListObjectsCommand,
PutObjectCommand,
S3Client,
} from "@aws-sdk/client-s3";
import { fromCognitoIdentityPool } from "@aws-sdk/credential-provider-cognito-identity";
import { CognitoIdentityClient } from "@aws-sdk/client-cognito-identity";
import { SendEmailCommand, SESClient } from "@aws-sdk/client-ses";
import { outputNames } from "./constants.js";
const email = process.env.VERIFIED_EMAIL_ADDRESS;
const region = process.env.REGION;
/** @type {Record<string, string> } */
const outputs = JSON.parse(process.env.CFN_OUTPUTS);
const imagesBucketName = outputs[outputNames.IMAGES_BUCKET_OUTPUT];
const reportsBucketName = outputs[outputNames.REPORTS_BUCKET_OUTPUT];
const identityPoolId = outputs[outputNames.IDENTITY_POOL_OUTPUT];
const credentials = fromCognitoIdentityPool({
client: new CognitoIdentityClient({ region: "us-east-1" }),
identityPoolId,
});
const s3Client = new S3Client({ credentials, region });
const rekognitionClient = new RekognitionClient({ credentials, region });
const sesClient = new SESClient({ credentials, region });
/**
* Update the info text box.
* @param {string} info
*/
const updateInfo = (info = "") => {
const infoEl = document.getElementById("info");
infoEl.innerText = info;
};
// Load images from Amazon S3 bucket to the table.
const loadTable = async () => {
try {
updateInfo();
const { Contents } = await s3Client.send(
new ListObjectsCommand({ Bucket: imagesBucketName }),
);
/** @type { HTMLUListElement | null } */
const imageList = document.getElementById("image-list");
if (imageList) {
imageList.innerHTML = "";
for (const content of Contents) {
const li = document.createElement("li");
const textNode = document.createTextNode(
`${content.Key} (${Math.ceil(content.Size / 1024)}KiB)`,
);
li.append(textNode);
imageList.append(li);
}
} else {
throw new Error("Could not find element.");
}
} catch (caught) {
if (caught instanceof Error) {
const errMessage = `Error listing S3 objects. ${caught.name}: ${caught.message}`;
console.error(errMessage);
updateInfo(errMessage);
} else {
throw caught;
}
}
};
window.addToBucket = async () => {
try {
/** @type { HTMLInputElement } */
const fileInput = document.getElementById("input-image");
const file = fileInput.files[0];
await s3Client.send(
new PutObjectCommand({
Bucket: imagesBucketName,
Body: file,
Key: file.name,
}),
);
loadTable();
updateInfo(`${file.name} added to ${imagesBucketName}.`);
} catch (caught) {
if (caught instanceof Error) {
const errMessage = `Error putting object in bucket. ${caught.name}: ${caught.message}`;
console.error(errMessage);
updateInfo(errMessage);
} else {
throw caught;
}
}
return false;
};
window.processImages = async () => {
try {
updateInfo("");
const listPhotosParams = {
Bucket: imagesBucketName,
};
// Retrieve list of objects in the Amazon S3 bucket.
const { Contents } = await s3Client.send(
new ListObjectsCommand(listPhotosParams),
);
// Loop through images. For each image, retrieve the image name,
// then analyze image by detecting it's labels, then parse results
// into CSV format.
for (const content of Contents) {
const imageName = content.Key;
const { Labels } = await rekognitionClient.send(
new DetectLabelsCommand({
Image: {
S3Object: {
Bucket: imagesBucketName,
Name: imageName,
},
},
}),
);
/** @type {string[][]} */
const analysis = [];
// Parse results into CVS format.
for (const label of Labels) {
analysis.push([label.Name, label.Confidence]);
}
// Create a CSV file report for each images.
createCsv({
headers: ["Object", "Confidence"],
rows: analysis,
name: imageName,
});
}
} catch (caught) {
if (caught instanceof Error) {
const errMessage = `Error analyzing images. ${caught.name}: ${caught.message}`;
console.error(errMessage);
updateInfo(errMessage);
} else {
throw caught;
}
}
return false;
};
/**
* Process a list of rows into a CSV string and upload to S3 bucket.
* @param {{ headers: string[], rows: string[][], name: string }}
*/
const createCsv = async ({ headers, rows, name }) => {
const csv = `${headers.join(",")}\n${rows.map((row) => row.join(",")).join("\n")}`;
await uploadFile(csv, name);
};
// Helper function to upload reports to Amazon S3 bucket for reports.
const uploadFile = async (csv, key) => {
try {
await s3Client.send(
new PutObjectCommand({
Bucket: reportsBucketName,
Body: csv,
Key: `${key}.csv`,
}),
);
const region = await s3Client.config.region();
const linkToCSV = `https://s3.console.aws.amazon.com/s3/object/${reportsBucketName}?region=${region}&prefix=${key}.csv`;
// Send an email to notify the user when report is available.
sendEmail(`${key}.csv`, linkToCSV);
} catch (caught) {
if (caught instanceof Error) {
const errMessage = `Error uploading CSV. ${caught.name}: ${caught.message}`;
updateInfo(errMessage);
console.error(errMessage);
} else {
throw caught;
}
}
};
// Helper function to send an email to the user.
const sendEmail = async (key, linkToCSV) => {
const toEmail = document.getElementById("email").value;
const fromEmail = email;
try {
// Set the parameters.
const params = {
Destination: {
/* required */
CcAddresses: [
/* Insert Cc email addresses here. */
],
ToAddresses: [
toEmail, //RECEIVER_ADDRESS
/* Insert additional email addresses here.. */
],
},
Message: {
/* required */
Body: {
/* required */
Html: {
Charset: "UTF-8",
Data: `<h1>Hello!</h1><p>Please see the the analyzed video report for ${key} <a href=${linkToCSV}> here</a></p>`,
},
Text: {
Charset: "UTF-8",
Data: `Hello,\\r\\nPlease see the attached file for the analyzed video report at${linkToCSV}\n\n`,
},
},
Subject: {
Charset: "UTF-8",
Data: `${key} analyzed video report ready`,
},
},
Source: fromEmail, // SENDER_ADDRESS
ReplyToAddresses: [
/* more items */
],
};
const data = await sesClient.send(new SendEmailCommand(params));
console.log("Email sent.", data);
} catch (caught) {
if (caught instanceof Error) {
const errMessage = `Error sending email. ${caught.name}: ${caught.message}`;
console.error(errMessage);
updateInfo(errMessage);
} else {
throw caught;
}
}
};
window.addEventListener("load", () => {
loadTable();
});