Sample code

package humanshaperecognitioncontrollers

import (
    "bytes"
    "container/list"
    "crypto/hmac"
    "crypto/sha1"
    "encoding/base64"
    "encoding/json"
    "fmt"
    "io"
    "io/ioutil"
    "math"
    "mime/multipart"
    "net/http"
    "net/url"
    "os"
    "smartcloud/common"
    "smartcloud/golib"
    "smartcloud/log"
    "smartcloud/models"
    "strconv"
    "strings"
    "sync"
    "time"

    "github.com/aws/aws-sdk-go/aws"
    "github.com/aws/aws-sdk-go/aws/awserr"
    "github.com/aws/aws-sdk-go/aws/credentials"
    "github.com/aws/aws-sdk-go/aws/session"
    "github.com/aws/aws-sdk-go/service/rekognition"
    "github.com/denverdino/aliyungo/oss"
)

type HSRController struct {
    HSRBaseController
}

var G_HSRController *HSRController

func init() {
    //StartTimer()
    //oss相关
    //ptstr := beego.AppConfig.String("pt::ptstr")
    //AccessKeyId = beego.AppConfig.String(fmt.Sprintf("dhsrapi::AccessKeyId"))
    //AccessKeySecret = beego.AppConfig.String(fmt.Sprintf("dhsrapi::AccessKeySecret"))
    //IsPro := beego.BConfig.RunMode == "prod"
    //if IsPro {
    //    Region = beego.AppConfig.String(fmt.Sprintf("dhsrapi::InternalRegion"))
    //    IHost := beego.AppConfig.String(fmt.Sprintf("dhsrapi::IHost", ptstr))
    //    if common.TestHost(IHost, "80") == false {
    //        Region = beego.AppConfig.String(fmt.Sprintf("dhsrapi::Region"))
    //    }
    //} else {
    //    Region = beego.AppConfig.String(fmt.Sprintf("dhsrapi::Region"))
    //}
    //Bucket = beego.AppConfig.String(fmt.Sprintf("dhsrapi::Bucket"))
    //OssRootPath = fmt.Sprintf("%s/", ptstr)
    //client = oss.NewOSSClient(oss.Region(Region), false, AccessKeyId, AccessKeySecret, false)
    //b = client.Bucket(Bucket)
}

//token 24小时有效
var default_expired_time time.Duration = 86400
var freeCounts int64 = 1000000 //免费次数
var HSRMtux sync.Mutex
var HFDMtux sync.Mutex
var HFRMtux sync.Mutex
var HFR_HFD_HFR_Mtux sync.Mutex

func (c *HSRController) SetFunName() {
    c.functionName = "human_shape_recognition"
    G_HSRController = c
}

func (c *HSRController) Get() {
    c.SetFunName()

    //c.Data["solutionsData"] = GetCompanyInfo(SolInfo, reviewStatus, c)
    //c.TplName = "solutions/solution_account.html"
}

func (c *HSRController) Post() {
    writelog.WriteDebug("人形识别Post")
    c.SetFunName()
}

func (c *HSRController) ClearIp() {
    ClearHsrAccessPermission()
    c.jsonStandardResult(0, "ok", nil)
    return
}

func (c *HSRController) GetRemainCount(service_key string) int64 {
    //这里还要判断剩多少钱,能调用多少次
    //所有企业免费使用10万次之后,再计费
    skInfo := models.GetServiceKeyInfoByServiceKey(service_key)
    if skInfo == nil {
        return 0
    }
    if skInfo.CapacityId == common.Capacity_AiFace {
        HSRMtux.Lock()
        defer HSRMtux.Unlock()
    } else if skInfo.CapacityId == common.Capacity_HFD {
        HFDMtux.Lock()
        defer HFDMtux.Unlock()
    }
    v, _ := models.GetHsrUsedCountsByCompanyId(skInfo.CompanyId, skInfo.CapacityId)
    if v != nil {
        counts := freeCounts - v.UsedCounts
        if counts > 0 {
            return counts
        } else {
            //这里要计算余额是否能够支付下次的计费
            //先允许使用,计费方案出来再扣费
            return 1
        }
    }
    return freeCounts
}

type KeyTokenTime struct {
    Service_key  string `json:"service_key"`
    Token        string `json:"token"`
    Expired_time int64  `json:"expired_time"`
}

给 API 服务器调用的,获取 token,http://yf.jfgou.com:81/devdocs/HumanShapeRecognition.md

https://apiyf.robotscloud.com/hsr/v1/token?service_key=Z4s77nyI4DMc050LbraYZJSdL5Jk4lJi

测试页面http://apiyf.robotscloud.com/hsr/v1/test.html

必须用 https 访问

func (c *HSRController) Token() {
    //这里判断一下,http不允许访问
    //    if c.Ctx.Request.TLS == nil {
    //        writelog.WriteDebug("Token 必须使用https协议")
    //        msg := models.ReturnMsg(c.Lang, c.functionName, "use_https_protocol")
    //        c.jsonStandardResult(-1, msg, nil)
    //        return
    //    }
    c.Post()
    service_key := c.GetString("service_key")
    if service_key == "" {
        c.msg2JsonResult(`{"ret":-1, "msg":"请输入service_key"}`)
        writelog.WriteDebug("请输入service_key")
        return
    }

    capacityId := models.GetCapacityIdByServiceKey(service_key)
    //platform_service.go里定义的Capacity
    if capacityId != common.Capacity_AiFace {
        c.msg2JsonResult(`{"ret":-2, "msg":"service_key不匹配"}`)
        writelog.WriteDebug("service_key不匹配")
        return
    }

    companyId := models.GetCompanyIdByServiceKey(service_key)
    if companyId < 0 {
        c.msg2JsonResult(`{"ret":-3, "msg":"未找到企业"}`)
        return
    }
    /*
        if c.GetRemainCount(service_key) <= 0 {
            c.msg2JsonResult(`{"ret":-4, "msg":"余额不足,请充值"}`)
            return
        }
    */

    var token_time KeyTokenTime
    token_time.Service_key = service_key
    for {
        token_time.Token = models.GetRandString(32)
        _, err := models.GetServerKeyTokenCache(token_time.Token)
        if err == nil {
            continue
        } else {
            break
        }
    }
    token_time.Expired_time = time.Now().Add(time.Second * default_expired_time).Unix()
    token_time_str, _ := json.Marshal(token_time)
    writelog.WriteDebug("----------------------" + string(token_time_str))
    err := models.SetServerKeyTokenCache(token_time.Token, string(token_time_str)) //注意这里是用token当做关键字存储,因为一个key可能会对应多个token

    if err != nil {
        c.msg2JsonResult(`{"ret":-3, "msg":"萝卜头服务器错误"}`)
    } else {
        c.Data["json"] = struct {
            Ret     int    `json:"ret"`
            Msg     string `json:"msg"`
            Token   string `json:"token"`
            Expired int64  `json:"expired"`
        }{
            Ret:     0,
            Msg:     "",
            Token:   token_time.Token,
            Expired: token_time.Expired_time,
        }
        //支持跨域
        c.Ctx.Output.Header("Access-Control-Allow-Origin", "*")
        c.Ctx.Output.Header("Access-Control-Allow-Methods", "GET,POST")
        c.ServeJSON()
    }

    return
}

v2 版本,增加 device_sn 和 service_code 参数

func (c *HSRController) Token_v2() {
    c.Post()
    service_key := c.GetString("service_key")
    if service_key == "" {
        c.msg2JsonResult(`{"ret":-1, "msg":"请输入service_key"}`)
        writelog.WriteDebug("请输入service_key")
        return
    }

    //device_sn和service_code暂未处理
    device_sn := c.GetString("device_sn")
    if device_sn == "" {
        c.msg2JsonResult(`{"ret":-2, "msg":"请输入device_sn"}`)
        writelog.WriteDebug("请输入device_sn")
        return
    }

    service_code := c.GetString("service_code")
    if service_code == "" {
        c.msg2JsonResult(`{"ret":-3, "msg":"请输入service_code"}`)
        writelog.WriteDebug("请输入service_code")
        return
    }

    capacityId := models.GetCapacityIdByServiceKey(service_key)
    //platform_service.go里定义的Capacity
    if capacityId != common.Capacity_AiFace {
        c.msg2JsonResult(`{"ret":-4, "msg":"service_key不匹配"}`)
        writelog.WriteDebug("key不匹配")
        return
    }

    companyId := models.GetCompanyIdByServiceKey(service_key)
    if companyId < 0 {
        c.msg2JsonResult(`{"ret":-5, "msg":"未找到企业"}`)
        return
    }
    /*
        if c.GetRemainCount(service_key) <= 0 {
            c.msg2JsonResult(`{"ret":-4, "msg":"余额不足,请充值"}`)
            return
        }
    */

    var token_time KeyTokenTime
    token_time.Service_key = service_key
    for {
        token_time.Token = models.GetRandString(32)
        _, err := models.GetServerKeyTokenCache(token_time.Token)
        if err == nil {
            continue
        } else {
            break
        }
    }
    token_time.Expired_time = time.Now().Add(time.Second * default_expired_time).Unix()
    token_time_str, _ := json.Marshal(token_time)
    writelog.WriteDebug("----------------------" + string(token_time_str))
    err := models.SetServerKeyTokenCache(token_time.Token, string(token_time_str)) //注意这里是用token当做关键字存储,因为一个key可能会对应多个token

    if err != nil {
        c.msg2JsonResult(`{"ret":-6, "msg":"萝卜头服务器错误"}`)
    } else {
        c.Data["json"] = struct {
            Ret     int    `json:"ret"`
            Msg     string `json:"msg"`
            Token   string `json:"token"`
            Expired int64  `json:"expired"`
        }{
            Ret:     0,
            Msg:     "",
            Token:   token_time.Token,
            Expired: token_time.Expired_time,
        }
        c.Ctx.Output.Header("Access-Control-Allow-Origin", "*")
        c.Ctx.Output.Header("Access-Control-Allow-Methods", "GET,POST")
        c.ServeJSON()
    }

    return
}

新增一个和 Token 功能相同的接口,允许 http 方法

http://apiyf.robotscloud.com/hsr/v1/token_sign?service_key=frkukGxj8te4Rot3VheleidmE0291gAk&sign=D38D706171EB3F967EF6FE74A9A2965EC1041EED176EB485679DA7A66A3A2A7455616ADA497B87F8CA38273FC83F22D6A5F7012D412F7647F77A397872C549EC

func (c *HSRController) TokenSign() {
    c.Post()
    service_key := c.GetString("service_key")
    if service_key == "" {
        c.msg2JsonResult(`{"ret":-1, "msg":"请输入service_key"}`)
        writelog.WriteDebug("请输入service_key")
        return
    }

    sign := c.GetString("sign")
    if sign == "" {
        c.msg2JsonResult(`{"ret":-2, "msg":"请输入sign"}`)
        writelog.WriteDebug("请输入sign")
        return
    }

    skInfo := models.GetServiceKeyInfoByServiceKey(service_key)
    if skInfo == nil {
        c.msg2JsonResult(`{"ret":-3, "msg":"service_key错误"}`)
        writelog.WriteDebug("service_key错误,%s", service_key)
        return
    }
    public_pem, _ := models.GetPublicKeyTostring(skInfo.CompanyId)
    b := common.SignVerify(service_key, sign, []byte(public_pem))
    if !b {
        c.msg2JsonResult(`{"ret":-4, "msg":"sign签名无效"}`)
        writelog.WriteDebug("sign签名无效,service_key=%s,sign=%s", service_key, sign)
        return
    }

    //capacityId := models.GetCapacityIdByServiceKey(service_key)
    //platform_service.go里定义的Capacity
    if skInfo.CapacityId != common.Capacity_AiFace {
        c.msg2JsonResult(`{"ret":-5, "msg":"key不匹配"}`)
        writelog.WriteDebug("key不匹配")
        return
    }

    companyId := models.GetCompanyIdByServiceKey(service_key)
    if companyId < 0 {
        c.msg2JsonResult(`{"ret":-6, "msg":"未找到企业"}`)
        return
    }

    if c.GetRemainCount(service_key) <= 0 {
        c.msg2JsonResult(`{"ret":-7, "msg":"余额不足,请充值"}`)
        return
    }

    var token_time KeyTokenTime
    token_time.Service_key = service_key
    for {
        token_time.Token = models.GetRandString(32)
        _, err := models.GetServerKeyTokenCache(token_time.Token)
        if err == nil {
            continue
        } else {
            break
        }
    }
    token_time.Expired_time = time.Now().Add(time.Second * default_expired_time).Unix()
    token_time_str, _ := json.Marshal(token_time)
    writelog.WriteDebug("----------------------" + string(token_time_str))
    err := models.SetServerKeyTokenCache(token_time.Token, string(token_time_str)) //注意这里是用token当做关键字存储,因为一个key可能会对应多个token

    if err != nil {
        c.msg2JsonResult(`{"ret":-3, "msg":"萝卜头服务器错误"}`)
    } else {
        c.Data["json"] = struct {
            Ret     int    `json:"ret"`
            Msg     string `json:"msg"`
            Token   string `json:"token"`
            Expired int64  `json:"expired"`
        }{
            Ret:     0,
            Msg:     "",
            Token:   token_time.Token,
            Expired: token_time.Expired_time,
        }
        c.Ctx.Output.Header("Access-Control-Allow-Origin", "*")
        c.Ctx.Output.Header("Access-Control-Allow-Methods", "GET,POST")
        c.ServeJSON()
    }

    return
}

人形检测

func (c *HSRController) HsrDetection() {
    if !GetHsrAccessPermission(c.Ip, c.InterfaceName) { //超出设置的访问速度
        c.jsonStandardResult(-100, "Access is too frequent", "")
        return
    }
    if common.GetContentLength(c.Ctx.Request) > common.SystemMaxInputLength10M { //防止被攻击
        writelog.WriteDebug("recieve attack: head length:%s", c.Ctx.Request.Header.Get("Content-Length"))
        c.jsonStandardResult(-999, "file size is too long", "")
        return
    }
    token := c.GetString("token")
    writelog.WriteDebug("token=%s", token)
    companyId := 0
    v, err := models.GetServerKeyTokenCache(token)
    if err == nil {
        var token_time KeyTokenTime
        json.Unmarshal([]byte(v.(string)), &token_time)
        //writelog.WriteDebug("%s, %s, %d", token_time.Token, token_time.Service_key, token_time.Expired_time)
        if time.Now().Unix()-token_time.Expired_time > 0 {
            //这里还是不删缓存,因为会调用很多次,如果删了,后面的报错就是token无效,不利于查找问题models.DelServerKeyTokenCache(tt.token)
            c.jsonStandardResult(-1, "expired token", nil)
            return
        }
        companyId = models.GetCompanyIdByServiceKey(token_time.Service_key)
        if companyId <= 0 { //理论上不会出现
            c.jsonStandardResult(-2, "company not found", "")
            return
        }
    } else {
        c.jsonStandardResult(-3, "invalid token", nil)
        return
    }

    f, h, _ := c.GetFile("file")
    if f != nil && h != nil {
        writelog.WriteDebug("filename=%s", h.Filename)
        bufstore := make([]byte, 1024*1024*11) //数据缓存11M
        i, _ := f.Read(bufstore)
        if i > MaxImageSize {
            c.jsonStandardResult(-4, "file should not exceed 10M", nil)
            return
        }
        //local_file_path := "./tmp/" + h.Filename
        //common.WriteFile(local_file_path, string(bufstore[:i]))
        //httpurl := fmt.Sprintf("http://127.0.0.1:7780/hsr_detection")
        v := url.Values{}
        v.Set("pic", base64.StdEncoding.EncodeToString(bufstore[:i]))
        resp, err := http.PostForm(c.HsrUrl, v)
        if err != nil {
            writelog.WriteError("调用本地服务hsr_detection错误,err:=%s", err.Error())
            c.jsonStandardResult(-5, "local service error", "")
            return
        }
        defer resp.Body.Close()
        body, _ := ioutil.ReadAll(resp.Body)
        result := string(body)
        //writelog.WriteDebug("aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa")
        //writelog.WriteDebug(result)
        if strings.HasPrefix(result, "[") && strings.HasSuffix(result, "]") { //检测完毕,不管是检测出来还是没检测出来,都要计数
            var features []Feature
            err1 := json.Unmarshal(body, &features)
            if err1 != nil {
                writelog.WriteError("调用本地服务hsr_detection错误,err:=%s", err1.Error())
                c.jsonStandardResult(-6, "local service error", "")
                return
            }
            c.Data["json"] = struct {
                Ret      int       `json:"ret"`
                Msg      string    `json:"msg"`
                Features []Feature `json:"features"`
            }{
                Ret:      0,
                Msg:      "ok",
                Features: features,
            }
            c.ServeJSON()
            RecordUseCounts(companyId, common.Capacity_AiFace)
            return
        } else if result == "" { //检测完毕,未检测到人形
            c.Data["json"] = struct {
                Ret      int       `json:"ret"`
                Msg      string    `json:"msg"`
                Features []Feature `json:"features"`
            }{
                Ret:      -9,
                Msg:      "检测完毕,未检测到人形",
                Features: nil,
            }
            c.ServeJSON()
            RecordUseCounts(companyId, common.Capacity_AiFace)
            return
        } else {
            c.jsonStandardResult(-6, "local service error", "")
            writelog.WriteDebug("local service error:" + result)
            return
        }
    } else {
        c.jsonStandardResult(-7, "file error", nil)
        return
    }

    c.jsonStandardResult(-8, "unknow error", nil)
    return
}
func (c *HSRController) HsrDetection_v2() {
    if !GetHsrAccessPermission(c.Ip, c.InterfaceName) { //超出设置的访问速度
        c.jsonStandardResult(-100, "Access is too frequent", "")
        return
    }
    if common.GetContentLength(c.Ctx.Request) > common.SystemMaxInputLength10M { //防止被攻击
        writelog.WriteDebug("recieve attack: head length:%s", c.Ctx.Request.Header.Get("Content-Length"))
        c.jsonStandardResult(-999, "file size is too long", "")
        return
    }
    token := c.GetString("token")
    writelog.WriteDebug("token=%s", token)
    companyId := 0
    v, err := models.GetServerKeyTokenCache(token)
    if err == nil {
        var token_time KeyTokenTime
        json.Unmarshal([]byte(v.(string)), &token_time)
        //writelog.WriteDebug("%s, %s, %d", token_time.Token, token_time.Service_key, token_time.Expired_time)
        if time.Now().Unix()-token_time.Expired_time > 0 {
            //这里还是不删缓存,因为会调用很多次,如果删了,后面的报错就是token无效,不利于查找问题models.DelServerKeyTokenCache(tt.token)
            c.jsonStandardResult(-1, "expired token", nil)
            return
        }
        companyId = models.GetCompanyIdByServiceKey(token_time.Service_key)
        if companyId <= 0 { //理论上不会出现
            c.jsonStandardResult(-2, "company not found", "")
            return
        }
    } else {
        c.jsonStandardResult(-3, "invalid token", nil)
        return
    }

    f, h, _ := c.GetFile("file")
    if f != nil && h != nil {
        writelog.WriteDebug("filename=%s", h.Filename)
        bufstore := make([]byte, 1024*1024*11) //数据缓存11M
        i, _ := f.Read(bufstore)
        if i > MaxImageSize {
            c.jsonStandardResult(-4, "file should not exceed 10M", nil)
            return
        }
        //local_file_path := "./tmp/" + h.Filename
        //common.WriteFile(local_file_path, string(bufstore[:i]))
        //httpurl := fmt.Sprintf("http://127.0.0.1:7780/hsr_detection")
        v := url.Values{}
        v.Set("pic", base64.StdEncoding.EncodeToString(bufstore[:i]))
        resp, err := http.PostForm(c.HsrUrl, v)
        if err != nil {
            writelog.WriteError("调用本地服务hsr_detection错误,err:=%s", err.Error())
            c.jsonStandardResult(-5, "local service error", "")
            return
        }
        defer resp.Body.Close()
        body, _ := ioutil.ReadAll(resp.Body)
        result := string(body)
        //writelog.WriteDebug("aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa")
        //writelog.WriteDebug(result)
        if strings.HasPrefix(result, "[") && strings.HasSuffix(result, "]") { //检测完毕,不管是检测出来还是没检测出来,都要计数
            var features []Feature
            err1 := json.Unmarshal(body, &features)
            if err1 != nil {
                writelog.WriteError("调用本地服务hsr_detection错误,err:=%s", err1.Error())
                c.jsonStandardResult(-6, "local service error", "")
                return
            }
            var hsrDetectionV2 HsrDetectionV2
            if len(features) > 0 {
                if features[0].Person.Confidence > 0.0 {
                    hsrDetectionV2.Person = 1
                }
            }

            c.Data["json"] = struct {
                Ret      int            `json:"ret"`
                Msg      string         `json:"msg"`
                Features HsrDetectionV2 `json:"features"`
            }{
                Ret:      0,
                Msg:      "ok",
                Features: hsrDetectionV2,
            }
            c.ServeJSON()
            RecordUseCounts(companyId, common.Capacity_AiFace)
            return
        } else if result == "" { //检测完毕,未检测到人形
            var hsrDetectionV2 HsrDetectionV2
            c.Data["json"] = struct {
                Ret      int            `json:"ret"`
                Msg      string         `json:"msg"`
                Features HsrDetectionV2 `json:"features"`
            }{
                Ret:      -9,
                Msg:      "检测完毕,未检测到人形",
                Features: hsrDetectionV2,
            }
            c.ServeJSON()
            RecordUseCounts(companyId, common.Capacity_AiFace)
            return
        } else {
            c.jsonStandardResult(-6, "local service error", "")
            writelog.WriteDebug("local service error:" + result)
            return
        }
    } else {
        c.jsonStandardResult(-7, "file error", nil)
        return
    }

    c.jsonStandardResult(-8, "unknow error", nil)
    return
}

在 HsrDetection_v2 的基础上合并了 Token_v2 的功能

func (c *HSRController) HsrDetectionWithToken_v2() {
    if !GetHsrAccessPermission(c.Ip, c.InterfaceName) { //超出设置的访问速度
        c.jsonStandardResult(-100, "Access is too frequent", "")
        return
    }
    service_key := c.GetString("service_key")
    if service_key == "" {
        c.msg2JsonResult(`{"ret":-1, "msg":"请输入service_key"}`)
        writelog.WriteDebug("请输入service_key")
        return
    }

    //device_sn和service_code暂未处理
    device_sn := c.GetString("device_sn")
    if device_sn == "" {
        c.msg2JsonResult(`{"ret":-2, "msg":"请输入device_sn"}`)
        writelog.WriteDebug("请输入device_sn")
        return
    }

    service_code := c.GetString("service_code")
    if service_code == "" {
        c.msg2JsonResult(`{"ret":-3, "msg":"请输入service_code"}`)
        writelog.WriteDebug("请输入service_code")
        return
    }

    capacityId := models.GetCapacityIdByServiceKey(service_key)
    //platform_service.go里定义的Capacity
    if capacityId != common.Capacity_AiFace {
        c.msg2JsonResult(`{"ret":-4, "msg":"service_key不匹配"}`)
        writelog.WriteDebug("service_key不匹配")
        return
    }

    companyId := models.GetCompanyIdByServiceKey(service_key)
    if companyId < 0 {
        c.msg2JsonResult(`{"ret":-5, "msg":"未找到企业"}`)
        return
    }

    if common.GetContentLength(c.Ctx.Request) > common.SystemMaxInputLength10M { //防止被攻击
        writelog.WriteDebug("recieve attack: head length:%s", c.Ctx.Request.Header.Get("Content-Length"))
        c.jsonStandardResult(-999, "file size is too long", "")
        return
    }

    f, h, _ := c.GetFile("file")
    if f != nil && h != nil {
        writelog.WriteDebug("filename=%s", h.Filename)
        bufstore := make([]byte, 1024*1024*11) //数据缓存11M
        i, _ := f.Read(bufstore)
        if i > MaxImageSize {
            c.jsonStandardResult(-6, "file should not exceed 10M", nil)
            return
        }
        //local_file_path := "./tmp/" + h.Filename
        //common.WriteFile(local_file_path, string(bufstore[:i]))
        //httpurl := fmt.Sprintf("http://127.0.0.1:7780/hsr_detection")
        v := url.Values{}
        v.Set("pic", base64.StdEncoding.EncodeToString(bufstore[:i]))
        resp, err := http.PostForm(c.HsrUrl, v)
        if err != nil {
            writelog.WriteError("调用本地服务hsr_detection错误,err:=%s,url=%s", err.Error(), c.HsrUrl)
            c.jsonStandardResult(-7, "local service error", "")
            return
        }
        defer resp.Body.Close()
        body, _ := ioutil.ReadAll(resp.Body)
        result := string(body)
        //writelog.WriteDebug("aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa")
        //writelog.WriteDebug(result)
        if strings.HasPrefix(result, "[") && strings.HasSuffix(result, "]") { //检测完毕,不管是检测出来还是没检测出来,都要计数
            var features []Feature
            err1 := json.Unmarshal(body, &features)
            if err1 != nil {
                writelog.WriteError("调用本地服务hsr_detection错误,err:=%s, url=%s", err1.Error(), c.HsrUrl)
                c.jsonStandardResult(-8, "local service error", "")
                return
            }
            var hsrDetectionV2 HsrDetectionV2
            if len(features) > 0 {
                if features[0].Person.Confidence > 0.0 {
                    hsrDetectionV2.Person = 1
                }
            }

            c.Data["json"] = struct {
                Ret      int            `json:"ret"`
                Msg      string         `json:"msg"`
                Features HsrDetectionV2 `json:"features"`
            }{
                Ret:      0,
                Msg:      "ok",
                Features: hsrDetectionV2,
            }
            c.ServeJSON()
            RecordUseCounts(companyId, common.Capacity_AiFace)
            return
        } else if result == "" { //检测完毕,未检测到人形
            var hsrDetectionV2 HsrDetectionV2
            c.Data["json"] = struct {
                Ret      int            `json:"ret"`
                Msg      string         `json:"msg"`
                Features HsrDetectionV2 `json:"features"`
            }{
                Ret:      -9,
                Msg:      "检测完毕,未检测到人形",
                Features: hsrDetectionV2,
            }
            c.ServeJSON()
            RecordUseCounts(companyId, common.Capacity_AiFace)
            return
        } else {
            c.jsonStandardResult(-10, "local service error ", "")
            writelog.WriteDebug(c.HsrUrl + " local service error:" + result)
            return
        }
    } else {
        c.jsonStandardResult(-11, "file error", nil)
        return
    }

    c.jsonStandardResult(-12, "unknow error", nil)
    return
}

物体检测

总共支持的类型有 80 种:person,bicycle,car,motorbike,aeroplane,bus,train,truck,boat,traffic light,fire hydrant,stop sign,parking meter,bench,bird,cat,dog,horse,sheep,cow,elephant,bear,zebra,giraffe,backpack,umbrella,handbag,tie,suitcase,frisbee,skis,snowboard,sports ball,kite,baseball bat,baseball glove,skateboard,surfboard,tennis racket,bottle,wine glass,cup,fork,knife,spoon,bowl,banana,apple,sandwich,orange,broccoli,carrot,hot dog,pizza,donut,cake,chair,sofa,pottedplant,bed,diningtable,toilet,tvmonitor,laptop,mouse,remote,keyboard,cell phone,microwave,oven,toaster,sink,refrigerator,book,clock,vase,scissors,teddy bear,hair drier,toothbrush

func (c *HSRController) OsrDetectionWithToken() {
    writelog.WriteDebug("OsrDetectionWithToken")
    writelog.WriteDebug(c.Ip)
    if !GetHsrAccessPermission(c.Ip, c.InterfaceName) { //超出设置的访问速度
        c.jsonStandardResult(-100, "Access is too frequent", "")
        return
    }
    service_key := c.GetString("service_key")
    if service_key == "" {
        c.msg2JsonResult(`{"ret":-1, "msg":"请输入service_key"}`)
        writelog.WriteDebug("请输入service_key")
        return
    }

    //device_sn和service_code暂未处理
    device_sn := c.GetString("device_sn")
    if device_sn == "" {
        c.msg2JsonResult(`{"ret":-2, "msg":"请输入device_sn"}`)
        writelog.WriteDebug("请输入device_sn")
        return
    }

    service_code := c.GetString("service_code")
    if service_code == "" {
        c.msg2JsonResult(`{"ret":-3, "msg":"请输入service_code"}`)
        writelog.WriteDebug("请输入service_code")
        return
    }

    capacityId := models.GetCapacityIdByServiceKey(service_key)
    //platform_service.go里定义的Capacity
    if capacityId != common.Capacity_AiFace { //这里有问题,这里填人形检测还是物体检测
        c.msg2JsonResult(`{"ret":-4, "msg":"service_key不匹配"}`)
        writelog.WriteDebug("service_key不匹配")
        return
    }

    companyId := models.GetCompanyIdByServiceKey(service_key)
    if companyId < 0 {
        c.msg2JsonResult(`{"ret":-5, "msg":"未找到企业"}`)
        return
    }

    if common.GetContentLength(c.Ctx.Request) > common.SystemMaxInputLength10M { //防止被攻击
        writelog.WriteDebug("recieve attack: head length:%s", c.Ctx.Request.Header.Get("Content-Length"))
        c.jsonStandardResult(-999, "file size is too long", "")
        return
    }

    f, h, _ := c.GetFile("file")
    if f != nil && h != nil {
        writelog.WriteDebug("filename=%s", h.Filename)
        bufstore := make([]byte, 1024*1024*11) //数据缓存11M
        i, _ := f.Read(bufstore)
        if i > MaxImageSize {
            c.jsonStandardResult(-6, "file should not exceed 10M", nil)
            return
        }
        v := url.Values{}
        //图片检测之前先矫正一下方向
        v.Set("pic", base64.StdEncoding.EncodeToString(common.ImageOrient(bufstore[:i])))
        resp, err := http.PostForm(c.OsrUrl, v)
        if err != nil {
            writelog.WriteError("调用本地服务OsrDetectionWithToken错误,err:=%s,url=%s", err.Error(), c.OsrUrl)
            c.jsonStandardResult(-7, "local service error", "")
            return
        }
        defer resp.Body.Close()
        body, _ := ioutil.ReadAll(resp.Body)
        result := string(body)
        //writelog.WriteDebug("aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa")
        //writelog.WriteDebug(result)
        if strings.HasPrefix(result, "[") && strings.HasSuffix(result, "]") { //检测完毕,不管是检测出来还是没检测出来,都要计数
            var features []ObjFeature
            err1 := json.Unmarshal(body, &features)
            if err1 != nil {
                writelog.WriteError("调用本地服务OsrDetectionWithToken错误,err:=%s, url=%s", err1.Error(), c.OsrUrl)
                c.jsonStandardResult(-8, "local service error", "")
                return
            }
            c.Data["json"] = struct {
                Ret      int          `json:"ret"`
                Msg      string       `json:"msg"`
                Features []ObjFeature `json:"features"`
            }{
                Ret:      0,
                Msg:      "ok",
                Features: features,
            }
            c.ServeJSON()
            RecordUseCounts(companyId, common.Capacity_OSR)
            return
        } else if result == "" { //检测完毕,未检测到人形
            //var hsrDetectionV2 HsrDetectionV2
            c.Data["json"] = struct {
                Ret      int          `json:"ret"`
                Msg      string       `json:"msg"`
                Features []ObjFeature `json:"features"`
            }{
                Ret:      -9,
                Msg:      "检测完毕,未检测到人形",
                Features: nil,
            }
            c.ServeJSON()
            RecordUseCounts(companyId, common.Capacity_OSR)
            return
        } else {
            c.jsonStandardResult(-10, "local service error ", "")
            writelog.WriteDebug(c.OsrUrl + " local service error:" + result)
            return
        }
    } else {
        c.jsonStandardResult(-11, "file error", nil)
        return
    }

    c.jsonStandardResult(-12, "unknow error", nil)
    return
}

results matching ""

    No results matching ""