收藏本站,收获最前沿的人工智能与编程资讯!!

Spring AI 使用转录API

技术文档 13℃ 0


Spring AI 通过 TranscriptionModel 接口提供了统一的语音转文本转录API。这让你可以编写跨不同转录服务提供商兼容的可移植代码。

支持的服务提供商

OpenAI 的 Whisper API

Azure OpenAI Whisper API

通用接口

所有转录服务提供商都实现了以下共享接口:

TranscriptionModel

该接口提供了将音频转换为文本的方法:

public interface TranscriptionModel extends Model{

    /**
     * 转录来自给定提示词的音频。
     */
    AudioTranscriptionResponse call(AudioTranscriptionPrompt transcriptionPrompt);

    /**
     * 用于转录音频资源的便捷方法。
     */
    default String transcribe(Resource resource) {
        AudioTranscriptionPrompt prompt = new AudioTranscriptionPrompt(resource);
        return this.call(prompt).getResult().getOutput();
    }

    /**
     * 带配置选项的音频资源转录便捷方法。
     */
    default String transcribe(Resource resource, AudioTranscriptionOptions options) {
        AudioTranscriptionPrompt prompt = new AudioTranscriptionPrompt(resource, options);
        return this.call(prompt).getResult().getOutput();
    }
}

AudioTranscriptionPrompt

该类封装了输入音频和配置选项:

Resource audioFile = new FileSystemResource("/path/to/audio.mp3");
AudioTranscriptionPrompt prompt = new AudioTranscriptionPrompt(
    audioFile,
    options
);

AudioTranscriptionResponse

该类包含转录后的文本和元数据:

AudioTranscriptionResponse response = model.call(prompt);
String transcribedText = response.getResult().getOutput();
AudioTranscriptionResponseMetadata metadata = response.getMetadata();

编写与服务提供商无关的代码

共享转录接口的核心优势之一是能够编写无需修改即可适配任意转录服务提供商的代码。实际使用的提供商(OpenAI、Azure OpenAI等)由Spring Boot配置决定,你无需更改应用代码即可切换服务提供商。

基础服务示例

通过共享接口可以编写适配任意转录服务提供商的代码:

@Service
public class TranscriptionService {

    private final TranscriptionModel transcriptionModel;

    public TranscriptionService(TranscriptionModel transcriptionModel) {
        this.transcriptionModel = transcriptionModel;
    }

    public String transcribeAudio(Resource audioFile) {
        return transcriptionModel.transcribe(audioFile);
    }

    public String transcribeWithOptions(Resource audioFile, AudioTranscriptionOptions options) {
        AudioTranscriptionPrompt prompt = new AudioTranscriptionPrompt(audioFile, options);
        AudioTranscriptionResponse response = transcriptionModel.call(prompt);
        return response.getResult().getOutput();
    }
}

该服务可无缝适配OpenAI、Azure OpenAI或其他任意转录服务提供商,具体实现由Spring Boot配置决定。

服务提供商专属功能

共享接口提供了可移植性,同时每个服务提供商也通过专属配置选项类(如 OpenAiAudioTranscriptionOptionsAzureOpenAiAudioTranscriptionOptions)提供专属功能。这些类实现了 AudioTranscriptionOptions 接口,并扩展了服务提供商专属的能力。

有关服务提供商专属功能的详细信息,请参阅各提供商的独立文档页面。

相关推荐