import json
from base64 import b64decode

import cv2
import numpy as np
from fastapi import FastAPI, Request
from fastapi.middleware.cors import CORSMiddleware
from pydantic import BaseModel
from paddleocr import PaddleOCR, PPStructure
from sx_utils.sxweb import *
from sx_utils.sximage import *

import os

# 初始化app
app = FastAPI()
origins = ["*"]

app.add_middleware(
    CORSMiddleware,
    allow_origins=origins,
    allow_credentials=True,
    allow_methods=["*"],
    allow_headers=["*"],
)

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

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

# 初始化模型
table_engine = PPStructure(layout=False, table=True, show_log=True, table_model_dir="/Users/sxkj/opt/python-workspace/yili-ocr/ocr-table/table_ocr_infer")


class TableInfo(BaseModel):
    image: str


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



@app.post("/ocr_system/table")
@web_try()
def table(image: TableInfo):
    img = base64_to_np(image.image)
    res = table_engine(img)
    return res[0]['res']


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)
