Spaces:
Sleeping
Sleeping
File size: 1,424 Bytes
aa4728b 0125000 1cdc160 0125000 b9d651c 1cdc160 08606b0 5bf1b3e 08606b0 1cdc160 b9d651c 1cdc160 b9d651c |
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 |
from fastapi import FastAPI, File, UploadFile
from PIL import Image
from fastapi.middleware.cors import CORSMiddleware
from rapidocr_onnxruntime import RapidOCR
import io
import numpy as np
import pandas as pd
# det_model_path同理
model = RapidOCR()
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)
ocr_result, elapse = model(np_array)
dt_boxes, rec_res, scores = list(zip(*ocr_result))
out_df = pd.DataFrame(
[[box, rec, score] for box, rec, score in zip(dt_boxes, rec_res, scores)],
columns=("box", "rec", "score"),
)
return out_df.to_dict(orient='records')
|