服务类作用

百度云交互的基本服务类 (验证,图片识别(车牌,票据,身份证…..),语音识别)

源码

import { Common, IRetVo, MethodType, RetState } from "yh-designer/dist/utils/Common";


/**
 * 识别的类型
 */
export enum OcrType {
    /**
     * 车牌识别
     */
    licensePlate = 'licensePlate',
    /**
     * 行驶证识别
     */
    vehicleLicense = 'vehicleLicense',
    /**
     * 驾照识别
     */
    drivingLicense = 'drivingLicense',
}

/**
 * 百度识别结果
 */
export interface IBaiduOcrResult {
    /**
     * 日志id
     * 用于差为
     */
    log_id: string
    /**
     * 识别的项的数量
     */
    words_result_num: number

}
/**
 * 车牌的识别结果
 */
export interface ILicensePlate extends IBaiduOcrResult {
    /**
     * 车牌的颜色
     */
    color: string
    /**
     * 车牌号码
     */
    number: string
}
/**
 * 车牌的识别结果
 */
export interface ILicensePlateResutl extends IBaiduOcrResult {
    /**
     * 识别结果
     */
    words_result: ILicensePlate
}

/**
 * 识别的结果
 */
export interface IOcrWords {
    words: string
}
/**
 * 识别返回的结果
 */
export interface IOCRResutl extends IBaiduOcrResult {
    /**
     * 识别结果
     */
    words_result: IOcrWords[]
}
/**
 * OCR位置
 */
export interface IOCRPosition {
    /**
     * 垂直坐标 Y
     */
    top: number,
    /**
     * 水平坐标 X
     */
    left: number,
    /**
     * 宽
     */
    width: number,
    /**
     * 高
     */
    height: number
}
/**
 * 包含坐标的识别结果项
 */
export interface IOCRWordsPosition {
    /**
     * 识别的字符串
     */
    wrods: string
    /**
     * 字符串的位置
     */
    location: IOCRPosition
}


/**
 * 包含了坐标的识别总结果
 */
export interface IOCRPositionResutl extends IBaiduOcrResult {
    /**
     * 识别结果
     */
    words_result: IOCRWordsPosition[]

}
/**
 * 通用识别总结果
 */
export interface IOCRCommonResutl extends IBaiduOcrResult {
    /**
     * 识别结果
     */
    words_result: any

}



/**
 * 行驶证识别的结果接口
 */
export interface IVehicleLicense extends IBaiduOcrResult {
    车辆识别代号: IOcrWords,
    住址: IOcrWords,
    发证日期: IOcrWords,
    发证单位: IOcrWords,
    品牌型号: IOcrWords,
    车辆类型: IOcrWords,
    所有人: IOcrWords,
    使用性质: IOcrWords,
    发动机号码: IOcrWords,
    号牌号码: IOcrWords,
    注册日期: IOcrWords
}
/**
 * 行驶证识别的结果接口
 */
export interface IVehicleLicenseResult extends IBaiduOcrResult {
    /**
     * 识别结果
     */
    words_result: IVehicleLicense
}
/**
 * 驾驶证识别的结果接口
 */
export interface IDrivingLicense extends IBaiduOcrResult {
    车辆识别代号: IOcrWords,
    住址: IOcrWords,
    发证日期: IOcrWords,
    发证单位: IOcrWords,
    品牌型号: IOcrWords,
    车辆类型: IOcrWords,
    所有人: IOcrWords,
    使用性质: IOcrWords,
    发动机号码: IOcrWords,
    号牌号码: IOcrWords,
    注册日期: IOcrWords
}
/**
 * 驾驶证识别的结果接口
 */
export interface IDrivingLicenseResult extends IBaiduOcrResult {
    /**
     * 识别结果
     */
    words_result: IDrivingLicense
}

/**
 * 百度云服务
 */
export class BaiduService {
    static BAIDU_DOMAIN = Common.getContextPath()
    static BAIDU_ACCESSTOKEN_URL = '/baidu/getAccessToken'
    static ERROR = {
        1: "Unknown error(服务器内部错误,请再次请求,如果持续出现此类错误,请在控制台提交工单联系技术支持团队)",
        2: "Service temporarily unavailable(服务暂不可用,请再次请求,如果持续出现此类错误,请在控制台提交工单联系技术支持团队)",
        3: "Unsupported openapi method(调用的API不存在,请检查请求URL后重新尝试,一般为URL中有非英文字符,如' - ',可手动输入重试)",
        4: "Open api request limit reached(集群超限额,请再次请求,如果持续出现此类错误,请在控制台提交工单联系技术支持团队)",
        6: "No permission to access data(无权限访问该用户数据,创建应用时未勾选相关文字识别接口,请登录百度云控制台,找到对应的应用,编辑应用,勾选上相关接口后重新调用)",
        14: "IAM Certification failed(IAM鉴权失败,建议用户参照文档自查生成sign的方式是否正确,或换用控制台中ak sk的方式调用)",
        17: "Open api daily request limit reached(免费测试资源使用完毕,每天请求量超限额,已支持计费的接口,您可以在控制台文字识别服务选择购买相关接口的次数包或开通按量后付费;邀测和未支持计费的接口,您可以在控制台提交工单申请提升限额)",
        18: "Open api qps request limit reached(QPS超限额,免费额度并发限制为2QPS,开通按量后付费或购买次数包后并发限制为10QPS,如您需要更多的并发量,可以选择购买QPS叠加包;邀测和未支持计费的接口,您可以在控制台提交工单申请提升限额)",
        19: "Open api total request limit reached(请求总量超限额,已支持计费的接口,您可以在控制台文字识别服务选择购买相关接口的次数包或开通按量后付费;邀测和未支持计费的接口,您可以在控制台提交工单申请提升限额)",
        100: "Invalid parameter(无效的access_token参数,token拉取失败,您可以参考“Access Token获取”文档重新获取)",
        110: "Access token invalid or no longer valid(access_token无效,token有效期为30天,请注意需要定期更换,也可以每次请求都拉取新token)",
        111: "Access token expired(access token过期,token有效期为30天,请注意需要定期更换,也可以每次请求都拉取新token)",
        216100: "invalid param(请求中包含非法参数,请检查后重新尝试)",
        216101: "not enough param(缺少必须的参数,请检查参数是否有遗漏)",
        216102: "service not support(请求了不支持的服务,请检查调用的url)",
        216103: "param too long(请求中某些参数过长,请检查后重新尝试)",
        216110: "appid not exist(appid不存在,请重新核对信息是否为后台应用列表中的appid)",
        216200: "empty image(图片为空,请检查后重新尝试)",
        216201: "image format error(上传的图片格式错误,现阶段我们支持的图片格式为:PNG、JPG、JPEG、BMP,请进行转码或更换图片)",
        216202: "input oversize(上传的包体积过大,现阶段不支持 10M 或以上的数据包)",
        216630: "recognize error(识别错误,请再次请求,请确保图片中包含对应卡证票据)",
        216631: "recognize bank card error(识别银行卡错误,出现此问题的原因一般为:您上传的图片非银行卡正面,上传了异形卡的图片、上传的银行卡正面图片不完整或模糊)",
        216633: "recognize idcard error(识别身份证错误,出现此问题的原因一般为:您上传了非身份证图片、上传的身份证图片不完整或模糊)",
        216634: "detect error(检测错误,请再次请求,如果持续出现此类错误,请在控制台提交工单联系技术支持团队)",
        282000: "internal error(服务器内部错误,如果您使用的是高精度接口,报这个错误码的原因可能是您上传的图片中文字过多,识别超时导致的,建议您对图片进行切割后再识别,其他情况请再次请求, 如果持续出现此类错误,请在控制台提交工单联系技术支持团队)",
        282003: "missing parameters: {参数名}(请求参数缺失)",
        282005: "batch processing error(处理批量任务时发生部分或全部错误,请根据具体错误码排查)",
        282006: "batch task limit reached(批量任务处理数量超出限制,请将任务数量减少到10或10以下)",
        282100: "image transcode error(图片压缩转码错误)",
        282102: "target detect error(未检测到图片中识别目标,请确保图片中包含对应卡证票据,出现此问题的原因一般为:您上传了非卡证图片、图片不完整或模糊)",
        282103: "target recognize error(图片目标识别错误,请确保图片中包含对应卡证票据,出现此问题的原因一般为:您上传了非卡证图片、图片不完整或模糊)",
        282110: "urls not exit(URL参数不存在,请核对URL后再次提交)",
        282111: "url format illegal(URL格式非法,请检查url格式是否符合相应接口的入参要求)",
        282112: "url download timeout(url下载超时,请检查url对应的图床/图片无法下载或链路状况不好,或图片大小大于3M,或图片存在防盗链,您可以重新尝试一下,如果多次尝试后仍不行,建议更换图片地址)",
        282113: "url response invalid(URL返回无效参数)",
        282114: "url size error(URL长度超过1024字节或为0)",
        282808: "request id: xxxxx not exist(request id xxxxx 不存在)",
        282809: "result type error(返回结果请求错误(不属于excel或json))",
        282810: "image recognize error(图像识别错误,请再次请求,如果持续出现此类错误,请在控制台提交工单联系技术支持团队)",
    }
    private static accesstokenid: string;


    /**
     * 得到AcceessToken
     * @returns 返回AccessTokenId
     */
    public static AccessToken() {
        BaiduService.accesstokenid = '';
        Common.asyncAjax(Common.getContextPath() + BaiduService.BAIDU_ACCESSTOKEN_URL, MethodType.POST, {}, (res: IRetVo) => {
            if (res.state == RetState.OK) {
                BaiduService.accesstokenid = res.obj;
            } else {
                Common.errorMsg('获取百度AccessToken出现问题:' + res.msg)
            }
        })
        return BaiduService.accesstokenid;
    }

    /**
     * 同步请求百度云的数据
     * @param url 识别的api 
     * @param param 参数对象
     * @param onSuccess 可选参数 成功回调
     * @param onError  可选参数 错误回调
     * @param onCompolete 可选参数 完成回调
     */
    private static baiduPost(url: string, param?: any, onSuccess?: (result) => void, onError?: (err) => void, onCompolete?: () => void) {
        let that = this;
        $.ajax({
            url: url,
            type: MethodType.POST,
            async: false,
            data: param,
            contentType: 'application/x-www-form-urlencoded',
            success: function (result) {
                if (result.error_code) {
                    Common.errorMsg(that.ERROR[result.error_code]);
                    onError && onError(that.ERROR[result.error_msg]);
                } else if (result.words_result) {
                    onSuccess && onSuccess(result);
                }
            },
            error: function (xhr, textStatus) {
                Common.doError(xhr, textStatus);
                onError && onError(xhr.responseText);
            },
            complete: function (xhr) {
                onCompolete && onCompolete();
            }
        });
    }


    /**
     * 车牌图片识别
     * @param imgUrl 需要识别的图片全路径如: http://xxx.com/yyyy/123.jpg
     * @param onSuccess 可选参数 成功回调
     * @param onError  可选参数 错误回调
     * @param onCompolete 可选参数 完成回调
     * @returns 返回车牌的数据 ILicensePlateResutl
     */
    public static licensePlate(imgUrl: string, onSuccess?: (result) => void, onError?: (err) => void, onCompolete?: () => void): ILicensePlate {
        BaiduService.AccessToken();
        let apiUrl = BaiduService.BAIDU_DOMAIN + '/rest/2.0/ocr/v1/license_plate?access_token=' + BaiduService.accesstokenid + '&multi_detect=false';
        let ret: ILicensePlate;
        BaiduService.baiduPost(apiUrl, { url: imgUrl }, (result: ILicensePlateResutl) => {
            if (result.words_result) {
                ret = result.words_result;
                onSuccess && onSuccess(ret);
            } else {
                onError && onError('返回格式有误');
            }
        }, (err) => {
            onError && onError(err);
        }, () => {
            onCompolete && onCompolete();
        })
        return ret;
    }
    /**
     * 行驶证识别
     * 对机动车行驶证主页及副页所有22个字段进行结构化识别,包括号牌号码、车辆类型、所有人、品牌型号、车辆识别代码、发动机号码、核定载人数、质量、尺寸、检验记录等。
     * @param imgUrl 需要识别的图片全路径如: http://xxx.com/yyyy/123.jpg
     * @param onSuccess 可选参数 成功回调
     * @param onError  可选参数 错误回调
     * @param onCompolete 可选参数 完成回调
     * @returns 返回行驶证识别的数据 IVehicleLicense
     */
    public static vehicleLicense(imgUrl: string, onSuccess?: (result) => void, onError?: (err) => void, onCompolete?: () => void): IVehicleLicense {
        BaiduService.AccessToken();
        let apiUrl = BaiduService.BAIDU_DOMAIN + '/rest/2.0/ocr/v1/vehicle_license?access_token=' + BaiduService.accesstokenid + "&detect_direction=false";
        let ret: IVehicleLicense;
        BaiduService.baiduPost(apiUrl, { url: imgUrl }, (result: IVehicleLicenseResult) => {
            if (result.words_result) {
                ret = result.words_result;
                onSuccess && onSuccess(ret);
            } else {
                onError && onError('返回格式有误');
            }
        }, (err) => {
            onError && onError(err);
        }, () => {
            onCompolete && onCompolete();
        })
        return ret;
    }

    /**
     * 驾驶证识别
     * 支持对机动车驾驶证正页及副页所有15个字段进行结构化识别,包括证号、姓名、性别、国籍、住址、出生日期、初次领证日期、准驾车型、有效期限、发证单位、档案编号等。
     * @param imgUrl 需要识别的图片全路径如: http://xxx.com/yyyy/123.jpg
     * @param onSuccess 可选参数 成功回调
     * @param onError  可选参数 错误回调
     * @param onCompolete 可选参数 完成回调
     * @returns 返回驾驶证的数据IDrivingLicense
     */
    public static drivingLicense(imgUrl: string, onSuccess?: (result) => void, onError?: (err) => void, onCompolete?: () => void): IDrivingLicense {
        BaiduService.AccessToken();
        let apiUrl = BaiduService.BAIDU_DOMAIN + '/rest/2.0/ocr/v1/driving_license?access_token=' + BaiduService.accesstokenid + "&detect_direction=false";
        let ret: IDrivingLicense;
        BaiduService.baiduPost(apiUrl, { url: imgUrl }, (result: IDrivingLicenseResult) => {
            if (result.words_result) {
                ret = result.words_result;
                onSuccess && onSuccess(ret);
            } else {
                onError && onError('返回格式有误');
            }
        }, (err) => {
            onError && onError(err);
        }, () => {
            onCompolete && onCompolete();
        })
        return ret;
    }

    /**
     * 通用文字识别- 
     * 在通用文字识别的基础上,提供更高精度的识别服务,支持更多语种识别(丹麦语、荷兰语、马来语、瑞典语、印尼语、波兰语、罗马尼亚语、土耳其语、希腊语、匈牙利语),并将字库从1w+扩展到2w+,能识别所有常用字和大部分生僻字。
     * @param imgUrl 需要识别的图片全路径如: http://xxx.com/yyyy/123.jpg
     * @param onSuccess 可选参数 成功回调
     * @param onError  可选参数 错误回调
     * @param onCompolete 可选参数 完成回调
     * @returns 返回识别的文字结果 
     * {
            "log_id": 1390582998516105216,
            "words_result_num": 2
            "words_result": [
                {
                    "words": " OCR"
                },
                {
                    "words": "百度通用文字识别高精度版"
                }
            ],  
        }
     */
    public static accurateBasic(imgUrl: string, onSuccess?: (result) => void, onError?: (err) => void, onCompolete?: () => void): IDrivingLicense {
        BaiduService.AccessToken();
        let apiUrl = BaiduService.BAIDU_DOMAIN + '/rest/2.0/ocr/v1/accurate_basic?access_token=' + BaiduService.accesstokenid;
        let ret: IDrivingLicense;
        BaiduService.baiduPost(apiUrl, { url: imgUrl }, (result: IDrivingLicenseResult) => {
            if (result.words_result) {
                ret = result.words_result;
                onSuccess && onSuccess(ret);
            } else {
                onError && onError('返回格式有误');
            }
        }, (err) => {
            onError && onError(err);
        }, () => {
            onCompolete && onCompolete();
        })
        return ret;
    }

    /**
     * 通用文字识别-高精度版 
     * 在通用文字识别的基础上,提供更高精度的识别服务,支持更多语种识别(丹麦语、荷兰语、马来语、瑞典语、印尼语、波兰语、罗马尼亚语、土耳其语、希腊语、匈牙利语),并将字库从1w+扩展到2w+,能识别所有常用字和大部分生僻字。
     * @param imgUrl 需要识别的图片全路径如: http://xxx.com/yyyy/123.jpg
     * @param onSuccess 可选参数 成功回调
     * @param onError  可选参数 错误回调
     * @param onCompolete 可选参数 完成回调
     * @returns 返回识别的文字结果 
     * {
            "log_id": 1390584857033179136,
            "words_result_num": 2
            "words_result": [
                {
                    "words": " OCR",
                    "location": {
                        "top": 19,
                        "left": 54,
                        "width": 119,
                        "height": 46
                    }
                },
                {
                    "words": "百度通用文字识别高精度版",
                    "location": {
                        "top": 85,
                        "left": 54,
                        "width": 206,
                        "height": 37
                    }
                }
            ],
        }
     * */
    public static accurate(imgUrl: string, onSuccess?: (result) => void, onError?: (err) => void, onCompolete?: () => void): IOCRWordsPosition[] {
        BaiduService.AccessToken();
        let apiUrl = BaiduService.BAIDU_DOMAIN + '/rest/2.0/ocr/v1/accurate?access_token=' + BaiduService.accesstokenid;
        let ret: IOCRWordsPosition[];
        BaiduService.baiduPost(apiUrl, { url: imgUrl }, (result: IOCRPositionResutl) => {
            if (result.words_result) {
                ret = result.words_result;
                onSuccess && onSuccess(ret);
            } else {
                onError && onError('返回格式有误');
            }
        }, (err) => {
            onError && onError(err);
        }, () => {
            onCompolete && onCompolete();
        })
        return ret;
    }
    /**
     * 支持对图片中的手写中文、手写数字进行检测和识别,针对不规则的手写字体进行专项优化,识别准确率可达90%以上。
     * @param imgUrl 需要识别的图片全路径如: http://xxx.com/yyyy/123.jpg
     * @param onSuccess 可选参数 成功回调
     * @param onError  可选参数 错误回调
     * @param onCompolete 可选参数 完成回调
     * @returns 返回识别的文字结果 
     * {
            "log_id": 1390584857033179136,
            "words_result_num": 2
            "words_result": [
                {
                    "words": " OCR",
                    "location": {
                        "top": 19,
                        "left": 54,
                        "width": 119,
                        "height": 46
                    }
                },
                {
                    "words": "百度通用文字识别高精度版",
                    "location": {
                        "top": 85,
                        "left": 54,
                        "width": 206,
                        "height": 37
                    }
                }
            ],
        }
     * */
    public static handwriting(imgUrl: string, onSuccess?: (result) => void, onError?: (err) => void, onCompolete?: () => void): IOCRWordsPosition[] {
        BaiduService.AccessToken();
        let apiUrl = BaiduService.BAIDU_DOMAIN + '/rest/2.0/ocr/v1/handwriting?access_token=' + BaiduService.accesstokenid;
        let ret: IOCRWordsPosition[];
        BaiduService.baiduPost(apiUrl, { url: imgUrl }, (result: IOCRPositionResutl) => {
            if (result.words_result) {
                ret = result.words_result;
                onSuccess && onSuccess(ret);
            } else {
                onError && onError('返回格式有误');
            }
        }, (err) => {
            onError && onError(err);
        }, () => {
            onCompolete && onCompolete();
        })
        return ret;
    }

    /**
    * 针对网络图片进行专项优化,支持识别艺术字体或背景复杂的文字内容。
    * @param imgUrl 需要识别的图片全路径如: http://xxx.com/yyyy/123.jpg
    * @param onSuccess 可选参数 成功回调
    * @param onError  可选参数 错误回调
    * @param onCompolete 可选参数 完成回调
    * @returns 返回识别的文字结果 
    * {
           "log_id": 1390650576630448128,
           "words_result_num": 2,
           "words_result": [
               {
                   "words": "梦想起航"
               },
               {
                   "words": "前往下一个目的地"
               },
               {
                   "words": "开始新的旅程"
               }
           ],
       }
    * */
    public static webimage(imgUrl: string, onSuccess?: (result) => void, onError?: (err) => void, onCompolete?: () => void): IOcrWords[] {
        BaiduService.AccessToken();
        let apiUrl = BaiduService.BAIDU_DOMAIN + '/rest/2.0/ocr/v1/webimage?access_token=' + BaiduService.accesstokenid;
        let ret: IOcrWords[];
        BaiduService.baiduPost(apiUrl, { url: imgUrl }, (result: IOCRResutl) => {
            if (result.words_result) {
                ret = result.words_result;
                onSuccess && onSuccess(ret);
            } else {
                onError && onError('返回格式有误');
            }
        }, (err) => {
            onError && onError(err);
        }, () => {
            onCompolete && onCompolete();
        })
        return ret;
    }

    /**
     * 对图片中的数字进行提取和识别,自动过滤非数字内容,仅返回数字内容及其位置信息,识别准确率超过99%。
     * @param imgUrl 需要识别的图片全路径如: http://xxx.com/yyyy/123.jpg
     * @param onSuccess 可选参数 成功回调
     * @param onError  可选参数 错误回调
     * @param onCompolete 可选参数 完成回调
     * @returns 返回识别的文字结果 
     * {
             "log_id": 1390650576630448128,
            "words_result_num": 2,
            "words_result": [
                {
                    "location": {
                        "left": 56,
                        "top": 0,
                        "width": 21,
                        "height": 210
                    },
                    "words": "3"
                }
            ],
        }
    * */
    public static numbers(imgUrl: string, onSuccess?: (result) => void, onError?: (err) => void, onCompolete?: () => void): IOCRWordsPosition[] {
        BaiduService.AccessToken();
        let apiUrl = BaiduService.BAIDU_DOMAIN + '/rest/2.0/ocr/v1/numbers?access_token=' + BaiduService.accesstokenid;
        let ret: IOCRWordsPosition[];
        BaiduService.baiduPost(apiUrl, { url: imgUrl }, (result: IOCRPositionResutl) => {
            if (result.words_result) {
                ret = result.words_result;
                onSuccess && onSuccess(ret);
            } else {
                onError && onError('返回格式有误');
            }
        }, (err) => {
            onError && onError(err);
        }, () => {
            onCompolete && onCompolete();
        })
        return ret;
    }

    /**
     *身份证混贴识别支持自动检测与识别身份证正反面在同一张图片上的场景,一次识别图片中身份证正反面所有字段。
     *支持对二代居民身份证正反面所有8个字段进行结构化识别,包括姓名、性别、民族、出生日期、住址、身份证号、签发机关、有效期限,识别准确率超过99%;同时支持身份证正面头像检测,并返回头像切片的base64编码及位置信息。
     *同时,支持对用户上传的身份证图片进行图像风险和质量检测,可识别图片是否为复印件或临时身份证,是否被翻拍或编辑,是否存在正反颠倒、模糊、欠曝、过曝等质量问题。
     * @param imgUrl 需要识别的图片全路径如: http://xxx.com/yyyy/123.jpg
     * @param onSuccess 可选参数 成功回调
     * @param onError  可选参数 错误回调
     * @param onCompolete 可选参数 完成回调
     * @returns 返回识别的文字结果 
     * {
             "log_id": 1390650576630448128,
            "words_result_num": 2,
            "words_result": [
                {
                    "location": {
                        "left": 56,
                        "top": 0,
                        "width": 21,
                        "height": 210
                    },
                    "words": "3"
                }
            ],
        }
    * */
    public static multiIdcard(imgUrl: string, onSuccess?: (result) => void, onError?: (err) => void, onCompolete?: () => void): any[] {
        BaiduService.AccessToken();
        let apiUrl = BaiduService.BAIDU_DOMAIN + '/rest/2.0/ocr/v1/multi_idcard?access_token=' + BaiduService.accesstokenid;
        let ret;
        BaiduService.baiduPost(apiUrl, { url: imgUrl }, (result: IOCRCommonResutl) => {
            if (result.words_result) {
                ret = result.words_result;
                onSuccess && onSuccess(ret);
            } else {
                onError && onError('返回格式有误');
            }
        }, (err) => {
            onError && onError(err);
        }, () => {
            onCompolete && onCompolete();
        })
        return ret;
    }

}

参考

百度云的使用配置
百度服务类API

作者:texbox  创建时间:2022-12-15 20:50
最后编辑:admin  更新时间:2024-04-26 09:11