docker部署PaddleOCR2.6.1
用 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
*/
public long getEndTime() {
return endTime;
}
}
4. 遇到的问题
- 报 protobuf 包依赖冲突,后在Dockerfile 文件里后面加了这行,安装个低版本的 protobuf 解决
RUN pip install protobuf==3.20.0 -i https://mirror.baidu.com/pypi/simple
- PaddlePaddle出现“非法指令”或“illegal instruction”
原因:PaddlePaddle使用avx SIMD指令提高cpu执行效率,因此错误的使用二进制发行版可能会导致这种错误,请先判断你的电脑是否支持AVX指令集,再选择性的安装支持AVX指令集的PaddlePaddle还是不支持AVX指令集的PaddlePaddle,或者使用Docker镜像来安装最新版本的PaddlePaddle,Docker镜像中的PaddlePaddle默认支持是支持AVX指令集的,可以提高cpu的执行效率。在启动的时候会检查系统是否支持PaddlePaddle初始化时所需要的资源,从AVX指令集开始检查。
解决:遇到此问题可以先用 lscpu 命令查看docker宿主机是否支持AVX指令集,我是换台服务器解决。
- 容器运行后,调用的时候报了 module ‘numpy’ has no attribute ‘int’. 异常
AttributeError: module 'numpy' has no attribute 'int'.
`np.int` was a deprecated alias for the builtin `int`. To avoid this error in existing code, use `int` by itself. Doing this will not modify any behavior and is safe. When replacing `np.int`, you may wish to use e.g. `np.int64` or `np.int32` to specify the precision. If you wish to review your current use, check the release note link for additional information.
The aliases was originally deprecated in NumPy 1.20; for more details and guidance see the original release note at:
原因:np.int 在 NumPy 1.20 中已弃用,在 NumPy 1.24 中已删除。
解决:将容器中的 /PaddleOCR/deploy/hubserving/ocr_system/module.py
/np.ini 文件中的 np.int 更改为np.int_
具体操作如下:
# 进入容器内
docker exec -it ocr /bin/bash
# 修改文件
vim /PaddleOCR/deploy/hubserving/ocr_system/module.py
/np.ini
# 如下位置
for dno in range(dt_num):
text, score = rec_res[dno]
rec_res_final.append({
'text': text,
'confidence': float(score),
'text_region': dt_boxes[dno].astype(np.int_).tolist()
})
all_results.append(rec_res_final)
return all_results
# 修改后重启容器即可解决
docker restart ocr