### Run Web UI Development Server Source: https://github.com/aws-samples/amazon-rekognition-virtual-proctor/blob/master/CONTRIBUTING.md Starts the web UI development server with hot reloading enabled. Edit files in `src/web-ui` to make changes. ```bash npm start ``` -------------------------------- ### Run Web UI Locally Source: https://context7.com/aws-samples/amazon-rekognition-virtual-proctor/llms.txt Sets up the local development environment for the web UI. After deploying the CloudFormation stack, download 'settings.js' and start the development server. This allows local testing against the live AWS backend. ```bash # 1. Install dependencies npm install # 2. Deploy the stack first to get real AWS endpoints # (see CloudFormation Deployment above) # 3. Download the generated settings.js from the deployed S3 bucket STACK_URL=$(aws cloudformation describe-stacks \ --stack-name VirtualProctor \ --query "Stacks[0].Outputs[?OutputKey=='url'].OutputValue" \ --output text) curl "${STACK_URL}/settings.js" -o src/web-ui/public/settings.js # 4. Start the dev server with hot reload npm start # Browser opens at http://localhost:3000 # 5. Build and package for custom deployment npm run build ``` -------------------------------- ### Upload Custom Frontend and Deploy with Overrides Source: https://context7.com/aws-samples/amazon-rekognition-virtual-proctor/llms.txt Use these commands to upload your custom frontend assets to an S3 bucket and then deploy the CloudFormation stack, specifying custom parameters like the admin email and a pre-built artifacts bucket override. Ensure you have the AWS CLI and npm installed and configured. ```bash CFN_BUCKET=my-staging-bucket npm run upload-custom-bucket CFN_BUCKET=my-staging-bucket npm run cfn-package aws cloudformation deploy \ --template-file templates/packaged.yaml \ --stack-name VirtualProctorCustom \ --capabilities CAPABILITY_IAM CAPABILITY_AUTO_EXPAND \ --parameter-overrides \ AdminEmail=admin@example.com \ PreBuiltArtefactsBucketOverride=my-staging-bucket ``` -------------------------------- ### Exponential Backoff Retry Utility (retryWrapper) Source: https://context7.com/aws-samples/amazon-rekognition-virtual-proctor/llms.txt Wraps Promise-returning functions with automatic retry logic, attempting up to 3 times with exponentially increasing delays starting at 1000ms. Useful for network requests. ```javascript // src/web-ui/src/utils/index.js const MAX_RETRIES = 3; const RETRY_START = 1000; export const retryWrapper = (p, timeout, retryN) => new Promise((resolve, reject) => p() .then(resolve) .catch((e) => { if (retryN === MAX_RETRIES) return reject(e); // Exhausted retries const t = (timeout || RETRY_START / 2) * 2; // 1000ms → 2000ms → 4000ms const r = (retryN || 0) + 1; console.log(`Retry n. ${r} in ${t / 1000}s...`); setTimeout(() => retryWrapper(p, t, r).then(resolve).catch(reject), t); }) ); // Usage: retryWrapper(() => fetch("/some-api").then(r => r.json())) .then(data => console.log(data)) .catch(err => console.error("All retries failed:", err)); ``` -------------------------------- ### Build Web UI for Deployment Source: https://github.com/aws-samples/amazon-rekognition-virtual-proctor/blob/master/CONTRIBUTING.md Compiles the web UI assets for deployment. This command should be run in the root of the repository. ```bash npm run build ``` -------------------------------- ### Upload Custom Web UI to S3 Bucket Source: https://github.com/aws-samples/amazon-rekognition-virtual-proctor/blob/master/CONTRIBUTING.md Uploads the packaged UI to a specified staging S3 bucket. Replace `` with your actual bucket name. ```bash CFN_BUCKET= npm run upload-custom-bucket ``` -------------------------------- ### Deploy Custom CloudFormation Stack Source: https://github.com/aws-samples/amazon-rekognition-virtual-proctor/blob/master/CONTRIBUTING.md Deploys the CloudFormation stack with the customized web UI. Ensure you specify parameters and override the pre-built artifacts bucket. Replace `` and `` with your actual values. ```bash aws cloudformation deploy --template-file ./templates/packaged.yaml --stack-name VirtualProctorEdited --capabilities CAPABILITY_IAM CAPABILITY_AUTO_EXPAND --parameter-overrides PreBuiltArtefactsBucketOverride= AdminEmail= ``` -------------------------------- ### Package CloudFormation Template Source: https://github.com/aws-samples/amazon-rekognition-virtual-proctor/blob/master/CONTRIBUTING.md Packages the CloudFormation template, creating a `cfn/packaged.yaml` file ready for deployment. Replace `` with your actual bucket name. ```bash CFN_BUCKET= npm run cfn-package ``` -------------------------------- ### Frontend Configuration Writer (writeSettings) Source: https://context7.com/aws-samples/amazon-rekognition-virtual-proctor/llms.txt Generates the settings.js file for the React app, embedding Cognito and API Gateway details. This file is written directly to the S3 web UI bucket. ```javascript // src/functions/setup/s3-handler.js — writeSettings writeSettings: () => s3.putObject({ ACL: "private", // or "public-read" when CloudFront is disabled Bucket: process.env.TO_BUCKET, Key: "settings.js", Body: `window.rekognitionSettings = ${JSON.stringify({ apiGateway: process.env.API_GATEWAY, // e.g., "https://xyz.execute-api.eu-west-1.amazonaws.com/Prod/" cognitoIdentityPool: process.env.COGNITO_IDENTITY_POOL, // e.g., "eu-west-1:xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx" cognitoUserPoolId: process.env.COGNITO_USERPOOL_ID, // e.g., "eu-west-1_XXXXXXXXX" cognitoUserPoolClientId:process.env.COGNITO_USERPOOLCLIENT_ID, region: process.env.REGION, // e.g., "eu-west-1" })};`, }).promise(), ``` -------------------------------- ### API Client Gateway (addUser, processImage) Source: https://context7.com/aws-samples/amazon-rekognition-virtual-proctor/llms.txt Wraps API calls using AWS Amplify for request signing and includes a retry mechanism. Use addUser to register faces and processImage to analyze webcam frames. ```javascript // src/web-ui/src/utils/gateway.js import request from "./request"; const gateway = { // Register a new test-taker face addUser(params) { // params: { image: "", fullName: "Jane Doe" } return request("/faces/index", "post", { image: params.image, fullName: params.fullName, }); // Returns: { ExternalImageId: "uuid-string" } }, // Analyze a single webcam frame processImage(image) { // image: base64-encoded JPEG string (no data URI prefix) return request("/process", "post", { image }); // Returns: Array of 4 test result objects }, }; // Usage in React component: const b64Frame = webcamRef.current.getScreenshot().split(",")[1]; gateway.processImage(b64Frame).then((results) => { // results = [ // { TestName: "Objects of Interest", Success: true, Details: "0" }, // { TestName: "Person Detection", Success: true, Details: 1 }, // { TestName: "Person Recognition", Success: true, Details: "Jane Doe" }, // { TestName: "Unsafe Content", Success: true, Details: "0" }, // ] setTestResults(results); }); ``` -------------------------------- ### Deploy CloudFormation Stack Source: https://context7.com/aws-samples/amazon-rekognition-virtual-proctor/llms.txt Deploys the full application infrastructure using AWS CloudFormation. This includes API Gateway, Lambda, Cognito, DynamoDB, S3, and optionally CloudFront. Ensure you have the AWS CLI configured. ```bash # Deploy via AWS CLI aws cloudformation deploy \ --template-file templates/packaged.yaml \ --stack-name VirtualProctor \ --capabilities CAPABILITY_IAM CAPABILITY_AUTO_EXPAND \ --parameter-overrides \ AdminEmail=admin@example.com \ MinConfidence=85 \ ObjectsOfInterestLabels="Mobile Phone,Cell Phone" \ CreateCloudFrontDistribution=true \ ResourcePrefix=VirtualProctor # Get the application URL from stack outputs aws cloudformation describe-stacks \ --stack-name VirtualProctor \ --query "Stacks[0].Outputs[?OutputKey=='url'].OutputValue" \ --output text # e.g., https://d1234abcd.cloudfront.net # Remove the stack and all resources aws cloudformation delete-stack --stack-name VirtualProctor ``` -------------------------------- ### Analyze a Webcam Frame Source: https://context7.com/aws-samples/amazon-rekognition-virtual-proctor/llms.txt Accepts a single base64-encoded JPEG frame and runs four Rekognition checks in parallel: object-of-interest detection, person count, face matching against the indexed collection, and unsafe content moderation. Returns an array of test result objects, each with `TestName`, `Success` (boolean), and `Details` (string). ```APIDOC ## POST /process — Analyze a Webcam Frame ### Description Accepts a single base64-encoded JPEG frame and runs four Rekognition checks in parallel: object-of-interest detection, person count, face matching against the indexed collection, and unsafe content moderation. Returns an array of test result objects, each with `TestName`, `Success` (boolean), and `Details` (string). ### Method POST ### Endpoint /process ### Parameters #### Request Body - **image** (string) - Required - The base64-encoded JPEG frame from the webcam. ### Request Example ```bash IMAGE_B64=$(base64 -i /path/to/frame.jpg) AUTH_TOKEN="" API_URL="https://.execute-api..amazonaws.com/Prod" curl -X POST "${API_URL}/process" \ -H "Content-Type: application/json" \ -H "Authorization: Bearer ${AUTH_TOKEN}" \ -d "{\"image\": \"${IMAGE_B64}\"}" ``` ### Response #### Success Response (200) - An array of test result objects. - **TestName** (string) - The name of the test performed (e.g., "Objects of Interest"). - **Success** (boolean) - Indicates if the test passed. - **Details** (string) - Additional details about the test result. #### Response Example ```json [ {"TestName": "Objects of Interest", "Success": true, "Details": "0"}, {"TestName": "Person Detection", "Success": true, "Details": 1}, {"TestName": "Person Recognition", "Success": true, "Details": "Jane Doe"}, {"TestName": "Unsafe Content", "Success": false, "Details": "Explicit Nudity, Violence"} ] ``` ``` -------------------------------- ### Python Index Face to Collection Source: https://context7.com/aws-samples/amazon-rekognition-virtual-proctor/llms.txt Indexes a face image into a Rekognition collection for searching. The collection must exist prior to execution. Requires 'media/face-index.jpeg'. ```python # python-samples/index-face.py import boto3, json COLLECTION_ID = "virtual-proctor-sample-collection" EXTERNAL_IMAGE_ID = "jane-doe-employee-id-123" # Your own identifier for this person with open("media/face-index.jpeg", "rb") as f: image_bytes = bytearray(f.read()) rekognition = boto3.client("rekognition") ``` -------------------------------- ### Python Compare Two Face Images Source: https://context7.com/aws-samples/amazon-rekognition-virtual-proctor/llms.txt Compares a source face image against a target image using the Rekognition compare_faces API. Requires 'media/image1.png' and 'media/image2.png', saves output to 'compare-faces.json'. ```python # python-samples/compare-faces.py import boto3, json with open("media/image1.png", "rb") as f: source_bytes = bytearray(f.read()) with open("media/image2.png", "rb") as f: target_bytes = bytearray(f.read()) rekognition = boto3.client("rekognition") response = rekognition.compare_faces( SourceImage={"Bytes": source_bytes}, TargetImage={"Bytes": target_bytes}, SimilarityThreshold=90, # Only return matches above 90% similarity QualityFilter="HIGH", ) for match in response["FaceMatches"]: print(f"Match similarity: {match['Similarity']:.1f}%") # e.g., "Match similarity: 97.3%" print(f"Unmatched faces in target: {len(response['UnmatchedFaces'])}") with open("compare-faces.json", "w") as f: json.dump(response, f) ``` -------------------------------- ### Python Detect Faces in Image Source: https://context7.com/aws-samples/amazon-rekognition-virtual-proctor/llms.txt Uses the Rekognition detect_faces API via boto3 to analyze facial attributes in a local image file. Requires 'media/face.png' and saves output to 'detect-faces.json'. ```python # python-samples/detect-faces.py import boto3, json with open("media/face.png", "rb") as f: image_bytes = bytearray(f.read()) rekognition = boto3.client("rekognition") response = rekognition.detect_faces( Image={"Bytes": image_bytes}, Attributes=["ALL"], # Optionally request detailed attributes (age, emotion, etc.) ) # response["FaceDetails"] is a list of detected faces for face in response["FaceDetails"]: print(f"Confidence: {face['Confidence']:.1f}%") print(f"BoundingBox: {face['BoundingBox']}") # e.g., {"Width": 0.23, "Height": 0.45, "Left": 0.31, "Top": 0.12} with open("detect-faces.json", "w") as f: json.dump(response, f) ``` -------------------------------- ### Search for a Face in Rekognition Collection Source: https://context7.com/aws-samples/amazon-rekognition-virtual-proctor/llms.txt Searches an existing Rekognition collection for faces matching a query image. Returns the top matching faces ranked by similarity. Set 'FaceMatchThreshold' to control the minimum similarity percentage required for a match. ```python # python-samples/search-faces.py import boto3, json COLLECTION_ID = "virtual-proctor-sample-collection" with open("media/face-search.jpeg", "rb") as f: image_bytes = bytearray(f.read()) rekognition = boto3.client("rekognition") response = rekognition.search_faces_by_image( CollectionId=COLLECTION_ID, Image={"Bytes": image_bytes}, MaxFaces=5, # Return up to 5 matches FaceMatchThreshold=95, # Only return results ≥95% similarity QualityFilter="HIGH", ) for match in response["FaceMatches"]: face = match["Face"] print(f"ExternalImageId: {face['ExternalImageId']}, Similarity: {match['Similarity']:.1f}%") # e.g., ExternalImageId: jane-doe-employee-id-123, Similarity: 98.2% with open("search-faces.json", "w") as f: json.dump(response, f) ``` -------------------------------- ### Analyze Webcam Frame with API Source: https://context7.com/aws-samples/amazon-rekognition-virtual-proctor/llms.txt This cURL command sends a base64-encoded JPEG frame to the API Gateway endpoint for real-time analysis. It triggers four Rekognition checks and returns the results. ```bash IMAGE_B64=$(base64 -i /path/to/frame.jpg) AUTH_TOKEN="" API_URL="https://.execute-api..amazonaws.com/Prod" curl -X POST "${API_URL}/process" \ -H "Content-Type: application/json" \ -H "Authorization: Bearer ${AUTH_TOKEN}" \ -d "{\"image\": \"${IMAGE_B64}\"}" ``` -------------------------------- ### Fetch Labels Lambda for Object & Person Detection Source: https://context7.com/aws-samples/amazon-rekognition-virtual-proctor/llms.txt This function detects people and objects of interest using `rekognition.detectLabels`. It checks for exactly one person and ensures no prohibited objects are present. The list of objects to watch is configurable via an environment variable. ```javascript const fetchLabels = async (imageBytes) => { const objectsOfInterestLabels = process.env.OBJECTS_OF_INTEREST_LABELS.trim().split(","); // e.g., ["Mobile Phone", "Cell Phone"] const labels = await rekognition.detectLabels({ Image: { Bytes: imageBytes }, MinConfidence: process.env.MIN_CONFIDENCE, // e.g., 85 }).promise(); // Person count check const people = labels.Labels.find((x) => x.Name === "Person"); const nPeople = people ? people.Instances.length : 0; const peopleTest = { TestName: "Person Detection", Success: nPeople === 1, Details: nPeople }; // Object-of-interest check const objectsOfInterest = labels.Labels.filter((x) => objectsOfInterestLabels.includes(x.Name)); const objectsOfInterestTest = { TestName: "Objects of Interest", Success: objectsOfInterest.length === 0, Details: objectsOfInterest.length === 0 ? "0" : objectsOfInterest.map((x) => x.Name).sort().join(", "), // e.g., "Cell Phone, Mobile Phone" }; return [objectsOfInterestTest, peopleTest]; }; ``` -------------------------------- ### Process Handler Lambda for Multi-Check Image Analysis Source: https://context7.com/aws-samples/amazon-rekognition-virtual-proctor/llms.txt This function orchestrates concurrent image analysis using four Rekognition checks. It expects a base64 encoded JPEG image in the POST body and returns a combined array of test results. ```javascript // src/functions/proctor/index.js exports.processHandler = async (event) => { const body = JSON.parse(event.body); const imageBytes = Buffer.from(body.image, "base64"); // All four checks run in parallel const result = await Promise.all([ fetchLabels(imageBytes), searchForIndexedFaces(imageBytes), fetchFaces(imageBytes), fetchModerationLabels(imageBytes), ]); // result.flat() merges the nested array from fetchLabels return { statusCode: 200, body: JSON.stringify(result.flat()), headers: { "Access-Control-Allow-Origin": "*", "Content-Type": "application/json" }, }; }; ``` -------------------------------- ### Fetch Faces Lambda for Face Count Detection Source: https://context7.com/aws-samples/amazon-rekognition-virtual-proctor/llms.txt This function uses `rekognition.detectFaces` to count faces in an image. The proctoring test passes only if exactly one face is detected. ```javascript const fetchFaces = async (imageBytes) => { const faces = await rekognition.detectFaces({ Image: { Bytes: imageBytes }, }).promise(); const nFaces = faces.FaceDetails.length; return { TestName: "Face Detection", Success: nFaces === 1, // Pass only if exactly 1 face Details: nFaces, // Raw count for display }; }; ``` -------------------------------- ### Register Test-Taker Face with API Source: https://context7.com/aws-samples/amazon-rekognition-virtual-proctor/llms.txt Use this cURL command to encode a face image to base64 and call the deployed API Gateway endpoint to register a test-taker. Ensure you replace placeholders for the API URL, region, and Cognito JWT token. ```bash # Encode an image to base64 and call the deployed API Gateway endpoint IMAGE_B64=$(base64 -i /path/to/face.jpg) AUTH_TOKEN="" API_URL="https://.execute-api..amazonaws.com/Prod" curl -X POST "${API_URL}/faces/index" \ -H "Content-Type: application/json" \ -H "Authorization: Bearer ${AUTH_TOKEN}" \ -d "{\"fullName\": \"Jane Doe\", \"image\": \"${IMAGE_B64}\"}" ``` -------------------------------- ### CloudFormation Custom Resource Lambda Source: https://context7.com/aws-samples/amazon-rekognition-virtual-proctor/llms.txt This Lambda function handles stack creation and deletion events for CloudFormation. It copies frontend files, writes configuration, and manages Rekognition collections. ```javascript // src/functions/setup/index.js exports.handler = (event, context, callback) => { const eventType = event.RequestType; // "Create" | "Delete" | "Update" let actions; if (eventType === "Create") { actions = [ copyFiles(), // Unzip frontend.zip from source bucket to WebUIBucket writeSettings(), // Write settings.js with API Gateway / Cognito config createCollection(), // Create Rekognition face collection ]; } else if (eventType === "Delete") { actions = [ removeFiles(), // Empty the WebUIBucket deleteCollection(), // Delete Rekognition face collection ]; } Promise.all(actions) .then(() => sendResponse("SUCCESS", { Message: `Resources successfully ${eventType.toLowerCase()}d` })) .catch((err) => sendResponse("FAILED")); }; ``` -------------------------------- ### React Webcam Proctoring Loop Source: https://context7.com/aws-samples/amazon-rekognition-virtual-proctor/llms.txt Manages webcam capture, polling, and authentication state in a React application. Captures JPEG frames and sends them to the API for analysis. ```jsx // src/web-ui/src/App.js (simplified) import Webcam from "react-webcam"; import gateway from "./utils/gateway"; const App = () => { const webcam = useRef(undefined); const iterating = useRef(false); const [testResults, setTestResults] = useState([]); const getSnapshot = () => { const image = webcam.current.getScreenshot(); // Returns data URI: "data:image/jpeg;base64,..." const b64Encoded = image.split(",")[1]; // Strip prefix → raw base64 gateway.processImage(b64Encoded).then((response) => { if (response) setTestResults(response); if (iterating.current) setTimeout(getSnapshot, 300); // Poll every 300ms else setTestResults([]); }); }; const toggleRekognition = () => { iterating.current = !iterating.current; if (iterating.current) getSnapshot(); else setTestResults([]); }; return ( <> {/* RekognitionButton calls toggleRekognition on click */} ); }; ``` -------------------------------- ### Fetch Moderation Labels Lambda for Unsafe Content Detection Source: https://context7.com/aws-samples/amazon-rekognition-virtual-proctor/llms.txt This function uses `rekognition.detectModerationLabels` to identify explicit or unsafe content. The test passes if no moderation labels are detected above the specified confidence threshold. ```javascript const fetchModerationLabels = async (imageBytes) => { const labels = await rekognition.detectModerationLabels({ Image: { Bytes: imageBytes }, MinConfidence: process.env.MIN_CONFIDENCE, // e.g., 85 }).promise(); const nLabels = labels.ModerationLabels.length; return { TestName: "Unsafe Content", Success: nLabels === 0, Details: nLabels === 0 ? "0" : labels.ModerationLabels.map((l) => l.Name).sort().join(", "), // e.g., "Explicit Nudity, Violence" }; }; ``` -------------------------------- ### React Engagement Summary Component Source: https://context7.com/aws-samples/amazon-rekognition-virtual-proctor/llms.txt Renders test results as Bootstrap Cards, displaying pass/fail icons, test names, and details. Requires testResults prop to be an array of objects. ```jsx // src/web-ui/src/components/EngagementsSummary.js import { Card } from "react-bootstrap"; import Icon from "./Icon"; const EngagementsSummary = ({ testResults }) => (
{testResults.map((test, index) => ( {test.TestName} {/* e.g., "✓ Person Detection" or "✗ Objects of Interest" */} {test.Details} {/* e.g., Details: 1 (person count) or "Cell Phone" (detected object) */} ))}
); // testResults shape: // [ // { TestName: "Objects of Interest", Success: true, Details: "0" }, // { TestName: "Person Detection", Success: false, Details: 2 }, // { TestName: "Person Recognition", Success: true, Details: "Jane Doe" }, // { TestName: "Unsafe Content", Success: true, Details: "0" }, // ] ``` -------------------------------- ### Face Indexing Lambda Function Source: https://context7.com/aws-samples/amazon-rekognition-virtual-proctor/llms.txt The `indexHandler` Lambda function registers a face into Amazon Rekognition and stores associated metadata in DynamoDB. It requires `COLLECTION_ID` and `FACES_TABLENAME` environment variables. ```javascript // src/functions/proctor/index.js const AWS = require("aws-sdk"); const uuid = require("uuid").v4; const rekognition = new AWS.Rekognition({ region: process.env.REGION }); const dynamo = new AWS.DynamoDB({ region: process.env.REGION }); exports.indexHandler = async (event) => { const ExternalImageId = uuid(); const body = JSON.parse(event.body); // { image: "", fullName: "Jane Doe" } // Step 1: Index the face into the Rekognition collection await rekognition.indexFaces({ CollectionId: process.env.COLLECTION_ID, ExternalImageId, Image: { Bytes: Buffer.from(body.image, "base64") }, }).promise(); // Step 2: Persist name metadata to DynamoDB await dynamo.putItem({ TableName: process.env.FACES_TABLENAME, Item: { CollectionId: { S: process.env.COLLECTION_ID }, ExternalImageId: { S: ExternalImageId }, FullName: { S: body.fullName }, }, }).promise(); return { statusCode: 200, body: JSON.stringify({ ExternalImageId }), headers: { "Access-Control-Allow-Origin": "*", "Content-Type": "application/json" }, }; }; ``` -------------------------------- ### Index Faces in Rekognition Collection Source: https://context7.com/aws-samples/amazon-rekognition-virtual-proctor/llms.txt Indexes a face from an image into a specified Rekognition collection. Ensure the collection exists before indexing. The 'ExternalImageId' is stored with the face vector for later retrieval. ```python response = rekognition.index_faces( CollectionId=COLLECTION_ID, Image={"Bytes": image_bytes}, ExternalImageId=EXTERNAL_IMAGE_ID, # Stored alongside the face vector MaxFaces=1, QualityFilter="HIGH", ) for face_record in response["FaceRecords"]: print(f"FaceId: {face_record['Face']['FaceId']}") print(f"ExternalImageId: {face_record['Face']['ExternalImageId']}") # e.g., ExternalImageId: jane-doe-employee-id-123 with open("index-faces.json", "w") as f: json.dump(response, f) ``` -------------------------------- ### Search For Indexed Faces Lambda for Face Identity Matching Source: https://context7.com/aws-samples/amazon-rekognition-virtual-proctor/llms.txt This function uses `rekognition.searchFacesByImage` to compare a face against a Rekognition collection and retrieves the matched person's name from DynamoDB. It handles cases where no faces match by returning a failure. ```javascript const searchForIndexedFaces = async (imageBytes) => { try { const faces = await rekognition.searchFacesByImage({ CollectionId: process.env.COLLECTION_ID, FaceMatchThreshold: process.env.MIN_CONFIDENCE, // e.g., 85 MaxFaces: 1, Image: { Bytes: imageBytes }, }).promise(); const faceDetails = await dynamo.getItem({ TableName: process.env.FACES_TABLENAME, Key: { ExternalImageId: { S: faces.FaceMatches[0].Face.ExternalImageId } }, }).promise(); return { TestName: "Person Recognition", Success: !!faceDetails.Item, Details: faceDetails.Item?.FullName.S || "0", // e.g., "Jane Doe" }; } catch (e) { // rekognition.searchFacesByImage throws when 0 faces match return { TestName: "Person Recognition", Success: false, Details: "0" }; } }; ``` -------------------------------- ### Register a Test-Taker's Face Source: https://context7.com/aws-samples/amazon-rekognition-virtual-proctor/llms.txt Indexes a base64-encoded face image into the Rekognition collection and stores the user's full name in DynamoDB. Returns the generated `ExternalImageId` that links the Rekognition face record to the user's metadata. ```APIDOC ## POST /faces/index — Register a Test-Taker's Face ### Description Indexes a base64-encoded face image into the Rekognition collection and stores the user's full name in DynamoDB. Returns the generated `ExternalImageId` that links the Rekognition face record to the user's metadata. ### Method POST ### Endpoint /faces/index ### Parameters #### Request Body - **fullName** (string) - Required - The full name of the test-taker. - **image** (string) - Required - The base64-encoded face image. ### Request Example ```bash IMAGE_B64=$(base64 -i /path/to/face.jpg) AUTH_TOKEN="" API_URL="https://.execute-api..amazonaws.com/Prod" curl -X POST "${API_URL}/faces/index" \ -H "Content-Type: application/json" \ -H "Authorization: Bearer ${AUTH_TOKEN}" \ -d "{\"fullName\": \"Jane Doe\", \"image\": \"${IMAGE_B64}\"}" ``` ### Response #### Success Response (200) - **ExternalImageId** (string) - The unique identifier linking the Rekognition face record to user metadata. #### Response Example ```json { "ExternalImageId": "a3f1c2d4-5678-90ab-cdef-1234567890ab" } ``` #### Error Response (500) - **error** (object) - Contains error code and message. - **code** (string) - The error code (e.g., `InvalidImageFormatException`). - **message** (string) - A description of the error. ``` ``` === COMPLETE CONTENT === This response contains all available snippets from this library. No additional content exists. Do not make further requests.