LIMA
Libre Multilingual Analyzer — C++ API
Loading...
Searching...
No Matches
lemm_rules.h
Go to the documentation of this file.
1// Copyright 2026 CEA LIST
2// SPDX-FileCopyrightText: 2026 CEA LIST <gael.de-chalendar@cea.fr>
3//
4// SPDX-License-Identifier: MIT
5
6#ifndef DEEPLIMA_LEMMATIZATION_LEMM_RULES_H
7#define DEEPLIMA_LEMMATIZATION_LEMM_RULES_H
8
49
50#include <algorithm>
51#include <cstdint>
52#include <functional>
53#include <istream>
54#include <map>
55#include <ostream>
56#include <stdexcept>
57#include <string>
58#include <tuple>
59#include <unordered_map>
60#include <utility>
61#include <vector>
62
63#include <unicode/uchar.h>
64#include <unicode/unistr.h>
65
66namespace deeplima
67{
68namespace lemmatization
69{
70
72inline std::u32string to_lower(const std::u32string& src)
73{
74 std::u32string result(src);
75 for (char32_t& c : result)
76 {
77 c = static_cast<char32_t>(u_tolower(static_cast<UChar32>(c)));
78 }
79 return result;
80}
81
82inline std::u32string utf8_to_u32(const std::string& src)
83{
84 const icu::UnicodeString u = icu::UnicodeString::fromUTF8(src);
85 std::u32string result(static_cast<size_t>(u.countChar32()), U'\0');
86 UErrorCode status = U_ZERO_ERROR;
87 u.toUTF32(reinterpret_cast<UChar32*>(result.data()), static_cast<int32_t>(result.size()), status);
88 if (U_FAILURE(status))
89 {
90 throw std::runtime_error("utf8_to_u32: can't convert \"" + src + "\"");
91 }
92 return result;
93}
94
95inline std::string u32_to_utf8(const std::u32string& src)
96{
97 const icu::UnicodeString u = icu::UnicodeString::fromUTF32(
98 reinterpret_cast<const UChar32*>(src.data()), static_cast<int32_t>(src.size()));
99 std::string result;
100 u.toUTF8String(result);
101 return result;
102}
103
105{
106 bool m_lower = false;
107 uint32_t m_strip = 0;
108 std::u32string m_add;
109
110 bool operator==(const edit_rule_t& other) const
111 {
112 return m_lower == other.m_lower && m_strip == other.m_strip && m_add == other.m_add;
113 }
114
116 bool operator<(const edit_rule_t& other) const
117 {
118 return std::make_tuple(m_strip, m_add.size(), m_add, m_lower)
119 < std::make_tuple(other.m_strip, other.m_add.size(), other.m_add, other.m_lower);
120 }
121};
122
128inline edit_rule_t extract_rule(const std::u32string& form, const std::u32string& lemma)
129{
130 auto make = [&lemma](const std::u32string& f, bool lower)
131 {
132 size_t p = 0;
133 while (p < f.size() && p < lemma.size() && f[p] == lemma[p])
134 {
135 ++p;
136 }
137 return edit_rule_t{lower, static_cast<uint32_t>(f.size() - p), lemma.substr(p)};
138 };
139 const edit_rule_t keep = make(form, false);
140 const edit_rule_t lower = make(to_lower(form), true);
141 return (std::make_pair(lower.m_strip, lower.m_add.size())
142 < std::make_pair(keep.m_strip, keep.m_add.size())) ? lower : keep;
143}
144
151
153inline size_t edit_cost(const affix_rule_t& r)
154{
155 return r.m_prefix.m_strip + r.m_prefix.m_add.size() + r.m_suffix.m_strip + r.m_suffix.m_add.size();
156}
157
162inline affix_rule_t extract_substring_rule(const std::u32string& form, const std::u32string& lemma,
163 bool lower)
164{
165 // Longest common substring, by dynamic programming on these short strings
166 size_t best = 0, best_i = 0, best_j = 0;
167 std::vector<size_t> previous(lemma.size() + 1, 0), current(lemma.size() + 1, 0);
168 for (size_t i = 1; i <= form.size(); ++i)
169 {
170 for (size_t j = 1; j <= lemma.size(); ++j)
171 {
172 current[j] = form[i - 1] == lemma[j - 1] ? previous[j - 1] + 1 : 0;
173 // Strictly longer only: on equal lengths, the earliest in form, then in
174 // lemma, stays
175 if (current[j] > best)
176 {
177 best = current[j];
178 best_i = i - best;
179 best_j = j - best;
180 }
181 }
182 std::swap(previous, current);
183 }
184 affix_rule_t r;
185 if (best == 0)
186 {
187 // Nothing in common: replace the whole word
188 r.m_suffix = edit_rule_t{lower, static_cast<uint32_t>(form.size()), lemma};
189 return r;
190 }
191 r.m_prefix = edit_rule_t{false, static_cast<uint32_t>(best_i), lemma.substr(0, best_j)};
192 r.m_suffix = edit_rule_t{lower, static_cast<uint32_t>(form.size() - best_i - best),
193 lemma.substr(best_j + best)};
194 return r;
195}
196
203inline affix_rule_t extract_affix_rule(const std::u32string& form, const std::u32string& lemma,
204 size_t max_prefix)
205{
206 affix_rule_t best;
207 best.m_suffix = extract_rule(form, lemma);
208 if (max_prefix == 0)
209 {
210 return best;
211 }
212 for (bool lower : {false, true})
213 {
214 const affix_rule_t r = extract_substring_rule(lower ? to_lower(form) : form, lemma, lower);
215 if (r.m_prefix.m_strip <= max_prefix && edit_cost(r) < edit_cost(best))
216 {
217 best = r;
218 }
219 }
220 return best;
221}
222
227inline bool apply_rule(const std::u32string& form, const edit_rule_t& prefix, const edit_rule_t& suffix,
228 std::u32string& lemma)
229{
230 if (static_cast<size_t>(prefix.m_strip) + suffix.m_strip > form.size())
231 {
232 return false;
233 }
234 const std::u32string word = suffix.m_lower ? to_lower(form) : form;
235 std::u32string result = prefix.m_add;
236 result.append(word, prefix.m_strip, word.size() - prefix.m_strip - suffix.m_strip);
237 result += suffix.m_add;
238 if (result.empty())
239 {
240 return false;
241 }
242 lemma = std::move(result);
243 return true;
244}
245
247inline bool apply_rule(const std::u32string& form, const edit_rule_t& rule, std::u32string& lemma)
248{
249 return apply_rule(form, edit_rule_t{}, rule, lemma);
250}
251
253inline const std::string& any_feats()
254{
255 static const std::string s("*");
256 return s;
257}
258
275{
276public:
277 explicit lemm_rules_builder_t(size_t max_suffix = 6, size_t max_prefix = 0)
278 : m_max_suffix(max_suffix), m_max_prefix(max_prefix) {}
279
280 void add(const std::string& upos, const std::string& feats,
281 const std::u32string& form, const std::u32string& lemma)
282 {
283 if (form.empty() || lemma.empty())
284 {
285 return;
286 }
287 const affix_rule_t rule = extract_affix_rule(form, lemma, m_max_prefix);
288 const std::u32string low = to_lower(form);
289 for (const std::string* f : {&feats, &any_feats()})
290 {
291 for (size_t n = rule.m_suffix.m_strip; n <= std::min(m_max_suffix, low.size()); ++n)
292 {
293 m_counts[std::make_tuple(upos, *f, low.substr(low.size() - n))][rule.m_suffix]++;
294 }
295 // Without prefix rules, nothing: the identity everywhere
296 for (size_t n = rule.m_prefix.m_strip; m_max_prefix > 0 && n <= std::min(m_max_prefix, low.size()); ++n)
297 {
298 m_prefix_counts[std::make_tuple(upos, *f, low.substr(0, n))][rule.m_prefix]++;
299 }
300 }
301 }
302
307 void write(std::ostream& out) const
308 {
309 out << "# deeplima lemmatization rules\n"
310 << "# upos\tfeats\tsuffix\tlower\tstrip\tadd\tcount\n";
311 write(out, m_counts, "");
312 if (!m_prefix_counts.empty())
313 {
314 out << "# prefix\tupos\tfeats\tbeginning\tlower\tstrip\tadd\tcount\n";
315 write(out, m_prefix_counts, "prefix\t");
316 }
317 }
318
319private:
320 typedef std::map<std::tuple<std::string, std::string, std::u32string>, std::map<edit_rule_t, size_t>> counts_t;
321
322 static void write(std::ostream& out, const counts_t& counts, const char* line_start)
323 {
324 for (const auto& [key, rules] : counts)
325 {
326 const auto best = std::max_element(rules.begin(), rules.end(),
327 [](const auto& a, const auto& b)
328 {
329 // max_element: b wins if a < b; on equal
330 // counts the simpler rule must win
331 return a.second < b.second
332 || (a.second == b.second && b.first < a.first);
333 });
334 out << line_start
335 << std::get<0>(key) << '\t' << std::get<1>(key) << '\t' << u32_to_utf8(std::get<2>(key)) << '\t'
336 << (best->first.m_lower ? 1 : 0) << '\t' << best->first.m_strip << '\t'
337 << u32_to_utf8(best->first.m_add) << '\t' << best->second << '\n';
338 }
339 }
340
341 size_t m_max_suffix;
342 size_t m_max_prefix;
343 counts_t m_counts;
344 counts_t m_prefix_counts;
345};
346
349{
350 bool m_prefix = false; // a prefix rule, m_suffix then being the word's beginning
351 std::string m_upos;
352 std::string m_feats;
353 std::u32string m_suffix;
355 size_t m_count = 0;
356};
357
359inline std::vector<std::string> split_tabs(const std::string& line)
360{
361 std::vector<std::string> fields;
362 size_t start = 0;
363 while (true)
364 {
365 const size_t end = line.find('\t', start);
366 fields.push_back(line.substr(start, end == std::string::npos ? std::string::npos : end - start));
367 if (end == std::string::npos)
368 {
369 return fields;
370 }
371 start = end + 1;
372 }
373}
374
376inline void read_rules(std::istream& in, const std::function<void(const rule_line_t&)>& fn)
377{
378 std::string line;
379 size_t line_no = 0;
380 while (std::getline(in, line))
381 {
382 ++line_no;
383 if (!line.empty() && line.back() == '\r')
384 {
385 line.pop_back();
386 }
387 if (line.empty() || line[0] == '#')
388 {
389 continue;
390 }
391 std::vector<std::string> f = split_tabs(line);
392 auto fail = [&](const std::string& why)
393 {
394 throw std::runtime_error("Lemmatization rules line " + std::to_string(line_no)
395 + ": " + why + ": \"" + line + "\"");
396 };
397 rule_line_t r;
398 if (f.size() == 8 && f[0] == "prefix")
399 {
400 r.m_prefix = true;
401 f.erase(f.begin());
402 }
403 else if (f.size() != 7)
404 {
405 fail("expected 7 tab-separated fields (8 for a prefix rule)");
406 }
407 if (f[0].empty() || f[1].empty() || (f[3] != "0" && f[3] != "1") || (r.m_prefix && f[3] != "0"))
408 {
409 fail("bad upos, feats or lower field");
410 }
411 r.m_upos = f[0];
412 r.m_feats = f[1];
413 r.m_suffix = utf8_to_u32(f[2]);
414 r.m_rule.m_lower = f[3] == "1";
415 r.m_rule.m_add = utf8_to_u32(f[5]);
416 try
417 {
418 r.m_rule.m_strip = static_cast<uint32_t>(std::stoul(f[4]));
419 r.m_count = std::stoul(f[6]);
420 }
421 catch (const std::logic_error&)
422 {
423 fail("bad strip or count field");
424 }
425 fn(r);
426 }
427}
428
438template <typename K, typename KHash = std::hash<K>>
440{
441public:
447 void add(const K& key, const std::u32string& affix, const edit_rule_t& rule, size_t count,
448 bool fallback, bool prefix = false)
449 {
450 tables_t& tables = prefix ? m_prefix : m_suffix;
451 table_t& table = fallback ? tables.m_fallback : tables.m_exact;
452 auto [it, inserted] = table.try_emplace(std::make_pair(key, affix), entry_t{rule, count});
453 if (!inserted && count > it->second.m_count)
454 {
455 it->second = entry_t{rule, count};
456 }
457 tables.m_max_length = std::max(tables.m_max_length, affix.size());
458 }
459
460 bool empty() const { return m_suffix.empty(); }
461 size_t size() const { return m_suffix.size() + m_prefix.size(); }
462
469 bool lemmatize(const K& exact, const K& fallback, const std::u32string& form, std::u32string& lemma) const
470 {
471 if (empty())
472 {
473 return false;
474 }
475 const std::u32string low = to_lower(form);
476 for (size_t n = std::min(m_suffix.m_max_length, low.size()) + 1; n-- > 0; )
477 {
478 const std::u32string suffix = low.substr(low.size() - n);
479 for (const table_t* table : {&m_suffix.m_exact, &m_suffix.m_fallback})
480 {
481 const edit_rule_t* rule = find(*table, table == &m_suffix.m_exact ? exact : fallback, suffix);
482 if (nullptr != rule && rule->m_strip <= form.size()
483 && apply_rule(form, find_prefix(exact, fallback, low, form.size() - rule->m_strip), *rule, lemma))
484 {
485 return true;
486 }
487 }
488 }
489 return false;
490 }
491
492private:
493 struct entry_t
494 {
495 edit_rule_t m_rule;
496 size_t m_count;
497 };
498 struct key_hash
499 {
500 size_t operator()(const std::pair<K, std::u32string>& k) const
501 {
502 return KHash()(k.first) ^ (std::hash<std::u32string>()(k.second) * 31);
503 }
504 };
505
506 typedef std::unordered_map<std::pair<K, std::u32string>, entry_t, key_hash> table_t;
507
508 struct tables_t
509 {
510 table_t m_exact;
511 table_t m_fallback;
512 size_t m_max_length = 0; // of the longest affix
513
514 bool empty() const { return m_exact.empty() && m_fallback.empty(); }
515 size_t size() const { return m_exact.size() + m_fallback.size(); }
516 };
517
518 static const edit_rule_t* find(const table_t& table, const K& key, const std::u32string& affix)
519 {
520 const auto it = table.find(std::make_pair(key, affix));
521 return table.end() == it ? nullptr : &it->second.m_rule;
522 }
523
525 edit_rule_t find_prefix(const K& exact, const K& fallback, const std::u32string& low, size_t max_strip) const
526 {
527 for (size_t n = std::min(m_prefix.m_max_length, low.size()) + 1; !m_prefix.empty() && n-- > 0; )
528 {
529 const std::u32string beginning = low.substr(0, n);
530 for (const table_t* table : {&m_prefix.m_exact, &m_prefix.m_fallback})
531 {
532 const edit_rule_t* rule = find(*table, table == &m_prefix.m_exact ? exact : fallback, beginning);
533 if (nullptr != rule && rule->m_strip <= max_strip)
534 {
535 return *rule;
536 }
537 }
538 }
539 return edit_rule_t{};
540 }
541
542 tables_t m_suffix;
543 tables_t m_prefix;
544};
545
546} // namespace lemmatization
547} // namespace deeplima
548
549#endif
void write(std::ostream &out) const
The most supported rule of each (UPOS, FEATS, ending), then of each (UPOS, FEATS, beginning); ties go...
Definition lemm_rules.h:307
void add(const std::string &upos, const std::string &feats, const std::u32string &form, const std::u32string &lemma)
Definition lemm_rules.h:280
lemm_rules_builder_t(size_t max_suffix=6, size_t max_prefix=0)
Definition lemm_rules.h:277
Rules ready for lookup, keyed by K, the analyzer's encoding of UPOS(+FEATS) (morph_feats_t in TokenSe...
Definition lemm_rules.h:440
void add(const K &key, const std::u32string &affix, const edit_rule_t &rule, size_t count, bool fallback, bool prefix=false)
Adds a rule to the exact or the fallback table, of the suffixes or of the beginnings (prefix,...
Definition lemm_rules.h:447
bool lemmatize(const K &exact, const K &fallback, const std::u32string &form, std::u32string &lemma) const
Lemmatizes form with the rule of its longest known ending, the exact features before the UPOS-only fa...
Definition lemm_rules.h:469
const std::string & any_feats()
The feats value of the rule used when no rule matches the exact features.
Definition lemm_rules.h:253
std::string u32_to_utf8(const std::u32string &src)
Definition lemm_rules.h:95
edit_rule_t extract_rule(const std::u32string &form, const std::u32string &lemma)
The rule turning form into lemma that keeps the longest common prefix: lowercasing is part of the rul...
Definition lemm_rules.h:128
affix_rule_t extract_affix_rule(const std::u32string &form, const std::u32string &lemma, size_t max_prefix)
The rule turning form into lemma with a prefix edit stripping at most max_prefix characters: the suff...
Definition lemm_rules.h:203
bool apply_rule(const std::u32string &form, const edit_rule_t &prefix, const edit_rule_t &suffix, std::u32string &lemma)
Applies the prefix and suffix rules to form.
Definition lemm_rules.h:227
affix_rule_t extract_substring_rule(const std::u32string &form, const std::u32string &lemma, bool lower)
The edit turning form into lemma around their longest common substring, the earliest one in form,...
Definition lemm_rules.h:162
std::vector< std::string > split_tabs(const std::string &line)
Splits on tabs, keeping empty fields (utils::split drops them).
Definition lemm_rules.h:359
std::u32string to_lower(const std::u32string &src)
Lowercases code point by code point (ICU simple case mapping, any script).
Definition lemm_rules.h:72
void read_rules(std::istream &in, const std::function< void(const rule_line_t &)> &fn)
Reads a rules file, calling fn(const rule_line_t&) on each rule.
Definition lemm_rules.h:376
std::u32string utf8_to_u32(const std::string &src)
Definition lemm_rules.h:82
size_t edit_cost(const affix_rule_t &r)
The length of the edit: characters stripped and added at both ends.
Definition lemm_rules.h:153
Edit rules for lemmatizing words absent from the lemma dictionary.
A whole word's edit: a prefix rule (never lowercasing) and a suffix rule.
Definition lemm_rules.h:147
bool operator==(const edit_rule_t &other) const
Definition lemm_rules.h:110
bool operator<(const edit_rule_t &other) const
Simplest first: fewer characters stripped, then fewer added.
Definition lemm_rules.h:116
One line of a rules file, as read_rules() hands it over.
Definition lemm_rules.h:349