audio_cpp 0.1.0

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.
@@ -0,0 +1,38 @@
1
+ # frozen_string_literal: true
2
+
3
+ # Builds libaudiocpp (audio.cpp's C API) from source and installs it into the
4
+ # gem's lib/audio_cpp/native directory. There is no Ruby C extension: the gem
5
+ # loads the library with FFI, so the Makefile written at the end does nothing.
6
+ #
7
+ # Set AUDIOCPP_LIB to an existing libaudiocpp to skip the build entirely.
8
+ # See builder.rb for the other knobs (AUDIOCPP_MODELS, AUDIOCPP_JOBS, ...).
9
+
10
+ require_relative "builder"
11
+
12
+ def write_noop_makefile
13
+ File.write("Makefile", <<~MAKE)
14
+ all:
15
+ \t@:
16
+ install:
17
+ \t@:
18
+ clean:
19
+ \t@:
20
+ distclean:
21
+ \t@:
22
+ .PHONY: all install clean distclean
23
+ MAKE
24
+ end
25
+
26
+ gem_lib = File.expand_path("../../lib/audio_cpp/native", __dir__)
27
+
28
+ if ENV["AUDIOCPP_LIB"] && !ENV["AUDIOCPP_LIB"].strip.empty?
29
+ puts "[audio_cpp] AUDIOCPP_LIB is set (#{ENV["AUDIOCPP_LIB"]}); not building libaudiocpp"
30
+ else
31
+ begin
32
+ AudioCppBuild::Builder.new(install_dir: gem_lib, work_dir: File.expand_path("tmp", __dir__)).run
33
+ rescue AudioCppBuild::BuildError => e
34
+ abort "[audio_cpp] #{e.message}"
35
+ end
36
+ end
37
+
38
+ write_noop_makefile
@@ -0,0 +1,109 @@
1
+ # frozen_string_literal: true
2
+
3
+ module AudioCpp
4
+ # Interleaved float PCM in [-1.0, 1.0] with its sample rate and channel count.
5
+ # Immutable: every transformation returns a new Audio.
6
+ class Audio
7
+ ASR_SAMPLE_RATE = 16_000
8
+
9
+ attr_reader :samples, :sample_rate, :channels
10
+
11
+ # Reads a WAV file (16-bit PCM or 32-bit float). For other formats convert
12
+ # first, e.g. `ffmpeg -i in.mp3 -ac 1 -ar 16000 out.wav`.
13
+ def self.read(path)
14
+ WAV.read(path)
15
+ end
16
+
17
+ # Turns what a caller passed as "audio" into an Audio: a WAV path, an Audio,
18
+ # or an Array of Float samples (taken as mono at `sample_rate`).
19
+ def self.coerce(input, sample_rate: ASR_SAMPLE_RATE)
20
+ if input.is_a?(Audio) then input
21
+ elsif input.is_a?(Array) then new(input, sample_rate: sample_rate)
22
+ elsif input.is_a?(String) || input.respond_to?(:to_path) then read(input.to_s)
23
+ else raise ArgumentError, "expected a WAV path, an AudioCpp::Audio or an Array of samples, got #{input.class}"
24
+ end
25
+ end
26
+
27
+ def initialize(samples, sample_rate:, channels: 1)
28
+ raise ArgumentError, "samples must be an Array" unless samples.is_a?(Array)
29
+ raise ArgumentError, "sample_rate must be a positive Integer" unless sample_rate.is_a?(Integer) && sample_rate.positive?
30
+ raise ArgumentError, "channels must be a positive Integer" unless channels.is_a?(Integer) && channels.positive?
31
+ raise ArgumentError, "#{samples.size} samples do not split into #{channels} channels" unless (samples.size % channels).zero?
32
+
33
+ @samples = samples.frozen? ? samples : samples.dup.freeze
34
+ @sample_rate = sample_rate
35
+ @channels = channels
36
+ freeze
37
+ end
38
+
39
+ # Samples per channel.
40
+ def frames
41
+ samples.size / channels
42
+ end
43
+
44
+ # Length in seconds.
45
+ def duration
46
+ frames.fdiv(sample_rate)
47
+ end
48
+
49
+ def empty?
50
+ samples.empty?
51
+ end
52
+
53
+ # Averages the channels into one.
54
+ def mono
55
+ return self if channels == 1
56
+
57
+ mixed = samples.each_slice(channels).map { |frame| frame.sum / channels }
58
+ Audio.new(mixed, sample_rate: sample_rate)
59
+ end
60
+
61
+ # Linear interpolation to another rate; see Resampler for its limits.
62
+ def resample(rate)
63
+ return self if rate == sample_rate
64
+
65
+ resampled = Resampler.linear(samples, from: sample_rate, to: rate, channels: channels)
66
+ Audio.new(resampled, sample_rate: rate, channels: channels)
67
+ end
68
+
69
+ # Mono 16 kHz, the input most speech models expect.
70
+ def to_asr_input
71
+ mono.resample(ASR_SAMPLE_RATE)
72
+ end
73
+
74
+ # Yields consecutive pieces of `frames` frames each as Audio (the last one
75
+ # may be shorter). Returns an Enumerator without a block.
76
+ def each_chunk(frames)
77
+ raise ArgumentError, "chunk size must be positive" unless frames.positive?
78
+ return enum_for(:each_chunk, frames) unless block_given?
79
+
80
+ samples.each_slice(frames * channels) do |slice|
81
+ yield Audio.new(slice, sample_rate: sample_rate, channels: channels)
82
+ end
83
+ self
84
+ end
85
+
86
+ # Writes a WAV file: `format: :pcm16` (default) or `:float32`.
87
+ def to_wav(path, format: :pcm16)
88
+ WAV.write(path, self, format: format)
89
+ end
90
+
91
+ # The WAV file as a binary String, e.g. for `send_data`.
92
+ def to_wav_bytes(format: :pcm16)
93
+ WAV.encode(self, format: format)
94
+ end
95
+
96
+ def ==(other)
97
+ other.is_a?(Audio) && sample_rate == other.sample_rate && channels == other.channels && samples == other.samples
98
+ end
99
+ alias_method :eql?, :==
100
+
101
+ def hash
102
+ [samples, sample_rate, channels].hash
103
+ end
104
+
105
+ def inspect
106
+ format("#<%s %.2fs %d Hz %d ch>", self.class.name, duration, sample_rate, channels)
107
+ end
108
+ end
109
+ end
@@ -0,0 +1,70 @@
1
+ # frozen_string_literal: true
2
+
3
+ module AudioCpp
4
+ # Base class for everything this gem raises.
5
+ #
6
+ # Errors that come from a failing C call carry the call's status and the
7
+ # thread-local detail (`audiocpp_last_error`) read right after it.
8
+ class Error < StandardError
9
+ attr_reader :operation, :status, :status_name, :detail
10
+
11
+ def initialize(message = nil, operation: nil, status: nil, status_name: nil, detail: nil)
12
+ @operation = operation
13
+ @status = status
14
+ @status_name = status_name
15
+ @detail = detail
16
+ super(message || compose_message)
17
+ end
18
+
19
+ private
20
+
21
+ def compose_message
22
+ parts = [operation, status_name].compact.join(": ")
23
+ (detail.nil? || detail.empty?) ? parts : "#{parts} (#{detail})"
24
+ end
25
+ end
26
+
27
+ # The shared library could not be found or loaded.
28
+ class LibraryError < Error; end
29
+
30
+ # The library speaks another ABI than this gem.
31
+ class AbiMismatchError < LibraryError; end
32
+
33
+ # A method was called on a handle after #close.
34
+ class ClosedError < Error; end
35
+
36
+ class InvalidArgumentError < Error; end
37
+
38
+ class UnsupportedFamilyError < Error; end
39
+
40
+ class ModelLoadError < Error; end
41
+
42
+ # A failure inside the engine while running a task.
43
+ class EngineError < Error; end
44
+
45
+ class OutOfMemoryError < Error; end
46
+
47
+ class OutOfRangeError < Error; end
48
+
49
+ # The result does not carry the requested output (no audio, no text, ...).
50
+ class NotAvailableError < Error; end
51
+
52
+ # The WAV file uses an encoding this gem does not read.
53
+ class UnsupportedFormatError < Error; end
54
+
55
+ STATUS_ERRORS = {
56
+ invalid_argument: InvalidArgumentError,
57
+ unsupported_family: UnsupportedFamilyError,
58
+ load_failed: ModelLoadError,
59
+ runtime: EngineError,
60
+ out_of_memory: OutOfMemoryError,
61
+ out_of_range: OutOfRangeError,
62
+ not_available: NotAvailableError
63
+ }.freeze
64
+ private_constant :STATUS_ERRORS
65
+
66
+ # Maps a non-OK status Symbol to its Error subclass.
67
+ def self.error_class_for(status)
68
+ STATUS_ERRORS.fetch(status, Error)
69
+ end
70
+ end
@@ -0,0 +1,35 @@
1
+ # frozen_string_literal: true
2
+
3
+ require "ffi"
4
+
5
+ module AudioCpp
6
+ # Owns one C handle and frees it exactly once: on #close, or from a GC
7
+ # finalizer if #close was never called. Freeing twice is a no-op.
8
+ #
9
+ # Internal: Model and Session wrap one of these.
10
+ class Handle
11
+ # `releaser` is called with the raw pointer, once. It must not refer to the
12
+ # object that owns this handle, or the finalizer would keep it alive.
13
+ def initialize(pointer, releaser)
14
+ raise ArgumentError, "null handle" if pointer.nil? || pointer.null?
15
+
16
+ @pointer = FFI::AutoPointer.new(pointer, releaser)
17
+ end
18
+
19
+ # The live pointer; raises ClosedError after #close.
20
+ def pointer
21
+ @pointer or raise ClosedError, "handle used after close"
22
+ end
23
+
24
+ def close
25
+ pointer = @pointer
26
+ @pointer = nil
27
+ pointer&.free
28
+ nil
29
+ end
30
+
31
+ def closed?
32
+ @pointer.nil?
33
+ end
34
+ end
35
+ end
@@ -0,0 +1,38 @@
1
+ # frozen_string_literal: true
2
+
3
+ require "rbconfig"
4
+
5
+ module AudioCpp
6
+ # Finds libaudiocpp: ENV["AUDIOCPP_LIB"], then the copy built into the gem,
7
+ # then the system loader's search path.
8
+ module LibraryPath
9
+ BUNDLED_DIR = File.expand_path("native", __dir__)
10
+
11
+ module_function
12
+
13
+ def file_name
14
+ macos? ? "libaudiocpp.dylib" : "libaudiocpp.so"
15
+ end
16
+
17
+ def bundled
18
+ File.join(BUNDLED_DIR, file_name)
19
+ end
20
+
21
+ # The path (or bare name) to hand to the dynamic loader.
22
+ def resolve(env: ENV)
23
+ explicit = env["AUDIOCPP_LIB"]
24
+ if explicit && !explicit.empty?
25
+ return explicit if File.file?(explicit)
26
+
27
+ raise LibraryError, "AUDIOCPP_LIB points to #{explicit}, which is not a file"
28
+ end
29
+ return bundled if File.file?(bundled)
30
+
31
+ "audiocpp"
32
+ end
33
+
34
+ def macos?
35
+ RbConfig::CONFIG["host_os"].match?(/darwin/)
36
+ end
37
+ end
38
+ end
@@ -0,0 +1,221 @@
1
+ # frozen_string_literal: true
2
+
3
+ require "etc"
4
+ require "ffi"
5
+ require "monitor"
6
+
7
+ module AudioCpp
8
+ # A loaded model file (GGUF, safetensors package, ...). Load once and keep it:
9
+ # sessions are cheap next to loading.
10
+ #
11
+ # AudioCpp::Model.load("gigaam-v4-rnnt-q8_0.gguf") do |model|
12
+ # model.family # => "gigaam_asr"
13
+ # model.session { |s| puts s.transcribe("speech.wav").text }
14
+ # end
15
+ #
16
+ # Threads: the C API only promises that separate handles may be used
17
+ # concurrently. Two sessions of one model running at the same time is not
18
+ # promised (audio.cpp's own server runs one request per loaded model unless a
19
+ # family declares more), so every Session of a Model takes the Model's lock
20
+ # for each native call. Sharing one Model across threads is therefore safe
21
+ # but serial; load one Model per worker for parallel inference.
22
+ class Model
23
+ # What a model declares about one of its options.
24
+ OptionInfo = Struct.new(:name, :value_name, :description, :default, :min, :max, :required,
25
+ keyword_init: true) do
26
+ def required?
27
+ required
28
+ end
29
+ end
30
+
31
+ MODES = %w[offline streaming].freeze
32
+
33
+ # Loads `path`. `family:` skips identification from the path (audiocpp_cli's
34
+ # --family); `config:`, `weight:` and `spec_override:` map to --config,
35
+ # --weight and --model-spec-override; `options:` to --load-option.
36
+ #
37
+ # With a block, yields the model, closes it afterwards and returns the
38
+ # block's value.
39
+ def self.load(path, family: nil, config: nil, weight: nil, spec_override: nil, options: {})
40
+ model = new(path.to_s, family: family, config: config, weight: weight, spec_override: spec_override,
41
+ options: options)
42
+ return model unless block_given?
43
+
44
+ begin
45
+ yield model
46
+ ensure
47
+ model.close
48
+ end
49
+ end
50
+
51
+ attr_reader :path
52
+
53
+ def initialize(path, family: nil, config: nil, weight: nil, spec_override: nil, options: {})
54
+ raise ArgumentError, "no model at #{path}" unless File.exist?(path)
55
+
56
+ @path = path
57
+ @lock = Monitor.new
58
+ selection = {family_hint: family, config_id: config, weight_id: weight, model_spec_override: spec_override}
59
+ @handle = Handle.new(load_model(path, selection, options), Native.method(:audiocpp_model_free))
60
+ end
61
+
62
+ def family
63
+ synchronize { Native.utf8(Native.audiocpp_model_family(pointer)) }
64
+ end
65
+
66
+ def description
67
+ synchronize { Native.utf8(Native.audiocpp_model_description(pointer)) }
68
+ end
69
+
70
+ # Language codes the model declares (may be empty).
71
+ def languages
72
+ out = FFI::MemoryPointer.new(:pointer)
73
+ synchronize do
74
+ Array.new(Native.audiocpp_model_language_count(pointer)) do |index|
75
+ Native.check!(Native.audiocpp_model_language(pointer, index, out), "audiocpp_model_language")
76
+ Native.read_string(out)
77
+ end
78
+ end
79
+ end
80
+
81
+ # Whether the model can run `task` ("asr", "tts", "diar", ...; see
82
+ # AudioCpp.tasks) in `mode` ("offline" or "streaming"). Unlike the C call,
83
+ # an unknown task or mode raises instead of answering false.
84
+ def supports?(task, mode = "offline")
85
+ task = AudioCpp.validate_task(task)
86
+ mode = Model.validate_mode(mode)
87
+ synchronize { Native.audiocpp_model_supports(pointer, task, mode) == 1 }
88
+ end
89
+
90
+ # The tasks this model runs in `mode`.
91
+ def tasks(mode = "offline")
92
+ AudioCpp.tasks.select { |task| supports?(task, mode) }
93
+ end
94
+
95
+ def timestamps?
96
+ synchronize { Native.audiocpp_model_supports_timestamps(pointer) == 1 }
97
+ end
98
+
99
+ def speaker_reference?
100
+ synchronize { Native.audiocpp_model_supports_speaker_reference(pointer) == 1 }
101
+ end
102
+
103
+ def style_condition?
104
+ synchronize { Native.audiocpp_model_supports_style_condition(pointer) == 1 }
105
+ end
106
+
107
+ # The options the model declares for `scope`: :request (per run), :session
108
+ # (fixed when a session is created) or :load. Returns OptionInfo structs.
109
+ def options(scope = :request)
110
+ outs = Array.new(6) { FFI::MemoryPointer.new(:pointer) }
111
+ required = FFI::MemoryPointer.new(:int)
112
+ synchronize do
113
+ Array.new(Native.audiocpp_model_option_count(pointer, scope)) do |index|
114
+ Native.check!(Native.audiocpp_model_option(pointer, scope, index, *outs, required), "audiocpp_model_option")
115
+ name, value_name, description, default, min, max = outs.map { |out| Native.read_string(out) }
116
+ OptionInfo.new(name: name, value_name: value_name, description: description, default: default, min: min,
117
+ max: max, required: required.read_int == 1)
118
+ end
119
+ end
120
+ end
121
+
122
+ # Opens a Session. `task:` defaults to the model's only task (an error if it
123
+ # has several); `options:` are session options (--session-option), e.g.
124
+ # `{"gigaam_asr.head" => "raw"}`. `backend:` is "cpu", "metal", "cuda",
125
+ # "vulkan", ... or "best"; `threads:` defaults to the number of processors.
126
+ #
127
+ # With a block, yields the session, closes it afterwards and returns the
128
+ # block's value.
129
+ def session(task: nil, mode: "offline", backend: "cpu", device: 0, threads: nil, impl: nil, options: {}, &block)
130
+ Session.open(self, task: task || default_task(mode), mode: Model.validate_mode(mode), backend: backend.to_s,
131
+ device: device, threads: threads || Etc.nprocessors, impl: impl, options: options, &block)
132
+ end
133
+
134
+ # Frees the model. Sessions created from it keep working (they hold the
135
+ # model internally). Safe to call twice.
136
+ def close
137
+ synchronize { @handle.close }
138
+ end
139
+
140
+ def closed?
141
+ @handle.closed?
142
+ end
143
+
144
+ def inspect
145
+ return "#<#{self.class.name} closed>" if closed?
146
+
147
+ "#<#{self.class.name} #{family} #{path}>"
148
+ end
149
+
150
+ # @api private
151
+ def pointer
152
+ @handle.pointer
153
+ end
154
+
155
+ # @api private: serialises native calls on this model and its sessions.
156
+ def synchronize(&block)
157
+ @lock.synchronize(&block)
158
+ end
159
+
160
+ def self.validate_mode(mode)
161
+ mode = mode.to_s
162
+ return mode if MODES.include?(mode)
163
+
164
+ raise ArgumentError, "unknown mode #{mode.inspect}; expected one of #{MODES.join(", ")}"
165
+ end
166
+
167
+ private
168
+
169
+ def default_task(mode)
170
+ candidates = tasks(mode)
171
+ return candidates.first if candidates.size == 1
172
+
173
+ raise ArgumentError, "#{family} runs no task in #{mode} mode" if candidates.empty?
174
+
175
+ raise ArgumentError, "#{family} runs several tasks (#{candidates.join(", ")}); pass task:"
176
+ end
177
+
178
+ def load_model(path, selection, options)
179
+ family = selection[:family_hint]
180
+ raise UnsupportedFamilyError, missing_family_message(family) if family && !AudioCpp.families.include?(family.to_s)
181
+
182
+ call_load(path, selection, options)
183
+ rescue ModelLoadError => e
184
+ raise unless e.detail.to_s.include?("no registered model loader")
185
+
186
+ raise ModelLoadError.new("#{e.message}. #{unrecognized_file_hint}", operation: e.operation, status: e.status,
187
+ status_name: e.status_name, detail: e.detail)
188
+ end
189
+
190
+ def missing_family_message(family)
191
+ "family #{family} is not in this build of libaudiocpp (#{AudioCpp.families.size} families: " \
192
+ "#{AudioCpp.families.join(", ")}). Reinstall the gem with AUDIOCPP_MODELS=full, or with " \
193
+ "AUDIOCPP_MODELS=#{[built_models, family].compact.join(",")}"
194
+ end
195
+
196
+ def unrecognized_file_hint
197
+ "No family in this build recognized the file. If it belongs to one that is not built in " \
198
+ "(this build has #{AudioCpp.families.join(", ")}), reinstall the gem with AUDIOCPP_MODELS=full " \
199
+ "or a list that names it, or pass family:"
200
+ end
201
+
202
+ def built_models
203
+ models = AudioCpp.build_info&.fetch("models", nil)
204
+ models unless models.nil? || %w[full core].include?(models)
205
+ end
206
+
207
+ def call_load(path, selection, options)
208
+ Registry.open do |registry|
209
+ Options.open(options) do |options_pointer|
210
+ strings = selection.transform_values { |value| value && FFI::MemoryPointer.from_string(value.to_s) }
211
+ config = Native::ModelConfig.new
212
+ strings.each { |field, string| config[field] = string || FFI::Pointer::NULL }
213
+ out = FFI::MemoryPointer.new(:pointer)
214
+ status = Native.audiocpp_model_load(registry, path, config, options_pointer, out)
215
+ Native.check!(status, "audiocpp_model_load #{File.basename(path)}")
216
+ out.read_pointer
217
+ end
218
+ end
219
+ end
220
+ end
221
+ end
@@ -0,0 +1,177 @@
1
+ # frozen_string_literal: true
2
+
3
+ require "digest"
4
+ require "fileutils"
5
+ require "net/http"
6
+ require "uri"
7
+ require_relative "errors"
8
+
9
+ module AudioCpp
10
+ # Downloads GGUF files from Hugging Face, pinned to a repository revision and
11
+ # checked against their SHA-256, so what lands on disk is exactly what was
12
+ # tested. Interrupted downloads resume from the `.part` file.
13
+ #
14
+ # path = AudioCpp::Models.fetch("gigaam-v4", dir: "models")
15
+ # AudioCpp::Model.load(path)
16
+ #
17
+ # Another revision of a catalog file needs its SHA-256 (the size is then
18
+ # not checked), and any file works through a Spec of your own:
19
+ #
20
+ # AudioCpp::Models.fetch("gigaam-v4", dir: "models", revision: "<commit>", sha256: "<hex>")
21
+ # spec = AudioCpp::Models::Spec.new(id: "x", repo: "org/repo", revision: "<commit>",
22
+ # file: "model.gguf", sha256: "<hex>") # size: optional
23
+ # AudioCpp::Models.fetch(spec, dir: "models")
24
+ module Models
25
+ class ChecksumError < Error; end
26
+
27
+ class DownloadError < Error; end
28
+
29
+ Spec = Struct.new(:id, :family, :repo, :revision, :file, :size, :sha256, :license, keyword_init: true) do
30
+ def url
31
+ "https://huggingface.co/#{repo}/resolve/#{revision}/#{file}"
32
+ end
33
+
34
+ def file_name
35
+ File.basename(file)
36
+ end
37
+ end
38
+
39
+ # Files these bindings are tested with, at fixed revisions.
40
+ CATALOG = [
41
+ Spec.new(id: "gigaam-v4", family: "gigaam_asr", repo: "amx-community/GigaAM-v4-GGUF",
42
+ revision: "395373afe9eae8f21834bb8f43c3623c9da3c220", file: "gigaam-v4-rnnt-q8_0.gguf",
43
+ size: 270_912_032, sha256: "14ad051b9e61a732aca2b7de8466553a64a6d6749341f2440cc5afa59c4ebe53",
44
+ license: "MIT"),
45
+ Spec.new(id: "gigaam-multilingual-v2", family: "gigaam_asr", repo: "audio-cpp/audio.cpp-gguf",
46
+ revision: "6ce7ba8b319aa35d385a9481d69fc03de14ac72f",
47
+ file: "GigaAM-ASR-GGUF/gigaam-multilingual-v2-rnnt-q8_0.gguf",
48
+ size: 867_834_368, sha256: "8f51325379f1a82eb6b96af1c21e3e9ab1b93177ab95d7dd5e5d6af382ac9d3f",
49
+ license: "MIT"),
50
+ Spec.new(id: "nemotron-3-diarization", family: "nemotron_3_diar", repo: "audio-cpp/Nemotron-3-Diarization-GGUF",
51
+ revision: "647d39feaa0e91dca5ce355a95403837b76dff56", file: "nemotron-3-diarization-q8_0.gguf",
52
+ size: 106_675_136, sha256: "9a737455bd10123bcf1e036d9a0b07b6e8c42e7d0dd1a5ee4141dc386db46d0b",
53
+ license: "OpenMDW-1.1"),
54
+ Spec.new(id: "gigaedge-tts", family: "gigaedge_tts", repo: "amx-community/GigaEdge-TTS-GGUF",
55
+ revision: "77a0cda3c61825fd146e2903a2590476188381ff", file: "gigaedge-tts-f16.gguf",
56
+ size: 207_949_472, sha256: "0017363fcf5738574f1f7e65e96d599868820d344387a235f60c58184181d770",
57
+ license: "MIT")
58
+ ].freeze
59
+
60
+ MAX_REDIRECTS = 5
61
+ CHUNK = 1 << 20
62
+
63
+ module_function
64
+
65
+ def catalog
66
+ CATALOG
67
+ end
68
+
69
+ # The catalog entry for `id` (or the Spec itself); raises KeyError for an
70
+ # unknown id. `revision:` and `sha256:` override the pinned ones; a new
71
+ # revision needs its SHA-256, and drops the size check unless `size:` is
72
+ # given too.
73
+ def spec(id, revision: nil, sha256: nil, size: nil)
74
+ base = id.is_a?(Spec) ? id : CATALOG.find { |spec| spec.id == id.to_s }
75
+ raise KeyError, "unknown model #{id.inspect}; known: #{CATALOG.map(&:id).join(", ")}" unless base
76
+ return base unless revision || sha256 || size
77
+ raise ArgumentError, "a new revision needs its sha256:" if revision && revision != base.revision && !sha256
78
+
79
+ changed = base.dup
80
+ changed.revision = revision if revision
81
+ changed.size = (revision || sha256) ? size : size || base.size
82
+ changed.sha256 = sha256 if sha256
83
+ changed
84
+ end
85
+
86
+ def path(id, dir:)
87
+ File.join(dir.to_s, spec(id).file_name)
88
+ end
89
+
90
+ # True when the file is on disk with the pinned size (the hash is checked
91
+ # when it is downloaded, and again by #verify!). Without a known size, true
92
+ # when the file exists.
93
+ def installed?(id, dir:)
94
+ expected = spec(id).size
95
+ actual = File.size?(path(id, dir: dir))
96
+ expected ? actual == expected : !actual.nil?
97
+ end
98
+
99
+ # Raises ChecksumError unless the file has the pinned size (when known)
100
+ # and SHA-256.
101
+ def verify!(id, file)
102
+ spec = spec(id)
103
+ actual_size = File.size?(file).to_i
104
+ if spec.size && actual_size != spec.size
105
+ raise ChecksumError, "#{file}: #{actual_size} bytes, expected #{spec.size}"
106
+ end
107
+
108
+ actual = Digest::SHA256.file(file).hexdigest
109
+ raise ChecksumError, "#{file}: SHA-256 #{actual}, expected #{spec.sha256}" unless actual == spec.sha256
110
+
111
+ file
112
+ end
113
+
114
+ # Downloads `id` (a catalog id or a Spec) into `dir` unless a verified copy
115
+ # is there, and returns its path. `revision:`, `sha256:` and `size:`
116
+ # override the catalog's (see #spec). `progress` is called with
117
+ # `(bytes_done, bytes_total)` while downloading.
118
+ def fetch(id, dir:, revision: nil, sha256: nil, size: nil, progress: nil)
119
+ spec = spec(id, revision: revision, sha256: sha256, size: size)
120
+ target = path(spec, dir: dir)
121
+ return target if installed?(spec, dir: dir) && verified?(spec, target)
122
+
123
+ FileUtils.mkdir_p(dir.to_s)
124
+ part = "#{target}.part"
125
+ download(URI(spec.url), part, spec.size, progress)
126
+ begin
127
+ verify!(spec, part)
128
+ rescue ChecksumError
129
+ File.delete(part)
130
+ raise
131
+ end
132
+ File.rename(part, target)
133
+ target
134
+ end
135
+
136
+ def verified?(spec, file)
137
+ verify!(spec, file)
138
+ true
139
+ rescue ChecksumError
140
+ false
141
+ end
142
+
143
+ def download(uri, part, total, progress, redirects = 0)
144
+ raise DownloadError, "too many redirects for #{uri}" if redirects > MAX_REDIRECTS
145
+
146
+ offset = File.size?(part).to_i
147
+ offset = 0 if total && offset > total
148
+ Net::HTTP.start(uri.host, uri.port, use_ssl: uri.scheme == "https", open_timeout: 30, read_timeout: 120) do |http|
149
+ request = Net::HTTP::Get.new(uri)
150
+ request["Range"] = "bytes=#{offset}-" if offset.positive?
151
+ http.request(request) do |response|
152
+ case response
153
+ when Net::HTTPRedirection
154
+ return download(URI.join(uri.to_s, response["location"]), part, total, progress, redirects + 1)
155
+ when Net::HTTPPartialContent
156
+ write_body(response, part, "ab", offset, total || (offset + response.content_length.to_i), progress)
157
+ when Net::HTTPOK then write_body(response, part, "wb", 0, total || response.content_length.to_i, progress)
158
+ when Net::HTTPRangeNotSatisfiable then nil # the .part is already complete
159
+ else raise DownloadError, "GET #{uri}: HTTP #{response.code}"
160
+ end
161
+ end
162
+ end
163
+ end
164
+
165
+ def write_body(response, part, mode, done, total, progress)
166
+ File.open(part, mode) do |file|
167
+ response.read_body do |chunk|
168
+ file.write(chunk)
169
+ done += chunk.bytesize
170
+ progress&.call(done, total)
171
+ end
172
+ end
173
+ end
174
+
175
+ private_class_method :verified?, :download, :write_body
176
+ end
177
+ end