File size: 2,576 Bytes
17f5b5c
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
a1d4680
17f5b5c
 
a1d4680
17f5b5c
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
#include "Wchtcr.h"
#include "ImageOcr.h"
#include <fstream>
#include <chrono>
#include <thread>
#include <iostream>
#include <filesystem>
#include <regex>
#include "nlohmann/json.hpp"

using json = nlohmann::json;

Wchtcr::Wchtcr()
{
}

//std::future<std::string> Wchtcr::rec_async(const std::string& pth_img)
//{
//    // 创建新的Promise
//    _promise = std::promise<std::string>();
//    std::future<std::string> future = _promise.get_future();
//    
//    // 在新线程中执行OCR
//    std::thread([this, pth_img, &future]() {
//        try
//        {
//            // 创建OCR实例并执行识别
//            ImageOcr ocr;
//            ocr.Run(pth_img, [this](const std::string& path, std::string& result) {
//                _promise.set_value(result);
//            });
//            
//            // 等待一小时超时
//            auto status = future.wait_for(std::chrono::hours(1));
//            if (status == std::future_status::timeout)
//            {
//                _promise.set_value("");
//            }
//        }
//        catch (const std::exception& ex)
//        {
//            std::cerr << "Error: " << ex.what() << std::endl;
//            _promise.set_value("");
//        }
//    }).detach();
//    
//    return future;
//}

std::string Wchtcr::rec(const std::string& pth_img)
{
    // 检查文件是否存在
    if (!std::filesystem::exists(pth_img))
    {
        return "文件不存在: " + pth_img;
    }
    
    try
    {

        std::string result;

        // 创建一个原子变量来标记任务是否完成
        std::atomic<bool> taskCompleted(false);

        // 创建 ImageOcr 实例
        //ImageOcr ocr;

        // 设置回调函数并执行OCR
        this->ocr.Run(pth_img, [&taskCompleted, &result](const std::string& imagePath, std::string& jsonstr) {

            result = jsonstr;

            // 标记任务完成
            taskCompleted = true;
            });

        std::cout << "OCR任务已提交,等待结果..." << std::endl;

        // 等待任务完成或超时
        int timeoutSeconds = 600;
        for (int i = 0; i < timeoutSeconds * 10 && !taskCompleted; i++) {
            std::this_thread::sleep_for(std::chrono::milliseconds(100));
        }

        if (taskCompleted) {
            std::cout << "OCR任务已完成!" << std::endl;
        }
        else {
            std::cout << "OCR任务超时!" << std::endl;
        }

		return result;

    }
    catch (const std::exception& ex)
    {
        return "错误: " + std::string(ex.what());
    }
}