#include <Sample.h>
#include <opencv2/dnn.hpp>
#include <SimpleLog.h>
#include <Filesystem.h>
#include <Crnn.h>
#include <fstream>


using namespace std;
using namespace cv;
using namespace cv::dnn;
using namespace migraphx;
using namespace migraphxSamples;


void Sample_Crnn()
{
    // 创建CRNN文本识别
    Crnn crnn;
    InitializationParameterOfOcr initParamOfOcrCRNN;
    initParamOfOcrCRNN.parentPath = "";
    initParamOfOcrCRNN.configFilePath = CONFIG_FILE;
    initParamOfOcrCRNN.logName = "";
    ErrorCode errorCode=crnn.Initialize(initParamOfOcrCRNN, false);
    if(errorCode!=SUCCESS)
    {
        LOG_ERROR(stdout, "fail to initialize crnn!\n");
        exit(-1);
    }
    LOG_INFO(stdout, "succeed to initialize crnn\n");

    // 读取测试图片
    cv:: Mat srcImage=cv::imread("../Resource/Images/text.jpg", 1);

    // 推理
    std::vector<char> resultRaw;
    std::vector<char> resultSim;
    double time1 = getTickCount();
    crnn.Infer(srcImage,resultRaw, true, false);
    crnn.Infer(srcImage,resultSim, false, false);
    double time2 = getTickCount();
    double elapsedTime = (time2 - time1)*1000*0.5 / getTickFrequency();
    LOG_INFO(stdout, "inference time:%f ms\n", elapsedTime);

    // 获取推理结果
    LOG_INFO(stdout,"========== Ocr Results ==========\n");
    for(int i = 0; i < resultRaw.size(); i++)
    {
          std::cout << resultRaw.at(i);
    }    
    std::cout << " => ";
    for(int i = 0; i < resultSim.size(); i++)
    {
        std::cout << resultSim.at(i);
    }
    std::cout << std::endl;
}

void Sample_Crnn_Dynamic()
{
    // 创建CRNN文本识别
    Crnn crnn;
    InitializationParameterOfOcr initParamOfOcrCRNN;
    initParamOfOcrCRNN.parentPath = "";
    initParamOfOcrCRNN.configFilePath = CONFIG_FILE;
    initParamOfOcrCRNN.logName = "";
    ErrorCode errorCode=crnn.Initialize(initParamOfOcrCRNN, true);
    if(errorCode!=SUCCESS)
    {
        LOG_ERROR(stdout, "fail to initialize crnn!\n");
        exit(-1);
    }
    LOG_INFO(stdout, "succeed to initialize crnn\n");

    // 读取测试图片
    std::vector<cv::Mat> srcImages;
    cv::String folder = "../Resource/Images/CrnnDynamicPic";
    std::vector<cv::String> imagePathList;
    cv::glob(folder,imagePathList);
    for (int i = 0; i < imagePathList.size(); ++i)
    {
        cv:: Mat srcImage=cv::imread(imagePathList[i], 1);
        srcImages.push_back(srcImage); 
    }

    // 获取推理结果
    LOG_INFO(stdout,"========== Ocr Results ==========\n");
    for(int i=0; i<srcImages.size(); ++i)
    {    
        std::vector<char> resultSim;
        crnn.Infer(srcImages[i],resultSim, false, true);

        for(int i = 0; i < resultSim.size(); i++)
        {
            std::cout << resultSim.at(i);
        }
        std::cout << std::endl;
    }
    
}