-
-
Notifications
You must be signed in to change notification settings - Fork 398
/
Copy pathmain.py
131 lines (107 loc) · 3.66 KB
/
main.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
# -*- 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()
@app.get("/")
def root():
return {"message": "Welcome to RapidOCR API Server!"}
@app.post("/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()