├── .github └── FUNDING.yml ├── .gitignore ├── Dockerfile ├── LICENSE ├── README.md ├── README_CN.md ├── docker-compose.yml ├── log_conf.yaml ├── main.py ├── models ├── OCRModel.py ├── RestfulModel.py └── __init__.py ├── pp-ocrv4 └── download_det_cls_rec.sh ├── requirements.in ├── requirements.txt ├── routers ├── __init__.py └── ocr.py ├── screenshots └── Swagger.png └── utils ├── ImageHelper.py └── __init__.py /.github/FUNDING.yml: -------------------------------------------------------------------------------- 1 | # These are supported funding model platforms 2 | 3 | github: # Replace with up to 4 GitHub Sponsors-enabled usernames e.g., [user1, user2] 4 | patreon: # Replace with a single Patreon username 5 | open_collective: # Replace with a single Open Collective username 6 | ko_fi: # Replace with a single Ko-fi username 7 | tidelift: # Replace with a single Tidelift platform-name/package-name e.g., npm/babel 8 | community_bridge: # Replace with a single Community Bridge project-name e.g., cloud-foundry 9 | liberapay: # Replace with a single Liberapay username 10 | issuehunt: # Replace with a single IssueHunt username 11 | otechie: # Replace with a single Otechie username 12 | lfx_crowdfunding: # Replace with a single LFX Crowdfunding project-name e.g., cloud-foundry 13 | custom: [ 'https://www.buymeacoffee.com/cgcel' ] # Replace with up to 4 custom sponsorship URLs e.g., ['link1', 'link2'] 14 | -------------------------------------------------------------------------------- /.gitignore: -------------------------------------------------------------------------------- 1 | __pycache__/ 2 | test.py -------------------------------------------------------------------------------- /Dockerfile: -------------------------------------------------------------------------------- 1 | # 使用 Python 3.8 slim 基础镜像 2 | FROM python:3.8-slim-bullseye 3 | 4 | # 暴露端口 5 | EXPOSE 8000 6 | 7 | # 设置工作目录 8 | WORKDIR /app 9 | 10 | # 复制依赖文件并安装系统依赖 11 | COPY requirements.txt /app/requirements.txt 12 | 13 | # 换源并安装系统依赖 14 | RUN sed -i "s@http://deb.debian.org@http://mirrors.tuna.tsinghua.edu.cn@g" /etc/apt/sources.list && \ 15 | apt-get update && \ 16 | apt-get install -y --no-install-recommends \ 17 | libgl1 \ 18 | libgomp1 \ 19 | libglib2.0-0 \ 20 | libsm6 \ 21 | libxrender1 \ 22 | libxext6 && \ 23 | apt-get clean && \ 24 | rm -rf /var/lib/apt/lists/* 25 | 26 | # 换源并安装 Python 依赖 27 | RUN python3 -m pip install -i https://pypi.tuna.tsinghua.edu.cn/simple --upgrade pip && \ 28 | pip3 config set global.index-url https://pypi.tuna.tsinghua.edu.cn/simple && \ 29 | pip3 install --no-cache-dir -r requirements.txt 30 | 31 | # 复制项目文件 32 | COPY . /app 33 | 34 | # 创建模型目录并解压模型文件 35 | RUN mkdir -p /root/.paddleocr/whl/cls/ && \ 36 | mkdir -p /root/.paddleocr/whl/det/ch/ && \ 37 | mkdir -p /root/.paddleocr/whl/rec/ch/ && \ 38 | tar xf /app/pp-ocrv4/ch_ppocr_mobile_v2.0_cls_infer.tar -C /root/.paddleocr/whl/cls/ 2>/dev/null && \ 39 | tar xf /app/pp-ocrv4/ch_PP-OCRv4_det_infer.tar -C /root/.paddleocr/whl/det/ch/ && \ 40 | tar xf /app/pp-ocrv4/ch_PP-OCRv4_rec_infer.tar -C /root/.paddleocr/whl/rec/ch/ && \ 41 | rm -rf /app/pp-ocrv4/*.tar 42 | 43 | # 启动命令 44 | CMD ["uvicorn", "main:app", "--host", "0.0.0.0", "--workers", "2", "--log-config", "./log_conf.yaml"] 45 | -------------------------------------------------------------------------------- /LICENSE: -------------------------------------------------------------------------------- 1 | Copyright 2023 GC Chen 2 | 3 | Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the “Software”), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: 4 | 5 | The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. 6 | 7 | THE SOFTWARE IS PROVIDED “AS IS”, WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. 8 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # PaddleOCRFastAPI 2 | 3 | ![GitHub](https://img.shields.io/github/license/cgcel/PaddleOCRFastAPI) 4 | 5 | [中文](./README_CN.md) 6 | 7 | A simple way to deploy `PaddleOCR` based on `FastAPI`. 8 | 9 | ## Support Version 10 | 11 | | PaddleOCR | Branch | 12 | | :--: | :--: | 13 | | v2.5 | [paddleocr-v2.5](https://github.com/cgcel/PaddleOCRFastAPI/tree/paddleocr-v2.5) | 14 | | v2.7 | [paddleocr-v2.7](https://github.com/cgcel/PaddleOCRFastAPI/tree/paddleocr-v2.7) | 15 | 16 | ## Features 17 | 18 | - [x] Local path image recognition 19 | - [x] Base64 data recognition 20 | - [x] Upload file recognition 21 | 22 | ## Deployment Methods 23 | 24 | ### Deploy Directly 25 | 26 | 1. Copy the project to the deployment path 27 | 28 | ```shell 29 | git clone https://github.com/cgcel/PaddleOCRFastAPI.git 30 | ``` 31 | 32 | > *The master branch is the most recent version of PaddleOCR supported by the project. To install a specific version, clone the branch with the corresponding version number.* 33 | 34 | 2. (Optional) Create new virtual environment to avoid dependency conflicts 35 | 3. Install required dependencies 36 | 37 | ```shell 38 | pip3 install -r requirements.txt 39 | ``` 40 | 41 | 4. Run FastAPI 42 | 43 | ```shell 44 | uvicorn main:app --host 0.0.0.0 45 | ``` 46 | 47 | ### Docker Deployment 48 | 49 | Test completed in `Centos 7`, `Ubuntu 20.04`, `Ubuntu 22.04`, `Windows 10`, `Windows 11`, requires `Docker` to be installed. 50 | 51 | 1. Copy the project to the deployment path 52 | 53 | ```shell 54 | git clone https://github.com/cgcel/PaddleOCRFastAPI.git 55 | ``` 56 | 57 | > *The master branch is the most recent version of PaddleOCR supported by the project. To install a specific version, clone the branch with the corresponding version number.* 58 | 59 | 2. Building a Docker Image 60 | 61 | ```shell 62 | cd PaddleOCRFastAPI 63 | # 手工下载模型,避免程序第一次运行时自动下载,实现完全离线,加快启动速度 64 | cd pp-ocrv4/ && sh download_det_cls_rec.sh 65 | 66 | # 返回Dockfile所在目录,开始build 67 | cd .. 68 | # 使用宿主机网络 69 | # 可直接使用宿主机上的代理设置,例如在build时,用宿主机上的代理 70 | # docker build -t paddleocrfastapi:latest --network host --build-arg HTTP_PROXY=http://127.0.0.1:8888 --build-arg HTTPS_PROXY=http://127.0.0.1:8888 . 71 | docker build -t paddleocrfastapi:latest --network host . 72 | ``` 73 | 74 | 3. Edit `docker-compose.yml` 75 | 76 | ```yaml 77 | version: "3" 78 | 79 | services: 80 | 81 | paddleocrfastapi: 82 | container_name: paddleocrfastapi # Custom Container Name 83 | image: paddleocrfastapi:lastest # Customized Image Name & Label in Step 2 84 | environment: 85 | - TZ=Asia/Hong_Kong 86 | - OCR_LANGUAGE=ch # support 80 languages. refer to https://github.com/Mushroomcat9998/PaddleOCR/blob/main/doc/doc_en/multi_languages_en.md#language_abbreviations 87 | ports: 88 | - "8000:8000" # Customize the service exposure port, 8000 is the default FastAPI port, do not modify 89 | restart: unless-stopped 90 | ``` 91 | 92 | 4. Create the Docker container and run 93 | 94 | ```shell 95 | docker compose up -d 96 | ``` 97 | 98 | 5. Swagger Page at `localhost:/docs` 99 | 100 | ## Change language 101 | 102 | 1. Clone this repo to localhost. 103 | 2. Edit `routers/ocr.py`, modify the parameter "lang": 104 | 105 | ```python 106 | ocr = PaddleOCR(use_angle_cls=True, lang="ch") 107 | ``` 108 | 109 | Before modify, read the [supported language list](https://github.com/PaddlePaddle/PaddleOCR/blob/release/2.7/doc/doc_en/multi_languages_en.md#5-support-languages-and-abbreviations). 110 | 111 | 3. Rebuild the docker image, or run the `main.py` directly. 112 | 113 | ## Screenshots 114 | API Docs: `/docs` 115 | 116 | ![Swagger](https://raw.githubusercontent.com/cgcel/PaddleOCRFastAPI/dev/screenshots/Swagger.png) 117 | 118 | ## Todo 119 | 120 | - [x] support ppocr v4 121 | - [ ] GPU mode 122 | - [x] Image url recognition 123 | 124 | ## License 125 | 126 | **PaddleOCRFastAPI** is licensed under the MIT license. Refer to [LICENSE](https://github.com/cgcel/PaddleOCRFastAPI/blob/master/LICENSE) for more information. 127 | -------------------------------------------------------------------------------- /README_CN.md: -------------------------------------------------------------------------------- 1 | # PaddleOCRFastAPI 2 | 3 | 一个可 Docker (Compose) 部署的, 基于 `FastAPI` 的简易版 Paddle OCR Web API. 4 | 5 | ## 版本选择 6 | 7 | | PaddleOCR | Branch | 8 | | :--: | :--: | 9 | | v2.5 | [paddleocr-v2.5](https://github.com/cgcel/PaddleOCRFastAPI/tree/paddleocr-v2.5) | 10 | | v2.7 | [paddleocr-v2.7](https://github.com/cgcel/PaddleOCRFastAPI/tree/paddleocr-v2.7) | 11 | 12 | ## 接口功能 13 | 14 | - [x] 局域网范围内路径图片 OCR 识别 15 | - [x] Base64 数据识别 16 | - [x] 上传文件识别 17 | 18 | ## 部署方式 19 | 20 | ### 直接部署 21 | 22 | 1. 复制项目至部署路径 23 | 24 | ```shell 25 | git clone https://github.com/cgcel/PaddleOCRFastAPI.git 26 | ``` 27 | 28 | > *master 分支为项目中支持的 PaddleOCR 的最新版本, 如需安装特定版本, 请克隆对应版本号的分支.* 29 | 30 | 2. (可选) 新建虚拟环境, 避免依赖冲突 31 | 3. 安装所需依赖 32 | 33 | ```shell 34 | pip3 install -r requirements.txt 35 | ``` 36 | 37 | 4. 运行 FastAPI 38 | 39 | ```shell 40 | uvicorn main:app --host 0.0.0.0 41 | ``` 42 | 43 | ### Docker 部署 44 | 45 | 在 `Centos 7`, `Ubuntu 20.04`, `Ubuntu 22.04`, `Windows 10`, `Windows 11` 中测试成功, 需要先安装好 `Docker`. 46 | 47 | 1. 复制项目至部署路径 48 | 49 | ```shell 50 | git clone https://github.com/cgcel/PaddleOCRFastAPI.git 51 | ``` 52 | 53 | > *master 分支为项目中支持的 PaddleOCR 的最新版本, 如需安装特定版本, 请克隆对应版本号的分支.* 54 | 55 | 2. 制作 Docker 镜像 56 | 57 | ```shell 58 | cd PaddleOCRFastAPI 59 | # 手工下载模型,避免程序第一次运行时自动下载。实现完全离线,加快启动速度 60 | cd pp-ocrv4/ && sh download_det_cls_rec.sh 61 | 62 | # 返回Dockfile所在目录,开始build 63 | cd .. 64 | # 使用宿主机网络build 65 | # 可以用宿主机上的http_proxy和https_proxy 66 | docker build -t paddleocrfastapi:latest --network host . 67 | ``` 68 | 69 | 3. 编辑 `docker-compose.yml` 70 | 71 | ```yaml 72 | version: "3" 73 | 74 | services: 75 | 76 | paddleocrfastapi: 77 | container_name: paddleocrfastapi # 自定义容器名 78 | image: paddleocrfastapi:latest # 第2步自定义的镜像名与标签 79 | environment: 80 | - TZ=Asia/Hong_Kong 81 | ports: 82 | - "8000:8000" # 自定义服务暴露端口, 8000 为 FastAPI 默认端口, 不做修改 83 | restart: unless-stopped 84 | ``` 85 | 86 | 4. 生成 Docker 容器并运行 87 | 88 | ```shell 89 | docker-compose up -d 90 | ``` 91 | 92 | 5. Swagger 页面请访问 localhost:\/docs 93 | 94 | ## Change language 95 | 96 | 1. 将此仓库克隆至本地. 97 | 2. 编辑 `routers/ocr.py`, 修改参数 "lang": 98 | 99 | ```python 100 | ocr = PaddleOCR(use_angle_cls=True, lang="ch") 101 | ``` 102 | 103 | 编辑前, 先阅读 [supported language list](https://github.com/PaddlePaddle/PaddleOCR/blob/release/2.7/doc/doc_en/multi_languages_en.md#5-support-languages-and-abbreviations). 104 | 105 | 3. 重新创建 docker 镜像, 或直接运行 `main.py`. 106 | 107 | ## 运行截图 108 | API 文档:`/docs` 109 | 110 | ![Swagger](https://raw.githubusercontent.com/cgcel/PaddleOCRFastAPI/dev/screenshots/Swagger.png) 111 | 112 | ## Todo 113 | 114 | - [ ] support ppocr v4 115 | - [ ] GPU mode 116 | - [x] Image url recognition 117 | 118 | ## License 119 | 120 | **PaddleOCRFastAPI** is licensed under the MIT license. Refer to [LICENSE](https://github.com/cgcel/PaddleOCRFastAPI/blob/master/LICENSE) for more information. 121 | -------------------------------------------------------------------------------- /docker-compose.yml: -------------------------------------------------------------------------------- 1 | # version: "3" 2 | 3 | services: 4 | 5 | PaddleOCR: 6 | build: . 7 | container_name: paddle_ocr_api # 自定义容器名 8 | image: paddleocrfastapi:latest # 第2步自定义的镜像名与标签 9 | environment: 10 | - TZ=Asia/Hong_Kong 11 | - OCR_LANGUAGE=ch 12 | ports: 13 | - "8000:8000" # 自定义服务暴露端口, 8000为FastAPI默认端口, 不做修改,只能改前面的8000,不要忘了引号 14 | restart: unless-stopped 15 | -------------------------------------------------------------------------------- /log_conf.yaml: -------------------------------------------------------------------------------- 1 | version: 1 2 | disable_existing_loggers: False 3 | formatters: 4 | default: 5 | # "()": uvicorn.logging.DefaultFormatter 6 | format: '%(asctime)s - %(name)s - %(levelname)s - %(message)s' 7 | access: 8 | # "()": uvicorn.logging.AccessFormatter 9 | format: '%(asctime)s - %(name)s - %(levelname)s - %(message)s' 10 | handlers: 11 | default: 12 | formatter: default 13 | class: logging.StreamHandler 14 | stream: ext://sys.stderr 15 | access: 16 | formatter: access 17 | class: logging.StreamHandler 18 | stream: ext://sys.stdout 19 | loggers: 20 | uvicorn.error: 21 | level: INFO 22 | handlers: 23 | - default 24 | propagate: no 25 | uvicorn.access: 26 | level: INFO 27 | handlers: 28 | - access 29 | propagate: no 30 | root: 31 | level: DEBUG 32 | handlers: 33 | - default 34 | propagate: no 35 | -------------------------------------------------------------------------------- /main.py: -------------------------------------------------------------------------------- 1 | # -*- coding: utf-8 -*- 2 | 3 | # import uvicorn 4 | from fastapi import FastAPI 5 | from fastapi.middleware.cors import CORSMiddleware 6 | # import uvicorn 7 | import yaml 8 | 9 | from models.RestfulModel import * 10 | from routers import ocr 11 | from utils.ImageHelper import * 12 | 13 | app = FastAPI(title="Paddle OCR API", 14 | description="基于 Paddle OCR 和 FastAPI 的自用接口") 15 | 16 | 17 | # 跨域设置 18 | origins = [ 19 | "*" 20 | ] 21 | app.add_middleware( 22 | CORSMiddleware, 23 | allow_origins=origins, 24 | allow_credentials=True, 25 | allow_methods=["*"], 26 | allow_headers=["*"] 27 | ) 28 | 29 | app.include_router(ocr.router) 30 | 31 | # uvicorn.run(app=app, host="0.0.0.0", port=8000) 32 | -------------------------------------------------------------------------------- /models/OCRModel.py: -------------------------------------------------------------------------------- 1 | # -*- coding: utf-8 -*- 2 | 3 | from typing import List, Set 4 | 5 | from pydantic import BaseModel 6 | 7 | 8 | class OCRModel(BaseModel): 9 | coordinate: List # 图像坐标 10 | result: Set 11 | 12 | 13 | class Base64PostModel(BaseModel): 14 | base64_str: str # base64字符串 15 | -------------------------------------------------------------------------------- /models/RestfulModel.py: -------------------------------------------------------------------------------- 1 | # -*- coding: utf-8 -*- 2 | 3 | from typing import List, Union 4 | from pydantic import BaseModel 5 | from fastapi import status 6 | from fastapi.responses import JSONResponse, Response 7 | 8 | from .OCRModel import OCRModel 9 | 10 | class RestfulModel(BaseModel): 11 | resultcode : int = 200 # 响应代码 12 | message: str = None # 响应信息 13 | data: Union[List, str] = [] # 数据 14 | 15 | def resp_200(*, data: Union[list, dict, str]) -> Response: 16 | return JSONResponse( 17 | status_code=status.HTTP_200_OK, 18 | content={ 19 | 20 | 'code': 200, 21 | 'message': "Success", 22 | 'data': data, 23 | } 24 | ) 25 | 26 | def resp_400(*, data: str = None, message: str="BAD REQUEST") -> Response: 27 | return JSONResponse( 28 | status_code=status.HTTP_400_BAD_REQUEST, 29 | content={ 30 | 31 | 'code': 400, 32 | 'message': message, 33 | 'data': data, 34 | } 35 | ) -------------------------------------------------------------------------------- /models/__init__.py: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/velviagris/PaddleOCRFastAPI/3a1de3f36aca1908af1e9c9897e3992a5b9af9cf/models/__init__.py -------------------------------------------------------------------------------- /pp-ocrv4/download_det_cls_rec.sh: -------------------------------------------------------------------------------- 1 | # pp-ocrv4模型下载: 2 | # https://github.com/PaddlePaddle/PaddleOCR/blob/main/docs/model/index.md 3 | wget https://paddleocr.bj.bcebos.com/PP-OCRv4/chinese/ch_PP-OCRv4_det_infer.tar 4 | wget https://paddleocr.bj.bcebos.com/dygraph_v2.0/ch/ch_ppocr_mobile_v2.0_cls_infer.tar 5 | wget https://paddleocr.bj.bcebos.com/PP-OCRv4/chinese/ch_PP-OCRv4_rec_infer.tar 6 | -------------------------------------------------------------------------------- /requirements.in: -------------------------------------------------------------------------------- 1 | FastAPI 2 | paddlepaddle 3 | paddleocr 4 | uvicorn 5 | python-multipart 6 | requests 7 | numpy -------------------------------------------------------------------------------- /requirements.txt: -------------------------------------------------------------------------------- 1 | # 2 | # This file is autogenerated by pip-compile with python 3.8 3 | # To update, run: 4 | # 5 | # pip-compile 6 | # 7 | fastapi==0.101.0 8 | # via -r requirements.in 9 | paddleocr==2.7.0.0 10 | # via -r requirements.in 11 | paddlepaddle==2.5.1 12 | # via -r requirements.in 13 | python-multipart==0.0.6 14 | # via -r requirements.in 15 | uvicorn==0.23.2 16 | # via -r requirements.in 17 | requests==2.31.0 18 | # via -r requirements.in 19 | numpy==1.23.5 20 | # via -r requirements.in 21 | pyyaml 22 | 23 | # The following packages are considered to be unsafe in a requirements file: 24 | # setuptools 25 | -------------------------------------------------------------------------------- /routers/__init__.py: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/velviagris/PaddleOCRFastAPI/3a1de3f36aca1908af1e9c9897e3992a5b9af9cf/routers/__init__.py -------------------------------------------------------------------------------- /routers/ocr.py: -------------------------------------------------------------------------------- 1 | # -*- coding: utf-8 -*- 2 | 3 | from fastapi import APIRouter, HTTPException, UploadFile, status 4 | from models.OCRModel import * 5 | from models.RestfulModel import * 6 | from paddleocr import PaddleOCR 7 | from utils.ImageHelper import base64_to_ndarray, bytes_to_ndarray 8 | import requests 9 | import os 10 | 11 | OCR_LANGUAGE = os.environ.get("OCR_LANGUAGE", "ch") 12 | 13 | router = APIRouter(prefix="/ocr", tags=["OCR"]) 14 | 15 | ocr = PaddleOCR(use_angle_cls=True, lang=OCR_LANGUAGE) 16 | 17 | 18 | @router.get('/predict-by-path', response_model=RestfulModel, summary="识别本地图片") 19 | def predict_by_path(image_path: str): 20 | result = ocr.ocr(image_path, cls=True) 21 | restfulModel = RestfulModel( 22 | resultcode=200, message="Success", data=result, cls=OCRModel) 23 | return restfulModel 24 | 25 | 26 | @router.post('/predict-by-base64', response_model=RestfulModel, summary="识别 Base64 数据") 27 | def predict_by_base64(base64model: Base64PostModel): 28 | img = base64_to_ndarray(base64model.base64_str) 29 | result = ocr.ocr(img=img, cls=True) 30 | restfulModel = RestfulModel( 31 | resultcode=200, message="Success", data=result, cls=OCRModel) 32 | return restfulModel 33 | 34 | 35 | @router.post('/predict-by-file', response_model=RestfulModel, summary="识别上传文件") 36 | async def predict_by_file(file: UploadFile): 37 | restfulModel: RestfulModel = RestfulModel() 38 | if file.filename.endswith((".jpg", ".png")): # 只处理常见格式图片 39 | restfulModel.resultcode = 200 40 | restfulModel.message = file.filename 41 | file_data = file.file 42 | file_bytes = file_data.read() 43 | img = bytes_to_ndarray(file_bytes) 44 | result = ocr.ocr(img=img, cls=True) 45 | restfulModel.data = result 46 | else: 47 | raise HTTPException( 48 | status_code=status.HTTP_400_BAD_REQUEST, 49 | detail="请上传 .jpg 或 .png 格式图片" 50 | ) 51 | return restfulModel 52 | 53 | 54 | @router.get('/predict-by-url', response_model=RestfulModel, summary="识别图片 URL") 55 | async def predict_by_url(imageUrl: str): 56 | restfulModel: RestfulModel = RestfulModel() 57 | response = requests.get(imageUrl) 58 | image_bytes = response.content 59 | if image_bytes.startswith(b"\xff\xd8\xff") or image_bytes.startswith(b"\x89PNG\r\n\x1a\n"): # 只处理常见格式图片 (jpg / png) 60 | restfulModel.resultcode = 200 61 | img = bytes_to_ndarray(image_bytes) 62 | result = ocr.ocr(img=img, cls=True) 63 | restfulModel.data = result 64 | restfulModel.message = "Success" 65 | else: 66 | raise HTTPException( 67 | status_code=status.HTTP_400_BAD_REQUEST, 68 | detail="请上传 .jpg 或 .png 格式图片" 69 | ) 70 | return restfulModel 71 | -------------------------------------------------------------------------------- /screenshots/Swagger.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/velviagris/PaddleOCRFastAPI/3a1de3f36aca1908af1e9c9897e3992a5b9af9cf/screenshots/Swagger.png -------------------------------------------------------------------------------- /utils/ImageHelper.py: -------------------------------------------------------------------------------- 1 | # -*- coding: utf-8 -*- 2 | 3 | import base64 4 | 5 | import cv2 6 | import numpy as np 7 | 8 | 9 | def base64_to_ndarray(b64_data: str): 10 | """base64转numpy数组 11 | 12 | Args: 13 | b64_data (str): base64数据 14 | 15 | Returns: 16 | _type_: _description_ 17 | """ 18 | image_bytes = base64.b64decode(b64_data) 19 | image_np = np.frombuffer(image_bytes, dtype=np.uint8) 20 | image_np2 = cv2.imdecode(image_np, cv2.IMREAD_COLOR) 21 | return image_np2 22 | 23 | 24 | def bytes_to_ndarray(img_bytes: str): 25 | """字节转numpy数组 26 | 27 | Args: 28 | img_bytes (str): 图片字节 29 | 30 | Returns: 31 | _type_: _description_ 32 | """ 33 | image_array = np.frombuffer(img_bytes, dtype=np.uint8) 34 | image_np2 = cv2.imdecode(image_array, cv2.IMREAD_COLOR) 35 | return image_np2 36 | -------------------------------------------------------------------------------- /utils/__init__.py: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/velviagris/PaddleOCRFastAPI/3a1de3f36aca1908af1e9c9897e3992a5b9af9cf/utils/__init__.py --------------------------------------------------------------------------------