Debian Codegraph @

src/PhraseExtract.cpp

raw symbols SCIP
1 /*
2 * Open Chinese Convert
3 *
4 * Copyright 2015-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 <algorithm>
20 #include <cmath>
21 #include <unordered_map>
22
23 #include "marisa/trie.h"
24
25 #include "PhraseExtract.hpp"
26
27 #ifdef _MSC_VER
28 #pragma execution_character_set("utf-8")
29 #endif
30
31 namespace opencc {
32
33 namespace internal {
34
35 bool ContainsPunctuation(const PhraseExtract::UTF8StringSlice8Bit& word) {
36 static const std::vector<PhraseExtract::UTF8StringSlice8Bit> punctuations = {
37 " ", "\n", "\r", "\t", "-", ",", ".", "?", "!", "*", " ",
38 ",", "。", "、", ";", ":", "?", "!", "…", "“", "”", "「",
39 "」", "—", "-", "(", ")", "《", "》", ".", "/", "\"};
40 for (const auto& punctuation : punctuations) {
41 if (word.FindBytePosition(punctuation) !=
42 static_cast<PhraseExtract::UTF8StringSlice8Bit::LengthType>(-1)) {
43 return true;
44 }
45 }
46 return false;
47 }
48
49 } // namespace internal
50
51 class PhraseExtract::DictType {
52 public:
53 typedef PhraseExtract::Signals ValueType;
54 typedef std::pair<UTF8StringSlice8Bit, ValueType> ItemType;
55
56 PhraseExtract::Signals& Get(const UTF8StringSlice8Bit& key) {
57 marisa::Agent agent;
58 agent.set_query(key.CString(), key.ByteLength());
59 if (marisa_trie.lookup(agent)) {
60 size_t item_id = marisa_id_item_map[agent.key().id()];
61 return items[item_id].second;
62 }
63
64 throw ShouldNotBeHere();
65 }
66
67 PhraseExtract::Signals& AddKey(const UTF8StringSlice8Bit& key) {
68 return dict[key];
69 }
70
71 void Clear() {
72 ClearDict();
73 marisa_trie.clear();
74 }
75
76 const std::vector<ItemType>& Items() const { return items; }
77
78 void Build() {
79 BuildKeys();
80 BuildTrie();
81 }
82
83 private:
84 void BuildKeys() {
85 items.reserve(dict.size());
86 for (const auto& item : dict) {
87 items.push_back(item);
88 }
89 ClearDict();
90 std::sort(
91 items.begin(), items.end(),
92 [](const ItemType& a, const ItemType& b) { return a.first < b.first; });
93 }
94
95 void ClearDict() {
96 std::unordered_map<UTF8StringSlice8Bit, PhraseExtract::Signals,
97 UTF8StringSlice8Bit::Hasher>()
98 .swap(dict);
99 }
100
101 void BuildTrie() {
102 std::unordered_map<std::string, size_t> key_item_id_map;
103 marisa::Keyset keyset;
104 for (size_t i = 0; i < items.size(); i++) {
105 const auto& key = items[i].first;
106 key_item_id_map[key.ToString()] = i;
107 keyset.push_back(key.CString(), key.ByteLength());
108 }
109 marisa_trie.build(keyset);
110 marisa::Agent agent;
111 agent.set_query("");
112 marisa_id_item_map.resize(items.size());
113 while (marisa_trie.predictive_search(agent)) {
114 size_t marisa_id = agent.key().id();
115 const std::string key(agent.key().ptr(), agent.key().length());
116 const auto it = key_item_id_map.find(key);
117 if (it == key_item_id_map.end()) {
118 throw ShouldNotBeHere();
119 }
120 size_t item_id = it->second;
121 marisa_id_item_map[marisa_id] = item_id;
122 }
123 }
124
125 std::unordered_map<UTF8StringSlice8Bit, PhraseExtract::Signals,
126 UTF8StringSlice8Bit::Hasher>
127 dict;
128 std::vector<ItemType> items;
129 marisa::Trie marisa_trie;
130 std::vector<size_t> marisa_id_item_map;
131 };
132
133 using namespace internal;
134
135 bool PhraseExtract::DefaultPreCalculationFilter(
136 const PhraseExtract&, const PhraseExtract::UTF8StringSlice8Bit&) {
137 return false;
138 }
139
140 bool PhraseExtract::DefaultPostCalculationFilter(
141 const PhraseExtract& phraseExtract,
142 const PhraseExtract::UTF8StringSlice8Bit& word) {
143 const PhraseExtract::Signals& signals = phraseExtract.Signal(word);
144 const double logProbability = phraseExtract.LogProbability(word);
145 const double cohesionScore = signals.cohesion - logProbability * 0.5;
146 const double entropyScore =
147 sqrt((signals.prefixEntropy) * (signals.suffixEntropy + 1)) -
148 logProbability * 0.85;
149 bool accept = cohesionScore > 9 && entropyScore > 11 &&
150 signals.prefixEntropy > 0.5 && signals.suffixEntropy > 0 &&
151 signals.prefixEntropy + signals.suffixEntropy > 3;
152 return !accept;
153 }
154
155 PhraseExtract::PhraseExtract()
156 : wordMinLength(2), wordMaxLength(2), prefixSetLength(1),
157 suffixSetLength(1), preCalculationFilter(DefaultPreCalculationFilter),
158 postCalculationFilter(DefaultPostCalculationFilter), utf8FullText(""),
159 signals(new DictType) {
160 Reset();
161 }
162
163 PhraseExtract::~PhraseExtract() { delete signals; }
164
165 void PhraseExtract::Reset() {
166 prefixesExtracted = false;
167 suffixesExtracted = false;
168 frequenciesCalculated = false;
169 wordCandidatesExtracted = false;
170 cohesionsCalculated = false;
171 prefixEntropiesCalculated = false;
172 suffixEntropiesCalculated = false;
173 wordsSelected = false;
174 totalOccurrence = 0;
175 logTotalOccurrence = 0;
176 ReleasePrefixes();
177 ReleaseSuffixes();
178 wordCandidates.clear();
179 words.clear();
180 signals->Clear();
181 utf8FullText = UTF8StringSlice("");
182 preCalculationFilter = DefaultPreCalculationFilter;
183 postCalculationFilter = DefaultPostCalculationFilter;
184 }
185
186 void PhraseExtract::ExtractSuffixes() {
187 suffixes.reserve(utf8FullText.UTF8Length() / 2 *
188 (wordMaxLength + suffixSetLength));
189 for (UTF8StringSlice text = utf8FullText; text.UTF8Length() > 0;
190 text.MoveRight()) {
191 const LengthType suffixLength =
192 (std::min)(static_cast<LengthType>(wordMaxLength + suffixSetLength),
193 text.UTF8Length());
194 const UTF8StringSlice& slice = text.Left(suffixLength);
195 suffixes.push_back(UTF8StringSlice8Bit(
196 slice.CString(),
197 static_cast<UTF8StringSlice8Bit::LengthType>(slice.UTF8Length()),
198 static_cast<UTF8StringSlice8Bit::LengthType>(slice.ByteLength())));
199 }
200 suffixes.shrink_to_fit();
201 // Sort suffixes
202 std::sort(suffixes.begin(), suffixes.end());
203 suffixesExtracted = true;
204 }
205
206 void PhraseExtract::ExtractPrefixes() {
207 prefixes.reserve(utf8FullText.UTF8Length() / 2 *
208 (wordMaxLength + prefixSetLength));
209 for (UTF8StringSlice text = utf8FullText; text.UTF8Length() > 0;
210 text.MoveLeft()) {
211 const LengthType prefixLength =
212 (std::min)(static_cast<LengthType>(wordMaxLength + prefixSetLength),
213 text.UTF8Length());
214 const UTF8StringSlice& slice = text.Right(prefixLength);
215 prefixes.push_back(UTF8StringSlice8Bit(
216 slice.CString(),
217 static_cast<UTF8StringSlice8Bit::LengthType>(slice.UTF8Length()),
218 static_cast<UTF8StringSlice8Bit::LengthType>(slice.ByteLength())));
219 }
220 prefixes.shrink_to_fit();
221 // Sort suffixes reversely
222 std::sort(prefixes.begin(), prefixes.end(),
223 [](const UTF8StringSlice8Bit& a, const UTF8StringSlice8Bit& b) {
224 return a.ReverseCompare(b) < 0;
225 });
226 prefixesExtracted = true;
227 }
228
229 void PhraseExtract::CalculateFrequency() {
230 if (!suffixesExtracted) {
231 ExtractSuffixes();
232 }
233 for (const auto& suffix : suffixes) {
234 for (UTF8StringSlice8Bit::LengthType i = 1;
235 i <= suffix.UTF8Length() && i <= wordMaxLength; i++) {
236 const UTF8StringSlice8Bit wordCandidate = suffix.Left(i);
237 signals->AddKey(wordCandidate).frequency++;
238 totalOccurrence++;
239 }
240 }
241 logTotalOccurrence = log(totalOccurrence);
242 signals->Build();
243 frequenciesCalculated = true;
244 }
245
246 void PhraseExtract::ExtractWordCandidates() {
247 if (!frequenciesCalculated) {
248 CalculateFrequency();
249 }
250 for (const auto& item : signals->Items()) {
251 const auto& wordCandidate = item.first;
252 if (wordCandidate.UTF8Length() < wordMinLength) {
253 continue;
254 }
255 if (ContainsPunctuation(wordCandidate)) {
256 continue;
257 }
258 if (preCalculationFilter(*this, wordCandidate)) {
259 continue;
260 }
261 wordCandidates.push_back(wordCandidate);
262 }
263 // Sort by frequency
264 std::sort(wordCandidates.begin(), wordCandidates.end(),
265 [this](const UTF8StringSlice8Bit& a, const UTF8StringSlice8Bit& b) {
266 const size_t freqA = Frequency(a);
267 const size_t freqB = Frequency(b);
268 if (freqA > freqB) {
269 return true;
270 } else if (freqA < freqB) {
271 return false;
272 } else {
273 return a < b;
274 }
275 });
276 wordCandidatesExtracted = true;
277 }
278
279 typedef std::unordered_map<PhraseExtract::UTF8StringSlice8Bit, size_t,
280 PhraseExtract::UTF8StringSlice8Bit::Hasher>
281 AdjacentSetType;
282
283 template <bool SUFFIX>
284 void CalculatePrefixSuffixEntropy(
285 const std::vector<PhraseExtract::UTF8StringSlice8Bit>& presuffixes,
286 const PhraseExtract::LengthType setLength,
287 const PhraseExtract::LengthType wordMinLength,
288 const PhraseExtract::LengthType wordMaxLength,
289 const std::function<void(const PhraseExtract::UTF8StringSlice8Bit& word,
290 AdjacentSetType& adjacentSet)>& updateEntropy) {
291 AdjacentSetType adjacentSet;
292 auto setLength8Bit =
293 static_cast<PhraseExtract::UTF8StringSlice8Bit::LengthType>(setLength);
294 for (PhraseExtract::LengthType length = wordMinLength;
295 length <= wordMaxLength; length++) {
296 adjacentSet.clear();
297 PhraseExtract::UTF8StringSlice8Bit lastWord("");
298 for (const auto& presuffix : presuffixes) {
299 if (presuffix.UTF8Length() < length) {
300 continue;
301 }
302 auto length8Bit =
303 static_cast<PhraseExtract::UTF8StringSlice8Bit::LengthType>(length);
304 const auto& wordCandidate =
305 SUFFIX ? presuffix.Left(length8Bit) : presuffix.Right(length8Bit);
306 if (wordCandidate != lastWord) {
307 updateEntropy(lastWord, adjacentSet);
308 lastWord = wordCandidate;
309 }
310 if (length + setLength <= presuffix.UTF8Length()) {
311 if (SUFFIX) {
312 const auto& wordSuffix =
313 presuffix.SubString(length8Bit, setLength8Bit);
314 adjacentSet[wordSuffix]++;
315 } else {
316 const auto& wordPrefix = presuffix.SubString(
317 presuffix.UTF8Length() - length8Bit - setLength8Bit,
318 setLength8Bit);
319 adjacentSet[wordPrefix]++;
320 }
321 }
322 }
323 updateEntropy(lastWord, adjacentSet);
324 }
325 }
326
327 void PhraseExtract::CalculateSuffixEntropy() {
328 if (!suffixesExtracted) {
329 ExtractSuffixes();
330 }
331 if (!frequenciesCalculated) {
332 CalculateFrequency();
333 }
334 CalculatePrefixSuffixEntropy<true>(
335 suffixes, suffixSetLength, wordMinLength, wordMaxLength,
336 [this](const PhraseExtract::UTF8StringSlice8Bit& word,
337 AdjacentSetType& adjacentSet) {
338 if (word.UTF8Length() > 0) {
339 signals->Get(word).suffixEntropy = CalculateEntropy(adjacentSet);
340 adjacentSet.clear();
341 }
342 });
343 suffixEntropiesCalculated = true;
344 }
345
346 void PhraseExtract::CalculatePrefixEntropy() {
347 if (!prefixesExtracted) {
348 ExtractPrefixes();
349 }
350 if (!frequenciesCalculated) {
351 CalculateFrequency();
352 }
353 CalculatePrefixSuffixEntropy<false>(
354 prefixes, prefixSetLength, wordMinLength, wordMaxLength,
355 [this](const PhraseExtract::UTF8StringSlice8Bit& word,
356 AdjacentSetType& adjacentSet) {
357 if (word.UTF8Length() > 0) {
358 signals->Get(word).prefixEntropy = CalculateEntropy(adjacentSet);
359 adjacentSet.clear();
360 }
361 });
362 prefixEntropiesCalculated = true;
363 }
364
365 void PhraseExtract::CalculateCohesions() {
366 if (!wordCandidatesExtracted) {
367 ExtractWordCandidates();
368 }
369 if (!frequenciesCalculated) {
370 CalculateFrequency();
371 }
372 for (const auto& wordCandidate : wordCandidates) {
373 signals->Get(wordCandidate).cohesion = CalculateCohesion(wordCandidate);
374 }
375 cohesionsCalculated = true;
376 }
377
378 const PhraseExtract::Signals&
379 PhraseExtract::Signal(const UTF8StringSlice8Bit& wordCandidate) const {
380 return signals->Get(wordCandidate);
381 }
382
383 double PhraseExtract::Cohesion(const UTF8StringSlice8Bit& word) const {
384 return Signal(word).cohesion;
385 }
386
387 double PhraseExtract::Entropy(const UTF8StringSlice8Bit& word) const {
388 return SuffixEntropy(word) + PrefixEntropy(word);
389 }
390
391 double PhraseExtract::SuffixEntropy(const UTF8StringSlice8Bit& word) const {
392 return Signal(word).suffixEntropy;
393 }
394
395 double PhraseExtract::PrefixEntropy(const UTF8StringSlice8Bit& word) const {
396 return Signal(word).prefixEntropy;
397 }
398
399 size_t PhraseExtract::Frequency(const UTF8StringSlice8Bit& word) const {
400 const size_t frequency = Signal(word).frequency;
401 return frequency;
402 }
403
404 double PhraseExtract::Probability(const UTF8StringSlice8Bit& word) const {
405 const size_t frequency = Frequency(word);
406 return static_cast<double>(frequency) / totalOccurrence;
407 }
408
409 double PhraseExtract::LogProbability(const UTF8StringSlice8Bit& word) const {
410 // log(frequency / totalOccurrence) = log(frequency) - log(totalOccurrence)
411 const size_t frequency = Frequency(word);
412 return log(frequency) - logTotalOccurrence;
413 }
414
415 double PhraseExtract::PMI(const UTF8StringSlice8Bit& wordCandidate,
416 const UTF8StringSlice8Bit& part1,
417 const UTF8StringSlice8Bit& part2) const {
418 // PMI(x, y) = log(P(x, y) / (P(x) * P(y)))
419 // = log(P(x, y)) - log(P(x)) - log(P(y))
420 return LogProbability(wordCandidate) - LogProbability(part1) -
421 LogProbability(part2);
422 }
423
424 double PhraseExtract::CalculateCohesion(
425 const UTF8StringSlice8Bit& wordCandidate) const {
426 // TODO Try average value
427 double minPMI = INFINITY;
428 for (UTF8StringSlice8Bit::LengthType leftLength = 1;
429 leftLength <= wordCandidate.UTF8Length() - 1; leftLength++) {
430 const auto& leftPart = wordCandidate.Left(leftLength);
431 const auto& rightPart =
432 wordCandidate.Right(wordCandidate.UTF8Length() - leftLength);
433 double pmi = PMI(wordCandidate, leftPart, rightPart);
434 minPMI = (std::min)(pmi, minPMI);
435 }
436 return minPMI;
437 }
438
439 double PhraseExtract::CalculateEntropy(
440 const std::unordered_map<UTF8StringSlice8Bit, size_t,
441 UTF8StringSlice8Bit::Hasher>& choices) const {
442 double totalChoices = 0;
443 for (const auto& item : choices) {
444 totalChoices += item.second;
445 }
446 double entropy = 0;
447 for (const auto& item : choices) {
448 const size_t occurrence = item.second;
449 const double probability = occurrence / totalChoices;
450 entropy += probability * log(probability);
451 }
452 if (entropy != 0) {
453 entropy = -entropy;
454 }
455 return entropy;
456 }
457
458 void PhraseExtract::SelectWords() {
459 if (!wordCandidatesExtracted) {
460 ExtractWordCandidates();
461 }
462 if (!cohesionsCalculated) {
463 CalculateCohesions();
464 }
465 if (!prefixEntropiesCalculated) {
466 CalculatePrefixEntropy();
467 }
468 if (!suffixEntropiesCalculated) {
469 CalculateSuffixEntropy();
470 }
471 for (const auto& word : wordCandidates) {
472 if (!postCalculationFilter(*this, word)) {
473 words.push_back(word);
474 }
475 }
476 wordsSelected = true;
477 }
478
479 } // namespace opencc