• 4. 遇到的问题

用 docker 部署 PaddleOCR 是因为 PaddleOCR 以源码安装的方式比较繁杂,要注意比较多的细节,而且很多环境往往是没有外网的,因此Docker就是一个很好的解决方案,它将开放所需要的环境都封装在镜像中了,方便部署使用。

1. PaddleOCR 镜像制作

Dockerfile文件

# Version: 2.0.0
FROM paddlepaddle/paddle:2.6.1

# PaddleOCR base on Python3.7
RUN pip install --no-cache-dir --upgrade pip -i https://mirror.baidu.com/pypi/simple

RUN pip install --no-cache-dir paddlehub --upgrade -i https://mirror.baidu.com/pypi/simple

RUN pip uninstall -y astroid

RUN pip install astroid==2.12.2

RUN git clone https://gitee.com/PaddlePaddle/PaddleOCR.git /PaddleOCR

WORKDIR /PaddleOCR

RUN pip install --no-cache-dir -r requirements.txt -i https://mirror.baidu.com/pypi/simple

RUN mkdir -p /PaddleOCR/inference/

# Download orc detect model(light version). if you want to change normal version, you can change ch\_ppocr\_mobile\_v2.0\_det\_infer to ch\_ppocr\_server\_v2.0\_det\_infer, also remember change det\_model\_dir in deploy/hubserving/ocr\_system/params.py)
ADD https://paddleocr.bj.bcebos.com/PP-OCRv3/chinese/ch_PP-OCRv3_det_infer.tar /PaddleOCR/inference/
ADD https://paddleocr.bj.bcebos.com/dygraph_v2.0/ch/ch_ppocr_mobile_v2.0_cls_infer.tar /PaddleOCR/inference/
ADD https://paddleocr.bj.bcebos.com/PP-OCRv3/chinese/ch_PP-OCRv3_rec_infer.tar /PaddleOCR/inference/


RUN tar xf /PaddleOCR/inference/ch_PP-OCRv3_det_infer.tar -C /PaddleOCR/inference/
RUN tar xf /PaddleOCR/inference/ch_ppocr_mobile_v2.0_cls_infer.tar -C /PaddleOCR/inference/
RUN tar xf /PaddleOCR/inference/ch_PP-OCRv3_rec_infer.tar -C /PaddleOCR/inference/

RUN pip install protobuf==3.20.0 -i https://mirror.baidu.com/pypi/simple

EXPOSE 8866

CMD ["/bin/bash","-c","hub install deploy/hubserving/ocr\_system/ && hub serving start -m ocr\_system"]

创建好Dockerfile文件后,执行如下命令即可自动构建镜像,要预留足够的存储空间,构建完成后大概6G多,整个构建过程根据网速定,我花了差不多1.5小时才构建完。

docker build -t paddle-ocr:2.6.1 .

2. 运行

docker run -dp 8866:8866 --name ocr paddle-ocr:2.6.1

当然也可以用 docker-compose 管理

version: '3'
services:
  ocr:
    image: paddle-ocr:2.6.1
    restart: always
    container_name: ocr
    ports:
      - 8866:8866

3. 测试调用

package com.aaron;

import java.io.IOException;
import java.io.InputStream;
import java.nio.charset.Charset;
import java.nio.file.Files;
import java.nio.file.Paths;
import java.text.ParseException;
import org.apache.http.HttpResponse;
import org.apache.http.HttpStatus;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.util.EntityUtils;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;

import sun.misc.BASE64Encoder;
public class InvoiceOcr {

    //接口地址
    private static String apiURL = "http://192.168.0.101:8866/predict/ocr\_system";
    private HttpClient httpClient = null;
    private HttpPost method = null;
    private long startTime = 0L;
    private long endTime = 0L;
    private int status = 0;
    
    public InvoiceOcr(String url) {

        if (url != null) {
            this.apiURL = url;
        }
        if (apiURL != null) {
            httpClient = new DefaultHttpClient();
            method = new HttpPost(apiURL);

        }
    }

    public static void main(String[] args) throws ParseException {
        InvoiceOcr ac = new InvoiceOcr(apiURL);
        JSONArray arry = new JSONArray();
        JSONObject param = new JSONObject();
        arry.add(imageToBase64("E:\\第16页-0.png"));
        param.put("images",arry);
        String result = ac.post(param.toJSONString());
        System.out.println(result);
    }

    /**
     * 调用 API
     */
    public String post(String parameters) {
        String body = null;
        if (method != null & parameters != null && !"".equals(parameters.trim())) {
            try {

                // 建立一个NameValuePair数组,用于存储欲传送的参数
                method.addHeader("Content-type","application/json");
                method.setHeader("Accept", "application/json");
                method.setEntity(new StringEntity(parameters, Charset.forName("UTF-8")));
                startTime = System.currentTimeMillis();

                HttpResponse response = httpClient.execute(method);

                endTime = System.currentTimeMillis();
                int statusCode = response.getStatusLine().getStatusCode();

                System.out.println("statusCode:" + statusCode);
                System.out.println("调用API 花费时间(单位:毫秒):" + (endTime - startTime));
                if (statusCode != HttpStatus.SC_OK) {
                    System.out.println("Method failed:" + response.getStatusLine());
                    status = 1;
                }
                body = EntityUtils.toString(response.getEntity(),"utf-8");
            } catch (IOException e) {
                // 网络错误
                status = 3;
                e.printStackTrace();
            } finally {
                System.out.println("调用接口状态:" + status);
            }
        }
        return body;
    }

    public static String imageToBase64(String path) {
        byte[] data = null;
        // 读取图片字节数组
        try {
            InputStream in = Files.newInputStream(Paths.get(path));
            data = new byte[in.available()];
            in.read(data);
            in.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
        // 对字节数组Base64编码
        BASE64Encoder encoder = new BASE64Encoder();
        return encoder.encode(data);// 返回Base64编码过的字节数组字符串
    }
    /**
     * 0.成功 1.执行方法失败 2.协议错误 3.网络错误
     *
     * @return the status
     */
    public int getStatus() {
        return status;
    }

    /**
     * @param status
     *            the status to set
     */
    public void setStatus(int status) {
        this.status = status;
    }

    /**
     * @return the startTime
     */
    public long getStartTime() {
        return startTime;
    }

    /**
     * @return the endTime
     */