From efc1a429493039d36cc78075fce974e6fa9e5eed Mon Sep 17 00:00:00 2001 From: 苗权威 <1160292058@qq.com> Date: Wed, 24 Jun 2020 20:11:20 +0800 Subject: [PATCH] 6.24 --- .idea/workspace.xml | 839 +++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- spirit/src/main/java/ai/qiwu/tmall/spirit/service/Test.java | 7 ++++++- spirit/src/main/java/ai/qiwu/tmall/spirit/spirit/SpiritAudioUpload.java | 67 +++++++++++++++++++++++++++++++++++++++++++++++++++++-------------- tts_service/src/main/java/ai/qiwu/com/tts_service/common/ApachHttpUtils.java | 113 ++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++------------- tts_service/src/main/java/ai/qiwu/com/tts_service/common/CallPython.java | 4 ++-- tts_service/src/main/java/ai/qiwu/com/tts_service/common/TTSUtils.java | 20 +++++++++----------- tts_service/src/main/java/ai/qiwu/com/tts_service/common/TTServiceUtil.java | 39 ++++++++++++++++++++++++++++++++++++++- tts_service/src/main/java/ai/qiwu/com/tts_service/controller/DeployController.java | 120 ++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++-------------- tts_service/src/main/java/ai/qiwu/com/tts_service/controller/TTSController.java | 84 ++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++------------------------ tts_service/src/main/java/ai/qiwu/com/tts_service/pojo/Dialog.java | 9 ++++++++- tts_service/src/main/java/ai/qiwu/com/tts_service/pojo/GeneralMP3Data.java | 2 +- tts_service/src/main/java/ai/qiwu/com/tts_service/pojo/TextInfo.java | 18 +++++++++++++++++- tts_service/src/main/java/ai/qiwu/com/tts_service/pojo/jmter/UserIdAndWord.java | 17 +++++++++++++++++ tts_service/src/main/java/ai/qiwu/com/tts_service/service/Initialize.java | 26 ++++++++++++++++++++++---- tts_service/src/main/java/ai/qiwu/com/tts_service/service/TTService.java | 38 +++++++++++++++++++++----------------- tts_service/src/main/java/ai/qiwu/com/tts_service/service/TTServiceEdition2.java | 1082 ++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ tts_service/src/main/java/ai/qiwu/com/tts_service/service/baidu/ThirdPartyService.java | 5 +++-- xiaoduhome/src/main/java/ai/qiwu/com/xiaoduhome/controller/XiaoAiController.java | 17 +++++++++++++++-- xiaoduhome/src/main/java/ai/qiwu/com/xiaoduhome/xiaoai/common/RequestTerminal.java | 5 +++++ 19 files changed, 1932 insertions(+), 580 deletions(-) create mode 100644 tts_service/src/main/java/ai/qiwu/com/tts_service/pojo/jmter/UserIdAndWord.java create mode 100644 tts_service/src/main/java/ai/qiwu/com/tts_service/service/TTServiceEdition2.java diff --git a/.idea/workspace.xml b/.idea/workspace.xml index cd95d75..0d44865 100644 --- a/.idea/workspace.xml +++ b/.idea/workspace.xml @@ -1,84 +1,27 @@ + + + - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - + + + + + - - + + + + - - - + + + @@ -116,93 +59,48 @@ - + - - - - - - - - - - - - - - - - - - - - - - - - - + + + + - - - - - - - - - - - - - - - - - - - - - - - - - + - - + + - + + + + - + - - - - - + + - - + + - - + + @@ -210,26 +108,15 @@ - - + + - - - + - - - - - - - - - @@ -242,26 +129,36 @@ - getOtherServerAddress - getAllProjects - jiaoyouChannel2Bots - BASE_HOST_URL - \\p{P} - progressFunction - _type - folder + tmpRequest fileName - Files.copy - StandardCopyOption - dealMp3UrlRequest - log - App.LOGGER - tmp_audio_name - THIRD_PARTY - Initialize.getThirdParty() - AUDIO_DIR - MapUtils.isNotEmpty - buildMp3ResponseForAudioCDN + particularPersonMoodUrl + httpClient + RandomAccessFile + transfer + getFromFutureAndGenerateB64File + redisKey + filePath + xiaoai + path + URLEncoder.encode + text + requestTemplate + 缓存 + 2 + stringRedisTemplate.opsForValue() + 5 + 1 + ffmpeg + generalMP3 + npcName + data + String rootFolderRoot = new StringBuilder(Initialize.getAudioDir()).append(File.separator).append(botName).append(File.separator).toString(); + String uploadFolderRoot = new StringBuilder(rootFolderRoot).append(Initialize.getUploadedDir()).append(File.separator).toString(); + 中控 + buildTTS_lsResponse + stringRedisTemplate + generalMP3 wav + targetFilepath log @@ -276,7 +173,6 @@ @@ -331,15 +239,6 @@ - - - - - - - - - @@ -532,7 +379,7 @@ - + @@ -553,13 +400,13 @@ - - - - - + - - + + - - + + @@ -832,7 +706,7 @@ - + @@ -843,11 +717,11 @@ - + - + @@ -857,416 +731,437 @@ - + + + + + + + + - - + + - + - + - + - - + + - + - - + + + + + - + - - + + - + - - + + + + + + - + - - + + - - + + - + - - + + - + - - + + - + - + - - + + - - - - - - - - + - - + + - + - - + + - + - - + + - - - - + + - + - - + + + + + - + - - + + - + - - - - - - - - + + - + - - + + - + - + - - + + - + - - + + + + + - + - - + + - + - - + + - + - - + + - + - + - + - - + + - + - - + + + + + + - + - - - - - - - + + - + - - + + - + - - + + - + - - + + + + + - + - - + + - + - - + + - - + + - + - - + + - - + + - + - - + + - + - - + + - + - - + + - + - - + + - - - - + + + - + - - + + + + + - + - - + + + + + + - + - - + + - + - - - - - - - + + - + - - - - - + + - + - - + + - + - - + + - + + + + - + - - + + + + - + - - + + - - - - - - - - - - - - + + + + + + + + + + + + + + + + - - + + + + + + + + + diff --git a/spirit/src/main/java/ai/qiwu/tmall/spirit/service/Test.java b/spirit/src/main/java/ai/qiwu/tmall/spirit/service/Test.java index b73d598..aca6adb 100644 --- a/spirit/src/main/java/ai/qiwu/tmall/spirit/service/Test.java +++ b/spirit/src/main/java/ai/qiwu/tmall/spirit/service/Test.java @@ -47,6 +47,11 @@ public class Test { } public static void main(String[] args) throws IOException { - testTts("/home/yf01/下载/SpiritAudioCsv/ttsLog/access_log.2020-01-05.log"); + String src = "/home/yf01/下载/yace/data/datum_"; + String dst = "/home/yf01/data901_1200/datum_"; + Files.createDirectories(Paths.get("/home/yf01/data901_1200")); + for (int i = 1; i <= 300; i++) { + Files.copy(Paths.get(src+(900+i)+".csv"), Paths.get(dst+i+".csv")); + } } } diff --git a/spirit/src/main/java/ai/qiwu/tmall/spirit/spirit/SpiritAudioUpload.java b/spirit/src/main/java/ai/qiwu/tmall/spirit/spirit/SpiritAudioUpload.java index 1536e75..e9e8ef0 100644 --- a/spirit/src/main/java/ai/qiwu/tmall/spirit/spirit/SpiritAudioUpload.java +++ b/spirit/src/main/java/ai/qiwu/tmall/spirit/spirit/SpiritAudioUpload.java @@ -1207,20 +1207,59 @@ public class SpiritAudioUpload { return ApachHttpUtils.getProbe(path, headers); } + private static void jmeter(List recommendWordList, CSVPrinter csvPrinter, String uid, List keyList, + int index, int botCount, Map openMap) throws IOException { + Collections.shuffle(recommendWordList); + for (int j = 0; j < 10; j++) { + csvPrinter.printRecord(uid, recommendWordList.get(j)); + } + String openBot = keyList.get(index%botCount); + csvPrinter.printRecord(uid, openBot); + String openBotPath = "/home/yf01/下载/yace/"+openMap.get(openBot); + try (CSVParser botReader = CSVFormat.EXCEL.parse(new BufferedReader(new InputStreamReader( + new FileInputStream(openBotPath), Charset.forName("UTF-8"))))){ + String word; + for (CSVRecord line: botReader) { + word = line.get(0); + csvPrinter.printRecord(uid, StringUtils.isBlank(word) ? "是的":word); + } + } + csvPrinter.printRecord(uid, "退出当前作品"); + } + public static void main(String[] args) throws IOException { - Map headers = new HashMap<>(); - headers.put("Accept", "application/json"); - headers.put("Accept-Encoding", "gzip, deflate, br"); - headers.put("Connection", "keep-alive"); - headers.put("content-type", "application/json"); - headers.put("Cookie", cookie); - headers.put("Host", "open.aligenie.com"); - headers.put("Referer", "https://open.aligenie.com/console/skill/"+45894+"/audiolist"); - headers.put("TE", "Trailers"); - headers.put("Token", token);//token - headers.put("User-Agent", "Mozilla/5.0 (X11; Ubuntu; Linux x86_64; rv:70.0) Gecko/20100101 Firefox/70.0"); - headers.put("x-csrf-token", csrfToken); // ctoken - String result = ApachHttpUtils.get("https://open.aligenie.com/api/oss/credentials", headers, new HashMap<>()); - System.out.println(result); + List recommendWordList = new ArrayList<>(); + Map openMap = new HashMap<>(); + try (CSVParser recommendReader = CSVFormat.EXCEL.parse(new BufferedReader(new InputStreamReader( + new FileInputStream("/home/yf01/下载/yace/recommand.csv"), Charset.forName("UTF-8")))); + CSVParser openReader = CSVFormat.EXCEL.parse(new BufferedReader(new InputStreamReader( + new FileInputStream("/home/yf01/下载/yace/open.csv"), Charset.forName("UTF-8"))))){ + for (CSVRecord line: recommendReader) { + recommendWordList.add(line.get(0)); + } + for (CSVRecord line: openReader) { + openMap.put(line.get(0), line.get(1)); + } + + String uid; + CSVFormat format; + int index = 0; + int botCount = openMap.size(); + List keyList = new ArrayList<>(openMap.keySet()); + for (int i = 1; i <= 3000; i++) { + uid = RandomStringUtils.random(10, true, true)+"_"+i; + format = CSVFormat.DEFAULT.withHeader(uid, "word"); + try (CSVPrinter csvPrinter = new CSVPrinter(new OutputStreamWriter( + new FileOutputStream("/home/yf01/下载/yace/data/datum_"+i+".csv", true), Charset.forName("UTF-8")),format)) { + for (int j = 0; j < 20; j++) { + jmeter(recommendWordList, csvPrinter, uid, keyList, index+j, botCount, openMap); + } + csvPrinter.printRecord(uid, "退出"); + index++; + } + } + } catch (Exception e) { + e.printStackTrace(); + } } } diff --git a/tts_service/src/main/java/ai/qiwu/com/tts_service/common/ApachHttpUtils.java b/tts_service/src/main/java/ai/qiwu/com/tts_service/common/ApachHttpUtils.java index 42ba733..bfbc70a 100644 --- a/tts_service/src/main/java/ai/qiwu/com/tts_service/common/ApachHttpUtils.java +++ b/tts_service/src/main/java/ai/qiwu/com/tts_service/common/ApachHttpUtils.java @@ -20,6 +20,7 @@ import org.apache.http.entity.StringEntity; import org.apache.http.entity.mime.HttpMultipartMode; import org.apache.http.entity.mime.MultipartEntityBuilder; import org.apache.http.impl.client.CloseableHttpClient; +import org.apache.http.impl.client.DefaultHttpRequestRetryHandler; import org.apache.http.impl.client.HttpClients; import org.apache.http.impl.conn.PoolingHttpClientConnectionManager; import org.apache.http.impl.nio.client.CloseableHttpAsyncClient; @@ -35,10 +36,11 @@ import org.apache.http.util.EntityUtils; import org.springframework.util.CollectionUtils; import javax.servlet.http.HttpServletResponse; -import java.io.BufferedReader; -import java.io.IOException; -import java.io.InputStreamReader; +import java.io.*; import java.net.URISyntaxException; +import java.nio.channels.Channels; +import java.nio.channels.FileChannel; +import java.nio.channels.ReadableByteChannel; import java.nio.charset.Charset; import java.nio.charset.StandardCharsets; import java.nio.file.Files; @@ -49,6 +51,7 @@ import java.util.List; import java.util.Map; import java.util.concurrent.ConcurrentHashMap; import java.util.concurrent.Future; +import java.util.concurrent.Semaphore; /** * @author 苗权威 @@ -74,6 +77,7 @@ public class ApachHttpUtils { httpClient = HttpClients.custom() .setConnectionManager(connManager) + .setRetryHandler(new DefaultHttpRequestRetryHandler(4, false)) .setDefaultRequestConfig(requestConfig) .build(); } @@ -242,9 +246,52 @@ public class ApachHttpUtils { } } - public static Future asyncFileDataDownloadGet(String url, Map params, - Map headers, String tarPath, - ConcurrentHashMap recordAlreadyFineSlice) { + public static Boolean audioSliceGet(String url, Map params, + Map headers, String tarPath) { + try { + URIBuilder builder = new URIBuilder(url, StandardCharsets.UTF_8); + if (!CollectionUtils.isEmpty(params)) { + List list = new ArrayList<>(); + BasicNameValuePair param; + for (Map.Entry entry: params.entrySet()) { + param = new BasicNameValuePair(entry.getKey(), entry.getValue()); + list.add(param); + } + builder.setParameters(list); + } + HttpGet httpGet = new HttpGet(builder.build()); + if (!CollectionUtils.isEmpty(headers)) { + for (Map.Entry entry:headers.entrySet()) { + httpGet.setHeader(entry.getKey(), entry.getValue()); + } + } + RequestConfig requestConfig = RequestConfig.custom() + .setConnectionRequestTimeout(3000) + .setSocketTimeout(300000) + .setConnectTimeout(300000).build(); + httpGet.setConfig(requestConfig); + try (CloseableHttpResponse response = getHttpClient().execute(httpGet)){ + int status = response.getStatusLine().getStatusCode();//获取返回状态值 + if (status == HttpServletResponse.SC_OK) { + HttpEntity httpEntity = response.getEntity(); + if(httpEntity != null){ + byte[] bytes = EntityUtils.toByteArray(httpEntity); + log.error("同步获取分片文件数据成功:"+tarPath); + Files.write(Paths.get(tarPath), bytes, StandardOpenOption.WRITE, StandardOpenOption.CREATE_NEW); + EntityUtils.consume(httpEntity);//关闭资源 + return true; + } + } + } + } catch (Exception e) { + log.error(ExceptionUtils.getStackTrace(e)); + } + return false; + } + + public static Future asyncFileDataDownloadGet(String url, Map params, Map headers, + String tarPath, ConcurrentHashMap recordAlreadyFineSlice, + Semaphore semaphore) { try { URIBuilder builder = new URIBuilder(url, StandardCharsets.UTF_8); if (!CollectionUtils.isEmpty(params)) { @@ -264,8 +311,8 @@ public class ApachHttpUtils { } RequestConfig requestConfig = RequestConfig.custom() .setConnectionRequestTimeout(60000) - .setSocketTimeout(480000) - .setConnectTimeout(60000).build(); + .setSocketTimeout(300000) + .setConnectTimeout(300000).build(); httpGet.setConfig(requestConfig); FutureCallback callback = new FutureCallback() { @@ -277,9 +324,10 @@ public class ApachHttpUtils { if(httpEntity != null){ try { byte[] bytes = EntityUtils.toByteArray(httpEntity); - log.error("异步获取分片文件数据成功:"+tarPath); +// log.error("异步获取分片文件数据成功:{}",tarPath); Files.write(Paths.get(tarPath), bytes, StandardOpenOption.WRITE, StandardOpenOption.CREATE_NEW); - recordAlreadyFineSlice.put(tarPath, true); + recordAlreadyFineSlice.put(tarPath, "success"); + semaphore.release(); } catch (IOException e) { log.error("asyncFileDataDownloadGet error:"+e); } @@ -289,7 +337,9 @@ public class ApachHttpUtils { @Override public void failed(Exception e) { - log.error("异步get失败:"+e); + recordAlreadyFineSlice.put(tarPath, "failure"); + semaphore.release(); + log.error("异步get失败:{},PATH:{}",e, tarPath); } @Override @@ -420,8 +470,8 @@ public class ApachHttpUtils { } RequestConfig requestConfig = RequestConfig.custom() .setConnectionRequestTimeout(3000) - .setSocketTimeout(3000) - .setConnectTimeout(3000).build(); + .setSocketTimeout(600000) + .setConnectTimeout(600000).build(); httpGet.setConfig(requestConfig); try (CloseableHttpResponse response = getHttpClient().execute(httpGet)){ int status = response.getStatusLine().getStatusCode();//获取返回状态值 @@ -480,4 +530,41 @@ public class ApachHttpUtils { } return null; } + + public static Integer audioPost(String url, String jsonString, String path) { + HttpPost httpPost = new HttpPost(url); + RequestConfig requestConfig = RequestConfig.custom() + .setConnectTimeout(10000) + .setConnectionRequestTimeout(10000) + .setSocketTimeout(60000).build(); + httpPost.setConfig(requestConfig); + httpPost.addHeader("Content-type", "application/json"); + httpPost.setEntity(new StringEntity(jsonString, ContentType.APPLICATION_JSON)); + try(CloseableHttpResponse response = getHttpClient().execute(httpPost)) { + Integer status; + if ((status=response.getStatusLine().getStatusCode()) == HttpServletResponse.SC_OK) { + HttpEntity httpEntity = response.getEntity(); + byte[] bytes = EntityUtils.toByteArray(httpEntity); + log.info("audioPost path:{},bytes:{}",path, bytes.length); + Files.write(Paths.get(path), bytes, StandardOpenOption.WRITE, StandardOpenOption.CREATE_NEW); + EntityUtils.consume(httpEntity); + } + return status; + +// try (InputStream stream = response.getEntity().getContent(); +// FileChannel fileChannel = new RandomAccessFile(path, "rw").getChannel()){ +// long count = stream.available(); +// ReadableByteChannel fromChannel = Channels.newChannel(stream); +// System.out.println("audioPost=======:"+count+",path="+path+",url:"+url+",jsonurl:"+jsonString); +// fileChannel.transferFrom(fromChannel, 0, count); +// return HttpServletResponse.SC_OK; +// } catch (IOException e) { +// log.error("audioPost error:"+e); +// return 500; +// } + } catch (IOException e) { + log.error("audioPost error2:"+e); + } + return 0; + } } diff --git a/tts_service/src/main/java/ai/qiwu/com/tts_service/common/CallPython.java b/tts_service/src/main/java/ai/qiwu/com/tts_service/common/CallPython.java index 712b7cd..c67f8ce 100755 --- a/tts_service/src/main/java/ai/qiwu/com/tts_service/common/CallPython.java +++ b/tts_service/src/main/java/ai/qiwu/com/tts_service/common/CallPython.java @@ -124,7 +124,7 @@ public class CallPython { return "1"; } - public static String ffmpegExecute(String arg) { + static String ffmpegExecute(String arg) { ProcessBuilder processBuilder = new ProcessBuilder(arg.split(" ")); processBuilder.redirectErrorStream(true); //错误输出流合并到标准输出流中 StringBuilder builder = new StringBuilder(); @@ -143,7 +143,7 @@ public class CallPython { log.error("ffmpeg执行出错:{}",builder.toString()); return "0"; } - }else { + } else { while ((line = reader.readLine()) != null) { // builder.append(line); } diff --git a/tts_service/src/main/java/ai/qiwu/com/tts_service/common/TTSUtils.java b/tts_service/src/main/java/ai/qiwu/com/tts_service/common/TTSUtils.java index 8be7b90..25d18f6 100755 --- a/tts_service/src/main/java/ai/qiwu/com/tts_service/common/TTSUtils.java +++ b/tts_service/src/main/java/ai/qiwu/com/tts_service/common/TTSUtils.java @@ -19,10 +19,7 @@ import java.io.*; import java.nio.channels.FileLock; import java.nio.charset.Charset; import java.nio.charset.StandardCharsets; -import java.nio.file.Files; -import java.nio.file.Path; -import java.nio.file.Paths; -import java.nio.file.StandardOpenOption; +import java.nio.file.*; import java.text.Normalizer; import java.util.*; import java.util.regex.Matcher; @@ -388,12 +385,13 @@ public class TTSUtils { if (file.exists()) { //log.info("文件:{},大小为:{}", filePath, file.length()); if (file.length() == 0) { - if (file.delete()) { - log.info("大小为0的文件:{}, 删除成功",filePath); - } else { - log.info("大小为0的文件:{}, 删除失败",filePath); - } - return false; + log.info("大小为0的文件:{}",filePath); +// if (file.delete()) { +// log.info("大小为0的文件:{}, 删除成功",filePath); +// } else { +// log.info("大小为0的文件:{}, 删除失败",filePath); +// } +// return false; } return true; } @@ -539,7 +537,7 @@ public class TTSUtils { // String command = "sox "+ StringUtils.join(filePathList, " "); if (filePathList.size() == 1) { String[] arr = filePathList.toArray(new String[]{}); - Files.copy(Paths.get(arr[0]), Paths.get(targetFilepath)); + Files.copy(Paths.get(arr[0]), Paths.get(targetFilepath), StandardCopyOption.REPLACE_EXISTING); } else { List str = filePathList.stream().map(s -> "-i "+s).collect(Collectors.toList()); StringBuilder builder = new StringBuilder("ffmpeg ").append(StringUtils.join(str, " ")).append(" -filter_complex "); diff --git a/tts_service/src/main/java/ai/qiwu/com/tts_service/common/TTServiceUtil.java b/tts_service/src/main/java/ai/qiwu/com/tts_service/common/TTServiceUtil.java index 2bd6cc0..189656f 100755 --- a/tts_service/src/main/java/ai/qiwu/com/tts_service/common/TTServiceUtil.java +++ b/tts_service/src/main/java/ai/qiwu/com/tts_service/common/TTServiceUtil.java @@ -136,6 +136,43 @@ public class TTServiceUtil { } } + public static void buildTTSMp3Response(HttpServletResponse response, MP3Response mp3Response, String fileName, int status, boolean fileType) { + response.reset(); + response.setStatus(status); + if (mp3Response != null) { + String ttsResJsonStr = JSON.toJSONString(mp3Response); + response.setCharacterEncoding("UTF-8"); + response.setContentType("application/json;charset=utf-8"); + try (PrintWriter out = response.getWriter()){ + out.append(ttsResJsonStr); + out.flush(); + } catch (Exception e) { + log.error("buildTTSMp3Response():获取PrintWriter出错:{}",e.toString()); + } + } else { + try (WritableByteChannel outChannel = Channels.newChannel(response.getOutputStream()); + FileChannel fileChannel = new RandomAccessFile(fileName, "r").getChannel()){ + long size; + response.setContentType("audio/mp3"); + response.setHeader("Content-Length", String.valueOf((size=fileChannel.size()))); + response.setHeader("Cache-Control", "max-age=43200, public"); + if (fileType) { + String loadName = fileName.substring(fileName.lastIndexOf("/")+1).trim(); + if (StringUtils.isBlank(loadName)) { + loadName = String.valueOf(System.currentTimeMillis()); + } + String value = String.format("attachment;filename=\"%s\"", loadName); + response.setHeader("Content-Disposition", value); + } + fileChannel.transferTo(0, size, outChannel); + } catch (ClientAbortException e) { + + } catch (IOException e) { + log.error("buildTTSMp3Response:写入音频流到HttpServletResponse失败:{}", e.toString()); + } + } + } + public static void buildMp3ResponseForAudioNoRange(HttpServletResponse response, String fileName, Boolean xiaoai) { try (BufferedInputStream inputStream = new BufferedInputStream(new FileInputStream(fileName)); @@ -311,7 +348,7 @@ public class TTServiceUtil { out.append(ttsResJsonStr); out.flush(); } catch (Exception e) { - log.error("buildTTS_lsResponse():获取PrintWriter出错:{}",e.toString()); + log.error("buildTTS_lsResponse():获取PrintWriter出错:{}",ExceptionUtils.getStackTrace(e)); } } diff --git a/tts_service/src/main/java/ai/qiwu/com/tts_service/controller/DeployController.java b/tts_service/src/main/java/ai/qiwu/com/tts_service/controller/DeployController.java index b7b01c3..1c738ac 100644 --- a/tts_service/src/main/java/ai/qiwu/com/tts_service/controller/DeployController.java +++ b/tts_service/src/main/java/ai/qiwu/com/tts_service/controller/DeployController.java @@ -2,8 +2,14 @@ package ai.qiwu.com.tts_service.controller; import ai.qiwu.com.tts_service.common.ApachHttpUtils; import ai.qiwu.com.tts_service.common.FileUtil; +import ai.qiwu.com.tts_service.service.Initialize; +import ai.qiwu.com.tts_service.service.TTService; +import lombok.RequiredArgsConstructor; import lombok.extern.slf4j.Slf4j; import org.apache.commons.lang3.RandomStringUtils; +import org.apache.commons.lang3.StringUtils; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.data.redis.core.StringRedisTemplate; import org.springframework.web.bind.annotation.GetMapping; import org.springframework.web.bind.annotation.RequestHeader; import org.springframework.web.bind.annotation.RequestMapping; @@ -14,10 +20,12 @@ import java.io.IOException; import java.io.RandomAccessFile; import java.nio.channels.FileChannel; import java.nio.file.Files; +import java.nio.file.Path; import java.nio.file.Paths; import java.util.HashMap; import java.util.Map; import java.util.concurrent.ConcurrentHashMap; +import java.util.concurrent.Semaphore; /** * painter @@ -26,59 +34,143 @@ import java.util.concurrent.ConcurrentHashMap; @RestController @RequestMapping("/upload") @Slf4j +@RequiredArgsConstructor(onConstructor_ = { @Autowired}) public class DeployController { @GetMapping("/syn/download") - public void synSysImgTargetServerDown(Long length, String path, String sourceServer,String zipDir,String targetDir, - @RequestHeader("Authorization") String auth) { -// log.error("/upload/syn/download 开始"); + public String synSysImgTargetServerDownInThread(Long length, String path, String sourceServer,String zipDir, + String targetDir, String type, @RequestHeader("Authorization") String auth) { + if (StringUtils.startsWith(zipDir, ".")) { + log.warn("zipDir start with ."); + return "failure"; + } + if ("image_deploy".equals(type) && StringUtils.startsWith(zipDir, "/var/www/html/Editor")) { + log.warn("image deploy param wrong:zipDir -> "+zipDir); + return "failure"; + } + String botAccount = path.substring(path.lastIndexOf(File.separator)+1, path.length()-4); + String markPath = zipDir+ File.separator+botAccount+".csv"; + try { + Path pt; + Files.createDirectories((pt=Paths.get(markPath)).getParent()); + Files.createFile(pt); + } catch (IOException e) { + log.error("mark file create fail:{}, botAccount:{},path:{}",e,botAccount,path); + return "failure"; + } + TTService.POOL.submit(() -> synSysImgTargetServerDown(length, path, sourceServer, zipDir, + targetDir, auth, botAccount,type)); + return "success"; + } + + private void synSysImgTargetServerDown(Long length, String path, String sourceServer,String zipDir,String targetDir, + String auth, String botAccount, String type) { + log.info("/upload/syn/download 开始:"+path); long startTime = System.currentTimeMillis(); - int sliceSize = 5*1024*1024; + int sliceSize = 6*1024*1024; long start = 0, end = sliceSize-1; sourceServer += "/upload/range/download"; Map params = new HashMap<>(); params.put("path", path); + params.put("pass", "mqw"+RandomStringUtils.random(3)); + params.put("serverName", Initialize.getServerName()); Map headers = new HashMap<>(); headers.put("Authorization", auth); - String tempSliceName = zipDir+ File.separator+ RandomStringUtils.randomAlphabetic(5)+"_"; + String prefix = RandomStringUtils.randomAlphabetic(5); + String tempSliceName = zipDir+ File.separator+ prefix+"_"; try { Files.createDirectories(Paths.get(zipDir)); int i = 1; - ConcurrentHashMap recordAlreadyFineSlice = new ConcurrentHashMap<>(); + ConcurrentHashMap recordAlreadyFineSlice = new ConcurrentHashMap<>(); + Semaphore semaphore = new Semaphore(6); while (start < length) { if (end >= length-1) headers.put("Range", "bytes="+start+"-"); else headers.put("Range", "bytes="+start+"-"+end); -// log.error("发送分片请求:"+start); - ApachHttpUtils.asyncFileDataDownloadGet(sourceServer, params, headers, tempSliceName+i++, recordAlreadyFineSlice); + try { + semaphore.acquire(); + ApachHttpUtils.asyncFileDataDownloadGet(sourceServer, params, headers, + tempSliceName+i++, recordAlreadyFineSlice,semaphore); + } catch (InterruptedException e) { + log.warn("semaphore error:"+e); + } start = end+1; end += sliceSize; } - log.error("耗时:"+(System.currentTimeMillis()-startTime)); FileChannel toChannel = new RandomAccessFile(tempSliceName+".zip", "rw").getChannel(); String slice; + String res; for (int j = 1; j < i; j++) { slice = tempSliceName+j; int num = 0; - while (!recordAlreadyFineSlice.containsKey(slice) && num < 5000) { + while ((res = recordAlreadyFineSlice.get(slice)) == null && num < 180) { + log.info("休眠于:"+slice+"-"+num); try { - Thread.sleep(200); + Thread.sleep(1000); } catch (InterruptedException e) { // do nothing } ++num; } + if (res == null) { + log.error("180s仍未获取到响应信息"); + deleteSlice(zipDir, prefix, botAccount); + params.put("result", "failure"); + ApachHttpUtils.asyncDelete(sourceServer, params, headers); + return; + } + if ("failure".equals(res)) { + int count = 0; + boolean success; + do { + int numbers = Integer.parseInt(slice.substring(6)); + end = numbers*sliceSize-1; + start = end-sliceSize+1; + if (end >= length) end = length-1; + headers.put("Range", "bytes="+start+"-"+end); + success = ApachHttpUtils.audioSliceGet(sourceServer, params, headers, slice); + count++; + if (!success) log.error("第{}次同步获取分片文件数据失败, path:{}",count,slice); + } while (!success && count < 10); + if (!success) { + params.put("result", "failure"); + ApachHttpUtils.asyncDelete(sourceServer, params, headers); + return; + } + } FileChannel fromChannel = new RandomAccessFile(slice, "r").getChannel(); fromChannel.transferTo(0, fromChannel.size(), toChannel); fromChannel.close(); } + log.error("耗时:"+(System.currentTimeMillis()-startTime)); toChannel.close(); - FileUtil.deleteFile(new File(targetDir)); + if ("audio".equals(targetDir)) FileUtil.deleteFile(new File(targetDir)); FileUtil.decompress(tempSliceName+".zip", targetDir); - FileUtil.deleteFile(new File(zipDir)); - params.put("pass", "mqw"+RandomStringUtils.random(3)); + deleteSlice(zipDir, prefix, botAccount); + params.put("result", "success"); ApachHttpUtils.asyncDelete(sourceServer, params, headers); } catch (IOException e) { + deleteSlice(zipDir, prefix, botAccount); + params.put("result", "failure"); + ApachHttpUtils.asyncDelete(sourceServer, params, headers); log.error("分段下载出错:"+e); } } + + private void deleteSlice(String zipDir, String prefix, String botAccount) { + try { + Files.list(Paths.get(zipDir)) + .filter(path1 -> StringUtils.startsWithAny(path1.getFileName().toString(), prefix, botAccount) + && !StringUtils.startsWith(path1.toAbsolutePath().toString(), "/root/TTS-service/audio")) + .forEach(path1 -> { + try { + Files.deleteIfExists(path1); + } catch (IOException e) { + // do nothing + log.warn("分片文件删除出错:{},prefix:{},botAccount:{}",e, prefix, botAccount); + } + }); + } catch (IOException e) { + log.error("分片文件删除出错ss:{},prefix:{},botAccount:{}",e, prefix, botAccount); + } + } } diff --git a/tts_service/src/main/java/ai/qiwu/com/tts_service/controller/TTSController.java b/tts_service/src/main/java/ai/qiwu/com/tts_service/controller/TTSController.java index be31188..4ab99a0 100755 --- a/tts_service/src/main/java/ai/qiwu/com/tts_service/controller/TTSController.java +++ b/tts_service/src/main/java/ai/qiwu/com/tts_service/controller/TTSController.java @@ -3,15 +3,12 @@ package ai.qiwu.com.tts_service.controller; import ai.qiwu.com.tts_service.common.TTSUtils; import ai.qiwu.com.tts_service.pojo.*; import ai.qiwu.com.tts_service.pojo.upload.UploadOneSenData; -import ai.qiwu.com.tts_service.service.Initialize; -import ai.qiwu.com.tts_service.service.LieHuSchedule; -import ai.qiwu.com.tts_service.service.TTService; -import ai.qiwu.com.tts_service.service.TtsLsService; -import ai.qiwu.com.tts_service.service.cdn.CdnService; +import ai.qiwu.com.tts_service.service.*; import lombok.extern.slf4j.Slf4j; import org.apache.commons.lang3.StringUtils; import org.apache.commons.lang3.exception.ExceptionUtils; import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.data.redis.core.StringRedisTemplate; import org.springframework.web.bind.annotation.*; import org.springframework.web.multipart.MultipartFile; import org.springframework.web.multipart.MultipartHttpServletRequest; @@ -20,9 +17,15 @@ import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import java.io.File; +import java.io.IOException; import java.io.UnsupportedEncodingException; import java.net.URLDecoder; import java.net.URLEncoder; +import java.nio.file.Files; +import java.nio.file.Paths; +import java.nio.file.StandardCopyOption; +import java.util.regex.Matcher; +import java.util.regex.Pattern; /** @@ -40,16 +43,22 @@ public class TTSController { */ private final TTService ttService; - private final TtsLsService ttsLsService; +// private final TtsLsService ttsLsService; + + private final TTServiceEdition2 ttServiceEdition2; private final LieHuSchedule lieHuSchedule; // private final CdnService cdnService; @Autowired - public TTSController(TTService ttService, TtsLsService ttsLsService, LieHuSchedule lieHuSchedule) { + private StringRedisTemplate stringRedisTemplate; + + @Autowired + public TTSController(TTService ttService, TTServiceEdition2 ttServiceEdition2, LieHuSchedule lieHuSchedule) { this.ttService = ttService; - this.ttsLsService = ttsLsService; +// this.ttsLsService = ttsLsService; + this.ttServiceEdition2 = ttServiceEdition2; this.lieHuSchedule = lieHuSchedule; } @@ -93,7 +102,8 @@ public class TTSController { @RequestParam(required = false) String pitch, @RequestParam(required = false) String speed, @RequestParam(required = false) Boolean get_online, @RequestParam(required = false) String npcName,HttpServletResponse servletResponse) { TTSRequest ttsRequest = new TTSRequest(person, text, _type, pitch, tone, botname, volume, speed,get_online,npcName); - ttService.tts(ttsRequest, "GET", servletResponse); +// ttService.tts(ttsRequest, "GET", servletResponse); + ttServiceEdition2.tts(ttsRequest, "GET", servletResponse); } /** @@ -105,7 +115,8 @@ public class TTSController { public void tts_post(@RequestBody TTSRequest ttsRequest, HttpServletResponse response) { // String remoteAddr = request.getRemoteAddr(); // if (!TTS_REMOTE_ADDR.equals(remoteAddr) && !TTS_REMOTE_ADDR.equals(remoteAddr)) - ttService.tts(ttsRequest, "POST", response); +// ttService.tts(ttsRequest, "POST", response); + ttServiceEdition2.tts(ttsRequest, "POST", response); } /** @@ -115,7 +126,8 @@ public class TTSController { */ @PutMapping("/api/tts") public void tts_put(@RequestBody TTSRequest ttsRequest,HttpServletResponse response) { - ttService.tts(ttsRequest, "PUT", response); +// ttService.tts(ttsRequest, "PUT", response); + ttServiceEdition2.tts(ttsRequest, "PUT", response); } /** @@ -127,7 +139,8 @@ public class TTSController { public void tts_ls(@RequestBody TTSLSRequest request, HttpServletResponse response) { // long start = System.currentTimeMillis(); try { - ttsLsService.tts_ls(request, response); +// ttsLsService.tts_ls(request, response); + ttServiceEdition2.tts_ls(request, response); } catch (Exception e) { response.setStatus(500); log.error(ExceptionUtils.getStackTrace(e)); @@ -240,7 +253,7 @@ public class TTSController { @PostMapping("/api/audio") public String apiAudio(@RequestBody ApiAudioData data) { - return ttService.apiAudio(data); + return ttServiceEdition2.apiAudio(data); } @GetMapping("/api/audio/get") @@ -256,14 +269,32 @@ public class TTSController { ttService.cdnAudioGet(filename, exist, response); } - @PostMapping("/api/update/xiaoai") - public void xiaoaiCallbackUpdate(String callbackUrl, String secret) { - if ("mqwXiaoAi.".equals(secret) && StringUtils.isNotBlank(callbackUrl) && callbackUrl.contains("xiaoai/audio/play")) { - Initialize.audioUrl = callbackUrl; - log.warn("小爱回调地址更新:"+callbackUrl); - } + @GetMapping("/api/audio/tts") + public void apiTTSAudioGet(@RequestParam(required = false) Integer exist, @RequestParam(required = false) String _type, + @RequestParam String filename, HttpServletResponse response) { + ttServiceEdition2.ttsAudioGet(filename, exist, _type, response); } +// @GetMapping("/api/audio/test") +// public String audioTestRedis(String key, Integer type) { +// if (type == null) { +// String s = stringRedisTemplate.opsForValue().get(key); +// System.out.println("file exist:"+Files.exists(Paths.get(s))); +// System.out.println(s); +// log.info(s); +// return s; +// } +// return "0"; +// } + +// @PostMapping("/api/update/xiaoai") +// public void xiaoaiCallbackUpdate(String callbackUrl, String secret) { +// if ("mqwXiaoAi.".equals(secret) && StringUtils.isNotBlank(callbackUrl) && callbackUrl.contains("xiaoai/audio/play")) { +// Initialize.audioUrl = callbackUrl; +// log.warn("小爱回调地址更新:"+callbackUrl); +// } +// } + // @GetMapping("/api/audio/purge") // public void activePurge() { // cdnService.getPurgeState(); @@ -279,10 +310,15 @@ public class TTSController { // return cdnService.getDirPugeState(botAccount); // } - public static void main(String[] args) throws UnsupportedEncodingException { - String s = "test^sggs^a收费剧情123^愿意付费^"; - String ss; - System.out.println((ss=URLEncoder.encode(s, "utf-8"))); - System.out.println(URLDecoder.decode(ss, "utf-8")); + public static void main(String[] args) throws IOException { + String path = "/home/yf01/下载/yace/data/datum_"; + String targetPath = "/home/yf01/data601_900/datum_"; + Files.createDirectories(Paths.get("/home/yf01/data601_900")); + String s; + for (int i = 1; i <= 300; i++) { + s = path+(600+i)+".csv"; + Files.copy(Paths.get(s), Paths.get(targetPath+i+".csv"), StandardCopyOption.REPLACE_EXISTING); + } } + } diff --git a/tts_service/src/main/java/ai/qiwu/com/tts_service/pojo/Dialog.java b/tts_service/src/main/java/ai/qiwu/com/tts_service/pojo/Dialog.java index 86a116a..fc7398a 100644 --- a/tts_service/src/main/java/ai/qiwu/com/tts_service/pojo/Dialog.java +++ b/tts_service/src/main/java/ai/qiwu/com/tts_service/pojo/Dialog.java @@ -3,6 +3,9 @@ package ai.qiwu.com.tts_service.pojo; import lombok.Getter; import lombok.Setter; import lombok.ToString; +import org.apache.commons.lang3.StringUtils; + +import java.io.File; /** * @author 苗权威 @@ -10,7 +13,6 @@ import lombok.ToString; */ @Getter @Setter -@ToString public class Dialog { private String botAccount; private String npcName; @@ -20,4 +22,9 @@ public class Dialog { private String pitch; private String speed; private String volume; + + @Override + public String toString() { + return StringUtils.join(new String[]{botAccount,npcName,person,tone,text}, File.separator); + } } diff --git a/tts_service/src/main/java/ai/qiwu/com/tts_service/pojo/GeneralMP3Data.java b/tts_service/src/main/java/ai/qiwu/com/tts_service/pojo/GeneralMP3Data.java index 194518c..c9bae89 100755 --- a/tts_service/src/main/java/ai/qiwu/com/tts_service/pojo/GeneralMP3Data.java +++ b/tts_service/src/main/java/ai/qiwu/com/tts_service/pojo/GeneralMP3Data.java @@ -26,7 +26,7 @@ public class GeneralMP3Data { private String format; private String npcName; - private String tmpName; + private String tmpName; // 用于试听生成的临时mp3文件名 public GeneralMP3Data(String server, String text, String person, String tone, String botname, Boolean cache, Double volume, Double speed, Double pitch) { diff --git a/tts_service/src/main/java/ai/qiwu/com/tts_service/pojo/TextInfo.java b/tts_service/src/main/java/ai/qiwu/com/tts_service/pojo/TextInfo.java index 212ab15..e7a308f 100755 --- a/tts_service/src/main/java/ai/qiwu/com/tts_service/pojo/TextInfo.java +++ b/tts_service/src/main/java/ai/qiwu/com/tts_service/pojo/TextInfo.java @@ -4,6 +4,11 @@ import com.fasterxml.jackson.annotation.JsonIgnoreProperties; import lombok.Getter; import lombok.Setter; import lombok.ToString; +import org.apache.commons.lang3.StringUtils; + +import java.io.File; +import java.io.UnsupportedEncodingException; +import java.net.URLEncoder; /** * @author 苗权威 @@ -11,7 +16,6 @@ import lombok.ToString; */ @Getter @Setter -@ToString @JsonIgnoreProperties(ignoreUnknown = true) public class TextInfo { private String person; @@ -25,4 +29,16 @@ public class TextInfo { private String botname; private String botAccount; private String npcName; + + @Override + public String toString() { + return StringUtils.join(new String[]{botAccount,npcName,person,tone,text}, File.separator); +// String result = StringUtils.join(new String[]{botAccount,npcName,person,tone,text}, File.separator); +// try { +// result = URLEncoder.encode(StringUtils.join(new String[]{botAccount,npcName,person,tone,text}, File.separator), "UTF-8"); +// } catch (UnsupportedEncodingException e) { +// // do nothing +// } +// return result; + } } diff --git a/tts_service/src/main/java/ai/qiwu/com/tts_service/pojo/jmter/UserIdAndWord.java b/tts_service/src/main/java/ai/qiwu/com/tts_service/pojo/jmter/UserIdAndWord.java new file mode 100644 index 0000000..d2b6df5 --- /dev/null +++ b/tts_service/src/main/java/ai/qiwu/com/tts_service/pojo/jmter/UserIdAndWord.java @@ -0,0 +1,17 @@ +package ai.qiwu.com.tts_service.pojo.jmter; + +import lombok.Getter; +import lombok.Setter; +import lombok.ToString; + +/** + * painter + * 20-6-15 下午3:33 + */ +@Getter +@Setter +@ToString +public class UserIdAndWord { + private String uid; + private String word; +} diff --git a/tts_service/src/main/java/ai/qiwu/com/tts_service/service/Initialize.java b/tts_service/src/main/java/ai/qiwu/com/tts_service/service/Initialize.java index ac825c8..3f848de 100755 --- a/tts_service/src/main/java/ai/qiwu/com/tts_service/service/Initialize.java +++ b/tts_service/src/main/java/ai/qiwu/com/tts_service/service/Initialize.java @@ -22,7 +22,7 @@ import java.util.*; @Slf4j public class Initialize implements InitializingBean { - public static volatile String audioUrl = Config.getProperty("audioCallBack","https://didi-gz4.jiaoyou365.com/xiaoai/audio/play?userId="); +// public static volatile String audioUrl = Config.getProperty("audioCallBack","https://didi-gz4.jiaoyou365.com/xiaoai/audio/play?userId="); /** * 默认person */ @@ -111,7 +111,7 @@ public class Initialize implements InitializingBean { /** * 线下服务地址,用于删除线下服务器上的缓存还有响应线下mp3文件的请求 */ - private static final String OFFLINE_SERVER; + public static final String OFFLINE_SERVER; /** * 第三方请求的标识,出现在tts_ls请求返回的.b64文件名列表和.b64文件数据中 */ @@ -139,6 +139,8 @@ public class Initialize implements InitializingBean { */ private final SpeakerInfoRepository speakerInfoRepository; + public static final String AUDIO_GENERATE_SERVER; + /** * 静态代码块 */ @@ -161,6 +163,7 @@ public class Initialize implements InitializingBean { delCacheCallbackUrl = Config.getProperty("del_cache_callback_url"); delRecordCallbackUrl = Config.getProperty("del_record_callback_url"); record_callback_url = Config.getProperty("record_callback_url"); + AUDIO_GENERATE_SERVER = Config.getProperty("audio_generate_server"); // 根据数据库表中get_online字段的值来抉择不同的服务器 String[] online_sever_list = Config.getProperty("online_sever").split(","); @@ -407,7 +410,7 @@ public class Initialize implements InitializingBean { return THIRD_PARTY_TTS; } - static String getServerName() { + public static String getServerName() { return SERVER_NAME; } @@ -465,7 +468,22 @@ public class Initialize implements InitializingBean { return URL_2_PERSON_TON.get(url); } - public static String getServerUrlCdn() { + static String getServerUrlCdn() { return SERVER_URL_CDN; } + + static List getTheOfflineJumpPersonInfo(String person, String mood) { + Map moodJumpId = OFFLINE_2_ONLINE.get(person); + if (moodJumpId != null) { + Integer id; + if ((id=moodJumpId.get(mood)) != null) { + return URL_2_PERSON_TON.get(ONLINE_ID_2_URL.get(id)); + } + } + List list = new ArrayList<>(); + list.add(init_person); + list.add(init_tone); + log.warn("没有获取到该人物情绪对应的线上person选用默认"); + return list; + } } diff --git a/tts_service/src/main/java/ai/qiwu/com/tts_service/service/TTService.java b/tts_service/src/main/java/ai/qiwu/com/tts_service/service/TTService.java index 131c699..824c498 100755 --- a/tts_service/src/main/java/ai/qiwu/com/tts_service/service/TTService.java +++ b/tts_service/src/main/java/ai/qiwu/com/tts_service/service/TTService.java @@ -2,48 +2,37 @@ package ai.qiwu.com.tts_service.service; import ai.qiwu.com.tts_service.common.*; import ai.qiwu.com.tts_service.pojo.*; -import ai.qiwu.com.tts_service.pojo.upload.RecordCallbackData; import ai.qiwu.com.tts_service.pojo.upload.UploadCallbackResponse; import ai.qiwu.com.tts_service.pojo.upload.UploadOneSenData; import ai.qiwu.com.tts_service.service.baidu.ThirdPartyService; import com.alibaba.fastjson.JSON; -import com.csvreader.CsvReader; import lombok.extern.slf4j.Slf4j; -import org.apache.catalina.connector.Response; import org.apache.commons.csv.CSVFormat; import org.apache.commons.csv.CSVParser; import org.apache.commons.csv.CSVRecord; import org.apache.commons.lang3.RandomStringUtils; import org.apache.commons.lang3.StringUtils; import org.apache.commons.lang3.exception.ExceptionUtils; -import org.apache.commons.lang3.math.NumberUtils; import org.springframework.beans.factory.annotation.Autowired; -import org.springframework.beans.factory.annotation.Value; import org.springframework.data.redis.core.StringRedisTemplate; import org.springframework.stereotype.Service; import org.springframework.util.CollectionUtils; import org.springframework.web.multipart.MultipartFile; -import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import java.io.*; import java.net.URLDecoder; import java.net.URLEncoder; -import java.nio.channels.FileLock; import java.nio.charset.Charset; -import java.nio.charset.StandardCharsets; import java.nio.file.Files; import java.nio.file.Path; import java.nio.file.Paths; import java.util.*; import java.util.concurrent.*; import java.util.concurrent.atomic.AtomicInteger; -import java.util.concurrent.locks.ReentrantLock; import java.util.regex.Matcher; import java.util.regex.Pattern; -import static ai.qiwu.com.tts_service.common.TTSConstants.Audio.XIAOAI; -import static ai.qiwu.com.tts_service.common.TTSConstants.Audio.XIAODU; /** @@ -2282,12 +2271,13 @@ public class TTService { public void cdnAudioGet(String path, Integer exist,HttpServletResponse response) { if (StringUtils.startsWith(path,"%2F")) { try { - log.info("检测到重复加密存在:"+path); +// log.info("检测到重复加密存在:"+path); path = URLDecoder.decode(path, "UTF-8"); } catch (Exception e) { path = path.replaceAll("%2f", "/"); } } +// log.info("cdnAudioGet path:"+path); path = Initialize.getAudioDir()+path; Path pt = Paths.get(path); // exist == null 表明调用时确定已存在 @@ -2422,7 +2412,7 @@ public class TTService { //log.info("不存在地址:{},text:{}, botname:{}, tone:{}, person:{}",filepath, text, botName, tone, person); final GeneralMP3Data data = new GeneralMP3Data(Initialize.getServerName(), text, person, tone, botName, true, volume, speed, pitch); - data.setNpcName(npcName); + if (!isPersonThirdParty) data.setNpcName(npcName); final String path = filepath; final String moodUrl = url; Future future = POOL.submit(() -> { @@ -2484,9 +2474,9 @@ public class TTService { if (allExist) return result; else return "a"+result; } else { - String temp = TTSUtils.pythonlistToStr(file_ls); +// String temp = TTSUtils.pythonlistToStr(file_ls); // String dirs = String.format("[%s,xiaoai]", botName); - final String tmp_audio_name = StringUtils.join(new String[]{Initialize.getAudioDir(), botName, "xiaoai",temp}, File.separator); + final String tmp_audio_name = StringUtils.join(new String[]{Initialize.getAudioDir(), botName, "xiaoai",TTSUtils.buildMP3Filename(file_ls.toString())}, File.separator); if (!TTSUtils.doesFileExist(tmp_audio_name)) { POOL.submit(() -> task(futures, tmp_audio_name, file_ls)); return "a"+tmp_audio_name.substring(23); @@ -2566,7 +2556,21 @@ public class TTService { } public static void main(String[] args) throws UnsupportedEncodingException { - String s = "/root/TTS-service/audio/abc/234/ac"; - System.out.println(s.substring(23)); + Pattern pattern = Pattern.compile("1000[167]|1001[012]"); + List list = new ArrayList<>(); + list.add("10001"); + list.add("10006"); + list.add("10007"); + list.add("10010"); + list.add("10011"); + list.add("10012"); + list.add("10013"); + list.add("10002"); + for (String item: list) { + Matcher matcher = pattern.matcher(item); + while (matcher.find()) { + System.out.println(matcher.group(0)); + } + } } } diff --git a/tts_service/src/main/java/ai/qiwu/com/tts_service/service/TTServiceEdition2.java b/tts_service/src/main/java/ai/qiwu/com/tts_service/service/TTServiceEdition2.java new file mode 100644 index 0000000..4c3eb0a --- /dev/null +++ b/tts_service/src/main/java/ai/qiwu/com/tts_service/service/TTServiceEdition2.java @@ -0,0 +1,1082 @@ +package ai.qiwu.com.tts_service.service; + +import ai.qiwu.com.tts_service.common.*; +import ai.qiwu.com.tts_service.pojo.*; +import ai.qiwu.com.tts_service.service.baidu.ThirdPartyService; +import com.alibaba.fastjson.JSON; +import lombok.RequiredArgsConstructor; +import lombok.extern.slf4j.Slf4j; +import org.apache.commons.lang3.RandomStringUtils; +import org.apache.commons.lang3.StringUtils; +import org.apache.commons.lang3.exception.ExceptionUtils; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.data.redis.core.StringRedisTemplate; +import org.springframework.stereotype.Service; +import org.springframework.util.CollectionUtils; +import org.springframework.util.DigestUtils; + +import javax.servlet.http.HttpServletResponse; +import java.io.File; +import java.io.UnsupportedEncodingException; +import java.net.URLEncoder; +import java.nio.file.Files; +import java.nio.file.Path; +import java.nio.file.Paths; +import java.nio.file.StandardCopyOption; +import java.util.*; +import java.util.concurrent.Future; +import java.util.concurrent.TimeUnit; +import java.util.regex.Matcher; +import java.util.regex.Pattern; + +import static ai.qiwu.com.tts_service.service.TTService.POOL; + +/** + * painter + * 20-6-17 上午10:31 + */ +@Slf4j +@Service +@RequiredArgsConstructor(onConstructor_ = { @Autowired}) +public class TTServiceEdition2 { + private final StringRedisTemplate stringRedisTemplate; + + public void tts(TTSRequest ttsRequest, String requestMethod, HttpServletResponse servletResponse) { + // text字段不能为空 + String text = ttsRequest.getText(); + if (StringUtils.isBlank(text)) { + TTServiceUtil.buildServletResponse(servletResponse, new TTSResponse(HttpServletResponse.SC_BAD_REQUEST, "文本不能为空"), null, HttpServletResponse.SC_BAD_REQUEST); + return; + } + // 获取person,没有或数据库中不存在,则付值 init_person + String person = ttsRequest.getPerson(); + if (StringUtils.isBlank(person)) person = Initialize.init_person; + + // 获取情绪值,不存在则置为"正常" + String mood = ttsRequest.getTone(); + if (StringUtils.isBlank(mood)) mood = Initialize.init_tone; + // 第三方请求的情绪置为"正常",非第三方的请求则获取其请求地址url + boolean doesThirdPerson = Initialize.getThirdPartyTts().contains(person); + String moodUrl = null; + if (!doesThirdPerson) { + // 请求person不存在直接返回 + Map map; + if ((map=Initialize.PERSON_MOODURL.get(person)) == null) { + TTServiceUtil.buildServletResponse(servletResponse, new TTSResponse(HttpServletResponse.SC_NOT_FOUND, "找不到"+person), null, HttpServletResponse.SC_NOT_FOUND); + return; + } + if (!map.containsKey(mood)) { + Map.Entry changedMoodUrl = map.entrySet().iterator().next(); + log.warn("tts 修正{}的情绪:{}->{}",person, mood, changedMoodUrl.getKey()); + mood = changedMoodUrl.getKey(); + } + if (StringUtils.endsWith(person, "offline")) { + moodUrl = Initialize.OFFLINE_SERVER; + } else { + moodUrl = Initialize.AUDIO_GENERATE_SERVER; + } +// moodUrl = map.get(mood); +// log.info("获取moodurl:"+moodUrl); + } else { + mood = "正常"; + } + // 是否是线上请求,该字段的目的是优化,若其为false则代表是线下请求, + // 那么当我们通过其url获取不到文件的时候则直接返回404,不再像之前一样修正参数改变url重新请求 + Boolean getOnline = ttsRequest.getGet_online(); + if (getOnline == null) getOnline = true; + + double volume = Double.parseDouble(ttsRequest.getVolume() == null ? "0" : ttsRequest.getVolume()); + double pitch = Double.parseDouble(ttsRequest.getPitch() == null ? "0" : ttsRequest.getPitch()); + double speed = Double.parseDouble(ttsRequest.getSpeed() == null ? "1" : ttsRequest.getSpeed()); + + // botname为空则赋予tmp + String botName = ttsRequest.getBotname(); + boolean tmpRequest = false; + if (StringUtils.isBlank(botName)) { + botName = "tmp"; + tmpRequest = true; + } + String npcName = ttsRequest.getNpcName(); + + // (audio_dir)/botname/person/mood目录 + String botFolder = new StringBuilder(Initialize.getAudioDir()).append(File.separator).append(botName).toString(); + String fileName = TTSUtils.buildMP3Filename(text); + String filePath; + // (audio_dir)/botname/person/mood/xxx.mp3文件路径 + if (StringUtils.isNotBlank(npcName) && !"PUT".equals(requestMethod)) { + String uploadedFilePath = StringUtils.join(new String[]{botFolder,Initialize.getUploadedDir(),npcName,fileName}, File.separator); + if (TTSUtils.doesFileExist(uploadedFilePath)) { + filePath = uploadedFilePath; + } else { + filePath = StringUtils.join(new String[]{botFolder, person, mood, fileName}, File.separator); + } + } else { + filePath = StringUtils.join(new String[]{botFolder, person, mood, fileName}, File.separator); + } + TTSResponse response = null; + // _type为json,则构建请求get_audio接口的信息 + boolean shouldGenerateMp3 = !TTSUtils.doesFileExist(filePath) || requestMethod.equals("PUT"); + if ("json".equals(ttsRequest.get_type())) { + String audioGetUrl; + if (tmpRequest) { + fileName = RandomStringUtils.randomAlphabetic(3) + System.currentTimeMillis() + ".mp3"; + audioGetUrl = filePath.substring(23, filePath.lastIndexOf(File.separator)+1)+fileName; + } else { + audioGetUrl = filePath.substring(23); + } + //http://(server_url)/api/tts/get_audio?dirs=[botname+person,mood]&filename=xxx.mp3 + try { + audioGetUrl = URLEncoder.encode(audioGetUrl, "UTF-8"); + } catch (UnsupportedEncodingException e) { + log.error("URLEncoding编码出错:{},path:{}", e.toString(),audioGetUrl); + } + if (shouldGenerateMp3) audioGetUrl += "&exist=1"; + audioGetUrl = Initialize.getServerUrl()+"/api/audio/tts?filename="+audioGetUrl; + response = new TTSResponse(audioGetUrl,HttpServletResponse.SC_OK); + } + boolean generate = true; + boolean setSuccess = false; +// String redisKey = ""; + // filepath文件不存在或是put请求,调用generalMP3生成该filepath所指的mp3文件 + if (shouldGenerateMp3){ + generate = false; + GeneralMP3Data data = new GeneralMP3Data(Initialize.getServerName(), ttsRequest.getText(), + person, mood, botName, true, volume, speed, pitch); + data.setNpcName(npcName); + if (tmpRequest) data.setTmpName(fileName); +// try { +// redisKey = URLEncoder.encode(filePath, "UTF-8"); +// } catch (Exception e) { +// redisKey = filePath; +// } + try { + if ((setSuccess=Boolean.TRUE.equals(stringRedisTemplate.opsForValue().setIfAbsent(filePath, "1", 15, TimeUnit.SECONDS)))) { + ResponseCodeWithData codeWithData = generalMP3(moodUrl, data, filePath, requestMethod, getOnline); + if (codeWithData == null) { + TTServiceUtil.buildServletResponse(servletResponse, new TTSResponse(HttpServletResponse.SC_INTERNAL_SERVER_ERROR), null, HttpServletResponse.SC_INTERNAL_SERVER_ERROR); + return; + } + if (codeWithData.getCode() != HttpServletResponse.SC_OK) { + if (codeWithData.getCode() == HttpServletResponse.SC_NOT_FOUND) { + log.info("404,请求地址不存在"); + }else { + log.error("下载:{}音频失败", moodUrl); + } + TTServiceUtil.buildServletResponse(servletResponse, new TTSResponse(codeWithData.getCode()), null, codeWithData.getCode()); + return; + } + } + } catch (Exception e) { + log.warn(ExceptionUtils.getStackTrace(e)); + response = new TTSResponse(HttpServletResponse.SC_INTERNAL_SERVER_ERROR, "出错"); + } finally { + if (setSuccess) stringRedisTemplate.delete(filePath); + } + } + if (response == null) { + if (generate || setSuccess) TTServiceUtil.buildServletResponse(servletResponse, null, new File(filePath), HttpServletResponse.SC_OK); + else { + int count = 0; + while (Boolean.TRUE.equals(stringRedisTemplate.hasKey(filePath)) && count < 10) { + try { + Thread.sleep(1000); + } catch (Exception e) { + // do nothing + } + ++count; + } + if (count == 10 && Boolean.TRUE.equals(stringRedisTemplate.hasKey(filePath))) { + log.warn("tts 竞争超时:"+filePath); + TTServiceUtil.buildServletResponse(servletResponse, new TTSResponse(HttpServletResponse.SC_INTERNAL_SERVER_ERROR), + null, HttpServletResponse.SC_INTERNAL_SERVER_ERROR); + } else { + TTServiceUtil.buildServletResponse(servletResponse, null, new File(filePath), HttpServletResponse.SC_OK); + } + } + } else { + TTServiceUtil.buildServletResponse(servletResponse, response, null, HttpServletResponse.SC_OK); + } + } + + public void ttsAudioGet(String filename, Integer exist, String _type, HttpServletResponse response) { + boolean tmp = StringUtils.startsWith(filename, "/tmp"); + if (StringUtils.endsWith(filename,".mp3")) { + String filepath = Initialize.getAudioDir() + filename; + Path pt = Paths.get(filepath); + // exist == null 表明调用时确定已存在 + if (exist == null) { + if (Files.exists(pt)) { + if ("file".equals(_type)) { + // 请求头中添加 Content-Disposition = attachment 可下载 + TTServiceUtil.buildTTSMp3Response(response, null, filepath, HttpServletResponse.SC_OK, true); + } else { + TTServiceUtil.buildTTSMp3Response(response, null, filepath, HttpServletResponse.SC_OK, false); + } + if (tmp) { + POOL.submit(() -> { + if (!new File(filepath).delete()) log.info("ttsAudioGet 删除tmp文件失败:{}",filepath); + }); + } + } else { + log.warn("ttsAudioGet exist but path not exist:"+filename); + response.setStatus(HttpServletResponse.SC_NOT_FOUND); + } + } else { + int count = 0; + boolean fileExist; + while (!(fileExist=Files.exists(pt)) && count < 16) { + try { + Thread.sleep(500); + count++; + } catch (Exception e) {} + } + if (!fileExist) { + response.setStatus(HttpServletResponse.SC_NOT_FOUND); + log.warn("ttsAudioGet 等待8s后音频文件仍不存在:"+filename); + return; + } + while (Boolean.TRUE.equals(stringRedisTemplate.hasKey(filename))&& count < 30) { + try { + Thread.sleep(HttpServletResponse.SC_INTERNAL_SERVER_ERROR); + count++; + } catch (Exception e) {} + } + if (count == 30 && Boolean.TRUE.equals(stringRedisTemplate.hasKey(filename))) { + response.setStatus(HttpServletResponse.SC_NOT_FOUND); + log.warn("ttsAudioGet:15s后竞争者仍未完成音频操作"); + return; + } + if ("file".equals(_type)) { + // 请求头中添加 Content-Disposition = attachment 可下载 + TTServiceUtil.buildTTSMp3Response(response, null, filepath, HttpServletResponse.SC_OK, true); + } else { + TTServiceUtil.buildTTSMp3Response(response, null, filepath, HttpServletResponse.SC_OK, false); + } + if (tmp) { + POOL.submit(() -> { + if (!new File(filepath).delete()) log.info("ttsAudioGet 删除tmp文件失败:{}",filepath); + }); + } + } + } else if (StringUtils.endsWithAny(filename, ".wav", ".b64")) { + TTServiceUtil.buildTTSMp3Response(response, null, filename, HttpServletResponse.SC_OK, true); + } else { + TTServiceUtil.buildTTSMp3Response(response, new MP3Response(HttpServletResponse.SC_BAD_REQUEST), null, HttpServletResponse.SC_BAD_REQUEST, false); + } + } + + public void tts_ls(TTSLSRequest request, HttpServletResponse response) { + String _type = request.get_type(); + String platform = request.getPlatform(); + List infoList = request.getText_info_ls(); + // botname不能为空 + String botName = request.getBotname(); + if (botName == null) botName = "中控"; + else if (botName.trim().equals("")) { + TTServiceUtil.buildTTS_lsResponse(response, new TTSResponse(HttpServletResponse.SC_BAD_REQUEST, "no botname"), null, HttpServletResponse.SC_BAD_REQUEST); + return; + } + List> futures = new ArrayList<>(); + List file_ls = new ArrayList<>(); + String rootFolderRoot = new StringBuilder(Initialize.getAudioDir()).append(File.separator).append(botName).append(File.separator).toString(); + String uploadFolderRoot = new StringBuilder(rootFolderRoot).append(Initialize.getUploadedDir()).append(File.separator).toString(); + // 第三方语音是否生成,为0则代表不处理该第三方语音 + boolean geneThird = request.getGen3rd() == null || request.getGen3rd() != 0; + if (infoList != null && infoList.size() != 0) { + for (TextInfo info : infoList) { +// String beforeCache; +// String cacheKey; +// if (StringUtils.isNotBlank((beforeCache=stringRedisTemplate.opsForValue().get((cacheKey = info.toString()))))) { +//// log.info("缓存命中:"+beforeCache); +// file_ls.add(beforeCache); +// continue; +// } + String uploadFolder, rootFolder; + if (botName.equals(info.getBotAccount()) || StringUtils.isBlank(info.getBotAccount())) { + rootFolder = rootFolderRoot; + uploadFolder = uploadFolderRoot; + } else { + rootFolder = new StringBuilder(Initialize.getAudioDir()).append(File.separator) + .append(info.getBotAccount()).append(File.separator).toString(); + uploadFolder = new StringBuilder(rootFolder).append(Initialize.getUploadedDir()).append(File.separator).toString(); + } + + // person没有值或是不存在则赋予init_person + String person = info.getPerson(); + if (StringUtils.isBlank(person)) person = Initialize.init_person; + + // text 字段不为空 + String text = info.getText(); + if (StringUtils.isBlank(text)) continue; + + String url = null; //moodUrl + String tone = "正常"; // 第三方请求的情绪为:正常 + + // 是否是第三方请求 + boolean isPersonThirdParty = Initialize.getThirdPartyTts().contains(person); + + // 非第三方请求需要对person及tone进行校正,以得到确实存在的url + if (!isPersonThirdParty) { + if (!Initialize.PERSON_MOODURL.containsKey(person)) person = Initialize.init_person; + //log.info("person:{}",person); + + // 确保tone值为person的某个已有的情绪值 + tone = info.getTone() == null ? Initialize.init_tone : info.getTone(); + // + Map moodUrlMap = Initialize.PERSON_MOODURL.get(person); + if (!moodUrlMap.containsKey(tone)) tone = TTSConstants.DEFAULT_MOOD; + if (!moodUrlMap.containsKey(tone)) { + if (person.equals(Initialize.init_person)) tone = Initialize.init_tone; + else tone = moodUrlMap.keySet().iterator().next(); + } + // 获取该person的mood的url地址 + if (StringUtils.endsWith(person,"offline")) url = Initialize.OFFLINE_SERVER; + else url = Initialize.AUDIO_GENERATE_SERVER; + } + + String filepath = null; + // 只处理明确指定要生成的第三方语音及非第三方 + if (geneThird || !isPersonThirdParty) { + double volume = Double.parseDouble(StringUtils.isBlank(info.getVolume()) ? "0" : info.getVolume()); + double pitch = Double.parseDouble(StringUtils.isBlank(info.getPitch()) ? "0" : info.getPitch()); + double speed = Double.parseDouble(StringUtils.isBlank(info.getSpeed()) ? "1" : info.getSpeed()); + + String npcName = info.getNpcName(); + String fileName = TTSUtils.buildMP3Filename(text); + // 含有npcName字段则先去人工合成目录下找寻,人工没有则去合成目录寻找 + if (StringUtils.isNotBlank(npcName)) { + String path = new StringBuilder(uploadFolder).append(npcName).append(File.separator).append(fileName).toString(); + if (TTSUtils.doesFileExist(path)) filepath = path; + } + if (filepath == null) { + filepath = new StringBuilder(rootFolder).append(person).append(File.separator).append(tone) + .append(File.separator).append(fileName).toString(); + } + + if (!TTSUtils.doesFileExist(filepath)) { + if (botName.equals("550829152")) return; + final GeneralMP3Data data = new GeneralMP3Data(Initialize.getServerName(), text, + person, tone, botName, true, volume, speed, pitch); + if (!isPersonThirdParty) data.setNpcName(npcName); + final String path = filepath; + final String moodUrl = url; + Future future = POOL.submit(() -> { +// String encodePth; +// try { +// encodePth = URLEncoder.encode(path, "UTF-8"); +// encodePth = encodePth.replaceAll("%2F", "/"); +// } catch (Exception e) { +// encodePth = path; +// } + if (Boolean.TRUE.equals(stringRedisTemplate.opsForValue().setIfAbsent(path, "1", 20, TimeUnit.SECONDS))) { + log.info("future generate:{},text:{}",path,text); + if (!TTSUtils.doesFileExist(path)) { + ResponseCodeWithData response1 = generalMP3(moodUrl, data, path, "GET",true); + if (response1 == null) response1 = new ResponseCodeWithData(HttpServletResponse.SC_INTERNAL_SERVER_ERROR, "tts_ls:generalMP3 return null"); + stringRedisTemplate.delete(path); + return response1; + } + } + return new ResponseCodeWithData(8, path); + }); + futures.add(future); + } + + // _type为filename则说明请求要获取的是.b64文件名列表,platform字段优先级高于_type + if ("filename".equals(_type) && !"xiaoai".equals(platform)) { + filepath = filepath+".b64"; + } + } else { + filepath = Initialize.getThirdParty(); + } + file_ls.add(filepath); + } + + boolean xiaoai; + if ((xiaoai="xiaoai".equals(platform)) || !StringUtils.endsWith(_type, "64")) { + // 异步合成b64文件 + final String finalBotName = botName; + POOL.submit(() -> getFromFutureAndGenerateB64File(futures, response, file_ls, xiaoai, finalBotName)); + dealMp3UrlRequest(response, file_ls, botName, _type, xiaoai); + } else { + if (!getFromFutureAndGenerateB64File(futures, response, file_ls, false, botName)) return; + dealHasB64FileRequest(response, file_ls, botName, _type); + } + } else { + TTServiceUtil.buildTTS_lsResponse(response, new TTSResponse(HttpServletResponse.SC_BAD_REQUEST, "text_info_ls字段不能为空"), null, HttpServletResponse.SC_BAD_REQUEST); + } + } + + private ResponseCodeWithData generalMP3(String url, GeneralMP3Data data, String filePath, String requestMethod, + boolean getOnline) { + ResponseCodeWithData res = null; + try { + Files.createDirectories(Paths.get(filePath).getParent()); + } catch (Exception e) { + log.error("generalMP3 目录创建失败:{},msg:{}",filePath,e); + return new ResponseCodeWithData(HttpServletResponse.SC_INTERNAL_SERVER_ERROR); + } + String wavFilename = filePath.substring(0, filePath.length()-4)+".wav"; + //对于请求参数中带有npcName的,首先判断其是否是分段请求,即检查text中是否包含AB符号 + if (StringUtils.isNotBlank(data.getNpcName())) { + if (genRecordWithChange(url, data, filePath, requestMethod, getOnline)) return new ResponseCodeWithData(HttpServletResponse.SC_OK); + } + // 若wav不存在则先下载,通过person来区分是否是第三方 + if (!TTSUtils.doesFileExist(wavFilename)) { + if (Initialize.getThirdPartyTts().contains(data.getPerson())) { + res = dealThirdParty(data.getText(), data.getPerson(), wavFilename); + if (res.getCode() != HttpServletResponse.SC_OK) return res; + } else { + data.setFormat("wav"); + res = requestTemplate(url, data, wavFilename, getOnline); + if (res == null || res.getCode() != HttpServletResponse.SC_OK) { + log.error("generalMP3 下载wav失败:{}, 响应信息:{}",wavFilename,res); + return res; + } + } + if (TTSUtils.doesFileExist(wavFilename)) { + log.error("generalMP3 wav size is 0:{}",wavFilename); + return new ResponseCodeWithData(HttpServletResponse.SC_INTERNAL_SERVER_ERROR); + } + } + // 对于put请求则直接讲wav转为mp3,其他则先判断mp3文件是否存在, + // 不存在对于线下请求则去url地址下载该mp3文件,线上的则直接转wav + boolean fileExist = TTSUtils.doesFileExist(filePath); + if (requestMethod.equals("PUT")) { + if (fileExist) { + new File(filePath).delete(); + } + // 试听生成的临时mp3文件名 + if (data.getTmpName() != null) filePath = filePath.substring(0, filePath.lastIndexOf(File.separator)+1)+data.getTmpName(); + res = changeSound(wavFilename, data.getVolume(), data.getSpeed(), data.getPitch(), filePath); + } else if (!fileExist) { + if (Initialize.OFFLINE_SERVER.equals(url)) { + data.setFormat("mp3"); + int status = ApachHttpUtils.audioPost(url, JSON.toJSONString(data), filePath); + if (status != HttpServletResponse.SC_OK) { + log.info("直接下载人物{}的mp3文件失败,TEXT:{}",filePath,data.getText()); + } + // 若是下载mp3文件失败,或是下载了个空文件,则wav转mp3 + if (!TTSUtils.doesFileExist(filePath)) { + res = changeSound(wavFilename, data.getVolume(), data.getSpeed(), data.getPitch(), filePath); + } + }else { + res = changeSound(wavFilename, data.getVolume(), data.getSpeed(), data.getPitch(), filePath); + } + } + if (res == null) res = new ResponseCodeWithData(HttpServletResponse.SC_OK); + return res; + } + + private ResponseCodeWithData requestTemplate(String url, GeneralMP3Data data, String filePath, boolean getOnline) { + ResponseCodeWithData res; + int status = ApachHttpUtils.audioPost(url, JSON.toJSONString(data), filePath); +// OkHttp3Utils.doPostTimeout() + if (status == 0) res = new ResponseCodeWithData(HttpServletResponse.SC_INTERNAL_SERVER_ERROR, "请求出错"); + else if (status == HttpServletResponse.SC_NOT_FOUND && Initialize.OFFLINE_SERVER.equals(url)) { + if (!getOnline) return new ResponseCodeWithData(HttpServletResponse.SC_NOT_FOUND, "没有找到该文件"); + List list = Initialize.getTheOfflineJumpPersonInfo(data.getPerson(), data.getTone()); + +// log.warn("build new jump GeneralMP3Data"); + GeneralMP3Data jumpedData = new GeneralMP3Data(data.getServer(), data.getText(), list.get(0), list.get(1), + data.getBotname(), data.getCache(), data.getVolume(), data.getSpeed(), data.getPitch()); + log.warn("线下人物请求404,跳转到其对应的线上人物:人物:{}->{},情绪:{}->{}",data.getPerson(),jumpedData.getPerson(),data.getTone(), jumpedData.getTone()); + status = ApachHttpUtils.audioPost(Initialize.AUDIO_GENERATE_SERVER, JSON.toJSONString(jumpedData), filePath); + res = new ResponseCodeWithData(status); + } else { + res = new ResponseCodeWithData(status); + } + +// if ((res == null || res.getCode() != 200) && !"mp3".equals(data.getFormat())) { +// log.warn("requestTemplate:列户小雅兜底调用"); +// res = dealThirdParty(data.getText(), "Liehu1", filePath); +// } + return res; + } + + private ResponseCodeWithData changeSound(String wavFilename, double volume, double speed, + double pitch, String mp3FilePath) { + ResponseCodeWithData res = null; + try { + CallPython.changeSoundByPython(wavFilename, String.valueOf(volume), String.valueOf(speed), + String.valueOf(pitch), mp3FilePath); + if (!TTSUtils.doesFileExist(mp3FilePath)) { + log.error("python代码出错,mp3文件没有创建成功.{},{},{},{}", wavFilename, volume, speed, pitch); + res = new ResponseCodeWithData(HttpServletResponse.SC_INTERNAL_SERVER_ERROR); + } + } catch (Exception e) { + log.error("调用changeSound出错:{}", e.toString()); + res = new ResponseCodeWithData(HttpServletResponse.SC_INTERNAL_SERVER_ERROR); + } + return res; + } + + private boolean genRecordWithChange(String url, GeneralMP3Data data, String personToneFilePath, + String requestMethod, boolean getOnline) { + final String text = data.getText(); + // 存储变量集合 + List variableTextList = new ArrayList<>(); + // 获取AB之间的变量,为空则忽略 + Pattern pattern = Pattern.compile(TTSUtils.getAbRegex()); + Matcher matcher = pattern.matcher(text); + while (matcher.find()) { + String variableText = matcher.group(1); + if (StringUtils.isNotBlank(variableText)) variableTextList.add(variableText); + } + //log.info("variableTextList:{}",variableTextList); + //不是分段语句则返回false,回到generalMP3方法整体处理 + if (variableTextList.size() != 0) { + // 要合并的mp3地址集合 + TreeMap combineMp3Text2FilePath = new TreeMap<>(Comparator.comparingInt(text::indexOf)); + // 人工上传目录, audio_dir/botname/record/npcname + String recordFolder = StringUtils.join(new String[]{Initialize.getAudioDir(), data.getBotname(), + Initialize.getUploadedDir(), data.getNpcName()}, File.separator); + // 非变量部分 + String[] notVariableTextArray = pattern.split(text); + //log.info("notVariableTextArray:{}",Arrays.toString(notVariableTextArray)); + // 遍历所有非变量,若其mp3文件在人工目录下不存在则返回false回到generalMp3方法,整句合成 + int i = 0; + for (String notVariableText: notVariableTextArray) { + if (StringUtils.isBlank(notVariableText)) { + ++i; + continue; + } + if (i++ == notVariableTextArray.length-1) { + boolean notVariableLast = text.lastIndexOf(notVariableText)+notVariableText.length() == text.length(); + //log.info("notVariableLast:{}", notVariableLast); + if (notVariableLast) { + String last = notVariableText; + last = last.replaceAll("\\p{P}", ""); + if (StringUtils.isBlank(last)) { + //log.info("last is empty"); + break; + } + } + } + String notVariableTextPath = new StringBuilder(recordFolder).append(File.separator) + .append(TTSUtils.buildMP3Filename(notVariableText)).toString(); + //log.info("notVariableTextPath:{}",notVariableTextPath); + if (!TTSUtils.doesFileExist(notVariableTextPath)) return false; + combineMp3Text2FilePath.put(notVariableText, notVariableTextPath); + } + // 语音合成目录;audio_dir/botname/person/tone + String usDir = StringUtils.join(new String[]{Initialize.getAudioDir(),data.getBotname(), + data.getPerson(), data.getTone()}, File.separator); + // 遍历所有变量,若其mp3文件在人工目录下不存在则调用generalMP3方法生成 + for (String variableText: variableTextList) { + String variableTextFilename = TTSUtils.buildMP3Filename(variableText); + String variableTextPath = new StringBuilder(recordFolder).append(File.separator) + .append(variableTextFilename).toString(); + if (!TTSUtils.doesFileExist(variableTextPath)) { + GeneralMP3Data variableData = new GeneralMP3Data(data.getServer(), variableText,data.getPerson(), + data.getTone(), data.getBotname(), data.getCache(),data.getVolume(),data.getSpeed(),data.getPitch()); + String variablePathInUsDir = new StringBuilder(usDir).append(File.separator).append(variableTextFilename).toString(); + ResponseCodeWithData response = generalMP3(url, variableData, variablePathInUsDir, requestMethod, getOnline); + if (response == null || response.getCode() != 200) return false; + combineMp3Text2FilePath.put(variableText, variablePathInUsDir); + }else { + combineMp3Text2FilePath.put(variableText, variableTextPath); + } + } + // 合并所有分段mp3文件 + try { + TTSUtils.combineMp3File(combineMp3Text2FilePath.values(), personToneFilePath); + if (!new File(personToneFilePath).exists()) { + log.error("分段合并音频,未找到合并后的文件"); + return false; + } + } catch (Exception e) { + log.error("genRecordWithChange:合成音频失败:{}",e.toString()); + return false; + } + return true; + } + return false; + } + + private ResponseCodeWithData dealThirdParty(String text, String person, String filepath) { + boolean result; + // 去除所有{/../} + text = text.replaceAll("\\{/.*?/}|\uD83C\uDD70|\uD83C\uDD71", "").trim(); + if (StringUtils.isBlank(text)) { + log.error("第三方请求内容为空"); + return new ResponseCodeWithData(HttpServletResponse.SC_INTERNAL_SERVER_ERROR, "第三方请求内容为空"); + } + result = ThirdPartyService.thirdPartyCall(text, Initialize.theThirdPartysPer(person), filepath, person); + if (result) { + return new ResponseCodeWithData(HttpServletResponse.SC_OK, "创建第三方wav文件成功"); + } + log.error("调用第三方生成wav文件失败"); + return new ResponseCodeWithData(HttpServletResponse.SC_INTERNAL_SERVER_ERROR, "调用第三方生成wav文件失败"); + } + + private boolean getFromFutureAndGenerateB64File(List> futures, HttpServletResponse response, + List file_ls, boolean xiaoai, String botName) { + // 阻塞等待mp3文件生成成功 +// if (futures.size() == 0) log.info("futures is empty"); + for (Future future : futures) { + try { + ResponseCodeWithData data = future.get(6, TimeUnit.MINUTES); + if (data.getCode() != HttpServletResponse.SC_OK) { + if (data.getCode() == 8) { + log.info("tts_ls:出现竞争情况->"+data.getRes()+",时间:"+new Date(System.currentTimeMillis())); + if (data.getRes() != null) { + int count = 0; + while (Boolean.TRUE.equals(stringRedisTemplate.hasKey(data.getRes())) && count < 20) { + try { + Thread.sleep(500); + } catch (Exception e){ + // do nothing + } + ++count; + } + if (count == 20 && Boolean.TRUE.equals(stringRedisTemplate.hasKey(data.getRes()))) { + log.warn("tts_ls:10s后竞争者仍未完成音频操作->"+data.getRes()); + TTServiceUtil.buildTTS_lsResponse(response, new TTSResponse(HttpServletResponse.SC_INTERNAL_SERVER_ERROR), null, HttpServletResponse.SC_INTERNAL_SERVER_ERROR); + return false; + } + } + } else { + log.error("tts_ls: future execute fail, status:"+data.getCode()); + TTServiceUtil.buildTTS_lsResponse(response, new TTSResponse(data.getCode()), null, data.getCode()); + return false; + } + } + } catch (Exception e) { + log.error("tts_ls获取结果出错:{}", ExceptionUtils.getStackTrace(e)); + TTServiceUtil.buildTTS_lsResponse(response, new TTSResponse(HttpServletResponse.SC_BAD_REQUEST), null, HttpServletResponse.SC_BAD_REQUEST); + return false; + } + } + + if (xiaoai) { + String tmp_audio_name = StringUtils.join(new String[]{Initialize.getAudioDir(), botName, "xiaoai", TTSUtils.buildMP3Filename(file_ls.toString())}, File.separator); + if (!TTSUtils.doesFileExist(tmp_audio_name)) { + if (Boolean.TRUE.equals(stringRedisTemplate.opsForValue() + .setIfAbsent(tmp_audio_name, "1", 20, TimeUnit.SECONDS))) { + if (!TTSUtils.doesFileExist(tmp_audio_name)) { + try { + Files.createDirectories(Paths.get(tmp_audio_name).getParent()); + TTSUtils.combineMp3File(file_ls, tmp_audio_name); + if (!TTSUtils.doesFileExist(tmp_audio_name)) { + log.error("小爱平台的请求,合并mp3文件失败:"+file_ls); + } + } catch (Exception e) { + log.error("ffmpeg 合并音频出错:{},file_ls:{}",e,file_ls); + } finally { + stringRedisTemplate.delete(tmp_audio_name); + } + } + } else { + log.warn("tts_ls xiaoai 合成竞争->"+tmp_audio_name+",时间:"+new Date(System.currentTimeMillis())); + } + } + } else { + // 非xiaoai平台的请求,首先将.mp3文件的数据存储在对应的.mp3.b64文件内 + // 将.mp3文件的数据存储在对应的.mp3.b64文件内 + for (String filename : file_ls) { + if (filename.equals(Initialize.getThirdParty())) { + continue; + } + boolean endWithB64; + String filename_64 = (endWithB64=StringUtils.endsWith(filename, ".b64")) ? filename : filename+".b64"; + if (!TTSUtils.doesFileExist(filename_64)) { + if (endWithB64) filename = filename_64.substring(0, filename_64.length()-4); + try { + Files.copy(Paths.get(filename), Paths.get(filename_64), StandardCopyOption.REPLACE_EXISTING); + } catch (Exception e) { + log.error("拷贝.b64文件出错:"+e); + new File(filename_64).delete(); + } + } + } + } +// if (beforeAiHas) log.error("xiaoAi 之前已存在该音频:"+xiaoaiCacheKey); + return true; + } + + private void dealHasB64FileRequest(HttpServletResponse response, + List file_ls, String botName, String _type) { + // 若请求字段_type为filename,则返回.b64文件的路径列表,负责返回所有.b64文件的内容数据 + TtsLsResponse ttsLsResponse = new TtsLsResponse(); + try { + switch (TtsLsType.valueOf(_type)) { + case urlB64: { + buildB64UrlResponse(ttsLsResponse, file_ls, botName); + break; + } + case fileB64: { + buildB64FileNameResponse(ttsLsResponse, file_ls); + break; + } + case b64: + default: { + // default b64 + buildB64Response(ttsLsResponse, file_ls); + } + } + } catch (Exception e) { + log.error("tts_ls的switch出错:{},_type:{}",e.toString(), _type); + buildB64Response(ttsLsResponse, file_ls); + } + TTServiceUtil.buildNewTtsLsResponse(response, ttsLsResponse, HttpServletResponse.SC_OK); + } + + private void dealMp3UrlRequest(HttpServletResponse response, List file_ls, + String botName, String _type, boolean xiaoai) { + // 小爱平台的请求,我们会讲所有mp3文件合在一起,文件路径为(audio_dir)/botname/xiaoai/xxx.mp3, + // 成功则构建请求get_audio接口的请求url,包括参数信息,返回该url + if (xiaoai) { + String tmp_audio_name = StringUtils.join(new String[]{Initialize.getAudioDir(), botName, "xiaoai", TTSUtils.buildMP3Filename(file_ls.toString())}, File.separator); + String audio = Initialize.getServerUrlCdn()+"/api/audio/cache/"+botName+"/?filename="+tmp_audio_name.substring(23); + if (!Files.exists(Paths.get(tmp_audio_name))) { + audio += "&exist=1"; + } + TTServiceUtil.buildTTS_lsResponse(response, new TTSResponse(audio,HttpServletResponse.SC_OK), null, HttpServletResponse.SC_OK); + } else { + TtsLsResponse ttsLsResponse = new TtsLsResponse(); + try { + switch (TtsLsType.valueOf(_type)) { + case url: { + buildUrlResponse(ttsLsResponse, file_ls, botName); + break; + } + case filename: { + buildFilenameResponse(ttsLsResponse, file_ls); + break; + } + case urlFile: { + buildUrlFileResponse(ttsLsResponse, file_ls, botName); + break; + } + default: { + // default url + buildUrlResponse(ttsLsResponse, file_ls, botName); + } + } + } catch (Exception e) { + log.error("tts_ls的switch出错:{},_type:{}",e.toString(), _type); + buildUrlResponse(ttsLsResponse, file_ls, botName); + } + TTServiceUtil.buildNewTtsLsResponse(response, ttsLsResponse, 200); + } + } + + private void buildB64Response(TtsLsResponse response, List file_ls) { + for (String filename : file_ls) { + TtsLsAudio audio = new TtsLsAudio(); + if (filename.equals(Initialize.getThirdParty())) { + audio.setB64(filename); + response.getAudio().add(audio); + continue; + } + filename = filename+".b64"; + try { + audio.setB64(TTSUtils.readAllFile(filename)); + } catch (Exception e) { + log.error("读取文件{}内容出错:{}", filename, e.toString()); + audio.setB64(""); + } + response.getAudio().add(audio); + } + } + + private void buildB64UrlResponse(TtsLsResponse ttsLsResponse, List file_ls, String botName) { + String pre = Initialize.getServerUrlCdn()+"/api/audio/cache/"+botName+"/?filename="; + for (String path: file_ls) { + TtsLsAudio audio = new TtsLsAudio(); + if (path.equals(Initialize.getThirdParty())) { + audio.setUrl(path); + audio.setB64(path); + ttsLsResponse.getAudio().add(audio); + continue; + } + try { + audio.setB64(TTSUtils.readAllFile(path+".b64")); + } catch (Exception e) { + log.error("读取文件{}.b64内容出错:{}", path, e.toString()); + audio.setB64(""); + } + audio.setUrl(pre+path.substring(23)); + ttsLsResponse.getAudio().add(audio); + } + } + + private void buildB64FileNameResponse(TtsLsResponse ttsLsResponse, List file_ls) { + for (String path: file_ls) { + TtsLsAudio audio = new TtsLsAudio(); + if (path.equals(Initialize.getThirdParty())) { + audio.setFilename(path); + audio.setB64(path); + ttsLsResponse.getAudio().add(audio); + continue; + } + path = path+".b64"; + audio.setFilename(path.substring(23)); + try { + audio.setB64(TTSUtils.readAllFile(path)); + } catch (Exception e) { + log.error("读取文件{}内容出错:{}", path, e.toString()); + audio.setB64(""); + } + ttsLsResponse.getAudio().add(audio); + } + } + + private void buildUrlResponse(TtsLsResponse ttsLsResponse, List file_ls, String botName) { + String pre = Initialize.getServerUrlCdn()+"/api/audio/cache/"+botName+"/?filename="; + for (String path: file_ls) { + TtsLsAudio audio = new TtsLsAudio(); + if (path.equals(Initialize.getThirdParty())) { + audio.setUrl(path); + ttsLsResponse.getAudio().add(audio); + continue; + } + if (Files.exists(Paths.get(path))) { + audio.setUrl(pre+path.substring(23)); + } else { + audio.setUrl(pre+path.substring(23)+"&exist=1"); + } + ttsLsResponse.getAudio().add(audio); + } + } + + private void buildUrlFileResponse(TtsLsResponse ttsLsResponse, List file_ls, String botName) { + String pre = Initialize.getServerUrlCdn()+"/api/audio/cache/"+botName+"/?filename="; + for (String path: file_ls) { + TtsLsAudio audio = new TtsLsAudio(); + if (path.equals(Initialize.getThirdParty())) { + audio.setUrl(path); + audio.setFilename(path); + ttsLsResponse.getAudio().add(audio); + continue; + } + String relativePath; + audio.setFilename((relativePath=path.substring(23))+".b64"); + if (Files.exists(Paths.get(path))) { + audio.setUrl(pre+relativePath); + } else { + audio.setUrl(pre+relativePath+"&exist=1"); + } + ttsLsResponse.getAudio().add(audio); + } + } + + private void buildFilenameResponse(TtsLsResponse ttsLsResponse, List file_ls) { + for (String name: file_ls) { + TtsLsAudio audio = new TtsLsAudio(); + audio.setFilename(name.substring(23)); + ttsLsResponse.getAudio().add(audio); + } + } + + public String apiAudio(ApiAudioData apiAudioData) { + List dialogs = apiAudioData.getDialogs(); + // botname不能为空 + String botName = apiAudioData.getAipioneerUsername(); + if (botName == null) botName = "中控"; + else if (StringUtils.isBlank(botName)) return "null"; + boolean allExist = true; + List> futures = new ArrayList<>(); + List file_ls = new ArrayList<>(); + String rootFolderRoot = new StringBuilder(Initialize.getAudioDir()).append(File.separator).append(botName).append(File.separator).toString(); + String uploadFolderRoot = new StringBuilder(rootFolderRoot).append(Initialize.getUploadedDir()).append(File.separator).toString(); + if (!CollectionUtils.isEmpty(dialogs)) { + for (Dialog info : dialogs) { + String uploadFolder, rootFolder; + if (botName.equals(info.getBotAccount()) || StringUtils.isBlank(info.getBotAccount())) { + rootFolder = rootFolderRoot; + uploadFolder = uploadFolderRoot; + } else { + rootFolder = new StringBuilder(Initialize.getAudioDir()).append(File.separator) + .append(info.getBotAccount()).append(File.separator).toString(); + uploadFolder = new StringBuilder(rootFolder).append(Initialize.getUploadedDir()).append(File.separator).toString(); + } + + // person没有值或是不存在则赋予init_person + String person = info.getPerson(); + if (StringUtils.isBlank(person)) person = Initialize.init_person; + + // text 字段不为空 + String text = info.getText(); + if (StringUtils.isBlank(text)) continue; + + String url = null; //moodUrl + String tone = "正常"; // 第三方请求的情绪为:正常 + + // 是否是第三方请求 + boolean isPersonThirdParty = Initialize.getThirdPartyTts().contains(person); + + // 非第三方请求需要对person及tone进行校正,以得到确实存在的url + if (!isPersonThirdParty) { + if (!Initialize.PERSON_MOODURL.containsKey(person)) person = Initialize.init_person; + //log.info("person:{}",person); + + // 确保tone值为person的某个已有的情绪值 + tone = info.getTone() == null ? Initialize.init_tone : info.getTone(); + // + Map moodUrlMap = Initialize.PERSON_MOODURL.get(person); + if (!moodUrlMap.containsKey(tone)) tone = TTSConstants.DEFAULT_MOOD; + if (!moodUrlMap.containsKey(tone)) { + if (person.equals(Initialize.init_person)) tone = Initialize.init_tone; + else tone = moodUrlMap.keySet().iterator().next(); + } + // 获取该person的mood的url地址 + if (StringUtils.endsWith(person,"offline")) url = Initialize.OFFLINE_SERVER; + else url = Initialize.AUDIO_GENERATE_SERVER; + } + + String filepath = null; + // 只处理明确指定要生成的第三方语音及非第三方 + double volume = Double.parseDouble(StringUtils.isBlank(info.getVolume()) ? "0" : info.getVolume()); + double pitch = Double.parseDouble(StringUtils.isBlank(info.getPitch()) ? "0" : info.getPitch()); + double speed = Double.parseDouble(StringUtils.isBlank(info.getSpeed()) ? "1" : info.getSpeed()); + + String npcName = info.getNpcName(); + String fileName = TTSUtils.buildMP3Filename(text); + // 含有npcName字段则先去人工合成目录下找寻,人工没有则去合成目录寻找 + if (StringUtils.isNotBlank(npcName)) { + String path = new StringBuilder(uploadFolder).append(npcName).append(File.separator).append(fileName).toString(); + if (TTSUtils.doesFileExist(path)) filepath = path; + } + if (filepath == null) { + filepath = new StringBuilder(rootFolder).append(person).append(File.separator).append(tone) + .append(File.separator).append(fileName).toString(); + } + + if (!TTSUtils.doesFileExist(filepath)) { + allExist = false; + final GeneralMP3Data data = new GeneralMP3Data(Initialize.getServerName(), text, + person, tone, botName, true, volume, speed, pitch); + if (!isPersonThirdParty) data.setNpcName(npcName); + final String path = filepath; + final String moodUrl = url; + Future future = POOL.submit(() -> { + boolean setSuccess = false; + try { + if ((setSuccess = Boolean.TRUE.equals(stringRedisTemplate.opsForValue() + .setIfAbsent(path, "1", 20, TimeUnit.SECONDS)))) { + if (!TTSUtils.doesFileExist(path)) return generalMP3(moodUrl, data, path, "GET",true); + } + return new ResponseCodeWithData(8, path); + } catch (Exception e) { + log.warn(ExceptionUtils.getStackTrace(e)); + return new ResponseCodeWithData(HttpServletResponse.SC_INTERNAL_SERVER_ERROR, path); + } finally { + if (setSuccess) stringRedisTemplate.delete(path); + } + }); + futures.add(future); + } + file_ls.add(filepath); + } + + // 小爱平台的请求,我们会讲所有mp3文件合在一起,文件路径为(audio_dir)/botname/xiaoai/xxx.mp3, + // 成功则构建请求get_audio接口的请求url,包括参数信息,返回该url + if (file_ls.size() == 1) { + String tmp_audio_name = file_ls.get(0); + if (!allExist) { + POOL.submit(() -> task(futures, tmp_audio_name, file_ls)); + } + // cut "/root/TTS-service/audio" + String result = tmp_audio_name.substring(23); + try { + result = URLEncoder.encode(result, "UTF-8"); + } catch (Exception e) { + log.warn("apiAudio URLEncoder fail"); + result = URLEncoder.encode(result); + } + if (allExist) return result; + else return "a"+result; + } else { + final String tmp_audio_name = StringUtils.join(new String[]{Initialize.getAudioDir(), botName, "xiaoai",TTSUtils.buildMP3Filename(file_ls.toString())}, File.separator); + if (!TTSUtils.doesFileExist(tmp_audio_name)) { + POOL.submit(() -> task(futures, tmp_audio_name, file_ls)); + return "a"+tmp_audio_name.substring(23); + } else { + return tmp_audio_name.substring(23); + } + } + } + return "null"; + } + + private void task(List> futures, String tmp_audio_name, List file_ls) { + try { + // 阻塞等待mp3文件生成成功 + for (Future future : futures) { + try { + ResponseCodeWithData data = future.get(); + if (data == null) { + log.warn("task:data is null"); + return; + } + else if (data.getCode() != HttpServletResponse.SC_OK) { + if (data.getCode() == 8) { + if (file_ls.size() == 1) { + log.info("音箱,单个,不存在,竞争:"+tmp_audio_name); + return; + } + log.info("task:出现竞争情况->"+data.getRes()); + if (data.getRes() != null) { + int count = 0; + while (Boolean.TRUE.equals(stringRedisTemplate.hasKey(data.getRes())) && count < 20) { + try { + Thread.sleep(500); + } catch (Exception e){} + ++count; + } + if (count == 20 && Boolean.TRUE.equals(stringRedisTemplate.hasKey(data.getRes()))) { + log.info("task:等待10仍未等到对方完成该任务->{},file_ls:{}",data.getRes(),file_ls); + return; + } + } + } else { + log.warn("task: 下载音频失败,status="+data.getCode()); + } + return; + } + } catch (Exception e) { + log.error("task 获取结果出错:{}", ExceptionUtils.getStackTrace(e)); + return; + } + } + if (!TTSUtils.doesFileExist(tmp_audio_name)) { + boolean addSuccess = false; + try { + if ((addSuccess=Boolean.TRUE.equals(stringRedisTemplate.opsForValue() + .setIfAbsent(tmp_audio_name, "1", 20, TimeUnit.SECONDS)))) { + if (!TTSUtils.doesFileExist(tmp_audio_name)) { + Files.createDirectories(Paths.get(tmp_audio_name).getParent()); + TTSUtils.combineMp3File(file_ls, tmp_audio_name); + if (!TTSUtils.doesFileExist(tmp_audio_name)) { + log.error("音箱小爱平台的请求,聚合mp3文件失败"); + } + } + } else { + log.info("task:小爱合并音频出现竞争->"+tmp_audio_name+",时间:"+new Date(System.currentTimeMillis())); + } + } catch (Exception e) { + log.error("音箱小爱平台的请求,聚合mp3文件失败:{},file_ls:{}", tmp_audio_name, file_ls); + } finally { + if (addSuccess) stringRedisTemplate.delete(tmp_audio_name); + } + } + } catch (Exception e) { + log.error("合成多个音频文件出错:{}", e.toString()); + } + } + + public static void main(String[] args) { +// List file_ls = new ArrayList<>(); +// file_ls.add("/root/TTS-service/audio/46128715/B32/通用/22d08303d7c18ef3f7d56f30ed1cd0b0.mp3"); +// file_ls.add("/root/TTS-service/audio/46128715/A25_offline/开心/b8a01e3bfe90be43ff2cf9f973d29674.mp3"); +// String tmp_name = TTSUtils.pythonlistToStr(file_ls); +// String tmp_audio_name = StringUtils.join(new String[]{"46128715", "xiaoai", tmp_name}, File.separator); +// String audio = "/api/audio/cache/"+"46128715"+"/?filename="+tmp_audio_name; +// System.out.println(audio); + + String s = "\uD83C\uDD70推荐如下作品:《江湖逆袭记》、《{/test/}穿越小剧本》、《小太阳》\uD83C\uDD71 你可以说:“打开江湖逆袭记”".replaceAll("\\{/.*?/}|\uD83C\uDD70|\uD83C\uDD71", "").trim(); + System.out.println(s); + } +} diff --git a/tts_service/src/main/java/ai/qiwu/com/tts_service/service/baidu/ThirdPartyService.java b/tts_service/src/main/java/ai/qiwu/com/tts_service/service/baidu/ThirdPartyService.java index 106dc7d..711438c 100755 --- a/tts_service/src/main/java/ai/qiwu/com/tts_service/service/baidu/ThirdPartyService.java +++ b/tts_service/src/main/java/ai/qiwu/com/tts_service/service/baidu/ThirdPartyService.java @@ -6,6 +6,7 @@ import ai.qiwu.com.tts_service.common.pcm.Pcm2Wav; import ai.qiwu.com.tts_service.common.TTSConstants; import ai.qiwu.com.tts_service.common.TTSConstants.BAI_DU; import ai.qiwu.com.tts_service.service.LieHuSchedule; +import com.alibaba.fastjson.JSON; import com.baidu.aip.speech.AipSpeech; import com.baidu.aip.speech.TtsResponse; import lombok.extern.slf4j.Slf4j; @@ -81,9 +82,9 @@ public class ThirdPartyService { log.error("写入mp3数据信息失败:{}", e.toString()); } } else { - log.warn("res:{}",res); + log.warn("res:{}", JSON.toJSONString(res)); Integer errorCode = (Integer) res.getResult().get("err_no"); - log.error("错误码:{},错误信息:{}", errorCode, ErrorMsgEnum.findMsgByCode(errorCode)); + log.error("错误码:{},错误信息:{},TEXT:{}", errorCode, ErrorMsgEnum.findMsgByCode(errorCode),text); // if ("SDK108".equals(errorCode)) { // log.error("错误码:SDK108,错误信息:{}", "连接超时或读取数据超时"); // }else { diff --git a/xiaoduhome/src/main/java/ai/qiwu/com/xiaoduhome/controller/XiaoAiController.java b/xiaoduhome/src/main/java/ai/qiwu/com/xiaoduhome/controller/XiaoAiController.java index 7e7e57f..26376f3 100644 --- a/xiaoduhome/src/main/java/ai/qiwu/com/xiaoduhome/controller/XiaoAiController.java +++ b/xiaoduhome/src/main/java/ai/qiwu/com/xiaoduhome/controller/XiaoAiController.java @@ -1,6 +1,9 @@ package ai.qiwu.com.xiaoduhome.controller; +import ai.qiwu.com.xiaoduhome.common.OkHttp3Utils; import ai.qiwu.com.xiaoduhome.pojo.data.XiaoAiPhoneMark; +import ai.qiwu.com.xiaoduhome.spirit.SpiritTerminateRequest; +import ai.qiwu.com.xiaoduhome.xiaoai.common.RequestTerminal; import ai.qiwu.com.xiaoduhome.xiaoai.common.Utils; import ai.qiwu.com.xiaoduhome.xiaoai.model.request.XiaoAiRequest; import ai.qiwu.com.xiaoduhome.xiaoai.model.response.XiaoAiResponse; @@ -18,10 +21,12 @@ import org.springframework.beans.factory.annotation.Autowired; import org.springframework.web.bind.annotation.*; import javax.servlet.http.HttpServletRequest; +import java.io.IOException; import java.io.InputStream; import java.lang.reflect.Type; import java.util.ArrayList; import java.util.Enumeration; +import java.util.HashMap; import static ai.qiwu.com.xiaoduhome.xiaoai.common.XiaoAiConstants.ERROR_MSG.SORRY_REPEAT; @@ -228,7 +233,15 @@ public class XiaoAiController { return response; } - public static void main(String[] args) { - System.out.println(new ArrayList<>().toString()); + public static void main(String[] args) throws IOException { + SpiritTerminateRequest requestPojo = new SpiritTerminateRequest(); + requestPojo.setUid("wetewt23424"); + requestPojo.setMsg("推荐作品"); + requestPojo.setResptype(null); + HashMap ALL_HEADERS = new HashMap<>(); + ALL_HEADERS.put("Content-Type", "application/json;charset=utf-8"); + ALL_HEADERS.put("App-Channel-Id", "xiaoai-jiaoyou-audio-test"); + String resStr = OkHttp3Utils.doPostJsonStr("http://hw-gz19.heyqiwu.cn:8888/centralControl/api/chat2", JSON.toJSONString(requestPojo), ALL_HEADERS); + System.out.println(resStr); } } diff --git a/xiaoduhome/src/main/java/ai/qiwu/com/xiaoduhome/xiaoai/common/RequestTerminal.java b/xiaoduhome/src/main/java/ai/qiwu/com/xiaoduhome/xiaoai/common/RequestTerminal.java index c81196a..d154828 100755 --- a/xiaoduhome/src/main/java/ai/qiwu/com/xiaoduhome/xiaoai/common/RequestTerminal.java +++ b/xiaoduhome/src/main/java/ai/qiwu/com/xiaoduhome/xiaoai/common/RequestTerminal.java @@ -99,4 +99,9 @@ public class RequestTerminal { String requestJsonStr = JSON.toJSONString(requestPojo); OkHttp3Utils.tmallBackPostAsync(ScheduleServiceNew.BASE_HOST_URL+"8070/api/chat2", requestJsonStr, type); } + + public static void main(String[] args) throws IOException { + String s = requestTerminate("12342134dfg", "推荐作品", 2, "http://hw-gz15.heyqiwu.cn:"); + System.out.println(s); + } } -- libgit2 0.27.1