6#ifndef DEEPLIMA_LEMMATIZATION_LEMM_RULES_H
7#define DEEPLIMA_LEMMATIZATION_LEMM_RULES_H
59#include <unordered_map>
63#include <unicode/uchar.h>
64#include <unicode/unistr.h>
72inline std::u32string
to_lower(
const std::u32string& src)
74 std::u32string result(src);
75 for (
char32_t& c : result)
77 c =
static_cast<char32_t>(u_tolower(
static_cast<UChar32
>(c)));
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))
90 throw std::runtime_error(
"utf8_to_u32: can't convert \"" + src +
"\"");
97 const icu::UnicodeString u = icu::UnicodeString::fromUTF32(
98 reinterpret_cast<const UChar32*
>(src.data()),
static_cast<int32_t
>(src.size()));
100 u.toUTF8String(result);
130 auto make = [&lemma](
const std::u32string& f,
bool lower)
133 while (p < f.size() && p < lemma.size() && f[p] == lemma[p])
137 return edit_rule_t{lower,
static_cast<uint32_t
>(f.size() - p), lemma.substr(p)};
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;
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)
170 for (
size_t j = 1; j <= lemma.size(); ++j)
172 current[j] = form[i - 1] == lemma[j - 1] ? previous[j - 1] + 1 : 0;
175 if (current[j] > best)
182 std::swap(previous, current);
193 lemma.substr(best_j + best)};
212 for (
bool lower : {
false,
true})
228 std::u32string& lemma)
230 if (
static_cast<size_t>(prefix.
m_strip) + suffix.
m_strip > form.size())
235 std::u32string result = prefix.
m_add;
237 result += suffix.
m_add;
242 lemma = std::move(result);
255 static const std::string s(
"*");
278 : m_max_suffix(max_suffix), m_max_prefix(max_prefix) {}
280 void add(
const std::string& upos,
const std::string& feats,
281 const std::u32string& form,
const std::u32string& lemma)
283 if (form.empty() || lemma.empty())
288 const std::u32string low =
to_lower(form);
289 for (
const std::string* f : {&feats, &
any_feats()})
291 for (
size_t n = rule.
m_suffix.
m_strip; n <= std::min(m_max_suffix, low.size()); ++n)
293 m_counts[std::make_tuple(upos, *f, low.substr(low.size() - n))][rule.
m_suffix]++;
296 for (
size_t n = rule.
m_prefix.
m_strip; m_max_prefix > 0 && n <= std::min(m_max_prefix, low.size()); ++n)
298 m_prefix_counts[std::make_tuple(upos, *f, low.substr(0, n))][rule.
m_prefix]++;
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())
314 out <<
"# prefix\tupos\tfeats\tbeginning\tlower\tstrip\tadd\tcount\n";
315 write(out, m_prefix_counts,
"prefix\t");
320 typedef std::map<std::tuple<std::string, std::string, std::u32string>, std::map<edit_rule_t, size_t>> counts_t;
322 static void write(std::ostream& out,
const counts_t& counts,
const char* line_start)
324 for (
const auto& [key, rules] : counts)
326 const auto best = std::max_element(rules.begin(), rules.end(),
327 [](
const auto& a,
const auto& b)
331 return a.second < b.second
332 || (a.second == b.second && b.first < a.first);
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';
344 counts_t m_prefix_counts;
359inline std::vector<std::string>
split_tabs(
const std::string& line)
361 std::vector<std::string> fields;
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)
380 while (std::getline(in, line))
383 if (!line.empty() && line.back() ==
'\r')
387 if (line.empty() || line[0] ==
'#')
391 std::vector<std::string> f =
split_tabs(line);
392 auto fail = [&](
const std::string& why)
394 throw std::runtime_error(
"Lemmatization rules line " + std::to_string(line_no)
395 +
": " + why +
": \"" + line +
"\"");
398 if (f.size() == 8 && f[0] ==
"prefix")
403 else if (f.size() != 7)
405 fail(
"expected 7 tab-separated fields (8 for a prefix rule)");
407 if (f[0].empty() || f[1].empty() || (f[3] !=
"0" && f[3] !=
"1") || (r.
m_prefix && f[3] !=
"0"))
409 fail(
"bad upos, feats or lower field");
421 catch (
const std::logic_error&)
423 fail(
"bad strip or count field");
438template <
typename K,
typename KHash = std::hash<K>>
447 void add(
const K& key,
const std::u32string& affix,
const edit_rule_t& rule,
size_t count,
448 bool fallback,
bool prefix =
false)
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)
455 it->second = entry_t{rule, count};
457 tables.m_max_length = std::max(tables.m_max_length, affix.size());
460 bool empty()
const {
return m_suffix.empty(); }
461 size_t size()
const {
return m_suffix.size() + m_prefix.size(); }
469 bool lemmatize(
const K& exact,
const K& fallback,
const std::u32string& form, std::u32string& lemma)
const
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; )
478 const std::u32string suffix = low.substr(low.size() - n);
479 for (
const table_t* table : {&m_suffix.m_exact, &m_suffix.m_fallback})
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))
500 size_t operator()(
const std::pair<K, std::u32string>& k)
const
502 return KHash()(k.first) ^ (std::hash<std::u32string>()(k.second) * 31);
506 typedef std::unordered_map<std::pair<K, std::u32string>, entry_t, key_hash> table_t;
512 size_t m_max_length = 0;
514 bool empty()
const {
return m_exact.empty() && m_fallback.empty(); }
515 size_t size()
const {
return m_exact.size() + m_fallback.size(); }
518 static const edit_rule_t* find(
const table_t& table,
const K& key,
const std::u32string& affix)
520 const auto it = table.find(std::make_pair(key, affix));
521 return table.end() == it ? nullptr : &it->second.m_rule;
525 edit_rule_t find_prefix(
const K& exact,
const K& fallback,
const std::u32string& low,
size_t max_strip)
const
527 for (
size_t n = std::min(m_prefix.m_max_length, low.size()) + 1; !m_prefix.empty() && n-- > 0; )
529 const std::u32string beginning = low.substr(0, n);
530 for (
const table_t* table : {&m_prefix.m_exact, &m_prefix.m_fallback})
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)
539 return edit_rule_t{};
void write(std::ostream &out) const
The most supported rule of each (UPOS, FEATS, ending), then of each (UPOS, FEATS, beginning); ties go...
void add(const std::string &upos, const std::string &feats, const std::u32string &form, const std::u32string &lemma)
lemm_rules_builder_t(size_t max_suffix=6, size_t max_prefix=0)
Rules ready for lookup, keyed by K, the analyzer's encoding of UPOS(+FEATS) (morph_feats_t in TokenSe...
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,...
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...
const std::string & any_feats()
The feats value of the rule used when no rule matches the exact features.
std::string u32_to_utf8(const std::u32string &src)
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...
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...
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.
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,...
std::vector< std::string > split_tabs(const std::string &line)
Splits on tabs, keeping empty fields (utils::split drops them).
std::u32string to_lower(const std::u32string &src)
Lowercases code point by code point (ICU simple case mapping, any script).
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.
std::u32string utf8_to_u32(const std::string &src)
size_t edit_cost(const affix_rule_t &r)
The length of the edit: characters stripped and added at both ends.
Edit rules for lemmatizing words absent from the lemma dictionary.
A whole word's edit: a prefix rule (never lowercasing) and a suffix rule.
bool operator==(const edit_rule_t &other) const
bool operator<(const edit_rule_t &other) const
Simplest first: fewer characters stripped, then fewer added.
One line of a rules file, as read_rules() hands it over.