#!/usr/bin/env groovy
// PUBLIC DOMAIN - NO LICENSE, NO WARRANTY
// Copyright 2025 TimeHexOn & foxhop & russell@unturf
// https://www.permacomputer.com


// Text-to-Speech Example using OpenAI Java Client

@Grapes([
    @Grab(group='com.openai', module='openai-java', version='4.2.0')
])

import com.openai.client.okhttp.OpenAIOkHttpClient
import com.openai.models.SpeechCreateParams
import java.nio.file.Files
import java.nio.file.Paths

def baseUrl = "https://speech.ai.unturf.com/v1"
def outputFile = "speech.mp3"

try {
    println "Generating speech from TTS...\n"

    // Create OpenAI client with custom base URL
    def client = OpenAIOkHttpClient.builder()
        .baseUrl(baseUrl)
        .apiKey("YOLO")
        .build()

    // Create TTS request
    def params = SpeechCreateParams.builder()
        .model(SpeechCreateParams.Model.TTS_1)
        .voice(SpeechCreateParams.Voice.ALLOY)
        .speed(0.9)
        .input("I think so therefore, Today is a wonderful day to grow something people love!")
        .build()

    // Generate speech and get response as bytes
    def response = client.audio().speech().create(params)

    // Write to file
    Files.write(Paths.get(outputFile), response.readAllBytes())

    println "Speech saved to: ${outputFile}"

} catch (Exception e) {
    println "Error: ${e.message}"
    e.printStackTrace()
}
