from fastapi import FastAPI, Request
from fastapi.middleware.cors import CORSMiddleware
from pydantic import BaseModel
from paddleocr import PaddleOCR
from sx_utils.sximage import *
from sx_utils.sxtime import sxtimeit
from sx_utils.sxweb import web_try
from core.ocr import IdCardOcr
import os


app = FastAPI()

origins = ["*"]

app.add_middleware(
    CORSMiddleware,
    allow_origins=origins,
    allow_credentials=True,
    allow_methods=["*"],
    allow_headers=["*"],
)
# templates = Jinja2Templates(directory='templates')

use_gpu = False
if os.getenv('USE_CUDA') == 'gpu':
    use_gpu = True

print(f'use gpu: {use_gpu}')

# 初始化ocr模型和后处理模型
ocr = PaddleOCR(use_angle_cls=True,
                rec_model_dir="./idcard_rec_infer/",
                det_model_dir="./idcard_det_infer/",
                cls_model_dir="idcard_cls_infer",
                rec_algorithm='CRNN',
                ocr_version='PP-OCRv2',
                rec_char_dict_path="./ppocr_keys_v1.txt", lang="ch",
                use_gpu=use_gpu,
                warmup=True)

m = IdCardOcr(ocr)

@app.get("/ping")
def ping():
    return "pong!"

# @app.get("/")
# def home(request: Request):
#     ''' Returns html jinja2 template render for home page form
#     '''
#
#     return templates.TemplateResponse('home.html', {
#             "request": request,
#         })


class IdCardInfo(BaseModel):
    image: str
    image_type: str

# /ocr_system/bankcard 银行卡
# /ocr_system/regbook 户口本
# /ocr_system/schoolcert 学信网

@app.post("/ocr_system/idcard")
@sxtimeit
@web_try()
def idcard(request: Request, id_card: IdCardInfo):
    image = base64_to_np(id_card.image)

    return m.predict(image, id_card.image_type)


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)
