Last active
November 10, 2024 09:05
-
-
Save kojix2/7761d6d385a4976d97b4a2ee7dfe3838 to your computer and use it in GitHub Desktop.
Command line tool to call ChatGPT's Speech API from Ruby
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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