'''
部署再h5物理机。给超哥开接口。识别图片中的文本
'''
from paddleocr import PaddleOCR
import logging
from flask import Flask, request, jsonify

app = Flask(__name__)
logging.getLogger('ppocr').setLevel(logging.ERROR)


def OCR(language, url):
    try:
        # language = 'en'
        # url = 'http://soundasia.oss-cn-shenzhen.aliyuncs.com/product_img/2024/12/05/EQ6368_1733363300_%E7%94%BB%E6%9D%BF%203.jpg'
        # path = r'D:\新建文件夹\requests_files'
        ocr = PaddleOCR(use_angle_cls=True, lang=language)
        result = ocr.ocr(url, cls=True)
        data_list = []
        for idx in range(len(result)):
            res = result[idx]
            for line in res:
                xy_dict = {}
                xy_dict['a'] = {'x': line[0][0][0], 'y': line[0][0][1]}
                xy_dict['b'] = {'x': line[0][1][0], 'y': line[0][1][1]}
                xy_dict['c'] = {'x': line[0][2][0], 'y': line[0][2][1]}
                xy_dict['d'] = {'x': line[0][3][0], 'y': line[0][3][1]}
                xy_dict['value'] = line[1][0]
                xy_dict['accuracy'] = round(line[1][1], 3)
                data_list.append(xy_dict)
        # data_json = json.dumps(data_list)
        if data_list:
            return data_list
        else:
            return None
        # with open(rf'{path}', 'w', encoding='utf-8')as f:
        #     f.write(data_json)
    except Exception as e:
        print('识别错误。。', e)
        return 'error'


@app.route('/cron/staff/toOCR', methods=['GET'])
def get_args():
    language = request.args.get('language')
    url = request.args.get('url')
    if language and url and 'http' in url:
        data_json = OCR(language, url)
        if data_json:
            items = {"code": 200, "message": "success", 'items': data_json}
        elif data_json == 'error':
            items = {"code": 500, "message": "Something went wrong while downloading models", 'items': None}
        else:
            items = {"code": 200, "message": "check Image Url", 'items': data_json}
    else:
        items = {"code": 400, "message": "Parameter error", 'items': None}
    return jsonify(items)


if __name__ == '__main__':
    app.run('0.0.0.0', 10245)
