LIMA
Libre Multilingual Analyzer — C++ API
Loading...
Searching...
No Matches
mwt_lexicon.h
Go to the documentation of this file.
1// Copyright 2021 CEA LIST
2// SPDX-FileCopyrightText: 2026 CEA LIST <gael.de-chalendar@cea.fr>
3//
4// SPDX-License-Identifier: MIT
5
6#ifndef DEEPLIMA_MWT_LEXICON_H
7#define DEEPLIMA_MWT_LEXICON_H
8
9#include <algorithm>
10#include <cstdint>
11#include <fstream>
12#include <istream>
13#include <map>
14#include <ostream>
15#include <stdexcept>
16#include <string>
17#include <tuple>
18#include <unordered_map>
19#include <vector>
20
22
23namespace deeplima
24{
25
64{
65public:
66 struct Rule
67 {
68 bool suffix = true;
69 std::string affix; // removed from the surface
70 std::string rewrite; // appended (suffix) or prepended (prefix) to the stem
71 std::vector<std::string> words; // after (suffix) or before (prefix) the stem word
72 uint32_t support = 0; // dictionary entries the rule reproduces
73 uint32_t applicable = 0; // dictionary entries having the affix
74
75 double score() const
76 {
77 return double(support) / double(applicable + 1);
78 }
79
80 // Is this rule better than the other one (score, support, affix length,
81 // then a fixed order for determinism)?
82 bool better_than(const Rule& o) const
83 {
84 if (score() != o.score()) return score() > o.score();
85 if (support != o.support) return support > o.support;
86 if (affix.size() != o.affix.size()) return affix.size() > o.affix.size();
87 return std::tie(suffix, affix, rewrite, words) < std::tie(o.suffix, o.affix, o.rewrite, o.words);
88 }
89
90 std::vector<std::string> apply(const std::string& surface) const
91 {
92 std::vector<std::string> result;
93 if (suffix)
94 {
95 result.push_back(surface.substr(0, surface.size() - affix.size()) + rewrite);
96 result.insert(result.end(), words.begin(), words.end());
97 }
98 else
99 {
100 result = words;
101 result.push_back(rewrite + surface.substr(affix.size()));
102 }
103 return result;
104 }
105 };
106
107 MwtLexicon() = default;
108
109 explicit MwtLexicon(const std::string& fn)
110 {
111 load(fn);
112 }
113
114 void load(const std::string& fn)
115 {
116 std::ifstream f(fn);
117 if (!f.is_open())
118 {
119 throw std::runtime_error("MwtLexicon: can't open \"" + fn + "\"");
120 }
121 load(f);
122 // The seq2seq fallback, when trained for this dictionary
123 m_s2s.clear();
124 if (std::ifstream(fn + ".s2s").good())
125 {
126 m_s2s.load(fn + ".s2s");
127 }
128 }
129
130 void load(std::istream& f)
131 {
132 m_dict.clear();
133 m_suffix_rules.clear();
134 m_prefix_rules.clear();
135 std::string line;
136 while (std::getline(f, line))
137 {
138 if (!line.empty() && '\r' == line.back())
139 {
140 line.pop_back();
141 }
142 if (line.empty())
143 {
144 continue;
145 }
146 const std::vector<std::string> fields = split(line);
147 if ('#' == line[0])
148 {
149 // #rule suffix|prefix affix rewrite support applicable word1 ...
150 if (fields.size() >= 7 && "#rule" == fields[0]
151 && ("suffix" == fields[1] || "prefix" == fields[1]) && !fields[2].empty())
152 {
153 Rule r;
154 r.suffix = ("suffix" == fields[1]);
155 r.affix = fields[2];
156 r.rewrite = fields[3];
157 try
158 {
159 r.support = uint32_t(std::stoul(fields[4]));
160 r.applicable = uint32_t(std::stoul(fields[5]));
161 }
162 catch (const std::logic_error&)
163 {
164 continue; // malformed counts: not a rule
165 }
166 r.words.assign(fields.begin() + 6, fields.end());
167 add_rule(std::move(r));
168 }
169 continue;
170 }
171 // surface count word1 word2 ...: at least two words
172 if (fields.size() < 4 || fields[0].empty())
173 {
174 continue;
175 }
176 m_dict.emplace(fields[0], std::vector<std::string>(fields.begin() + 2, fields.end()));
177 }
178 }
179
180 size_t size() const
181 {
182 return m_dict.size();
183 }
184
185 size_t rules_size() const
186 {
187 return m_suffix_rules.size() + m_prefix_rules.size();
188 }
189
190 bool has_seq2seq() const
191 {
192 return m_s2s.loaded();
193 }
194
195 void add_entry(const std::string& surface, const std::vector<std::string>& words)
196 {
197 m_dict.emplace(surface, words);
198 }
199
200 // Keeps, for each affix, the best rule.
202 {
203 auto& rules = r.suffix ? m_suffix_rules : m_prefix_rules;
204 auto it = rules.find(r.affix);
205 if (rules.end() == it)
206 {
207 std::string affix = r.affix;
208 rules.emplace(std::move(affix), std::move(r));
209 }
210 else if (r.better_than(it->second))
211 {
212 it->second = std::move(r);
213 }
214 }
215
216 // The dictionary's expansion of surface, or nullptr.
217 const std::vector<std::string>* lookup(const std::string& surface) const
218 {
219 const auto it = m_dict.find(surface);
220 return (m_dict.end() == it) ? nullptr : &it->second;
221 }
222
223 // The best rule for surface, or nullptr. The stem keeps at least one character.
224 const Rule* find_rule(const std::string& surface) const
225 {
226 const Rule* best = nullptr;
227 // Every character boundary strictly inside the surface
228 for (size_t i = 1; i < surface.size(); ++i)
229 {
230 if (is_continuation(surface[i]))
231 {
232 continue;
233 }
234 const auto s = m_suffix_rules.find(surface.substr(i));
235 if (m_suffix_rules.end() != s && (nullptr == best || s->second.better_than(*best)))
236 {
237 best = &s->second;
238 }
239 const auto p = m_prefix_rules.find(surface.substr(0, i));
240 if (m_prefix_rules.end() != p && (nullptr == best || p->second.better_than(*best)))
241 {
242 best = &p->second;
243 }
244 }
245 return best;
246 }
247
248 // Expands surface into words: from the dictionary, then, when use_rules
249 // (the segmenter flagged it), with the best rule and the seq2seq, in the
250 // order the seq2seq model asks. False when the surface stays as it is.
251 bool expand(const std::string& surface, std::vector<std::string>& words, bool use_rules) const
252 {
253 if (const auto* w = lookup(surface))
254 {
255 words = *w;
256 return true;
257 }
258 if (use_rules)
259 {
260 const bool s2s = m_s2s.loaded();
261 if (s2s && m_s2s.before_rules())
262 {
263 std::vector<std::string> w = m_s2s.expand(surface);
264 if (!w.empty())
265 {
266 words = std::move(w);
267 return true;
268 }
269 }
270 if (const Rule* r = find_rule(surface))
271 {
272 words = r->apply(surface);
273 return true;
274 }
275 if (s2s && !m_s2s.before_rules())
276 {
277 std::vector<std::string> w = m_s2s.expand(surface);
278 if (!w.empty())
279 {
280 words = std::move(w);
281 return true;
282 }
283 }
284 }
285 return false;
286 }
287
288 // Learns the affix rules from the dictionary (see the class comment).
289 // Returns the number of rules kept.
290 size_t learn_rules(uint32_t min_support)
291 {
292 m_suffix_rules.clear();
293 m_prefix_rules.clear();
294 if (0 == min_support)
295 {
296 return 0;
297 }
298
299 std::map<Rule, uint32_t, RuleOrder> support;
300 for (const auto& [surface, words] : m_dict)
301 {
302 for (Rule& r : rules_of(surface, words))
303 {
304 support[r]++;
305 }
306 }
307
308 // Entries having each affix, for the affixes of the rules that are kept
309 std::map<std::pair<bool, std::string>, uint32_t> applicable;
310 for (const auto& [r, n] : support)
311 {
312 if (n >= min_support)
313 {
314 applicable.emplace(std::make_pair(r.suffix, r.affix), 0);
315 }
316 }
317 for (const auto& [surface, words] : m_dict)
318 {
319 for (size_t i = 1; i < surface.size(); ++i)
320 {
321 if (is_continuation(surface[i]))
322 {
323 continue;
324 }
325 auto s = applicable.find(std::make_pair(true, surface.substr(i)));
326 if (applicable.end() != s) s->second++;
327 auto p = applicable.find(std::make_pair(false, surface.substr(0, i)));
328 if (applicable.end() != p) p->second++;
329 }
330 }
331
332 for (const auto& [r, n] : support)
333 {
334 if (n < min_support)
335 {
336 continue;
337 }
338 Rule kept = r;
339 kept.support = n;
340 kept.applicable = applicable[std::make_pair(r.suffix, r.affix)];
341 add_rule(std::move(kept));
342 }
343 return rules_size();
344 }
345
346 // Writes the rules in the file format, by side then affix.
347 void write_rules(std::ostream& out) const
348 {
349 for (const auto* rules : {&m_suffix_rules, &m_prefix_rules})
350 {
351 std::map<std::string, const Rule*> sorted;
352 for (const auto& [affix, r] : *rules)
353 {
354 sorted.emplace(affix, &r);
355 }
356 for (const auto& [affix, r] : sorted)
357 {
358 out << "#rule\t" << (r->suffix ? "suffix" : "prefix") << "\t" << r->affix << "\t"
359 << r->rewrite << "\t" << r->support << "\t" << r->applicable;
360 for (const auto& w : r->words)
361 {
362 out << "\t" << w;
363 }
364 out << "\n";
365 }
366 }
367 }
368
369 // The suffix and the prefix rule an entry gives, if any.
370 static std::vector<Rule> rules_of(const std::string& surface, const std::vector<std::string>& words)
371 {
372 std::vector<Rule> result;
373 if (words.size() < 2)
374 {
375 return result;
376 }
377 // Suffix: surface = stem + affix, first word = stem + rewrite
378 const std::string& first = words.front();
379 const size_t k = common_prefix(surface, first);
380 if (k > 0 && k < surface.size())
381 {
382 Rule r;
383 r.suffix = true;
384 r.affix = surface.substr(k);
385 r.rewrite = first.substr(k);
386 r.words.assign(words.begin() + 1, words.end());
387 result.push_back(std::move(r));
388 }
389 // Prefix: surface = affix + stem, last word = rewrite + stem
390 const std::string& last = words.back();
391 const size_t l = common_suffix(surface, last);
392 if (l > 0 && l < surface.size())
393 {
394 Rule r;
395 r.suffix = false;
396 r.affix = surface.substr(0, surface.size() - l);
397 r.rewrite = last.substr(0, last.size() - l);
398 r.words.assign(words.begin(), words.end() - 1);
399 result.push_back(std::move(r));
400 }
401 return result;
402 }
403
404 // Byte length of the longest common prefix of a and b, on a character boundary
405 static size_t common_prefix(const std::string& a, const std::string& b)
406 {
407 size_t k = 0;
408 while (k < a.size() && k < b.size() && a[k] == b[k])
409 {
410 ++k;
411 }
412 // Back to the start of a character, in both strings
413 while (k > 0 && ((k < a.size() && is_continuation(a[k])) || (k < b.size() && is_continuation(b[k]))))
414 {
415 --k;
416 }
417 return k;
418 }
419
420 // Byte length of the longest common suffix of a and b, on a character boundary
421 static size_t common_suffix(const std::string& a, const std::string& b)
422 {
423 size_t k = 0;
424 while (k < a.size() && k < b.size() && a[a.size() - 1 - k] == b[b.size() - 1 - k])
425 {
426 ++k;
427 }
428 // The common part must start a character
429 while (k > 0 && is_continuation(a[a.size() - k]))
430 {
431 --k;
432 }
433 return k;
434 }
435
436private:
437 static bool is_continuation(char c)
438 {
439 return (static_cast<unsigned char>(c) & 0xC0) == 0x80;
440 }
441
442 static std::vector<std::string> split(const std::string& line)
443 {
444 std::vector<std::string> fields;
445 size_t start = 0;
446 for (;;)
447 {
448 const size_t tab = line.find('\t', start);
449 fields.push_back(line.substr(start, std::string::npos == tab ? std::string::npos : tab - start));
450 if (std::string::npos == tab)
451 {
452 break;
453 }
454 start = tab + 1;
455 }
456 return fields;
457 }
458
459 // Identity of a rule, its counts excluded
460 struct RuleOrder
461 {
462 bool operator()(const Rule& a, const Rule& b) const
463 {
464 return std::tie(a.suffix, a.affix, a.rewrite, a.words) < std::tie(b.suffix, b.affix, b.rewrite, b.words);
465 }
466 };
467
468 std::unordered_map<std::string, std::vector<std::string>> m_dict;
469 std::unordered_map<std::string, Rule> m_suffix_rules; // by affix
470 std::unordered_map<std::string, Rule> m_prefix_rules; // by affix
471 MwtSeq2Seq m_s2s;
472};
473
474} // namespace deeplima
475
476#endif
size_t size() const
static std::vector< Rule > rules_of(const std::string &surface, const std::vector< std::string > &words)
const Rule * find_rule(const std::string &surface) const
size_t rules_size() const
bool has_seq2seq() const
void write_rules(std::ostream &out) const
void load(std::istream &f)
void add_entry(const std::string &surface, const std::vector< std::string > &words)
bool expand(const std::string &surface, std::vector< std::string > &words, bool use_rules) const
size_t learn_rules(uint32_t min_support)
const std::vector< std::string > * lookup(const std::string &surface) const
void load(const std::string &fn)
MwtLexicon(const std::string &fn)
static size_t common_suffix(const std::string &a, const std::string &b)
static size_t common_prefix(const std::string &a, const std::string &b)
void add_rule(Rule r)
Edit rules for lemmatizing words absent from the lemma dictionary.
std::vector< std::string > words
Definition mwt_lexicon.h:71
bool better_than(const Rule &o) const
Definition mwt_lexicon.h:82
std::vector< std::string > apply(const std::string &surface) const
Definition mwt_lexicon.h:90