Module: Yanagi::Lexicon

Defined in:
lib/yanagi/lexicon.rb

Constant Summary collapse

UKRAINIAN_SUFFIXES =
%w[
  ами ями ах ях ів їв ою ею єю
  ом ем єм
  а е и і о у ю я ї й
].freeze
MIN_STEM_LENGTH =
4
NON_JP_NOTE_MARKERS =

Terms of non-Japanese origin (Chinese works, place names) are transliterated by their own language's conventions, so Japanese mora rules must not apply. Detected from the glossary note column, which states the provenance.

[
  "Китай", "китайськ", "конфуціанськ", "Даоськ", "даоськ", "Янцзи"
].freeze

Class Method Summary collapse

Class Method Details

.build_from_glossary(glossary_path, out_path: nil) ⇒ Object



36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
# File 'lib/yanagi/lexicon.rb', line 36

def self.build_from_glossary(glossary_path, out_path: nil)
  content = File.read(glossary_path, encoding: "UTF-8")
  lexicon = {}

  content.each_line do |line|
    next unless line.start_with?("|")
    parts = line.split("|").map(&:strip).reject(&:empty?)
    next if parts.empty? || parts[0].start_with?("-") || parts[0] =~ /Японське/i

    col0 = parts[0]
    col1 = parts[1]
    col2 = parts[2]

    kanji = nil
    reading = nil
    if col0 =~ /^(.+?)\s*\((.+?)\)$/
      kanji = Regexp.last_match(1).strip
      reading = Regexp.last_match(2).strip
    else
      kanji = col0.strip
      reading = nil
    end

    uk_clean = col1.gsub(/^[«"'\`]|["'\`»]$/, "").strip
    key = kanji.gsub(/^[«"'\`]|["'\`»]$/, "").strip
    next if key.empty?

    cyr = reading || uk_clean

    lexicon[key] = {
      "kanji" => kanji,
      "reading" => reading,
      "cyrillic" => cyr,
      "ukrainian" => col1,
      "note" => col2,
      "origin" => detect_origin(col2)
    }
  end

  out_file = out_path || Rules.path_for("lexicon.yml")
  File.write(out_file, YAML.dump(lexicon))
  reload!
  Rules.reload!
  lexicon
end

.detect_origin(note) ⇒ Object



29
30
31
32
33
34
# File 'lib/yanagi/lexicon.rb', line 29

def self.detect_origin(note)
  text = note.to_s
  return "zh" if NON_JP_NOTE_MARKERS.any? { |m| text.include?(m) }

  "ja"
end

.exact_indexObject



150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
# File 'lib/yanagi/lexicon.rb', line 150

def self.exact_index
  @exact_index ||= begin
    idx = {}
    load_entries.each do |k, entry|
      cyr = (entry[:cyrillic] || entry["cyrillic"])&.to_s&.downcase
      next unless cyr

      # Index full term
      idx[cyr] = { key: k.to_s, entry: entry, stem: cyr, suffix: "", exact: true }

      # Also index individual words of multi-word phrases (e.g. 'хонінбо', 'шюсай')
      words = cyr.split(/[\s-]+/).map(&:strip).reject(&:empty?)
      if words.length > 1
        words.each do |w|
          idx[w] ||= { key: k.to_s, entry: entry, stem: w, suffix: "", exact: true } if w.length >= MIN_STEM_LENGTH
        end
      end
    end
    idx
  end
end

.find_by_stem(token) ⇒ Object



190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
# File 'lib/yanagi/lexicon.rb', line 190

def self.find_by_stem(token)
  clean = token.downcase.gsub(/^[«"'\`\(\[\{]|["'\`\)\]\}\.,;:!?—–]+$/, "")
  return exact_index[clean] if exact_index.key?(clean)

  stem, suffix = strip_inflection(clean)
  return nil if stem.length < MIN_STEM_LENGTH

  if stem_index.key?(stem)
    info = stem_index[stem]
    return {
      key: info[:key],
      entry: info[:entry],
      stem: stem,
      suffix: suffix,
      exact: false
    }
  end

  nil
end

.load_entriesObject



18
19
20
# File 'lib/yanagi/lexicon.rb', line 18

def self.load_entries
  Rules.lexicon || {}
end

.merge_proposal(proposal_path, out_path: nil) ⇒ Object



82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
# File 'lib/yanagi/lexicon.rb', line 82

def self.merge_proposal(proposal_path, out_path: nil)
  proposals = YAML.safe_load_file(proposal_path, permitted_classes: [Symbol, Date], symbolize_names: true) || []
  proposals = [proposals] unless proposals.is_a?(Array)

  current_lexicon = Rules.lexicon ? Rules.lexicon.transform_keys(&:to_s) : {}
  new_lexicon = current_lexicon.dup

  errors = []

  proposals.each do |prop|
    status = prop[:status]&.to_s
    unless status == "accepted"
      errors << "Proposal #{prop[:term] || prop[:kanji]} status is '#{status}', must be 'accepted' to merge"
      next
    end

    kanji = prop[:kanji]&.to_s
    reading = prop[:reading]&.to_s
    cyrillic = prop[:cyrillic]&.to_s

    if reading && !reading.empty? && cyrillic && !cyrillic.empty?
      derived_cyr = Yanagi.cyrillic(reading).text
      if derived_cyr != cyrillic && prop[:override] != true
        errors << "Proposal #{kanji || reading} Cyrillic '#{cyrillic}' does not match engine derived '#{derived_cyr}'"
        next
      end
    end

    key = (kanji && !kanji.empty?) ? kanji : cyrillic
    new_lexicon[key] = {
      "kanji" => kanji,
      "reading" => reading,
      "cyrillic" => cyrillic,
      "ukrainian" => prop[:ukrainian] || cyrillic,
      "note" => prop[:note]
    }
  end

  unless errors.empty?
    raise Error, "Cannot merge proposals:\n- #{errors.join("\n- ")}"
  end

  out_file = out_path || Rules.path_for("lexicon.yml")
  File.write(out_file, YAML.dump(new_lexicon))
  reload!
  Rules.reload!
  new_lexicon
end

.reload!Object



145
146
147
148
# File 'lib/yanagi/lexicon.rb', line 145

def self.reload!
  @exact_index = nil
  @stem_index = nil
end

.stem_indexObject



172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
# File 'lib/yanagi/lexicon.rb', line 172

def self.stem_index
  @stem_index ||= begin
    idx = {}
    load_entries.each do |k, entry|
      cyr = (entry[:cyrillic] || entry["cyrillic"])&.to_s&.downcase
      next unless cyr

      words = cyr.split(/[\s-]+/).map(&:strip).reject(&:empty?)
      words.each do |w|
        stem, _ = strip_inflection(w)
        idx[stem] ||= { key: k.to_s, entry: entry, stem: stem } if stem.length >= MIN_STEM_LENGTH
        idx[w] ||= { key: k.to_s, entry: entry, stem: w } if w.length >= MIN_STEM_LENGTH
      end
    end
    idx
  end
end

.strip_inflection(token) ⇒ Object



131
132
133
134
135
136
137
138
139
140
141
142
143
# File 'lib/yanagi/lexicon.rb', line 131

def self.strip_inflection(token)
  w = token.downcase.gsub(/^[«"'\`\(\[\{]|["'\`\)\]\}\.,;:!?—–]+$/, "")
  return [w, ""] if w.length <= MIN_STEM_LENGTH

  UKRAINIAN_SUFFIXES.each do |suffix|
    if w.end_with?(suffix) && (w.length - suffix.length) >= MIN_STEM_LENGTH
      stem = w[0...(w.length - suffix.length)]
      return [stem, suffix]
    end
  end

  [w, ""]
end