
Serverless computing refers to the concept of building and running applications that do not require server management. It describes a finer-grained deployment model where applications, bundled as one or more functions, are uploaded to a platform and then executed, scaled, and billed in response to the exact demand needed at the moment.
今天,我们会通过快速组合京东云 Serverless + AI,实现一个简单的 API 接口,进行人脸属性识别和简单数据分析。带领大家一起来感受一下Serverless的轻量虚拟化。
Serverless Service:函数服务+API 网关
人工智能产品:AI 人脸识别
Step1:创建函数
#coding=utf-8
import json
import base64
import os
from jdcloud_apim_sdk.core.credential import Credential
from jdcloud_apim_sdk.core.config import Config
from jdcloud_apim_sdk.core.const import SCHEME_HTTPS, SCHEME_HTTP
from ai_sdk.apis.ai_face_detect_attr_request import *
from ai_sdk.client.ai_Face_Detect_Attr_client import *
'''
AI
'''
def handler(event,context):
if not bool(event):
result = {
'statusCode': 200,
'headers': {},
'body': "",
}
return result
# get request data
print('AI Request')
# get request data
body = event['detail']['body']
body = json.loads(body)
if type(body) == unicode:
body = json.loads(body)
# request
access_key = 'XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX'
secret_key = 'XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX'
credential = Credential(access_key, secret_key)
config = Config('aiapi.jdcloud.com', scheme=SCHEME_HTTPS)
client = AiFaceDetectAttrClient(credential, config)
header = dict()
parameters = {
'return_landmark':0,
'return_attr':1,
'face_detect_num':0
}
data = body.get('data', "")
imageBase64Data = 'imageBase64=' + data.decode("utf-8")
s = imageBase64Data.encode('utf-8')
ai_face_detect_attr_request = AiFaceDetectAttrRequest(parameters, s, header)
AiFaceDetectAttr_response = client.send(ai_face_detect_attr_request)
respBody = {'code': 0, 'data': AiFaceDetectAttr_response.json()}
resp = json.dumps(respBody)
result = {
'statusCode': 200,
'headers': {},
'body': resp,
}
# statistics
resp = AiFaceDetectAttr_response.json()
if resp['result']['status'] == 0:
attrs = json.loads(resp['result']['result'])
if len(attrs['faces']) > 0:
if attrs['faces'][0]['faceAttribute']['gender'] == 0:
print("lookup ai attr success, this is a woman")
else:
print("lookup ai attr success, this is a man")
return result
Step2:测试函数
Step3:对接 API 网关
Step4:测试验证上线



