利用百度api实现ocr识别发票

一、准备工作

1、百度智能云申请一个文字识别的api
在这里插入图片描述
里面每个月有1000次调用测试应该够用
在这里插入图片描述
2、一个springboot项目

二、主要代码

①、pom依赖引入

 <dependency>
            <groupId>com.baidu.aip</groupId>
            <artifactId>java-sdk</artifactId>
            <version>4.16.5</version>
            <exclusions>
                <exclusion>
                    <artifactId>guava</artifactId>
                    <groupId>com.google.guava</groupId>
                </exclusion>
                <exclusion>
                    <artifactId>slf4j-simple</artifactId>
                    <groupId>org.slf4j</groupId>
                </exclusion>
            </exclusions>
        </dependency>
        <dependency>
            <groupId>com.baidubce</groupId>
            <artifactId>api-explorer-sdk</artifactId>
            <version>1.0.3.1</version>
            <exclusions>
                <exclusion>
                    <artifactId>guava</artifactId>
                    <groupId>com.google.guava</groupId>
                </exclusion>
            </exclusions>
        </dependency>
        <dependency>
            <groupId>com.squareup.okhttp3</groupId>
            <artifactId>okhttp</artifactId>
            <version>3.10.0</version>
        </dependency>

②、控制层

    @ApiOperation("识别发票")
    @ResponseBody
    public ResponseEntity<InvoiceInfo> identifyInvoice(MultipartFile file) throws BizException {
        return new ResponseEntity<>(invoiceInfoService.identifyInvoice(file), HttpStatus.OK);
    }

③、实现层

    public InvoiceInfo identifyInvoice(MultipartFile file) {
        InvoiceInfo invoiceInfo = new InvoiceInfo();
        // 请求url
        String url = "https://aip.baidubce.com/rest/2.0/ocr/v1/vat_invoice";
        try {
            byte[] fileData = file.getBytes();
            String originalFilename = file.getOriginalFilename();
            boolean isPdf = originalFilename.endsWith("pdf") || originalFilename.endsWith("PDF");

            String fileStr = Base64Util.encode(fileData);
            String fileParam = URLEncoder.encode(fileStr, "UTF-8");
            String param = (isPdf ? "pdf_file" : "image") + "=" + fileParam;
            // 注意这里仅为了简化编码每一次请求都去获取access_token,线上环境access_token有过期时间, 客户端可自行缓存,过期后重新获取。
            String accessToken = AuthService.getAuth();
            String result = HttpUtil.post(url, accessToken, param);
            JSONObject jsonObject = JSON.parseObject(result);
            if (jsonObject.getInteger("error_code") != null) {
                String errorMsg = BaiduOcrConstant.ERROR_CODE_MAP.get(jsonObject.getInteger("error_code"));
                System.out.println("票据识别失败,错误信息:" + errorMsg);
            } else {
                JSONObject words_result = jsonObject.getJSONObject("words_result");
                invoiceInfo.setInvoiceType(words_result.getString("InvoiceTypeOrg"));
                invoiceInfo.setImportType(isPdf ? 0L : 1L);
                invoiceInfo.setCheckFlag(0L);
                invoiceInfo.setSupplierName(words_result.getString("SellerName"));
                invoiceInfo.setSupplierNumber(words_result.getString("SellerRegisterNum"));
                invoiceInfo.setSupplierDescription(words_result.getString("SellerAddress"));
                invoiceInfo.setBankNumber(words_result.getString("SellerBank"));
                invoiceInfo.setPurchaserName(words_result.getString("PurchaserName"));
                invoiceInfo.setPurchaserNumber(words_result.getString("PurchaserRegisterNum"));
                invoiceInfo.setBillingDate(words_result.getDate("InvoiceDate"));
                invoiceInfo.setInvoiceCode(words_result.getString("InvoiceCodeConfirm"));
                invoiceInfo.setInvoiceNumber(words_result.getString("InvoiceNum"));
                invoiceInfo.setCheckCode(words_result.getString("CheckCode"));
                invoiceInfo.setAmountTotal(words_result.getBigDecimal("AmountInFiguers"));
                invoiceInfo.setAmount(words_result.getBigDecimal("TotalAmount"));
                if("*".equals(words_result.getString("TotalTax"))){
                    invoiceInfo.setTaxAmount(new BigDecimal("0.00"));
                }else {
                    invoiceInfo.setTaxAmount(words_result.getBigDecimal("TotalTax"));
                }
                invoiceInfo.setRate(words_result.getBigDecimal("TotalAmount"));
                invoiceInfo.setCreateTime(new Date());
            }
            return invoiceInfo;
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }
}

其次就是百度需要的utils包

最后直接调用就行
在这里插入图片描述

  • 2
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
好的,以下是制作一个调用百度APIOCR识别页面的步骤: 1. 首先,你需要在百度AI平台上注册一个账号,并且创建一个应用,获取应用的API Key和Secret Key。 2. 在你的HTML页面中,创建一个表单,用于上传图片。 ```html <form method="POST" enctype="multipart/form-data"> <input type="file" name="image"> <input type="submit" value="识别"> </form> ``` 3. 在你的后端代码中,使用Python语言编写一个调用百度API的函数。下面是一个使用Python的requests库向百度API发送POST请求的示例代码: ```python import requests def recognize_text(image_path, api_key, secret_key): url = "https://aip.baidubce.com/oauth/2.0/token" grant_type = "client_credentials" # 获取Access Token response = requests.get( f"{url}?grant_type={grant_type}&client_id={api_key}&client_secret={secret_key}" ) access_token = response.json()["access_token"] # 发送OCR识别请求 url = "https://aip.baidubce.com/rest/2.0/ocr/v1/general_basic" headers = {"Content-Type": "application/x-www-form-urlencoded"} params = {"access_token": access_token} image = open(image_path, "rb").read() response = requests.post(url=url, headers=headers, params=params, data=image) # 解析响应 result = response.json() if "error_code" in result: return None else: return result["words_result"] ``` 4. 在你的后端代码中,获取上传的图片,并调用OCR识别函数。 ```python from flask import Flask, request, render_template app = Flask(__name__) @app.route("/", methods=["GET", "POST"]) def home(): if request.method == "POST": # 保存上传的图片 image = request.files["image"] image.save("image.png") # 调用OCR识别函数 api_key = "your_api_key" secret_key = "your_secret_key" result = recognize_text("image.png", api_key, secret_key) # 渲染模板,显示识别结果 return render_template("result.html", result=result) else: return render_template("index.html") if __name__ == "__main__": app.run(debug=True) ``` 5. 在你的HTML模板中,渲染识别结果。 ```html {% if result %} <h2>识别结果:</h2> <ul> {% for text in result %} <li>{{ text }}</li> {% endfor %} </ul> {% endif %} ``` 以上就是制作一个调用百度APIOCR识别页面的步骤。

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值