File size: 2,052 Bytes
24e799c
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1b5b073
24e799c
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
b91a87c
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
import gradio as gr 
import json
import base64
import requests
import cv2

def hand_classification(img):
    # 可选的请求参数
    # top_num: 返回的分类数量,不声明的话默认为 6 个
    PARAMS = {"top_num": 2}

    # 服务详情 中的 接口地址
    MODEL_API_URL = "https://aip.baidubce.com/rpc/2.0/ai_custom/v1/classification/handclass"

    # 调用 API 需要 ACCESS_TOKEN。若已有 ACCESS_TOKEN 则于下方填入该字符串
    # 否则,留空 ACCESS_TOKEN,于下方填入 该模型部署的 API_KEY 以及 SECRET_KEY,会自动申请并显示新 ACCESS_TOKEN
    ACCESS_TOKEN = ""
    API_KEY = "TPhSFQU5i8tYivTgsLWBRLi9"
    SECRET_KEY = "eZbQHnOqTGYBVDXGTqzAy5kvU03t32Qz"


    print("1. 读取目标图片 ")
    success,encoded_image = cv2.imencode(".jpg",img) #注意这句编码,否则图像质量不合格
    img_test = base64.b64encode(encoded_image)
    PARAMS["image"] = img_test.decode('UTF8')


    if not ACCESS_TOKEN:
        print("2. ACCESS_TOKEN 为空,调用鉴权接口获取TOKEN")
        auth_url = "https://aip.baidubce.com/oauth/2.0/token?grant_type=client_credentials&client_id={}&client_secret={}".format(API_KEY, SECRET_KEY)
        auth_resp = requests.get(auth_url)
        auth_resp_json = auth_resp.json()
        ACCESS_TOKEN = auth_resp_json["access_token"]
        print("新 ACCESS_TOKEN: {}".format(ACCESS_TOKEN))
    else:
        print("2. 使用已有 ACCESS_TOKEN")


    print("3. 向模型接口 'MODEL_API_URL' 发送请求")
    request_url = "{}?access_token={}".format(MODEL_API_URL, ACCESS_TOKEN)
    response = requests.post(url=request_url, json=PARAMS)
    response_json = response.json()
    response_str = json.dumps(response_json, indent=4, ensure_ascii=False)
    print("结果:\n{}".format(response_str))
    result = response_json["results"]
    res = {result[0]["name"]:result[0]["score"],result[1]["name"]:result[1]["score"]}
    return res
 
demo = gr.Interface(fn=hand_classification, inputs="image", outputs="label")
gr.close_all()
demo.launch()