server.py 1.5 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364
  1. from fastapi import FastAPI, Request
  2. from fastapi.middleware.cors import CORSMiddleware
  3. from pydantic import BaseModel
  4. from paddleocr import PaddleOCR
  5. from core.ocr import *
  6. from utils.image import *
  7. from utils.time import timeit
  8. from utils.web import web_try
  9. import os
  10. # 导入一些包
  11. app = FastAPI()
  12. origins = ["*"]
  13. # CORS 跨源资源共享
  14. app.add_middleware(
  15. CORSMiddleware,
  16. allow_origins=origins,
  17. allow_credentials=True,
  18. allow_methods=["*"],
  19. allow_headers=["*"],
  20. )
  21. use_gpu = os.getenv('USE_CUDA') == 'gpu'
  22. print(f'use gpu: {use_gpu}')
  23. ocr = PaddleOCR(use_angle_cls=True,
  24. rec_model_dir='models/rec/',
  25. det_model_dir='models/det/',
  26. cls_model_dir='models/cls/',
  27. rec_char_type='ch',
  28. use_gpu=use_gpu,
  29. warmup=True)
  30. p = Ocr(ocr)
  31. class PPOcrInfo(BaseModel):
  32. image: str
  33. # Get 健康检查
  34. @app.get("/ping")
  35. def ping():
  36. return "pong!"
  37. @app.post("/ppocr")
  38. @timeit
  39. @web_try()
  40. def cet(request: Request, ppocr: PPOcrInfo):
  41. return p.predict(base64_to_np(ppocr.image))
  42. if __name__ == '__main__':
  43. import uvicorn
  44. import argparse
  45. parser = argparse.ArgumentParser()
  46. parser.add_argument('--host', default='0.0.0.0')
  47. parser.add_argument('--port', default=8080)
  48. opt = parser.parse_args()
  49. app_str = 'server:app' # make the app string equal to whatever the name of this file is
  50. uvicorn.run(app_str, host=opt.host, port=int(opt.port), reload=True)