Code Monkey home page Code Monkey logo

brain-power / brain-power-amazon-fidgetology Goto Github PK

View Code? Open in Web Editor NEW
103.0 9.0 45.0 124.54 MB

Serverless web app for streaming browser webcam feed to Amazon Kinesis Video Streams and Rekognition Video. See our post on the AWS Machine Learning Blog: https://aws.amazon.com/blogs/machine-learning/building-automatic-analysis-of-body-language-to-gauge-attention-and-engagement-using-amazon-kinesis-video-streams-and-amazon-ai-services

License: Apache License 2.0

CSS 0.01% HTML 0.32% JavaScript 99.39% Shell 0.09% Java 0.19%
serverless-applications serverless-deployments face-detection-application aws-cloudformation aws-lambda amazon-rekognition kinesis-video-streams rekognition-video

brain-power-amazon-fidgetology's Introduction

Brain-Power-Amazon-Fidgetology

Repository for demo app + code artifacts associated with Brain Power fidgetology post on AWS Machine Learning Blog.

Overview

This is a serverless web application for streaming webcam feed from a browser to Amazon Kinesis Video Streams and Amazon Rekognition Video. Body motion metrics can be then be visualized in web app with minimal delay.

AWS Technologies used:

  • Kinesis Video Streams
  • Rekognition Video
  • Kinesis Data Streams
  • API Gateway
  • Lambda
  • S3
  • CloudFormation

Components

Web Dashboard App

The client dashboard app allows users to 1) upload pre-recorded video and 2) stream a webcam feed to Amazon Kinesis Video Streams, and visualize the resulting face motion metrics computed by Amazon Rekognition Video in near real-time. For details on how client-side streaming works and tools used to build the web app, see the dashboard app-specific documentation.

Uploading a Video

Streaming Video from a Webcam

(*Faces censored)

Browser Support

The webcam streaming functionality (backed by WebRTC getUserMedia API) has been tested on the following combinations of browsers and platforms. Most notably, it currently works on the latest version of all major browsers and platforms, with the exception of iOS mobile browsers.

Platform Browser Notes
Windows Chrome 30+ Works
Windows Firefox 20+ Works
Windows Edge (latest) Works
Windows IE 9+ Requires Adobe Flash Player
Mac OS X Chrome 30+ Works
Mac OS X Firefox 20+ Works
Mac OS X Safari 6+ Requires Adobe Flash Player
Android Chrome (latest) Works
Android Native browser Doesn't Work
iOS Safari/Chrome Doesn't Work

Stream Conversion

When static video or buffered webcam frames are uploaded in the web app, a Lambda function converts them to streamable MKV files (currently, MKV is the only file container supported by Kinesis Video Stream).

  • If the source is a static video upload, then the lambda/MKVConverter function is triggered directly by an S3 upload event. An FFmpeg subprocess is used for file conversion.

  • If the source is a sequence of buffered webcam frames, the browser client posts frame data to an API Gateway - Lambda Proxy endpoint, triggering the lambda/WebApi/frame-converter function. This function uses FFmpeg to construct a short MKV fragment out of the image frame sequence. For details on how this API request is executed, see the function-specific documentation.

In both cases, converted MKV files are archived in an S3 bucket, triggering the next step in the pipeline.

Kinesis Video Stream

An MKV file upload event triggers the lambda/S3ToKVS function, which uses the Kinesis Video Stream Producer SDK for Java to put the media fragments into a Kinesis Video Stream.

Below is a side-by-side illustration of webcam streaming to the Kinesis Video Streams online console. The lag between the live webcam app feed (left) and the time these frames are played back on the KVS console (right) is about 5 seconds (though this may vary depending on browser/platform/specs of your machine).



To decrease the lag, you can experiment with adjusting the No. Frames to Buffer parameter using the form input below the live webcam feed. Beware that specifying too low of a buffer size may cause KVS to receive frames out-of-order.

Misc KVS Notes

Note 1: Currently, Kinesis Video Stream Producer SDK is only available in Java/C++, so this step could not be merged with the previous stream conversion step, which runs in a Node.js container for consistently fast startup time. If a KVS Producer SDK becomes available in Node.js/Python, then this step should just be merged with the previous step (as a single Lambda execution) to avoid the needless latency of using S3 as a file transfer proxy between different Lambda containers. While a viable alternative is to do the previous stream conversion step in Java as well, the faster startup times and smaller deployment packages associated with Node.js make it more suitable for this demo. One could definitely explore re-factoring all the serverless Lambda functions in Java to see if it improves performance.

Note 2: To simplify the build process, we do not include the entire Java project associated with this S3ToKVS function. We only include the compiled, deploy-ready .jar package, and the main LambdaFunctionHandler.java file to demonstrate usage of the putMedia operation with the Java KVS Producer SDK. However, if you want modify the Lambda function handler for your own use, you must follow instructions to create a Lambda deployment package for Java, which involves using Maven/Eclipse, greatly complicating the build process. All in all, until a KVS Producer SDK becomes available in Node.js/Python, there is not an easy workaround.

Note 3: Another route is to abandon Serverless/Lambda and provision a custom AMI as a webRTC server that also handles stream conversion. This solution will probably yield the best performance and lowest latency, but is not in the spirit of this Serverless demo.

Rekognition Stream Processor

The Kinesis Video Stream is used as input to a Rekognition Stream Processor, that detects and recognizes faces in the video stream, and publishes raw records to a Kinesis Data Stream. See lambda/StreamResourceProvisioner for how these resources are provisioned.

Body Motion Analytics

The raw output of Rekognition Stream Processor is published to a Kinesis Data Stream. When new records appear in this raw stream, a Lambda function is triggered that computes interesting derived metrics on faces in successive video frames, such as the rotational/translational motion velocities. These processed metrics are then published to another Kinesis Data Stream, for consumption by downstream applications and web dashboards. See lambda/StreamAnalyzer for an example of how one might analyze the raw output of Rekognition Video.

Visualizing the Metrics

For this demo, the web app consumes body motion metrics directly from the processed Kinesis Data Stream and renders them as real-time updating chart visualizations.

Deploying

CloudFormation Deployment

There are two flavors of this project that can be deployed:

  • 'Full' version - expressed in template.yaml. Includes all components described in previous section.
  • 'Lite' version - expressed in template_lite.yaml. Only includes browser Webcam to Kinesis Video Streams component. Rekognition Video, Kinesis Data Streams, and demo analytics + visualizations are excluded for simplicity.

This project can be deployed using AWS CloudFormation as a Change Set for a New Stack (a serverless application transform must first be applied to the template.yaml definition).

Click the button to begin the stack creation process:

Full Version:

Lite Version:

Step 1. Click Next, and specify brain-power-fidgetology-demo as the Stack name. Accept all default parameters and click Next.



Step 2. Click Next again to get to the final Review page. Under Capabilities and transforms, confirm acknowledgement that new IAM resources will be created. Then click Create stack.



Step 3. Refresh the CloudFormation page to find your newly created stack. Click on it to monitor the deployment process, which should take no more than 3 minutes.



Step 4. After deployment is complete, launch the demo web app by visiting the WebAppSecureURL link listed under Outputs.



By default, the CloudFormation template creates all necessary AWS resources for this project (Kinesis Video Stream, Rekognition Stream Processor, Kinesis Data Streams, serverless Lambda functions, and an API Gateway endpoint). It copies the dashboard web application to an Amazon S3 bucket and outputs a secure URL (fronted by API Gateway) for accessing the web app.

Command Line Deployment

Prerequisites:

  • (For customized deployment) AWS-CLI installed. Ensure you have required permissions on your account (most notably: S3 bucket creation/deletion, full access to Rekognition and Kinesis Video Stream. Other resources launched in this project include: Lambda, API Gateway, Kinesis Data Stream)
  • (For local development only) Node.js (>= 10) installed.

The CloudFormation stack defined in template.yaml is expressed using the AWS Serverless Application Model. Review it for a description of the configuration options and AWS resource components. The template can be modified for a custom deployment.

From the command line, you can deploy all required AWS resources and demo web app in one go using the master deploy command:

./deploy_example.sh

Note: Currently deployment is supported only in regions where AWS Rekognition and Kinesis Video Stream services are both available (as of now, these are: us-east-1 or us-west-2). If your default AWS region is not supported, you must change your default region before executing the deploy command.

This command will:

  • Package code artifacts (Lambda function source files in the lambda/ directory and dashboard/ static files) and upload to a bootstrapping S3 bucket.
  • Generate a master-template.yaml CloudFormation template that is then deployed to your AWS account using AWS-CLI.
  • Configure the dashboard web app with required API routes, and upload static website files in the dashboard/ directory to be hosted from an S3 bucket.
  • Output the public URL of the demo web app hosted in the S3 bucket.

Usage

Running locally

If you deployed the stack using the command line, the web app can be tested locally. Please ensure you have Node.JS/NPM.

Before you run the local development server, you need to install the Node.js development dependencies with the command:

npm install

To start the HTTP server web on port 3000, issue the command:

# serves http://localhost:3000
npm start

Then navigate to http://localhost:3000 in your browser.

Tear down

If you launched the stack from the CloudFormation online console, simply delete the stack online.



If you deployed from the command line, run the master tear down command:

./delete_stack.sh

In both cases, this will tear down all AWS resources that were provisioned with the CloudFormation stack, delete all videos fragments that were uploaded/streamed using the web app, and delete the bucket hosting the web app.

Potential Improvements

  • See Misc KVS Notes for potential improvements to stream conversion-to-KVS flow.
  • Explore Kinesis Analytics for analyzing raw output of Rekognition stream processor, with unsupervised anomaly detection capabilities.
  • Expose an API Gateway endpoint for reading from the KDS of processed motion metrics, allowing web app to avoid consuming directly from the processed stream.
  • Modify StreamAnalyzer to allow for tracking of multiple faces/bodies in a feed.
  • Once Kinesis Video Stream and Rekognition Stream Processor become available as CloudFormation Resource Types, add them to the template definitions, removing the need for StreamResourceProvisioner Custom resource.

brain-power-amazon-fidgetology's People

Contributors

dependabot[bot] avatar natestraub avatar ozydingo avatar powerned avatar runpengl avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

brain-power-amazon-fidgetology's Issues

create failed?why?

The following resource(s) failed to create: [WebAPIRole, MKVConverterLambdaRole, WebAppBootstrapperLambdaRole, StreamResourceProvisionerLambdaRole, IdPool, WebAppBucket, RawDataStream, ProcessedDataStream, StreamAnalyzerRole, S3ToKVSLambdaRole, RekognitionServiceRole]. . Rollback requested by user.

index.handler is undefined or not exported

Hi,

I am seeing the following error in my API Gateway ""index.handler is undefined or not exported" as you can see below:

Fri Apr 17 18:23:22 UTC 2020 : Sending request to https://lambda.us-east-1.amazonaws.com/2015-03-31/functions/arn:aws:lambda:us-east-1:XXXXXXXXXXXX:function:brain-WebAPI-S7UEBDW371IM/invocations
Fri Apr 17 18:23:22 UTC 2020 : Received response. Status: 200, Integration latency: 154 ms
Fri Apr 17 18:23:22 UTC 2020 : Endpoint response headers: {Date=Fri, 17 Apr 2020 18:23:22 GMT, Content-Type=application/json, Content-Length=839, Connection=keep-alive, x-amzn-RequestId=037a86de-479d-4b74-80d1-1398aec85561, X-Amz-Function-Error=Unhandled, x-amzn-Remapped-Content-Length=0, X-Amz-Executed-Version=$LATEST, X-Amzn-Trace-Id=root=1-5abe31a-6ab7a3545768546468184;sampled=0}
Fri Apr 17 18:23:22 UTC 2020 : Endpoint response body before transformations: {"errorType":"Runtime.HandlerNotFound","errorMessage":"index.handler is undefined or not exported","trace":["Runtime.HandlerNotFound: index.handler is undefined or not exported"," at Object.module.exports.load (/var/runtime/UserFunction.js:144:11)"," at Object. (/var/runtime/index.js:45:30)"," at Module._compile (internal/modules/cjs/loader.js:778:30)"," at Object.Module._extensions..js (internal/modules/cjs/loader.js:789:10)"," at Module.load (internal/modules/cjs/loader.js:653:32)"," at tryModuleLoad (internal/modules/cjs/loader.js:593:12)"," at Function.Module._load (internal/modules/cjs/loader.js:585:3)"," at Function.Module.runMain (internal/modules/cjs/loader.js:831:12)"," at startup (internal/bootstrap/node.js:283:19)"," at bootstrapNodeJSCore (internal/bootstrap/node.js:623:3)"]}
Fri Apr 17 18:23:22 UTC 2020 : Lambda execution failed with status 200 due to customer function error: index.handler is undefined or not exported. Lambda request id: 187a86de-4acd-4124-80d1-13ca43565561
Fri Apr 17 18:23:22 UTC 2020 : Method completed with status: 502

I am wondering if you would be able to help?

Thanks!

include stream audio?

hello -
i've gone and included the 'audio:true' in the mediastream constraints, but nothing is coming thru the stream.

what should i do to include the audio?

ffmpeg is not working in lambda function

We have configured this solution in to our aws account.
Now we are getting an error "ENOENT: no such file or directory, lstat '/tmp/_1573629857064.mkv'" from the api gateway..

Error Stack Template is empty

@runpengl Hi mate, I was trying to stack this on cloud formation but I am getting an error stating "This template does not includes any resources to import" Kindly help me out please

Getting error related to ffmpeg

Hello, using the latest code we get the following sequence of errors:

ERROR (node:7) [DEP0005] DeprecationWarning: Buffer() is deprecated due to security and usability issues. Please use the Buffer.alloc(), Buffer.allocUnsafe(), or Buffer.from() methods instead.

INFO Executing... undefined -r 10 -f image2 -s 640x480 -i /tmp/53680642-frame-%03d.jpg -vcodec libx264 -crf 25 -pix_fmt yuv420p /tmp/_1587230228128.mkv

INFO Error with command: undefined -r 10 -f image2 -s 640x480 -i /tmp/53680642-frame-%03d.jpg -vcodec libx264 -crf 25 -pix_fmt yuv420p /tmp/_1587230228128.mkv { Error: Command failed: undefined -r 10 -f image2 -s 640x480 -i /tmp/53680642-frame-%03d.jpg -vcodec libx264 -crf 25 -pix_fmt yuv420p /tmp/_1587230228128.mkv
/bin/sh: undefined: command not found

It looks that ffmpeg cannot be found. Please advise. Would appreciate any help, Thanks!

Stack Launch Failed - AccessDenied for StreamResourceProvisioner

Lambda function for StreamResourceProvisioner fails with AccessDenied exception causing the stack to rollback.

Here are the cloudwatch logs for the same:
{ "Status": "FAILED", "Reason": "See the details in CloudWatch Log Stream: 2019/12/03/[$LATEST]1ac14ac3aa7f44ffb57ad60007206699", "PhysicalResourceId": "2019/12/03/[$LATEST]1ac14ac3aa7f44ffb57ad60007206699", "StackId": "arn:aws:cloudformation:ap-south-1:864043271127:stack/SmartAdEngine-20191203/edf72bb0-15c9-11ea-9a40-0a95c9550e3e", "RequestId": "aff3b66f-2753-4761-b7d2-25572b75b15c", "LogicalResourceId": "StreamResourceProvisioner", "Data": { "Error": { "message": null, "code": "AccessDeniedException", "time": "2019-12-03T12:40:35.844Z", "requestId": "355060ef-0e99-40a4-a046-0747cf2bac91", "statusCode": 400, "retryable": false, "retryDelay": 7.615761158881429 } } }

client upload error

PROBLEM
I can run locally per the instructions, and I see my video from the browser on localhost:3000, but the frames do not make it to KVS.

image

There are some errors about config.js that might be related.

image

STEPS TO REPRODUCE
Tested with Chrome on OSX and Nodejs 12.3.1.

  1. click the button to Launch the Stack for Full Version
  2. brew install ffmpeg
  3. git clone [email protected]:brain-power/Brain-Power-Amazon-Fidgetology.git
  4. cd Brain-Power-Amazon-Fidgetology; npm install; npm start
  5. open http://localhost:3000
  6. ./delete_stack.sh

403 Forbidden - MissingAuthenticationTokenException

Hi,

When I start the Stream Webcam from the client app I am seeing a 500 error when accessing the URL API Gateway: https://XXXXXX.execute-api.us-east-1.amazonaws.com/Prod/FrameData.

Details below:

HTTP/1.1 403 Forbidden
Date: Sat, 18 Apr 2020 07:50:55 GMT
Content-Type: application/json
Content-Length: 42
Connection: keep-alive
x-amzn-RequestId: c6a1d40c-8434-4be6-b923-5dba2fb3e34b
x-amzn-ErrorType: MissingAuthenticationTokenException
x-amz-apigw-id: LLCm7FonFiAFXFg=

Can you please help?

Thanks,

Joana.

Create New Streams with this Stack

I'm wondering how to create new streams via the KinesisVideo api with the same process and stack for the new stream. Is it possible to just create a new stream with this implementation already working? Does this make sense?

Thanks

Not able to launch the stack

I tried multiple times from the blog link and from the git, but I am not able to launch the stack.
Can you please help me out with this?

Issue launching stack

Hello!

I'm experiencing the following issue trying to launch the full stack:

2018-05-04T23:48:08.713Z	97cf58c6-4ff5-11e8-bd37-9728fc6a5980	{ ProvisionedThroughputExceededException: Provisioned rate exceeded
at Request.extractError (/var/runtime/node_modules/aws-sdk/lib/protocol/json.js:48:27)
at Request.callListeners (/var/runtime/node_modules/aws-sdk/lib/sequential_executor.js:105:20)
at Request.emit (/var/runtime/node_modules/aws-sdk/lib/sequential_executor.js:77:10)
at Request.emit (/var/runtime/node_modules/aws-sdk/lib/request.js:683:14)
at Request.transition (/var/runtime/node_modules/aws-sdk/lib/request.js:22:10)
at AcceptorStateMachine.runTo (/var/runtime/node_modules/aws-sdk/lib/state_machine.js:14:12)
at /var/runtime/node_modules/aws-sdk/lib/state_machine.js:26:10
at Request.<anonymous> (/var/runtime/node_modules/aws-sdk/lib/request.js:38:9)
at Request.<anonymous> (/var/runtime/node_modules/aws-sdk/lib/request.js:685:12)
at Request.callListeners (/var/runtime/node_modules/aws-sdk/lib/sequential_executor.js:115:18)
message: 'Provisioned rate exceeded',
code: 'ProvisionedThroughputExceededException',
time: 2018-05-04T23:48:08.712Z,
requestId: '98f75dc5-4ff5-11e8-873e-4996545812d4',
statusCode: 400,
retryable: true }

Any idea what could be causing this error?

Local env | Not Streaming to Kinesis Stream

Hello,

Am a newbie to Kinesis. Have tried to setup the project in all three mentioned ways in the readme but cannot make it to work.

Local Env: I have setup all required versions and did intall the project. NPM start gives following response.

<addr>
> node server.js

Express HTTP server listening on port 3000

Uploads bucket: brain-power-fidgetology-demo-uploads-862986627627

GET / 304 4.464 ms - -
GET /css/main.css 304 7.172 ms - -
GET /js/app/config.js 404 14.544 ms - 155
GET /js/lib/aws-sdk/aws-sdk.min.js 304 15.438 ms - -
GET /js/lib/font-awesome/fontawesome-all.min.js 304 14.277 ms - -
GET /js/lib/echarts/echarts.min.js 304 13.420 ms - -
GET /js/lib/ng-file-upload/ng-file-upload.min.js 304 12.919 ms - -
GET /js/lib/ng-file-upload/ng-file-upload-shim.min.js 304 12.457 ms - -
GET /js/lib/webcamjs/webcam.js 304 7.609 ms - -
GET /js/custom/frame-buffer.js 304 7.896 ms - -
GET /js/app/ng-config.js 304 13.389 ms - -
GET /js/app/webcam-stream-controller.js 304 13.743 ms - -
GET /js/app/chart-controllers/metrics-chart-controller.js 304 13.544 ms - -
GET /js/app/root-controller.js 304 13.424 ms - -
GET /js/app/chart-controllers/fidgetometer-controller.js 304 1.017 ms - -
GET /js/app/config.js 404 1.100 ms - 155
GET /Prod/Config 404 0.551 ms - 150
GET /favicon.ico 200 2.356 ms - 1150
<addr>

The camera stream starts on browser but nothing gets posted to kinesis

Please help.

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.