File size: 9,947 Bytes
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
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317

#include <fstream>
#include <iostream>
#include <thread>
#include <chrono>
#include <cstring>
#include <filesystem>

#include "OcrManager.h"
#include "Constant.h"
#include "protobuf/ocr_protobuf.pb.h"


OcrManager::OcrManager(const std::string& path) : isWeChatOcrRunning(false), isConnected(false) {
    // 初始化队列
    for (int i = 0; i < OcrMaxTaskId; i++) {
        queueIds.push(i);
        timers[i] = std::chrono::high_resolution_clock::now();
    }
    
    if (path.empty()) {
        // 使用默认路径
        SetExePath(Constant::WeChatOcrData); // Constant::WeChatOcrData
        SetUsrLibDir(Constant::WeChatOcrData); // Constant::WeChatOcrData
    }
    else {
        // 使用指定路径
        std::string ocrExePath = "";
        std::string wechatDir = "";
        
        // 这里需要实现Utilities类中的方法
        // 暂时使用简化的实现
        ocrExePath = path + "\\WeChatOCR.exe";
        wechatDir = path;
        
        // 复制DLL文件
        // 这里需要实现Utilities类中的方法
        
        SetExePath(ocrExePath);
        SetUsrLibDir(wechatDir);
    }
}

OcrManager::~OcrManager() {
    if (isWeChatOcrRunning) {
        KillWeChatOcr();
    }
}

void OcrManager::SetUsrLibDir(const std::string& usrLibDir) {
    AppendSwitchNativeCmdLine("user-lib-dir", usrLibDir);
}

void OcrManager::SetOcrResultCallback(std::function<void(const std::string&, std::string&)> func) {
    Callback = func;
}

void OcrManager::StartWeChatOcr(void* ocrManager) {
    SetCallbackUsrData(ocrManager);
    SetDefaultCallbacks();
    InitMmMojoEnv();
    isWeChatOcrRunning = true;
}

void OcrManager::KillWeChatOcr() {
    isConnected = false;
    isWeChatOcrRunning = false;
    StopMmMojoEnv();
}

void OcrManager::DoOcrTask(const std::string& imgPath) {
    if (!isWeChatOcrRunning) {
        throw std::runtime_error("请先调用StartWeChatOCR启动");
    }
    
    // 检查文件是否存在
    std::ifstream file(imgPath);
    if (!file.good()) {
        throw std::runtime_error("给定图片路径不存在: " + imgPath);
    }
    file.close();
    
    // 获取绝对路径
    std::string fullPath = std::filesystem::absolute(imgPath).string();
    
    // 等待连接成功
    int numTry = 0;
    while (!isConnected) {
        std::this_thread::sleep_for(std::chrono::milliseconds(100));
        if (numTry++ > 3) {
            throw std::runtime_error("连接Ocr服务超时!");
        }
    }
    
    // 获取空闲任务ID
    int taskId = GetIdleTaskId();
    if (taskId < 0) {
        throw std::overflow_error("当前队列已满,请等待后重试!");
    }
    
    // 发送OCR任务
    SendOcrTask(taskId, fullPath);
}

void OcrManager::SendOcrTask(int taskId, const std::string& picPath) {
    dicImageID[taskId] = picPath;
    
    // 创建OCR请求
    // 这里需要使用Google Protobuf
    // 假设我们有一个OcrRequest类
    ocr_protobuf::OcrRequest ocrRequest;
    ocrRequest.set_unknow(0);
    ocrRequest.set_task_id(taskId);
    auto* picPaths = ocrRequest.mutable_pic_path();
    picPaths->add_pic_path(picPath);

    // 序列化请求
    std::string serializedData;
    ocrRequest.SerializeToString(&serializedData);
    
    // 发送序列化数据
    SendPbSerializedData((const unsigned char*)serializedData.c_str(), serializedData.length(), 
                         (int)MMMojoInfoMethod::kMMPush, 0, (int)RequestIdOcr::OcrPush);
}

WeChatOcrResult* OcrManager::ParseJsonResponse(const std::string& jsonResponseStr) {
    return ParseOcrResult::ParseJson(jsonResponseStr);
}

void OcrManager::SetConnectState(bool connect) {
    isConnected = connect;
}

int OcrManager::GetIdleTaskId() {
    int taskId = -1;
    try {
        if (!queueIds.empty()) {
            taskId = queueIds.front();
            queueIds.pop();
            timers[taskId] = std::chrono::high_resolution_clock::now();
        }
    }
    catch (const std::exception&) {
        // 队列为空,返回-1
    }
    return taskId;
}

void OcrManager::SetTaskIdIdle(int taskId) {
    queueIds.push(taskId);
    
    // 计算任务耗时
    auto now = std::chrono::high_resolution_clock::now();
    auto duration = std::chrono::duration_cast<std::chrono::milliseconds>(now - timers[taskId]).count();
    
    // 输出任务完成信息(可选)
    // std::cout << "任务" << taskId << "完成,耗时" << duration << "毫秒" << std::endl;
}

void OcrManager::SetDefaultCallbacks() {
    SetOneCallback("kMMRemoteConnect", (void*)&OcrManager::OCRRemoteOnConnect);
    SetOneCallback("kMMRemoteDisconnect", (void*)&OcrManager::OCRRemoteOnDisconnect);
    SetOneCallback("kMMReadPush", (void*)&OcrManager::OCRReadOnPush);
}

void OcrManager::OCRRemoteOnConnect(bool isConnected, void* userData) {
    if (userData == nullptr) return;
    
    OcrManager* manager = static_cast<OcrManager*>(userData);
    manager->SetConnectState(true);
}

void OcrManager::OCRRemoteOnDisconnect(void* userData) {
    if (userData != nullptr) {
        OcrManager* manager = static_cast<OcrManager*>(userData);
        manager->SetConnectState(false);
    }
}

void OcrManager::OCRReadOnPush(unsigned int requestId, void* requestInfo, void* userData) {
    if (userData == nullptr) return;
    
    OcrManager* manager = static_cast<OcrManager*>(userData);
    
    // 获取序列化数据
    unsigned int pbSize = 0;
    void* pbData = manager->GetPbSerializedData(requestInfo, &pbSize);
    if (pbSize <= 20) return;
    
    // 处理用户回调
    manager->CallUserCallback(requestId, pbData, (int)pbSize);
    
    // 移除请求信息
    manager->RemoveReadInfo(requestInfo);
}

void OcrManager::CallUserCallback(unsigned int requestId, void* serializedData, int dataSize) {
    std::cout << "回调函数 CallUserCallback 被调用,request_id: " << requestId << std::endl;
    
    // 复制序列化数据
    unsigned char* ocrResponseArray = new unsigned char[dataSize];
    memcpy(ocrResponseArray, serializedData, dataSize);
    
    // 解析Protobuf响应
    ocr_protobuf::OcrResponse ocrResponse;
    ocrResponse.ParseFromArray(ocrResponseArray, dataSize);
    
    // 释放内存
    delete[] ocrResponseArray;
    
    // 获取任务ID
    int taskId = ocrResponse.task_id();

    // 检查图片路径是否存在
    auto it = dicImageID.find(taskId);
    if (it == dicImageID.end()) return;
    
    std::string pth_img = it->second;


    ///////////
    // 创建结果对象
    WeChatOcrResult* result = new WeChatOcrResult();
    result->TaskId = ocrResponse.task_id();
    result->OcrResult = std::make_shared<OcrResult>();

    // 解析 OCR 结果
    if (ocrResponse.has_ocr_result()) {
        const auto& protoOcrResult = ocrResponse.ocr_result();

        // 解析单行结果
        for (int i = 0; i < protoOcrResult.single_result_size(); i++) {
            const auto& protoSingleResult = protoOcrResult.single_result(i);
            SingleResult singleResult;

            // 解析单行文本
            if (!protoSingleResult.single_str_utf8().empty()) {
                singleResult.SingleStrUtf8 = protoSingleResult.single_str_utf8(); // Base64Decode();
            }

            // 解析单行位置信息
            singleResult.SingleRate = protoSingleResult.single_rate();
            singleResult.Left = protoSingleResult.left();
            singleResult.Top = protoSingleResult.top();
            singleResult.Right = protoSingleResult.right();
            singleResult.Bottom = protoSingleResult.bottom();

            // 解析单行位置
            if (protoSingleResult.has_single_pos()) {
                singleResult.SinglePos = std::make_shared<SinglePos>();
                const auto& protoSinglePos = protoSingleResult.single_pos();

                for (int j = 0; j < protoSinglePos.pos_size(); j++) {
                    const auto& protoPosXY = protoSinglePos.pos(j);
                    Pos pos;
                    pos.X = protoPosXY.x();
                    pos.Y = protoPosXY.y();
                    singleResult.SinglePos->Pos.push_back(pos);
                }
            }

            // 解析单字结果
            for (int j = 0; j < protoSingleResult.one_result_size(); j++) {
                const auto& protoOneResult = protoSingleResult.one_result(j);
                OneResult oneResult;

                // 解析单字文本
                if (!protoOneResult.one_str_utf8().empty()) {
                    oneResult.OneStrUtf8 = protoOneResult.one_str_utf8(); // Base64Decode();
                }

                // 解析单字位置
                if (protoOneResult.has_one_pos()) {
                    oneResult.OnePos = std::make_shared<OnePos>();
                    const auto& protoOnePos = protoOneResult.one_pos();

                    for (int k = 0; k < protoOnePos.pos_size(); k++) {
                        const auto& protoPosXY = protoOnePos.pos(k);
                        Pos pos;
                        pos.X = protoPosXY.x();
                        pos.Y = protoPosXY.y();
                        oneResult.OnePos->Pos.push_back(pos);
                    }
                }

                singleResult.OneResult.push_back(oneResult);
            }

            result->OcrResult->SingleResult.push_back(singleResult);
        }
    }

    std::string ocr_result;
    if (!result->OcrResult->SingleResult.empty()) {
        ocr_result = result->OcrResult->ToJson(pth_img); // 将结果转换为JSON字符串
    }

    //std::cout << ocr_result << std::endl;
	

    ///////////

    
    // 仅用于调试
    std::string jsonResponseStr = ocrResponse.DebugString();
    
    // 解析JSON响应
    //WeChatOcrResult* result = ParseJsonResponse(jsonResponseStr);
    
    // 调用用户回调
    if (Callback) {
        Callback(pth_img, ocr_result);
    }
    
    // 设置任务ID为空闲
    SetTaskIdIdle(taskId);
}