Module: Kanji::Translator

Defined in:
lib/kanji/translator.rb,
lib/kanji/translator/version.rb

Defined Under Namespace

Classes: Error, HTTPError, TimeoutError

Constant Summary collapse

USER_AGENT =
"kanji-translator/#{VERSION}".freeze
HOST =
"yomikatawa.com"
ASCII_RE =
/[A-Za-z0-9]/
SPACE_RE =

ASCII whitespace or IDEOGRAPHIC SPACE

/[\s\u3000]/
NON_ALNUM_RE =
/[^a-z0-9]+/
JAPANESE_RE =
/[一-龯々〆ヵヶぁ-ゖゝゞァ-ヴー]/
BOUNDARY =
:__BOUNDARY__
DIGRAPHS =
{
  "きゃ" => "kya", "きゅ" => "kyu", "きぇ" => "kye", "きょ" => "kyo",
  "ぎゃ" => "gya", "ぎゅ" => "gyu", "ぎぇ" => "gye", "ぎょ" => "gyo",
  "しゃ" => "sha", "しゅ" => "shu", "しぇ" => "she", "しょ" => "sho",
  "じゃ" => "ja",  "じゅ" => "ju",  "じぇ" => "je",  "じょ" => "jo",
  "ちゃ" => "cha", "ちゅ" => "chu", "ちぇ" => "che", "ちょ" => "cho",
  "にゃ" => "nya", "にゅ" => "nyu", "にぇ" => "nye", "にょ" => "nyo",
  "ひゃ" => "hya", "ひゅ" => "hyu", "ひぇ" => "hye", "ひょ" => "hyo",
  "びゃ" => "bya", "びゅ" => "byu", "びぇ" => "bye", "びょ" => "byo",
  "ぴゃ" => "pya", "ぴゅ" => "pyu", "ぴぇ" => "pye", "ぴょ" => "pyo",
  "みゃ" => "mya", "みゅ" => "myu", "みぇ" => "mye", "みょ" => "myo",
  "りゃ" => "rya", "りゅ" => "ryu", "りぇ" => "rye", "りょ" => "ryo",
  "ゔぁ" => "va",  "ゔぃ" => "vi",  "ゔぇ" => "ve",  "ゔぉ" => "vo",
  "ふぁ" => "fa",  "ふぃ" => "fi",  "ふぇ" => "fe",  "ふぉ" => "fo"
}.freeze
BASIC =
{
  "あ" => "a",  "い" => "i",  "う" => "u",  "え" => "e",  "お" => "o",
  "か" => "ka", "き" => "ki", "く" => "ku", "け" => "ke", "こ" => "ko",
  "さ" => "sa", "し" => "shi", "す" => "su", "せ" => "se", "そ" => "so",
  "た" => "ta", "ち" => "chi", "つ" => "tsu", "て" => "te", "と" => "to",
  "な" => "na", "に" => "ni", "ぬ" => "nu", "ね" => "ne", "の" => "no",
  "は" => "ha", "ひ" => "hi", "ふ" => "fu", "へ" => "he", "ほ" => "ho",
  "ま" => "ma", "み" => "mi", "む" => "mu", "め" => "me", "も" => "mo",
  "や" => "ya", "ゆ" => "yu", "よ" => "yo",
  "ら" => "ra", "り" => "ri", "る" => "ru", "れ" => "re", "ろ" => "ro",
  "わ" => "wa", "ゐ" => "wi", "ゑ" => "we", "を" => "o",
  "ん" => "n",
  "が" => "ga", "ぎ" => "gi", "ぐ" => "gu", "げ" => "ge", "ご" => "go",
  "ざ" => "za", "じ" => "ji", "ず" => "zu", "ぜ" => "ze", "ぞ" => "zo",
  "だ" => "da", "ぢ" => "ji", "づ" => "zu", "で" => "de", "ど" => "do",
  "ば" => "ba", "び" => "bi", "ぶ" => "bu", "べ" => "be", "ぼ" => "bo",
  "ぱ" => "pa", "ぴ" => "pi", "ぷ" => "pu", "ぺ" => "pe", "ぽ" => "po",
  "ぁ" => "a",  "ぃ" => "i",  "ぅ" => "u",  "ぇ" => "e",  "ぉ" => "o",
  "ゔ" => "vu", "ゎ" => "wa", "ー" => "-"
}.freeze
VERSION =
"1.1.0"

Class Method Summary collapse

Class Method Details

.fetch_page(text, timeout:, retries:, backoff:, user_agent: USER_AGENT) ⇒ Object



62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
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
# File 'lib/kanji/translator.rb', line 62

def self.fetch_page(text, timeout:, retries:, backoff:, user_agent: USER_AGENT)
  encoded = URI.encode_www_form_component(text)
  path = "/kanji/#{encoded}"
  attempt = 0

  begin
    attempt += 1
    http = Net::HTTP.new(HOST, 443)
    http.use_ssl = true
    http.open_timeout = timeout
    http.read_timeout = timeout

    req = Net::HTTP::Get.new(path)
    req["User-Agent"] = user_agent

    resp = http.request(req)

    case resp.code.to_i
    when 200
      resp.body
    when 429
      raise HTTPError, "rate limited: 429"
    when 500..599
      raise HTTPError, "server error: #{resp.code}"
    else
      raise HTTPError, "unexpected response: #{resp.code}"
    end
  rescue Timeout::Error => e
    raise TimeoutError, e.message if attempt > retries + 1

    sleep(backoff_for(attempt, base: backoff))
    retry
  rescue HTTPError => e
    if e.message.include?("429") && attempt <= retries
      # Respect Retry-After if present (best-effort)
      # WebMock tests usually set 0, production may set seconds
      retry_after = 0.0
      sleep(retry_after)
      sleep(backoff_for(attempt, base: backoff))
      retry
    elsif e.message.include?("server error") && attempt <= retries
      sleep(backoff_for(attempt, base: backoff))
      retry
    else
      raise
    end
  end
end

.hiragana_to_romaji(hira) ⇒ Object



165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
# File 'lib/kanji/translator.rb', line 165

def self.hiragana_to_romaji(hira)
  # Handle digraphs first
  s = hira.dup
  DIGRAPHS.each { |k, v| s.gsub!(k, v) }

  result = String.new
  chars = s.chars
  i = 0
  while i < chars.length
    ch = chars[i]
    nx = chars[i + 1]

    # sokuon (small tsu)
    if ch == "っ" && nx
      cons = case nx
             when "c" then "t" # chu -> c but doubled as t (match 'c' + 'h')
             when /^[a-z]/ then nx[0]
             end
      # If next piece already converted (e.g., from digraph), take first consonant of romaji
      if cons.nil?
        # Look ahead: convert nx to romaji to get first consonant
        nx_romaji = BASIC[nx] || nx
        cons = nx_romaji[0]
      end
      result << cons if cons
      i += 1
      next
    end

    if ch == "ー"
      # Prolonged sound mark – skip simple handling
      i += 1
      next
    end

    romaji = BASIC[ch]
    result << (romaji || ch)
    i += 1
  end

  # Simple normalization: "nn" before vowels -> "n" (basic handling)
  result.gsub(/n(?=[aiueoy])/, "n")
end

.parse_hiragana(html) ⇒ Object

Raises:



111
112
113
114
115
116
117
118
# File 'lib/kanji/translator.rb', line 111

def self.parse_hiragana(html)
  doc = Nokogiri::HTML(html)
  cell = doc.at_css("#yomikata tbody tr td")
  text = cell&.inner_text&.strip
  raise Error, "failed to parse reading" if text.nil? || text.empty?

  text
end

.to_hira(text, timeout: 5, retries: 2, backoff: 0.5, user_agent: USER_AGENT) ⇒ Object

Raises:

  • (ArgumentError)


22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
# File 'lib/kanji/translator.rb', line 22

def self.to_hira(text, timeout: 5, retries: 2, backoff: 0.5, user_agent: USER_AGENT)
  raise ArgumentError, "text must be a String" unless text.is_a?(String)

  # Fast-path for kana inputs: avoid network and normalize locally
  if text.match?(/\A[ぁ-ゖーゝゞ]+\z/)
    return text
  elsif text.match?(/\A[ァ-ヴーヽヾヵヶ]+\z/)
    return katakana_to_hiragana(text)
  end

  body = fetch_page(text, timeout: timeout, retries: retries, backoff: backoff, user_agent: user_agent)
  hira = parse_hiragana(body)
  # Ensure result is normalized to hiragana only (remote may mix katakana like 固有名詞)
  katakana_to_hiragana(hira)
end

.to_kata(text) ⇒ Object



38
39
40
41
# File 'lib/kanji/translator.rb', line 38

def self.to_kata(text, **)
  hira = to_hira(text, **)
  hiragana_to_katakana(hira)
end

.to_roma(text) ⇒ Object



43
44
45
46
# File 'lib/kanji/translator.rb', line 43

def self.to_roma(text, **)
  hira = to_hira(text, **)
  hiragana_to_romaji(hira)
end

.to_slug(text, separator: "-", **opts) ⇒ Object



48
49
50
51
52
53
54
55
56
57
58
59
60
# File 'lib/kanji/translator.rb', line 48

def self.to_slug(text, separator: "-", **opts)
  sep       = separator
  downcase  = opts.fetch(:downcase, true)
  collapse  = opts.fetch(:collapse, true)
  net_opts  = slice_opts(opts, :timeout, :retries, :backoff, :user_agent)

  tokens = segment_with_tiny(text)
  raw_parts = tokens.filter_map { |tok| normalize_slug_part(tok, net_opts) }
  parts = merge_ascii_parts(raw_parts)
  s = parts.join(sep)

  normalize_slug_string(s, sep: sep, downcase: downcase, collapse: collapse)
end