📄 Awesome OCR multiple programing languages toolkits based on ONNX Runtime, OpenVINO, MNN, PaddlePaddle, TensorRT and PyTorch.
chore(rapidocr_api): move rapidocr_api to independent repo
SWHL395d30a440d1
diff --git a/api/Dockerfile b/api/Dockerfiledeleted file mode 100644index 6cc29aa..0000000--- a/api/Dockerfile+++ /dev/null@@ -1,21 +0,0 @@-FROM python:3.10.11-slim-buster--ENV DEBIAN_FRONTEND=noninteractive--# 设置工作目录-WORKDIR /app--# 安装vim,如果不需要临时修改容器文件,此步骤可以删-RUN apt-get update && \- apt-get install -y --no-install-recommends vim && \- apt-get clean && \- rm -rf /var/lib/apt/lists/*--RUN set -eux; \- pip install --no-cache-dir rapidocr_api pillow rapidocr-onnxruntime==1.3.25 -i https://mirrors.aliyun.com/pypi/simple; \- pip uninstall -y opencv-python; \- pip install --no-cache-dir opencv-python-headless -i https://mirrors.aliyun.com/pypi/simple--EXPOSE 9003--CMD ["bash", "-c", "rapidocr_api -ip 0.0.0.0 -p 9003 -workers 2"]diff --git a/api/README.md b/api/README.mdindex 3d153be..33894ef 100644--- a/api/README.md+++ b/api/README.md@@ -1 +1,3 @@+### See [RapidOCRAPI](https://github.com/RapidAI/RapidOCRAPI) for details+### See [Documentation](https://rapidai.github.io/RapidOCRDocs/install_usage/rapidocr_api/usage/)diff --git a/api/demo.py b/api/demo.pydeleted file mode 100644index 9db8671..0000000--- a/api/demo.py+++ /dev/null@@ -1,50 +0,0 @@-# -*- encoding: utf-8 -*--# @Author: SWHL-# @Contact: [email protected]-import base64-import time--import requests--url = "http://localhost:9003/ocr"-img_path = "../python/tests/test_files/ch_en_num.jpg"--# 方式一:使用base64编码传-stime = time.time()-with open(img_path, "rb") as fa:- img_str = base64.b64encode(fa.read())--payload = {"image_data": img_str}-response = requests.post(url, data=payload) # , timeout=60--print(response.json())-etime = time.time() - stime-print(f"用时:{etime:.3f}秒")--print("-" * 40)--# 方式二:使用文件上传方式-stime = time.time()-with open(img_path, "rb") as f:- file_dict = {"image_file": (img_path, f, "image/png")}- response = requests.post(url, files=file_dict) # , timeout=60- print(response.json())--etime = time.time() - stime-print(f"用时:{etime:.3f}秒")-print("-" * 40)--# 方式三:控制是否使用检测、方向分类和识别这三部分的模型; 不使用检测模型:use_det=False-stime = time.time()-img_path = "../python/tests/test_files/test_without_det.jpg"--with open(img_path, "rb") as f:- file_dict = {"image_file": (img_path, f, "image/png")}- # 添加控制参数- data = {"use_det": False, "use_cls": True, "use_rec": True}- response = requests.post(url, files=file_dict, data=data) # , timeout=60- print(response.json())--etime = time.time() - stime-print(f"用时:{etime:.3f}秒")-print("-" * 40)diff --git a/api/rapidocr_api/__init__.py b/api/rapidocr_api/__init__.pydeleted file mode 100644index 0ecdd4f..0000000--- a/api/rapidocr_api/__init__.py+++ /dev/null@@ -1,3 +0,0 @@-# -*- encoding: utf-8 -*--# @Author: SWHL-# @Contact: [email protected]diff --git a/api/rapidocr_api/main.py b/api/rapidocr_api/main.pydeleted file mode 100644index b37598e..0000000--- a/api/rapidocr_api/main.py+++ /dev/null@@ -1,131 +0,0 @@-# -*- encoding: utf-8 -*--# @Author: SWHL-# @Contact: [email protected]-import argparse-import base64-import importlib.util-import io-import os-import sys-from pathlib import Path-from typing import Dict--import numpy as np-import uvicorn-from fastapi import FastAPI, Form, UploadFile-from PIL import Image--if importlib.util.find_spec("rapidocr_onnxruntime"):- from rapidocr_onnxruntime import RapidOCR-elif importlib.util.find_spec("rapidocr_paddle"):- from rapidocr_paddle import RapidOCR-elif importlib.util.find_spec("rapidocr_openvino"):- from rapidocr_openvino import RapidOCR-else:- raise ImportError(- "Please install one of [rapidocr_onnxruntime,rapidocr-paddle,rapidocr-openvino]"- )--sys.path.append(str(Path(__file__).resolve().parent.parent))---class OCRAPIUtils:- def __init__(self) -> None:- det_model_path = os.getenv("det_model_path", None)- cls_model_path = os.getenv("cls_model_path", None)- rec_model_path = os.getenv("rec_model_path", None)-- if det_model_path is None or cls_model_path is None or rec_model_path is None:- self.ocr = RapidOCR()- else:- self.ocr = RapidOCR(- det_model_path=det_model_path,- cls_model_path=cls_model_path,- rec_model_path=rec_model_path,- )-- def __call__(- self, img: Image.Image, use_det=None, use_cls=None, use_rec=None, **kwargs- ) -> Dict:- img = np.array(img)- ocr_res, _ = self.ocr(- img, use_det=use_det, use_cls=use_cls, use_rec=use_rec, **kwargs- )-- if not ocr_res:- return {}-- out_dict = {}- for i, dats in enumerate(ocr_res):- values = {}- for dat in dats:- if isinstance(dat, str):- values["rec_txt"] = dat-- if isinstance(dat, np.float32):- values["score"] = f"{dat:.4f}"-- if isinstance(dat, list):- values["dt_boxes"] = dat- out_dict[str(i)] = values-- return out_dict---app = FastAPI()-processor = OCRAPIUtils()--[email protected]("/")-def root():- return {"message": "Welcome to RapidOCR API Server!"}--[email protected]("/ocr")-def ocr(- image_file: UploadFile = None,- image_data: str = Form(None),- use_det: bool = Form(None),- use_cls: bool = Form(None),- use_rec: bool = Form(None),-):- if image_file:- img = Image.open(image_file.file)- elif image_data:- img_bytes = str.encode(image_data)- img_b64decode = base64.b64decode(img_bytes)- img = Image.open(io.BytesIO(img_b64decode))- else:- raise ValueError(- "When sending a post request, data or files must have a value."- )- ocr_res = processor(img, use_det=use_det, use_cls=use_cls, use_rec=use_rec)- return ocr_res---def main():- parser = argparse.ArgumentParser("rapidocr_api")- parser.add_argument("-ip", "--ip", type=str, default="0.0.0.0", help="IP Address")- parser.add_argument("-p", "--port", type=int, default=9003, help="IP port")- parser.add_argument(- "-workers", "--workers", type=int, default=1, help="number of worker process"- )- args = parser.parse_args()-- # 修改 uvicorn 的默认日志配置- log_config = uvicorn.config.LOGGING_CONFIG- log_config["formatters"]["access"]["fmt"] = "%(asctime)s %(levelname)s %(message)s"- log_config["formatters"]["default"]["fmt"] = "%(asctime)s %(levelname)s %(message)s"-- uvicorn.run(- "rapidocr_api.main:app",- host=args.ip,- port=args.port,- reload=0,- workers=args.workers,- log_config=log_config,- )---if __name__ == "__main__":- main()diff --git a/api/requirements.txt b/api/requirements.txtdeleted file mode 100644index e58d9a2..0000000--- a/api/requirements.txt+++ /dev/null@@ -1,4 +0,0 @@-requests-fastapi-uvicorn[standard]-python-multipart\ No newline at end of filediff --git a/api/setup.py b/api/setup.pydeleted file mode 100644index 0f852fa..0000000--- a/api/setup.py+++ /dev/null@@ -1,84 +0,0 @@-# -*- encoding: utf-8 -*--# @Author: SWHL-# @Contact: [email protected]-import sys-from pathlib import Path-from typing import List--import setuptools-from get_pypi_latest_version import GetPyPiLatestVersion---def read_txt(txt_path: str) -> List:- if not isinstance(txt_path, str):- txt_path = str(txt_path)-- with open(txt_path, "r", encoding="utf-8") as f:- data = list(map(lambda x: x.rstrip("\n"), f))- return data---def get_readme():- root_dir = Path(__file__).resolve().parent.parent- readme_path = str(root_dir / "docs" / "doc_whl_rapidocr_api.md")- with open(readme_path, "r", encoding="utf-8") as f:- readme = f.read()- return readme---MODULE_NAME = "rapidocr_api"--obtainer = GetPyPiLatestVersion()-try:- latest_version = obtainer(MODULE_NAME)-except ValueError:- latest_version = "0.0.1"-VERSION_NUM = obtainer.version_add_one(latest_version, add_patch=True)--if len(sys.argv) > 2:- match_str = " ".join(sys.argv[2:])- matched_versions = obtainer.extract_version(match_str)- if matched_versions:- VERSION_NUM = matched_versions-sys.argv = sys.argv[:2]--setuptools.setup(- name=MODULE_NAME,- version=VERSION_NUM,- platforms="Any",- description="A cross platform OCR API Library based on OnnxRuntime.",- long_description=get_readme(),- long_description_content_type="text/markdown",- author="SWHL",- author_email="[email protected]",- url="https://github.com/RapidAI/RapidOCR",- download_url="https://github.com/RapidAI/RapidOCR.git",- license="Apache-2.0",- include_package_data=True,- install_requires=read_txt("requirements.txt"),- packages=[MODULE_NAME],- package_data={"": ["*.ico", "*.css", "*.js", "*.html"]},- keywords=[- "ocr,text_detection,text_recognition,db,onnxruntime,paddleocr,openvino,rapidocr"- ],- classifiers=[- "Programming Language :: Python :: 3.6",- "Programming Language :: Python :: 3.7",- "Programming Language :: Python :: 3.8",- "Programming Language :: Python :: 3.9",- "Programming Language :: Python :: 3.10",- "Programming Language :: Python :: 3.11",- "Programming Language :: Python :: 3.12",- ],- python_requires=">=3.6,<3.13",- entry_points={- "console_scripts": [- f"{MODULE_NAME}={MODULE_NAME}.main:main",- ],- },- extras_require={- "onnx": ["rapidocr-onnxruntime"],- "paddle": ["rapidocr-paddle"],- "openvino": ["rapidocr-openvino"],- },-)