TextToSpeechViaOpenAIAPI

InfoGeneratePackages

This Ruby code defines a class that interacts with an API to convert text to speech. Inside a module named `Sublayer`, nested within another module called `Actions`, the class `TextToSpeechAction` inherits from a base class and is designed to take a piece of text as input and convert it to speech using an API call. The class initializes with the text to be converted and has a method `call` to perform the conversion. This method sends a POST request to the OpenAI API with necessary headers, including authorization and content type, and a body that specifies the text input, voice model, and response format. The method returns the API's response, which presumably contains the speech data in WAV format.

module Sublayer
  module Actions
    class TextToSpeechAction < Base
      def initialize(text)
        @text = text
      end

      def call
        speech = HTTParty.post(
          "https://api.openai.com/v1/audio/speech",
          headers: {
            "Authorization" => "Bearer #{ENV["OPENAI_API_KEY"]}",
            "Content-Type" => "application/json",
          },
          body: {
            "model": "tts-1",
            "input": @text,
            "voice": "nova",
            "response_format": "wav"
          }.to_json
        )

        speech
      end
    end
  end
end