pico2wave-ruby 0.3.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.
checksums.yaml ADDED
@@ -0,0 +1,7 @@
1
+ ---
2
+ SHA256:
3
+ metadata.gz: 0d564aea57011b335b461a65ad8159738b5d747b2ddb67881796fd0922ad3cd5
4
+ data.tar.gz: b09b7e34a95237cb271f4036e19b456d1cb4fae2778494742a10482723a95a11
5
+ SHA512:
6
+ metadata.gz: 82e992214dcfd0e4e6231e2f6993359f89cd3add351592eed20887f2067131e1e6b85c2453c9fb81934b562fa1cc180b93e5530a1d28183ecbdd652559731fe2
7
+ data.tar.gz: 25e8a47b5e9fa8f26c582ef6440ed5579a4fae98f3b9c02177e3888c7e74b21611083985724709f8e262de5371a82e14e8a775e136bc31022e50ae97787fb768
data/CHANGELOG.md ADDED
@@ -0,0 +1,35 @@
1
+ # Changelog
2
+
3
+ ## [0.3.0] - 2026-12-05
4
+
5
+ First release on rubygems.org. Changes since 0.2.2 (git only):
6
+
7
+ ### Breaking changes
8
+
9
+ - `Speech#speak` streams the audio to the player's standard input by default; the player is run with `-` as its
10
+ last argument. Set `speech.stream = false` to play from a temporary file as before.
11
+ - `Maker#make` raises `Pico2Wave::Error` when Pico reports an error, instead of returning a status.
12
+ - `<` characters are removed from the text, since Pico interprets markup tags.
13
+ - `require 'pico2wave'` raises `Pico2Wave::MissingDependencyError` instead of exiting when Pico is missing.
14
+ - `Speech#speak` returns `false` when the player fails, and no longer deletes a wav file set with `tmp_wav_path=`.
15
+ - Licensed under MIT instead of GPL-3.0.
16
+ - `Pico2Wave.name` / `Pico2Wave.name=` are renamed `Pico2Wave.voice_name` / `Pico2Wave.voice_name=`: they
17
+ overrode Ruby's `Module#name`, so `Pico2Wave.name` now returns `"Pico2Wave"` again.
18
+
19
+ ### Added
20
+
21
+ - Choice of audio player via `player_command`, the `PICO2WAVE_PLAYER` environment variable, or `aplay` by default.
22
+ - Per-call language and voice: `Speech.new(text, lang: 'en-US')`, `Maker.new(text, path, lang: 'en-US')`, as well as
23
+ `lang_data:`, `speaker_data:`, `bpath:` and `voice_name:`.
24
+ - `Maker#write(io)` and `Play#stream` to stream the WAV to any IO or player.
25
+ - Pico engines are reused between calls (`Pico2Wave.close_engines` frees them).
26
+ - `gem install` checks that Pico is installed (skip with `PICO2WAVE_SKIP_DEPENDENCY_CHECK=1`).
27
+
28
+ ### Fixed
29
+
30
+ - Text could inject Pico markup, letting it write or read arbitrary files.
31
+ - Texts longer than about 260 bytes were silently truncated.
32
+ - Pico errors were ignored and could crash the Ruby process; Pico resources are now released.
33
+ - The player command was run through a shell (paths with spaces broke it, and commands could be injected).
34
+ - The temporary wav file was world-readable in the shared tmp directory; it is now private.
35
+ - `ffi` and `logger` are declared as dependencies.
data/LICENSE ADDED
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2019-2026 Maxime Désécot
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.
data/README.md ADDED
@@ -0,0 +1,126 @@
1
+ # pico2wave-ruby
2
+
3
+ Ruby wrapper for **pico2wave** TTS
4
+
5
+ ## Install
6
+
7
+ Add _pico2wave-ruby_ to Gemfile
8
+
9
+ ```ruby
10
+ gem "pico2wave-ruby", require: "pico2wave"
11
+ ```
12
+
13
+ ## Examples
14
+
15
+ ### Generate .wav from text
16
+
17
+ ```ruby
18
+ require 'pico2wave'
19
+ Pico2Wave::Maker.new("Hello!", "/tmp/pico-test.wav").make
20
+ ```
21
+
22
+ ### Generate and play text
23
+
24
+ ```ruby
25
+ require 'pico2wave'
26
+ speech = Pico2Wave::Speech.new("Hello!")
27
+ speech.speak
28
+ ```
29
+
30
+ ### Language and voice
31
+
32
+ French (`fr-FR`) is used by default. Choose the language per call, which is safe across threads:
33
+
34
+ ```ruby
35
+ Pico2Wave::Speech.new("Hello!", lang: "en-US").speak
36
+ Pico2Wave::Maker.new("Hello!", "/tmp/pico-test.wav", lang: "en-US").make
37
+ ```
38
+
39
+ The installed languages are listed by `Pico2Wave.lang_datas` (e.g. `en-US_ta.bin` for `en-US`).
40
+ `lang_data:`, `speaker_data:`, `bpath:` (language files directory) and `voice_name:` can also be given to pick the
41
+ Pico files directly. The process-wide defaults are set with `Pico2Wave.lang_data=`, `Pico2Wave.speaker_data=`,
42
+ `Pico2Wave.bpath=` and `Pico2Wave.voice_name=`.
43
+
44
+ ### Text input
45
+
46
+ The text is converted to UTF-8 and every `<` character is removed before synthesis:
47
+ Pico interprets markup tags (some of them read or write files), so the text cannot contain any.
48
+ `Pico2Wave::Error` is raised when Pico reports an error.
49
+
50
+ ### Engine reuse
51
+
52
+ The Pico engine is initialized once per language/voice and reused by later calls (thread-safe; calls on the same
53
+ voice are serialized). Call `Pico2Wave.close_engines` to free them.
54
+
55
+ ### Streaming
56
+
57
+ By default `Speech#speak` streams the audio to the player's standard input while it is being generated: playback
58
+ starts almost immediately and no temporary file is written. The player is run with `-` as its last argument, so
59
+ it must read a WAV stream from standard input when given `-` (e.g. `aplay`, `mpv`, `ffplay -nodisp -autoexit`).
60
+
61
+ For a player that can only read files, disable streaming; a temporary wav file is then written and its path is
62
+ appended to the command:
63
+
64
+ ```ruby
65
+ Pico2Wave::Speech.new("Hello!") { |speech| speech.stream = false }.speak
66
+ ```
67
+
68
+ To stream yourself, `Maker#write` writes the WAV to any IO:
69
+
70
+ ```ruby
71
+ Pico2Wave::Play.new(player_command: "aplay").stream { |io| Pico2Wave::Maker.new("Hello!").write(io) }
72
+ ```
73
+
74
+ ### Choose the audio player
75
+
76
+ `aplay` is used by default. Another player can be set, from highest to lowest priority:
77
+
78
+ ```ruby
79
+ # on Play
80
+ Pico2Wave::Play.new("/tmp/pico-test.wav", player_command: "aplay -q").run!
81
+
82
+ # on Speech
83
+ Pico2Wave::Speech.new("Hello!") { |speech| speech.player_command = "mpv --really-quiet" }.speak
84
+ ```
85
+
86
+ ```shell
87
+ # for the whole program
88
+ PICO2WAVE_PLAYER="ffplay -nodisp -autoexit" ruby my_script.rb
89
+ ```
90
+
91
+ The command can include arguments; `-` (streaming) or the wav file path is appended at the end.
92
+
93
+ ## Installing dependencies
94
+
95
+ The gem needs the SVOX Pico TTS library (`libttspico`) and its language files in `/usr/share/pico/lang`.
96
+ `gem install` checks for them and stops with instructions if they are missing.
97
+ Set `PICO2WAVE_SKIP_DEPENDENCY_CHECK=1` to skip this check (e.g. when Pico is installed in a later build step).
98
+
99
+ ### Debian / Ubuntu
100
+
101
+ ```shell
102
+ sudo apt-get install -y libttspico-utils sox
103
+ ```
104
+
105
+
106
+ ## Development
107
+
108
+ ```shell
109
+ bundle install
110
+ bundle exec rake # tests and RuboCop
111
+ bundle exec rake test # tests only
112
+ ```
113
+
114
+ The tests never play sound. Tests that need Pico are skipped when it is not installed.
115
+
116
+ ## Third-party software
117
+
118
+ This gem does not bundle SVOX Pico. It dynamically loads the system library `libttspico`
119
+ (Apache License 2.0, © SVOX AG / Google) and its language files, which must be installed separately
120
+ (see [Installing dependencies](#installing-dependencies)).
121
+
122
+ pico2wave-ruby is not affiliated with SVOX, Nuance or Google.
123
+
124
+ ## Licence
125
+
126
+ pico2wave-ruby is released under the [MIT License](LICENSE).
data/VERSION ADDED
@@ -0,0 +1 @@
1
+ 0.3.0
@@ -0,0 +1,28 @@
1
+ # frozen_string_literal: true
2
+
3
+ require 'fiddle'
4
+ require_relative '../../lib/pico2wave/errors'
5
+
6
+ LIBRARY = 'libttspico.so.0.0.0'
7
+ LANG_DIR = '/usr/share/pico/lang'
8
+
9
+ def library_available?
10
+ Fiddle.dlopen(LIBRARY).close
11
+ true
12
+ rescue Fiddle::DLError
13
+ false
14
+ end
15
+
16
+ def lang_files_available?
17
+ Dir[File.join(LANG_DIR, '*_ta.bin')].any?
18
+ end
19
+
20
+ unless ENV['PICO2WAVE_SKIP_DEPENDENCY_CHECK'] || (library_available? && lang_files_available?)
21
+ abort [
22
+ "pico2wave-ruby requires the SVOX Pico TTS library (#{LIBRARY}) and its language files in #{LANG_DIR}.",
23
+ Pico2Wave::Errors.install_hint,
24
+ 'Set PICO2WAVE_SKIP_DEPENDENCY_CHECK=1 to skip this check.'
25
+ ].compact.join("\n\n")
26
+ end
27
+
28
+ File.write('Makefile', "all:\n\t@:\ninstall:\n\t@:\nclean:\n\t@:\n")
@@ -0,0 +1,32 @@
1
+ # frozen_string_literal: true
2
+
3
+ module Pico2Wave
4
+ class Common
5
+ @which_cache = {}
6
+ @which_mutex = Mutex.new
7
+
8
+ class << self
9
+ def which(cmd)
10
+ key = [cmd, ENV.fetch('PATH', ''), ENV.fetch('PATHEXT', nil)]
11
+ cached = @which_mutex.synchronize { @which_cache[key] }
12
+ return cached if cached && File.executable?(cached)
13
+
14
+ path = find_executable(cmd)
15
+ @which_mutex.synchronize { @which_cache[key] = path }
16
+ end
17
+
18
+ private
19
+
20
+ def find_executable(cmd)
21
+ exts = ENV['PATHEXT'] ? ENV['PATHEXT'].split(';') : ['']
22
+ ENV.fetch('PATH', '').split(File::PATH_SEPARATOR).each do |path|
23
+ exts.each do |ext|
24
+ exe = File.join(path, "#{cmd}#{ext}")
25
+ return exe if File.executable?(exe) && !File.directory?(exe)
26
+ end
27
+ end
28
+ nil
29
+ end
30
+ end
31
+ end
32
+ end
@@ -0,0 +1,33 @@
1
+ # frozen_string_literal: true
2
+
3
+ module Pico2Wave
4
+ class Error < StandardError; end
5
+
6
+ class MissingDependencyError < LoadError; end
7
+
8
+ module Errors
9
+ class << self
10
+ def missing_dependencies_message(cause)
11
+ [cause.message, install_hint].compact.join("\n\n")
12
+ end
13
+
14
+ def install_hint
15
+ return unless RUBY_PLATFORM.include?('linux')
16
+
17
+ if debian_like?
18
+ "Install it with:\nsudo apt-get install -y libttspico-utils"
19
+ else
20
+ 'Install the SVOX Pico TTS library (libttspico) and its language files with your package manager.'
21
+ end
22
+ end
23
+
24
+ private
25
+
26
+ def debian_like?
27
+ return false unless File.readable?('/etc/os-release')
28
+
29
+ File.read('/etc/os-release').match?(/^ID(_LIKE)?="?[^\n]*\b(debian|ubuntu)\b/)
30
+ end
31
+ end
32
+ end
33
+ end
@@ -0,0 +1,49 @@
1
+ # frozen_string_literal: true
2
+
3
+ require 'English'
4
+ require 'shellwords'
5
+
6
+ module Pico2Wave
7
+ class Play
8
+ PLAYER_ENV_VAR = 'PICO2WAVE_PLAYER'
9
+ DEFAULT_PLAYER = 'aplay'
10
+
11
+ attr_writer :player_command
12
+
13
+ def initialize(file_path = nil, player_command: nil)
14
+ @file_path = file_path
15
+ @player_command = player_command
16
+ end
17
+
18
+ def run!
19
+ system(*Shellwords.split(player_command), @file_path, out: File::NULL, err: File::NULL)
20
+ end
21
+
22
+ def stream
23
+ IO.popen([*Shellwords.split(player_command), '-'], 'wb', out: File::NULL, err: File::NULL) do |stdin|
24
+ yield stdin
25
+ rescue Errno::EPIPE
26
+ nil
27
+ end
28
+ $CHILD_STATUS.success?
29
+ rescue Errno::ENOENT, Errno::EACCES
30
+ nil
31
+ end
32
+
33
+ private
34
+
35
+ def player_command
36
+ @player_command ||= env_player_command || default_player_command
37
+ end
38
+
39
+ def env_player_command
40
+ value = ENV.fetch(PLAYER_ENV_VAR, '').strip
41
+ value unless value.empty?
42
+ end
43
+
44
+ def default_player_command
45
+ Pico2Wave::Common.which(DEFAULT_PLAYER) ||
46
+ raise(Error, "no audio player found: install #{DEFAULT_PLAYER} or set #{PLAYER_ENV_VAR}")
47
+ end
48
+ end
49
+ end
@@ -0,0 +1,90 @@
1
+ # frozen_string_literal: true
2
+
3
+ require 'fileutils'
4
+ require 'logger'
5
+ require 'tmpdir'
6
+
7
+ module Pico2Wave
8
+ class Speech
9
+ attr_writer :logger, :player_command, :stream
10
+
11
+ def initialize(text, **voice_options)
12
+ @text = text
13
+ @voice_options = voice_options
14
+ yield(self) if block_given?
15
+ end
16
+
17
+ def speak
18
+ stream? ? spoken_by_streaming? : spoken_from_file?
19
+ end
20
+
21
+ def stream?
22
+ @stream != false
23
+ end
24
+
25
+ def save
26
+ Pico2Wave::Maker.new(@text, tmp_wav_path, **@voice_options).make
27
+ end
28
+
29
+ def tmp_wav_path
30
+ return @tmp_wav_path if defined?(@tmp_wav_path)
31
+
32
+ @tmp_dir = Dir.mktmpdir('pico2wave-')
33
+ @tmp_wav_path = File.join(@tmp_dir, 'speech.wav').tap do |path|
34
+ File.open(path, File::WRONLY | File::CREAT | File::EXCL, 0o600, &:close)
35
+ end
36
+ end
37
+
38
+ def tmp_wav_path=(path)
39
+ remove_tmp_dir
40
+ @tmp_wav_path = path
41
+ end
42
+
43
+ def logger
44
+ return @logger if defined?(@logger)
45
+
46
+ @logger = Logger.new($stdout)
47
+ end
48
+
49
+ private
50
+
51
+ def spoken_by_streaming?
52
+ error = nil
53
+ played = Play.new(player_command: @player_command).stream do |io|
54
+ Pico2Wave::Maker.new(@text, **@voice_options).write(io)
55
+ rescue Error => e
56
+ error = e
57
+ end
58
+ succeeded?(played, error)
59
+ end
60
+
61
+ def spoken_from_file?
62
+ begin
63
+ save
64
+ rescue Error => e
65
+ return succeeded?(false, e)
66
+ end
67
+ succeeded?(play, nil)
68
+ ensure
69
+ remove_tmp_dir
70
+ end
71
+
72
+ def succeeded?(played, generation_error)
73
+ if generation_error
74
+ logger.error "an error has been detected in the generation of the .wav file: #{generation_error.message}"
75
+ elsif !played
76
+ logger.error 'an error has been detected while playing the .wav file'
77
+ end
78
+ !generation_error && played == true
79
+ end
80
+
81
+ def remove_tmp_dir
82
+ FileUtils.rm_rf(@tmp_dir) if @tmp_dir
83
+ @tmp_dir = nil
84
+ end
85
+
86
+ def play
87
+ Play.new(tmp_wav_path, player_command: @player_command).run!
88
+ end
89
+ end
90
+ end
@@ -0,0 +1,12 @@
1
+ # frozen_string_literal: true
2
+
3
+ module Pico2Wave
4
+ VERSION = File.read(File.expand_path('../../VERSION', __dir__)).strip.freeze
5
+
6
+ class << self
7
+ def version
8
+ VERSION
9
+ end
10
+ alias gem_version version
11
+ end
12
+ end
data/lib/pico2wave.rb ADDED
@@ -0,0 +1,16 @@
1
+ # frozen_string_literal: true
2
+
3
+ require 'pico2wave/version'
4
+ require 'pico2wave/errors'
5
+
6
+ module Pico2Wave
7
+ autoload :Common, 'pico2wave/common'
8
+ autoload :Speech, 'pico2wave/speech'
9
+ autoload :Play, 'pico2wave/play'
10
+ end
11
+
12
+ begin
13
+ require_relative 'pico_tts/pico_tts'
14
+ rescue LoadError => e
15
+ raise Pico2Wave::MissingDependencyError, Pico2Wave::Errors.missing_dependencies_message(e)
16
+ end
@@ -0,0 +1,125 @@
1
+ # frozen_string_literal: true
2
+
3
+ module Pico2Wave
4
+ class Engine
5
+ def initialize(config = EngineConfig.current)
6
+ @config = config
7
+ init_system
8
+ [config.lang_data, config.speaker_data].each { |file_name| load_resource(file_name) }
9
+ create_voice
10
+ @engine = FFI::MemoryPointer.new(:pointer)
11
+ check_system('pico_newEngine', Pico2Wave.pico_newEngine(system, @config.voice_name, @engine))
12
+ rescue StandardError
13
+ close
14
+ raise
15
+ end
16
+
17
+ def synthesize(text, &)
18
+ check_engine('pico_resetEngine', Pico2Wave.pico_resetEngine(engine, PICO_RESET_FULL))
19
+ input = FFI::MemoryPointer.from_string(text)
20
+ remaining = text.bytesize + 1
21
+ offset = 0
22
+
23
+ while remaining.positive?
24
+ sent = put_text(input + offset, [remaining, TEXT_CHUNK_MAX_BYTES].min)
25
+ offset += sent
26
+ remaining -= sent
27
+ drain(&)
28
+ end
29
+ end
30
+
31
+ def close
32
+ return if @system.nil? || system.null?
33
+
34
+ dispose_engine
35
+ @resources&.reverse_each { |resource| Pico2Wave.pico_unloadResource(system, resource) }
36
+ Pico2Wave.pico_terminate(@system)
37
+ ensure
38
+ @system = @engine = @resources = @voice_defined = nil
39
+ end
40
+
41
+ private
42
+
43
+ def init_system
44
+ @svox_memory = FFI::MemoryPointer.new(:char, SVOX_MEMORY_SIZE)
45
+ @system = FFI::MemoryPointer.new(:pointer)
46
+ @resources = []
47
+ check_system('pico_initialize', Pico2Wave.pico_initialize(@svox_memory, SVOX_MEMORY_SIZE, @system))
48
+ end
49
+
50
+ def load_resource(file_name)
51
+ resource = FFI::MemoryPointer.new(:pointer)
52
+ path = File.join(@config.bpath, file_name)
53
+ check_system("loading #{path}", Pico2Wave.pico_loadResource(system, path, resource))
54
+ @resources << resource
55
+ end
56
+
57
+ def create_voice
58
+ check_system('pico_createVoiceDefinition', Pico2Wave.pico_createVoiceDefinition(system, @config.voice_name))
59
+ @voice_defined = true
60
+ @resources.each do |resource|
61
+ status = Pico2Wave.pico_addResourceToVoiceDefinition(system, @config.voice_name, resource_name(resource))
62
+ check_system('pico_addResourceToVoiceDefinition', status)
63
+ end
64
+ end
65
+
66
+ def resource_name(resource)
67
+ name = FFI::MemoryPointer.new(:char, RETSTRING_SIZE)
68
+ check_system('pico_getResourceName', Pico2Wave.pico_getResourceName(system, resource.read_pointer, name))
69
+ name
70
+ end
71
+
72
+ def put_text(chunk, size)
73
+ bytes_sent = FFI::MemoryPointer.new(:int16)
74
+ check_engine('pico_putTextUtf8', Pico2Wave.pico_putTextUtf8(engine, chunk, size, bytes_sent))
75
+ sent = bytes_sent.read_int16
76
+ raise Error, 'pico_putTextUtf8 accepted no input' unless sent.positive?
77
+
78
+ sent
79
+ end
80
+
81
+ def dispose_engine
82
+ Pico2Wave.pico_disposeEngine(system, @engine) if @engine && !engine.null?
83
+ Pico2Wave.pico_releaseVoiceDefinition(system, @config.voice_name) if @voice_defined
84
+ end
85
+
86
+ def drain
87
+ out_buffer = FFI::MemoryPointer.new(:char, OUT_BUFFER_SIZE)
88
+ bytes_received = FFI::MemoryPointer.new(:int16)
89
+ data_type = FFI::MemoryPointer.new(:int16)
90
+
91
+ loop do
92
+ status = Pico2Wave.pico_getData(engine, out_buffer, OUT_BUFFER_SIZE, bytes_received, data_type)
93
+ check_engine('pico_getData', status) unless [PICO_STEP_BUSY, PICO_STEP_IDLE].include?(status)
94
+
95
+ received = bytes_received.read_int16
96
+ yield out_buffer.read_bytes(received) if received.positive?
97
+ break unless status == PICO_STEP_BUSY
98
+ end
99
+ end
100
+
101
+ def system
102
+ @system.read_pointer
103
+ end
104
+
105
+ def engine
106
+ @engine.read_pointer
107
+ end
108
+
109
+ def check_system(action, status)
110
+ check(action, status, system, :pico_getSystemStatusMessage)
111
+ end
112
+
113
+ def check_engine(action, status)
114
+ check(action, status, engine, :pico_getEngineStatusMessage)
115
+ end
116
+
117
+ def check(action, status, handle, message_function)
118
+ return if status == PICO_OK
119
+
120
+ message = FFI::MemoryPointer.new(:char, RETSTRING_SIZE)
121
+ Pico2Wave.public_send(message_function, handle, status, message) unless handle.null?
122
+ raise Error, "#{action} failed (#{status}): #{message.read_string}"
123
+ end
124
+ end
125
+ end
@@ -0,0 +1,43 @@
1
+ # frozen_string_literal: true
2
+
3
+ module Pico2Wave
4
+ EngineConfig = Data.define(:bpath, :lang_data, :speaker_data, :voice_name) do
5
+ def self.current
6
+ build
7
+ end
8
+
9
+ def self.build(lang: nil, bpath: Pico2Wave.bpath, lang_data: nil, speaker_data: nil,
10
+ voice_name: Pico2Wave.voice_name)
11
+ lang_data ||= lang ? "#{language(lang)}_ta.bin" : Pico2Wave.lang_data
12
+ speaker_data ||= lang ? default_speaker_data(bpath, lang) : Pico2Wave.speaker_data
13
+ new(bpath:, lang_data:, speaker_data:, voice_name:)
14
+ end
15
+
16
+ def self.language(lang)
17
+ return lang if lang.to_s.match?(/\A[a-z]{2}-[A-Z]{2}\z/)
18
+
19
+ raise Error, %(invalid lang "#{lang}", expected a code like "en-US")
20
+ end
21
+
22
+ def self.default_speaker_data(bpath, lang)
23
+ path = Dir[File.join(bpath, "#{language(lang)}_*_sg.bin")].min
24
+ raise Error, %(no voice found for lang "#{lang}" in #{bpath}) unless path
25
+
26
+ File.basename(path)
27
+ end
28
+
29
+ def initialize(bpath:, lang_data:, speaker_data:, voice_name:)
30
+ check_file_name(lang_data, '_ta.bin')
31
+ check_file_name(speaker_data, '_sg.bin')
32
+ super
33
+ end
34
+
35
+ private
36
+
37
+ def check_file_name(file_name, suffix)
38
+ return if file_name.match?(/\A[\w-]+#{Regexp.escape(suffix)}\z/)
39
+
40
+ raise Error, %(invalid resource file name "#{file_name}", expected a "*#{suffix}" file name)
41
+ end
42
+ end
43
+ end
@@ -0,0 +1,49 @@
1
+ # frozen_string_literal: true
2
+
3
+ module Pico2Wave
4
+ class EnginePool
5
+ Slot = Struct.new(:mutex, :engine)
6
+
7
+ def initialize
8
+ @slots = {}
9
+ @mutex = Mutex.new
10
+ end
11
+
12
+ def with_engine(config = EngineConfig.current, &)
13
+ slot = @mutex.synchronize { @slots[config] ||= Slot.new(Mutex.new) }
14
+ slot.mutex.synchronize { use(slot, config, &) }
15
+ end
16
+
17
+ def close_all
18
+ slots = @mutex.synchronize { @slots.values.tap { @slots.clear } }
19
+ slots.each { |slot| slot.mutex.synchronize { discard(slot) } }
20
+ end
21
+
22
+ private
23
+
24
+ def use(slot, config)
25
+ slot.engine ||= Engine.new(config)
26
+ completed = false
27
+ result = yield slot.engine
28
+ completed = true
29
+ result
30
+ ensure
31
+ discard(slot) unless completed
32
+ end
33
+
34
+ def discard(slot)
35
+ slot.engine&.close
36
+ slot.engine = nil
37
+ end
38
+ end
39
+
40
+ class << self
41
+ def engine_pool
42
+ @engine_pool ||= EnginePool.new
43
+ end
44
+
45
+ def close_engines
46
+ engine_pool.close_all
47
+ end
48
+ end
49
+ end
@@ -0,0 +1,59 @@
1
+ # frozen_string_literal: true
2
+
3
+ module Pico2Wave
4
+ class Maker
5
+ WAV_HEADER_SIZE = 44
6
+ STREAM_DATA_SIZE = 0xFFFFFFFF - 36
7
+ WRITE_BUFFER_SIZE = 8192
8
+
9
+ def self.sanitize(text)
10
+ text.to_s.encode(Encoding::UTF_8, invalid: :replace, undef: :replace).scrub.tr("<\0", ' ')
11
+ end
12
+
13
+ def self.wav_header(data_size)
14
+ [
15
+ 'RIFF', 36 + data_size, 'WAVE',
16
+ 'fmt ', 16, 1, 1, SAMPLE_RATE, SAMPLE_RATE * 2, 2, 16,
17
+ 'data', data_size
18
+ ].pack('a4Va4a4VvvVVvva4V')
19
+ end
20
+
21
+ def initialize(txt, wav_path = nil, **)
22
+ @text = self.class.sanitize(txt)
23
+ @wav_path = wav_path
24
+ @config = EngineConfig.build(**)
25
+ end
26
+
27
+ def make
28
+ File.open(@wav_path, 'wb') do |file|
29
+ file.write(self.class.wav_header(0))
30
+ synthesize_to(file)
31
+ file.rewind
32
+ file.write(self.class.wav_header(file.size - WAV_HEADER_SIZE))
33
+ end
34
+ PICO_STEP_IDLE
35
+ end
36
+
37
+ def write(io)
38
+ io.write(self.class.wav_header(STREAM_DATA_SIZE))
39
+ synthesize_to(io)
40
+ PICO_STEP_IDLE
41
+ end
42
+
43
+ private
44
+
45
+ def synthesize_to(io)
46
+ buffer = String.new(capacity: WRITE_BUFFER_SIZE, encoding: Encoding::BINARY)
47
+ Pico2Wave.engine_pool.with_engine(@config) do |engine|
48
+ engine.synthesize(@text) do |pcm|
49
+ buffer << pcm
50
+ next if buffer.bytesize < WRITE_BUFFER_SIZE
51
+
52
+ io.write(buffer)
53
+ buffer.clear
54
+ end
55
+ end
56
+ io.write(buffer)
57
+ end
58
+ end
59
+ end
@@ -0,0 +1,85 @@
1
+ # frozen_string_literal: true
2
+
3
+ require 'ffi'
4
+
5
+ module Pico2Wave
6
+ extend FFI::Library
7
+
8
+ ffi_lib 'libttspico.so.0.0.0'
9
+
10
+ SVOX_MEMORY_SIZE = 3_145_728 # 3*1024**2
11
+ OUT_BUFFER_SIZE = 4096
12
+ RETSTRING_SIZE = 200
13
+ TEXT_CHUNK_MAX_BYTES = 32_767
14
+ SAMPLE_RATE = 16_000
15
+ PICO_OK = 0
16
+ PICO_STEP_IDLE = 200
17
+ PICO_STEP_BUSY = 201
18
+ PICO_RESET_FULL = 0
19
+
20
+ attach_function :pico_initialize, %i[pointer uint32 pointer], :int
21
+ attach_function :pico_terminate, %i[pointer], :int
22
+ attach_function :pico_getSystemStatusMessage, %i[pointer int pointer], :int
23
+ attach_function :pico_loadResource, %i[pointer string pointer], :int
24
+ attach_function :pico_unloadResource, %i[pointer pointer], :int
25
+ attach_function :pico_getResourceName, %i[pointer pointer pointer], :int
26
+ attach_function :pico_createVoiceDefinition, %i[pointer string], :int
27
+ attach_function :pico_addResourceToVoiceDefinition, %i[pointer string pointer], :int
28
+ attach_function :pico_releaseVoiceDefinition, %i[pointer string], :int
29
+ attach_function :pico_newEngine, %i[pointer string pointer], :int
30
+ attach_function :pico_disposeEngine, %i[pointer pointer], :int
31
+ attach_function :pico_putTextUtf8, %i[pointer pointer int16 pointer], :int
32
+ attach_function :pico_getData, %i[pointer pointer int16 pointer pointer], :int
33
+ attach_function :pico_resetEngine, %i[pointer int32], :int
34
+ attach_function :pico_getEngineStatusMessage, %i[pointer int pointer], :int
35
+
36
+ class << self
37
+ attr_writer :voice_name
38
+
39
+ def bpath
40
+ @bpath ||= '/usr/share/pico/lang'
41
+ end
42
+
43
+ def bpath=(value)
44
+ @bpath = value
45
+ @lang_datas = @speaker_datas = nil
46
+ end
47
+
48
+ def voice_name
49
+ @voice_name ||= 'PicoVoice'
50
+ end
51
+
52
+ def lang_data
53
+ @lang_data ||= 'fr-FR_ta.bin'
54
+ end
55
+
56
+ def lang_data=(value)
57
+ raise Error, %(invalid lang_data "#{value}") unless lang_datas.include?(value)
58
+
59
+ @lang_data = value
60
+ end
61
+
62
+ def lang_datas
63
+ @lang_datas ||= Dir[File.join(bpath, '*_ta.bin')].map { |path| File.basename(path) }.freeze
64
+ end
65
+
66
+ def speaker_data
67
+ @speaker_data ||= 'fr-FR_nk0_sg.bin'
68
+ end
69
+
70
+ def speaker_data=(value)
71
+ raise Error, %(invalid speaker_data "#{value}") unless speaker_datas.include?(value)
72
+
73
+ @speaker_data = value
74
+ end
75
+
76
+ def speaker_datas
77
+ @speaker_datas ||= Dir[File.join(bpath, '*_sg.bin')].map { |path| File.basename(path) }.freeze
78
+ end
79
+ end
80
+ end
81
+
82
+ require_relative 'engine_config'
83
+ require_relative 'engine'
84
+ require_relative 'engine_pool'
85
+ require_relative 'maker'
metadata ADDED
@@ -0,0 +1,86 @@
1
+ --- !ruby/object:Gem::Specification
2
+ name: pico2wave-ruby
3
+ version: !ruby/object:Gem::Version
4
+ version: 0.3.0
5
+ platform: ruby
6
+ authors:
7
+ - Maxime Désécot
8
+ bindir: bin
9
+ cert_chain: []
10
+ date: 1980-01-02 00:00:00.000000000 Z
11
+ dependencies:
12
+ - !ruby/object:Gem::Dependency
13
+ name: ffi
14
+ requirement: !ruby/object:Gem::Requirement
15
+ requirements:
16
+ - - "~>"
17
+ - !ruby/object:Gem::Version
18
+ version: '1.17'
19
+ type: :runtime
20
+ prerelease: false
21
+ version_requirements: !ruby/object:Gem::Requirement
22
+ requirements:
23
+ - - "~>"
24
+ - !ruby/object:Gem::Version
25
+ version: '1.17'
26
+ - !ruby/object:Gem::Dependency
27
+ name: logger
28
+ requirement: !ruby/object:Gem::Requirement
29
+ requirements:
30
+ - - "~>"
31
+ - !ruby/object:Gem::Version
32
+ version: '1.6'
33
+ type: :runtime
34
+ prerelease: false
35
+ version_requirements: !ruby/object:Gem::Requirement
36
+ requirements:
37
+ - - "~>"
38
+ - !ruby/object:Gem::Version
39
+ version: '1.6'
40
+ description: pico2wave-ruby is a small Ruby wrapper around the ‘pico2wave’ TTS engine
41
+ to create Text-To-Speech wav files
42
+ email: maxime.desecot@gmail.com
43
+ executables: []
44
+ extensions:
45
+ - ext/pico2wave/extconf.rb
46
+ extra_rdoc_files: []
47
+ files:
48
+ - CHANGELOG.md
49
+ - LICENSE
50
+ - README.md
51
+ - VERSION
52
+ - ext/pico2wave/extconf.rb
53
+ - lib/pico2wave.rb
54
+ - lib/pico2wave/common.rb
55
+ - lib/pico2wave/errors.rb
56
+ - lib/pico2wave/play.rb
57
+ - lib/pico2wave/speech.rb
58
+ - lib/pico2wave/version.rb
59
+ - lib/pico_tts/engine.rb
60
+ - lib/pico_tts/engine_config.rb
61
+ - lib/pico_tts/engine_pool.rb
62
+ - lib/pico_tts/maker.rb
63
+ - lib/pico_tts/pico_tts.rb
64
+ homepage: https://github.com/RaoH37/pico2wave-ruby
65
+ licenses:
66
+ - MIT
67
+ metadata:
68
+ rubygems_mfa_required: 'true'
69
+ rdoc_options: []
70
+ require_paths:
71
+ - lib
72
+ required_ruby_version: !ruby/object:Gem::Requirement
73
+ requirements:
74
+ - - ">="
75
+ - !ruby/object:Gem::Version
76
+ version: 3.3.14
77
+ required_rubygems_version: !ruby/object:Gem::Requirement
78
+ requirements:
79
+ - - ">="
80
+ - !ruby/object:Gem::Version
81
+ version: 1.8.11
82
+ requirements: []
83
+ rubygems_version: 3.6.9
84
+ specification_version: 4
85
+ summary: Ruby wrapper for ‘pico2wave’ TTS
86
+ test_files: []