Baidu AI provides a very powerful AI interface, can be very easy to achieve such as picture recognition, speech recognition, text recognition, face recognition and other functions. The following takes face recognition as an example to explain how to use Nodejs to retrieve Baidu AI interface to realize face location, age, gender, appearance level, emotion and other information.
1. Project creation
Start by creating a project using Express scaffolding. For those unfamiliar with Express, take a look at this document: www.expressjs.com.cn/
Installation of Express scaffolding
npm install express-generator -g
Copy the code
Create a project:
express myapp
Copy the code
After the project is created, install AXIOS to make network requests.
npm i axios -S
Copy the code
2. Log in to Baidu AI and create a project
Before formally calling the interface, you need to register your Baidu account first, and then log in to Baidu AI open platform: ai.baidu.com/ after successful login, click the upper right corner to enter the console.
3. Obtain the Access Token
Call face recognition interface, need to pass in an Access Token parameter, so we need to obtain the Token first.
Get the Access Token
Request URL data format
https://aip.baidubce.com/oauth/2.0/token sends a request to authorized service address (it is recommended to use POST), and to bring the following parameters in the URL:
- Grant_type: mandatory parameter, which is fixed to client_credentials.
- Client_id: mandatory parameter, application API Key.
- Client_secret: mandatory parameter, the Secret Key of the application.
The server returns the following JSON text parameters:
- Access_token: Access Token to be obtained.
- Expires_in: Validity period of the Access Token (in seconds, usually one month).
- Other parameters are ignored for the time being.
Such as:
{
"refresh_token": "25. B55fe1d287227ca97aab219bb249b8ab. 315360000.1798284651.282335-8574074"."expires_in": 2592000,
"scope": "public wise_adapt"."session_key": "9mzdDZXu3dENdFZQurfg0Vz8slgSgvvOAUebNFzyzcpQ5EnbxbF+hfG9DQkpUVQdh4p6HbQcAiz5RmuBAja1JJGgIdJI"."access_token": "24.6 c5e1ff107f0e8bcef8c46d3424a0e78. 2592000.1485516651.282335-8574074"."session_secret": "dfac94a3489fe9fca7c3221cbf7525ff"
}
Copy the code
The validity period of the token is 2592000ms. It’s best to cache tokens. Here I’m using Redis for caching.
Install redis
Download redis: redis. IO/Download redis:
- Decompress: tar ZXVF redis-4.0.10.tar.gz
- Move to: mv redis-4.0.10 /usr/local/
- Go to CD /usr/local/redis-4.0.10/
- Compile tests: sudo make test
- Sudo make install
- Activation: redis server. –
- Create a new terminal window and enter the command line redis-cli
- Set name ‘davie’
- Get data get name
Install redis library
To use Redis on Nodejs, you need to install the Redis library. Reference: www.npmjs.com/package/red… Installation:
npm install redis
Copy the code
Get the Access Token
var qs = require('querystring');
let axios = require('axios');
var redis = require("redis"),
client = redis.createClient();
client.on("error".function (err) {
console.log("Error "+ err); }); /** * cache tokens in redis */ asyncfunction getToken() {return new Promise(function(resolve,reject){
client.get('token',async (err,reply) =>{
if(err){
reject(err)
}else{
if(reply){
resolve(reply)
}else{
letresult = await getNewToken(); / / cache the token, set a time / / reference https://www.npmjs.com/package/redis client. Set ('token', result.data.access_token, 'EX', result.data.expires_in);
resolve(result.data.access_token)
}
}
})
})
}
async function getNewToken(){
const param = qs.stringify({
'grant_type': 'client_credentials'.'client_id': I'm going to put your API Key here..'client_secret': 'Here's your Secret Key'
});
return axios.get('https://aip.baidubce.com/oauth/2.0/token?'+ param)
}
module.exports = getToken;
Copy the code
4. Upload pictures
To achieve picture upload function, to obtain pictures.
Add a picture upload page
Create home.jade in the views directory with the following code:
Extends Layout Block Content h1= title Div Uploads a form(Action ="/upload", method="post" enctype="multipart/form-data")
input(type="file" name="avatar")
input(type="submit" value="Submit")
Copy the code
This page is written using Jade, you can also use EJS or other templates.
Route to the home page and change routes/index.js
/* GET home page. */
router.get('/'.function(req, res, next) {
res.render('home', { title: 'Express'}); // Render home page});Copy the code
To test it, start the server
npm start
Copy the code
Enter http://localhost:300 in the browser address bar to see an image upload page.
Install multer middleware
To implement image upload, we also need Multer, which is a Nodejs image upload middleware. Documents: www.npmjs.com/package/mul… Install multer:
npm install --save multer
Copy the code
Set the image upload directory:
var multer = require('multer')
var upload = multer({ dest: 'public/uploads/' })
Copy the code
Image upload interface:
Add the following to routes/index.js:
router.post('/upload',upload.single('avatar'),(req,res)=>{
let imgUlr = 'http://localhost:3000/uploads/' + req.file.filename
})
Copy the code
After selecting “Submit” from the front-end image upload page, the data will be submitted to this interface and the image will be saved to the public/uploads/ directory.
After uploading pictures name for: the req. File. The filename, so an accessible picture address is: ‘http://localhost:3000/uploads/’ + the req. File. The filename
5. Invoke the face recognition interface
Interface address: https://aip.baidubce.com/rest/2.0/face/v1/merge?access_token= you touken use post method request, token stitching on the url.
Request parameters:
- Image: Indicates the image information (the total data size should be less than 10 MB). The image uploading mode is determined based on image_type
- Image_type:
- BASE64: The BASE64 value of an image. The image data encoded by BASE64 is less than 2M in size.
- URL: INDICATES the URL of the image (it may take a long time to download the image due to network reasons).
- FACE_TOKEN: The unique identifier of a face image. When the face detection interface is invoked, each face image is assigned a unique FACE_TOKEN. The Same FACE_TOKEN is obtained after multiple detection of the same image
The other mandatory parameters are face_field, max_face_num, face_type, and liveness_control. For details, see ai.baidu.com/ai-doc/FACE…
Where image_type can be BASE64,URL, and FACE_TOKEN, I used the first BASE64. Then you need to convert the uploaded image to Base64.
Pictures turn base64
Install the image – to – base64
https://www.npmjs.com/package/image-to-base64
Copy the code
Usage:
const image2base64 = require('image-to-base64');
image2base64("path/to/file.jpg") // you can also to use url .then( (response) => { console.log(response); //cGF0aC90by9maWxlLmpwZw== } ) .catch( (error) => { console.log(error); //Exepection error.... })Copy the code
Request interface
async function getFaceResult(imgUrl,response){
try {
let token = await getToken();
let imgBase64 = await image2base64(imgUrl) // you can also to use url
let faceResult = await axios.post('https://aip.baidubce.com/rest/2.0/face/v3/detect?access_token='+ token,
{
image:imgBase64,
image_type:"BASE64",
face_field:'age,beauty,expression,face_shape,gender,glasses,landmark,landmark150,race,quality,eye_status,emotion,face_type'
})
response.render('index',faceResult.data.result.face_list[0])
} catch (error) {
response.send(error)
}
}
Copy the code
Call after uploading picture:
router.post('/upload',upload.single('avatar'),(req,res)=>{
let imgUlr = 'http://localhost:3000/uploads/' + req.file.filename
getFaceResult(imgUlr,res);
})
Copy the code
To complete.