Commit 38d0c4d0 by 苗权威

9.27

parent a7e65528
......@@ -10,6 +10,10 @@
<file type="web" url="file://$PROJECT_DIR$/xiaodu" />
<file type="web" url="file://$PROJECT_DIR$/xiaoya" />
</component>
<component name="JavadocGenerationManager">
<option name="OUTPUT_DIRECTORY" value="/home/yf01/下载/tts/" />
<option name="OPTION_SCOPE" value="private" />
</component>
<component name="MavenProjectsManager">
<option name="originalFiles">
<list>
......
......@@ -99,13 +99,14 @@ public class OkHttp3Utils {
return doPost(url , new HashMap<>(), new HashMap<>(), file);
}
public static String doPostJsonStr(String url, String requestJsonStr) throws IOException {
public static String doPostJsonStr(String url, String requestJsonStr, HashMap<String, String> headers) throws IOException {
Request.Builder builder = new Request.Builder();
Request request = builder.url(url).build();
Headers.Builder headBuilder = request.headers().newBuilder();
headBuilder.add("Content-Type","application/json; charset=utf-8");
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));
try (Response response = client.newCall(builder.build()).execute()){
......
......@@ -108,7 +108,7 @@ public class TTSController {
String tid = mulRequest.getParameter("tid");
UploadOneSenData data = new UploadOneSenData(Integer.valueOf(tid), botName, npcName, text, file);
ttService.uploadOneSen(data, response);
ttService.uploadOneSen(data, response, request.getHeader("Authorization"));
}
// @PostMapping("/api/upload/record/one_npc")
......@@ -125,12 +125,13 @@ public class TTSController {
String botName = mulRequest.getParameter("botName");
String npcName = mulRequest.getParameter("npcName");
UploadOneSenData data = new UploadOneSenData(botName, npcName, file);
ttService.uploadOneNpc(data, response);
ttService.uploadOneNpc(data, response, request.getHeader("Authorization"));
}
@DeleteMapping("/api/delete/record/one_sen")
public void deleteOneSen(@RequestBody UploadOneSenData data,HttpServletResponse response) {
ttService.delOneSen(data, response);
public void deleteOneSen(@RequestBody UploadOneSenData data,HttpServletResponse response,HttpServletRequest request) {
String head = request.getHeader("Authorization");
ttService.delOneSen(data, response, head);
}
@PostMapping("/api/offline_callback")
......
package ai.qiwu.com.tts_service.service;
import ai.qiwu.com.tts_service.common.OkHttp3Utils;
import ai.qiwu.com.tts_service.common.TTSUtils;
import ai.qiwu.com.tts_service.common.TTServiceUtil;
import ai.qiwu.com.tts_service.pojo.TTSResponse;
import ai.qiwu.com.tts_service.pojo.upload.UploadCallbackResponse;
import ai.qiwu.com.tts_service.pojo.upload.UploadOneSenData;
import com.alibaba.fastjson.JSON;
import com.csvreader.CsvReader;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.apache.commons.lang3.exception.ExceptionUtils;
import javax.servlet.http.HttpServletResponse;
import java.io.*;
import java.nio.charset.Charset;
import java.nio.file.Files;
import java.util.*;
/**
* @author 苗权威
* @dateTime 19-9-27 下午1:56
*/
@Slf4j
public class Test {
public static void uploadOneNpc(UploadOneSenData data) {
final String folder = "/home/yf01/下载/tts/test/齐齐";
// zipDir(专门存放压缩包及解压缩后的文件的)/botname+timestamp(确保文件名唯一,防止统一用户删除操作与上传操作的冲突)
final String zipFolder = "/home/yf01/下载/tts/test/zipFolder";
// 构建服务器上该压缩包的绝对路径
String zipFilename = "齐齐.zip";
String filename = new StringBuilder(zipFolder).append(File.separator).append(zipFilename).toString();
// 检查压缩包格式是否正确,标准是不含有目录
if (!TTSUtils.checkZipFile(filename)){
log.info("压缩包结构不正确");
return;
}
// 解压
if (!TTSUtils.unZip(zipFolder, filename)) {
log.info("压缩包解压失败");
return;
}
// 压缩包中之应该只含有一个csv文件
File[] csvFiles = new File(zipFolder).listFiles((dir, name) -> StringUtils.endsWith(name, ".csv"));
if (csvFiles == null || csvFiles.length != 1) {
int count = csvFiles == null ? 0 : csvFiles.length;
log.info("csv文件数量为"+count);
return;
}
File csvFile = csvFiles[0];
// 判断该文件的编码
String encoding = TTSUtils.charset(csvFile);
log.info("encoding:{}",encoding);
// 意料之外的错误发生,无法判断程序进度,记录该种情况最后根据情况返回相应的信息
final List<String> needDeleteB64File = new ArrayList<>();
Set<String> successUpLoadFileIds = new HashSet<>();
HashSet<String> textSet = new HashSet<>();
List<String> failList = new ArrayList<>();
int repeate = 0;
CsvReader reader = null;
try {
reader = new CsvReader(csvFile.getAbsolutePath(), ',', Charset.forName(encoding));
int all = 0;
int empty = 0;
int noeTextSameId = 0;
while (reader.readRecord()) {
all++;
// id,text,isUpload,filename
if (StringUtils.isBlank(reader.get(3))) {
empty++;
continue;
}
//keng55.add(reader.get(0));
if (!textSet.add(reader.get(1))) {
boolean bn = successUpLoadFileIds.add(reader.get(0));
if (!bn) repeate++;
continue;
}
String md5Name = TTSUtils.buildMP3Filename(reader.get(1)); //构造mp3文件名
String audioFileName = reader.get(3);
boolean hasSuffix = StringUtils.endsWith(audioFileName,".mp3") || StringUtils.endsWith(audioFileName,".MP3");
if (!hasSuffix) audioFileName = audioFileName+".mp3";
String fileInPackage = new StringBuilder(zipFolder).append(File.separator).append(audioFileName).toString();
final String usFilename = new StringBuilder(folder).append(File.separator).append(md5Name).toString();
boolean doesFileExit = TTSUtils.doesFileExist(fileInPackage);
if (!doesFileExit && !hasSuffix) {
fileInPackage = new StringBuilder(zipFolder).append(File.separator)
.append(reader.get(3)).append(".MP3").toString();
doesFileExit = TTSUtils.doesFileExist(fileInPackage);
}
if (doesFileExit) {
File usFile = new File(usFilename);
boolean result=true;
// 删除之前的旧文件
if (TTSUtils.doesFileExist(usFilename)) {
result = usFile.delete();
}
// 删除成功后删除其b64文件,且将压缩包中的文件移到安置目录下,即
// /root/TTS-service/mqwZip/audioFilename -> audio_dir/botname/record/npcname/xxx.mp3
if (result) {
needDeleteB64File.add(new StringBuilder(usFilename).append(".b64").toString());
try {
Files.copy(new File(fileInPackage).toPath(), usFile.toPath());
boolean re = successUpLoadFileIds.add(reader.get(0));
if (!re) noeTextSameId++;
} catch (Exception e) {
failList.add(reader.get(0));
textSet.remove(reader.get(1));
}
}else {
failList.add(reader.get(0));
textSet.remove(reader.get(1));
log.error("删除之前的就音频失败:{}",fileInPackage);
}
} else {
textSet.remove(reader.get(1));
failList.add(reader.get(0));
}
}
System.out.println("all:"+all);
System.out.println("empty:"+empty);
System.out.println("noeTextSameId:"+noeTextSameId);
} catch (Exception e) {
log.error("解析csv文件出错:{}",ExceptionUtils.getStackTrace(e));
return;
} finally {
if (reader != null) reader.close();
}
//log.info("msg:{}",msg);
if (failList.size() == 0) {
log.info("全部成功,id列表大小"+(successUpLoadFileIds.size()+repeate));
} else {
if (failList.get(0).equals("内部代号")) failList.remove(0);
if (failList.size() == 0) {
log.info("222全部成功,id列表大小"+(successUpLoadFileIds.size()+repeate));
return;
}
log.info("没有全部成功,失败的id有:"+failList);
}
}
private static void test2(Set<String> successIds) throws IOException {
String target = "/home/yf01/下载/tts/test/target.csv";
CsvReader reader = new CsvReader(target, ',', Charset.forName("UTF-8"));
List<String> missIds = new ArrayList<>();
System.out.println("list size:"+successIds.size());
while (reader.readRecord()) {
if (!successIds.contains(reader.get(0))) {
missIds.add(reader.get(0));
}
}
System.out.println("length:"+missIds.size());
System.out.println(missIds);
}
private static void test3() throws IOException {
String target = "/home/yf01/下载/tts/test/target.csv";
CsvReader reader = new CsvReader(target, ',', Charset.forName("UTF-8"));
HashMap<String, String> idText = new HashMap<>();
int i = 0;
while (reader.readRecord()) {
if (StringUtils.isBlank(reader.get(3))) continue;
//String res = idText.putIfAbsent(reader.get(0), reader.get(1));
String res;
if ((res = idText.get(reader.get(0))) != null) {
if (!res.equals(reader.get(1))) i++;
} else idText.put(reader.get(0), reader.get(1));
}
System.out.println(i);
}
private static void test4() throws IOException {
String target = "/home/yf01/下载/猎狗-人工配音关系对于表.csv";
CsvReader reader = new CsvReader(new BufferedReader(new InputStreamReader(new FileInputStream(target),Charset.forName("UTF-8"))), ',');
HashMap<String, String> idText = new HashMap<>();
int i = 0;
while (reader.readRecord()) {
System.out.println(reader.get(1));
System.out.println(reader.get(1).length());
}
reader.close();
System.out.println("///////////////////////////");
BufferedReader readers = new BufferedReader(new InputStreamReader(new FileInputStream(target), Charset.forName("UTF-8")));
readers.readLine();
String row;
int j = 0;
while ((row = readers.readLine()) != null) {
j++;
String[] arr = row.split(",");
System.out.println(Arrays.toString(arr));
}
System.out.println("jjjj:"+j);
readers.close();
}
public static void main(String[] args) throws IOException {
// long start = System.currentTimeMillis();
// uploadOneNpc(null);
// System.out.println(System.currentTimeMillis()-start);
// String folder = "/home/yf01/下载/tts/test/齐齐";
// File file = new File(folder);
// int i = 0;
// for (File f: file.listFiles()) {
// if (f.getName().length() <= 8) {
// i++;
// System.out.println(f.getName()+" ");
// }
// }
// System.out.println(i);
test4();
}
}
......@@ -12,16 +12,26 @@ import java.util.Map;
import java.util.concurrent.TimeUnit;
/**
* 网络请求封装类
* @author 苗权威
* @dateTime 19-7-18 上午10:54
*/
@Slf4j
public class OkHttp3Utils {
/**
* 客户端对象
*/
private static OkHttpClient client = new OkHttpClient.Builder()
.connectTimeout(10, TimeUnit.SECONDS)
.readTimeout(12, TimeUnit.SECONDS)
.build();
/**
* Get请求
* @param url 请求地址
* @return
* @throws IOException
*/
public static String doGet(String url) throws IOException {
return doGet(url, new HashMap<>());
}
......
......@@ -15,9 +15,25 @@ import org.springframework.web.bind.annotation.*;
@Slf4j
public class XiaoAiController {
/**
* 功能实现类
*/
private final XiaoAiService xiaoAiService;
/**
* 构造函数的方式注入XiaoAiService
* @param xiaoAiService 功能实现类
*/
@Autowired
private XiaoAiService xiaoAiService;
public XiaoAiController(XiaoAiService xiaoAiService) {
this.xiaoAiService = xiaoAiService;
}
/**
* Controller控制器
* @param request
* @return
*/
@RequestMapping("/xiaoai")
public XiaoAiResponse xiaoai(@RequestBody XiaoAiRequest request) {
//log.info("请求:"+request);
......
......@@ -30,14 +30,27 @@ import static ai.qiwu.mi.xiaoai.commons.XiaoAiConstants.ERROR_MSG.SORRY_REPEAT;
@Service
@Slf4j
public class XiaoAiService {
/**
* cpu个数,包括核
*/
private static final int CORE = Runtime.getRuntime().availableProcessors();
/**
* 线程池,核心线程书为核数+1,最大线程数为1500,非核心线程空闲时间为2.5s
*/
private static final ThreadPoolExecutor POOL = new ThreadPoolExecutor(CORE+1, 1500,
2500, TimeUnit.MILLISECONDS, new ArrayBlockingQueue<>(CORE), new ThreadPoolExecutor.CallerRunsPolicy());
/**
* 缓存上次超时的响应结果,下次返回给用户
*/
private static final ConcurrentHashMap<String, XiaoAiResponse> LAST_OUTTIME_RESULT = new ConcurrentHashMap<>();
public static volatile String deviceId;
/**
* 处理不同意图,type为0则说明是启动,为1则说明是会话进行中,为2则说明用户退出
* @param request 封装请求信息
* @return 响应结果
*/
public XiaoAiResponse getResponse(XiaoAiRequest request) {
String userId = getUserId(request);
int type = request.getRequest().getType();
......@@ -89,6 +102,11 @@ public class XiaoAiService {
// return buildAudioResponse(audioUrl);
// }
/**
* 构建基础返回信息,注意is_session_end字段置为false,
* open_mic这个字段很重要,他会在播放音频或是tts结束后,开麦收音,因为默认麦是关闭的,若不主动打开则小爱在一次会话后退出技能。
* @return 小爱返回信息
*/
private XiaoAiResponse buildResponse() {
XiaoAiResponse response = new XiaoAiResponse();
response.setVersion("1.0");
......@@ -102,6 +120,11 @@ public class XiaoAiService {
return response;
}
/**
* 构建语音返回信息
* @param audioUrl 音频文件地址
* @return 小爱返回信息
*/
private XiaoAiResponse buildAudioResponse(String audioUrl) {
XiaoAiResponse response = buildResponse();
Response responseInfo = response.getResponse();
......@@ -120,6 +143,11 @@ public class XiaoAiService {
return response;
}
/**
* 构建文字返回信息
* @param text 文字
* @return 小爱返回信息
*/
private XiaoAiResponse buildTextResponse(String text) {
XiaoAiResponse response = buildResponse();
Response responseInfo = response.getResponse();
......@@ -132,11 +160,23 @@ public class XiaoAiService {
return response;
}
/**
* 处理启动意图,返回欢迎语
* @param request 请求信息
* @return 响应信息
*/
private XiaoAiResponse dealWithLaunchRequest(XiaoAiRequest request) {
if (deviceId == null) deviceId = getUserId(request);
return buildTextResponse(TTS.WELCOME_WORD);
}
/**
* 处理正常会话意图;
* 将任务提交线程池,监控其执行时间,若1.8s内没有返回则判为超时,提示用户稍等,下一次再将结果返回给用户
* @param request 请求信息
* @param userId 用户在小爱上的id
* @return 响应信息
*/
private XiaoAiResponse dealWithIntentRequest(XiaoAiRequest request, String userId) {
Boolean idle = request.getRequest().getNo_response();
if (idle != null && idle) {
......@@ -171,6 +211,11 @@ public class XiaoAiService {
return LAST_OUTTIME_RESULT.remove(userId);
}
/**
* 处理用户退出意图,先向中控发送“退出”,之后返回结束语
* @param userId 用户id
* @return 返回信息
*/
private XiaoAiResponse dealWithEndRequest(String userId) {
POOL.submit(() -> {
try {
......@@ -183,6 +228,11 @@ public class XiaoAiService {
return buildTextResponse(TTS.END_BYE);
}
/**
* 获取用户id
* @param request 请求信息
* @return 用户id
*/
private String getUserId(XiaoAiRequest request) {
String userId = request.getContext().getDevice_id();
if (userId == null) {
......@@ -198,6 +248,9 @@ public class XiaoAiService {
return LAST_OUTTIME_RESULT.remove(userId);
}
/**
* 任务封装类
*/
class Task implements Runnable {
private String userId;
private String userWord;
......
......@@ -7,12 +7,17 @@ import com.csvreader.CsvWriter;
import com.eclipsesource.json.JsonObject;
import lombok.*;
import org.apache.commons.lang3.StringUtils;
import org.apache.commons.lang3.exception.ExceptionUtils;
import org.springframework.util.DigestUtils;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.net.URLDecoder;
import java.nio.ByteBuffer;
import java.nio.charset.Charset;
import java.nio.charset.StandardCharsets;
import java.nio.file.Files;
import java.sql.Timestamp;
import java.text.SimpleDateFormat;
import java.util.*;
......@@ -189,31 +194,38 @@ public class TestBuild {
if (srcOver != srcReader.readRecord()) System.out.println("大小不一致");
}
public static void getNum(String target) throws IOException {
CsvReader srcReader = new CsvReader(target, ',',Charset.forName("UTF-8"));
srcReader.readHeaders();
HashSet<String> set = new HashSet<>();
while (srcReader.readRecord()) {
//String[] arr = srcReader.getRawRecord().split(",");
if (StringUtils.isBlank(srcReader.get(3))) {
System.out.print(srcReader.get(0)+" ");
continue;
public static String buildMP3Filename(String filename) {
String file = DigestUtils.md5DigestAsHex(filename.getBytes(StandardCharsets.UTF_8));
file = file+".mp3";
return file;
}
if (srcReader.get(3).lastIndexOf(".") != -1 &&
(!StringUtils.endsWith(srcReader.get(3),".mp3") && !StringUtils.endsWith(srcReader.get(3),".MP3"))) continue;
set.add(srcReader.get(0));
public static boolean doesFileExist(String filePath) {
File file = new File(filePath);
if (file.exists()) {
//log.info("文件:{},大小为:{}", filePath, file.length());
if (file.length() == 0) {
if (file.delete()) {
System.out.println("大小为0的文件, 删除成功:"+filePath);
} else {
System.out.println("大小为0的文件, 删除成功:"+filePath);
}
System.out.println(set.size());
return false;
}
return true;
}
return false;
}
public static void main(String[] args) throws IOException {
String target = "/home/yf01/下载/tts/target.csv";
String target = "/home/yf01/下载/tts/齐齐/target.csv";
String target2 = "/home/yf01/下载/target.csv";
String src = "/home/yf01/下载/齐齐-人工配音关系对于表(2).csv";
String srcModify = "/home/yf01/下载/qiOld.csv";
String v2 = "/home/yf01/下载/qiNew.csv";
//csvUtil(target, src, srcModify, v2);
//check(src, srcModify, target);
getNum(srcModify);
}
}
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