Debian Codegraph @

plugins/jieba/src/JiebaSegmentationPlugin.cpp

raw symbols SCIP
1 /*
2 * Open Chinese Convert
3 *
4 * Copyright 2010-2026 Carbo Kuo and contributors
5 *
6 * Licensed under the Apache License, Version 2.0 (the "License");
7 * you may not use this file except in compliance with the License.
8 * You may obtain a copy of the License at
9 *
10 * http://www.apache.org/licenses/LICENSE-2.0
11 *
12 * Unless required by applicable law or agreed to in writing, software
13 * distributed under the License is distributed on an "AS IS" BASIS,
14 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
15 * See the License for the specific language governing permissions and
16 * limitations under the License.
17 */
18
19 #include "Exception.hpp"
20 #include "JiebaSegmentation.hpp"
21 #include "Segments.hpp"
22 #include "UTF8Util.hpp"
23 #include "plugin/OpenCCPlugin.h"
24
25 #include <cstdlib>
26 #include <cstring>
27 #include <fstream>
28 #include <memory>
29 #include <string>
30 #include <vector>
31
32 #include "cppjieba/Jieba.hpp"
33
34 #if defined(_WIN32) || defined(_WIN64)
35 #include <windows.h>
36 namespace {
37 std::wstring LocalWideFromUtf8(const std::string& utf8) {
38 if (utf8.empty()) {
39 return L"";
40 }
41 int size = MultiByteToWideChar(CP_UTF8, 0, utf8.c_str(), -1, nullptr, 0);
42 if (size <= 1) {
43 return L"";
44 }
45 std::wstring wide(static_cast<size_t>(size), L'\0');
46 MultiByteToWideChar(CP_UTF8, 0, utf8.c_str(), -1, &wide[0], size);
47 wide.resize(static_cast<size_t>(size - 1));
48 return wide;
49 }
50 } // namespace
51 #endif
52
53 struct opencc_segmentation_handle {
54 explicit opencc_segmentation_handle(
55 std::unique_ptr<opencc::Segmentation> segmentation)
56 : segmentation(std::move(segmentation)) {}
57
58 std::unique_ptr<opencc::Segmentation> segmentation;
59 };
60
61 namespace {
62
63 bool IsAbsolutePath(const std::string& path) {
64 if (path.empty()) {
65 return false;
66 }
67 if (path[0] == '/' || path[0] == '\\') {
68 return true;
69 }
70 return path.size() > 1 && path[1] == ':';
71 }
72
73 bool IsReadableFile(const std::string& path) {
74 #if defined(_WIN32) || defined(_WIN64)
75 const DWORD attributes = GetFileAttributesW(LocalWideFromUtf8(path).c_str());
76 return attributes != INVALID_FILE_ATTRIBUTES &&
77 (attributes & FILE_ATTRIBUTE_DIRECTORY) == 0;
78 #else
79 std::ifstream ifs(path.c_str());
80 return ifs.is_open();
81 #endif
82 }
83
84 std::string BaseName(const std::string& path) {
85 const std::string::size_type pos = path.find_last_of("/\\");
86 if (pos == std::string::npos) {
87 return path;
88 }
89 return path.substr(pos + 1);
90 }
91
92 std::string ParentDir(const std::string& path) {
93 std::string normalized = path;
94 while (!normalized.empty() &&
95 (normalized.back() == '/' || normalized.back() == '\\')) {
96 normalized.pop_back();
97 }
98 const std::string::size_type pos = normalized.find_last_of("/\\");
99 if (pos == std::string::npos) {
100 return "";
101 }
102 return normalized.substr(0, pos);
103 }
104
105 std::string JoinPath(const std::string& left, const std::string& right) {
106 if (left.empty()) {
107 return right;
108 }
109 const char last = left.back();
110 if (last == '/' || last == '\\') {
111 return left + right;
112 }
113 return left + "/" + right;
114 }
115
116 bool EndsWith(const std::string& value, const std::string& suffix) {
117 return value.size() >= suffix.size() &&
118 value.compare(value.size() - suffix.size(), suffix.size(), suffix) == 0;
119 }
120
121 std::vector<std::string> SplitSearchPath(const char* raw) {
122 std::vector<std::string> entries;
123 if (raw == nullptr || *raw == '\0') {
124 return entries;
125 }
126 const char separator =
127 #if defined(_WIN32) || defined(_WIN64)
128 ';';
129 #else
130 ':';
131 #endif
132 std::string path(raw);
133 std::string::size_type start = 0;
134 while (start <= path.size()) {
135 const std::string::size_type end = path.find(separator, start);
136 const std::string entry = path.substr(start, end - start);
137 if (!entry.empty()) {
138 entries.push_back(entry);
139 }
140 if (end == std::string::npos) {
141 break;
142 }
143 start = end + 1;
144 }
145 return entries;
146 }
147
148 void SetError(opencc_error_t* error,
149 int code,
150 const std::string& message) {
151 if (error == nullptr) {
152 return;
153 }
154 if (error->message != nullptr) {
155 delete[] error->message;
156 error->message = nullptr;
157 }
158 error->code = code;
159 char* buffer = new char[message.size() + 1];
160 std::memcpy(buffer, message.c_str(), message.size() + 1);
161 error->message = buffer;
162 }
163
164 bool ReadConfigValue(const opencc_kv_pair_t* config,
165 size_t size,
166 const char* key,
167 std::string* value) {
168 for (size_t i = 0; i < size; i++) {
169 if (config[i].key != nullptr && std::string(config[i].key) == key) {
170 *value = config[i].value == nullptr ? "" : config[i].value;
171 return true;
172 }
173 }
174 return false;
175 }
176
177 uint32_t CodePointLength(const std::string& text) {
178 return static_cast<uint32_t>(opencc::UTF8Util::Length(text.c_str()));
179 }
180
181 std::string ResolveResourcePath(const std::string& rawPath,
182 const std::string& configDir) {
183 if (rawPath.empty()) {
184 return rawPath;
185 }
186 if (IsAbsolutePath(rawPath) && IsReadableFile(rawPath)) {
187 return rawPath;
188 }
189 if (IsReadableFile(rawPath)) {
190 return rawPath;
191 }
192 if (!configDir.empty()) {
193 const std::string candidate = JoinPath(configDir, rawPath);
194 if (IsReadableFile(candidate)) {
195 return candidate;
196 }
197 const std::string parent = ParentDir(configDir);
198 if (!parent.empty()) {
199 const std::string parentCandidate = JoinPath(parent, rawPath);
200 if (IsReadableFile(parentCandidate)) {
201 return parentCandidate;
202 }
203 const std::string parentParent = ParentDir(parent);
204 if (!parentParent.empty()) {
205 const std::string basename = rawPath.substr(rawPath.find_last_of("/\\") == std::string::npos
206 ? 0
207 : rawPath.find_last_of("/\\") + 1);
208 const std::string devCandidate = JoinPath(parentParent, "deps/cppjieba/dict/" + basename);
209 if (IsReadableFile(devCandidate)) {
210 return devCandidate;
211 }
212 }
213 }
214 }
215 for (const std::string& pluginDir :
216 SplitSearchPath(std::getenv("OPENCC_SEGMENTATION_PLUGIN_PATH"))) {
217 const std::string candidate = JoinPath(pluginDir, rawPath);
218 if (IsReadableFile(candidate)) {
219 return candidate;
220 }
221 const std::string pluginParent = ParentDir(pluginDir);
222 if (!pluginParent.empty()) {
223 const std::string parentCandidate = JoinPath(pluginParent, rawPath);
224 if (IsReadableFile(parentCandidate)) {
225 return parentCandidate;
226 }
227 }
228 }
229 const char* dataDir = std::getenv("OPENCC_DATA_DIR");
230 if (dataDir != nullptr && *dataDir != '\0') {
231 const std::string candidate = JoinPath(dataDir, rawPath);
232 if (IsReadableFile(candidate)) {
233 return candidate;
234 }
235 }
236 if (!PACKAGE_DATA_DIRECTORY.empty()) {
237 const std::string candidate = JoinPath(PACKAGE_DATA_DIRECTORY, rawPath);
238 if (IsReadableFile(candidate)) {
239 return candidate;
240 }
241 }
242
243
244 return rawPath;
245 }
246
247 std::string ResolveAuxPath(const std::string& dictPath,
248 const std::string& modelPath,
249 const std::string& configDir,
250 const std::string& fileName) {
251 const std::string::size_type pos = dictPath.find_last_of("/\\");
252 if (pos != std::string::npos) {
253 const std::string candidate = dictPath.substr(0, pos + 1) + fileName;
254 if (IsReadableFile(candidate)) {
255 return candidate;
256 }
257 }
258 const std::string::size_type modelPos = modelPath.find_last_of("/\\");
259 if (modelPos != std::string::npos) {
260 const std::string modelCandidate =
261 modelPath.substr(0, modelPos + 1) + fileName;
262 if (IsReadableFile(modelCandidate)) {
263 return modelCandidate;
264 }
265 }
266 // Development fallback: try deps/cppjieba/dict/ relative to the source tree
267 const std::string needle = "share/opencc/jieba_dict/";
268 const std::string::size_type needlePos = dictPath.find(needle);
269 if (needlePos != std::string::npos) {
270 std::string alt = dictPath;
271 alt.replace(needlePos, needle.size(), "plugins/jieba/deps/cppjieba/dict/");
272 const std::string::size_type altPos = alt.find_last_of("/\\");
273 if (altPos != std::string::npos) {
274 const std::string altCandidate = alt.substr(0, altPos + 1) + fileName;
275 if (IsReadableFile(altCandidate)) {
276 return altCandidate;
277 }
278 }
279 }
280 return ResolveResourcePath("jieba_dict/" + fileName, configDir);
281 }
282
283 void FallbackToTextJiebaDictionaries(const std::string& requestedDictPath,
284 const std::string& configDir,
285 std::string* dictPath,
286 std::string* userDictPath,
287 bool hasExplicitUserDictPath) {
288 if (dictPath == nullptr || userDictPath == nullptr) {
289 return;
290 }
291 if (IsReadableFile(*dictPath) || !EndsWith(requestedDictPath, "jieba_merged.ocd2")) {
292 return;
293 }
294
295 std::string textDictRaw = requestedDictPath;
296 const std::string mergedBase = BaseName(requestedDictPath);
297 const std::string textBase = "jieba.dict.utf8";
298 const std::string userBase = "user.dict.utf8";
299 if (mergedBase == requestedDictPath) {
300 textDictRaw = textBase;
301 } else {
302 textDictRaw.replace(textDictRaw.size() - mergedBase.size(), mergedBase.size(),
303 textBase);
304 }
305
306 const std::string resolvedTextDict = ResolveResourcePath(textDictRaw, configDir);
307 if (!IsReadableFile(resolvedTextDict)) {
308 return;
309 }
310
311 std::string userDictRaw = textDictRaw;
312 userDictRaw.replace(userDictRaw.size() - textBase.size(), textBase.size(),
313 userBase);
314 const std::string resolvedUserDict = ResolveResourcePath(userDictRaw, configDir);
315
316 *dictPath = resolvedTextDict;
317 if (!hasExplicitUserDictPath && IsReadableFile(resolvedUserDict)) {
318 *userDictPath = resolvedUserDict;
319 }
320 }
321
322 int CreateJiebaSegmentation(opencc_segmentation_create_args_t* args) {
323 if (args == nullptr || args->struct_size < sizeof(*args) ||
324 args->out == nullptr) {
325 SetError(args == nullptr ? nullptr : args->error,
326 OPENCC_ERROR_INVALID_ARGUMENT, "Output handle is null.");
327 return -1;
328 }
329 *args->out = nullptr;
330
331 std::string configDir;
332 std::string dictPath;
333 std::string modelPath;
334 std::string userDictPath;
335 const bool hasExplicitUserDictPath =
336 ReadConfigValue(args->config, args->config_size, "user_dict_path",
337 &userDictPath);
338 ReadConfigValue(args->config, args->config_size, "__config_dir", &configDir);
339 if (!ReadConfigValue(args->config, args->config_size, "dict_path", &dictPath) ||
340 dictPath.empty()) {
341 SetError(args->error, OPENCC_ERROR_PLUGIN_RESOURCE_MISSING,
342 "Required resource missing: dict_path");
343 return -1;
344 }
345 if (!ReadConfigValue(args->config, args->config_size, "model_path", &modelPath) ||
346 modelPath.empty()) {
347 SetError(args->error, OPENCC_ERROR_PLUGIN_RESOURCE_MISSING,
348 "Required resource missing: model_path");
349 return -1;
350 }
351
352 const std::string requestedDictPath = dictPath;
353 dictPath = ResolveResourcePath(dictPath, configDir);
354 modelPath = ResolveResourcePath(modelPath, configDir);
355 userDictPath = userDictPath.empty() ? "" : ResolveResourcePath(userDictPath, configDir);
356 FallbackToTextJiebaDictionaries(requestedDictPath, configDir, &dictPath,
357 &userDictPath, hasExplicitUserDictPath);
358 const std::string idfPath =
359 ResolveAuxPath(dictPath, modelPath, configDir, "idf.utf8");
360 const std::string stopWordsPath =
361 ResolveAuxPath(dictPath, modelPath, configDir, "stop_words.utf8");
362
363 if (!IsReadableFile(dictPath) || !IsReadableFile(modelPath) ||
364 (!userDictPath.empty() && !IsReadableFile(userDictPath)) ||
365 !IsReadableFile(idfPath) || !IsReadableFile(stopWordsPath)) {
366 SetError(args->error, OPENCC_ERROR_PLUGIN_RESOURCE_MISSING,
367 "Failed to locate Jieba resource files.");
368 return -1;
369 }
370
371 try {
372 std::unique_ptr<opencc::Segmentation> segmentation(
373 new opencc::JiebaSegmentation(dictPath, modelPath, userDictPath, idfPath,
374 stopWordsPath));
375 *args->out = new opencc_segmentation_handle(std::move(segmentation));
376 return 0;
377 } catch (const std::exception& ex) {
378 SetError(args->error, OPENCC_ERROR_PLUGIN_RUNTIME_FAILURE, ex.what());
379 return -1;
380 } catch (...) {
381 SetError(args->error, OPENCC_ERROR_PLUGIN_RUNTIME_FAILURE,
382 "Unknown error while creating Jieba segmentation.");
383 return -1;
384 }
385 }
386
387 opencc::Segmentation* GetSegmentation(opencc_segmentation_handle_t* handle) {
388 return handle->segmentation.get();
389 }
390
391 void FreeSegmentLengths(opencc_segment_length_array_t* segmentLengths) {
392 if (segmentLengths == nullptr || segmentLengths->codepoint_lengths == nullptr) {
393 return;
394 }
395 delete[] segmentLengths->codepoint_lengths;
396 segmentLengths->codepoint_lengths = nullptr;
397 segmentLengths->segment_count = 0;
398 }
399
400 int SegmentWithJieba(opencc_segmentation_segment_args_t* args) {
401 if (args == nullptr || args->struct_size < sizeof(*args) ||
402 args->handle == nullptr || args->segment_lengths == nullptr ||
403 args->segment_lengths->struct_size < sizeof(*args->segment_lengths) ||
404 args->utf8_text == nullptr) {
405 SetError(args == nullptr ? nullptr : args->error,
406 OPENCC_ERROR_INVALID_ARGUMENT,
407 "Segment arguments are invalid.");
408 return -1;
409 }
410 try {
411 opencc::SegmentsPtr segments =
412 GetSegmentation(args->handle)->Segment(args->utf8_text);
413 const std::string text(args->utf8_text);
414 std::vector<uint32_t> lengths;
415 lengths.reserve(segments->Length() + 1);
416 size_t byteOffset = 0;
417
418 for (size_t i = 0; i < segments->Length(); i++) {
419 const std::string token = segments->At(i);
420 const size_t tokenPos = text.find(token, byteOffset);
421 if (tokenPos == std::string::npos) {
422 throw opencc::Exception("Jieba token sequence could not be aligned to input text.");
423 }
424 if (tokenPos > byteOffset) {
425 lengths.push_back(CodePointLength(text.substr(byteOffset, tokenPos - byteOffset)));
426 }
427 lengths.push_back(CodePointLength(token));
428 byteOffset = tokenPos + token.size();
429 }
430 if (byteOffset < text.size()) {
431 lengths.push_back(CodePointLength(text.substr(byteOffset)));
432 }
433
434 args->segment_lengths->codepoint_lengths = nullptr;
435 args->segment_lengths->segment_count = lengths.size();
436 args->segment_lengths->codepoint_lengths =
437 new uint32_t[args->segment_lengths->segment_count]();
438 for (size_t i = 0; i < args->segment_lengths->segment_count; i++) {
439 args->segment_lengths->codepoint_lengths[i] = lengths[i];
440 }
441 return 0;
442 } catch (const std::exception& ex) {
443 FreeSegmentLengths(args->segment_lengths);
444 SetError(args->error, OPENCC_ERROR_PLUGIN_RUNTIME_FAILURE, ex.what());
445 return -1;
446 } catch (...) {
447 FreeSegmentLengths(args->segment_lengths);
448 SetError(args->error, OPENCC_ERROR_PLUGIN_RUNTIME_FAILURE,
449 "Unknown error while segmenting text.");
450 return -1;
451 }
452 }
453
454 void DestroyJiebaSegmentation(opencc_segmentation_handle_t* handle) {
455 delete handle;
456 }
457
458 void FreeError(opencc_error_t* error) {
459 if (error == nullptr || error->message == nullptr) {
460 return;
461 }
462 delete[] error->message;
463 error->message = nullptr;
464 }
465
466 const opencc_segmentation_plugin_v2 kJiebaPlugin = {
467 sizeof(opencc_segmentation_plugin_v2),
468 OPENCC_SEGMENTATION_PLUGIN_ABI_MAJOR,
469 OPENCC_SEGMENTATION_PLUGIN_ABI_MINOR,
470 "opencc-jieba",
471 "jieba",
472 &CreateJiebaSegmentation,
473 &SegmentWithJieba,
474 &FreeSegmentLengths,
475 &DestroyJiebaSegmentation,
476 &FreeError,
477 };
478
479 } // namespace
480
481 extern "C" OPENCC_PLUGIN_EXPORT const opencc_segmentation_plugin_v2*
482 opencc_get_segmentation_plugin_v2(void) {
483 return &kJiebaPlugin;
484 }