package com.yeejoin.amos.speech;

import okhttp3.Call;
import okhttp3.Callback;
import okhttp3.Response;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.io.File;
import java.io.IOException;
import java.util.HashMap;

/**
 * 录音文件识别极速版（支持提交音频文件识别，文件大小，文件时长有限制）
 * <p>
 * 音频格式：支持AAC/MP3/OPUS/WAV格式编码的音频。
 * 使用限制：支持100 MB以内且不超过2小时的音频文件的识别。
 *
 * @see SpeechRecognizer
 * 时长超过2小时的文件请使用录音文件识别普通版
 *
 * <p>
 * 模型类型：8000（电话）/16000（非电话）。
 * <p>
 * 同步返回识别结果
 */
public class SpeechFlashRecognizer {
    private static final Logger logger = LoggerFactory.getLogger(SpeechFlashRecognizer.class);
    //音频文件
    private final File speechFile;
    //音频格式
    private final String format;
    //音频采样率
    private final int sampleRate;
    //识别回调函数
    private final Callback callback;

    /**
     * 使用示例
     * 不支持试用，需要付费
     * 不支持试用，需要付费
     * 不支持试用，需要付费
     */
    public static void main(String[] args) {
        //String fileName = SpeechRecognizerRestfulDemo.class.getClassLoader().getResource("./nls-sample-16k.wav").getPath();
        // 重要：此处用一个本地文件来模拟发送实时流数据，实际使用时，您可以从某处实时采集或接收语音流并发送到ASR服务端。
        String fileName = "D:\\ffmpeg-4.4-full_build-shared\\bin\\test.mp3";
        String format = "mp3";
        int sampleRate = 16000;
        SpeechFlashRecognizer speechFlashRecognizer = new SpeechFlashRecognizer(new File(fileName), format, sampleRate, new Callback() {
            @Override
            public void onFailure(Call call, IOException e) {
                logger.error("语音识别失败，原因：" + e.getMessage());
            }

            @Override
            public void onResponse(Call call, Response response) throws IOException {
                assert response.body() != null;
                logger.warn("语音识别结果：" + response.body().string());
            }
        });
        speechFlashRecognizer.process();
    }

    public SpeechFlashRecognizer(File speechFile, String format, int sampleRate, Callback callback) {
        if (speechFile != null && speechFile.exists() && speechFile.isFile()) {
            throw new IllegalArgumentException("待识别的文件存在异常");
        }
        if (null == format || "".equals(format)) {
            throw new IllegalArgumentException("音频文件格式不能为空");
        }
        if (sampleRate == 0) {
            throw new IllegalArgumentException("音频采样率不能为0");
        }
        this.speechFile = speechFile;
        this.format = format;
        this.sampleRate = sampleRate;
        this.callback = callback;
    }

    /**
     * 设置HTTPS REST POST请求
     * 1.使用http协议
     * 2.语音识别服务域名：nls-gateway.cn-shanghai.aliyuncs.com
     * 3.语音识别接口请求路径：/stream/v1/FlashRecognizer
     * 4.设置必须请求参数：appkey、token、format、sample_rate
     * 5.Content-Type 类型必须为 application/octet-stream
     */
    public void process() {
        String request = "https://nls-gateway.cn-shanghai.aliyuncs.com/stream/v1/FlashRecognizer";
        request = request + "?appkey=" + SpeechConfig.AppKey;
        request = request + "&token=" + AppNslClientToken.instance().getToken();
        request = request + "&format=" + format;
        request = request + "&sample_rate=" + sampleRate;
        logger.info("Request: " + request);
        HashMap<String, String> headers = new HashMap<>();
        headers.put("Content-Type", "application/octet-stream");
        AppOkHttpClient.sendPostFile(request, headers, this.speechFile, this.callback);
    }
}