from fastapi import FastAPI, Request from fastapi.middleware.cors import CORSMiddleware from pydantic import BaseModel from paddleocr import PaddleOCR from core.ocr import * from utils.image import * from utils.time import timeit from utils.web import web_try import os # 导入一些包 app = FastAPI() origins = ["*"] # CORS 跨源资源共享 app.add_middleware( CORSMiddleware, allow_origins=origins, allow_credentials=True, allow_methods=["*"], allow_headers=["*"], ) use_gpu = os.getenv('USE_CUDA') == 'gpu' print(f'use gpu: {use_gpu}') ocr = PaddleOCR(use_angle_cls=True, rec_model_dir='models/rec/', det_model_dir='models/det/', cls_model_dir='models/cls/', rec_char_type='ch', use_gpu=use_gpu, warmup=True) p = Ocr(ocr) class PPOcrInfo(BaseModel): image: str # Get 健康检查 @app.get("/ping") def ping(): return "pong!" @app.post("/ppocr") @timeit @web_try() def cet(request: Request, ppocr: PPOcrInfo): return p.predict(base64_to_np(ppocr.image)) if __name__ == '__main__': import uvicorn import argparse parser = argparse.ArgumentParser() parser.add_argument('--host', default='0.0.0.0') parser.add_argument('--port', default=8080) opt = parser.parse_args() app_str = 'server:app' # make the app string equal to whatever the name of this file is uvicorn.run(app_str, host=opt.host, port=int(opt.port), reload=True)