Class: Kiribi::Gemma4::E2B::AudioEncoder

Inherits:
Object
  • Object
show all
Defined in:
lib/kiribi/gemma4/e2b/audio_encoder.rb

Instance Method Summary collapse

Constructor Details

#initializeAudioEncoder

Returns a new instance of AudioEncoder.



11
12
13
# File 'lib/kiribi/gemma4/e2b/audio_encoder.rb', line 11

def initialize
  @model = OnnxRuntime::Model.new(AUDIO_ENCODER_FILEPATH)
end

Instance Method Details

#encode(pcm_samples) ⇒ Object

pcm_samples: 16kHz mono float32 PCM サンプル配列またはバイナリ文字列audio_features 配列を返す



17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
# File 'lib/kiribi/gemma4/e2b/audio_encoder.rb', line 17

def encode(pcm_samples)
  pcm = pcm_samples.is_a?(String) ? pcm_samples.unpack("e*") : pcm_samples

  frame_length = 320
  hop_length = 160
  fft_length = 512
  num_mels = 128
  mel_floor = 0.001

  window = Array.new(frame_length) { 0.5 - 0.5 * Math.cos(2.0 * Math::PI * it / frame_length) }
  mel_filters = build_mel_filterbank(fft_length / 2 + 1, num_mels, 0.0, 8000.0, 16_000)

  pad_left = frame_length / 2
  padded = Array.new(pad_left, 0.0) + pcm
  mask_raw = Array.new(pad_left, false) + Array.new(pcm.length, true)

  frame_size = frame_length + 1
  num_frames = (padded.length - frame_size) / hop_length + 1

  input_features = []
  input_features_mask = []

  num_frames.times do |fi|
    start = fi * hop_length
    windowed = frame_length.times.map { padded[start + it] * window[it] }

    mag = rfft_magnitude(windowed, fft_length)

    mel = num_mels.times.map do |m|
      sum = 0.0
      mag.each_with_index { |v, i| sum += v * mel_filters[i][m] }
      Math.log(sum + mel_floor)
    end

    end_idx = fi * hop_length + frame_size - 1
    valid = end_idx < mask_raw.length && mask_raw[end_idx]

    input_features << (valid ? mel : Array.new(num_mels, 0.0))
    input_features_mask << valid
  end

  # pad_to_multiple_of 128
  padded_frames = ((input_features.length + 127) / 128) * 128
  while input_features.length < padded_frames
    input_features << Array.new(num_mels, 0.0)
    input_features_mask << false
  end

  @model.predict({
    "input_features" => [input_features],
    "input_features_mask" => [input_features_mask],
  })["audio_features"]
end