Skip to content

Instantly share code, notes, and snippets.

@kojix2
Last active November 10, 2024 09:05
Show Gist options
  • Save kojix2/7761d6d385a4976d97b4a2ee7dfe3838 to your computer and use it in GitHub Desktop.
Save kojix2/7761d6d385a4976d97b4a2ee7dfe3838 to your computer and use it in GitHub Desktop.
Command line tool to call ChatGPT's Speech API from Ruby
require 'getoptlong'
require 'openai'
options = {
'output' => 'speech.mp3'
}
parameters = {
'model' => 'tts-1',
'input' => nil,
'voice' => 'alloy',
'response_format' => 'mp3',
'speed' => '1.0'
}
parser = GetoptLong.new
parser.set_options(
['--output', '-o', GetoptLong::REQUIRED_ARGUMENT],
['--model', '-m', GetoptLong::REQUIRED_ARGUMENT],
['--input', '-i', GetoptLong::REQUIRED_ARGUMENT],
['--voice', '-v', GetoptLong::REQUIRED_ARGUMENT],
['--response-format', '-f', GetoptLong::REQUIRED_ARGUMENT],
['--speed', '-s', GetoptLong::REQUIRED_ARGUMENT]
)
parser.each do |name, arg|
name = name.delete_prefix('--').gsub(/-/, '_')
case name
when *parameters.keys
parameters[name] = arg
when *options.keys
options[name] = arg
end
end
parameters['input'] = ARGF.read if parameters['input'].nil?
client = OpenAI::Client.new(access_token: ENV['OPENAI_API_KEY'])
response = client.audio.speech(
parameters: parameters
)
File.binwrite(options['output'], response)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment