1 Answer
- Newest
- Most votes
- Most comments
0
import { S3Client, GetObjectCommand } from "@aws-sdk/client-s3";
import { RekognitionClient, StartFaceLivenessSessionCommand } from "@aws-sdk/client-rekognitionstreaming";
import { Readable } from "stream";
import ffmpeg from "fluent-ffmpeg";
// AWS SDK configuration
const awsConfig = {
region: "us-east-1",
credentials: {
accessKeyId: process.env.accessKeyId, // Use environment variables for security
secretAccessKey: process.env.secretAccessKey, // Use environment variables for security
},
};
// Initialize AWS clients
const s3Client = new S3Client({ region: awsConfig.region });
const rekognitionClient = new RekognitionClient(awsConfig);
// Utility to buffer the stream from S3
async function bufferToStream(stream) {
return new Promise((resolve, reject) => {
const chunks = [];
stream.on("data", (chunk) => chunks.push(chunk));
stream.on("error", reject);
stream.on("end", () => resolve(Buffer.concat(chunks)));
});
}
// Get video file from S3
async function getFileFromS3(bucketName, objectKey) {
const params = {
Bucket: bucketName,
Key: objectKey,
};
try {
const data = await s3Client.send(new GetObjectCommand(params));
const fileBuffer = await bufferToStream(data.Body);
console.log(`Buffer size: ${fileBuffer.length} bytes`);
return fileBuffer;
} catch (error) {
console.error("Error getting file from S3:", error);
throw error;
}
}
// Generate chunks from video buffer
function generateChunks(buffer, chunkSize = 1024 * 1024) {
const chunks = [];
let offset = 0;
while (offset < buffer.length) {
const chunk = buffer.slice(offset, offset + chunkSize);
chunks.push({
VideoEvent: {
VideoChunk: Buffer.from(chunk).toString("base64"), // Ensure the chunk is Base64 encoded
TimestampMillis: Date.now(),
},
});
offset += chunkSize;
}
return chunks;
}
// Main function to start liveness check
async function startLivenessCheck() {
try {
const bucketName = "myBucketName";
const objectKey = "myObjectKey";
console.log("Fetching video file from S3...");
const fileBuffer = await getFileFromS3(bucketName, objectKey);
console.log("Creating liveness session...");
const createInput = {
Settings: {
OutputConfig: {
S3Bucket: bucketName,
S3KeyPrefix: objectKey,
},
AuditImagesLimit: 4,
},
ClientRequestToken: Date.now().toString(),
};
const createCommand = new StartFaceLivenessSessionCommand(createInput);
const createResponse = await rekognitionClient.send(createCommand);
console.log("Liveness session created. SessionId:", createResponse.SessionId);
console.log("Generating video chunks...");
const chunks = generateChunks(fileBuffer, 1024 * 1024);
console.log(`Generated ${chunks.length} chunks`);
// Event streaming generator function
const livenessStream = async function* () {
for (const chunk of chunks) {
const videoEvent = chunk.VideoEvent;
// Ensure valid JSON structure for the chunk
console.log("Sending chunk:", JSON.stringify({ VideoEvent: videoEvent }, null, 2));
yield { VideoEvent: videoEvent };
await new Promise((resolve) => setTimeout(resolve, 100)); // Simulate streaming delay
}
};
console.log("Starting liveness session...");
const startInput = {
SessionId: createResponse.SessionId,
VideoWidth: 480,
VideoHeight: 850,
ChallengeVersions: "challenge_1.0.0",
LivenessRequestStream: livenessStream(),
};
const rekognitionStreamingClient = new RekognitionStreamingClient(awsConfig);
const startCommand = new StartFaceLivenessSessionCommand(startInput);
const startResponse = await rekognitionStreamingClient.send(startCommand);
console.log("Liveness session started successfully:", startResponse);
if (startResponse.LivenessResponseStream) {
for await (const event of startResponse.LivenessResponseStream) {
console.log("Event received:", event);
}
}
} catch (error) {
console.error("Error during liveness session:", error);
if (error.$responseBodyText) {
console.log("Raw response body:", error.$responseBodyText);
}
}
}
startLivenessCheck();
Relevant content
asked 4 years ago
asked 2 years ago
- AWS OFFICIALUpdated 3 years ago
