1、使用FastAPI创建服务实例
import os
from fastapi import FastAPI, File, UploadFile
from paddleocr import PaddleOCR
import uvicorn
from typing import List
from PIL import Image
import numpy as np
# 初始化 PaddleOCR
ocr = PaddleOCR(lang='ch')
# 创建 FastAPI 实例
app = FastAPI()
# 定义 OCR 接口
@app.post("/ocr/")
async def perform_ocr(files: List[UploadFile] = File(...)):
# 获取环境变量 OCR_NEWLINE,默认为 False
newline_flag = os.getenv("OCR_NEWLINE", "false").lower() == "true"
results = ""
for file in files:
contents = await file.read()
# 将图像保存到临时文件并执行 OCR
with open(f"/tmp/{file.filename}", "wb") as f:
f.write(contents)
# 调整图像大小
image = Image.open(f"/tmp/{file.filename}")
image = image.resize((1280, 720), Image.LANCZOS)
# 将 PIL 图像转换为 NumPy 数组
image_np = np.array(image)
result = ocr.ocr(image_np, cls=True)
# 保存识别结果
for line in result:
for word_info in line:
text = word_info[1][0]
if newline_flag:
results += text + "\n" # 使用换行符
else:
results += text + " "
return {"ocr_text": results}
# 定义多张图片 OCR 接口
@app.post("/multi_ocr/")
async def perform_multi_ocr(files: List[UploadFile] = File(...)):
# 获取环境变量 OCR_NEWLINE,默认为 False
newline_flag = os.getenv("OCR_NEWLINE", "false").lower() == "true"
results = []
for file in files:
contents = await file.read()
# 将图像保存到临时文件并执行 OCR
print(f"Processing file: {file.filename}")
with open(f"/tmp/{file.filename}", "wb") as f:
f.write(contents)
# 调整图像大小
image = Image.open(f"/tmp/{file.filename}")
image = image.resize((1280, 720), Image.LANCZOS)
# 将 PIL 图像转换为 NumPy 数组
image_np = np.array(image)
# 保存识别结果
result = ocr.ocr(image_np, cls=True)
image_result = ""
for line in result:
for word_info in line:
text = word_info[1][0]
if newline_flag:
image_result += text + "\n" # 使用换行符
else:
image_result += text + " "
results.append({"filename": file.filename, "ocr_text": image_result.strip()}) # 添加每张图片的结果
return {"ocr_results": results}
# 主函数,运行 API
if __name__ == "__main__":
uvicorn.run(app, host="0.0.0.0", port=6012)
2、编写Dockerfile
# 使用 Python 基础镜像
FROM python:3.12-slim
# 设置工作目录
WORKDIR /app
# 安装系统依赖(包括 git 和编译工具等)
RUN apt-get update && apt-get install -y \
libgl1-mesa-glx \
libglib2.0-0 \
libgomp1 \
&& rm -rf /var/lib/apt/lists/*
# 安装 PaddleOCR 所需的依赖包
COPY requirements.txt .
RUN pip install --no-cache-dir -r requirements.txt
# 复制应用程序代码
COPY . .
# 暴露 API 服务端口
EXPOSE 6012
# 启动 FastAPI 应用
CMD ["uvicorn", "app:app", "--host", "0.0.0.0", "--port", "6012"]
3、requirements.txt
flask
setuptools
fastapi
uvicorn
python-multipart
paddlepaddle
paddleocr
4、构建镜像&运行容器
# 可以把本地的whl打包到model,便于离线环境使用。
docker build -t paddleocr-api .
docker run --name paddleocr-api --privileged -p 6012:6012 -e OCR_NEWLINE=true -v $PWD/model:/root/.paddleocr -d paddleocr-api:1.0