kabosu 0.6.10-x86_64-linux

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 ADDED
@@ -0,0 +1,7 @@
1
+ ---
2
+ SHA256:
3
+ metadata.gz: 6f21c38458d6bddfff0ef24e7cc1bc9b67d0287e07e1203f801dc33cbef51b1c
4
+ data.tar.gz: 8e69d59ac135972c9c0acd1cb655cd061e0cda2da1fb011b207116b3e3b9c6df
5
+ SHA512:
6
+ metadata.gz: 2e57b175eb9f95ac253172f85cd9853cfcf45a3035477c7b838c74106de641de5966c536e6fe911a029aa927545036aa0fdc70af97fb21dad304b70691ee7e46
7
+ data.tar.gz: 652a6ebfc1c5265781bdff2365c29dfa1276c14203a7b997cafcacda8ee9c1508e3dd995ceb4b022d163173f0f43dd18b45f478e88cc6bad26f9c210c808297c
data/LICENSE ADDED
@@ -0,0 +1,191 @@
1
+
2
+ Apache License
3
+ Version 2.0, January 2004
4
+ http://www.apache.org/licenses/
5
+
6
+ TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
7
+
8
+ 1. Definitions.
9
+
10
+ "License" shall mean the terms and conditions for use, reproduction,
11
+ and distribution as defined by Sections 1 through 9 of this document.
12
+
13
+ "Licensor" shall mean the copyright owner or entity authorized by
14
+ the copyright owner that is granting the License.
15
+
16
+ "Legal Entity" shall mean the union of the acting entity and all
17
+ other entities that control, are controlled by, or are under common
18
+ control with that entity. For the purposes of this definition,
19
+ "control" means (i) the power, direct or indirect, to cause the
20
+ direction or management of such entity, whether by contract or
21
+ otherwise, or (ii) ownership of fifty percent (50%) or more of the
22
+ outstanding shares, or (iii) beneficial ownership of such entity.
23
+
24
+ "You" (or "Your") shall mean an individual or Legal Entity
25
+ exercising permissions granted by this License.
26
+
27
+ "Source" form shall mean the preferred form for making modifications,
28
+ including but not limited to software source code, documentation
29
+ source, and configuration files.
30
+
31
+ "Object" form shall mean any form resulting from mechanical
32
+ transformation or translation of a Source form, including but
33
+ not limited to compiled object code, generated documentation,
34
+ and conversions to other media types.
35
+
36
+ "Work" shall mean the work of authorship, whether in Source or
37
+ Object form, made available under the License, as indicated by a
38
+ copyright notice that is included in or attached to the work
39
+ (an example is provided in the Appendix below).
40
+
41
+ "Derivative Works" shall mean any work, whether in Source or Object
42
+ form, that is based on (or derived from) the Work and for which the
43
+ editorial revisions, annotations, elaborations, or other modifications
44
+ represent, as a whole, an original work of authorship. For the purposes
45
+ of this License, Derivative Works shall not include works that remain
46
+ separable from, or merely link (or bind by name) to the interfaces of,
47
+ the Work and Derivative Works thereof.
48
+
49
+ "Contribution" shall mean any work of authorship, including
50
+ the original version of the Work and any modifications or additions
51
+ to that Work or Derivative Works thereof, that is intentionally
52
+ submitted to the Licensor for inclusion in the Work by the copyright owner
53
+ or by an individual or Legal Entity authorized to submit on behalf of
54
+ the copyright owner. For the purposes of this definition, "submitted"
55
+ means any form of electronic, verbal, or written communication sent
56
+ to the Licensor or its representatives, including but not limited to
57
+ communication on electronic mailing lists, source code control systems,
58
+ and issue tracking systems that are managed by, or on behalf of, the
59
+ Licensor for the purpose of discussing and improving the Work, but
60
+ excluding communication that is conspicuously marked or otherwise
61
+ designated in writing by the copyright owner as "Not a Contribution."
62
+
63
+ "Contributor" shall mean Licensor and any individual or Legal Entity
64
+ on behalf of whom a Contribution has been received by the Licensor and
65
+ subsequently incorporated within the Work.
66
+
67
+ 2. Grant of Copyright License. Subject to the terms and conditions of
68
+ this License, each Contributor hereby grants to You a perpetual,
69
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
70
+ copyright license to reproduce, prepare Derivative Works of,
71
+ publicly display, publicly perform, sublicense, and distribute the
72
+ Work and such Derivative Works in Source or Object form.
73
+
74
+ 3. Grant of Patent License. Subject to the terms and conditions of
75
+ this License, each Contributor hereby grants to You a perpetual,
76
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
77
+ (except as stated in this section) patent license to make, have made,
78
+ use, offer to sell, sell, import, and otherwise transfer the Work,
79
+ where such license applies only to those patent claims licensable
80
+ by such Contributor that are necessarily infringed by their
81
+ Contribution(s) alone or by combination of their Contribution(s)
82
+ with the Work to which such Contribution(s) was submitted. If You
83
+ institute patent litigation against any entity (including a
84
+ cross-claim or counterclaim in a lawsuit) alleging that the Work
85
+ or a Contribution incorporated within the Work constitutes direct
86
+ or contributory patent infringement, then any patent licenses
87
+ granted to You under this License for that Work shall terminate
88
+ as of the date such litigation is filed.
89
+
90
+ 4. Redistribution. You may reproduce and distribute copies of the
91
+ Work or Derivative Works thereof in any medium, with or without
92
+ modifications, and in Source or Object form, provided that You
93
+ meet the following conditions:
94
+
95
+ (a) You must give any other recipients of the Work or
96
+ Derivative Works a copy of this License; and
97
+
98
+ (b) You must cause any modified files to carry prominent notices
99
+ stating that You changed the files; and
100
+
101
+ (c) You must retain, in the Source form of any Derivative Works
102
+ that You distribute, all copyright, patent, trademark, and
103
+ attribution notices from the Source form of the Work,
104
+ excluding those notices that do not pertain to any part of
105
+ the Derivative Works; and
106
+
107
+ (d) If the Work includes a "NOTICE" text file as part of its
108
+ distribution, then any Derivative Works that You distribute must
109
+ include a readable copy of the attribution notices contained
110
+ within such NOTICE file, excluding any notices that do not
111
+ pertain to any part of the Derivative Works, in at least one
112
+ of the following places: within a NOTICE text file distributed
113
+ as part of the Derivative Works; within the Source form or
114
+ documentation, if provided along with the Derivative Works; or,
115
+ within a display generated by the Derivative Works, if and
116
+ wherever such third-party notices normally appear. The contents
117
+ of the NOTICE file are for informational purposes only and
118
+ do not modify the License. You may add Your own attribution
119
+ notices within Derivative Works that You distribute, alongside
120
+ or as an addendum to the NOTICE text from the Work, provided
121
+ that such additional attribution notices cannot be construed
122
+ as modifying the License.
123
+
124
+ You may add Your own copyright statement to Your modifications and
125
+ may provide additional or different license terms and conditions
126
+ for use, reproduction, or distribution of Your modifications, or
127
+ for any such Derivative Works as a whole, provided Your use,
128
+ reproduction, and distribution of the Work otherwise complies with
129
+ the conditions stated in this License.
130
+
131
+ 5. Submission of Contributions. Unless You explicitly state otherwise,
132
+ any Contribution intentionally submitted for inclusion in the Work
133
+ by You to the Licensor shall be under the terms and conditions of
134
+ this License, without any additional terms or conditions.
135
+ Notwithstanding the above, nothing herein shall supersede or modify
136
+ the terms of any separate license agreement you may have executed
137
+ with Licensor regarding such Contributions.
138
+
139
+ 6. Trademarks. This License does not grant permission to use the trade
140
+ names, trademarks, service marks, or product names of the Licensor,
141
+ except as required for reasonable and customary use in describing the
142
+ origin of the Work and reproducing the content of the NOTICE file.
143
+
144
+ 7. Disclaimer of Warranty. Unless required by applicable law or
145
+ agreed to in writing, Licensor provides the Work (and each
146
+ Contributor provides its Contributions) on an "AS IS" BASIS,
147
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
148
+ implied, including, without limitation, any warranties or conditions
149
+ of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
150
+ PARTICULAR PURPOSE. You are solely responsible for determining the
151
+ appropriateness of using or redistributing the Work and assume any
152
+ risks associated with Your exercise of permissions under this License.
153
+
154
+ 8. Limitation of Liability. In no event and under no legal theory,
155
+ whether in tort (including negligence), contract, or otherwise,
156
+ unless required by applicable law (such as deliberate and grossly
157
+ negligent acts) or agreed to in writing, shall any Contributor be
158
+ liable to You for damages, including any direct, indirect, special,
159
+ incidental, or consequential damages of any character arising as a
160
+ result of this License or out of the use or inability to use the
161
+ Work (including but not limited to damages for loss of goodwill,
162
+ work stoppage, computer failure or malfunction, or any and all
163
+ other commercial damages or losses), even if such Contributor
164
+ has been advised of the possibility of such damages.
165
+
166
+ 9. Accepting Warranty or Additional Liability. While redistributing
167
+ the Work or Derivative Works thereof, You may choose to offer,
168
+ and charge a fee for, acceptance of support, warranty, indemnity,
169
+ or other liability obligations and/or rights consistent with this
170
+ License. However, in accepting such obligations, You may act only
171
+ on Your own behalf and on Your sole responsibility, not on behalf
172
+ of any other Contributor, and only if You agree to indemnify,
173
+ defend, and hold each Contributor harmless for any liability
174
+ incurred by, or claims asserted against, such Contributor by reason
175
+ of your accepting any such warranty or additional liability.
176
+
177
+ END OF TERMS AND CONDITIONS
178
+
179
+ Copyright 2025 davafons
180
+
181
+ Licensed under the Apache License, Version 2.0 (the "License");
182
+ you may not use this file except in compliance with the License.
183
+ You may obtain a copy of the License at
184
+
185
+ http://www.apache.org/licenses/LICENSE-2.0
186
+
187
+ Unless required by applicable law or agreed to in writing, software
188
+ distributed under the License is distributed on an "AS IS" BASIS,
189
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
190
+ See the License for the specific language governing permissions and
191
+ limitations under the License.
data/README.md ADDED
@@ -0,0 +1,205 @@
1
+ <p align="center">
2
+ <img src="logo.png" alt="Kabosu" width="150">
3
+ </p>
4
+
5
+ <h1 align="center">Kabosu</h1>
6
+
7
+ <p align="center">
8
+ <a href="https://rubygems.org/gems/kabosu"><img src="https://img.shields.io/gem/v/kabosu" alt="Gem Version"></a>
9
+ <a href="https://github.com/davafons/kabosu/actions/workflows/edge.yml"><img src="https://github.com/davafons/kabosu/actions/workflows/edge.yml/badge.svg" alt="CI"></a>
10
+ <a href="https://github.com/davafons/kabosu/blob/main/LICENSE"><img src="https://img.shields.io/github/license/davafons/kabosu" alt="License"></a>
11
+ <a href="https://rubygems.org/gems/kabosu"><img src="https://img.shields.io/gem/dt/kabosu" alt="Downloads"></a>
12
+ </p>
13
+
14
+ Ruby bindings for [sudachi.rs](https://github.com/WorksApplications/sudachi.rs), a Rust implementation of the [Sudachi](https://github.com/WorksApplications/Sudachi) Japanese morphological analyzer.
15
+
16
+ ## Usage
17
+
18
+ ```ruby
19
+ require "kabosu"
20
+
21
+ # Explicit dictionary + tokenizer lifecycle
22
+ dict = Kabosu::Dictionary.new(system_dict: Kabosu::Dictionary.path)
23
+ tokenizer = dict.create(mode: :c)
24
+
25
+ # Tokenize Japanese text
26
+ morphemes = Kabosu.tokenize("東京都に住んでいる", tokenizer: tokenizer)
27
+
28
+ # Bulk accessors for quick extraction
29
+ morphemes.surfaces # => ["東京都", "に", "住ん", "で", "いる"]
30
+ morphemes.readings # => ["トウキョウト", "ニ", "スン", "デ", "イル"]
31
+ morphemes.dictionary_forms # => ["東京都", "に", "住む", "で", "居る"]
32
+
33
+ # Each morpheme exposes rich linguistic detail
34
+ morpheme = morphemes.first
35
+ morpheme.surface # => "東京都" - surface form (as it appears in text)
36
+ morpheme.part_of_speech # => ["名詞", "固有名詞", "地名", "一般"] — part-of-speech tags
37
+ morpheme.part_of_speech_id # => 5 - numeric POS id
38
+ morpheme.dictionary_form # => "東京都" - base/dictionary form
39
+ morpheme.normalized_form # => "東京都" - normalized form
40
+ morpheme.reading_form # => "トウキョウト" - phonetic reading
41
+ morpheme.oov? # => false - out-of-vocabulary?
42
+ morpheme.dictionary_id # => 0 - source dictionary id
43
+ morpheme.word_id # => 544373 - internal word id
44
+ morpheme.synonym_group_ids # => [] - synonym group ids
45
+ morpheme.dictionary_form_word_id # => -1 - dictionary-form word id
46
+ morpheme.head_word_length # => 3 - head word length in codepoints
47
+ morpheme.a_unit_split # => [123, 456] - split-A word ids
48
+ morpheme.b_unit_split # => [] - split-B word ids
49
+ morpheme.word_structure # => [123, 456] - word-structure ids
50
+ morpheme.total_cost # => 5765 - morphological analysis cost
51
+ morpheme.begin # => 0 - start byte offset
52
+ morpheme.end # => 9 - end byte offset
53
+ morpheme.begin_c # => 0 - start character offset
54
+ morpheme.end_c # => 3 - end character offset
55
+ morpheme.system? # => true - from system dictionary?
56
+ morpheme.user? # => false - from user dictionary?
57
+
58
+ # Split text into natural Japanese sentence boundaries
59
+ Kabosu.split_sentences("東京都に住んでいる。大阪も好きだ。")
60
+ # => ["東京都に住んでいる。", "大阪も好きだ。"]
61
+ ```
62
+
63
+ ## Installation
64
+
65
+ - Ruby >= 3.1
66
+ - Rust toolchain (for compiling the native extension)
67
+
68
+ Add to your Gemfile:
69
+
70
+ ```ruby
71
+ gem "kabosu"
72
+ ```
73
+
74
+ Then install and download a [Sudachi dictionary](https://github.com/WorksApplications/SudachiDict):
75
+
76
+ ```sh
77
+ bundle install
78
+ bundle exec rake kabosu:install[small] # or core, full
79
+ ```
80
+
81
+ Dictionary editions (from smallest to largest): `small`, `core`, `full`. See the [SudachiDict documentation](https://github.com/WorksApplications/SudachiDict?tab=readme-ov-file#dictionary-types) for details on the differences between editions.
82
+
83
+ ## Dictionary management
84
+
85
+ Rake tasks for managing Sudachi dictionaries:
86
+
87
+ ```sh
88
+ rake kabosu:install[small] # Install a dictionary (VERSION=YYYYMMDD for a specific version)
89
+ rake kabosu:list # List installed dictionaries
90
+ rake kabosu:versions # Show available versions from GitHub
91
+ rake kabosu:path # Show path to best available dictionary
92
+ rake kabosu:remove[small] # Remove a dictionary (VERSION=YYYYMMDD for a specific version)
93
+ ```
94
+
95
+ Dictionaries are stored in `~/.kabosu/dict/` by default. Set `KABOSU_DICT_DIR` to customize.
96
+
97
+ ## Tokenization modes
98
+
99
+ Sudachi provides three [split modes](https://github.com/WorksApplications/Sudachi?tab=readme-ov-file#the-modes-of-splitting):
100
+
101
+ | Mode | Description |
102
+ |------|-------------|
103
+ | `A` | Short units (most granular) |
104
+ | `B` | Middle units |
105
+ | `C` | Named entity units (default) |
106
+
107
+ ```ruby
108
+ dict = Kabosu::Dictionary.new(system_dict: Kabosu::Dictionary.path)
109
+ tok_a = dict.create(mode: :a)
110
+ tok_c = dict.create(mode: :c)
111
+ tok_a.tokenize("東京都").surfaces # => ["東京", "都"]
112
+ tok_c.tokenize("東京都").surfaces # => ["東京都"]
113
+ ```
114
+
115
+ Modes are symbols only (`:a`, `:b`, `:c` or `Kabosu::MODE_A/B/C`).
116
+
117
+ ## Advanced Use Cases
118
+
119
+ ```ruby
120
+ # Custom system dictionary + optional user dictionaries
121
+ dict = Kabosu::Dictionary.new(
122
+ system_dict: "/path/to/custom/system.dic",
123
+ user_dicts: ["/path/to/domain.dic", "/path/to/names.dic"]
124
+ )
125
+
126
+ # Create tokenizer with explicit mode/fields
127
+ tokenizer = dict.create(mode: :c, fields: %i[surface pos_id reading_form])
128
+
129
+ # Tokenize (returns MorphemeList; lazily hydrates morphemes)
130
+ list = tokenizer.tokenize("国会議事堂前駅")
131
+ list.surfaces
132
+ list.first.part_of_speech
133
+
134
+ # Dictionary prefix lookup
135
+ dict.lookup("東京都").surfaces
136
+
137
+ # Morpheme split
138
+ m = tokenizer.tokenize("東京都").first
139
+ m.split(mode: :a).surfaces
140
+
141
+ # Sentence splitting
142
+ Kabosu.split_sentences("東京都に住んでいる。大阪も好きだ。", ranges: true)
143
+ Kabosu.split_sentences("長い文...", limit: 12, with_checker: true)
144
+ ```
145
+
146
+ ## Benchmarks
147
+
148
+ Kabosu ships with a benchmark suite that measures tokenization throughput and compares the Ruby bindings against raw [sudachi.rs](https://github.com/WorksApplications/sudachi.rs).
149
+
150
+ This benchmark uses [Wagahai wa Neko de Aru](https://www.aozora.gr.jp/cards/000148/card789.html) (I Am a Cat) by Natsume Soseki, sourced from [Aozora Bunko](https://www.aozora.gr.jp/) (public domain) as the source text. ~958 KB of Japanese prose, 2,256 lines as input.
151
+
152
+ ### Results
153
+
154
+ Measured on an AMD Ryzen 7 5800X, `full` dictionary edition, Ruby 3.4, Rust 1.84:
155
+
156
+ Single-thread (10 iterations):
157
+
158
+ | Scenario | Rust | Ruby | Ratio |
159
+ |---|---|---|---|
160
+ | split_sentences | 1.550s | 1.615s | 1.0x |
161
+ | tokenize (mode C) | 3.148s | 3.395s | 1.1x |
162
+ | tokenize (mode A) | 3.227s | 3.525s | 1.1x |
163
+ | tokenize (mode B) | 3.226s | 3.582s | 1.1x |
164
+ | **Throughput** | **2.94 MB/s** | **2.69 MB/s** | **1.1x** |
165
+
166
+ Multithread (8 threads x 20,000 requests):
167
+
168
+ | Scenario | Rust | Ruby | Ratio |
169
+ |---|---|---|---|
170
+ | rails-style shared tokenizer | 1.475s | 2.101s | 1.4x |
171
+ | tokenizer per thread | 1.381s | 2.154s | 1.6x |
172
+ | **Throughput ST** | **20.44 MB/s** | **14.35 MB/s** | **1.4x** |
173
+ | **Throughput PT** | **21.84 MB/s** | **14.00 MB/s** | **1.6x** |
174
+
175
+ Notes:
176
+ - `shared tokenizer` matches Rails-style access where all request threads call one tokenizer instance.
177
+ - `per thread` creates one tokenizer per worker thread.
178
+ - Ratios are `Ruby / Rust`, and values vary by CPU, Ruby version, and dictionary edition.
179
+
180
+ To reproduce these results, run:
181
+
182
+ ```sh
183
+ bundle exec ruby bench/start
184
+ ```
185
+
186
+ To generate flamegraph SVGs alongside the benchmark:
187
+
188
+ ```sh
189
+ bundle exec ruby bench/start --profile
190
+ ```
191
+
192
+ This records both the Rust and Ruby runs with `perf` and produces interactive SVGs (`bench/flamegraph-rust.svg`, `bench/flamegraph-ruby.svg`). Open them in a browser to explore.
193
+
194
+ ## Contributing
195
+
196
+ ```sh
197
+ bundle install
198
+
199
+ bundle exec rake kabosu:install # Install Sudachi dictionary
200
+
201
+ bundle exec rake compile # Build the native extension
202
+ bundle exec rake test # Run tests
203
+
204
+ bench/start # Run benchmarks
205
+ ```
Binary file
Binary file
Binary file
Binary file
Binary file
@@ -0,0 +1,239 @@
1
+ require "net/http"
2
+ require "uri"
3
+ require "fileutils"
4
+ require "json"
5
+ require "open3"
6
+
7
+ module Kabosu
8
+ class DictManager
9
+ EDITIONS = %w[small core full].freeze
10
+ EDITION_PRIORITY = %w[full core small].freeze
11
+ GITHUB_REPO = "WorksApplications/SudachiDict"
12
+ GITHUB_API = "https://api.github.com"
13
+
14
+ class DictNotFound < StandardError; end
15
+ class DownloadError < StandardError; end
16
+
17
+ # Default storage directory: ~/.kabosu/dict/
18
+ def self.default_dir
19
+ File.join(Dir.home, ".kabosu", "dict")
20
+ end
21
+
22
+ def initialize(dir: self.class.default_dir)
23
+ @dir = dir
24
+ end
25
+
26
+ attr_reader :dir
27
+
28
+ # ── Install ──
29
+
30
+ # Download and extract a dictionary edition.
31
+ #
32
+ # manager.install("small")
33
+ # manager.install("core", version: "20260116")
34
+ #
35
+ def install(edition = "core", version: nil)
36
+ edition = validate_edition(edition)
37
+ version ||= latest_version
38
+
39
+ dest_dir = File.join(@dir, "sudachi-dictionary-#{version}")
40
+ dic_path = File.join(dest_dir, "system_#{edition}.dic")
41
+
42
+ if File.exist?(dic_path)
43
+ $stderr.puts "Already installed: #{dic_path}"
44
+ return dic_path
45
+ end
46
+
47
+ url = release_asset_url(version, edition)
48
+ zip_path = File.join(@dir, "sudachi-dictionary-#{version}-#{edition}.zip")
49
+
50
+ FileUtils.mkdir_p(@dir)
51
+ download(url, zip_path)
52
+ extract(zip_path, @dir)
53
+ FileUtils.rm_f(zip_path)
54
+
55
+ unless File.exist?(dic_path)
56
+ raise DownloadError, "Expected #{dic_path} after extraction, but file not found"
57
+ end
58
+
59
+ $stderr.puts "Installed: #{dic_path}"
60
+ dic_path
61
+ end
62
+
63
+ # ── Discovery ──
64
+
65
+ # List all installed dictionaries.
66
+ # Returns an array of hashes: { version:, edition:, path: }
67
+ def installed
68
+ results = []
69
+ return results unless Dir.exist?(@dir)
70
+
71
+ Dir.glob(File.join(@dir, "sudachi-dictionary-*")).sort.reverse.each do |version_dir|
72
+ next unless File.directory?(version_dir)
73
+
74
+ version = File.basename(version_dir).sub("sudachi-dictionary-", "")
75
+ EDITIONS.each do |edition|
76
+ dic = File.join(version_dir, "system_#{edition}.dic")
77
+ next unless File.exist?(dic)
78
+
79
+ results << { version: version, edition: edition, path: dic }
80
+ end
81
+ end
82
+
83
+ results
84
+ end
85
+
86
+ # Find the best available dictionary path.
87
+ # Prefers: latest version, then full > core > small.
88
+ def find(edition: nil)
89
+ candidates = installed
90
+ raise DictNotFound, "No dictionaries installed. Run: rake kabosu:install" if candidates.empty?
91
+
92
+ if edition
93
+ edition = validate_edition(edition)
94
+ match = candidates.find { |d| d[:edition] == edition }
95
+ raise DictNotFound, "No #{edition} dictionary installed" unless match
96
+ return match[:path]
97
+ end
98
+
99
+ # Group by version (already sorted newest-first), pick best edition
100
+ by_version = candidates.group_by { |d| d[:version] }
101
+ latest_version_dicts = by_version.values.first
102
+
103
+ best = EDITION_PRIORITY.each do |ed|
104
+ found = latest_version_dicts.find { |d| d[:edition] == ed }
105
+ break found if found
106
+ end
107
+
108
+ best.is_a?(Hash) ? best[:path] : latest_version_dicts.first[:path]
109
+ end
110
+
111
+ # ── Remove ──
112
+
113
+ # Remove a specific dictionary edition, or an entire version.
114
+ def remove(edition: nil, version: nil)
115
+ targets = installed
116
+ targets = targets.select { |d| d[:version] == version } if version
117
+ targets = targets.select { |d| d[:edition] == edition } if edition
118
+
119
+ raise DictNotFound, "No matching dictionary found" if targets.empty?
120
+
121
+ targets.each do |d|
122
+ FileUtils.rm_f(d[:path])
123
+ $stderr.puts "Removed: #{d[:path]}"
124
+
125
+ # Clean up empty version directories
126
+ version_dir = File.dirname(d[:path])
127
+ dics_remaining = Dir.glob(File.join(version_dir, "system_*.dic"))
128
+ if dics_remaining.empty?
129
+ FileUtils.rm_rf(version_dir)
130
+ $stderr.puts "Removed empty directory: #{version_dir}"
131
+ end
132
+ end
133
+ end
134
+
135
+ # ── Version resolution ──
136
+
137
+ # Fetch the latest release tag from GitHub.
138
+ def latest_version
139
+ uri = URI("#{GITHUB_API}/repos/#{GITHUB_REPO}/releases/latest")
140
+ response = http_get(uri, headers: { "Accept" => "application/json" })
141
+ data = JSON.parse(response.body)
142
+ tag = data["tag_name"]
143
+ # Tags are like "v20260116" — strip the "v" prefix
144
+ tag.sub(/\Av/, "")
145
+ end
146
+
147
+ # List available versions from GitHub releases.
148
+ def available_versions
149
+ uri = URI("#{GITHUB_API}/repos/#{GITHUB_REPO}/releases")
150
+ response = http_get(uri, headers: { "Accept" => "application/json" })
151
+ JSON.parse(response.body).map { |r| r["tag_name"].sub(/\Av/, "") }
152
+ end
153
+
154
+ private
155
+
156
+ def validate_edition(edition)
157
+ edition = edition.to_s.downcase
158
+ unless EDITIONS.include?(edition)
159
+ raise ArgumentError, "Unknown edition '#{edition}'. Must be one of: #{EDITIONS.join(", ")}"
160
+ end
161
+ edition
162
+ end
163
+
164
+ def release_asset_url(version, edition)
165
+ "https://github.com/#{GITHUB_REPO}/releases/download/v#{version}/sudachi-dictionary-#{version}-#{edition}.zip"
166
+ end
167
+
168
+ def download(url, dest)
169
+ $stderr.puts "Downloading #{url}..."
170
+ uri = resolve_redirects(URI(url))
171
+
172
+ Net::HTTP.start(uri.host, uri.port, use_ssl: uri.scheme == "https") do |http|
173
+ http.request(Net::HTTP::Get.new(uri)) do |response|
174
+ unless response.is_a?(Net::HTTPSuccess)
175
+ raise DownloadError, "Failed to download: #{response.code} #{response.message}"
176
+ end
177
+
178
+ total = response["Content-Length"]&.to_i
179
+ written = 0
180
+
181
+ File.open(dest, "wb") do |f|
182
+ response.read_body do |chunk|
183
+ f.write(chunk)
184
+ written += chunk.bytesize
185
+ if total && total > 0
186
+ pct = (written * 100 / total).clamp(0, 100)
187
+ $stderr.print "\r #{(written.to_f / 1024 / 1024).round(1)} / #{(total.to_f / 1024 / 1024).round(1)} MB (#{pct}%)"
188
+ end
189
+ end
190
+ end
191
+
192
+ $stderr.puts "\r #{(written.to_f / 1024 / 1024).round(1)} MB downloaded"
193
+ end
194
+ end
195
+ end
196
+
197
+ def resolve_redirects(uri, limit: 5)
198
+ raise DownloadError, "Too many redirects" if limit == 0
199
+
200
+ Net::HTTP.start(uri.host, uri.port, use_ssl: uri.scheme == "https") do |http|
201
+ response = http.request(Net::HTTP::Head.new(uri))
202
+ case response
203
+ when Net::HTTPRedirection
204
+ resolve_redirects(URI(response["location"]), limit: limit - 1)
205
+ else
206
+ uri
207
+ end
208
+ end
209
+ end
210
+
211
+ def http_get(uri, headers: {}, redirect_limit: 5)
212
+ raise DownloadError, "Too many redirects" if redirect_limit == 0
213
+
214
+ http = Net::HTTP.new(uri.host, uri.port)
215
+ http.use_ssl = (uri.scheme == "https")
216
+
217
+ request = Net::HTTP::Get.new(uri)
218
+ headers.each { |k, v| request[k] = v }
219
+
220
+ response = http.request(request)
221
+
222
+ case response
223
+ when Net::HTTPRedirection
224
+ http_get(URI(response["location"]), headers: headers, redirect_limit: redirect_limit - 1)
225
+ else
226
+ response
227
+ end
228
+ end
229
+
230
+ def extract(zip_path, dest_dir)
231
+ $stderr.puts "Extracting..."
232
+ # Use system unzip — available everywhere, handles large files well
233
+ _stdout, stderr, status = Open3.capture3("unzip", "-o", zip_path, "-d", dest_dir)
234
+ unless status.success?
235
+ raise DownloadError, "Failed to extract #{zip_path}: #{stderr}"
236
+ end
237
+ end
238
+ end
239
+ end