import cv2
import math
import numpy as np


def preprocess(img_path, new_shape=(48, 320)):
    img = cv2.imread(img_path)
    h, w, _ = img.shape
    resized_h = new_shape[0]
    resized_w = min(math.ceil((w / h) * resized_h), new_shape[1])
    img = cv2.resize(img, (resized_w, resized_h)).astype('float32')
    img = (img - 127.5) * 0.0078125
    padding_im = np.zeros((new_shape[0], new_shape[1], 3), dtype=np.float32)
    padding_im[:, :resized_w, :] = img
    padding_im = np.expand_dims(padding_im, axis=0)
    return padding_im


def postprocess(outputs, character):
    result_list = []
    preds_idx = outputs.argmax(axis=2)
    preds_prob = outputs.max(axis=2)
    for batch_idx, pred_idx in enumerate(preds_idx):
        char_list = []
        conf_list = []
        pre_c = pred_idx[0]
        if pre_c != 0:
            char_list.append(character[pre_c])
            conf_list.append(preds_prob[batch_idx][0])
        for idx, c in enumerate(pred_idx):
            if (pre_c == c) or (c == 0):
                if c == 0:
                    pre_c = c
                continue
            char_list.append(character[c])
            conf_list.append(preds_prob[batch_idx][idx])
            pre_c = c
        result_list.append((''.join(char_list), np.mean(conf_list)))
    return result_list