📄 Awesome OCR multiple programing languages toolkits based on ONNX Runtime, OpenVINO, MNN, PaddlePaddle, TensorRT and PyTorch.
Add fastapi
SWHLd37329aa4a8f
diff --git a/docs/doc_whl_rapidocr_web.md b/docs/doc_whl_rapidocr_web.mdindex d7f6149..e5c3394 100644--- a/docs/doc_whl_rapidocr_web.md+++ b/docs/doc_whl_rapidocr_web.md@@ -3,65 +3,135 @@<a href=""><img src="https://img.shields.io/badge/Python->=3.7,<=3.10-aff.svg"></a><a href=""><img src="https://img.shields.io/badge/OS-Linux%2C%20Win%2C%20Mac-pink.svg"></a><a href="https://pypi.org/project/rapidocr-web/"><img alt="PyPI" src="https://img.shields.io/pypi/v/rapidocr-web"></a>+ <a href="https://pepy.tech/project/rapidocr_web"><img src="https://static.pepy.tech/personalized-badge/rapidocr_web?period=total&units=abbreviation&left_color=grey&right_color=blue&left_text=Downloads"></a></p>-### 1. Install package by pypi.-```bash-$ pip install rapidocr-web-```+### Web use-### 2. Run by command line.-- Usage:+1. Install package by pypi.```bash- $ rapidocr_web -h- usage: rapidocr_web [-h] [-ip IP] [-p PORT] [-api]-- optional arguments:- -h, --help show this help message and exit- -ip IP, --ip IP IP Address- -p PORT, --port PORT IP port- -api, --is_api Whether to use the api format.+ $ pip install rapidocr-web```-- Example:- ```bash- # Web mode- $ rapidocr_web -ip "0.0.0.0" -p 9003+2. Run by command line.+ - Usage:+ ```bash+ $ rapidocr_web -h+ usage: rapidocr_web [-h] [-ip IP] [-p PORT]- # API mode- $ rapidocr_web -ip "0.0.0.0" -p 9003 -api- ```+ optional arguments:+ -h, --help show this help message and exit+ -ip IP, --ip IP IP Address+ -p PORT, --port PORT IP port+ ```+ - Example:+ ```bash+ $ rapidocr_web -ip "0.0.0.0" -p 9003+ ```+3. Open `http://localhost:9003/` to view, enjoy it.-### 3. Use.-- Web mode: Open `http://localhost:9003/` to view, enjoy it.-- API mode:- ```python- import ast- import base64- import json+### API Use+1. Install`rapidocr_web[api]`+ ```bash+ $ pip install rapidocr_web[api]+ ```+2. Run+ - Usage:+ ```bash+ $ rapidocr_api -h+ usage: rapidocr_api [-h] [-ip IP] [-p PORT]+ optional arguments:+ -h, --help show this help message and exit+ -ip IP, --ip IP IP Address+ -p PORT, --port PORT IP port+ ```+ - Example:+ ```bash+ $ rapidocr_api -ip 0.0.0.0 -p 9003+ ```+3. Use+ ```pythonimport requests+ url = 'http://localhost:9003/ocr'+ img_path = '../python/tests/test_files/ch_en_num.jpg'- def get_json_format(img_path):- with open(img_path, 'rb') as f:- img_byte = base64.b64encode(f.read())- img_json = json.dumps({'file': img_byte.decode('ascii')})- return img_json+ with open(img_path, 'rb') as f:+ file_dict = {'image': (img_path, f, 'image/png')}+ response = requests.post(url, files=file_dict, timeout=60)+ res_rec = response.json()+ print(res_rec)+ ```+4. Output+ <details>+ <summary>Click to expand</summary>- if __name__ == '__main__':- url = 'http://localhost:9003/ocr'- header = {'Content-Type': 'application/json; charset=UTF-8'}-- img_path = '1.jpg'- img_json = get_json_format(img_path)-- response = requests.post(url, data=img_json, headers=header)- if response.status_code == 200:- rec_res = ast.literal_eval(response.text)- print(rec_res)- else:- print(response.status_code)+ ```json+ {+ "0": {+ "rec_txt": "香港深圳抽血,",+ "dt_boxes": [+ [265, 18],+ [472, 231],+ [431, 271],+ [223, 59]+ ],+ "score": "0.8175641223788261"+ },+ "1": {+ "rec_txt": "专业查性别",+ "dt_boxes": [+ [388, 15],+ [636, 257],+ [587, 307],+ [339, 65]+ ],+ "score": "0.8293875356515249"+ },+ "2": {+ "rec_txt": "专业鉴定B超单",+ "dt_boxes": [+ [215, 84],+ [509, 413],+ [453, 463],+ [159, 134]+ ],+ "score": "0.8626169338822365"+ },+ "3": {+ "rec_txt": "b超仪器查性别",+ "dt_boxes": [+ [128, 135],+ [430, 478],+ [366, 534],+ [64, 192]+ ],+ "score": "0.8449362441897392"+ },+ "4": {+ "rec_txt": "加微信eee",+ "dt_boxes": [+ [58, 189],+ [268, 450],+ [209, 498],+ [0, 236]+ ],+ "score": "0.8176911813872201"+ },+ "5": {+ "rec_txt": "可邮寄",+ "dt_boxes": [+ [493, 261],+ [617, 384],+ [577, 423],+ [454, 300]+ ],+ "score": "0.7494261413812637"+ }+ }```+ </details>+### See details for [RapidOCR](https://github.com/RapidAI/RapidOCR/tree/main/ocrweb).\ No newline at end of filediff --git a/ocrweb/README.md b/ocrweb/README.mdindex 50f7fae..6833089 100755--- a/ocrweb/README.md+++ b/ocrweb/README.md@@ -10,7 +10,8 @@- [RapidOCR Web Demo](#rapidocr-web-demo)- [简要说明](#简要说明)- - [使用步骤](#使用步骤)+ - [界面版使用步骤](#界面版使用步骤)+ - [API版使用步骤](#api版使用步骤)### 简要说明@@ -20,14 +21,13 @@```textch_PP-OCRv3_det + ch_ppocr_mobile_v2.0_cls + ch_PP-OCRv3_rec```-- **在线demo运行机器配置:** `4核 AMD EPYC 7K62 48-Core Processor`- 网页上显示的推理时间具体解释如下:<div align="center"><img src="https://github.com/RapidAI/RapidOCR/blob/main/assets/ocrweb_time.jpg" width="80%" height="80%"></div>-### 使用步骤+### 界面版使用步骤1. 安装`rapidocr_web````bashpip install rapidocr_web@@ -37,86 +37,143 @@- 用法:```bash$ rapidocr_web -h- usage: rapidocr_web [-h] [-ip IP] [-p PORT] [-api]+ usage: rapidocr_web [-h] [-ip IP] [-p PORT]optional arguments:-h, --help show this help message and exit-ip IP, --ip IP IP Address-p PORT, --port PORT IP port- -api, --is_api Whether to use the api format.```- 示例:```bash- # 界面模式- $ rapidocr_web -ip "0.0.0.0" -p 9003-- # API调用模式- $ rapidocr_web -ip "0.0.0.0" -p 9003 -api+ $ rapidocr_web -ip 0.0.0.0 -p 9003```3. 使用- - 界面模式:浏览器打开`http://localhost:9003/`,enjoy it.- - API模式:- ```python- # python 示例,本质就是发送一个POST请求,其他语言同理。- import base64- import json-- import requests--- class WebAPI():- def __init__(self, url: str) -> None:- self.url = url- self.header = {'Content-Type': 'application/json; charset=UTF-8'}-- def __call__(self, img_path: str):- img_json = self.get_json_format(img_path)- response = requests.post(self.url,- data=img_json,- headers=self.header)- status_code = response.status_code- if status_code == 200:- return response.json()- raise ValueError(f'requests post error, status code is {status_code}')+ - 浏览器打开`http://localhost:9003/`,enjoy it.- @staticmethod- def get_json_format(img_path: str):- with open(img_path, 'rb') as f:- img_byte = base64.b64encode(f.read())-- img_json = json.dumps({'file': img_byte.decode('ascii')})- return img_json+### API版使用步骤+1. 安装`rapidocr_web[api]`+ ```bash+ $ pip install rapidocr_web[api]+ ```+2. 运行+ - 用法:+ ```bash+ $ rapidocr_api -h+ usage: rapidocr_api [-h] [-ip IP] [-p PORT]- if __name__ == '__main__':- web_url = 'http://localhost:9003/ocr'- img_path = '../images/1.jpg'+ optional arguments:+ -h, --help show this help message and exit+ -ip IP, --ip IP IP Address+ -p PORT, --port PORT IP port+ ```+ - 示例:+ ```bash+ $ rapidocr_api -ip 0.0.0.0 -p 9003+ ```+3. 使用+ ```python+ # python 示例,本质就是发送一个POST请求,其他语言同理。+ import requests- web_api = WebAPI(web_url)+ url = 'http://localhost:9003/ocr'+ img_path = '../python/tests/test_files/ch_en_num.jpg'- res_rec = web_api(img_path)- print(res_rec)- ```+ with open(img_path, 'rb') as f:+ file_dict = {'image': (img_path, f, 'image/png')}+ response = requests.post(url, files=file_dict, timeout=60)+ res_rec = response.json()+ print(res_rec)+ ```4. API输出- 示例结果:- ```text- [- [[[265.0, 18.0], [472.0, 231.0], [431.0, 271.0], [223.0, 59.0]], '香港深圳抽血', 0.8021483932222638],- [[[388.0, 15.0], [636.0, 257.0], [587.0, 307.0], [339.0, 65.0]], '专业查性别', 0.7488822937011719],- [[[215.0, 84.0], [509.0, 413.0], [453.0, 463.0], [159.0, 134.0]], '专业鉴定B超单', 0.8711239919066429],- [[[128.0, 135.0], [430.0, 478.0], [366.0, 534.0], [64.0, 192.0]], 'b超仪器查性别', 0.8705329671502113],- [[[58.0, 189.0], [268.0, 450.0], [209.0, 498.0], [0.0, 236.0]], '加微信eee', 0.8492027946880886],- [[[493.0, 261.0], [617.0, 384.0], [577.0, 423.0], [454.0, 300.0]], '可邮寄', 0.7494295984506607]- ]+ <details>+ <summary>详情</summary>++ ```json+ {+ "0": {+ "rec_txt": "香港深圳抽血,",+ "dt_boxes": [+ [265, 18],+ [472, 231],+ [431, 271],+ [223, 59]+ ],+ "score": "0.8175641223788261"+ },+ "1": {+ "rec_txt": "专业查性别",+ "dt_boxes": [+ [388, 15],+ [636, 257],+ [587, 307],+ [339, 65]+ ],+ "score": "0.8293875356515249"+ },+ "2": {+ "rec_txt": "专业鉴定B超单",+ "dt_boxes": [+ [215, 84],+ [509, 413],+ [453, 463],+ [159, 134]+ ],+ "score": "0.8626169338822365"+ },+ "3": {+ "rec_txt": "b超仪器查性别",+ "dt_boxes": [+ [128, 135],+ [430, 478],+ [366, 534],+ [64, 192]+ ],+ "score": "0.8449362441897392"+ },+ "4": {+ "rec_txt": "加微信eee",+ "dt_boxes": [+ [58, 189],+ [268, 450],+ [209, 498],+ [0, 236]+ ],+ "score": "0.8176911813872201"+ },+ "5": {+ "rec_txt": "可邮寄",+ "dt_boxes": [+ [493, 261],+ [617, 384],+ [577, 423],+ [454, 300]+ ],+ "score": "0.7494261413812637"+ }+ }```- - 输出结果说明:如果图像中存在文字,则会输出`List`类型,具体格式介绍如下:- ```text- [- # 坐标为左上角 → 右上角 → 右下角 → 左下角- [[[left, top], [right, top], [right, bottom], [left, bottom]], 识别文本, 置信度]- ]+ </details>++ - 输出结果说明:+ - 如果图像中存在文字,则会输出json格式,具体格式介绍如下:+ ```python+ {+ "0": {+ "rec_txt": "香港深圳抽血,", # 识别的文本+ "dt_boxes": [ # 依次为左上角 → 右上角 → 右下角 → 左下角+ [265, 18],+ [472, 231],+ [431, 271],+ [223, 59]+ ],+ "score": "0.8175641223788261" # 置信度+ }+ }```- - 如果没有检测到文字,则会输出空列表(`[]`)。-5. **!!说明:OCR的输出结果为最原始结果,大家可按需进一步扩展。**+ - 如果没有检测到文字,则会输出空json(`{}`)。+5. **!!说明:OCR的输出结果为最原始结果,大家可按需进一步扩展。**\ No newline at end of filediff --git a/ocrweb/rapidocr_web/api.py b/ocrweb/rapidocr_web/api.pynew file mode 100644index 0000000..12fc4b1--- /dev/null+++ b/ocrweb/rapidocr_web/api.py@@ -0,0 +1,61 @@+# -*- encoding: utf-8 -*-+# @Author: SWHL+# @Contact: [email protected]+import argparse+import json++import cv2+import numpy as np+import uvicorn+from fastapi import FastAPI, UploadFile+from PIL import Image+from rapidocr_onnxruntime import RapidOCR+++class OCRAPIUtils():+ def __init__(self) -> None:+ self.ocr = RapidOCR()++ def __call__(self, img):+ img = np.array(img)+ img = cv2.cvtColor(img, cv2.COLOR_RGB2BGR)++ ocr_res, _ = self.ocr(img)+ if not ocr_res:+ return json.dumps({})++ out_dict = {str(i): {'rec_txt': rec,+ 'dt_boxes': dt_box,+ 'score': score}+ for i, (dt_box, rec, score) in enumerate(ocr_res)}+ return json.dumps(out_dict, indent=2, ensure_ascii=False)+++app = FastAPI()+processor = OCRAPIUtils()++[email protected]("/")+async def root():+ return {'message': 'Welcome to RapidOCR Server!'}++[email protected]('/ocr')+async def ocr(image: UploadFile):+ image = Image.open(image.file)+ ocr_res = processor(image)+ 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')+ args = parser.parse_args()+ uvicorn.run(app, host=args.ip, port=args.port)+++if __name__ == '__main__':+ main()diff --git a/ocrweb/rapidocr_web/ocrweb.py b/ocrweb/rapidocr_web/ocrweb.pyindex de45234..e11c49e 100644--- a/ocrweb/rapidocr_web/ocrweb.py+++ b/ocrweb/rapidocr_web/ocrweb.py@@ -6,10 +6,7 @@ from pathlib import Pathfrom wsgiref.simple_server import make_serverfrom flask import Flask, render_template, request-try:- from .task import OCRWebUtils-except:- from task import OCRWebUtils+from rapidocr_web.task import OCRWebUtilsroot_dir = Path(__file__).resolve().parent@@ -20,15 +17,14 @@ processor = OCRWebUtils()@app.route('/')def index():- if not app.config['is_api']:- return render_template('index.html')+ return render_template('index.html')@app.route('/ocr', methods=['POST'])def ocr():if request.method == 'POST':img_str = request.get_json().get('file', None)- ocr_res = processor(img_str, is_api=app.config['is_api'])+ ocr_res = processor(img_str)return ocr_res@@ -38,11 +34,8 @@ def main():help='IP Address')parser.add_argument('-p', '--port', type=int, default=9003,help='IP port')- parser.add_argument('-api', '--is_api', action='store_true',- default=False, help='Whether to use the api format.')args = parser.parse_args()- app.config['is_api'] = args.is_apiserver = make_server(args.ip, args.port, app)server.serve_forever()diff --git a/ocrweb/rapidocr_web/task.py b/ocrweb/rapidocr_web/task.pyindex 2171bdb..f37f591 100644--- a/ocrweb/rapidocr_web/task.py+++ b/ocrweb/rapidocr_web/task.py@@ -4,13 +4,12 @@import base64import copyimport json+from collections import namedtuplefrom functools import reducefrom typing import List, Tuple, Union-from collections import namedtupleimport cv2import numpy as np-from rapidocr_onnxruntime import RapidOCR@@ -21,21 +20,15 @@ class OCRWebUtils():'WebReturn',['image', 'total_elapse', 'elapse_part', 'rec_res'])- def __call__(self, img_content: str, is_api=False) -> namedtuple:+ def __call__(self, img_content: str) -> namedtuple:if img_content is None:raise ValueError('img is None')-- img = self.prepare_img(img_content, is_api)+ img = self.prepare_img(img_content)ocr_res, elapse = self.ocr(img)-- if is_api:- return self.get_api_result(ocr_res)return self.get_web_result(img, ocr_res, elapse)- def prepare_img(self, img_str: str, is_api: bool) -> np.ndarray:- if not is_api:- img_str = img_str.split(',')[1]-+ def prepare_img(self, img_str: str) -> np.ndarray:+ img_str = img_str.split(',')[1]image = base64.b64decode(img_str + '=' * (-len(img_str) % 4))nparr = np.frombuffer(image, np.uint8)image = cv2.imdecode(nparr, cv2.IMREAD_COLOR)@@ -43,9 +36,6 @@ class OCRWebUtils():image = cv2.cvtColor(image, cv2.COLOR_GRAY2BGR)return image- def get_api_result(self, ocr_res: List) -> str:- return json.dumps(ocr_res, indent=2, ensure_ascii=False)-def get_web_result(self,img: np.ndarray,ocr_res: List,@@ -73,7 +63,7 @@ class OCRWebUtils():@staticmethoddef img_to_base64(img) -> str:- img = cv2.imencode('.jpg', img)[1]+ img = cv2.imencode('.png', img)[1]img_str = str(base64.b64encode(img))[2:-1]return img_strdiff --git a/ocrweb/requirements.txt b/ocrweb/requirements.txtindex 7b13fb3..113a704 100644--- a/ocrweb/requirements.txt+++ b/ocrweb/requirements.txt@@ -4,3 +4,5 @@ Flask>=2.1.0rapidocr_onnxruntimeget_pypi_latest_versionwheel+fastapi+uvicorn[standard]diff --git a/ocrweb/setup.py b/ocrweb/setup.pyindex 8e06aae..2e42cf7 100644--- a/ocrweb/setup.py+++ b/ocrweb/setup.py@@ -61,6 +61,11 @@ setuptools.setup(],python_requires='>=3.6,<=3.10',entry_points={- 'console_scripts': [f'{MODULE_NAME}={MODULE_NAME}.ocrweb:main'],+ 'console_scripts': [+ f'{MODULE_NAME}={MODULE_NAME}.ocrweb:main',+ f'rapidocr_api={MODULE_NAME}.api.main'],},+ extras_require={+ 'api': ['fastapi', 'uvicorn[standard]']+ })