CoolFace
Apppublic

olive100/hand_classification

sourceHugging Faceupdated 3y agoView on Hugging Face
0likes
app.py52 linesDownload Raw Back to root
1import gradio as gr 2import json3import base644import requests5import cv26 7def hand_classification(img):8    # 可选的请求参数9    # top_num: 返回的分类数量,不声明的话默认为 6 个10    PARAMS = {"top_num": 2}11 12    # 服务详情 中的 接口地址13    MODEL_API_URL = "https://aip.baidubce.com/rpc/2.0/ai_custom/v1/classification/handclass"14 15    # 调用 API 需要 ACCESS_TOKEN。若已有 ACCESS_TOKEN 则于下方填入该字符串16    # 否则,留空 ACCESS_TOKEN,于下方填入 该模型部署的 API_KEY 以及 SECRET_KEY,会自动申请并显示新 ACCESS_TOKEN17    ACCESS_TOKEN = ""18    API_KEY = "TPhSFQU5i8tYivTgsLWBRLi9"19    SECRET_KEY = "eZbQHnOqTGYBVDXGTqzAy5kvU03t32Qz"20 21 22    print("1. 读取目标图片 ")23    success,encoded_image = cv2.imencode(".jpg",img) #注意这句编码,否则图像质量不合格24    img_test = base64.b64encode(encoded_image)25    PARAMS["image"] = img_test.decode('UTF8')26 27 28    if not ACCESS_TOKEN:29        print("2. ACCESS_TOKEN 为空,调用鉴权接口获取TOKEN")30        auth_url = "https://aip.baidubce.com/oauth/2.0/token?grant_type=client_credentials&client_id={}&client_secret={}".format(API_KEY, SECRET_KEY)31        auth_resp = requests.get(auth_url)32        auth_resp_json = auth_resp.json()33        ACCESS_TOKEN = auth_resp_json["access_token"]34        print("新 ACCESS_TOKEN: {}".format(ACCESS_TOKEN))35    else:36        print("2. 使用已有 ACCESS_TOKEN")37 38 39    print("3. 向模型接口 'MODEL_API_URL' 发送请求")40    request_url = "{}?access_token={}".format(MODEL_API_URL, ACCESS_TOKEN)41    response = requests.post(url=request_url, json=PARAMS)42    response_json = response.json()43    response_str = json.dumps(response_json, indent=4, ensure_ascii=False)44    print("结果:\n{}".format(response_str))45    result = response_json["results"]46    res = {result[0]["name"]:result[0]["score"],result[1]["name"]:result[1]["score"]}47    return res48 49demo = gr.Interface(fn=hand_classification, inputs="image", outputs="label")50gr.close_all()51demo.launch()52