Commit c54f6196 by 苗权威

12.29

parent b3d69a48
......@@ -5,6 +5,7 @@ import lombok.extern.slf4j.Slf4j;
import okhttp3.*;
import okio.BufferedSink;
import okio.Okio;
import org.apache.commons.lang3.StringUtils;
import org.apache.commons.lang3.exception.ExceptionUtils;
import org.jetbrains.annotations.NotNull;
import org.springframework.util.CollectionUtils;
......@@ -86,6 +87,44 @@ public class OkHttp3Utils {
return 0;
}
public static int biaoBeiPost(String url, Map<String, String> headers,
String requestJsonStr, String path) {
try {
Request.Builder builder = new Request.Builder();
Request request = builder.url(url).build();
Headers.Builder headBuilder = request.headers().newBuilder();
Iterator<Map.Entry<String, String>> headIterator = headers.entrySet().iterator();
headIterator.forEachRemaining(e -> headBuilder.add(e.getKey(), e.getValue()));
builder.headers(headBuilder.build()).post(RequestBody.create(MediaType.parse("application/json; charset=utf-8"), requestJsonStr));
Response response = client.newCall(builder.build()).execute();
String conType = response.header("Content-Type");
try (ResponseBody body = response.body()){
int code = response.code();
if (code == HttpServletResponse.SC_OK) {
if (StringUtils.startsWith(conType, "audio")) {
try (BufferedSink sink = Okio.buffer(Okio.sink(new File(path)))){
sink.writeAll(Objects.requireNonNull(body).source());
}
} else {
log.error("biaoBeiPost application/json response: {}, path:{}",body.string(), path);
return 0;
}
}
return code;
}catch (SocketTimeoutException e) {
log.error("捕获到SocketTimeoutException:{}", e.toString());
client.dispatcher().cancelAll();
client.connectionPool().evictAll();
}
} catch (Exception e) {
log.error("postTTSEdition2 error:{}, path:{}", e, path);
}
return 0;
}
public static String getTTSeDITION2(String url, Map<String, String> params, Map<String, String> header) throws IOException {
Request.Builder builder = new Request.Builder();
Request request = builder.url(url).build();
......
......@@ -66,4 +66,11 @@ public interface TTSConstants {
String XIAOAI = "XIAOAI";
String XIAODU = "XIAODU";
}
interface BIAO_BEI {
String YUE_YU_URL = "https://openapi.data-baker.com/tts_cantonese";
String NORMAL_URL = "https://openapi.data-baker.com/tts";
String CLIENT_ID = "";
String CLIENT_SECRET = "";
}
}
......@@ -554,6 +554,22 @@ public class TTSUtils {
return filename;
}
public static Boolean addAudioSlice(String targetPath) {
try {
String temp = targetPath.substring(0, targetPath.lastIndexOf("."))+"_.mp3";
if ("1".equals(CallPython.ffmpegExecute(new StringBuilder("ffmpeg -i ").append(targetPath)
.append(" -i ").append(Initialize.getAudioDir()).append("/silence/250ms.mp3")
.append(" -filter_complex [0:a:0][1:a:0]concat=n=2:v=0:a=1[a] -map [a] -ar 44100 -b:a 64k")
.append(" -y ").append(temp).toString()))) {
Files.move(new File(temp).toPath(), new File(targetPath).toPath(), StandardCopyOption.REPLACE_EXISTING);
return true;
}
} catch (Exception e) {
log.error("changeAudioConfig 修改音频数据出错:targetPath:{}, {}", targetPath, e);
}
return false;
}
public static Boolean changeAudioConfigAddSilence(Integer sampleRate, String bitRate, String targetPath) {
try {
String temp = targetPath.substring(0, targetPath.lastIndexOf("."))+"_.mp3";
......
......@@ -12,10 +12,8 @@ import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.nio.file.StandardCopyOption;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.text.SimpleDateFormat;
import java.util.*;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.Semaphore;
import java.util.stream.Collectors;
......@@ -256,6 +254,29 @@ public class DeployController {
Path pt;
Files.createDirectories((pt=Paths.get(markPath)).getParent());
Files.createFile(pt);
Path botAccountPt = Paths.get(Initialize.getAudioDir()+File.separator+botAccount);
if (!"image_deploy".equals(type) && StringUtils.isNotBlank(botAccount) && Files.exists(botAccountPt)) {
Files.list(botAccountPt)
.filter(path1 -> !StringUtils.startsWith(path1.getFileName().toString(), Initialize.getUploadedDir()))
.forEach(path1 -> FileUtil.deleteFile(path1.toAbsolutePath().toFile()));
Path recordPt = Paths.get(Initialize.getAudioDir()+File.separator+botAccount+File.separator+Initialize.getUploadedDir());
if (Files.exists(recordPt)) {
Files.list(recordPt).forEach(npcNameDir -> {
try {
Files.list(npcNameDir).filter(path1 -> !StringUtils.endsWith(path1.getFileName().toString(), ".mp3"))
.forEach(path1 -> {
try {
Files.delete(path1);
} catch (Exception e) {
// do nothing
}
});
} catch (Exception e) {
log.error("synSysImgTargetServerDownInThread 268:{}, npcNameDir:{}", e, npcNameDir.toString());
}
});
}
}
} catch (IOException e) {
log.error("mark file create fail:{}, botAccount:{},path:{}",e,botAccount,path);
new File(markPath).delete();
......@@ -268,7 +289,7 @@ public class DeployController {
private void synSysImgTargetServerDown(Long length, String path, String sourceServer,String zipDir,String targetDir,
String auth, String botAccount, String type, String gameServer) {
log.warn("/upload/syn/download 开始:"+path);
log.warn("/upload/syn/download 开始:{},sourceServer:{},gameServer:{}, botAccount:{}",path, sourceServer, gameServer, botAccount);
long startTime = System.currentTimeMillis();
int sliceSize = 6*1024*1024;
long start = 0, end = sliceSize-1;
......@@ -348,15 +369,18 @@ public class DeployController {
}
log.error("耗时:"+(System.currentTimeMillis()-startTime));
toChannel.close();
if (StringUtils.isNotBlank(botAccount)) {
FileUtil.deleteFile(new File(Initialize.getAudioDir()+File.separator+botAccount));
}
if ("audio".equals(targetDir)) FileUtil.deleteFile(new File(targetDir));
Files.createDirectories(Paths.get(targetDir));
FileUtil.decompress(tempSliceName+".zip", targetDir);
deleteSlice(zipDir, prefix, botAccount);
params.put("result", "success");
params.put("gameServer", gameServer);
// if (!"image_deploy".equals(type) && StringUtils.isNotBlank(botAccount)) {
//// Files.list(Paths.get(Initialize.getAudioDir()+File.separator+botAccount))
//// .filter(path1 -> !StringUtils.startsWithAny(path1.getFileName().toString(), Initialize.getUploadedDir(), "Baidu", "Liehu", "Tencent", "ProTencent", "XunFei", "Alyun"))
//// .forEach(path1 -> FileUtil.deleteFile(path1.toAbsolutePath().toFile()));
// FileUtil.deleteFile(new File(Initialize.getAudioDir()+File.separator+botAccount+File.separator+"xiaoai"));
// }
ApachHttpUtils.asyncDelete(sourceServer, params, headers);
} catch (IOException e) {
deleteSlice(zipDir, prefix, botAccount);
......@@ -431,6 +455,7 @@ public class DeployController {
@DeleteMapping("/range/download")
public Result delete(String path, String pass, String serverName, String gameServer,@RequestParam(required = false) String result,
@RequestHeader("Authorization") String auth) {
log.warn("delete callback:path:{}, serverName:{}, gameServer:{}, result:{}", path, serverName, gameServer, result);
if (StringUtils.isNotBlank(pass) && StringUtils.startsWith(pass,"mqw") && pass.length() == 6) {
try {
Path pt = Paths.get(path);
......@@ -691,9 +716,8 @@ public class DeployController {
}
public static void main(String[] args) {
String resultStr = "{\"code\":1,\"msg\":\"成功\",\"data\":null}";
ServerResponse serverResponse = JSON.parseObject(resultStr, ServerResponse.class);
System.out.println("serverResponse:"+serverResponse);
// System.out.println(TTSUtils.buildMP3Filename("这是一段测试文本,请听下音效,选择你认为合适的一套声音"));
// System.out.println(new SimpleDateFormat("yyyy-MM-dd").format(
// new Date(System.currentTimeMillis()-30*24*3600000L))+" 00:00:00");
System.out.println("sgtc-watch-sdk-proDeviceId8e000e7006203bf316907bd6f9f207d90b7c69fe@@@gz25bot1030bushushoubiaozho734186495@@@@LqVy2z3r8dshhD97Of7s".length());
}
}
package ai.qiwu.com.tts_service.pojo.third;
import lombok.Getter;
import lombok.Setter;
import java.sql.Timestamp;
/**
* painter
* 20-12-11 下午5:19
*/
@Getter
@Setter
public class BiaoBeiAccessToken {
private String access_token;
private Timestamp expires_in;
}
package ai.qiwu.com.tts_service.pojo.third;
import lombok.Getter;
import lombok.Setter;
/**
* painter
* 20-12-11 下午5:27
*/
@Getter
@Setter
public class BiaoBeiRequestData {
private String text;
private String access_token;
private Integer domain = 1;
private String language = "ZH"; // ENG, 支持粤语参数(cat)
private String voice_name;
private Integer audiotype = 6;
}
......@@ -68,7 +68,7 @@ public class Initialize implements InitializingBean {
/**
* 第三方person列表
*/
private static volatile Set<String> THIRD_PARTY_TTS;
public static volatile Set<String> THIRD_PARTY_TTS;
/**
* 第三方person及其角色识别标识
......@@ -152,6 +152,8 @@ public class Initialize implements InitializingBean {
public static Set<String> xunfeiUseSSMLPerson;
public static Set<String> biaoBeiYueYuPerson;
// private static final int XIAODU_TEXT_SIZE_LIMIT;
// private static final int LIEHU_TEXT_SIZE_LIMIT;
......@@ -454,7 +456,7 @@ public class Initialize implements InitializingBean {
return ZIP_DIR;
}
static String getUploadedDir() {return UPLOADED_DIR;}
public static String getUploadedDir() {return UPLOADED_DIR;}
static String getRecord_callback_url() {
return record_callback_url;
......
......@@ -2,6 +2,7 @@ package ai.qiwu.com.tts_service.service;
import ai.qiwu.com.tts_service.common.OkHttp3Utils;
import ai.qiwu.com.tts_service.common.TTSConstants;
import ai.qiwu.com.tts_service.pojo.third.BiaoBeiAccessToken;
import ai.qiwu.com.tts_service.pojo.third.LieHuTokenResponse;
import com.alibaba.fastjson.JSON;
import com.alibaba.nls.client.AccessToken;
......@@ -31,9 +32,11 @@ public class LieHuSchedule {
// private static final HashMap<String, String> LIE_HU_TOKEN_HEADER;
private static String LIE_HU_TOKEN;
public static volatile NlsClient nlsClient = new NlsClient("26cd4e5cfb6445a9bbf107b3896f573d");
public static volatile NlsClient nlsClient = new NlsClient("3a68162656244a94a75865d7a974462e");
private static volatile AccessToken accessToken;
public static volatile BiaoBeiAccessToken biaoBeiAccessToken;
static {
LIE_HU_TOKEN_PARAMS = new HashMap<>();
// LIE_HU_TOKEN_HEADER = new HashMap<>();
......@@ -45,7 +48,12 @@ public class LieHuSchedule {
// LIE_HU_TOKEN_HEADER.put("Content-Type", "application/json");
}
// @Scheduled(fixedDelay = 3600000, initialDelay = 36000000)
// @Scheduled(fixedDelay = 3600000)
public void scheduleBiaoBei() {
}
// @Scheduled(initialDelay = 7200000, fixedDelay = 3600000)
@Scheduled(fixedDelay = 3600000)
public void scheduleALiTTSToken() {
if (accessToken == null) {
......
......@@ -988,7 +988,7 @@ public class TTService {
// 对于put请求则直接讲wav转为mp3,其他则先判断mp3文件是否存在,
// 不存在对于线下请求则去url地址下载该mp3文件,线上的则直接转wav
boolean fileExist = TTSUtils.doesFileExist(filePath);
if (requestMethod.equals("PUT")) {
if ("PUT".equals(requestMethod)) {
if (fileExist) {
new File(filePath).delete();
}
......@@ -1125,7 +1125,7 @@ public class TTService {
}
// 语音合成目录;audio_dir/botname/person/tone
String usDir = StringUtils.join(new String[]{Initialize.getAudioDir(),data.getBotname(),
data.getPerson(), data.getTone()}, File.separator);
data.getPerson(), data.getTone()}, File.separator);
// 遍历所有变量,若其mp3文件在人工目录下不存在则调用generalMP3方法生成
for (String variableText: variableTextList) {
String variableTextFilename = TTSUtils.buildMP3Filename(variableText);
......
......@@ -857,6 +857,7 @@ public class TTServiceEdition2 {
}
private ResponseCodeWithData dealThirdParty(String text, String person, String filepath) {
// log.warn("dealThirdParty:text:{}, person:{}, filepath:{}", text, person, filepath);
boolean result;
// 去除所有{/../}
// text = text.replaceAll("[\uD83C\uDD70\uD83C\uDD71]", "").trim();
......@@ -1548,10 +1549,24 @@ public class TTServiceEdition2 {
// builder.append("concat=n=").append(filePathList.size()*2).append(":v=0:a=1[a] -map [a] ").append("out.mp3");
// System.out.println(builder);
System.out.println(new StringBuilder("ffmpeg -i ").append("1.mp3")
.append(" -i ").append("/root").append("/silence/250ms.mp3")
.append(" -filter_complex [0:a:0][1:a:0]concat=n=2:v=0:a=1[a] -map [a] -ar ").append("44100")
.append(" -b:a ").append("64k")
.append(" -y ").append("2.mp3").toString());
// System.out.println(new StringBuilder("ffmpeg -i ").append("1.mp3")
// .append(" -i ").append("/root").append("/silence/250ms.mp3")
// .append(" -filter_complex [0:a:0][1:a:0]concat=n=2:v=0:a=1[a] -map [a] -ar ").append("44100")
// .append(" -b:a ").append("64k")
// .append(" -y ").append("2.mp3").toString());
// String text = "【姜赫@正常】石岳为我耐心的讲解了那些我看不懂的地方。虽然有些感觉暴躁,讲的却极为详细。看他的样子就不像是一个为别人耐心讲解的人,没想到竟尤为负责。【石岳@正常】倒是忘了你们没接触过这些东西,看不懂很正常,现在懂了吧。【旁白@正常】回宿舍吗?,师傅,书上的我看不懂";
String text = "【小悟@正常】我不理解";
Map<String, String> roleAnswer = new HashMap<>();
int l = text.indexOf("【"), j, k;
String role;
while (l != -1) {
j = text.indexOf("@", l);
role = text.substring(l+1, j);
k = text.indexOf("】", j+1);
l = text.indexOf("【", k+1);
roleAnswer.put(role, text.substring(k+1, l == -1 ? text.length() : l).trim());
}
System.out.println(roleAnswer);
}
}
......@@ -33,6 +33,7 @@ import org.springframework.util.DigestUtils;
import javax.crypto.Mac;
import javax.crypto.spec.SecretKeySpec;
import javax.servlet.http.HttpServletResponse;
import java.io.*;
import java.net.URL;
import java.net.URLEncoder;
......@@ -120,6 +121,18 @@ public class ThirdPartyService {
return false;
}
}
case "Baker": {
try {
if (text.length() > 250 && text.getBytes(StandardCharsets.UTF_8).length > 1024) {
} else {
dealBiaoBei(per, text, filepath);
}
} catch (Exception e) {
log.error("biaoBeiTTS error:{}, text:{}, filepath:{}", e, text, filepath);
return false;
}
}
// 150 字节, 测试上限约50汉字
case "Tence" : {
if (text.length() > 45) {
......@@ -162,6 +175,26 @@ public class ThirdPartyService {
// return false;
}
// ============== biao bei ==============
private static boolean dealBiaoBei(String per, String text, String filepath) {
String url = TTSConstants.BIAO_BEI.NORMAL_URL;
BiaoBeiRequestData requestData = new BiaoBeiRequestData();
if (Initialize.biaoBeiYueYuPerson.contains(per)) {
url = TTSConstants.BIAO_BEI.YUE_YU_URL;
requestData.setLanguage("cat");
}
requestData.setAccess_token(LieHuSchedule.biaoBeiAccessToken.getAccess_token());
requestData.setText(text);
requestData.setVoice_name(per);
int result = OkHttp3Utils.biaoBeiPost(url, Collections.emptyMap(), JSON.toJSONString(requestData), filepath);
if (HttpServletResponse.SC_OK != result) {
log.error("dealBiaoBei response http statue is not 200,code:{}, path:{}", result, filepath);
return false;
}
return true;
}
// ============== ALI =======================
private static boolean dealAliYun(String per, String text, String filepath) {
......
Markdown is supported
0% or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment