yanagi 0.1.0 → 0.3.2

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
checksums.yaml CHANGED
@@ -1,7 +1,7 @@
1
1
  ---
2
2
  SHA256:
3
- metadata.gz: 7d9c51329617c5af3c378c075b472bc750348149a804068ebe4fc83b70b43d43
4
- data.tar.gz: a87fbe968fb608139db4c7cf4d59637fcb52d7e056f52b56d4ac4304798d34d2
3
+ metadata.gz: eb11af4f622e349335c427f97525944cff6c469ae090e4249060148bfed177a5
4
+ data.tar.gz: b1309b9442160572858b4809a86bc2eaaa7adf414613e407b587dd10406dcab8
5
5
  SHA512:
6
- metadata.gz: 56b3ba1f958741308ad2ca52ac55a9965df0df4e101cd8f7af2e1725df4215f2f78081bc56608e7343593126eacd176e5f2b20515639802fd0123460217cf11f
7
- data.tar.gz: 8b21ac53b568ab9a50fc71df6519cab2fcafbd945e4f40406d644b6632b1c99c10e779badbab953260bb16268e7c7eaad91641c4f1d6687764560047b0918408
6
+ metadata.gz: db04edf2c7f7d235aa792218c7630ff0496ff9d4fb20c81dba7e4efb0f37917425e900e91593d0af30fb4ca37f1d2f078caaaa78022d510f424b405a0571960c
7
+ data.tar.gz: fee02b95bc44a2b587766e50a7c892a907c9faa4af26b57396f3df11503ee663fb9378325496258ff2da7e289b39367beb4a6e1df6e50cfef2e34099be9b6c00
data/CHANGELOG.md CHANGED
@@ -5,6 +5,77 @@ All notable changes to this project are documented here.
5
5
  The format is based on [Keep a Changelog](https://keepachangelog.com/en/1.1.0/),
6
6
  and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0.html).
7
7
 
8
+ ## [0.3.2] — 2026-11-09
9
+
10
+ ### Fixed
11
+
12
+ - **Checker: Ukrainian words built on a Japanese one.** A token is now also tried without the
13
+ suffix «-ат» or «-ськ-» and their endings, so «сьогунат» is corrected to «шьоґунат» (将軍) and
14
+ «хіросімського» to «хірошімського». The base keeps its last letter unless it is а or я, so
15
+ «самурайський» stays as it is.
16
+
17
+ ## [0.3.1] — 2026-11-08
18
+
19
+ ### Fixed
20
+
21
+ - **Checker: a light exact match no longer hides a heavier correction.** With a large name list
22
+ (JMnedict) a Polivanov form often spells some rare name exactly in some case: «сусі» is the
23
+ locative of «Суса» (すさ). Such a token now counts as correct only when no heavier anchor spells
24
+ it otherwise, so すし still makes it «суші». A match that needs a case ending weighs 0.9 of a
25
+ bare one.
26
+ - **Key: い after a vowel and ん before a labial.** «суйка», «сусухараі», «каваї» now key like
27
+ yanagi's «суіка», «сусухарай», «кавайі», and «еммей», «шінбун» like «енмей», «шімбун»: gaps
28
+ found by checking Warodai's 45k Polivanov readings that differ from yanagi's.
29
+ - **Exonyms: «Росія»** (ろしあ), so the place name is not read as a Japanese «Рошія».
30
+ - **Checker: a hyphenated Ukrainian word is left alone whole.** «вряди-годи» is in the word list,
31
+ so its parts («годи») are no longer checked on their own.
32
+
33
+ ## [0.3.0] — 2026-11-08
34
+
35
+ ### Added
36
+
37
+ - **`Yanagi::Checker`.** `Checker.new(anchors:, ukrainian:, overrides:)#check(text)`
38
+ returns `Finding(start, stop, token, suggestion, kind, confidence, source)`
39
+ for Japanese words spelled against the policy, with character offsets.
40
+ `kind` is `override`, `dictionary` (an anchor matched by spelling key) or
41
+ `rule` (forbidden sequences plus Japanese markers, all substituted at once,
42
+ low confidence). Case endings and letter case are kept: «Хіросіму» →
43
+ «Хірошіму», «ХІРОСІМОЮ» → «ХІРОШІМОЮ». Words in the Ukrainian list are left
44
+ alone, and «ті» becomes «чі» only when an anchor confirms it.
45
+ - `Yanagi::Checker::MemoryAnchors` (rows, or `[kana, kanji]` pairs rendered with
46
+ `Yanagi.cyrillic`) and `Yanagi::Checker::WordSet`. Any object with
47
+ `lookup(key)` / `include?(word)` can stand in; the gem ships no data.
48
+ - `yanagi check FILE [--anchors x.yml] [--ukrainian words.txt] [--overrides x.yml] [--format json|human]`.
49
+ - **`Yanagi::Key.call(text)`**, the spelling-neutral key from Jibiki's search
50
+ (`Jibiki::Search::CyrillicKey`), with folds taken from the `forbidden:`
51
+ lists in `data/mora.yml` (дзі/зі→джі, тсу→цу, ху→фу, ё→ьо, …).
52
+ - **`Yanagi::Inflection`**: `split(token)` into stem + case ending candidates,
53
+ `bases(stem, ending)` for dictionary forms, and `rejoin(canonical, ending, case_of:)`.
54
+ - A RuboCop config, with a todo file for the existing code.
55
+
56
+ ## [0.2.0] — 2026-11-07
57
+
58
+ ### Added
59
+
60
+ - **`Yanagi.kana(romaji, script: :hiragana | :katakana)`.** Public romaji→kana
61
+ conversion for search input. Accepts Hepburn, Kunrei and wapuro spellings
62
+ (shi/si, chi/ti, tsu/tu, fu/hu, ji/zi/di, sha/sya, cha/tya, ja/zya/jya),
63
+ `n` before consonants, `n'`, `nn` and final `n` as ん, double consonants and
64
+ `tch` as っ, `m` before b/p/m as ん, and long vowels (`ou`, `oo`, `ō`, `â`).
65
+ Katakana output renders macrons, doubled vowels and `-` as ー. Input is
66
+ case-insensitive and trimmed. Returns `nil` when the input is not romaji.
67
+
68
+ ### Changed
69
+
70
+ - `Yanagi::Cyrillic.romaji_to_hiragana` delegates to `Yanagi::Kana`, so Mode A
71
+ romaji input now understands Kunrei and wapuro spellings too. Input that
72
+ cannot convert is still returned lowercased.
73
+
74
+ ### Fixed
75
+
76
+ - ジェ / じぇ and イェ / いぇ romanize as `je` and `ye` (they came out as `jiぇ`
77
+ and `iぇ`) and transliterate as «дже» and «є».
78
+
8
79
  ## [0.1.0] — 2026-08-29
9
80
 
10
81
  First release. Yanagi (柳) turns the Japanese→Ukrainian transliteration policy
@@ -47,4 +118,6 @@ reaching print.
47
118
  the engine was extracted from its predecessor without behaviour change.
48
119
  - Zero runtime dependencies; stdlib only.
49
120
 
121
+ [0.3.0]: https://github.com/shogi-dojo/yanagi/releases/tag/v0.3.0
122
+ [0.2.0]: https://github.com/shogi-dojo/yanagi/releases/tag/v0.2.0
50
123
  [0.1.0]: https://github.com/shogi-dojo/yanagi/releases/tag/v0.1.0
data/README.md CHANGED
@@ -11,6 +11,7 @@ Deterministic Japanese → Ukrainian transliteration and policy enforcement gem.
11
11
  - **Tier 1**: AUTOFIX-eligible (matches lexicon entry via forbidden Polivanov/anglicism substitution).
12
12
  - **Tier 2**: High-confidence report for unknown Japanese terms (contains JP markers, unanchored in lexicon/allowlist).
13
13
  - **Tier 3**: Polivanov markers check (off by default).
14
+ - **Checker**: Finds Japanese words in Ukrainian text spelled against the policy (Polivanov, Russian ё, case endings included) and suggests the canonical form, anchored by a dictionary you supply.
14
15
  - **Policy Synchronization (`DocSync`)**: Asserts agreement between markdown policy documents (`shared/transliteration.md`) and executable YAML rules.
15
16
 
16
17
  ## Corpus data
@@ -76,6 +77,25 @@ Yanagi.from_romaji("shuusai")
76
77
  # => "шюсай"
77
78
  ```
78
79
 
80
+ ### Romaji to kana (search input)
81
+
82
+ ```ruby
83
+ Yanagi.kana("Tōkyō") # => "とうきょう"
84
+ Yanagi.kana("kon'nichiha") # => "こんにちは"
85
+ Yanagi.kana("shimbun") # => "しんぶん"
86
+ Yanagi.kana("kitte") # => "きって"
87
+ Yanagi.kana("ra-men", script: :katakana) # => "ラーメン"
88
+ Yanagi.kana("taberu日本") # => nil (not romaji)
89
+ ```
90
+
91
+ Hepburn, Kunrei and wapuro spellings are all accepted (`shi`/`si`, `chi`/`ti`,
92
+ `tsu`/`tu`, `fu`/`hu`, `ji`/`zi`, `sha`/`sya`, `ja`/`zya`/`jya`). Case and
93
+ surrounding whitespace are ignored. `nn` before a vowel is read as ん plus the
94
+ n-row kana (`konnichi` → こんにち); type `nnn` or `n'` to force ん + vowel.
95
+ `di`/`du` give ぢ/づ, so callers matching a dictionary may want to fold them to
96
+ じ/ず. In katakana, `ō`, `â`, doubled vowels and `-` give ー, while `ou` stays
97
+ オウ. Anything that is not plain romaji returns `nil`.
98
+
79
99
  ### Mode B: Prose Audit & Correction
80
100
 
81
101
  ```ruby
@@ -86,6 +106,48 @@ findings = Yanagi.audit(["path/to/chapter.org"], tier2: true, tier3: false)
86
106
  Yanagi::Audit.apply("audit/findings.yml")
87
107
  ```
88
108
 
109
+ ### Checker
110
+
111
+ `Yanagi::Checker` finds Japanese words in Ukrainian prose that break the
112
+ policy and suggests the canonical spelling with the case ending and letter case
113
+ kept: «сьочю» → «шьочю», «Хіросіму» → «Хірошіму», «Мейдзі» → «Мейджі».
114
+
115
+ ```ruby
116
+ anchors = Yanagi::Checker::MemoryAnchors.from_pairs(
117
+ [%w[しょうちゅう 焼酎], %w[ひろしま 広島], %w[めいじ 明治]], origin: "jmdict"
118
+ )
119
+ words = Yanagi::Checker::WordSet.load("uk_words.txt")
120
+ checker = Yanagi::Checker.new(anchors: anchors, ukrainian: words, overrides: { "токіо" => "Токіо" })
121
+
122
+ checker.check("Ми пили сьочю в Хіросімі.")
123
+ # => [#<struct Finding start=8, stop=13, token="сьочю", suggestion="шьочю",
124
+ # kind=:dictionary, confidence=0.9, source={kana: "しょうちゅう", kanji: "焼酎", origin: "jmdict"}>,
125
+ # #<struct Finding start=16, stop=24, token="Хіросімі", suggestion="Хірошімі", ...>]
126
+ ```
127
+
128
+ `start` and `stop` are character offsets (`text[start...stop] == token`). Each
129
+ Cyrillic token (letters, inner apostrophes and hyphens) is checked in order:
130
+
131
+ 1. **`override`** — `overrides` (`{ wrong => right }`) match the token exactly or
132
+ as stem + case ending, and win over everything else.
133
+ 2. Words in the **Ukrainian word list** are skipped («сьогодні», «сім», «тісто»).
134
+ 3. **`dictionary`** — every stem + ending split (`Yanagi::Inflection.split`) is
135
+ looked up by its spelling key (`Yanagi::Key`). A canonical spelling means
136
+ the token is correct; otherwise the heaviest anchor is suggested.
137
+ 4. **`rule`** — a token with forbidden sequences *and* Japanese markers gets
138
+ every forbidden sequence substituted at once, at low confidence.
139
+
140
+ The gem ships no word lists or dictionaries. Anchors are any object with
141
+ `lookup(key) → [{ cyrillic:, kana:, kanji:, origin:, weight: }]`, and the
142
+ word list any object with `include?(lower_case_word)`; `MemoryAnchors` and
143
+ `WordSet` are simple in-memory ones. Build anchors from JMdict / JMnedict
144
+ readings with `MemoryAnchors.from_pairs`, which renders each with
145
+ `Yanagi.cyrillic`.
146
+
147
+ `Yanagi::Key.call(text)` is the spelling-neutral key on its own, for search
148
+ indexes: «Фудзі», «фуджі» and «ФУДЖІ» share one. Its folds come from the
149
+ `forbidden:` lists in `data/mora.yml`; «ті» stays, since yanagi writes ティ so.
150
+
89
151
  ### Policy Agreement Check
90
152
 
91
153
  ```ruby
@@ -109,6 +171,10 @@ yanagi audit books/meijin/translation/ua --out audit/findings.yml
109
171
  # Applying approved findings
110
172
  yanagi apply audit/findings.yml
111
173
 
174
+ # Checking a text against your own anchors and word list (exit 1 on findings)
175
+ yanagi check chapter.md --anchors anchors.yml --ukrainian uk_words.txt
176
+ yanagi check chapter.md --overrides overrides.yml --format json
177
+
112
178
  # Document synchronization & gold verification
113
179
  yanagi doc-sync shared/transliteration.md
114
180
  yanagi verify-gold
data/data/exonyms.yml CHANGED
@@ -12,3 +12,7 @@
12
12
  romaji: "osaka"
13
13
  cyrillic: "Осака"
14
14
  note: "Standard Ukrainian geographical exonym"
15
+ ろしあ:
16
+ romaji: "roshia"
17
+ cyrillic: "Росія"
18
+ note: "Ukrainian exonym for Russia; keeps «Росія» from being read as a Japanese «Рошія»"
data/data/mora.yml CHANGED
@@ -708,6 +708,16 @@
708
708
  cyrillic: "це"
709
709
  onset: "ts"
710
710
  nucleus: "e"
711
+ じぇ:
712
+ romaji: "je"
713
+ cyrillic: "дже"
714
+ onset: "j"
715
+ nucleus: "e"
716
+ いぇ:
717
+ romaji: "ye"
718
+ cyrillic: "є"
719
+ onset: "y"
720
+ nucleus: "e"
711
721
  ふぁ:
712
722
  romaji: "fa"
713
723
  cyrillic: "фа"
@@ -0,0 +1,70 @@
1
+ # frozen_string_literal: true
2
+
3
+ require "optparse"
4
+ require "json"
5
+ require "yaml"
6
+ require_relative "checker"
7
+
8
+ module Yanagi
9
+ # `yanagi check FILE [--anchors x.yml] [--ukrainian words.txt]
10
+ # [--overrides x.yml] [--format human|json]`. #run returns the exit status:
11
+ # 1 when there are findings.
12
+ class CheckCommand
13
+ USAGE = "Usage: yanagi check <file> [--anchors <anchors.yml>] [--ukrainian <words.txt>] " \
14
+ "[--overrides <overrides.yml>] [--format json|human]"
15
+
16
+ def initialize(args)
17
+ @args = args.dup
18
+ @options = { format: "human" }
19
+ end
20
+
21
+ def run
22
+ path = parser.parse!(@args).first
23
+ unless path && File.file?(path)
24
+ warn USAGE
25
+ return 1
26
+ end
27
+
28
+ text = File.read(path, encoding: "UTF-8")
29
+ findings = checker.check(text)
30
+ @options[:format] == "json" ? print_json(findings) : print_human(path, text, findings)
31
+ findings.empty? ? 0 : 1
32
+ end
33
+
34
+ private
35
+
36
+ def parser
37
+ OptionParser.new do |opts|
38
+ opts.on("--anchors FILE", "YAML anchors: rows or [kana, kanji] pairs") { |v| @options[:anchors] = v }
39
+ opts.on("--ukrainian FILE", "Ukrainian word list, one word per line") { |v| @options[:ukrainian] = v }
40
+ opts.on("--overrides FILE", "YAML map of wrong => right spellings") { |v| @options[:overrides] = v }
41
+ opts.on("--format FORMAT", %w[human json], "Output format (human or json)") { |v| @options[:format] = v }
42
+ end
43
+ end
44
+
45
+ def checker
46
+ Checker.new(
47
+ anchors: load(:anchors) { |path| Checker::MemoryAnchors.load(path) } || Checker::MemoryAnchors.new,
48
+ ukrainian: load(:ukrainian) { |path| Checker::WordSet.load(path) } || Checker::WordSet.new,
49
+ overrides: load(:overrides) { |path| YAML.safe_load_file(path) } || {}
50
+ )
51
+ end
52
+
53
+ def load(option)
54
+ path = @options[option]
55
+ yield path if path
56
+ end
57
+
58
+ def print_json(findings)
59
+ puts JSON.pretty_generate(findings.map(&:to_h))
60
+ end
61
+
62
+ def print_human(path, text, findings)
63
+ findings.each do |f|
64
+ line = text[0...f.start].count("\n") + 1
65
+ col = f.start - (f.start.zero? ? -1 : text.rindex("\n", f.start - 1) || -1)
66
+ puts "#{path}:#{line}:#{col}: #{f.token} -> #{f.suggestion} (#{f.kind}, #{f.confidence})"
67
+ end
68
+ end
69
+ end
70
+ end
@@ -0,0 +1,59 @@
1
+ # frozen_string_literal: true
2
+
3
+ require "yaml"
4
+ require_relative "../key"
5
+
6
+ module Yanagi
7
+ class Checker
8
+ # Dictionary anchors held in memory and indexed by Yanagi::Key. Rows are
9
+ # { cyrillic:, kana:, kanji:, origin:, weight: }; build them from
10
+ # dictionary [kana, kanji] pairs with .from_pairs, which renders each
11
+ # reading with Yanagi.cyrillic. The gem ships no anchors: callers bring
12
+ # their own (JMdict, JMnedict, a glossary).
13
+ class MemoryAnchors
14
+ FIELDS = %i[cyrillic kana kanji origin weight].freeze
15
+
16
+ def self.from_pairs(pairs, origin: nil, weight: 1)
17
+ new(pairs.map { |kana, kanji| pair_row(kana, kanji, origin: origin, weight: weight) })
18
+ end
19
+
20
+ # A YAML list whose items are rows (hashes) or [kana, kanji] pairs. A row
21
+ # without «cyrillic» is rendered from its kana.
22
+ def self.load(path)
23
+ items = YAML.safe_load_file(path, symbolize_names: true) || []
24
+ new(items.map { |item| item.is_a?(Array) ? pair_row(*item) : item })
25
+ end
26
+
27
+ def self.pair_row(kana, kanji = nil, origin: nil, weight: 1)
28
+ { kana: kana, kanji: kanji, origin: origin, weight: weight }
29
+ end
30
+
31
+ def initialize(rows = [])
32
+ @index = Hash.new { |hash, key| hash[key] = [] }
33
+ rows.each { |row| add(row) }
34
+ @index.default_proc = nil
35
+ @index.each_value(&:freeze)
36
+ @index.freeze
37
+ end
38
+
39
+ def lookup(key)
40
+ @index.fetch(key, [])
41
+ end
42
+
43
+ def size
44
+ @index.each_value.sum(&:size)
45
+ end
46
+
47
+ private
48
+
49
+ def add(row)
50
+ row = row.transform_keys(&:to_sym).slice(*FIELDS)
51
+ row[:cyrillic] ||= Yanagi.cyrillic(row[:kana].to_s, kanji: row[:kanji]).text
52
+ row[:weight] ||= 1
53
+ return if row[:cyrillic].to_s.empty?
54
+
55
+ @index[Key.call(row[:cyrillic])] << row.freeze
56
+ end
57
+ end
58
+ end
59
+ end
@@ -0,0 +1,33 @@
1
+ # frozen_string_literal: true
2
+
3
+ require "set"
4
+
5
+ module Yanagi
6
+ class Checker
7
+ # A plain Ukrainian word list: one word per line, «#» starts a comment.
8
+ # Lookups ignore case and the apostrophe variant.
9
+ class WordSet
10
+ APOSTROPHES = /['ʼ’`]/
11
+
12
+ def self.load(path)
13
+ new(File.foreach(path, encoding: "UTF-8").map { |line| line.sub(/#.*/, "").strip }.reject(&:empty?))
14
+ end
15
+
16
+ def self.normalize(word)
17
+ word.downcase.gsub(APOSTROPHES, "'")
18
+ end
19
+
20
+ def initialize(words = [])
21
+ @words = words.to_set { |word| self.class.normalize(word) }.freeze
22
+ end
23
+
24
+ def include?(word)
25
+ @words.include?(self.class.normalize(word))
26
+ end
27
+
28
+ def size
29
+ @words.size
30
+ end
31
+ end
32
+ end
33
+ end
@@ -0,0 +1,170 @@
1
+ # frozen_string_literal: true
2
+
3
+ require_relative "key"
4
+ require_relative "inflection"
5
+ require_relative "checker/word_set"
6
+ require_relative "checker/memory_anchors"
7
+
8
+ module Yanagi
9
+ # Finds Japanese words in Ukrainian text that break the transliteration
10
+ # policy and suggests the canonical spelling, ending and case kept:
11
+ # «Хіросіму» → «Хірошіму», «сьочю» → «шьочю».
12
+ #
13
+ # checker = Yanagi::Checker.new(anchors: anchors, ukrainian: words)
14
+ # checker.check(text) # => [Finding, ...]
15
+ #
16
+ # Each Cyrillic token goes through, in order:
17
+ # 1. +overrides+ ({ wrong => right }), exact or stem + ending;
18
+ # 2. the +ukrainian+ word list (#include?, lower case): such words are skipped;
19
+ # 3. the +anchors+ (#lookup(Key) → rows), via every stem + ending split:
20
+ # a canonical spelling means the token is correct, otherwise the
21
+ # heaviest row wins;
22
+ # 4. a +rule+ finding when the token holds forbidden sequences and Japanese
23
+ # markers: every forbidden sequence is substituted at once.
24
+ class Checker
25
+ Finding = Struct.new(:start, :stop, :token, :suggestion, :kind, :confidence, :source, keyword_init: true)
26
+
27
+ # Letters, apostrophes inside a word, and inner hyphens.
28
+ TOKEN = /\p{Cyrillic}+(?:['ʼ’]\p{Cyrillic}+)*(?:-\p{Cyrillic}+(?:['ʼ’]\p{Cyrillic}+)*)*/
29
+
30
+ CONFIDENCE = { override: 1.0, dictionary: 0.9, rule: 0.3 }.freeze
31
+
32
+ # How much a dictionary match that needs a case ending counts against a bare one.
33
+ INFLECTED = 0.9
34
+
35
+ # Sequences that only the Japanese rows produce. Unlike Audit::JP_MARKERS
36
+ # this leaves out C + я/ю/ьо (ня, ря, ньо), which are everyday Ukrainian.
37
+ MARKERS = %w[
38
+ ші чі джі ґ дза дзу дзе дзо
39
+ шя шю шьо чя чю чьо джя джю джьо
40
+ дзі дзя дзю дзьо тсу ё
41
+ ].freeze
42
+ MARKER_PATTERN = Regexp.union(MARKERS)
43
+
44
+ def initialize(anchors: MemoryAnchors.new, ukrainian: WordSet.new, overrides: {})
45
+ @anchors = anchors
46
+ @ukrainian = ukrainian
47
+ @overrides = overrides.to_h { |wrong, right| [wrong.to_s.downcase, right.to_s] }
48
+ end
49
+
50
+ def check(text)
51
+ findings = []
52
+ text.scan(TOKEN) do
53
+ match = Regexp.last_match
54
+ findings.concat(check_token(match[0], match.begin(0)))
55
+ end
56
+ findings
57
+ end
58
+
59
+ private
60
+
61
+ # A hyphenated token is checked whole first; unless an override or the
62
+ # dictionary knows it whole, its parts win over a rule guess.
63
+ def check_token(token, start)
64
+ return [] if token.include?("-") && @ukrainian.include?(token.downcase) && !@overrides.key?(token.downcase)
65
+
66
+ whole = check_word(token, start)
67
+ return [whole].compact if !token.include?("-") || (whole && whole.kind != :rule)
68
+
69
+ parts = check_parts(token, start)
70
+ parts.empty? ? [whole].compact : parts
71
+ end
72
+
73
+ def check_parts(token, start)
74
+ offset = start
75
+ token.split("-").filter_map do |part|
76
+ found = check_word(part, offset)
77
+ offset += part.length + 1
78
+ found
79
+ end
80
+ end
81
+
82
+ def check_word(token, start)
83
+ return if token.length < 2
84
+
85
+ forms = Inflection.split(token)
86
+ found = override(token, forms)
87
+ return finding(token, start, *found) if found
88
+ return if @ukrainian.include?(token.downcase)
89
+
90
+ found = dictionary(token, forms)
91
+ return if found == :correct
92
+
93
+ found ||= rule(token)
94
+ finding(token, start, *found) if found
95
+ end
96
+
97
+ def finding(token, start, suggestion, kind, source)
98
+ return if suggestion == token
99
+
100
+ Finding.new(start: start, stop: start + token.length, token: token, suggestion: suggestion,
101
+ kind: kind, confidence: CONFIDENCE.fetch(kind), source: source)
102
+ end
103
+
104
+ def override(token, forms)
105
+ each_base(forms) do |base, ending|
106
+ right = @overrides[base.downcase]
107
+ next unless right
108
+
109
+ return [Inflection.rejoin(right, ending, case_of: token), :override, source_of(origin: "override")]
110
+ end
111
+ nil
112
+ end
113
+
114
+ # A token spelled exactly like an anchor is correct, unless a heavier anchor spells it
115
+ # otherwise: «сусі» is the locative of a rare name «Суса» (すさ), but the common word すし
116
+ # makes it «суші». A match that needs an ending weighs a little less than a bare one.
117
+ def dictionary(token, forms)
118
+ hits = dictionary_hits(token, forms)
119
+ return if hits.empty?
120
+
121
+ same, other = hits.partition { |_, word, _| word.downcase == token.downcase }
122
+ return :correct if other.empty?
123
+
124
+ row, word, weight = other.each_with_index.max_by { |(_, _, hit_weight), index| [hit_weight, -index] }.first
125
+ return :correct if same.any? { |_, _, same_weight| same_weight >= weight }
126
+
127
+ [word, :dictionary, source_of(**row.slice(:kana, :kanji, :origin))]
128
+ end
129
+
130
+ # [row, the token respelled by it, weight] for every anchor of every stem + ending split.
131
+ def dictionary_hits(token, forms)
132
+ hits = []
133
+ each_base(forms) do |base, ending|
134
+ lookup_keys(base).each do |key|
135
+ @anchors.lookup(key).each do |row|
136
+ weight = row[:weight].to_f * (ending.empty? ? 1.0 : INFLECTED)
137
+ hits << [row, Inflection.rejoin(row[:cyrillic], ending, case_of: token), weight]
138
+ end
139
+ end
140
+ end
141
+ hits
142
+ end
143
+
144
+ def rule(token)
145
+ lower = token.downcase
146
+ return unless Key.forbidden?(lower) && MARKER_PATTERN.match?(lower)
147
+
148
+ [Inflection.apply_case(Key.respell(lower), like: token), :rule, source_of(origin: "rule")]
149
+ end
150
+
151
+ def each_base(forms)
152
+ forms.each do |stem, ending|
153
+ Inflection.bases(stem, ending).each { |base| yield base, ending }
154
+ end
155
+ end
156
+
157
+ # The key leaves «ті» alone, since yanagi writes ティ so; an anchor may
158
+ # still confirm that it stands for ち.
159
+ def lookup_keys(base)
160
+ lower = base.downcase
161
+ keys = [Key.call(lower)]
162
+ keys << Key.call(lower.gsub("ті", "чі")) if lower.include?("ті")
163
+ keys.uniq
164
+ end
165
+
166
+ def source_of(kana: nil, kanji: nil, origin: nil)
167
+ { kana: kana, kanji: kanji, origin: origin }
168
+ end
169
+ end
170
+ end
data/lib/yanagi/cli.rb CHANGED
@@ -4,6 +4,7 @@ require "optparse"
4
4
  require "json"
5
5
  require "yaml"
6
6
  require_relative "../yanagi"
7
+ require_relative "check_command"
7
8
 
8
9
  module Yanagi
9
10
  class CLI
@@ -29,6 +30,8 @@ module Yanagi
29
30
  cmd_audit
30
31
  when "apply"
31
32
  cmd_apply
33
+ when "check"
34
+ exit CheckCommand.new(@args).run
32
35
  when "doc-sync", "doc_sync"
33
36
  cmd_doc_sync
34
37
  when "lexicon"
@@ -333,6 +336,7 @@ module Yanagi
333
336
  yanagi cyrillic <kana> [--format json|human] [--kanji <kanji>]
334
337
  yanagi audit <paths...> [--tier2] [--tier3] [--format json|human|yaml] [--out <file>]
335
338
  yanagi apply <findings.yml>
339
+ yanagi check <file> [--anchors <anchors.yml>] [--ukrainian <words.txt>] [--overrides <overrides.yml>] [--format json|human]
336
340
  yanagi doc-sync [path/to/transliteration.md]
337
341
  yanagi lexicon build --glossary <glossary.org> [--out <file>]
338
342
  yanagi lexicon merge <proposal.yml> [--out <file>]
@@ -3,6 +3,7 @@
3
3
  require_relative "normalize"
4
4
  require_relative "rules"
5
5
  require_relative "mora"
6
+ require_relative "kana"
6
7
 
7
8
  module Yanagi
8
9
  Result = Struct.new(:text, :source, :confidence, :notes, keyword_init: true) do
@@ -52,7 +53,7 @@ module Yanagi
52
53
  E_COLUMN = %w[
53
54
  え け せ て ね へ め れ ゑ
54
55
  げ ぜ で べ ぺ
55
- しぇ ちぇ つぇ ふぇ うぇ ゔぇ
56
+ しぇ ちぇ つぇ じぇ いぇ ふぇ うぇ ゔぇ
56
57
  ].freeze
57
58
 
58
59
  I_COLUMN = %w[
@@ -243,60 +244,12 @@ module Yanagi
243
244
  text.start_with?("п", "б")
244
245
  end
245
246
 
246
- # Simple romaji to hiragana conversion for Mode A romaji input
247
+ # Romaji to hiragana for Mode A romaji input. Delegates to Yanagi::Kana, which
248
+ # accepts Hepburn, Kunrei and wapuro spellings. Unlike Yanagi.kana it never
249
+ # returns nil: input Kana cannot convert is returned lowercased and
250
+ # unchanged, as before.
247
251
  def self.romaji_to_hiragana(str)
248
- norm = str.downcase.gsub("'", "'")
249
- mora_map = Rules.mora_map
250
-
251
- # Build inverted map from romaji -> hiragana kana
252
- @romaji_to_hira_table ||= begin
253
- table = {}
254
- mora_map.each do |kana_sym, data|
255
- rom = data[:romaji]&.to_s
256
- table[rom] = kana_sym.to_s if rom
257
- end
258
- # Sort by romaji length descending to match longest substrings first
259
- table.sort_by { |k, _v| -k.length }.to_h
260
- end
261
-
262
- res = []
263
- i = 0
264
- len = norm.length
265
- while i < len
266
- matched = false
267
-
268
- # Check sokuon in romaji (e.g. kk, pp, tt, ss, tch, ssh, etc.)
269
- c = norm[i]
270
- c_next = norm[i + 1]
271
- c3 = norm[i, 3]
272
-
273
- if c3 == "tch"
274
- res << "っ"
275
- i += 1
276
- next
277
- elsif c == c_next && c =~ /[bcdfghjklmpqrstvwxyz]/ && c != "n"
278
- res << "っ"
279
- i += 1
280
- next
281
- end
282
-
283
- # Match table
284
- @romaji_to_hira_table.each do |rom, kana|
285
- if norm[i..].start_with?(rom)
286
- res << kana
287
- i += rom.length
288
- matched = true
289
- break
290
- end
291
- end
292
-
293
- unless matched
294
- res << norm[i]
295
- i += 1
296
- end
297
- end
298
-
299
- res.join
252
+ Kana.convert(str) || str.to_s.downcase
300
253
  end
301
254
  end
302
255
 
@@ -0,0 +1,83 @@
1
+ # frozen_string_literal: true
2
+
3
+ module Yanagi
4
+ # Ukrainian case endings on Japanese loanwords: «Хірошіму», «Хірошімою»,
5
+ # «ніхону». The checker looks words up by their dictionary form, so a token
6
+ # is split into stem and ending, and the canonical form gets the ending back.
7
+ module Inflection
8
+ # Longest first, so «ами» is tried before «и».
9
+ ENDINGS = %w[
10
+ ами ями ові еві
11
+ ою ею єю ам ям ах ях ом ем ів
12
+ и і ї у ю а я
13
+ ].sort_by { |ending| -ending.length }.freeze
14
+
15
+ # Ukrainian words built on a Japanese one: «сьогунат», «сьогунату», «хіросімський». The
16
+ # suffix with each ending it takes; the base keeps its last letter unless that is а or я
17
+ # (Хірошім-а → хірошім-ський, but самурай → самурай-ський).
18
+ DERIVED = {
19
+ "ат" => %w[ами ам ах ом ів а у і и],
20
+ "ськ" => %w[ими ого ому ий им ім их ої ій ою а е і у]
21
+ }.freeze
22
+ DERIVED_ENDINGS = DERIVED.flat_map { |suffix, tails| [suffix, *tails.map { |tail| suffix + tail }] }
23
+ .reject { |ending| ending == "ськ" }
24
+ .sort_by { |ending| -ending.length }.freeze
25
+ DERIVED_THEME_LETTERS = %w[а я].freeze
26
+
27
+ # The shortest stem worth looking up.
28
+ MIN_STEM_LENGTH = 3
29
+
30
+ # Final letters a declined word loses before its ending: Хірошім-а → Хірошім-у,
31
+ # самура-й → самура-ю.
32
+ THEME_LETTERS = %w[а я й].freeze
33
+
34
+ module_function
35
+
36
+ # [stem, ending] candidates for +token+, the bare token first. The stem
37
+ # keeps the token's own case.
38
+ def split(token)
39
+ lower = token.downcase
40
+ candidates = [[token, ""]]
41
+ (ENDINGS + DERIVED_ENDINGS).each do |ending|
42
+ next unless lower.end_with?(ending) && lower.length - ending.length >= MIN_STEM_LENGTH
43
+
44
+ candidates << [token[0...(token.length - ending.length)], token[(token.length - ending.length)..]]
45
+ end
46
+ candidates
47
+ end
48
+
49
+ # Dictionary forms a +stem+ may come from: itself, or with the theme letter
50
+ # its ending replaced. A bare token is its own dictionary form.
51
+ def bases(stem, ending)
52
+ return [stem] if ending.empty?
53
+ return [stem] + DERIVED_THEME_LETTERS.map { |letter| stem + letter } if derived?(ending)
54
+
55
+ [stem] + THEME_LETTERS.map { |letter| stem + letter }
56
+ end
57
+
58
+ # +canonical+ with +ending+ in place of its theme letter, in the case of
59
+ # +case_of+ (Title, UPPER or lower).
60
+ def rejoin(canonical, ending, case_of:)
61
+ word = canonical
62
+ unless ending.empty?
63
+ theme = derived?(ending) ? DERIVED_THEME_LETTERS : THEME_LETTERS
64
+ word = word[0...-1] if theme.include?(word[-1]&.downcase)
65
+ word += ending.downcase
66
+ end
67
+ apply_case(word, like: case_of)
68
+ end
69
+
70
+ def derived?(ending) = DERIVED_ENDINGS.include?(ending.downcase)
71
+
72
+ def apply_case(word, like:)
73
+ letters = like.scan(/\p{L}/).join
74
+ if letters.length > 1 && letters == letters.upcase
75
+ word.upcase
76
+ elsif letters[0] && letters[0] == letters[0].upcase
77
+ word.downcase.sub(/\p{L}/, &:upcase)
78
+ else
79
+ word.downcase
80
+ end
81
+ end
82
+ end
83
+ end
@@ -0,0 +1,220 @@
1
+ # frozen_string_literal: true
2
+
3
+ module Yanagi
4
+ # Romaji (Hepburn, Kunrei-shiki and wapuro/IME spellings) to kana, meant for
5
+ # search input. Pure and table-driven; independent of the transliteration
6
+ # rules so that accepting more spellings never changes generated output.
7
+ module Kana
8
+ VOWELS = %w[a i u e o].freeze
9
+
10
+ def self.build_table
11
+ t = {}
12
+ add = lambda do |kana, *romaji|
13
+ romaji.each { |r| t[r] = kana }
14
+ end
15
+
16
+ %w[あ a い i う u え e お o].each_slice(2) { |k, r| add.call(k, r) }
17
+ [
18
+ ["k", %w[か き く け こ]], ["g", %w[が ぎ ぐ げ ご]],
19
+ ["s", %w[さ し す せ そ]], ["z", %w[ざ じ ず ぜ ぞ]],
20
+ ["t", %w[た ち つ て と]], ["d", %w[だ ぢ づ で ど]],
21
+ ["n", %w[な に ぬ ね の]], ["h", %w[は ひ ふ へ ほ]],
22
+ ["b", %w[ば び ぶ べ ぼ]], ["p", %w[ぱ ぴ ぷ ぺ ぽ]],
23
+ ["m", %w[ま み む め も]], ["r", %w[ら り る れ ろ]]
24
+ ].each do |c, kanas|
25
+ VOWELS.each_with_index { |v, i| add.call(kanas[i], "#{c}#{v}") }
26
+ end
27
+ add.call("や", "ya")
28
+ add.call("ゆ", "yu")
29
+ add.call("よ", "yo")
30
+ add.call("いぇ", "ye")
31
+ add.call("わ", "wa")
32
+ add.call("を", "wo")
33
+ add.call("うぃ", "wi")
34
+ add.call("うぇ", "we")
35
+ add.call("ゐ", "wyi")
36
+ add.call("ゑ", "wye")
37
+
38
+ # Alternative spellings of the base syllables.
39
+ add.call("し", "shi")
40
+ add.call("ち", "chi")
41
+ add.call("つ", "tsu")
42
+ add.call("ふ", "fu")
43
+ add.call("じ", "ji")
44
+
45
+ # Digraphs: consonant + small ya/yu/yo.
46
+ {
47
+ "き" => %w[ky], "ぎ" => %w[gy], "し" => %w[sy sh], "じ" => %w[zy j jy],
48
+ "ち" => %w[ty ch cy], "ぢ" => %w[dy], "に" => %w[ny], "ひ" => %w[hy],
49
+ "び" => %w[by], "ぴ" => %w[py], "み" => %w[my], "り" => %w[ry]
50
+ }.each do |base, prefixes|
51
+ prefixes.each do |pre|
52
+ { "a" => "ゃ", "u" => "ゅ", "o" => "ょ" }.each do |v, small|
53
+ add.call("#{base}#{small}", "#{pre}#{v}")
54
+ end
55
+ end
56
+ end
57
+ # (sha/shu/sho, cha/chu/cho and ja/ju/jo come from the bare prefixes
58
+ # above.) The e-row and foreign sounds follow.
59
+ add.call("しぇ", "she", "sye")
60
+ add.call("ちぇ", "che", "tye")
61
+ add.call("じぇ", "je", "zye", "jye")
62
+ add.call("きぇ", "kye")
63
+ add.call("にぇ", "nye")
64
+ add.call("ひぇ", "hye")
65
+
66
+ add.call("ふぁ", "fa")
67
+ add.call("ふぃ", "fi")
68
+ add.call("ふぇ", "fe")
69
+ add.call("ふぉ", "fo")
70
+ add.call("ふゅ", "fyu")
71
+ add.call("ふ", "hu")
72
+ add.call("ゔぁ", "va")
73
+ add.call("ゔぃ", "vi")
74
+ add.call("ゔ", "vu")
75
+ add.call("ゔぇ", "ve")
76
+ add.call("ゔぉ", "vo")
77
+ add.call("つぁ", "tsa")
78
+ add.call("つぃ", "tsi")
79
+ add.call("つぇ", "tse")
80
+ add.call("つぉ", "tso")
81
+ add.call("づ", "dzu")
82
+ add.call("てぃ", "thi")
83
+ add.call("てゅ", "thu")
84
+ add.call("でぃ", "dhi")
85
+ add.call("でゅ", "dhu")
86
+ add.call("とぅ", "twu")
87
+ add.call("どぅ", "dwu")
88
+ add.call("くぁ", "kwa")
89
+ add.call("ぐぁ", "gwa")
90
+
91
+ # Explicit small kana (IME style).
92
+ %w[a i u e o].zip(%w[ぁ ぃ ぅ ぇ ぉ]).each do |v, k|
93
+ add.call(k, "x#{v}", "l#{v}")
94
+ end
95
+ add.call("ゃ", "xya", "lya")
96
+ add.call("ゅ", "xyu", "lyu")
97
+ add.call("ょ", "xyo", "lyo")
98
+ add.call("っ", "xtu", "ltu", "xtsu", "ltsu")
99
+ add.call("ゎ", "xwa", "lwa")
100
+
101
+ t.freeze
102
+ end
103
+
104
+ TABLE = build_table
105
+ MAX_KEY = TABLE.keys.map(&:length).max
106
+ CONSONANT_CHARS = /[bcdfghjklmpqrstvwxyz]/
107
+ # Characters allowed through the tokenizer untouched.
108
+ LONG_MARK = "ー"
109
+ MARKER = "̄"
110
+
111
+ SCRIPTS = %i[hiragana katakana].freeze
112
+
113
+ module_function
114
+
115
+ # Returns kana for +input+, or nil when it is not romaji.
116
+ def convert(input, script: :hiragana)
117
+ raise ArgumentError, "unknown script: #{script.inspect}" unless SCRIPTS.include?(script)
118
+ return nil unless input.is_a?(String)
119
+
120
+ s = normalize(input, script)
121
+ return nil if s.nil? || s.empty?
122
+
123
+ hira = tokenize(s)
124
+ return nil if hira.nil? || hira.strip.empty?
125
+
126
+ script == :katakana ? to_katakana(hira) : hira
127
+ end
128
+
129
+ def normalize(input, script)
130
+ s = input.unicode_normalize(:nfkc).strip.downcase
131
+ s = s.gsub(/[‘’ʼ`´]/, "'").gsub(/[‐-―−ー]/, "-")
132
+ s = s.unicode_normalize(:nfd).gsub(/[̂̄]/, MARKER)
133
+ return nil unless s.match?(/\A[a-z'\- ̄]+\z/)
134
+
135
+ # Long vowels: macron/circumflex always, doubled vowels in katakana.
136
+ if script == :katakana
137
+ s = s.gsub(/([aiueo])#{MARKER}/, '\1-').gsub(/([aiueo])\1/, '\1-')
138
+ else
139
+ s = s.gsub(/o#{MARKER}/, "ou").gsub(/([aiue])#{MARKER}/, '\1\1')
140
+ end
141
+ return nil if s.include?(MARKER)
142
+
143
+ s.gsub(/\s+/, " ")
144
+ end
145
+
146
+ def tokenize(s)
147
+ out = +""
148
+ i = 0
149
+ n = s.length
150
+ while i < n
151
+ c = s[i]
152
+ nxt = s[i + 1]
153
+
154
+ if c == " "
155
+ out << " "
156
+ i += 1
157
+ elsif c == "-"
158
+ return nil if out.empty? || out.end_with?(" ")
159
+
160
+ out << LONG_MARK
161
+ i += 1
162
+ elsif c == "'"
163
+ return nil
164
+ elsif c == "n"
165
+ if nxt == "'"
166
+ out << "ん"
167
+ i += 2
168
+ elsif nxt == "n"
169
+ after = s[i + 2]
170
+ if after && (VOWELS.include?(after) || after == "y")
171
+ out << "ん"
172
+ i += 1
173
+ else
174
+ out << "ん"
175
+ i += 2
176
+ end
177
+ elsif nxt.nil? || !(VOWELS.include?(nxt) || nxt == "y")
178
+ out << "ん"
179
+ i += 1
180
+ else
181
+ i = take(s, i, out) or return nil
182
+ end
183
+ elsif c == "m" && nxt && "bpm".include?(nxt)
184
+ out << "ん"
185
+ i += 1
186
+ elsif c == "t" && s[i, 3] == "tch"
187
+ out << "っ"
188
+ i += 1
189
+ elsif nxt == c && c.match?(CONSONANT_CHARS)
190
+ out << "っ"
191
+ i += 1
192
+ else
193
+ i = take(s, i, out) or return nil
194
+ end
195
+ end
196
+ out
197
+ end
198
+
199
+ def take(s, i, out)
200
+ MAX_KEY.downto(1) do |len|
201
+ kana = TABLE[s[i, len]]
202
+ next unless kana && s[i, len].length == len
203
+
204
+ out << kana
205
+ return i + len
206
+ end
207
+ nil
208
+ end
209
+
210
+ def to_katakana(hira)
211
+ hira.gsub(/[ぁ-ゖ]/) { |ch| (ch.ord + 0x60).chr(Encoding::UTF_8) }
212
+ end
213
+ end
214
+
215
+ # Convert romaji (Hepburn, Kunrei or wapuro) to kana. Returns nil if the
216
+ # input is not romaji. See README for details.
217
+ def self.kana(romaji, script: :hiragana)
218
+ Kana.convert(romaji, script: script)
219
+ end
220
+ end
data/lib/yanagi/key.rb ADDED
@@ -0,0 +1,84 @@
1
+ # frozen_string_literal: true
2
+
3
+ require_relative "rules"
4
+
5
+ module Yanagi
6
+ # A spelling-neutral key for Ukrainian renderings of Japanese words, so one
7
+ # word matches however it is spelled. yanagi writes ちゃ «чя», しょ «шьо»,
8
+ # じ «джі», が «ґа», and keeps long vowels and most doubled consonants
9
+ # single; people also type «ча», «шо», the Polivanov «сусі» and «Фудзі»,
10
+ # «г» for «ґ», «кітте» and «ніппон». Both sides of a comparison go through
11
+ # #call.
12
+ #
13
+ # The folds come from the `forbidden:` lists in data/mora.yml, so the key and
14
+ # the policy cannot drift apart. Only folds that cannot merge two different
15
+ # yanagi spellings are made: «ті» stays, since yanagi writes ティ that way.
16
+ module Key
17
+ # Forbidden sequences that are also correct yanagi output.
18
+ AMBIGUOUS = %w[ті].freeze
19
+
20
+ # Ukrainian spelling writes а / у / е / о after ж, ч, ш, щ, where yanagi
21
+ # keeps я / ю / є / ьо.
22
+ HUSHED = { "я" => "а", "ю" => "у", "є" => "е", "ьо" => "о" }.freeze
23
+ HUSHED_PATTERN = /([жчшщ])(ьо|я|ю|є)/
24
+ APOSTROPHES = "'ʼ’`"
25
+
26
+ # い after a vowel: yanagi writes «ай», «суі»; people also write «аі», «суй», «аї». The key
27
+ # reads them all as vowel + «і».
28
+ VOWEL_I = /(?<=[аеиоуяюєі])(?:йі|ї|й(?![аеиоуяюєії]))/
29
+
30
+ # ん before б, п, м: yanagi writes «м» only before п and б («шімбун», «енмей»); Polivanov
31
+ # also has «еммей». The key reads «м» before a labial as «н».
32
+ LABIAL_N = /м(?=[бпм])/
33
+
34
+ module_function
35
+
36
+ # The key: lower case, no apostrophes, forbidden spellings folded to the
37
+ # canonical ones, ґ read as г, hushed vowels plain, い after a vowel as «і»,
38
+ # «м» before a labial as «н», doubled letters single.
39
+ def call(text)
40
+ key = respell(text.downcase.delete(APOSTROPHES)).tr("ґ", "г")
41
+ key = key.gsub(HUSHED_PATTERN) { "#{Regexp.last_match(1)}#{HUSHED.fetch(Regexp.last_match(2))}" }
42
+ key.gsub(VOWEL_I, "і").gsub(LABIAL_N, "н").squeeze
43
+ end
44
+
45
+ # Replaces every forbidden sequence in a lower-case +text+ with its
46
+ # canonical spelling in one pass, so «сіндзюку» becomes «шінджюку».
47
+ def respell(text)
48
+ text.gsub(fold_pattern) { |seq| folds.fetch(seq) }
49
+ end
50
+
51
+ # True when lower-case +text+ holds any forbidden sequence.
52
+ def forbidden?(text)
53
+ fold_pattern.match?(text)
54
+ end
55
+
56
+ # { forbidden => canonical } from data/mora.yml.
57
+ def folds
58
+ @folds ||= Rules.mora_map.each_value.with_object({}) do |data, map|
59
+ canonical = data[:cyrillic].to_s
60
+ Array(data[:forbidden]).each do |seq|
61
+ seq = seq.to_s
62
+ next if seq.empty? || AMBIGUOUS.include?(seq)
63
+
64
+ map[seq] ||= canonical
65
+ end
66
+ end.freeze
67
+ end
68
+
69
+ # Longest sequences first. A forbidden sequence that ends the canonical
70
+ # one («за» in «дза») only counts when it is not already part of it.
71
+ def fold_pattern
72
+ @fold_pattern ||= Regexp.union(
73
+ folds.keys.sort_by { |seq| [-seq.length, seq] }.map do |seq|
74
+ prefix = folds[seq].delete_suffix(seq)
75
+ if prefix != folds[seq] && !prefix.empty?
76
+ /(?<!#{Regexp.escape(prefix)})#{Regexp.escape(seq)}/
77
+ else
78
+ /#{Regexp.escape(seq)}/
79
+ end
80
+ end
81
+ )
82
+ end
83
+ end
84
+ end
@@ -1,5 +1,5 @@
1
1
  # frozen_string_literal: true
2
2
 
3
3
  module Yanagi
4
- VERSION = "0.1.0"
4
+ VERSION = "0.3.2"
5
5
  end
data/lib/yanagi.rb CHANGED
@@ -5,10 +5,14 @@ require_relative "yanagi/normalize"
5
5
  require_relative "yanagi/rules"
6
6
  require_relative "yanagi/mora"
7
7
  require_relative "yanagi/romaji"
8
+ require_relative "yanagi/kana"
8
9
  require_relative "yanagi/cyrillic"
10
+ require_relative "yanagi/key"
11
+ require_relative "yanagi/inflection"
9
12
  require_relative "yanagi/doc_sync"
10
13
  require_relative "yanagi/lexicon"
11
14
  require_relative "yanagi/audit"
15
+ require_relative "yanagi/checker"
12
16
 
13
17
  module Yanagi
14
18
  class Error < StandardError; end
data/yanagi.gemspec CHANGED
@@ -31,4 +31,5 @@ Gem::Specification.new do |spec|
31
31
 
32
32
  spec.add_development_dependency "minitest", ">= 5.16"
33
33
  spec.add_development_dependency "rake", "~> 13.0"
34
+ spec.add_development_dependency "rubocop", "~> 1.92"
34
35
  end
metadata CHANGED
@@ -1,94 +1,122 @@
1
1
  --- !ruby/object:Gem::Specification
2
2
  name: yanagi
3
3
  version: !ruby/object:Gem::Version
4
- version: 0.1.0
4
+ version: 0.3.2
5
5
  platform: ruby
6
6
  authors:
7
- - shogi-dojo
7
+ - shogi-dojo
8
8
  bindir: exe
9
9
  cert_chain: []
10
10
  date: 1980-01-02 00:00:00.000000000 Z
11
11
  dependencies:
12
- - !ruby/object:Gem::Dependency
13
- name: minitest
14
- requirement: !ruby/object:Gem::Requirement
15
- requirements:
16
- - - ">="
17
- - !ruby/object:Gem::Version
18
- version: '5.16'
19
- type: :development
20
- prerelease: false
21
- version_requirements: !ruby/object:Gem::Requirement
22
- requirements:
23
- - - ">="
24
- - !ruby/object:Gem::Version
25
- version: '5.16'
26
- - !ruby/object:Gem::Dependency
27
- name: rake
28
- requirement: !ruby/object:Gem::Requirement
29
- requirements:
30
- - - "~>"
31
- - !ruby/object:Gem::Version
32
- version: '13.0'
33
- type: :development
34
- prerelease: false
35
- version_requirements: !ruby/object:Gem::Requirement
36
- requirements:
37
- - - "~>"
38
- - !ruby/object:Gem::Version
39
- version: '13.0'
40
- description: Zero-dependency Japanese to Ukrainian transliteration and policy enforcement
41
- gem.
12
+ - !ruby/object:Gem::Dependency
13
+ name: minitest
14
+ requirement: !ruby/object:Gem::Requirement
15
+ requirements:
16
+ -
17
+ - ">="
18
+ - !ruby/object:Gem::Version
19
+ version: "5.16"
20
+ type: :development
21
+ prerelease: false
22
+ version_requirements: !ruby/object:Gem::Requirement
23
+ requirements:
24
+ -
25
+ - ">="
26
+ - !ruby/object:Gem::Version
27
+ version: "5.16"
28
+ - !ruby/object:Gem::Dependency
29
+ name: rake
30
+ requirement: !ruby/object:Gem::Requirement
31
+ requirements:
32
+ -
33
+ - ~>
34
+ - !ruby/object:Gem::Version
35
+ version: "13.0"
36
+ type: :development
37
+ prerelease: false
38
+ version_requirements: !ruby/object:Gem::Requirement
39
+ requirements:
40
+ -
41
+ - ~>
42
+ - !ruby/object:Gem::Version
43
+ version: "13.0"
44
+ - !ruby/object:Gem::Dependency
45
+ name: rubocop
46
+ requirement: !ruby/object:Gem::Requirement
47
+ requirements:
48
+ -
49
+ - ~>
50
+ - !ruby/object:Gem::Version
51
+ version: "1.92"
52
+ type: :development
53
+ prerelease: false
54
+ version_requirements: !ruby/object:Gem::Requirement
55
+ requirements:
56
+ -
57
+ - ~>
58
+ - !ruby/object:Gem::Version
59
+ version: "1.92"
60
+ description: Zero-dependency Japanese to Ukrainian transliteration and policy enforcement gem.
42
61
  email:
43
- - play@shogi-dojo.com
62
+ - play@shogi-dojo.com
44
63
  executables:
45
- - yanagi
64
+ - yanagi
46
65
  extensions: []
47
66
  extra_rdoc_files: []
48
67
  files:
49
- - CHANGELOG.md
50
- - LICENSE
51
- - README.md
52
- - data/combinatorial.yml
53
- - data/exceptions.yml
54
- - data/exonyms.yml
55
- - data/mora.yml
56
- - exe/yanagi
57
- - lib/yanagi.rb
58
- - lib/yanagi/audit.rb
59
- - lib/yanagi/cli.rb
60
- - lib/yanagi/cyrillic.rb
61
- - lib/yanagi/doc_sync.rb
62
- - lib/yanagi/lexicon.rb
63
- - lib/yanagi/mora.rb
64
- - lib/yanagi/normalize.rb
65
- - lib/yanagi/romaji.rb
66
- - lib/yanagi/rules.rb
67
- - lib/yanagi/version.rb
68
- - yanagi.gemspec
69
- homepage: https://github.com/shogi-dojo/yanagi
68
+ - CHANGELOG.md
69
+ - LICENSE
70
+ - README.md
71
+ - data/combinatorial.yml
72
+ - data/exceptions.yml
73
+ - data/exonyms.yml
74
+ - data/mora.yml
75
+ - exe/yanagi
76
+ - lib/yanagi.rb
77
+ - lib/yanagi/audit.rb
78
+ - lib/yanagi/check_command.rb
79
+ - lib/yanagi/checker.rb
80
+ - lib/yanagi/checker/memory_anchors.rb
81
+ - lib/yanagi/checker/word_set.rb
82
+ - lib/yanagi/cli.rb
83
+ - lib/yanagi/cyrillic.rb
84
+ - lib/yanagi/doc_sync.rb
85
+ - lib/yanagi/inflection.rb
86
+ - lib/yanagi/kana.rb
87
+ - lib/yanagi/key.rb
88
+ - lib/yanagi/lexicon.rb
89
+ - lib/yanagi/mora.rb
90
+ - lib/yanagi/normalize.rb
91
+ - lib/yanagi/romaji.rb
92
+ - lib/yanagi/rules.rb
93
+ - lib/yanagi/version.rb
94
+ - yanagi.gemspec
95
+ homepage: "https://github.com/shogi-dojo/yanagi"
70
96
  licenses:
71
- - MIT
97
+ - MIT
72
98
  metadata:
73
- homepage_uri: https://github.com/shogi-dojo/yanagi
74
- source_code_uri: https://github.com/shogi-dojo/yanagi/tree/main
75
- bug_tracker_uri: https://github.com/shogi-dojo/yanagi/issues
76
- changelog_uri: https://github.com/shogi-dojo/yanagi/blob/main/CHANGELOG.md
99
+ homepage_uri: "https://github.com/shogi-dojo/yanagi"
100
+ source_code_uri: "https://github.com/shogi-dojo/yanagi/tree/main"
101
+ bug_tracker_uri: "https://github.com/shogi-dojo/yanagi/issues"
102
+ changelog_uri: "https://github.com/shogi-dojo/yanagi/blob/main/CHANGELOG.md"
77
103
  rdoc_options: []
78
104
  require_paths:
79
- - lib
105
+ - lib
80
106
  required_ruby_version: !ruby/object:Gem::Requirement
81
107
  requirements:
82
- - - ">="
83
- - !ruby/object:Gem::Version
84
- version: 3.0.0
108
+ -
109
+ - ">="
110
+ - !ruby/object:Gem::Version
111
+ version: 3.0.0
85
112
  required_rubygems_version: !ruby/object:Gem::Requirement
86
113
  requirements:
87
- - - ">="
88
- - !ruby/object:Gem::Version
89
- version: '0'
114
+ -
115
+ - ">="
116
+ - !ruby/object:Gem::Version
117
+ version: "0"
90
118
  requirements: []
91
- rubygems_version: 4.0.16
119
+ rubygems_version: 4.1.0
92
120
  specification_version: 4
93
121
  summary: Deterministic Japanese to Ukrainian transliteration engine
94
122
  test_files: []