| 1 | /* |
| 2 | * Open Chinese Convert |
| 3 | * |
| 4 | * Copyright 2026 Frank Lin <[email protected]> |
| 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 | * https://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 "JiebaSegmentation.hpp" |
| 20 | #include "Segments.hpp" |
| 21 | |
| 22 | #include <algorithm> |
| 23 | #include <cstdlib> |
| 24 | #include <stdexcept> |
| 25 | #if defined(_WIN32) || defined(_WIN64) |
| 26 | #include <windows.h> |
| 27 | #else |
| 28 | #include <sys/stat.h> |
| 29 | #endif |
| 30 | |
| 31 | #include "cppjieba/Jieba.hpp" |
| 32 | |
| 33 | #if defined(__has_include) |
| 34 | #if __has_include("MarisaDict.hpp") |
| 35 | #include "Lexicon.hpp" |
| 36 | #include "MarisaDict.hpp" |
| 37 | #include "SerializableDict.hpp" |
| 38 | #elif __has_include("src/MarisaDict.hpp") |
| 39 | #include "src/Lexicon.hpp" |
| 40 | #include "src/MarisaDict.hpp" |
| 41 | #include "src/SerializableDict.hpp" |
| 42 | #elif __has_include(<opencc/MarisaDict.hpp>) |
| 43 | #include <opencc/Lexicon.hpp> |
| 44 | #include <opencc/MarisaDict.hpp> |
| 45 | #include <opencc/SerializableDict.hpp> |
| 46 | #else |
| 47 | #error "Unable to locate OpenCC dictionary headers" |
| 48 | #endif |
| 49 | #else |
| 50 | #include "Lexicon.hpp" |
| 51 | #include "MarisaDict.hpp" |
| 52 | #include "SerializableDict.hpp" |
| 53 | #endif |
| 54 | |
| 55 | using namespace opencc; |
| 56 | |
| 57 | namespace { |
| 58 | using cppjieba::DictTrie; |
| 59 | using cppjieba::DictUnit; |
| 60 | using opencc::DictEntry; |
| 61 | using opencc::LexiconPtr; |
| 62 | using opencc::MarisaDict; |
| 63 | using opencc::SerializableDict; |
| 64 | |
| 65 | #if defined(_WIN32) || defined(_WIN64) |
| 66 | std::wstring LocalWideFromUtf8(const std::string& text) { |
| 67 | if (text.empty()) { |
| 68 | return L""; |
| 69 | } |
| 70 | const int size = MultiByteToWideChar(CP_UTF8, 0, text.c_str(), -1, nullptr, |
| 71 | 0); |
| 72 | if (size <= 1) { |
| 73 | return L""; |
| 74 | } |
| 75 | std::wstring wide(static_cast<size_t>(size), L'\0'); |
| 76 | MultiByteToWideChar(CP_UTF8, 0, text.c_str(), -1, &wide[0], size); |
| 77 | wide.resize(static_cast<size_t>(size - 1)); |
| 78 | return wide; |
| 79 | } |
| 80 | #endif |
| 81 | |
| 82 | std::string ParentDir(const std::string& path) { |
| 83 | std::string::size_type pos = path.find_last_of("/\\"); |
| 84 | if (pos == std::string::npos) { |
| 85 | return ""; |
| 86 | } |
| 87 | return path.substr(0, pos + 1); |
| 88 | } |
| 89 | |
| 90 | bool IsRegularFile(const std::string& path) { |
| 91 | #if defined(_WIN32) || defined(_WIN64) |
| 92 | const DWORD attributes = GetFileAttributesW(LocalWideFromUtf8(path).c_str()); |
| 93 | return attributes != INVALID_FILE_ATTRIBUTES && |
| 94 | (attributes & FILE_ATTRIBUTE_DIRECTORY) == 0; |
| 95 | #else |
| 96 | struct stat info; |
| 97 | if (stat(path.c_str(), &info) != 0) { |
| 98 | return false; |
| 99 | } |
| 100 | return (info.st_mode & S_IFMT) == S_IFREG; |
| 101 | #endif |
| 102 | } |
| 103 | |
| 104 | std::string ResolveAuxPath(const std::string& dictPath, |
| 105 | const std::string& modelPath, |
| 106 | const std::string& fileName) { |
| 107 | const std::string baseDir = ParentDir(dictPath); |
| 108 | const std::string candidate = baseDir + fileName; |
| 109 | if (IsRegularFile(candidate)) { |
| 110 | return candidate; |
| 111 | } |
| 112 | const std::string modelDir = ParentDir(modelPath); |
| 113 | if (!modelDir.empty()) { |
| 114 | const std::string modelCandidate = modelDir + fileName; |
| 115 | if (IsRegularFile(modelCandidate)) { |
| 116 | return modelCandidate; |
| 117 | } |
| 118 | } |
| 119 | // Development fallback: try deps/cppjieba/dict/ relative to the source tree |
| 120 | const std::string needle = "share/opencc/jieba_dict/"; |
| 121 | std::string::size_type pos = dictPath.find(needle); |
| 122 | if (pos != std::string::npos) { |
| 123 | std::string alt = dictPath; |
| 124 | alt.replace(pos, needle.size(), "plugins/jieba/deps/cppjieba/dict/"); |
| 125 | const std::string altDir = ParentDir(alt); |
| 126 | const std::string altCandidate = altDir + fileName; |
| 127 | if (IsRegularFile(altCandidate)) { |
| 128 | return altCandidate; |
| 129 | } |
| 130 | } |
| 131 | return candidate; |
| 132 | } |
| 133 | |
| 134 | bool EndsWith(const std::string& text, const std::string& suffix) { |
| 135 | return text.size() >= suffix.size() && |
| 136 | text.compare(text.size() - suffix.size(), suffix.size(), suffix) == 0; |
| 137 | } |
| 138 | |
| 139 | bool LooksLikeOpenccMergedDict(const std::string& path) { |
| 140 | return EndsWith(path, ".ocd2"); |
| 141 | } |
| 142 | |
| 143 | bool ParsePositiveDouble(const std::string& text, double* value) { |
| 144 | if (text.empty()) { |
| 145 | return false; |
| 146 | } |
| 147 | char* end = nullptr; |
| 148 | const double parsed = std::strtod(text.c_str(), &end); |
| 149 | if (end == text.c_str() || *end != '\0' || parsed <= 0.0) { |
| 150 | return false; |
| 151 | } |
| 152 | *value = parsed; |
| 153 | return true; |
| 154 | } |
| 155 | |
| 156 | bool ParseNonNegativeDouble(const std::string& text, double* value) { |
| 157 | if (text.empty()) { |
| 158 | return false; |
| 159 | } |
| 160 | char* end = nullptr; |
| 161 | const double parsed = std::strtod(text.c_str(), &end); |
| 162 | if (end == text.c_str() || *end != '\0' || parsed < 0.0) { |
| 163 | return false; |
| 164 | } |
| 165 | *value = parsed; |
| 166 | return true; |
| 167 | } |
| 168 | |
| 169 | struct RawMergedEntry { |
| 170 | std::string word; |
| 171 | std::string tag; |
| 172 | double freq; |
| 173 | bool contributes_to_base_sum; |
| 174 | bool uses_default_weight; |
| 175 | }; |
| 176 | |
| 177 | DictTrie::PrecomputedDict LoadMergedJiebaDict(const std::string& dictPath) { |
| 178 | const std::shared_ptr<MarisaDict> dict = |
| 179 | SerializableDict::NewFromFile<MarisaDict>(dictPath); |
| 180 | const LexiconPtr lexicon = dict->GetLexicon(); |
| 181 | |
| 182 | std::vector<RawMergedEntry> entries; |
| 183 | entries.reserve(lexicon->Length()); |
| 184 | double base_freq_sum = 0.0; |
| 185 | bool saw_metadata = false; |
| 186 | |
| 187 | for (size_t i = 0; i < lexicon->Length(); ++i) { |
| 188 | const DictEntry* entry = lexicon->At(i); |
| 189 | const std::vector<std::string> values = entry->Values(); |
| 190 | RawMergedEntry raw = {entry->Key(), "", 0.0, false, false}; |
| 191 | |
| 192 | if (values.size() == 3) { |
| 193 | saw_metadata = true; |
| 194 | raw.tag = values[1]; |
| 195 | if (values[2] == "base") { |
| 196 | if (!ParsePositiveDouble(values[0], &raw.freq)) { |
| 197 | throw std::runtime_error("invalid merged jieba base frequency for: " + |
| 198 | raw.word); |
| 199 | } |
| 200 | raw.contributes_to_base_sum = true; |
| 201 | } else if (values[2] == "user_freq") { |
| 202 | if (!ParseNonNegativeDouble(values[0], &raw.freq)) { |
| 203 | throw std::runtime_error( |
| 204 | "invalid merged jieba user frequency for: " + raw.word); |
| 205 | } |
| 206 | if (raw.freq == 0.0) { |
| 207 | raw.uses_default_weight = true; |
| 208 | } |
| 209 | } else if (values[2] == "user_default") { |
| 210 | raw.uses_default_weight = true; |
| 211 | } else { |
| 212 | throw std::runtime_error("unknown merged jieba entry kind for: " + |
| 213 | raw.word); |
| 214 | } |
| 215 | } else if (values.size() == 2) { |
| 216 | // Backward-compatible fallback for earlier generated dictionaries. |
| 217 | raw.tag = values[1]; |
| 218 | if (!ParsePositiveDouble(values[0], &raw.freq)) { |
| 219 | throw std::runtime_error("invalid merged jieba frequency for: " + |
| 220 | raw.word); |
| 221 | } |
| 222 | raw.contributes_to_base_sum = true; |
| 223 | } else if (values.size() == 1) { |
| 224 | raw.tag = values[0]; |
| 225 | raw.uses_default_weight = true; |
| 226 | } else { |
| 227 | throw std::runtime_error("invalid merged jieba values for: " + raw.word); |
| 228 | } |
| 229 | |
| 230 | if (raw.contributes_to_base_sum) { |
| 231 | base_freq_sum += raw.freq; |
| 232 | } |
| 233 | entries.push_back(raw); |
| 234 | } |
| 235 | |
| 236 | if (entries.empty()) { |
| 237 | throw std::runtime_error("merged jieba dictionary is empty"); |
| 238 | } |
| 239 | if (base_freq_sum <= 0.0) { |
| 240 | throw std::runtime_error("merged jieba dictionary has no base frequencies"); |
| 241 | } |
| 242 | |
| 243 | std::vector<double> base_weights; |
| 244 | base_weights.reserve(entries.size()); |
| 245 | for (size_t i = 0; i < entries.size(); ++i) { |
| 246 | if (entries[i].contributes_to_base_sum) { |
| 247 | base_weights.push_back(std::log(entries[i].freq / base_freq_sum)); |
| 248 | } else if (!saw_metadata && !entries[i].uses_default_weight && |
| 249 | entries[i].freq > 0.0) { |
| 250 | base_weights.push_back(std::log(entries[i].freq / base_freq_sum)); |
| 251 | } |
| 252 | } |
| 253 | if (base_weights.empty()) { |
| 254 | throw std::runtime_error( |
| 255 | "merged jieba dictionary has no weights for default entries"); |
| 256 | } |
| 257 | |
| 258 | std::sort(base_weights.begin(), base_weights.end()); |
| 259 | DictTrie::PrecomputedDict precomputed; |
| 260 | precomputed.freq_sum = base_freq_sum; |
| 261 | precomputed.min_weight = base_weights.front(); |
| 262 | precomputed.max_weight = base_weights.back(); |
| 263 | precomputed.median_weight = base_weights[base_weights.size() / 2]; |
| 264 | precomputed.node_infos.reserve(entries.size()); |
| 265 | |
| 266 | for (size_t i = 0; i < entries.size(); ++i) { |
| 267 | DictUnit node_info; |
| 268 | if (!cppjieba::DecodeUTF8RunesInString(entries[i].word, node_info.word)) { |
| 269 | throw std::runtime_error("UTF-8 decode failed for merged jieba word: " + |
| 270 | entries[i].word); |
| 271 | } |
| 272 | node_info.tag = entries[i].tag; |
| 273 | if (entries[i].uses_default_weight) { |
| 274 | node_info.weight = precomputed.median_weight; |
| 275 | } else { |
| 276 | node_info.weight = std::log(entries[i].freq / base_freq_sum); |
| 277 | } |
| 278 | const bool is_user_entry = |
| 279 | !entries[i].contributes_to_base_sum && (entries[i].uses_default_weight || |
| 280 | entries[i].freq >= 0.0); |
| 281 | if (is_user_entry && node_info.word.size() == 1) { |
| 282 | precomputed.single_char_user_words.insert(node_info.word[0]); |
| 283 | } |
| 284 | precomputed.node_infos.push_back(node_info); |
| 285 | } |
| 286 | |
| 287 | return precomputed; |
| 288 | } |
| 289 | } // namespace |
| 290 | |
| 291 | JiebaSegmentation::JiebaSegmentation(const std::string& dictPath, |
| 292 | const std::string& modelPath, |
| 293 | const std::string& userDictPath, |
| 294 | const std::string& idfPath, |
| 295 | const std::string& stopWordsPath) |
| 296 | : jieba_( |
| 297 | LooksLikeOpenccMergedDict(dictPath) |
| 298 | ? new cppjieba::Jieba(LoadMergedJiebaDict(dictPath), modelPath, |
| 299 | userDictPath.empty() ? "" : userDictPath, |
| 300 | idfPath.empty() |
| 301 | ? ResolveAuxPath(dictPath, modelPath, "idf.utf8") |
| 302 | : idfPath, |
| 303 | stopWordsPath.empty() |
| 304 | ? ResolveAuxPath(dictPath, modelPath, "stop_words.utf8") |
| 305 | : stopWordsPath) |
| 306 | : new cppjieba::Jieba( |
| 307 | dictPath, modelPath, |
| 308 | userDictPath.empty() ? "" : userDictPath, |
| 309 | idfPath.empty() |
| 310 | ? ResolveAuxPath(dictPath, modelPath, "idf.utf8") |
| 311 | : idfPath, |
| 312 | stopWordsPath.empty() |
| 313 | ? ResolveAuxPath(dictPath, modelPath, "stop_words.utf8") |
| 314 | : stopWordsPath)) { |
| 315 | } |
| 316 | |
| 317 | JiebaSegmentation::~JiebaSegmentation() = default; |
| 318 | |
| 319 | SegmentsPtr JiebaSegmentation::Segment(std::string_view text) const { |
| 320 | SegmentsPtr segments(new Segments); |
| 321 | std::vector<std::string> words; |
| 322 | jieba_->Cut(std::string(text), words, true); |
| 323 | for (const auto& word : words) { |
| 324 | segments->AddSegment(word); |
| 325 | } |
| 326 | return segments; |
| 327 | } |