Commit efc1a429 by 苗权威

6.24

parent 56b44d98
......@@ -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"));
}
}
}
......@@ -1207,20 +1207,59 @@ public class SpiritAudioUpload {
return ApachHttpUtils.getProbe(path, headers);
}
private static void jmeter(List<String> recommendWordList, CSVPrinter csvPrinter, String uid, List<String> keyList,
int index, int botCount, Map<String, String> 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<String, String> 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<String> recommendWordList = new ArrayList<>();
Map<String, String> 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<String> 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();
}
}
}
......@@ -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<HttpResponse> asyncFileDataDownloadGet(String url, Map<String, String> params,
Map<String, String> headers, String tarPath,
ConcurrentHashMap<String, Boolean> recordAlreadyFineSlice) {
public static Boolean audioSliceGet(String url, Map<String, String> params,
Map<String, String> headers, String tarPath) {
try {
URIBuilder builder = new URIBuilder(url, StandardCharsets.UTF_8);
if (!CollectionUtils.isEmpty(params)) {
List<NameValuePair> list = new ArrayList<>();
BasicNameValuePair param;
for (Map.Entry<String, String> 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<String, String> 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<HttpResponse> asyncFileDataDownloadGet(String url, Map<String, String> params, Map<String, String> headers,
String tarPath, ConcurrentHashMap<String, String> 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<HttpResponse> callback = new FutureCallback<HttpResponse>() {
......@@ -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;
}
}
......@@ -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);
}
......
......@@ -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<String> str = filePathList.stream().map(s -> "-i "+s).collect(Collectors.toList());
StringBuilder builder = new StringBuilder("ffmpeg ").append(StringUtils.join(str, " ")).append(" -filter_complex ");
......
......@@ -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));
}
}
......
......@@ -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<String, String> params = new HashMap<>();
params.put("path", path);
params.put("pass", "mqw"+RandomStringUtils.random(3));
params.put("serverName", Initialize.getServerName());
Map<String, String> 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<String, Boolean> recordAlreadyFineSlice = new ConcurrentHashMap<>();
ConcurrentHashMap<String, String> 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);
}
}
}
......@@ -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);
}
}
}
......@@ -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);
}
}
......@@ -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) {
......
......@@ -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;
}
}
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;
}
......@@ -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<String> getTheOfflineJumpPersonInfo(String person, String mood) {
Map<String, Integer> 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<String> list = new ArrayList<>();
list.add(init_person);
list.add(init_tone);
log.warn("没有获取到该人物情绪对应的线上person选用默认");
return list;
}
}
......@@ -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<ResponseCodeWithData> 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<String> 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));
}
}
}
}
......@@ -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 {
......
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<String, String> 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);
}
}
......@@ -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);
}
}
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