imradv3 / src /WeChatOcrCpp /OcrManager.cpp
fasdfsa's picture
todo: fix link err.
17f5b5c
#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);
}