File size: 7,162 Bytes
17f5b5c
3bca3f4
 
17f5b5c
 
 
 
 
 
 
 
 
f4ae1c5
17f5b5c
 
 
3bca3f4
 
f4ae1c5
 
 
 
 
 
a1d4680
 
f4ae1c5
 
17f5b5c
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
3bca3f4
 
 
 
a1d4680
 
3bca3f4
a1d4680
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
f4ae1c5
 
 
 
 
 
 
 
 
 
 
 
3bca3f4
f4ae1c5
3bca3f4
f4ae1c5
 
 
 
 
 
a1d4680
 
 
 
f4ae1c5
3bca3f4
f4ae1c5
3bca3f4
f4ae1c5
 
 
 
 
a1d4680
 
 
f4ae1c5
 
 
 
 
 
 
 
 
 
 
 
a1d4680
 
 
 
 
 
 
 
 
 
 
 
f4ae1c5
a1d4680
 
f4ae1c5
a1d4680
f4ae1c5
3bca3f4
f4ae1c5
 
a1d4680
 
3bca3f4
 
a1d4680
 
 
 
 
 
3bca3f4
a1d4680
 
f76c291
3bca3f4
 
 
a1d4680
3bca3f4
 
a1d4680
3bca3f4
 
 
a1d4680
17f5b5c
 
598b103
 
17f5b5c
 
 
a1d4680
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
3bca3f4
 
 
 
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
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

// 在所有包含之前定义这个宏
#define WIN32_LEAN_AND_MEAN  // for httplib.h

#include <iostream>
#include <thread>
#include <chrono>
#include <atomic>
#include <windows.h>

#include "ImageOcr.h"
#include "Wchtcr.h"
#include "Utilities.h"

#include "nlohmann/json.hpp"

#include "httplib.h"

#include <opencv2/core.hpp>
#include <opencv2/highgui.hpp>
#include <opencv2/imgcodecs.hpp>
#include <opencv2/videoio.hpp>
#include <opencv2/imgproc.hpp>

#include <format>



using json = nlohmann::json;

// DLL 入口点
BOOL APIENTRY DllMain(HMODULE hModule, DWORD ul_reason_for_call, LPVOID lpReserved) {
    switch (ul_reason_for_call) {
    case DLL_PROCESS_ATTACH:
        // 初始化代码
        break;
    case DLL_THREAD_ATTACH:
        break;
    case DLL_THREAD_DETACH:
        break;
    case DLL_PROCESS_DETACH:
        // 清理代码
        break;
    }
    return TRUE;
}

extern "C" {
    __declspec(dllexport) const char* rec(const char* pth_img) {
        thread_local static std::string result;
		Wchtcr wchtcr;
        result = wchtcr.rec(pth_img);
        return result.c_str();
    }
}

// 启动HTTP服务器的函数
void StartHttpServer(int port) {
    httplib::Server svr;

    std::atomic<int> totalTasks(0);  // 使用原子类型确保线程安全

    // 添加POST接口,接收base64编码的图片
    svr.Post("/wechatocr", [&totalTasks, &port](const httplib::Request& req, httplib::Response& res) {

		std::string msg_Warning_waiting = std::vformat("{{\"msg\":\"warning: waiting previous task done. port {}\" }}", std::make_format_args(port));
		std::string msg_Err_noParam = std::vformat("{{\"msg\":\"error: not have img param. port {}\" }}", std::make_format_args(port));
		std::string msg_Err_genFilename = std::vformat("{{\"msg\":\"error: gen tmp filename fail. port {}\" }}", std::make_format_args(port));
		std::string msg_Err_rec_fail = std::vformat("{{\"msg\":\"error: rec fail port {}\" }}", std::make_format_args(port));

         try {

    //        while (totalTasks + 1 > 1) {
    //            std::cout << "########## Warning: Max tasks overflow, Total tasks " << totalTasks << " waitting now... "  << std::endl;
				//std::this_thread::sleep_for(std::chrono::milliseconds(1000)); // 等待 1 秒
    //        }

           

            if (totalTasks > 0) {
                res.status = 201;
                res.set_content(msg_Warning_waiting, "application/json");
                return;
            }

			std::cout << "********* Received a new task. Total tasks: " << ++totalTasks << std::endl;

            // 检查Content-Type
            const auto& content_type = req.get_header_value("Content-Type");
            std::string body_content = req.body;

            // 如果是URL编码的JSON,先解码
            if (content_type.find("application/json") != std::string::npos &&
                req.body.find("%") != std::string::npos) {
                // 使用httplib内置的decode_path函数解码URL编码的内容
                body_content = httplib::detail::decode_path(req.body, true);
            }

            // 解析请求体中的JSON数据
            json request_data = json::parse(body_content);

            // 获取base64编码的图片数据
            std::string base64_image;
            if (request_data.contains("img")) {
                base64_image = request_data["img"].get<std::string>();
            }
            else {
                --totalTasks;
                res.status = 500;
                res.set_content(msg_Err_noParam, "application/json");
                return;
            }

            std::vector<unsigned char> b64_buf = Utilities::Base64Decode_Raw(base64_image);

            cv::Mat img_orgin = cv::imdecode(b64_buf, -1);

            char tempPath[MAX_PATH], tempFile[MAX_PATH];
            GetTempPathA(MAX_PATH, tempPath);              // 获取系统临时目录
            if (GetTempFileNameA(tempPath, "TMP", 0, tempFile) == 0) { // "TMP"为前缀,0表示自动生成唯一编号
                --totalTasks;
                res.status = 201;
                res.set_content(msg_Err_genFilename, "application/json");
                return;
            }
            strcat_s(tempFile, ".jpg");

            cv::imwrite(tempFile, img_orgin);

            //cv::imshow("原图", img_orgin);

            //cv::waitKey(0);

            // 调用rec函数进行OCR识别
            std::string result = rec(tempFile);
			if (result.empty()) {
				--totalTasks;
				res.status = 201;
				res.set_content(msg_Err_rec_fail, "application/json");
				return;
			}

            json jsn = json::parse(result);
			jsn["port"] = port; // 添加端口号到结果中
            result = jsn.dump(4);

            --totalTasks;
            
            std::cout << "one task done. Total tasks:" << totalTasks << std::endl;

            // 返回识别结果
            res.status = 200;
            res.set_content(result, "application/json");

            // 删除临时文件
            std::remove(tempFile);

            return;
        }
        catch (const std::exception& e) {
            --totalTasks;
            res.status = 201;
            std::string error_msg = e.what();
			std::string msg_exception = std::vformat("{\"msg\":\"error: server error. {} port {}\" }", std::make_format_args(error_msg, port) );
            res.set_content(msg_exception, "application/json");
            return;
        }

        
    });

    // 添加一个简单的GET接口,用于测试服务器是否正常运行
    svr.Get("/", [](const httplib::Request&, httplib::Response& res) {
        res.set_content("OCR Sever running ....", "text/plain");
        });

    std::cout << "OCR Sever running ... : " << port << std::endl;
    svr.listen("0.0.0.0", port);
}

int main(int argc, char* argv[])
{
	//Wchtcr wchtcr;
    //   
    //std::string result = wchtcr.rec("data/0025.jpg");
	//json jsn;
	//std::string jsn_str;

    // 默认端口号
    int port = 7788;
    
    // 如果提供了命令行参数,使用第一个参数作为端口号
    if (argc > 1) {
        try {
            port = std::stoi(argv[1]);
            if (port <= 0 || port > 65535) {
                std::cout << "Invalid port number. Using default port 7788." << std::endl;
                port = 7788;
            }
        } catch (const std::exception& e) {
            std::cout << "Invalid port number format. Using default port 7788." << std::endl;
            port = 7788;
        }
    }

    // 启动HTTP服务器,使用指定的端口
    std::thread server_thread(StartHttpServer, port);

    // 分离线程,让它在后台运行
    server_thread.detach();

    do {
        // 主线程可以做其他事情,或者等待用户输入退出
        //std::cout << "ok." << std::endl;
        std::cin.get();
    } while (true);

    std::string result = rec("t2.jpg");
    json jsn;
    std::string jsn_str;
    
    try {
		 jsn = json::parse(result);
		 jsn_str = jsn.dump(4);
    }
	catch (const std::exception& e) {
		std::cerr << "OCR识别异常: " << e.what() << std::endl;
		return 1;
	}

    return 0;
}