fastapi_rapidocr / main.py
HycJack's picture
add file
5bf1b3e
raw
history blame
1.15 kB
from fastapi import FastAPI, File, UploadFile
app = FastAPI()
from rapidocr_onnxruntime import RapidOCR
# det_model_path同理
model = RapidOCR()
# 1、导入对应的包
from fastapi.middleware.cors import CORSMiddleware
app = FastAPI()
# 2、声明一个 源 列表;重点:要包含跨域的客户端 源
origins = [
"https://hycjack-fastapi-rapidocr.hf.space/",
"http://localhost",
"http://localhost:7860",
# 客户端的源
"http://127.0.0.1:7860"
]
# 3、配置 CORSMiddleware
app.add_middleware(
CORSMiddleware,
allow_origins=origins, # 允许访问的源
allow_credentials=True, # 支持 cookie
allow_methods=["*"], # 允许使用的请求方法
allow_headers=["*"] # 允许携带的 Headers
)
@app.get("/")
def read_root():
return {"Hello": "World!"}
@app.post("/ocr")
async def ocr(file: UploadFile = File(...)):
# 读取上传的文件内容
contents = await file.read()
# 使用Pillow打开图像
image = Image.open(io.BytesIO(contents))
# 将图像转换为numpy数组
np_array = np.array(image)
result, elapse = model(np_array)
return result