package com.yn.bftl.thirdparty.modules.tencent.service.impl;

import com.tencentcloudapi.asr.v20190614.AsrClient;
import com.tencentcloudapi.asr.v20190614.models.SentenceRecognitionRequest;
import com.tencentcloudapi.asr.v20190614.models.SentenceRecognitionResponse;
import com.tencentcloudapi.common.exception.TencentCloudSDKException;
import com.tencentcloudapi.common.profile.HttpProfile;
import com.yn.bftl.common.common.exception.YnceError;
import com.yn.bftl.thirdparty.common.exception.YnceErrorException;
import com.yn.bftl.thirdparty.common.service.BaseMemberService;
import com.yn.bftl.thirdparty.modules.tencent.service.AsrService;
import com.yn.bftl.thirdparty.modules.tencent.util.TencentUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.Arrays;
import java.util.List;

/**
 * 语音识别服务实现
 *
 * @author huabiao
 * @create 2023/8/9  14:53
 **/
@Service
@Slf4j
public class AsrServiceImpl extends BaseMemberService implements AsrService {

    @Resource
    private TencentUtil tencentUtil;

    /**
     * 一句话识别支持的类型
     */
    private static List<String> supportRecognitionType = Arrays.asList("wav", "pcm", "ogg-opus", "speex", "silk", "mp3", "m4a", "aac", "amr");

    @Override
    public String sentenceRecognition(String url) {
        try {
            // 实例化要请求产品的client对象,clientProfile是可选的
            AsrClient client = new AsrClient(tencentUtil.getCredential(), "", tencentUtil.getClientProfile(HttpProfile.REQ_GET));
            // 实例化一个请求对象,每个接口都会对应一个request对象
            SentenceRecognitionRequest req = new SentenceRecognitionRequest();
            req.setEngSerViceType("16k_zh");
            req.setSourceType(0L);
            req.setUrl(url);
            // 判断识别类型
            String type = url.substring(url.lastIndexOf(".") + 1);
            if (!supportRecognitionType.contains(type)) {
                throw new YnceErrorException(YnceError.YNCE_222003);
            }
            req.setVoiceFormat(type);
            // 返回的resp是一个SentenceRecognitionResponse的实例，与请求对象对应
            SentenceRecognitionResponse sentenceRecognitionResponse = client.SentenceRecognition(req);
            return sentenceRecognitionResponse.getResult();
        } catch (TencentCloudSDKException e) {
            log.error("腾讯云[一句话识别]，错误码:{}，错误信息:{}", e.getErrorCode(), e.getMessage());
            throw new YnceErrorException(YnceError.YNCE_222002);
        }
    }
}
