Commit 35f456ef by 苗权威

12.27

parent 46b40227
This source diff could not be displayed because it is too large. You can view the blob instead.
...@@ -11,7 +11,7 @@ ...@@ -11,7 +11,7 @@
<groupId>ai.qiwu.tmall</groupId> <groupId>ai.qiwu.tmall</groupId>
<artifactId>spirit</artifactId> <artifactId>spirit</artifactId>
<version>0.0.1-SNAPSHOT</version> <version>0.0.1-SNAPSHOT</version>
<packaging>war</packaging> <!--<packaging>war</packaging>-->
<name>spirit</name> <name>spirit</name>
<description>Tmall spirit project</description> <description>Tmall spirit project</description>
...@@ -23,12 +23,6 @@ ...@@ -23,12 +23,6 @@
<dependency> <dependency>
<groupId>org.springframework.boot</groupId> <groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId> <artifactId>spring-boot-starter-web</artifactId>
<exclusions>
<exclusion>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-tomcat</artifactId>
</exclusion>
</exclusions>
</dependency> </dependency>
<dependency> <dependency>
...@@ -36,7 +30,10 @@ ...@@ -36,7 +30,10 @@
<artifactId>spring-boot-starter-test</artifactId> <artifactId>spring-boot-starter-test</artifactId>
<scope>test</scope> <scope>test</scope>
</dependency> </dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-jpa</artifactId>
</dependency>
<dependency> <dependency>
<groupId>com.tmall.spirit</groupId> <groupId>com.tmall.spirit</groupId>
<artifactId>tmall-sdk</artifactId> <artifactId>tmall-sdk</artifactId>
...@@ -44,39 +41,79 @@ ...@@ -44,39 +41,79 @@
<scope>system</scope> <scope>system</scope>
<systemPath>${project.basedir}/src/main/resources/lib/aliGenie-intent-sematic.jar</systemPath> <systemPath>${project.basedir}/src/main/resources/lib/aliGenie-intent-sematic.jar</systemPath>
</dependency> </dependency>
<dependency>
<!-- https://mvnrepository.com/artifact/org.apache.httpcomponents/httpclient --> <groupId>com.google.guava</groupId>
<artifactId>guava</artifactId>
<version>18.0</version>
</dependency>
<dependency>
<groupId>com.google.code.gson</groupId>
<artifactId>gson</artifactId>
<version>2.8.5</version>
</dependency>
<!--&lt;!&ndash;添加servlet-api的依赖,用来打war包 &ndash;&gt;-->
<!--<dependency>-->
<!--<groupId>javax.servlet</groupId>-->
<!--<artifactId>javax.servlet-api</artifactId>-->
<!--<version>LATEST</version>-->
<!--<scope>provided</scope>-->
<!--</dependency>-->
<dependency>
<groupId>ws.schild</groupId>
<artifactId>jave-core</artifactId>
<version>2.7.1</version>
</dependency>
<!-- https://mvnrepository.com/artifact/ws.schild/jave-native-linux64 -->
<dependency>
<groupId>ws.schild</groupId>
<artifactId>jave-native-linux64</artifactId>
<version>2.4.6</version>
</dependency>
<!-- https://mvnrepository.com/artifact/ws.schild/jave-native-linux32 -->
<dependency>
<groupId>ws.schild</groupId>
<artifactId>jave-native-linux32</artifactId>
<version>2.4.6</version>
</dependency>
<dependency> <dependency>
<groupId>org.apache.httpcomponents</groupId> <groupId>org.apache.httpcomponents</groupId>
<artifactId>httpclient</artifactId> <artifactId>httpclient</artifactId>
<version>4.5.8</version> </dependency>
<!-- https://mvnrepository.com/artifact/org.apache.httpcomponents/httpmime -->
<dependency>
<groupId>org.apache.httpcomponents</groupId>
<artifactId>httpmime</artifactId>
</dependency> </dependency>
<dependency> <dependency>
<groupId>com.alibaba</groupId> <groupId>com.alibaba</groupId>
<artifactId>fastjson</artifactId> <artifactId>fastjson</artifactId>
<version>1.2.60</version> <version>1.2.62</version>
</dependency> </dependency>
<dependency> <dependency>
<groupId>com.google.guava</groupId> <groupId>org.projectlombok</groupId>
<artifactId>guava</artifactId> <artifactId>lombok</artifactId>
<version>18.0</version> <version>1.18.8</version>
<scope>provided</scope>
</dependency> </dependency>
<dependency> <dependency>
<groupId>com.google.code.gson</groupId> <groupId>org.apache.commons</groupId>
<artifactId>gson</artifactId> <artifactId>commons-lang3</artifactId>
<version>2.8.5</version> <version>3.9</version>
</dependency> </dependency>
<!--添加servlet-api的依赖,用来打war包 -->
<dependency> <dependency>
<groupId>javax.servlet</groupId> <groupId>mysql</groupId>
<artifactId>javax.servlet-api</artifactId> <artifactId>mysql-connector-java</artifactId>
<version>LATEST</version> <scope>runtime</scope>
<scope>provided</scope> </dependency>
<dependency>
<groupId>org.apache.commons</groupId>
<artifactId>commons-csv</artifactId>
<version>1.7</version>
</dependency> </dependency>
</dependencies> </dependencies>
<build> <build>
<finalName>Spirit</finalName> <finalName>spirit</finalName>
<plugins> <plugins>
<plugin> <plugin>
<groupId>org.springframework.boot</groupId> <groupId>org.springframework.boot</groupId>
...@@ -96,19 +133,19 @@ ...@@ -96,19 +133,19 @@
</compilerArguments> </compilerArguments>
</configuration> </configuration>
</plugin> </plugin>
<plugin> <!--<plugin>-->
<groupId>org.apache.maven.plugins</groupId> <!--<groupId>org.apache.maven.plugins</groupId>-->
<artifactId>maven-war-plugin</artifactId> <!--<artifactId>maven-war-plugin</artifactId>-->
<version>3.2.3</version> <!--<version>3.2.3</version>-->
<configuration> <!--<configuration>-->
<webResources> <!--<webResources>-->
<resource> <!--<resource>-->
<directory>${project.basedir}/src/main/resources/lib</directory> <!--<directory>${project.basedir}/src/main/resources/lib</directory>-->
<targetPath>WEB-INF/lib</targetPath> <!--<targetPath>WEB-INF/lib</targetPath>-->
</resource> <!--</resource>-->
</webResources> <!--</webResources>-->
</configuration> <!--</configuration>-->
</plugin> <!--</plugin>-->
</plugins> </plugins>
</build> </build>
......
package ai.qiwu.tmall.spirit.common;
import lombok.extern.slf4j.Slf4j;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.NameValuePair;
import org.apache.http.ParseException;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.config.RequestConfig;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpOptions;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.client.utils.URIBuilder;
import org.apache.http.client.utils.URIUtils;
import org.apache.http.client.utils.URLEncodedUtils;
import org.apache.http.entity.ContentType;
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.HttpClients;
import org.apache.http.impl.conn.PoolingHttpClientConnectionManager;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.protocol.HTTP;
import org.apache.http.util.EntityUtils;
import org.springframework.util.CollectionUtils;
import java.io.BufferedReader;
import java.io.File;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.URI;
import java.nio.charset.Charset;
import java.nio.charset.StandardCharsets;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
/**
* @author 苗权威
* @dateTime 19-12-4 下午7:59
*/
@Slf4j
public class ApachHttpUtils {
private static CloseableHttpClient httpClient;
static {
PoolingHttpClientConnectionManager cm = new PoolingHttpClientConnectionManager();
cm.setMaxTotal(100);
cm.setDefaultMaxPerRoute(50);
httpClient = HttpClients.custom().setConnectionManager(cm).build();
}
public static String option(String url, Map<String, String> headers) {
try {
HttpOptions httpOptions = new HttpOptions(url);
if (!CollectionUtils.isEmpty(headers)) headers.forEach(httpOptions::setHeader);
try (CloseableHttpResponse response = httpClient.execute(httpOptions)){
HttpEntity entity = response.getEntity();
if (entity != null) {
return EntityUtils.toString(entity);
}
}
} catch (IOException e) {
e.printStackTrace();
}
return null;
}
public static String get(String url, Map<String, String> headers, Map<String, String> params) {
try {
URIBuilder uriBuilder = new URIBuilder(url);
if (!CollectionUtils.isEmpty(params)) {
List<NameValuePair> qparams = new ArrayList<>();
for (Map.Entry<String, String> e: params.entrySet()) {
qparams.add(new BasicNameValuePair(e.getKey(), e.getValue()));
}
uriBuilder.setParameters(qparams);
}
HttpGet httpget = new HttpGet(uriBuilder.build());
if (!CollectionUtils.isEmpty(headers)) headers.forEach(httpget::setHeader);
try (CloseableHttpResponse response = httpClient.execute(httpget)){
// 获取响应实体
HttpEntity entity = response.getEntity();
// 打印响应状态
// System.out.println(response.getStatusLine());
if (entity != null) {
return EntityUtils.toString(entity);
// // 打印响应内容长度
// System.out.println("Response content length: " + entity.getContentLength());
// // 打印响应内容
// System.out.println("Response content: " + EntityUtils.toString(entity));
}
} catch (IOException | ParseException e) {
log.error("ApachHttpUtils#get:{}",e);
}
} catch (Exception e) {
log.error("ApachHttpUtils#get:{}",e);
}
return null;
}
public static boolean getProbe(String url, Map<String, String> headers) {
try {
URIBuilder uriBuilder = new URIBuilder(url);
HttpGet httpget = new HttpGet(uriBuilder.build());
if (!CollectionUtils.isEmpty(headers)) headers.forEach(httpget::setHeader);
try (CloseableHttpResponse response = httpClient.execute(httpget)){
HttpEntity entity = response.getEntity();
if (entity != null) EntityUtils.toString(entity);
return response.getStatusLine().getStatusCode() == 200;
} catch (IOException | ParseException e) {
log.error("ApachHttpUtils#get:{}",e);
}
} catch (Exception e) {
log.error("ApachHttpUtils#get:{}",e);
}
return false;
}
public static String post(String url, String jsonString, Map<String, String> headers) {
String result = null;
HttpPost httpPost = new HttpPost(url);
RequestConfig requestConfig = RequestConfig.custom().setConnectTimeout(30000).setConnectionRequestTimeout(30000).setSocketTimeout(30000).build();
httpPost.setConfig(requestConfig);
if (!CollectionUtils.isEmpty(headers)) headers.forEach(httpPost::setHeader);
else {
httpPost.addHeader("Content-type", "application/json; charset=utf-8");
httpPost.setHeader("Accept", "application/json");
}
httpPost.setEntity(new StringEntity(jsonString, Charset.forName("UTF-8")));
try(CloseableHttpResponse response = httpClient.execute(httpPost);
BufferedReader in = new BufferedReader(new InputStreamReader(response.getEntity().getContent()))) {
StringBuilder sb = new StringBuilder();
String line;
while ((line = in.readLine()) != null) {
sb.append(line);
}
result = sb.toString();
} catch (IOException e) {
log.error("post表单请求出错:"+e);
}
return result;
}
public static String requestByPostParts(Map<String,String> map, Map<String,String> headers, String url, Charset charset, File file) {
try {
HttpPost post = new HttpPost(url);
if (!CollectionUtils.isEmpty(headers)) headers.forEach(post::setHeader);
MultipartEntityBuilder multipartEntityBuilder = MultipartEntityBuilder.create();
multipartEntityBuilder.setMode(HttpMultipartMode.BROWSER_COMPATIBLE);
if(map!=null) {
ContentType contentType = ContentType.create(HTTP.PLAIN_TEXT_TYPE, StandardCharsets.UTF_8);
for (Map.Entry<String, String> stringObjectEntry : map.entrySet()) {
String key = stringObjectEntry.getKey();
String value = stringObjectEntry.getValue();
multipartEntityBuilder.addTextBody(key, value, contentType);
}
}
if (file != null) {
multipartEntityBuilder.addBinaryBody("file", file);
}
post.setEntity(multipartEntityBuilder.build());
HttpResponse resp = httpClient.execute(post);
int ret = resp.getStatusLine().getStatusCode();
if (ret != 200) return null;
HttpEntity entity = resp.getEntity();
try (BufferedReader br = new BufferedReader(new InputStreamReader(entity.getContent(), charset))){
StringBuilder responseString = new StringBuilder();
String result = br.readLine();
while (result != null)
{
responseString.append(result);
result = br.readLine();
}
return responseString.toString();
}
} catch (Exception e)
{
log.error(e.toString());
}
return null;
}
}
package ai.qiwu.tmall.spirit.common;
import org.springframework.beans.BeansException;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;
import org.springframework.stereotype.Component;
/**
* @author 苗权威
* @dateTime 19-8-21 下午8:42
*/
@Component
public class BaseHolder implements ApplicationContextAware {
private static ApplicationContext applicationContext;
@Override
public void setApplicationContext(ApplicationContext applicationContext) throws BeansException {
BaseHolder.applicationContext = applicationContext;
}
public static ApplicationContext getApplicationContext() {
return applicationContext;
}
public static <T> T getBean(String beanName) {
return (T) applicationContext.getBean(beanName);
}
}
package ai.qiwu.tmall.spirit.common.config;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.boot.jdbc.DataSourceBuilder;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Primary;
import javax.sql.DataSource;
/**
* @author 苗权威
* @dateTime 19-8-22 下午2:23
*/
@Configuration
public class DataSourceConfig {
// @Primary
// @Bean(name = "primaryDatasourceProperties")
// @Qualifier("primaryDatasourceProperties")
// @ConfigurationProperties(prefix = "spring.datasource.primary")
// public DataSourceProperties primaryDatasourceProperties() {
// return new DataSourceProperties();
// }
@Bean("gameditorDataSource")
@Primary
@Qualifier("gameditorDataSource")
@ConfigurationProperties(prefix = "spring.datasource.gameditor")
public DataSource primaryDataSource() {
return DataSourceBuilder.create().build();
}
@Bean("secondaryDataSource")
@Qualifier("secondaryDataSource")
@ConfigurationProperties(prefix = "spring.datasource.secondary")
public DataSource secondaryDataSource() {
return DataSourceBuilder.create().build();
}
}
package ai.qiwu.tmall.spirit.common.config;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.boot.autoconfigure.orm.jpa.HibernateProperties;
import org.springframework.boot.autoconfigure.orm.jpa.HibernateSettings;
import org.springframework.boot.autoconfigure.orm.jpa.JpaProperties;
import org.springframework.boot.orm.jpa.EntityManagerFactoryBuilder;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Primary;
import org.springframework.data.jpa.repository.config.EnableJpaRepositories;
import org.springframework.orm.jpa.JpaTransactionManager;
import org.springframework.orm.jpa.LocalContainerEntityManagerFactoryBean;
import org.springframework.transaction.PlatformTransactionManager;
import org.springframework.transaction.annotation.EnableTransactionManagement;
import javax.persistence.EntityManager;
import javax.sql.DataSource;
import java.util.Map;
/**
* @author 苗权威
* @dateTime 19-8-22 下午2:30
*/
@Configuration
@EnableTransactionManagement
@EnableJpaRepositories(entityManagerFactoryRef = "entityManagerFactoryGameditor",
transactionManagerRef = "transactionManagerGameditor",
basePackages = {"ai.qiwu.tmall.spirit.repository.gameditor"})
public class GameditorConfig {
@Autowired
@Qualifier("gameditorDataSource")
private DataSource primaryDataSource;
@Primary
@Bean(name = "entityManagerFactoryGameditor")
public LocalContainerEntityManagerFactoryBean entityManagerFactoryPrimary(EntityManagerFactoryBuilder builder,
JpaProperties jpaProperties,
HibernateProperties hibernateProperties) {
Map<String, Object> properties = hibernateProperties.determineHibernateProperties(jpaProperties.getProperties(),
new HibernateSettings());
return builder
.dataSource(primaryDataSource)
.properties(properties)
.packages("ai.qiwu.tmall.spirit.entity.gameditor")
.persistenceUnit("gameditorPersistenceUnit")
.build();
}
@Primary
@Bean(name = "entityManagerGameditor")
public EntityManager entityManager(EntityManagerFactoryBuilder builder,
JpaProperties jpaProperties,HibernateProperties hibernateProperties) {
return entityManagerFactoryPrimary(builder, jpaProperties,hibernateProperties).getObject().createEntityManager();
}
@Primary
@Bean(name = "transactionManagerGameditor")
public PlatformTransactionManager transactionManager(EntityManagerFactoryBuilder builder,
JpaProperties jpaProperties,HibernateProperties hibernateProperties) {
return new JpaTransactionManager(entityManagerFactoryPrimary(builder, jpaProperties, hibernateProperties).getObject());
}
}
package ai.qiwu.tmall.spirit.common.config;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.boot.autoconfigure.orm.jpa.HibernateProperties;
import org.springframework.boot.autoconfigure.orm.jpa.HibernateSettings;
import org.springframework.boot.autoconfigure.orm.jpa.JpaProperties;
import org.springframework.boot.orm.jpa.EntityManagerFactoryBuilder;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.data.jpa.repository.config.EnableJpaRepositories;
import org.springframework.orm.jpa.JpaTransactionManager;
import org.springframework.orm.jpa.LocalContainerEntityManagerFactoryBean;
import org.springframework.transaction.PlatformTransactionManager;
import org.springframework.transaction.annotation.EnableTransactionManagement;
import javax.persistence.EntityManager;
import javax.sql.DataSource;
import java.util.Map;
/**
* @author 苗权威
* @dateTime 19-8-22 下午3:21
*/
@Configuration
@EnableTransactionManagement
@EnableJpaRepositories(entityManagerFactoryRef = "entityManagerFactorySecondary",
transactionManagerRef = "transactionManagerSecondary",
basePackages = {"ai.qiwu.tmall.spirit.repository.secondary"})
public class SecondaryConfig {
@Autowired
@Qualifier("secondaryDataSource")
private DataSource secondaryDataSource;
@Bean(name = "entityManagerFactorySecondary")
public LocalContainerEntityManagerFactoryBean entityManagerFactoryPrimary(EntityManagerFactoryBuilder builder,
JpaProperties jpaProperties,
HibernateProperties hibernateProperties) {
Map<String, Object> properties = hibernateProperties.determineHibernateProperties(jpaProperties.getProperties(),
new HibernateSettings());
return builder
.dataSource(secondaryDataSource)
.properties(properties)
.packages("ai.qiwu.com.xiaoduhome.entity.secondary")
.persistenceUnit("secondaryPersistenceUnit")
.build();
}
@Bean(name = "entityManagerSecondary")
public EntityManager entityManager(EntityManagerFactoryBuilder builder,
JpaProperties jpaProperties, HibernateProperties hibernateProperties) {
return entityManagerFactoryPrimary(builder, jpaProperties,hibernateProperties).getObject().createEntityManager();
}
@Bean(name = "transactionManagerSecondary")
public PlatformTransactionManager transactionManager(EntityManagerFactoryBuilder builder,
JpaProperties jpaProperties, HibernateProperties hibernateProperties) {
return new JpaTransactionManager(entityManagerFactoryPrimary(builder, jpaProperties, hibernateProperties).getObject());
}
}
package ai.qiwu.tmall.spirit.controller;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
/**
* @author 苗权威
* @dateTime 19-12-10 上午10:11
*/
@Controller
public class IdentifiedController {
@GetMapping("/aligenie/{name}")
public String spirit(@PathVariable String name, ModelMap modelMap) {
// if (name.equals("0b6b193b8b26ae5875b6d4e4f69a4103.txt")) return name;
return name;
}
}
package ai.qiwu.tmall.spirit.controller; package ai.qiwu.tmall.spirit.controller;
import ai.qiwu.tmall.spirit.service.SpiritService; import ai.qiwu.tmall.spirit.service.SpiritService;
import ai.qiwu.tmall.spirit.spirit.SpiritAudioUpload;
import com.alibaba.da.coin.ide.spi.standard.ResultModel; import com.alibaba.da.coin.ide.spi.standard.ResultModel;
import com.alibaba.da.coin.ide.spi.standard.TaskQuery; import com.alibaba.da.coin.ide.spi.standard.TaskQuery;
import com.alibaba.da.coin.ide.spi.standard.TaskResult; import com.alibaba.da.coin.ide.spi.standard.TaskResult;
import com.alibaba.da.coin.ide.spi.trans.MetaFormat; import com.alibaba.da.coin.ide.spi.trans.MetaFormat;
import org.slf4j.Logger; import com.alibaba.fastjson.JSON;
import org.slf4j.LoggerFactory; import org.apache.catalina.connector.ClientAbortException;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired; import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestBody; import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.*;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.RestController; import javax.servlet.http.HttpServletResponse;
import java.io.*;
import java.util.List;
/** /**
* 天猫自定义技能里Webhook中URL,假如填写的是http://test.com/spirit,
* 他会访问这里,并将请求参数映射到taskQuery上.关于证书的访问,
* 以上面URL为例天猫会访问http://test.com/aligenie/xxx.file,
* 这里我们将xxx.file放到了resources/aligenie下
* @author 苗权威 * @author 苗权威
* @dateTime 2019/6/18 * @dateTime 19-12-6 上午10:31
*/ */
@RestController @RestController
@RequestMapping("/spirit")
public class SpiritController { public class SpiritController {
private final SpiritService spiritService;
private final SpiritAudioUpload spiritAudioUpload;
/** @Value("${csvDic}")
* slf4j打印日志信息 private String csvDic;
*/
private static final Logger logger = LoggerFactory.getLogger(SpiritController.class);
/**
* 解析请求信息的实现类
*/
@Autowired @Autowired
private SpiritService spiritService; public SpiritController(SpiritService spiritService, SpiritAudioUpload spiritAudioUpload) {
this.spiritService = spiritService;
this.spiritAudioUpload = spiritAudioUpload;
}
/** /**
* 利用天猫精灵打开发包解析请求并从构造响应数据返回 * 利用天猫精灵打开发包解析请求并从构造响应数据返回
* @param taskQuery 请求的参数信息 * @param taskQuery 请求的参数信息
* @return 返回响应的JSON数据 * @return 返回响应的JSON数据
*/ */
@RequestMapping(value = "/spirit") @PostMapping(value = "/") //交游天下
public @ResponseBody ResultModel<TaskResult> getResponse(@RequestBody String taskQuery) { public ResultModel<TaskResult> getResponse(@RequestBody String taskQuery) {
logger.info("TaskQuery:{}",taskQuery); // log.info("TaskQuery:{}",taskQuery);
TaskQuery query = MetaFormat.parseToQuery(taskQuery);
// build response
ResultModel<TaskResult> resultModel = new ResultModel<>();
TaskResult taskResult = spiritService.getResponse(query, 1);
// logger.info("taskResult:"+taskResult);
resultModel.setReturnCode("0");
resultModel.setReturnValue(taskResult);
return resultModel;
}
@PostMapping(value = "/story") // 互动故事
public ResultModel<TaskResult> story(@RequestBody String taskQuery) {
// log.info("TaskQuery:{}",taskQuery);
TaskQuery query = MetaFormat.parseToQuery(taskQuery);
// build response
ResultModel<TaskResult> resultModel = new ResultModel<>();
TaskResult taskResult = spiritService.getResponse(query,2);
// logger.info("taskResult:"+taskResult);
resultModel.setReturnCode("0");
resultModel.setReturnValue(taskResult);
return resultModel;
}
@PostMapping(value = "/literature") // 互动文艺
public ResultModel<TaskResult> literature(@RequestBody String taskQuery) {
// log.info("TaskQuery:{}",taskQuery);
TaskQuery query = MetaFormat.parseToQuery(taskQuery); TaskQuery query = MetaFormat.parseToQuery(taskQuery);
// build response // build response
ResultModel<TaskResult> resultModel = new ResultModel<>(); ResultModel<TaskResult> resultModel = new ResultModel<>();
TaskResult taskResult = spiritService.getResponse(query); TaskResult taskResult = spiritService.getResponse(query,3);
logger.info("taskResult:"+taskResult); // logger.info("taskResult:"+taskResult);
resultModel.setReturnCode("0"); resultModel.setReturnCode("0");
resultModel.setReturnValue(taskResult); resultModel.setReturnValue(taskResult);
return resultModel; return resultModel;
} }
@PostMapping(value = "/smart") // 智能故事
public ResultModel<TaskResult> smart(@RequestBody String taskQuery) {
// log.info("TaskQuery:{}",taskQuery);
TaskQuery query = MetaFormat.parseToQuery(taskQuery);
// build response
ResultModel<TaskResult> resultModel = new ResultModel<>();
TaskResult taskResult = spiritService.getResponse(query,4);
// logger.info("taskResult:"+taskResult);
resultModel.setReturnCode("0");
resultModel.setReturnValue(taskResult);
return resultModel;
}
@PostMapping(value = "/novel") // 智能小说
public ResultModel<TaskResult> novel(@RequestBody String taskQuery) {
// log.info("TaskQuery:{}",taskQuery);
TaskQuery query = MetaFormat.parseToQuery(taskQuery);
// build response
ResultModel<TaskResult> resultModel = new ResultModel<>();
TaskResult taskResult = spiritService.getResponse(query,5);
// logger.info("taskResult:"+taskResult);
resultModel.setReturnCode("0");
resultModel.setReturnValue(taskResult);
return resultModel;
}
@GetMapping("/upload")
public String upload(String name,String botAccount, @RequestParam(required = false) String preBotAccount, Long skillId, Boolean record) {
new Thread(() -> spiritAudioUpload.uploadByDic(name,botAccount, preBotAccount, skillId, record)).start();
return "success";
}
@GetMapping("/get/csv")
public void getCsv(String name, HttpServletResponse response) {
String path = csvDic+name;
buildMp3Response(response, path, 200);
}
// @PostMapping("audio/no")
// public void noAudio(@RequestBody List<> dialogs) {
//
// }
private static void buildMp3Response(HttpServletResponse response, String fileName, int status) {
response.setStatus(status);
try (BufferedInputStream inputStream = new BufferedInputStream(new FileInputStream(fileName));
OutputStream out = new BufferedOutputStream(response.getOutputStream())){
response.reset();
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);
byte[] buffer = new byte[1024];
int ln;
while ((ln = inputStream.read(buffer)) != -1) {
out.write(buffer, 0, ln);
}
out.flush();
} catch (ClientAbortException e) {
} catch (IOException e) {
}
}
} }
package ai.qiwu.tmall.spirit.entity.gameditor;
import lombok.Getter;
import lombok.Setter;
import lombok.ToString;
import javax.persistence.*;
/**
* @author 苗权威
* @dateTime 19-8-14 下午8:29
*/
@Entity
@Table(name = "game_project_tb")
@Getter
@Setter
@ToString
public class GameProjectTb {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private Long id;
@Column
private String name;
@Column(name = "apply_status")
private Integer applyStatus;
@Column(name = "bot_account")
private String botAccount;
@Column(name = "user_nickname")
private String authorName;
@Column(name = "audio_type")
private Integer audioType;
}
package ai.qiwu.tmall.spirit.entity.gameditor;
import lombok.Getter;
import lombok.Setter;
import lombok.ToString;
import javax.persistence.*;
/**
* @author 苗权威
* @dateTime 19-12-10 下午2:33
*/
@Entity
@Table(name = "plot_text_tb")
@Getter
@Setter
@ToString
public class PlotTextTB {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private Long id;
@Column
private String content;
@Column(name = "npc_name")
private String npcName;
@Column
private String mood;
@Column(name = "project_id")
private Long projectId;
@Column(name = "audio_flag")
private Integer audioFlag; // 0 null, 1 audio, 2 record
}
package ai.qiwu.tmall.spirit.po;
import ai.qiwu.tmall.spirit.spirit.PostFileData;
import com.fasterxml.jackson.annotation.JsonIgnoreProperties;
import lombok.Getter;
import lombok.Setter;
import lombok.ToString;
import java.util.List;
/**
* @author 苗权威
* @dateTime 19-12-10 下午4:13
*/
@Getter
@Setter
@ToString
@JsonIgnoreProperties(ignoreUnknown = true)
public class AfterPostFileData {
private Integer retCode;
private List<PostFileData> retValue;
}
package ai.qiwu.tmall.spirit.po;
import lombok.Getter;
import lombok.Setter;
import lombok.ToString;
import java.util.List;
/**
* @author 苗权威
* @dateTime 19-12-21 上午11:04
*/
@Getter
@Setter
@ToString
public class DeleteAudioRequest {
private List<String> contentIds;
private Long skillId;
}
package ai.qiwu.tmall.spirit.po;
import com.fasterxml.jackson.annotation.JsonIgnoreProperties;
import lombok.Getter;
import lombok.Setter;
import lombok.ToString;
/**
* @author 苗权威
* @dateTime 19-12-11 下午3:40
*/
@Getter
@Setter
@ToString
@JsonIgnoreProperties(ignoreUnknown = true)
public class Dialog {
private String botAccount;
private String npcName;
private String person;
private String text;
private String tone;
}
package ai.qiwu.tmall.spirit.po;
import lombok.Builder;
import lombok.Getter;
import lombok.Setter;
/**
* @author 苗权威
* @dateTime 19-12-17 下午3:38
*/
@Getter
@Setter
@Builder
public class DicUploadErrorInfo {
private String person;
private String mood;
private String path;
private String msg;
}
package ai.qiwu.tmall.spirit.po;
import lombok.Builder;
import lombok.Getter;
import lombok.Setter;
import lombok.ToString;
/**
* @author 苗权威
* @dateTime 19-12-17 下午3:35
*/
@Getter
@Setter
@ToString
@Builder(toBuilder = true)
public class DicUploadInfo {
private String person;
private String mood;
private Long id;
private String md5;
private String upUrl;
}
package ai.qiwu.tmall.spirit.po;
import lombok.Getter;
import lombok.Setter;
/**
* @author 苗权威
* @dateTime 19-12-10 下午9:00
*/
@Getter
@Setter
public class PostFilePathAndId {
private Long id;
private String path;
public PostFilePathAndId(Long id, String path) {
this.id = id;
this.path = path;
}
}
package ai.qiwu.tmall.spirit.po;
import lombok.Getter;
import lombok.Setter;
import lombok.ToString;
/**
* @author 苗权威
* @dateTime 19-7-10 下午2:29
*/
@Getter
@Setter
@ToString
public class QiWuRequest {
private String uid;
private String msg;
private Integer resptype = 2;
// private String access;
}
package ai.qiwu.tmall.spirit.po;
import com.fasterxml.jackson.annotation.JsonIgnoreProperties;
import lombok.Getter;
import lombok.Setter;
import lombok.ToString;
import java.util.List;
@Getter
@Setter
@ToString
@JsonIgnoreProperties(ignoreUnknown = true)
public class QiWuResponse {
private String aipioneerUsername;
private List<Dialog> dialogs;
private String extraChatKey;
private String mainChatKey;
}
package ai.qiwu.tmall.spirit.po;
import lombok.Builder;
import lombok.Getter;
import lombok.Setter;
/**
* @author 苗权威
* @dateTime 19-12-10 下午8:36
*/
@Getter
@Setter
@Builder
public class UploadErrorInfo {
private String person;
private String mood;
private Long id;
private String text;
private String path;
private String msg;
}
package ai.qiwu.tmall.spirit.po;
import lombok.Builder;
import lombok.Getter;
import lombok.Setter;
import lombok.ToString;
/**
* @author 苗权威
* @dateTime 19-12-10 下午3:00
*/
@Getter
@Setter
@ToString
@Builder(toBuilder = true)
public class UploadInfo {
private String person;
private String mood;
private String md5;
private Long id;
private String text;
private String upUrl;
}
package ai.qiwu.tmall.spirit.repository.gameditor;
import ai.qiwu.tmall.spirit.entity.gameditor.GameProjectTb;
import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.data.jpa.repository.Query;
import org.springframework.stereotype.Repository;
import java.util.List;
/**
* @author 苗权威
* @dateTime 19-8-14 下午9:05
*/
@Repository
public interface GameProjectTbRepository extends JpaRepository<GameProjectTb, Long> {
// @Query(value = "select * from game_project_tb where apply_status=1 and score != 0 order by watch desc limit 8", nativeQuery = true)
// List<GameProjectTb> findFirst8();
}
package ai.qiwu.tmall.spirit.repository.gameditor;
import ai.qiwu.tmall.spirit.entity.gameditor.PlotTextTB;
import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.data.jpa.repository.Query;
import java.util.List;
/**
* @author 苗权威
* @dateTime 19-12-10 下午2:32
*/
public interface PlotTextTBRepository extends JpaRepository<PlotTextTB, Long> {
@Query(value = "select * from plot_text_tb where project_id=?1 and content is not null", nativeQuery = true)
List<PlotTextTB> getByProjectId(Long projectId);
}
package ai.qiwu.tmall.spirit.service; package ai.qiwu.tmall.spirit.service;
import ai.qiwu.tmall.spirit.common.ApachHttpUtils;
import ai.qiwu.tmall.spirit.po.QiWuRequest;
import ai.qiwu.tmall.spirit.po.QiWuResponse;
import com.alibaba.da.coin.ide.spi.meta.Action;
import com.alibaba.da.coin.ide.spi.meta.AskedInfoMsg; import com.alibaba.da.coin.ide.spi.meta.AskedInfoMsg;
import com.alibaba.da.coin.ide.spi.meta.ExecuteCode; import com.alibaba.da.coin.ide.spi.meta.ExecuteCode;
import com.alibaba.da.coin.ide.spi.meta.ResultType; import com.alibaba.da.coin.ide.spi.meta.ResultType;
import com.alibaba.da.coin.ide.spi.standard.TaskQuery; import com.alibaba.da.coin.ide.spi.standard.TaskQuery;
import com.alibaba.da.coin.ide.spi.standard.TaskResult; import com.alibaba.da.coin.ide.spi.standard.TaskResult;
import com.alibaba.fastjson.JSON; import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject; import lombok.extern.slf4j.Slf4j;
import org.apache.http.HttpEntity; import org.apache.commons.lang3.ArrayUtils;
import org.apache.http.client.methods.CloseableHttpResponse; import org.apache.commons.lang3.StringUtils;
import org.apache.http.client.methods.HttpPost; import org.apache.commons.lang3.exception.ExceptionUtils;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClientBuilder;
import org.apache.http.util.EntityUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Service; import org.springframework.stereotype.Service;
import java.io.IOException; import java.io.IOException;
import java.util.ArrayList; import java.util.*;
import java.util.HashMap; import java.util.regex.Matcher;
import java.util.regex.Pattern;
/** /**
* 解析请求参数,构造向终端接口发送打数据打JSON,之后得到响应数据,提取构造返回给天猫的响应数据 * 解析请求参数,构造向终端接口发送打数据打JSON,之后得到响应数据,提取构造返回给天猫的响应数据
...@@ -28,20 +27,20 @@ import java.util.HashMap; ...@@ -28,20 +27,20 @@ import java.util.HashMap;
* @dateTime 2019/6/18 * @dateTime 2019/6/18
*/ */
@Service @Service
@Slf4j
public class SpiritService { public class SpiritService {
/** private static final String REGEX_SEPERATE = "【(.+?)】";
* org.slf4j.Logger打印日志信息 private static final String QI_WU_TERMINATE_DIDI = "http://didi-gz3.jiaoyou365.com:8070/api/chat2";
*/ private static final String PREFIX_USERID = "TIANMAO_";
private static final Logger logger = LoggerFactory.getLogger(SpiritService.class);
/** /**
* 获取返回给天猫的数据 * 获取返回给天猫的数据
* @param request 请求参数 * @param request 请求参数
* @return 返回数据封装在开发包中的TaskResult * @return 返回数据封装在开发包中的TaskResult
*/ */
public TaskResult getResponse(TaskQuery request) { public TaskResult getResponse(TaskQuery request, int type) {
return getNeededParam(request); return getNeededParam(request, type);
} }
/** /**
...@@ -49,60 +48,48 @@ public class SpiritService { ...@@ -49,60 +48,48 @@ public class SpiritService {
* @param request 请求参数 * @param request 请求参数
* @return 返回数据封装在开发包中的TaskResult * @return 返回数据封装在开发包中的TaskResult
*/ */
private TaskResult getNeededParam(TaskQuery request) { private TaskResult getNeededParam(TaskQuery request, int type) {
Long userId = request.getBotId(); String userId = getUserId(request);
if (StringUtils.isBlank(userId)) return buildTaskResult(null, "不好意思好像出了什么问题,正在抓紧修复中", request.getIntentId());
String userWord = request.getUtterance(); String userWord = request.getUtterance();
logger.info("The customer say:"+userWord); log.info("天猫精灵用户说的话:"+userWord);
Long intentId = request.getIntentId(); Long intentId = request.getIntentId();
return postToQiWuInterface(userId, userWord, intentId);
}
/**
* 向接口公司的接口发送数据:user_id 包括用户id, text TTS文本内容,access 来源标识
* 获取返回:audio 音频链接,text TTS文本内容
* @param userId 用户id
* @param userWord TTS文本内容
* @param intentId 意图id
* @return 返回数据封装在开发包中的TaskResult
*/
private TaskResult postToQiWuInterface(Long userId, String userWord, Long intentId) {
String audioUrl = "";
String textContent = "请说推荐作品";
CloseableHttpClient httpClient = null;
CloseableHttpResponse response = null;
try { try {
httpClient = HttpClientBuilder.create().build(); return requestTerminate(userId, userWord, type, intentId);
HttpPost post = new HttpPost("http://aliyun-hz1.chewrobot.com:8070/api/chat");
HashMap<String, String> params = new HashMap<>();
params.put("user_id", String.valueOf(userId));
params.put("text", userWord);
params.put("access","TIANMAO");
String paramsJsonFormat = JSON.toJSONString(params);
StringEntity body = new StringEntity(paramsJsonFormat, "UTF-8");
post.setHeader("Content-Type", "application/json;charset=utf-8");
post.setEntity(body);
response = httpClient.execute(post);
HttpEntity responseBody = response.getEntity();
if (responseBody != null) {
String responseContent = EntityUtils.toString(responseBody);
logger.info("齐悟接口返回: "+ responseContent);
JSONObject responseJsonFormat = JSONObject.parseObject(responseContent);
audioUrl = (String) responseJsonFormat.get("audio");
textContent = (String) responseJsonFormat.get("text");
}
} catch (IOException e) { } catch (IOException e) {
e.printStackTrace(); log.error("天猫精灵出现问题:{}", ExceptionUtils.getStackTrace(e));
} finally {
try {
if (httpClient != null) httpClient.close();
if (response != null) response.close();
} catch (IOException e) {
e.printStackTrace();
}
} }
return buildTaskResult(audioUrl, textContent, intentId); return buildTaskResult(null, "不好意思请再说一遍吧", intentId);
}
private TaskResult requestTerminate(String userId, String userWord, Integer type, Long intentId) throws IOException {
QiWuRequest requestPojo = new QiWuRequest();
requestPojo.setUid(userId);
// requestPojo.setAccess(XiaoAiConstants.DEVICE_NAME);
requestPojo.setMsg(userWord);
String requestJsonStr = JSON.toJSONString(requestPojo);
//log.info("向终端发出请求的参数信息:{}", requestJsonStr);
HashMap<String, String> headers = new HashMap<>();
headers.put("Content-Type", "application/json;charset=utf-8");
String channelId = "jiaoyou-audio-test";
switch (type) {
case 2:
case 4: channelId = "jiaoyou-audio-child-test";break;
case 3:
case 5: channelId= "jiaoyou-audio-adult-test";break;
}
headers.put("App-Channel-Id", channelId);
String resStr= ApachHttpUtils.post(QI_WU_TERMINATE_DIDI, requestJsonStr, headers);
if (resStr == null) {
return null;
}
log.info("天猫精灵晓悟返回:"+resStr);
// QiWuResponse response = JSON.parseObject(resStr, QiWuResponse.class);
// if (StringUtils.isBlank() == null) {
// response.setText("不好意思请在说一遍吧");
// }
// return buildTaskResult(response.getAudio(), response.getText(), intentId);
return null;
} }
/** /**
...@@ -114,7 +101,7 @@ public class SpiritService { ...@@ -114,7 +101,7 @@ public class SpiritService {
*/ */
private TaskResult buildTaskResult(String audio, String text, Long intentId) { private TaskResult buildTaskResult(String audio, String text, Long intentId) {
TaskResult result = new TaskResult(); TaskResult result = new TaskResult();
result.setReply(text); result.setReply(buildText(text));
result.setResultType(ResultType.ASK_INF); result.setResultType(ResultType.ASK_INF);
result.setExecuteCode(ExecuteCode.SUCCESS); result.setExecuteCode(ExecuteCode.SUCCESS);
...@@ -123,13 +110,60 @@ public class SpiritService { ...@@ -123,13 +110,60 @@ public class SpiritService {
listInfo.add(askedInfoMsg); listInfo.add(askedInfoMsg);
result.setAskedInfos(listInfo); result.setAskedInfos(listInfo);
// List<Action> actions = new ArrayList<>();
// Action action = new Action("audioPlayGenieSource");
// //action.addProperty("audioGenieId", "21441");
// action.addProperty("audioGenieId", audio);
// actions.add(action);
// result.setActions(actions);
return result; return result;
} }
private String buildText(String text) {
Pattern pattern = Pattern.compile(REGEX_SEPERATE);
StringBuilder builder = new StringBuilder();
List<String> actors = seperateActor(text, pattern);
String[] word = seperateActorWord(text, pattern);
int i = 0;
for (String actor: actors) {
builder.append(actor).append("说:").append(word[i].replaceAll("<br>", "")).append("。");
i++;
}
if (builder.length() == 0) builder.append(text);
return builder.toString();
}
private String getUserId(TaskQuery query) {
// log.warn("requestData:{}", query.getRequestData());
String userId = query.getRequestData().get("userOpenId");
if (StringUtils.isBlank(userId)) {
userId = query.getRequestData().get("deviceOpenId");
}
if (StringUtils.isBlank(userId)) {
log.error("天猫精灵无法获取到唯一标识的id");
return null;
} else {
return new StringBuilder(PREFIX_USERID).append(userId).toString();
}
}
private static List<String> seperateActor(String text, Pattern pattern) {
Matcher matcher = pattern.matcher(text);
List<String> actorList = new ArrayList<>();
while (matcher.find()) {
String actor = matcher.group(1).trim();
actor = actor.substring(0, actor.indexOf("@"));
actorList.add(actor);
}
return actorList;
}
private static String[] seperateActorWord(String text, Pattern pattern) {
String[] actorWords = pattern.split(text);
if (StringUtils.startsWith(text.trim(), "【")) {
actorWords = ArrayUtils.remove(actorWords, 0);
}
return actorWords;
}
public static void main(String[] args) {
// System.out.println(buildText("【小悟@正常】推荐如下作品:《小狗小白》、《妖刀异闻录》、《星球问答》 。你可以说:“打开某作品”"));
// System.out.println(buildText("不好意思请在说一遍吧"));
// System.out.println(buildText("【齐齐@开心】小朋友真聪明。他们循声来到一颗大榕树后的一座木屋旁,<br>见到音乐家捧着一个像笛子一样的乐器正在入神地吹奏着。后来,音乐家很高兴接纳了他们,并在木屋旁边给他们安了新家,<br>四个小伙伴和善良的音乐家开心地住在水心湖边,再也不用担惊受怕了。每天和音乐家一起弹奏唱跳,认识他们的人都亲切地称他们为“水心湖的音乐家”。【齐齐@正常】好了,小朋友,今天的故事就到这里了,谢谢你的耐心听讲,再见!【晓悟@正常】已退出当前作品。【小悟@正常】推荐如下作品:《小神童闯关》、《遇见伽利略》、《会数学的杰瑞》 。你可以说:“打开某作品”"));
// System.out.println(buildText("【皮皮@正常】不好,我们在这里待得太久了,时空机要把我们带到下个地方去了【旁白@正常】随着时光穿梭机的强制转移,你和皮皮来到了动物园,动物园里有老虎,狮子,大象,还有几只大熊猫<br>【皮皮@正常】<br>我们好像被转移到动物园了。。。哇小朋友,你看!那里有熊猫耶,你喜欢熊猫吗? 。"));
}
} }
package ai.qiwu.tmall.spirit.spirit;
import lombok.Getter;
import lombok.Setter;
import lombok.ToString;
/**
* @author 苗权威
* @dateTime 19-12-9 下午6:43
*/
@Getter
@Setter
@ToString
public class Content {
private Object size;
private Object creatorId;
private Object gmtCreate;
private String name;
private String alias;
private String style = "default";
private String status;
private String actor;
private String sourceType="www";
private String fileType="mp3";
private Object gmtModified;
private String catalog="default";
private String icon;
private String source;
private Long id;
private String description="";
private String mediaType="audio";
}
package ai.qiwu.tmall.spirit.spirit;
import com.fasterxml.jackson.annotation.JsonIgnoreProperties;
import lombok.Getter;
import lombok.Setter;
import lombok.ToString;
/**
* @author 苗权威
* @dateTime 19-12-9 下午5:36
*/
@Getter
@Setter
@ToString
@JsonIgnoreProperties(ignoreUnknown = true)
public class Credential {
private Integer retCode;
private CredentialsResponse retValue;
}
package ai.qiwu.tmall.spirit.spirit;
import com.fasterxml.jackson.annotation.JsonIgnoreProperties;
import lombok.Getter;
import lombok.Setter;
import lombok.ToString;
/**
* @author 苗权威
* @dateTime 19-12-9 下午4:48
*/
@Getter
@Setter
@ToString
@JsonIgnoreProperties(ignoreUnknown = true)
public class CredentialsResponse {
private String accessId;
private String signature;
private String host;
private String dir;
private String policy;
}
package ai.qiwu.tmall.spirit.spirit;
import lombok.Getter;
import lombok.Setter;
/**
* @author 苗权威
* @dateTime 19-12-9 下午6:47
*/
@Getter
@Setter
public class ExtendAttrs {
private Integer duration;
private Integer contentId=0;
private String singer;
private String lyrics;
private String composer;
}
package ai.qiwu.tmall.spirit.spirit;
import lombok.Getter;
import lombok.Setter;
import lombok.ToString;
/**
* @author 苗权威
* @dateTime 19-12-9 下午6:42
*/
@Getter
@Setter
@ToString
public class PostFileData {
private Content content;
private ExtendAttrs extendAttrs;
}
package ai.qiwu.tmall.spirit.spirit;
import com.fasterxml.jackson.databind.annotation.JsonSerialize;
import lombok.Getter;
import lombok.Setter;
import lombok.ToString;
import java.util.List;
/**
* @author 苗权威
* @dateTime 19-12-9 下午6:39
*/
@Getter
@Setter
@ToString
public class PostFileVO {
private Long skillId;
private List<PostFileData> content;
}
package ai.qiwu.tmall.spirit.spirit;
import ai.qiwu.tmall.spirit.common.ApachHttpUtils;
import ai.qiwu.tmall.spirit.common.BaseHolder;
import ai.qiwu.tmall.spirit.entity.gameditor.GameProjectTb;
import ai.qiwu.tmall.spirit.entity.gameditor.PlotTextTB;
import ai.qiwu.tmall.spirit.po.*;
import ai.qiwu.tmall.spirit.repository.gameditor.GameProjectTbRepository;
import ai.qiwu.tmall.spirit.repository.gameditor.PlotTextTBRepository;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.csv.CSVFormat;
import org.apache.commons.csv.CSVParser;
import org.apache.commons.csv.CSVPrinter;
import org.apache.commons.csv.CSVRecord;
import org.apache.commons.lang3.RandomStringUtils;
import org.apache.commons.lang3.StringUtils;
import org.apache.http.client.utils.URLEncodedUtils;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;
import org.springframework.util.DigestUtils;
import ws.schild.jave.AudioInfo;
import ws.schild.jave.MultimediaObject;
import java.io.*;
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.text.SimpleDateFormat;
import java.util.*;
import java.util.regex.Matcher;
/**
* @author 苗权威
* @dateTime 19-12-9 下午4:38
*/
@Service
@Slf4j
public class SpiritAudioUpload {
@Value("${csvDic}")
private String csvDic;
private volatile String cookie = "cna=qsWIFY5RHlMCAXeJN3DsHj3O; isg=BFhY_wUGsjusjZ29XklHD24lKo8q6b1WxqYDypJJcBNeLfsXOFA0W-fLZaW4JnSj; CNZZDATA1261708326=1797143004-1560414985-%7C1577077139; _cnzz_CV1261708326=52463%7C%F0%9F%8C%8E%20common%2F%E8%8E%B7%E5%8F%96%20oss%20token%7Cp; hng=CN%7Czh-CN%7CCNY%7C156; enc=GlWCH0jde0teESrXYo%2BHF75NARTOPv7uKzyscUHesjr8NqyYTkHf%2BD6PG2iP4gPoGIsaO8aq%2BG41Q6kPPhYpvw%3D%3D; UM_distinctid=16ef9e5d343206-06ea6f889716618-76256753-1fa400-16ef9e5d344241; uc1=pas=0&cookie21=UtASsssme%2BBq&tag=8&cookie14=UoTbmEnmIFxXUw%3D%3D&existShop=false&cookie15=Vq8l%2BKCLz3%2F65A%3D%3D&lng=zh_CN&cookie16=VFC%2FuZ9az08KUQ56dCrZDlbNdA%3D%3D; t=925ffaa4a0ded6c2dc567c2eedd425f0; _tb_token_=3a3eeb3e68337; cookie2=145c78f447bf6a4cafb894c15072214f; dnk=tb13503054; tracknick=tb13503054; _l_g_=Ug%3D%3D; unb=1038446007; cookie1=UNMubI1eQ0gVOzLdxFCJj7hzIKFouglcA%2BlE1IYgcZQ%3D; login=true; cookie17=UoH8Vd06g9TEfA%3D%3D; _nk_=tb13503054; sg=47f; csg=f8c7b18a; ctoken=ThECcNhEBvJDLHL4AtCCWzqO; accountType=TB; EGG_SESS=OG910qv3Q3gsrSK4yqRmX3-1-P_ARlUIzlqweqLqnRF5dKELPTe4hiVT80Slz3WPDCsXS99IeB9EJ08mKe1fnCJBm_qC4NhmU1P2hSXcOOxhqcjA9knJrTbFO_08KukZd6segTIuGD5H9RDPRbAiBTjq3sXZE-ONRz07itH3ie_0MGVIB8n-XxMFQYetkS-BR11S3A-MA1iaMpYPPHfR5b5tg5_xnx0qw6APDlgMbNATwwRwWP1cybf5tiXsOgBw1DDDyMsFi0RN_djZp8RCYf7gwrqOhh3hNqNOz0IxeCznza7eUv9tbTMaR9r62A4NvYwEMI6gKCAQklI7LyPiHnc_xayqlbJxJdVGSv42QrTGGpDNj6tiQKCCRsKISe_3MCOJIIp5hDb2ybw_UcogYaiEd6IcIg97LWKY6ee-fuVIK9zSfzz60mlEYpKJ0KpK1XIeQXvt77C1Gv6yv-Vcw3fk_5Pnfq0frq5N0N3xgDDXaWxX1Vu6BUgBgtOYK8GpHmGi2tDTs-Fx3ATG9lELByjlDBVA1uHlmw4FAXR6gq_3DdvAbMlR2XYshBrIe9PpMNjHHHhjGPY9MdkFSX2HgXKcnCy_ID6oizYaaykxQGRv8mHiW8YjzE6X-KgXwm3JvFkHAqEXkty_xPBoz6u97mgJfY0Cps2ezNUQVgdIKupkX5NUvlFBDJD7lr1N6qZPChrPBluSDyexWuljvO2GB1ZsFKf2GVkCBvTIL5KMB3jrp37o7_9iztF50t4sVEY6jtjpXgSYXBs08gYX4cls2y3Jz3qgZ3GRNjqUOkm-KTg6V6D_cOxVx9lfoYH8oFX_ZixCURKlSOvDu8WIcj1_CCvPgEZbXfbYQLLmDQzk1X95SsJRd-sx2pZNu6e9ygDK-CG70ZMsJG1VfA2eBtss7nTpg2Poqlt7TirUPK9uQyneKBmB4EyyiJMZhJAzVKuQNPIUbiJwx8c23C-FH9iH6nR2vf10xcCv1ubRZqpxp33ucko9JAH2F7Mh9_dUeLsV8qiHHMdVFyAgrDslZ3K-RwUO_Fw_llfJ2Z4NQbwXG78lM5SlIi9W-26QdVEypDizWvuU56-Si9g5UhJ4ge2icWt-H3J9Gi6jf0OtQ7bdANyRIsou9X-pv0h_JjNtRyYlxpJk9ACiSdAwQvMv9_mgF1R5pS4cWb8nhG3BCDoKWJpZxIdwaHcLVvjP3ODJj0NOMvXHzHWvTXm646c5XTJSEMDFZYVz6suWLC-zlWzvPQbprj_rXaEHzPGL664gWnfUXOqTabK2OlQSSmnrzrSoVQIxy67VHcWDLGiggRzUxrh1J1wNiw6IRqFR6So-To74fagJX1jou2XSrdABsxGLOP2nMWEL719p7fpYSVsHwfPcCQUvs0J6UhMpOCqMlZjL8Xs5_p2DMX9fHc0HsRkgmbtYUfJ_R76pqm8ZKO2GMPSH6oJSHIndtkKzIGUwFqGMI-3ghXpmbbHCrcmYQ4h2HfO-2e7_NbhaDo5mj23KY6dG7Gcb5PMVfVxMgAY6raFfkAme6J8SR6_dQTAU9EizXWpslXXM2HeF3oKmrLpK4gWnoNaLmpN7MRPT7XUWP-UDaqxvy17rpHBAqM-AVwkVIJb4p29ycd0yGP34CgfA9z--n-LllmcMQ_MEo-Hu8en8wdKKgwyWJsIjxZAnWvG1YXe669xJ2LTFPPI7VP87T7P7y6KlNe9BarvWhWB76iJbB285jfiNQktDEX4PKsDR2Zvg384rKgEwlzeTgm7GiIkJfDnIZpphzwun-Ef2ejxCPwFGVhtMOOe4Qc-zDnItuielOx554weMBkfaI8N7e4sYJzBpjuIrhJWEJXjDtmwoo2IiRyiIitYWF7_t0pkJ6l2yxmBYb8zya_KxZe0RB2t6--3HTBTEGbCJvlfFDCzEVl88RDQdqzlHb5m8K9ncz0rUsonkRX_ym_yrif4lGVGM7NSGslp3PE4oY2RHFENxaLIifRmOI_GJPNGOIlaaaL4g-NCjWX2iDXKu4HQ3uLtDPS5nIIP-x7Dx6IInGpvFto1a0XyO44jsxhM01ZGR1ruCamyKov5grz0uoa0qcEAmX7L_V02nn3rakHWigyGQPgYmVG9DjbeE6w4mRTKe9uJ9LRpWnd0LP8P_vqPnIfK98zv5S2TswLlSbuy7hVCYKdtbJwvV7uVj2oYqwOQn4WhyP_gdRz4gFJQIr3XM7BdSBmke080u9fwYC1rIBb1_S5R8Pld04X3paL5Wc3A9PSOijtWoMpGFnT1AiXmc4WlCqDDdHB3xMR1f-GY_16ZWwk1xgyhy6ywqzgSpVvbWyw==; accountId=52463; token=hYDNXw+5PWJXA+QLwV3ToIKiqhXcIpGf5GxU1zvIt3E=; confirmProtocolVersion=1";
private volatile String token = "hYDNXw+5PWJXA+QLwV3ToIKiqhXcIpGf5GxU1zvIt3E=";
private volatile String csrfToken = "ThECcNhEBvJDLHL4AtCCWzqO";
public void updateCookie(String cookie) {
this.cookie = cookie;
// token=ol977BaL6nE1H5lss8t3Nx7G7LOB9n1S+S8mAlxsZnA=;
int is = cookie.indexOf("token");
int ie = cookie.indexOf(";", is);
this.token = cookie.substring(is+6, ie);
// ctoken=qPmE3U9PprUyT04i1wzN3ujO;
is = cookie.indexOf("ctoken");
ie = cookie.indexOf(";",is);
this.csrfToken = cookie.substring(is+7, ie);
}
private PostFilePathAndId getCredentials(Long skillId, String randomName, String customName,File file,
Integer duration, String description) {
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/"+skillId+"/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);
CredentialsResponse response = JSON.parseObject(result, Credential.class).getRetValue();
String path = response.getDir()+ File.separator+ randomName;
Map<String, String> params = new HashMap<>();
params.put("name", file.getName());
params.put("OSSAccessKeyId", response.getAccessId());
params.put("policy", response.getPolicy());
params.put("Signature", response.getSignature());
params.put("key", path);
// params.put("key", response.getDir()+ File.separator+ "k3y89mz1.mp3");
params.put("success_action_status", "200");
Map<String, String> prePostHeaders = new HashMap<>();
prePostHeaders.put("Accept", "*/*");
prePostHeaders.put("Connection", "keep-alive");
prePostHeaders.put("Origin", "https://open.aligenie.com");
prePostHeaders.put("Referer", "https://open.aligenie.com/console/skill/"+skillId+"/audiolist");
prePostHeaders.put("User-Agent", "Mozilla/5.0 (X11; Ubuntu; Linux x86_64; rv:70.0) Gecko/20100101 Firefox/70.0");
String resultPrePost = ApachHttpUtils.requestByPostParts(params, prePostHeaders, "https://ar-platform.oss-cn-shanghai.aliyuncs.com/", StandardCharsets.UTF_8,file);
if (resultPrePost != null) {
// System.out.println(resultPrePost);
PostFileVO vo = new PostFileVO();
vo.setSkillId(skillId);
PostFileData data = new PostFileData();
Content content = new Content();
content.setName(customName);
content.setAlias(file.getName());
content.setSource("https://ailabs.alibabausercontent.com/"+path);
content.setDescription(description);
ExtendAttrs extendAttrs = new ExtendAttrs();
extendAttrs.setDuration(duration);
data.setContent(content);
data.setExtendAttrs(extendAttrs);
vo.setContent(Collections.singletonList(data));
String request = JSON.toJSONString(vo);
// System.out.println(request);
String answer = ApachHttpUtils.post("https://open.aligenie.com/api/custom/audio/contents", request, headers);
// System.out.println(answer);
try {
AfterPostFileData postResponse = JSON.parseObject(answer, AfterPostFileData.class);
if (postResponse.getRetCode() == 0) {
return new PostFilePathAndId(postResponse.getRetValue().get(0).getContent().getId(), path);
} else {
log.error("post 3:{}",answer);
}
} catch (Exception e) {
log.error("post 3:{}",answer);
}
}
return null;
}
private void deleteTheAudio(List<String> ids, Long skillId) {
log.error("要删除的id列表:"+ids);
String url = "https://open.aligenie.com/api/custom/audios/delete";
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/"+skillId+"/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
DeleteAudioRequest request = new DeleteAudioRequest();
request.setContentIds(ids);
request.setSkillId(skillId);
String data = JSON.toJSONString(request);
try {
String result = ApachHttpUtils.post(url, data, headers);
if (StringUtils.isNotBlank(result)) {
JSONObject object = JSON.parseObject(result);
int retCode = object.getInteger("retCode");
if (retCode != 0) {
buildAuxiliaryDeleteTxt(data, skillId);
} else {
log.error("删除成功");
}
}
} catch (Exception e) {
log.error("删除错误"+e);
buildAuxiliaryDeleteTxt(data, skillId);
}
}
private void buildAuxiliaryDeleteTxt(String data, Long skillId) {
try {
Path p = Paths.get(csvDic+"auxiliaryDel.txt");
SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
String time = format.format(new Date());
String info = new StringBuilder(time).append("\n").append(data).append("\n").toString();
Files.write(p, info.getBytes(), StandardOpenOption.CREATE, StandardOpenOption.WRITE, StandardOpenOption.APPEND);
} catch (IOException e) {
log.error("buildAuxiliaryTxt:{}",e);
}
}
public void uploadByDic(String botName, String botAccount, String preBotAccount, Long skillId, Boolean record) {
log.error("请求成功:"+botName+";"+botAccount+";"+preBotAccount+";"+skillId+";"+record);
if(StringUtils.isNotBlank(preBotAccount)) {
updateAlreadyUploadedBot(botAccount, preBotAccount, record, skillId, botName);
} else {
Map<String, String> headers = new HashMap<>();
headers.put("Accept", "text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8");
headers.put("Accept-Encoding", "gzip, deflate, br");
headers.put("Connection", "keep-alive");
headers.put("User-Agent", "Mozilla/5.0 (X11; Ubuntu; Linux x86_64; rv:70.0) Gecko/20100101 Firefox/70.0");
ArrayList<DicUploadInfo> datas = new ArrayList<>();
List<DicUploadErrorInfo> errorDatas = new ArrayList<>();
int ln = 8;
int count = 0;
// int errorCount = 0;
String successMsgPath;
if (record) {
successMsgPath = new StringBuilder(csvDic)
.append(botAccount).append("_1.csv").toString();
} else {
successMsgPath = new StringBuilder(csvDic)
.append(botAccount).append("_0.csv").toString();
}
String errorMsgPath = new StringBuilder(csvDic)
.append(botAccount).append("_error.csv").toString();
String description;
if (Boolean.TRUE.equals(record)) {
String path = "/root/TTS-service/audio/"+botAccount+"/record";
File file = new File(path);
File[] dics = file.listFiles();
if (dics == null || dics.length == 0) {
log.error(path+":"+" 下没有人物目录");
return;
}
for (File dic: dics) {
String npcName = dic.getName();
File[] tfs = dic.listFiles((dir, name) -> StringUtils.endsWith(name, ".mp3"));
if (tfs == null || tfs.length == 0) {
log.error(npcName+": 下没有mp3");
continue;
}
for (File tf: tfs) {
if (doesFileExist(tf)) {
Integer duration = getMp3Time(tf);
if (duration == null) {
errorDatas.add(DicUploadErrorInfo.builder().person(npcName)
.msg("无法获取到该mp3文件的时长").path(tf.getAbsolutePath()).build());
continue;
}
String mp3FileName = tf.getName();
try {
String randomMp3Name;
int i = 0;
do {
if (i++ == 60) {
i = 0;
ln += 1;
log.error("循环60次名字仍然冲突");
}
randomMp3Name = RandomStringUtils.randomAlphabetic(ln)+".mp3";
} while (testTheName(randomMp3Name, headers));
description = new StringBuilder(botName).append(File.separator)
.append(npcName).append(File.separator).append("record")
.append(File.separator).append(mp3FileName).toString();
PostFilePathAndId data = getCredentials(skillId, randomMp3Name,
mp3FileName.substring(0,15), tf, duration,description);
Long id;
if (data != null && (id = data.getId()) != null) {
DicUploadInfo info = DicUploadInfo.builder().md5(mp3FileName).id(id)
.person(npcName).upUrl(data.getPath()).build();
datas.add(info);
} else {
errorDatas.add(DicUploadErrorInfo.builder()
.person(npcName).msg("发送请求失败,没有获取到id").path(tf.getAbsolutePath()).build());
}
if (datas.size()==100) {
buildDicCsv(successMsgPath, datas);
if (errorDatas.size() != 0) {
buildDicErrorCsv(errorMsgPath, errorDatas);
errorDatas.clear();
}
datas.clear();
log.error("到达100,datas清空后大小{},errorDatas清空后大小{}",datas.size(), errorDatas.size());
count += 100;
}
try {
Thread.sleep(1000);
} catch (Exception e) {}
} catch (Exception e) {
log.error("发送请求失败,出现异常:"+e.toString());
errorDatas.add(DicUploadErrorInfo.builder()
.person(npcName).msg("发送请求失败,出现异常").path(tf.getAbsolutePath()).build());
}
} else {
errorDatas.add(DicUploadErrorInfo.builder()
.person(npcName).msg("mp3大小为0").path(tf.getAbsolutePath()).build());
}
}
}
if (datas.size() != 0) {
buildDicCsv(successMsgPath, datas);
count += datas.size();
}
if (errorDatas.size() != 0) {
buildDicErrorCsv(errorMsgPath, errorDatas);
}
log.error("over, 总共上传音频个数:"+count);
} else {
String path = "/root/TTS-service/audio/"+botAccount;
File file = new File(path);
File[] personDics = file.listFiles();
if (personDics == null || personDics.length == 0) {
log.error(path+":"+" 下没有人物目录");
return;
}
for (File pf: personDics) {
String person = pf.getName();
File[] moodDics = pf.listFiles();
if (moodDics == null || moodDics.length == 0) {
log.error(person+":"+" 下没有情绪目录");
continue;
}
for (File mf: moodDics) {
String mood = mf.getName();
File[] mp3Files = mf.listFiles((dir, name) -> StringUtils.endsWith(name, ".mp3"));
if (mp3Files == null || mp3Files.length == 0) {
log.error(person+":"+mood+" 下没有mp3");
continue;
}
for (File tf: mp3Files) {
if (doesFileExist(tf)) {
Integer duration = getMp3Time(tf);
if (duration == null) {
errorDatas.add(DicUploadErrorInfo.builder().person(person).mood(mood)
.msg("无法获取到该mp3文件的时长").path(tf.getAbsolutePath()).build());
continue;
}
String mp3FileName = tf.getName();
try {
String randomMp3Name;
int i = 0;
do {
if (i++ == 60) {
i = 0;
ln += 1;
log.error("循环60次名字仍然冲突");
}
randomMp3Name = RandomStringUtils.randomAlphabetic(ln)+".mp3";
} while (testTheName(randomMp3Name, headers));
description = new StringBuilder(botName).append(File.separator)
.append(person).append(File.separator).append(mood)
.append(File.separator).append(mp3FileName).toString();
PostFilePathAndId data = getCredentials(skillId, randomMp3Name,
mp3FileName.substring(0,15), tf, duration,description);
Long id;
if (data != null && (id = data.getId()) != null) {
DicUploadInfo info = DicUploadInfo.builder().md5(mp3FileName).id(id)
.person(person).mood(mood).upUrl(data.getPath()).build();
datas.add(info);
} else {
errorDatas.add(DicUploadErrorInfo.builder().person(person).mood(mood)
.msg("发送请求失败,没有获取到id").path(tf.getAbsolutePath()).build());
}
if (datas.size()==50) {
buildDicCsv(successMsgPath, datas);
if (errorDatas.size() != 0) {
buildDicErrorCsv(errorMsgPath, errorDatas);
errorDatas.clear();
}
datas.clear();
log.error("到达50,datas清空后大小{},errorDatas清空后大小{}",datas.size(), errorDatas.size());
count += 50;
}
try {
Thread.sleep(1000);
} catch (Exception e) {}
} catch (Exception e) {
log.error("发送请求失败,出现异常:"+e.toString());
errorDatas.add(DicUploadErrorInfo.builder().person(person).mood(mood)
.msg("发送请求失败,出现异常").path(tf.getAbsolutePath()).build());
}
} else {
errorDatas.add(DicUploadErrorInfo.builder().person(person).mood(mood)
.msg("mp3大小为0").path(tf.getAbsolutePath()).build());
}
}
}
}
if (datas.size() != 0) {
buildDicCsv(successMsgPath, datas);
count += datas.size();
}
if (errorDatas.size() != 0) {
buildDicErrorCsv(errorMsgPath, errorDatas);
}
log.error("over, 总共上传音频个数:"+count);
}
}
buildDicAuxiliaryTxt(botAccount, preBotAccount, botName, record);
}
private void buildDicAuxiliaryTxt(String botAccount,String preBotAccount, String name, Boolean record) {
try {
Path p = Paths.get(csvDic+"auxiliary.txt");
SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
String time = format.format(new Date());
StringBuilder builder;
if (StringUtils.isNotBlank(preBotAccount)) {
builder = new StringBuilder("\n更新作品,作品新id:").append(botAccount)
.append(", 旧id:").append(preBotAccount).append("; ");
} else {
builder = new StringBuilder("\n");
}
builder.append("作品名:").append(name).append("; ").append("作品id:").append(botAccount).append("; 语音类型:")
.append(record ? "人工":"合成").append("; 上传时间:").append(time).append("\n");
Files.write(p, builder.toString().getBytes(), StandardOpenOption.CREATE, StandardOpenOption.WRITE, StandardOpenOption.APPEND);
} catch (IOException e) {
log.error("buildAuxiliaryTxt:{}",e);
}
}
private void updateAlreadyUploadedBot(String botAccount, String preBotAccount, Boolean record, Long skillId, String botName) {
List<String> delIds = new ArrayList<>();
List<DicUploadInfo> dataNew = new ArrayList<>();
String preCsvPath;
if (record) {
preCsvPath = csvDic+preBotAccount+"_1.csv";
} else {
preCsvPath = csvDic+preBotAccount+"_0.csv";
}
String csvPath;
if (preBotAccount.equals(botAccount)) {
if (record) {
csvPath = csvDic+botAccount+"_1_r.csv";
} else {
csvPath = csvDic+botAccount+"_0_r.csv";
}
} else {
if (record) {
csvPath = csvDic+botAccount+"_1.csv";
} else {
csvPath = csvDic+botAccount+"_0.csv";
}
}
String errorCsvPath = csvDic+botAccount+"_error.csv";
if (Boolean.TRUE.equals(record)) {
// id -> DicUploadInfo
String mp3DataPath = "/root/TTS-service/audio/"+botAccount+"/record/";
List<DicUploadInfo> oldDataList = new ArrayList<>();
Map<String, Set<String>> oldDatas = new HashMap<>();
try (CSVParser csvRecords = CSVFormat.EXCEL.parse(new BufferedReader(
new InputStreamReader(new FileInputStream(new File(preCsvPath)), StandardCharsets.UTF_8)))) {
boolean first = true;
DicUploadInfo data;
String mp3FilePath;
for (CSVRecord line: csvRecords) {
if (first) {
first = false;
continue;
}
// "person", "mood", "md5", "id", "upUrl"
String person = line.get(0);
String md5 = line.get(2);
String id = line.get(3);
mp3FilePath = new StringBuilder(mp3DataPath).append(person).append(File.separator).append(md5).toString();
if (!Files.exists(Paths.get(mp3FilePath))) {
delIds.add(id);
continue;
}
Set<String> md5Set = oldDatas.computeIfAbsent(person, s -> new HashSet<>());
md5Set.add(md5);
data = DicUploadInfo.builder().person(person).md5(md5)
.id(Long.valueOf(id)).upUrl(line.get(4)).build();
oldDataList.add(data);
}
} catch (Exception e) {
log.error("updateAlreadyUploadedBot:"+e.toString());
}
File[] npcNameFiles = new File(mp3DataPath).listFiles();
if (npcNameFiles == null || npcNameFiles.length == 0) {
log.error(mp3DataPath+":"+" 下没有人物目录");
return;
}
for (File npcNameFile: npcNameFiles) {
String npcName = npcNameFile.getName();
Set<String> md5List;
if ((md5List = oldDatas.get(npcName)) != null) {
List<String> md5ListNew = new ArrayList<>();
File[] md3Files = npcNameFile.listFiles((dir, name) -> StringUtils.endsWith(name, ".mp3"));
if (md3Files == null || md3Files.length == 0) {
log.error(npcName+": 下没有mp3");
continue;
}
for (File tf: md3Files) {
md5ListNew.add(tf.getName());
}
DicUploadInfo info;
md5ListNew.removeAll(md5List);
for (String md5: md5ListNew) {
info = DicUploadInfo.builder().person(npcName).md5(md5).build();
dataNew.add(info);
}
} else {
DicUploadInfo info;
File[] md3Files = npcNameFile.listFiles((dir, name) -> StringUtils.endsWith(name, ".mp3"));
if (md3Files == null || md3Files.length == 0) {
log.error(npcName+": 下没有mp3");
continue;
}
for (File tf: md3Files) {
info = DicUploadInfo.builder().person(npcName).md5(tf.getName()).build();
dataNew.add(info);
}
}
}
buildDicCsv(csvPath, oldDataList);
if (dataNew.size() != 0) uploadNewData(dataNew, skillId, true, botAccount, csvPath, errorCsvPath, botName);
if (delIds.size() != 0) deleteTheAudio(delIds, skillId);
} else {
String mp3DataPath = "/root/TTS-service/audio/"+botAccount+"/";
List<DicUploadInfo> oldDataList = new ArrayList<>();
Map<String, Map<String, Set<String>>> oldDatas = new HashMap<>();
try (CSVParser csvRecords = CSVFormat.EXCEL.parse(new BufferedReader(
new InputStreamReader(new FileInputStream(new File(preCsvPath)), StandardCharsets.UTF_8)))) {
boolean first = true;
DicUploadInfo data;
String mp3FilePath;
String person,mood,md5,id;
for (CSVRecord line: csvRecords) {
if (first) {
first = false;
continue;
}
// "person", "mood", "md5", "id", "upUrl"
person = line.get(0);
mood = line.get(1);
md5 = line.get(2);
id = line.get(3);
mp3FilePath = new StringBuilder(mp3DataPath).append(person).append(File.separator)
.append(mood).append(File.separator).append(md5).toString();
if (!Files.exists(Paths.get(mp3FilePath))) {
delIds.add(id);
continue;
}
Map<String, Set<String>> mood2Md5s = oldDatas.computeIfAbsent(person, s -> new HashMap<>());
Set<String> md5s = mood2Md5s.computeIfAbsent(mood, s -> new HashSet<>());
md5s.add(md5);
data = DicUploadInfo.builder().person(person).md5(md5).mood(mood)
.id(Long.valueOf(id)).upUrl(line.get(4)).build();
oldDataList.add(data);
}
} catch (Exception e) {
log.error("updateAlreadyUploadedBot:"+e.toString());
}
DicUploadInfo info;
Map<String, Set<String>> mood2Md5s;
Set<String> md5List;
String npcName, mood;
File[] npcNameFiles = new File(mp3DataPath).listFiles();
if (npcNameFiles == null || npcNameFiles.length == 0) {
log.error(mp3DataPath+":"+" 下没有人物目录");
return;
}
for (File npcNameFile: npcNameFiles) {
npcName = npcNameFile.getName();
mood2Md5s = oldDatas.get(npcName);
if (mood2Md5s == null) {
File[] moodFiles = npcNameFile.listFiles();
if (moodFiles == null || moodFiles.length == 0) {
log.error(npcName+": 下没有mood目录");
continue;
}
for (File moodDic: moodFiles) {
mood = moodDic.getName();
File[] md5Files = moodDic.listFiles((dir, name) -> StringUtils.endsWith(name, ".mp3"));
if (md5Files == null || md5Files.length == 0) {
log.error(npcName+":"+mood+" 下没有mp3");
continue;
}
for (File md5: md5Files) {
info = DicUploadInfo.builder().person(npcName).md5(md5.getName()).mood(mood).build();
dataNew.add(info);
}
}
} else {
File[] moodFiles = npcNameFile.listFiles();
if (moodFiles == null || moodFiles.length == 0) {
log.error(npcName+": 下没有mood目录");
continue;
}
for (File moodDic: moodFiles) {
mood = moodDic.getName();
md5List = mood2Md5s.get(mood);
File[] md5Files = moodDic.listFiles((dir, name) -> StringUtils.endsWith(name, ".mp3"));
if (md5Files == null || md5Files.length == 0) {
log.error(npcName+":"+mood+" 下没有mp3");
continue;
}
if (md5List == null) {
for (File md5: md5Files) {
info = DicUploadInfo.builder().person(npcName).md5(md5.getName()).mood(mood).build();
dataNew.add(info);
}
} else {
for (File md5: md5Files) {
String md5Name = md5.getName();
if (!md5List.contains(md5Name)) {
info = DicUploadInfo.builder().person(npcName).md5(md5Name).mood(mood).build();
dataNew.add(info);
}
}
}
}
}
}
buildDicCsv(csvPath, oldDataList);
log.error("dataNew:"+dataNew.size());
log.error("delIds:"+delIds.size());
if (dataNew.size() != 0) uploadNewData(dataNew, skillId, false, botAccount, csvPath, errorCsvPath,botName);
if (delIds.size() != 0) deleteTheAudio(delIds, skillId);
}
}
private void uploadNewData(List<DicUploadInfo> dataNew, Long skillId, Boolean record, String botAccount,
String path, String errorMsgPath, String botName) {
Map<String, String> headers = new HashMap<>();
headers.put("Accept", "text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8");
headers.put("Accept-Encoding", "gzip, deflate, br");
headers.put("Connection", "keep-alive");
headers.put("User-Agent", "Mozilla/5.0 (X11; Ubuntu; Linux x86_64; rv:70.0) Gecko/20100101 Firefox/70.0");
List<DicUploadErrorInfo> errorDatas = new ArrayList<>();
List<DicUploadInfo> datas = new ArrayList<>();
String description;
int ln = 8;
int count = 0;
if (Boolean.TRUE.equals(record)) {
String root = "/root/TTS-service/audio/"+botAccount+"/record/";
String mp3FilePath;
for (DicUploadInfo info: dataNew) {
String npcName = info.getPerson();
String mp3FileName = info.getMd5();
mp3FilePath = new StringBuilder(root).append(npcName).append(File.separator).append(mp3FileName).toString();
if (doesFileExist(mp3FilePath)) {
File file = new File(mp3FilePath);
Integer duration = getMp3Time(file);
if (duration == null) {
errorDatas.add(DicUploadErrorInfo.builder().person(npcName)
.msg("无法获取到该mp3文件的时长").path(mp3FilePath).build());
continue;
}
try {
String randomMp3Name;
int i = 0;
do {
if (i++ == 60) {
i = 0;
ln += 1;
log.error("循环60次名字仍然冲突");
}
randomMp3Name = RandomStringUtils.randomAlphabetic(ln)+".mp3";
} while (testTheName(randomMp3Name, headers));
description = new StringBuilder(botName).append(File.separator)
.append(npcName).append(File.separator).append("record")
.append(File.separator).append(mp3FileName).toString();
PostFilePathAndId data = getCredentials(skillId, randomMp3Name, mp3FileName.substring(0,15),
file, duration,description);
Long id;
if (data != null && (id = data.getId()) != null) {
DicUploadInfo dicUploadInfo = DicUploadInfo.builder().id(id).md5(mp3FileName)
.person(npcName).upUrl(data.getPath()).build();
datas.add(dicUploadInfo);
} else {
errorDatas.add(DicUploadErrorInfo.builder()
.person(npcName).msg("发送请求失败,没有获取到id").path(mp3FilePath).build());
}
if (datas.size()==100) {
buildDicCsv(path, datas);
if (errorDatas.size() != 0) {
buildDicErrorCsv(errorMsgPath, errorDatas);
errorDatas.clear();
}
datas.clear();
log.error("到达100,datas清空后大小{},errorDatas清空后大小{}",datas.size(), errorDatas.size());
count += 100;
}
try {
Thread.sleep(1000);
} catch (Exception e) {}
} catch (Exception e) {
log.error("发送请求失败,出现异常:"+e.toString());
errorDatas.add(DicUploadErrorInfo.builder()
.person(npcName).msg("发送请求失败,出现异常").path(mp3FilePath).build());
}
} else {
errorDatas.add(DicUploadErrorInfo.builder().person(npcName)
.msg("mp3不存在").path(mp3FilePath).build());
}
}
if (datas.size() != 0) {
buildDicCsv(path, datas);
count += datas.size();
}
if (errorDatas.size() != 0) {
buildDicErrorCsv(errorMsgPath, errorDatas);
}
log.error("over, 总共上传音频个数:"+count);
} else {
String root = "/root/TTS-service/audio/"+botAccount+"/";
String mp3FilePath, person, mood, mp3FileName;
for (DicUploadInfo info: dataNew) {
person = info.getPerson();
mood = info.getMood();
mp3FileName = info.getMd5();
mp3FilePath = new StringBuilder(root).append(person).append(File.separator).append(mood)
.append(File.separator).append(mp3FileName).toString();
if (doesFileExist(mp3FilePath)) {
File file = new File(mp3FilePath);
Integer duration = getMp3Time(file);
if (duration == null) {
errorDatas.add(DicUploadErrorInfo.builder().person(person).mood(mood)
.msg("无法获取到该mp3文件的时长").path(mp3FilePath).build());
continue;
}
try {
String randomMp3Name;
int i = 0;
do {
if (i++ == 60) {
i = 0;
ln += 1;
log.error("循环60次名字仍然冲突");
}
randomMp3Name = RandomStringUtils.randomAlphabetic(ln)+".mp3";
} while (testTheName(randomMp3Name, headers));
description = new StringBuilder(botName).append(File.separator)
.append(person).append(File.separator).append(mood)
.append(File.separator).append(mp3FileName).toString();
PostFilePathAndId data = getCredentials(skillId, randomMp3Name, mp3FileName.substring(0,15),
file, duration, description);
Long id;
if (data != null && (id = data.getId()) != null) {
DicUploadInfo dicUploadInfo = DicUploadInfo.builder().id(id).md5(mp3FileName).mood(mood)
.person(person).upUrl(data.getPath()).build();
datas.add(dicUploadInfo);
} else {
errorDatas.add(DicUploadErrorInfo.builder().mood(mood)
.person(person).msg("发送请求失败,没有获取到id").path(mp3FilePath).build());
}
if (datas.size()==100) {
buildDicCsv(path, datas);
if (errorDatas.size() != 0) {
buildDicErrorCsv(errorMsgPath, errorDatas);
errorDatas.clear();
}
datas.clear();
log.error("到达100,datas清空后大小{},errorDatas清空后大小{}",datas.size(), errorDatas.size());
count += 100;
}
try {
Thread.sleep(1000);
} catch (Exception e) {}
} catch (Exception e) {
log.error("发送请求失败,出现异常:"+e.toString());
errorDatas.add(DicUploadErrorInfo.builder().mood(mood)
.person(person).msg("发送请求失败,出现异常").path(mp3FilePath).build());
}
} else {
errorDatas.add(DicUploadErrorInfo.builder().person(person).mood(mood)
.msg("mp3不存在").path(mp3FilePath).build());
}
}
if (datas.size() != 0) {
buildDicCsv(path, datas);
count += datas.size();
}
if (errorDatas.size() != 0) {
buildDicErrorCsv(errorMsgPath, errorDatas);
}
log.error("over, 总共上传音频个数:"+count);
}
}
public void dealErrorData(String errorName, Long skillId, boolean record, String botName) {
Map<String, String> headers = new HashMap<>();
headers.put("Accept", "text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8");
headers.put("Accept-Encoding", "gzip, deflate, br");
headers.put("Connection", "keep-alive");
headers.put("User-Agent", "Mozilla/5.0 (X11; Ubuntu; Linux x86_64; rv:70.0) Gecko/20100101 Firefox/70.0");
String errorPath = csvDic+errorName;
Path pt = Paths.get(errorPath);
if (Files.exists(pt)) {
String botAccount = errorName.substring(0, errorName.indexOf("_"));
String suffix = "_0.csv";
if (record) {
suffix = "_1.csv";
}
String dataPath = csvDic+botAccount+suffix;
String description;
try (CSVParser csvRecords = CSVFormat.EXCEL.parse(new BufferedReader(
new InputStreamReader(new FileInputStream(new File(errorPath)), StandardCharsets.UTF_8)))){
boolean first = true;
List<UploadInfo> datas = new ArrayList<>();
List<UploadErrorInfo> errorDatas = new ArrayList<>();
for (CSVRecord csvRecord: csvRecords) {
if (first) {
first = false;
continue;
}
String person = csvRecord.get(0);
String mood = csvRecord.get(1);
String id = csvRecord.get(2);
String text = csvRecord.get(3);
String path = csvRecord.get(4);
String msg = csvRecord.get(5);
if (msg.startsWith("m") || msg.startsWith("n")) {
errorDatas.add(UploadErrorInfo.builder().person(person).mood(mood)
.id(Long.parseLong(id)).path(path).text(text).msg(msg).build());
}
else {
File file = new File(path);
Integer duration = getMp3Time(file);
if (duration == null) {
errorDatas.add(UploadErrorInfo.builder().person(person).mood(mood).id(Long.parseLong(id))
.msg("无法获取到该mp3文件的时长").path(path).text(text).build());
continue;
}
String mp3FileName = path.substring(path.lastIndexOf("/")+1);
String randomMp3Name;
int i = 0;
int ln = 8;
do {
if (i++ == 60) {
i = 0;
ln += 1;
log.error("循环60次名字仍然冲突");
}
randomMp3Name = RandomStringUtils.randomAlphabetic(ln)+".mp3";
} while (testTheName(randomMp3Name, headers));
description = new StringBuilder(botName).append(File.separator)
.append(person).append(File.separator).append(mood)
.append(File.separator).append(mp3FileName).toString();
PostFilePathAndId data = getCredentials(skillId, randomMp3Name, mp3FileName.substring(0,15),
file, duration,description);
Long resourceId;
if (data != null && (resourceId = data.getId()) != null) {
UploadInfo info = UploadInfo.builder().id(resourceId).md5(mp3FileName)
.mood(mood).person(person).text(text).upUrl(data.getPath()).build();
datas.add(info);
} else {
errorDatas.add(UploadErrorInfo.builder()
.person(person).mood(mood).id(Long.parseLong(id))
.msg("发送请求失败,没有获取到id").path(path).text(text).build());
}
}
}
if (datas.size() != 0) {
buildCsv(dataPath, datas);
}
if (errorDatas.size() != 0) {
int i = errorName.indexOf("_");
int i2 = errorName.indexOf("_", i+1);
int num;
if (i2 == -1) {
num = 2;
} else {
num = Integer.parseInt(errorName.substring(i2+1, i2+2));
}
buildErrorCsv(csvDic + botAccount + "_error_"+num+".csv", errorDatas);
}
} catch (IOException e) {
e.printStackTrace();
}
}
}
// ===================================================
public void upload(Long projectId, Long skillId, Boolean record) {
Map<String, String> headers = new HashMap<>();
headers.put("Accept", "text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8");
headers.put("Accept-Encoding", "gzip, deflate, br");
headers.put("Connection", "keep-alive");
headers.put("User-Agent", "Mozilla/5.0 (X11; Ubuntu; Linux x86_64; rv:70.0) Gecko/20100101 Firefox/70.0");
GameProjectTbRepository gameDao = BaseHolder.getBean("gameProjectTbRepository");
GameProjectTb gameTB = gameDao.getOne(projectId);
String botAccount = gameTB.getBotAccount();
if (StringUtils.isBlank(botAccount)) {
log.error("没有该作品");
return;
}
if (!record.equals(gameTB.getAudioType() == 1)) {
log.error("参数record与该作品的音频类型不匹配");
return;
}
int count = 0;
PlotTextTBRepository plotTextRepository = BaseHolder.getBean("plotTextTBRepository");
List<PlotTextTB> plotTextTBList = plotTextRepository.getByProjectId(projectId);
ArrayList<UploadInfo> datas = new ArrayList<>();
List<UploadErrorInfo> errorDatas = new ArrayList<>();
String root = "/root/TTS-service/audio/"+botAccount;
String recordPath = root+"/record/";
// person -> [mood -> md5]
Map<String, Map<String, Set<String>>> audioMap = new HashMap<>();
// npcName -> md5
Map<String, Set<String>> recordMap = new HashMap<>();
String path;
if (record) {
path = new StringBuilder(csvDic)
.append(botAccount).append("_1.csv").toString();
} else {
path = new StringBuilder(csvDic)
.append(botAccount).append("_0.csv").toString();
}
String errorMsgPath = new StringBuilder(csvDic)
.append(botAccount).append("_error.csv").toString();
int ln = 8;
for (PlotTextTB tb: plotTextTBList) {
String npcName = tb.getNpcName();
String mood = tb.getMood();
String content = tb.getContent();
if (StringUtils.isBlank(content)) {
log.error("文本为空:"+tb.toString());
continue;
}
if (StringUtils.isAnyBlank(npcName, mood)) {
errorDatas.add(UploadErrorInfo.builder().id(tb.getId())
.msg("npcName或mood为空").text(content).build());
continue;
}
String mp3FilePath;
String mp3FileName = buildMP3Filename(content);
if (record) {
Set<String> recordAlreadyUp = recordMap.computeIfAbsent(npcName, s -> new HashSet<>());
if (!recordAlreadyUp.add(mp3FileName)) {
// errorDatas.add(UploadErrorInfo.builder().msg("重复").path("").text(String.valueOf(tb.getId())).build());
continue;
}
mp3FilePath = new StringBuilder(recordPath).append(npcName).append(File.separator)
.append(mp3FileName).toString();
} else {
Map<String, Set<String>> audioAlreadyUpMap = audioMap.computeIfAbsent(npcName, s -> new HashMap<>());
Set<String> audioAlreadyUp = audioAlreadyUpMap.computeIfAbsent(mood, s -> new HashSet<>());
if (!audioAlreadyUp.add(mp3FileName)) {
// errorDatas.add(UploadErrorInfo.builder().msg("重复").path("").text(String.valueOf(tb.getId())).build());
continue;
}
mp3FilePath = new StringBuilder(root).append(File.separator).append(npcName)
.append(File.separator).append(mood).append(File.separator).append(mp3FileName).toString();
}
if (doesFileExist(mp3FilePath)) {
File file = new File(mp3FilePath);
Integer duration = getMp3Time(file);
if (duration == null) {
errorDatas.add(UploadErrorInfo.builder().person(npcName).mood(mood).id(tb.getId())
.msg("无法获取到该mp3文件的时长").path(mp3FilePath).text(content).build());
// buildErrorMessageTxt(errorMsgPath, mp3FilePath, content, "无法获取到该mp3文件的时长");
continue;
}
try {
String randomMp3Name;
int i = 0;
do {
if (i++ == 60) {
i = 0;
ln += 1;
log.error("循环60次名字仍然冲突");
}
randomMp3Name = RandomStringUtils.randomAlphabetic(ln)+".mp3";
} while (testTheName(randomMp3Name, headers));
PostFilePathAndId data = getCredentials(skillId, randomMp3Name, mp3FileName.substring(0,15), file, duration, "test");
Long id;
if (data != null && (id = data.getId()) != null) {
UploadInfo info = UploadInfo.builder().id(id).md5(mp3FileName)
.mood(mood).person(npcName).text(content).upUrl(data.getPath()).build();
datas.add(info);
} else {
errorDatas.add(UploadErrorInfo.builder()
.person(npcName).mood(mood).id(tb.getId())
.msg("发送请求失败,没有获取到id").path(mp3FilePath).text(content).build());
// buildErrorMessageTxt(errorMsgPath, mp3FilePath, content, "发送请求失败,没有获取到id");
}
if (datas.size()==100) {
buildCsv(path, datas);
if (errorDatas.size() != 0) {
buildErrorCsv(errorMsgPath, errorDatas);
errorDatas.clear();
}
datas.clear();
log.error("到达100,datas清空后大小{},errorDatas清空后大小{}",datas.size(), errorDatas.size());
count += 100;
}
try {
Thread.sleep(1000);
} catch (Exception e) {}
} catch (Exception e) {
log.error("发送请求失败,出现异常:"+e.toString());
errorDatas.add(UploadErrorInfo.builder()
.person(npcName).mood(mood).id(tb.getId())
.msg("发送请求失败,出现异常").path(mp3FilePath).text(content).build());
// buildErrorMessageTxt(errorMsgPath, mp3FilePath, content, "发送请求失败,出现异常");
}
} else {
if (record) {
if (tb.getAudioFlag() != 2) {
log.error("上传人工语音作品但是该句话的标识却不是人工语音:"+tb.toString());
continue;
}
} else {
if (tb.getAudioFlag() != 1) {
log.error("上系统合成音作品但是该句话的标识却不是系统音:"+tb.toString());
continue;
}
}
errorDatas.add(UploadErrorInfo.builder()
.person(npcName).mood(mood).id(tb.getId())
.msg("mp3不存在").path(mp3FilePath).text(content).build());
// buildErrorMessageTxt(errorMsgPath, mp3FilePath, content, "mp3不存在");
}
}
if (datas.size() != 0) {
buildCsv(path, datas);
count += datas.size();
}
if (errorDatas.size() != 0) {
buildErrorCsv(errorMsgPath, errorDatas);
}
buildAuxiliaryTxt(botAccount, gameTB.getName(), record);
log.error("over, 总共上传音频个数:{}",count);
}
private boolean doesFileExist(String filePath) {
File file = new File(filePath);
if (file.exists()) {
//log.info("文件:{},大小为:{}", filePath, file.length());
if (file.length() == 0) {
log.error("上传时大小为0的文件:{}",filePath);
return false;
}
return true;
}
return false;
}
private boolean doesFileExist(File file) {
if (file.exists()) {
//log.info("文件:{},大小为:{}", filePath, file.length());
if (file.length() == 0) {
log.error("上传时大小为0的文件:{}",file.getAbsolutePath());
return false;
}
return true;
}
return false;
}
private void buildErrorMessageTxt(String path, String mp3Path, String text, String errorMsg) {
StringBuilder builder = new StringBuilder("文本:").append(text).append("; 地址:").append(mp3Path)
.append("; 信息:").append(errorMsg).append("\n");
try {
Files.write(Paths.get(path), builder.toString().getBytes(), StandardOpenOption.CREATE,
StandardOpenOption.WRITE, StandardOpenOption.APPEND);
} catch (Exception e) {
log.error("buildErrorMessageTxt:{}",e);
log.error(builder.toString());
}
}
private String buildMP3Filename(String text) {
String file = DigestUtils.md5DigestAsHex(text.getBytes(StandardCharsets.UTF_8));
file = file+".mp3";
return file;
}
private void buildCsv(String path, List<UploadInfo> datas) {
CSVFormat format;
if (Files.exists(Paths.get(path))) format = CSVFormat.DEFAULT;
else format = CSVFormat.DEFAULT.withHeader("person", "mood", "md5", "id", "text", "upUrl");
try (CSVPrinter csvPrinter = new CSVPrinter(new OutputStreamWriter(
new FileOutputStream(path, true), Charset.forName("UTF-8")),format)){
for (UploadInfo info: datas) {
csvPrinter.printRecord(info.getPerson(), info.getMood(), info.getMd5(), info.getId(), info.getText(), info.getUpUrl());
}
} catch (IOException e) {
e.printStackTrace();
}
}
private void buildDicCsv(String path, List<DicUploadInfo> datas) {
CSVFormat format;
if (Files.exists(Paths.get(path))) format = CSVFormat.DEFAULT;
else format = CSVFormat.DEFAULT.withHeader("person", "mood", "md5", "id", "upUrl");
try (CSVPrinter csvPrinter = new CSVPrinter(new OutputStreamWriter(
new FileOutputStream(path, true), Charset.forName("UTF-8")),format)){
for (DicUploadInfo info: datas) {
csvPrinter.printRecord(info.getPerson(), info.getMood(), info.getMd5(), info.getId(), info.getUpUrl());
}
} catch (IOException e) {
e.printStackTrace();
}
}
private void buildErrorCsv(String path, List<UploadErrorInfo> datas) {
CSVFormat format;
if (Files.exists(Paths.get(path))) format = CSVFormat.DEFAULT;
else format = CSVFormat.DEFAULT.withHeader("person", "mood", "id", "text", "path", "msg");
try (CSVPrinter csvPrinter = new CSVPrinter(new OutputStreamWriter(
new FileOutputStream(path, true), Charset.forName("UTF-8")),format)){
for (UploadErrorInfo info: datas) {
csvPrinter.printRecord(info.getPerson(), info.getMood(), info.getId(),
info.getText(), info.getPath(), info.getMsg());
}
} catch (IOException e) {
e.printStackTrace();
}
}
private void buildDicErrorCsv(String path, List<DicUploadErrorInfo> datas) {
CSVFormat format;
if (Files.exists(Paths.get(path))) format = CSVFormat.DEFAULT;
else format = CSVFormat.DEFAULT.withHeader("person", "mood", "path", "msg");
try (CSVPrinter csvPrinter = new CSVPrinter(new OutputStreamWriter(
new FileOutputStream(path, true), Charset.forName("UTF-8")),format)){
for (DicUploadErrorInfo info: datas) {
csvPrinter.printRecord(info.getPerson(), info.getMood(), info.getPath(), info.getMsg());
}
} catch (IOException e) {
e.printStackTrace();
}
}
private void buildAuxiliaryTxt(String botAccount, String name, boolean record) {
try {
Path p = Paths.get(csvDic+"auxiliary.txt");
SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
String time = format.format(new Date());
StringBuilder builder = new StringBuilder("作品名:");
builder.append(name).append("; ").append("作品id:").append(botAccount).append("; 语音类型:")
.append(record ? "人工":"合成").append("上传时间:").append(time).append("\n");
Files.write(p, builder.toString().getBytes(), StandardOpenOption.CREATE, StandardOpenOption.WRITE, StandardOpenOption.APPEND);
} catch (IOException e) {
log.error("buildAuxiliaryTxt:{}",e);
}
}
private Integer getMp3Time(File file) {
try {
MultimediaObject sourceObject = new MultimediaObject(file);
return Math.toIntExact((sourceObject.getInfo().getDuration() / 1000));
} catch (Exception e) {
log.error("getMp3Time:{}",e);
}
return null;
}
private boolean testTheName(String path, Map<String, String> headers) {
path = "https://ailabs.alibabausercontent.com/images/4cb40023ec377287074815415900886a/"+path;
return ApachHttpUtils.getProbe(path, headers);
}
public static void main(String[] args) throws IOException {
SpiritAudioUpload instance = new SpiritAudioUpload();
// instance.getCredentials(36328L, "k3y9633c.mp3", "repeate", new File("/home/yf01/下载/out.mp3"), 3);
// System.out.println(URLEncodedUtils.parse("%E2%98%98%EF%B8%8F%20common%2F%E8%8E%B7%E5%8F%96%20oss%20token|%20|%20|0|", StandardCharsets.UTF_8));
Map<String, String> headers = new HashMap<>();
headers.put("Accept", "text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8");
headers.put("Accept-Encoding", "gzip, deflate, br");
headers.put("Connection", "keep-alive");
headers.put("User-Agent", "Mozilla/5.0 (X11; Ubuntu; Linux x86_64; rv:70.0) Gecko/20100101 Firefox/70.0");
boolean response = ApachHttpUtils.getProbe("https://ailabs.alibabausercontent.com/images/1488d8c03dfd3125db25b6aec94dcf92/k3ydx7n3.mp3", headers);
System.out.println(response);
boolean response2 = ApachHttpUtils.getProbe("https://ailabs.alibabausercontent.com/images/1488d8c03dfd3125db25b6aec94dcf92/k3ydx7n3dfs.mp3", headers);
System.out.println(response2);
}
}
logging.path=/usr/mqw/logs/spirit
logging.level.root = info
spring.output.ansi.enabled=detect
server:
port: 8188
logging:
path: /home/dc2-user/projects/audiobox/spirit/logs
level:
root: error
csvDic: /home/dc2-user/audioBox/spirit/csv/
spring:
datasource:
gameditor:
jdbc-url: jdbc:mysql://localhost:3306/game_editor_db?useUnicode=true&characterEncoding=utf-8&serverTimezone=Hongkong&useSSL=false
username: root
password: 38A0O1jEPOE
driver-class-name: com.mysql.cj.jdbc.Driver
secondary:
jdbc-url: jdbc:mysql://localhost:3306/game_editor_db?useUnicode=true&characterEncoding=utf-8&serverTimezone=Hongkong&useSSL=false
username: root
password: 38A0O1jEPOE
driver-class-name: com.mysql.cj.jdbc.Driver
# analysis:
# jdbc-url: jdbc:mysql://localhost:3306/analysis?useUnicode=true&characterEncoding=utf-8&serverTimezone=Hongkong&useSSL=false
# username: root
# password: 38A0O1jEPOE
# driver-class-name: com.mysql.cj.jdbc.Driver
jpa:
database: mysql
#控制台显示SQL
show-sql: true
hibernate:
ddl-auto: none
output:
ansi:
enabled: detect
\ No newline at end of file
Jfc4Z4Ur15JwUBuvUQD5wg7Nu8+l+HscqYlfofbyJdYGH+f3XrduI0FLgVW7gXyV
\ No newline at end of file
Jfc4Z4Ur15JwUBuvUQD5wg7Nu8+l+HscqYlfofbyJdaEr7275aEMVjPWxwUQXYKO
\ No newline at end of file
Jfc4Z4Ur15JwUBuvUQD5wg7Nu8+l+HscqYlfofbyJdbWemsw1KjF/K5sTmFtefcK
\ No newline at end of file
Jfc4Z4Ur15JwUBuvUQD5wg7Nu8+l+HscqYlfofbyJdYl1WV0wUh0suAg2swzr9op
\ No newline at end of file
Jfc4Z4Ur15JwUBuvUQD5wg7Nu8+l+HscqYlfofbyJdYHaA0JQeSQDRWj5Va+HtGy
\ No newline at end of file
Jfc4Z4Ur15JwUBuvUQD5wg7Nu8+l+HscqYlfofbyJdaEZbglH1ruVqu+Lzfq0fGo
\ No newline at end of file
...@@ -83,10 +83,41 @@ ...@@ -83,10 +83,41 @@
<scope>system</scope> <scope>system</scope>
<systemPath>${project.basedir}/src/main/resources/static/bot-sdk-1.2.0.jar</systemPath> <systemPath>${project.basedir}/src/main/resources/static/bot-sdk-1.2.0.jar</systemPath>
</dependency> </dependency>
<dependency>
<groupId>ws.schild</groupId>
<artifactId>jave-core</artifactId>
<version>2.7.1</version>
</dependency>
<!-- https://mvnrepository.com/artifact/ws.schild/jave-native-linux64 -->
<dependency>
<groupId>ws.schild</groupId>
<artifactId>jave-native-linux64</artifactId>
<version>2.4.6</version>
</dependency>
<!-- https://mvnrepository.com/artifact/ws.schild/jave-native-linux32 -->
<dependency>
<groupId>ws.schild</groupId>
<artifactId>jave-native-linux32</artifactId>
<version>2.4.6</version>
</dependency>
<dependency>
<groupId>org.apache.httpcomponents</groupId>
<artifactId>httpclient</artifactId>
</dependency>
<!-- https://mvnrepository.com/artifact/org.apache.httpcomponents/httpmime -->
<dependency>
<groupId>org.apache.httpcomponents</groupId>
<artifactId>httpmime</artifactId>
</dependency>
<dependency>
<groupId>com.alibaba</groupId>
<artifactId>fastjson</artifactId>
<version>1.2.62</version>
</dependency>
</dependencies> </dependencies>
<build> <build>
<finalName>testTool</finalName> <finalName>useTool</finalName>
<plugins> <plugins>
<plugin> <plugin>
<groupId>org.springframework.boot</groupId> <groupId>org.springframework.boot</groupId>
......
package ai.qiwu.com.third_party_load.common;
import lombok.extern.slf4j.Slf4j;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.NameValuePair;
import org.apache.http.ParseException;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.config.RequestConfig;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.ContentType;
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.HttpClients;
import org.apache.http.impl.conn.PoolingHttpClientConnectionManager;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.protocol.HTTP;
import org.apache.http.util.EntityUtils;
import org.springframework.util.CollectionUtils;
import java.io.BufferedReader;
import java.io.File;
import java.io.IOException;
import java.io.InputStreamReader;
import java.nio.charset.Charset;
import java.nio.charset.StandardCharsets;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
/**
* @author 苗权威
* @dateTime 19-12-4 下午7:59
*/
@Slf4j
public class ApachHttpUtils {
private static CloseableHttpClient httpClient;
static {
PoolingHttpClientConnectionManager cm = new PoolingHttpClientConnectionManager();
cm.setMaxTotal(100);
cm.setDefaultMaxPerRoute(50);
httpClient = HttpClients.custom().setConnectionManager(cm).build();
}
public static String get(String url, Map<String, String> headers, Map<String, String> params) {
HttpGet httpget = new HttpGet(url);
if (!CollectionUtils.isEmpty(headers)) headers.forEach(httpget::setHeader);
if (!CollectionUtils.isEmpty(params)) {
List<NameValuePair> qparams = new ArrayList<>();
qparams.add(new BasicNameValuePair("q"))
}
try {
CloseableHttpResponse response = httpClient.execute(httpget);
try {
// 获取响应实体
HttpEntity entity = response.getEntity();
// 打印响应状态
System.out.println(response.getStatusLine());
if (entity != null) {
// 打印响应内容长度
System.out.println("Response content length: " + entity.getContentLength());
// 打印响应内容
System.out.println("Response content: " + EntityUtils.toString(entity));
}
} finally {
response.close();
}
} catch (IOException | ParseException e) {
e.printStackTrace();
} finally {
// 关闭连接,释放资源
try {
httpclient.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
public static String post(String url, String jsonString, Map<String, String> headers) {
String result = null;
HttpPost httpPost = new HttpPost(url);
RequestConfig requestConfig = RequestConfig.custom().setConnectTimeout(30000).setConnectionRequestTimeout(30000).setSocketTimeout(30000).build();
httpPost.setConfig(requestConfig);
if (!CollectionUtils.isEmpty(headers)) headers.forEach(httpPost::setHeader);
else {
httpPost.addHeader("Content-type", "application/json; charset=utf-8");
httpPost.setHeader("Accept", "application/json");
}
httpPost.setEntity(new StringEntity(jsonString, Charset.forName("UTF-8")));
try(CloseableHttpResponse response = httpClient.execute(httpPost);
BufferedReader in = new BufferedReader(new InputStreamReader(response.getEntity().getContent()))) {
StringBuilder sb = new StringBuilder();
String line;
while ((line = in.readLine()) != null) {
sb.append(line);
}
result = sb.toString();
} catch (IOException e) {
log.error("post表单请求出错:"+e);
}
return result;
}
public static String requestByPostParts(Map<String,String> map, Map<String,String> headers, String url, Charset charset, File file) {
try {
HttpPost post = new HttpPost(url);
if (!CollectionUtils.isEmpty(headers)) headers.forEach(post::setHeader);
MultipartEntityBuilder multipartEntityBuilder = MultipartEntityBuilder.create();
multipartEntityBuilder.setMode(HttpMultipartMode.BROWSER_COMPATIBLE);
if(map!=null) {
ContentType contentType = ContentType.create(HTTP.PLAIN_TEXT_TYPE, StandardCharsets.UTF_8);
for (Map.Entry<String, String> stringObjectEntry : map.entrySet()) {
String key = stringObjectEntry.getKey();
String value = stringObjectEntry.getValue();
multipartEntityBuilder.addTextBody(key, value, contentType);
}
}
if (file != null) {
multipartEntityBuilder.addBinaryBody("file", file);
}
post.setEntity(multipartEntityBuilder.build());
HttpResponse resp = httpClient.execute(post);
int ret = resp.getStatusLine().getStatusCode();
if (ret != 200) return null;
HttpEntity entity = resp.getEntity();
try (BufferedReader br = new BufferedReader(new InputStreamReader(entity.getContent(), charset))){
StringBuilder responseString = new StringBuilder();
String result = br.readLine();
while (result != null)
{
responseString.append(result);
result = br.readLine();
}
return responseString.toString();
}
} catch (Exception e)
{
log.error(e.toString());
}
return null;
}
}
package ai.qiwu.com.third_party_load.spirit;
import lombok.Getter;
import lombok.Setter;
import lombok.ToString;
/**
* @author 苗权威
* @dateTime 19-12-9 下午6:43
*/
@Getter
@Setter
@ToString
public class Content {
private Object size;
private Object creatorId;
private Object gmtCreate;
private String name;
private String alias;
private String style = "default";
private String status;
private String actor;
private String sourceType="www";
private String fileType="mp3";
private Object gmtModified;
private String catalog="default";
private String icon;
private String source;
private String id;
private String description="";
private String mediaType="audio";
}
package ai.qiwu.com.third_party_load.spirit;
import com.fasterxml.jackson.annotation.JsonIgnoreProperties;
import lombok.Getter;
import lombok.Setter;
import lombok.ToString;
/**
* @author 苗权威
* @dateTime 19-12-9 下午5:36
*/
@Getter
@Setter
@ToString
@JsonIgnoreProperties(ignoreUnknown = true)
public class Credential {
private Integer retCode;
private CredentialsResponse retValue;
}
package ai.qiwu.com.third_party_load.spirit;
import com.fasterxml.jackson.annotation.JsonIgnoreProperties;
import lombok.Getter;
import lombok.Setter;
import lombok.ToString;
/**
* @author 苗权威
* @dateTime 19-12-9 下午4:48
*/
@Getter
@Setter
@ToString
@JsonIgnoreProperties(ignoreUnknown = true)
public class CredentialsResponse {
private String accessId;
private String signature;
private String host;
private String dir;
private String policy;
}
package ai.qiwu.com.third_party_load.spirit;
import lombok.Getter;
import lombok.Setter;
/**
* @author 苗权威
* @dateTime 19-12-9 下午6:47
*/
@Getter
@Setter
public class ExtendAttrs {
private Integer duration;
private Integer contentId=0;
private String singer;
private String lyrics;
private String composer;
}
package ai.qiwu.com.third_party_load.spirit;
import lombok.Getter;
import lombok.Setter;
import lombok.ToString;
/**
* @author 苗权威
* @dateTime 19-12-9 下午6:42
*/
@Getter
@Setter
@ToString
public class PostFileData {
private Content content;
private ExtendAttrs extendAttrs;
}
package ai.qiwu.com.third_party_load.spirit;
import lombok.Getter;
import lombok.Setter;
import lombok.ToString;
import java.util.List;
/**
* @author 苗权威
* @dateTime 19-12-9 下午6:39
*/
@Getter
@Setter
@ToString
public class PostFileVO {
private Long skillId;
private List<PostFileData> content;
}
package ai.qiwu.com.third_party_load.spirit;
import ai.qiwu.com.third_party_load.common.ApachHttpUtils;
import ai.qiwu.com.xiaoduhome.common.ApachHttpUtils;
import ai.qiwu.com.xiaoduhome.common.OkHttp3Utils;
import com.alibaba.fastjson.JSON;
import org.apache.commons.lang3.RandomStringUtils;
import java.io.File;
import java.io.IOException;
import java.nio.charset.StandardCharsets;
import java.util.Collections;
import java.util.HashMap;
import java.util.Map;
/**
* @author 苗权威
* @dateTime 19-12-9 下午4:38
*/
public class SpiritAudioUpload {
private static String cookie = "cna=qsWIFY5RHlMCAXeJN3DsHj3O; isg=BM_PGtqtziiZlsq4zXxIYq3YXWoZXCKL8pto7-HdBj5csOmy7sVEZ-xmsiCr0_uO; UM_distinctid=16b503f1b20c6-06eacd3e9803d68-70216751-1fa400-16b503f1b21428; CNZZDATA1261708326=1797143004-1560414985-%7C1575889065; _cnzz_CV1261708326=51805%7C%F0%9F%8C%8E%20skill-aduio%2F%E5%A2%9E%E5%8A%A0%E5%86%85%E5%AE%B9%7Cp; hng=CN%7Czh-CN%7CCNY%7C156; uc1=pas=0&cookie21=UtASsssme%2BBq&tag=8&cookie14=UoTbmEnmIFxXUw%3D%3D&existShop=false&cookie15=Vq8l%2BKCLz3%2F65A%3D%3D&lng=zh_CN&cookie16=VFC%2FuZ9az08KUQ56dCrZDlbNdA%3D%3D; t=925ffaa4a0ded6c2dc567c2eedd425f0; enc=GlWCH0jde0teESrXYo%2BHF75NARTOPv7uKzyscUHesjr8NqyYTkHf%2BD6PG2iP4gPoGIsaO8aq%2BG41Q6kPPhYpvw%3D%3D; _tb_token_=3a3eeb3e68337; cookie2=145c78f447bf6a4cafb894c15072214f; dnk=tb13503054; tracknick=tb13503054; _l_g_=Ug%3D%3D; unb=1038446007; cookie1=UNMubI1eQ0gVOzLdxFCJj7hzIKFouglcA%2BlE1IYgcZQ%3D; login=true; cookie17=UoH8Vd06g9TEfA%3D%3D; _nk_=tb13503054; sg=47f; csg=f8c7b18a; ctoken=356ALxSxQb1ZmQez6Jmob2DF; accountType=TB; EGG_SESS=OG910qv3Q3gsrSK4yqRmX3-1-P_ARlUIzlqweqLqnRF5dKELPTe4hiVT80Slz3WPDCsXS99IeB9EJ08mKe1fnDasFJb3eNz2Vf7jPG_XwDCT1o_6qx8JeGdgfBUNEuTSA3TZVaN9QVgibCFmDyQ3kLogAPW3lt69cHOY2V4lCJz0d4gFzNPaa6xGuHg1TO4J-Tv3jem9H5jX0yByaHu99DSyXPkfiuTXXTjodFtuEfzvuDIJHB6un7K0boZHL32LueAnmulxRRtwGGT6XCElBx-5QJtGusip5_X0kQr8CGnaJOOviUKCwrEYrpae2muO0QMDEazrmH-zNHo6_sHESFPSEkOfrLtuUoysIkskq67WaS7HdrPJ3jXX5ncYfHHajuTw60ua_tg308HFs2EhtuTwS0AYuSze87Qc7JGuqGiDUUmBHMKZPk98JAAXhIFUho2sM8NlZZd7R-Y0TEuQi50ZRwWKxekmWfhNdxCbbC3SAms35VZnXJNIRaqPa3HH6h0kAfsMLAkINm0uLR4aLmz-i1KJi67iRrNsCRNt5aMxG1dFC1sIWeX1vC_acAy_LGTEGRot6F9_ZemJpfL9To1MHC5iAoywxI0quYl6fFHVKrrNQMmmpHar2t_qxNv_JSEZYA4j4Tn5o8H6I9AuoqY3t0draEf-TYWdVJ-9ymynvx-yC8APBAQULkDtQhxIE9DB5qzTcVUngELwU5sGXA18Jchu8xxZfNguaq8CMPHYI4gVBu3kr4qcOmuobluhSWtYxqAQlGFL1ys7cbX79hnUwJZOxly6ZJhFjqv_iLglHn2sR0w8IaJVLzEs0WlP3kPcK3QeIC2MWz04-zdcybCz02JWPhgWvRWBekKSIyhEAqc4dlhphYhIGoiSoFySAT8lWfYpsD2Yq3FJDqtPksP94z0kIhtvo9ABLoi0Zsb_6xNlwCpO4VrfwTfKI92ZwoTQ-2owqGR30vyJsLlSww61irBBTwdCj9MuB8_p7vVt7kRDKW3zMVEiD6saoe2AduoSrgSm-H_a-hkn74DR8VWCE8WyzFAQaIFU9hQgtHPkF0wcLBejpF14y2KU1CyxwHQyR1GFhde8fEoTY35V6U7Tkh1XbTVblkcQ32h5g4bIH9-S1qWfSE-kr-LlVUD7c2hwQLFXPihx2mu1BNYK_895qBl7qcctVyBVZEpkZEflz9shW0FTfjKxS5t-oFLbUfxqVlYWUruikMuobOdEspQdi4sXFcWBSXarwFpqR8DTE2TUsWfwLZnmQVcxDSI0rgFUV1xTUYDR9JxePU1C79D9sEYbrM5kjaDOTAEyy-uwxp24tOIjXRGU1_EOtJs9Y10tIIx3ZhnkYAATQ0nbRn25S1l3q_cOUqaUWAw4dSDu-OP2YfM7MtCueHTDMmTgYQTzJCn_W6Z3UqlL4W04BJ-JUcy_iL6iYT0LxKVId-X7l7F-tyF19jE-g1-94WcFcDYwhO3RGbPIejQ-0qX3jnCyhhFwK4thLN8Kv8ZZOT5RgsjWZaMrhneYavxUJ9MT9spchtpFeQlvDpgkrhtSFVfiVQqagpyQuCNpXLhBVIfY9qkqEI46xG_svTgLUJhYO0dyB0wEbeDlTtu-Vkuu-hbskP927ZiAgDRPPcaoH8g6PSJc-rDXcpxTAg-yJSaMjcGxHbJBX513jJPyypAlj5cl7y3rzxOt2eQmlt93yrYIA4UYA-uCu63Lcghw4ONe_GX-KYgue8F39lTto4T_-_CsqJ3KV_7j27X3h4h-rEyArHcQAyzMCL28PiTSYLf7OCTWRfrFLV4KNFAp1xAfecsIAruvQZ6maiLDbV8wWbdjQ1gp31InnknlZ_EsSUMuv0-Zce_z8EdHsMjCW3ghZnqq3M0RdhKYMu5N0HBV-r_mfRzg-ozbMtYESIgNm3VCqLNAFb4cVdxKDpT3W5HzfuncbKvGjqMOQDzCHU1yX1_N4zXRXmZgu31GH6PztPLFpvmglcph1m7tXb9eDTM4q8CjXt_RO7BvOKRjyYVi4nbcC1_3eA-SDnu-jGVnZlFmPkBktT4KOLyUetFHV_4BtAdCrQpqGasaCDsLMSJNT1HuUoboyReaJdF3znNaYcVZ78d-2hGEZmpEfXYhLKIdPECG818C4kpX_GC1FYDjkMYP858gxgTuIEMTlg2HaDyHlFeRlKAjHAsEGjlD4t_J_5SI0Eyhq0bsCrhCw4wkpbrnDzOcvAWn3S8J3iR8lw_G; accountId=51805; token=J3OSUj5/Z6F0ikwsnEoTPwzMw/dDAe05NSImfEHH+gk=; confirmProtocolVersion=1";
private static void getCredentials(Long skillId, String randomName, String customName,File file, Integer duration) 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/36328/audiolist");
headers.put("TE", "Trailers");
headers.put("Token", "J3OSUj5/Z6F0ikwsnEoTPwzMw/dDAe05NSImfEHH+gk=");
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", "356ALxSxQb1ZmQez6Jmob2DF");
String result = OkHttp3Utils.doGet("https://open.aligenie.com/api/oss/credentials", new HashMap<>(), headers);
System.out.println(result);
CredentialsResponse response = JSON.parseObject(result, Credential.class).getRetValue();
String path = response.getDir()+ File.separator+ randomName;
Map<String, String> params = new HashMap<>();
params.put("name", file.getName());
params.put("OSSAccessKeyId", response.getAccessId());
params.put("policy", response.getPolicy());
params.put("Signature", response.getSignature());
params.put("key", path);
// params.put("key", response.getDir()+ File.separator+ "k3y89mz1.mp3");
params.put("success_action_status", "200");
Map<String, String> prePostHeaders = new HashMap<>();
prePostHeaders.put("Accept", "*/*");
prePostHeaders.put("Connection", "keep-alive");
prePostHeaders.put("Origin", "https://open.aligenie.com");
prePostHeaders.put("Referer", "https://open.aligenie.com/console/skill/36328/audiolist");
prePostHeaders.put("User-Agent", "Mozilla/5.0 (X11; Ubuntu; Linux x86_64; rv:70.0) Gecko/20100101 Firefox/70.0");
String resultPrePost = ApachHttpUtils.requestByPostParts(params, prePostHeaders, "https://ar-platform.oss-cn-shanghai.aliyuncs.com/", StandardCharsets.UTF_8,file);
if (resultPrePost != null) {
System.out.println(resultPrePost);
PostFileVO vo = new PostFileVO();
vo.setSkillId(skillId);
PostFileData data = new PostFileData();
Content content = new Content();
content.setName(customName);
content.setAlias(file.getName());
content.setSource("https://ailabs.alibabausercontent.com/"+path);
ExtendAttrs extendAttrs = new ExtendAttrs();
extendAttrs.setDuration(duration);
data.setContent(content);
data.setExtendAttrs(extendAttrs);
vo.setContent(Collections.singletonList(data));
String answer = ApachHttpUtils.post("https://open.aligenie.com/api/custom/audio/contents", JSON.toJSONString(vo), headers);
System.out.println(answer);
}
}
public static void main(String[] args) throws IOException {
getCredentials(36328L, RandomStringUtils.randomAlphabetic(9), "miaoRand", new File("/home/yf01/下载/out.mp3"), 3);
}
}
...@@ -110,25 +110,44 @@ ...@@ -110,25 +110,44 @@
<!--<artifactId>java-getopt</artifactId>--> <!--<artifactId>java-getopt</artifactId>-->
<!--<version>1.0.13</version>--> <!--<version>1.0.13</version>-->
<!--</dependency>--> <!--</dependency>-->
<!-- https://mvnrepository.com/artifact/ws.schild/jave-all-deps --> <!--<dependency>-->
<dependency> <!--<groupId>ws.schild</groupId>-->
<groupId>ws.schild</groupId> <!--<artifactId>jave-all-deps</artifactId>-->
<artifactId>jave-all-deps</artifactId> <!--<version>2.7.1</version>-->
<version>2.7.1</version> <!--</dependency>-->
</dependency>
<!-- https://mvnrepository.com/artifact/org/jaudiotagger --> <!--https://mvnrepository.com/artifact/ws.schild/jave-core-->
<dependency> <!--<dependency>-->
<groupId>org</groupId> <!--<groupId>ws.schild</groupId>-->
<artifactId>jaudiotagger</artifactId> <!--<artifactId>jave-core</artifactId>-->
<version>2.0.3</version> <!--<version>2.7.1</version>-->
</dependency> <!--</dependency>-->
<dependency> <!--&lt;!&ndash; https://mvnrepository.com/artifact/ws.schild/jave-native-linux64 &ndash;&gt;-->
<groupId>com.jave</groupId> <!--<dependency>-->
<artifactId>jave</artifactId> <!--<groupId>ws.schild</groupId>-->
<version>1.0.2</version> <!--<artifactId>jave-native-linux64</artifactId>-->
<scope>system</scope> <!--<version>2.4.6</version>-->
<systemPath>${project.basedir}/src/main/resources/static/jave-1.0.2.jar</systemPath> <!--</dependency>-->
</dependency> <!--&lt;!&ndash; https://mvnrepository.com/artifact/ws.schild/jave-native-linux32 &ndash;&gt;-->
<!--<dependency>-->
<!--<groupId>ws.schild</groupId>-->
<!--<artifactId>jave-native-linux32</artifactId>-->
<!--<version>2.4.6</version>-->
<!--</dependency>-->
<!--&lt;!&ndash; https://mvnrepository.com/artifact/org/jaudiotagger &ndash;&gt;-->
<!--<dependency>-->
<!--<groupId>org</groupId>-->
<!--<artifactId>jaudiotagger</artifactId>-->
<!--<version>2.0.3</version>-->
<!--</dependency>-->
<!--<dependency>-->
<!--<groupId>com.jave</groupId>-->
<!--<artifactId>jave</artifactId>-->
<!--<version>1.0.2</version>-->
<!--<scope>system</scope>-->
<!--<systemPath>${project.basedir}/src/main/resources/static/jave-1.0.2.jar</systemPath>-->
<!--</dependency>-->
<!--<dependency>--> <!--<dependency>-->
<!--<groupId>org.tritonus.share</groupId>--> <!--<groupId>org.tritonus.share</groupId>-->
<!--<artifactId>tritonus</artifactId>--> <!--<artifactId>tritonus</artifactId>-->
......
...@@ -122,6 +122,43 @@ public class CallPython { ...@@ -122,6 +122,43 @@ public class CallPython {
return "1"; return "1";
} }
public static String ffmpegExecute(String arg) {
ProcessBuilder processBuilder = new ProcessBuilder(arg.split(" "));
processBuilder.redirectErrorStream(true); //错误输出流合并到标准输出流中
StringBuilder builder = new StringBuilder();
Process process = null;
try {
//long startTime = System.currentTimeMillis();
process = processBuilder.start();
process.waitFor();
BufferedReader reader = new BufferedReader(new InputStreamReader(process.getInputStream()));
String line;
if (process.exitValue() != 0) {
while ((line = reader.readLine()) != null) {
builder.append(line);
}
if (builder.length() > 0) {
log.error("ffmpeg执行出错:{}",builder.toString());
return "0";
}
}else {
while ((line = reader.readLine()) != null) {
// builder.append(line);
}
// if (builder.length() != 0){
// log.info("ffmpeg返回信息:{}", builder.toString());
// }
}
//log.info(Thread.currentThread().getName()+"耗时:"+(System.currentTimeMillis()-startTime));
} catch (IOException | InterruptedException e) {
log.info("Error while running ffmpeg. {}",e.getMessage());
return "0";
} finally {
if (process != null) process.destroy();
}
return "1";
}
private static String execute(String[] args) { private static String execute(String[] args) {
ProcessBuilder processBuilder = new ProcessBuilder(args); ProcessBuilder processBuilder = new ProcessBuilder(args);
processBuilder.redirectErrorStream(true); //错误输出流合并到标准输出流中 processBuilder.redirectErrorStream(true); //错误输出流合并到标准输出流中
......
...@@ -5,6 +5,8 @@ import lombok.extern.slf4j.Slf4j; ...@@ -5,6 +5,8 @@ import lombok.extern.slf4j.Slf4j;
import okhttp3.*; import okhttp3.*;
import okio.BufferedSink; import okio.BufferedSink;
import okio.Okio; import okio.Okio;
import org.apache.commons.lang3.exception.ExceptionUtils;
import org.jetbrains.annotations.NotNull;
import java.io.File; import java.io.File;
import java.io.IOException; import java.io.IOException;
...@@ -444,4 +446,30 @@ public class OkHttp3Utils { ...@@ -444,4 +446,30 @@ public class OkHttp3Utils {
} }
return 555; return 555;
} }
public static void backPostAsync(String url) {
Request request = new Request.Builder()
.url(url)
.get()
.build();
client.newCall(request).enqueue(new Callback() {
@Override
public void onFailure(@NotNull Call call, @NotNull IOException e) {
log.info("退出失败");
}
@Override
public void onResponse(@NotNull Call call, @NotNull Response response) throws IOException {
try (ResponseBody body = response.body()){
body.string();
} catch (SocketTimeoutException e) {
log.error("捕获到SocketTimeoutException:{}", e.toString());
client.dispatcher().cancelAll();
client.connectionPool().evictAll();
} catch (Exception e) {
log.error(ExceptionUtils.getStackTrace(e));
}
}
});
}
} }
...@@ -39,4 +39,9 @@ public interface TTSConstants { ...@@ -39,4 +39,9 @@ public interface TTSConstants {
String URL = "https://speech.ainirobot.com/tts/v1/text2audio"; String URL = "https://speech.ainirobot.com/tts/v1/text2audio";
String AUTHORIZATION = "Bearer "; String AUTHORIZATION = "Bearer ";
} }
interface Audio {
String XIAOAI = "XIAOAI";
String XIAODU = "XIAODU";
}
} }
...@@ -16,12 +16,18 @@ import javax.sound.sampled.AudioInputStream; ...@@ -16,12 +16,18 @@ import javax.sound.sampled.AudioInputStream;
import javax.sound.sampled.AudioSystem; import javax.sound.sampled.AudioSystem;
import javax.sound.sampled.UnsupportedAudioFileException; import javax.sound.sampled.UnsupportedAudioFileException;
import java.io.*; import java.io.*;
import java.nio.channels.FileLock;
import java.nio.charset.Charset; import java.nio.charset.Charset;
import java.nio.charset.StandardCharsets; 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.text.Normalizer; import java.text.Normalizer;
import java.util.*; import java.util.*;
import java.util.regex.Matcher; import java.util.regex.Matcher;
import java.util.regex.Pattern; import java.util.regex.Pattern;
import java.util.stream.Collectors;
import java.util.zip.ZipEntry; import java.util.zip.ZipEntry;
import java.util.zip.ZipFile; import java.util.zip.ZipFile;
...@@ -177,6 +183,37 @@ public class TTSUtils { ...@@ -177,6 +183,37 @@ public class TTSUtils {
return true; return true;
} }
public static boolean UploadCallbackUnzip(String toFolder, String zipFilePath) {
try (ZipFile zipFile = new ZipFile(zipFilePath,Charset.forName("GBK"))){
Enumeration<?> entries = zipFile.entries();
boolean first = true;
byte[] buf;
ZipEntry entry;
String targetPath;
while (entries.hasMoreElements()) {
entry = (ZipEntry) entries.nextElement();
if (!entry.isDirectory()) {
targetPath = new StringBuilder(toFolder).append(File.separator).append(entry.getName()).toString();
if (first) {
first = false;
log.info("UploadCallbackUnzip:{} -> {}",zipFilePath,targetPath);
}
Path path = Paths.get(targetPath);
Files.createDirectories(path.getParent());
try (BufferedInputStream is = new BufferedInputStream(zipFile.getInputStream(entry))){
buf = new byte[is.available()];
is.read(buf);
Files.write(path, buf, StandardOpenOption.CREATE, StandardOpenOption.WRITE);
}
}
}
} catch (Exception e) {
log.error("压缩包解压失败:{}", ExceptionUtils.getStackTrace(e));
return false;
}
return true;
}
/** /**
* 删除文件 * 删除文件
* @param path 文件路径 * @param path 文件路径
...@@ -485,19 +522,29 @@ public class TTSUtils { ...@@ -485,19 +522,29 @@ public class TTSUtils {
*/ */
public static void combineMp3File(Collection<String> filePathList, String targetFilepath) public static void combineMp3File(Collection<String> filePathList, String targetFilepath)
throws IOException { throws IOException {
try { // try {
// List<String> filePaths = SampleRateConverter.equalSampleRate(filePathList); //// List<String> filePaths = SampleRateConverter.equalSampleRate(filePathList);
// List<String> filePaths = SampleRateConverter.equalWavData(filePathList); //// List<String> filePaths = SampleRateConverter.equalWavData(filePathList);
List<String> filePaths = SampleRateConverter.equalSampleRateUseFfmepg(filePathList); // List<String> filePaths = SampleRateConverter.equalSampleRateUseFfmepg(filePathList);
if (!CollectionUtils.isEmpty(filePaths)) filePathList = filePaths; // if (!CollectionUtils.isEmpty(filePaths)) filePathList = filePaths;
} catch (Exception e) { // } catch (Exception e) {
log.error("转换采样率出现错误:{}",e); // log.error("转换采样率出现错误:{}",e);
} // }
// ffmpeg -i human1.mp3 -i us1TEMP.mp3 -i us2TEMP.mp3
// -filter_complex "[0:a:0] [1:a:0] [2:a:0] concat=n=3:v=0:a=1 [a]" -map "[a]" result2.mp3
// String command = "sox "+ StringUtils.join(filePathList, " "); // String command = "sox "+ StringUtils.join(filePathList, " ");
filePathList.add(targetFilepath); List<String> str = filePathList.stream().map(s -> "-i "+s).collect(Collectors.toList());
CallPython.execute("sox "+ StringUtils.join(filePathList, " ")); StringBuilder builder = new StringBuilder("ffmpeg ").append(StringUtils.join(str, " ")).append(" -filter_complex ");
for (int i = 0; i < filePathList.size(); i++) {
builder.append("[").append(i).append(":a:0]");
}
builder.append("concat=n=").append(filePathList.size()).append(":v=0:a=1[a] -map [a] ").append(targetFilepath);
CallPython.ffmpegExecute(builder.toString());
// filePathList.add(targetFilepath);
// CallPython.execute("sox "+ StringUtils.join(filePathList, " "));
// try (BufferedOutputStream outputStream = new BufferedOutputStream(new FileOutputStream(new File(targetFilepath), true))){ // try (BufferedOutputStream outputStream = new BufferedOutputStream(new FileOutputStream(new File(targetFilepath), true))){
// AudioEnumeration<InputStream> audioEnumeration = new AudioEnumeration<>(); // AudioEnumeration<InputStream> audioEnumeration = new AudioEnumeration<>();
...@@ -517,16 +564,16 @@ public class TTSUtils { ...@@ -517,16 +564,16 @@ public class TTSUtils {
// outputStream.flush(); // outputStream.flush();
// sequenceInputStream.close(); // sequenceInputStream.close();
// } // }
final List<String> check = new ArrayList<>(filePathList); // final List<String> check = new ArrayList<>(filePathList);
TTService.POOL.submit(() -> { // TTService.POOL.submit(() -> {
for (String path: check) { // for (String path: check) {
if (StringUtils.endsWith(path, SampleRateConverter.SUFFIX_MP3)) { // if (StringUtils.endsWith(path, SampleRateConverter.SUFFIX_MP3)) {
if (!new File(path).delete()) log.error("删除采样率mp3出错:{}",path); // if (!new File(path).delete()) log.error("删除采样率mp3出错:{}",path);
// String wavTempPath = path.substring(0, path.length()-8)+SampleRateConverter.SUFFIX_WAV; //// String wavTempPath = path.substring(0, path.length()-8)+SampleRateConverter.SUFFIX_WAV;
// if (!new File(wavTempPath).delete()) log.error("删除采样率wav出错:{}",wavTempPath); //// if (!new File(wavTempPath).delete()) log.error("删除采样率wav出错:{}",wavTempPath);
} // }
} // }
}); // });
} }
/** /**
...@@ -609,12 +656,6 @@ public class TTSUtils { ...@@ -609,12 +656,6 @@ public class TTSUtils {
} }
public static void main(String[] args) throws IOException, UnsupportedAudioFileException { public static void main(String[] args) throws IOException, UnsupportedAudioFileException {
List<String> list = new ArrayList<>(); UploadCallbackUnzip("/home/yf01/下载/tts/testzip","/home/yf01/下载/testUnzip.zip");
list.add("/home/yf01/下载/tts/1.wav");
list.add("/home/yf01/下载/tts/2.wav");
list.add("/home/yf01/下载/tts/3.wav");
list.add("/home/yf01/下载/tts/4.wav");
//mergeWav(list, "/home/yf01/下载/tts/combine.wav");
System.out.println(System.currentTimeMillis());
} }
} }
...@@ -12,7 +12,10 @@ import org.apache.commons.lang3.exception.ExceptionUtils; ...@@ -12,7 +12,10 @@ import org.apache.commons.lang3.exception.ExceptionUtils;
import javax.servlet.http.HttpServletResponse; import javax.servlet.http.HttpServletResponse;
import java.io.*; import java.io.*;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List; import java.util.List;
import java.util.concurrent.atomic.AtomicInteger;
/** /**
* 响应构建类 * 响应构建类
...@@ -22,6 +25,8 @@ import java.util.List; ...@@ -22,6 +25,8 @@ import java.util.List;
@Slf4j @Slf4j
public class TTServiceUtil { public class TTServiceUtil {
private static final Integer MP3_BOUND = 50*1024;
/** /**
* 构建删除缓存接口的响应信息 * 构建删除缓存接口的响应信息
* @param response HttpServletResponse对象 * @param response HttpServletResponse对象
...@@ -50,7 +55,7 @@ public class TTServiceUtil { ...@@ -50,7 +55,7 @@ public class TTServiceUtil {
* @param fileType 是否下载 * @param fileType 是否下载
*/ */
public static void buildMp3Response(HttpServletResponse response, MP3Response mp3Response, public static void buildMp3Response(HttpServletResponse response, MP3Response mp3Response,
String fileName, int status, boolean fileType) { String fileName, int status, boolean fileType, String xiaoaiCount) {
response.setStatus(status); response.setStatus(status);
if (mp3Response != null) { if (mp3Response != null) {
String ttsResJsonStr = JSON.toJSONString(mp3Response); String ttsResJsonStr = JSON.toJSONString(mp3Response);
...@@ -68,8 +73,11 @@ public class TTServiceUtil { ...@@ -68,8 +73,11 @@ public class TTServiceUtil {
response.reset(); response.reset();
response.setContentType("audio/mp3"); response.setContentType("audio/mp3");
response.setHeader("Content-Type", "audio/mp3"); response.setHeader("Content-Type", "audio/mp3");
response.setHeader("Content-Length", String.valueOf(inputStream.available())); int length = inputStream.available();
response.setHeader("Cache-Control", "max-age=43200, public"); if (StringUtils.isBlank(xiaoaiCount)) {
response.setHeader("Content-Length", String.valueOf(length));
response.setHeader("Cache-Control", "max-age=43200, public");
}
if (fileType) { if (fileType) {
String loadName = fileName.substring(fileName.lastIndexOf("/")+1).trim(); String loadName = fileName.substring(fileName.lastIndexOf("/")+1).trim();
if (StringUtils.isBlank(loadName)) { if (StringUtils.isBlank(loadName)) {
...@@ -78,6 +86,33 @@ public class TTServiceUtil { ...@@ -78,6 +86,33 @@ public class TTServiceUtil {
String value = String.format("attachment;filename=\"%s\"", loadName); String value = String.format("attachment;filename=\"%s\"", loadName);
response.setHeader("Content-Disposition", value); response.setHeader("Content-Disposition", value);
} }
// if (StringUtils.isNotBlank(xiaoaiCount) && length >= MP3_BOUND) {
// byte[] buffer = new byte[1024];
// if (xiaoaiCount.equals(File.separator)) {
// for (int i = 0; i < 85; i++) {
// int ln = inputStream.read(buffer);
// if (ln == -1) break;
// out.write(buffer, 0, ln);
// }
// log.error("");
// out.flush();
// } else {
//// int begin = Integer.parseInt(xiaoaiCount.substring(0,xiaoaiCount.length()-1));
//// inputStream.read(new byte[begin]);
// int ln;
// while ((ln = inputStream.read(buffer)) != -1) {
// out.write(buffer, 0, ln);
// }
// out.flush();
// }
// } else {
// byte[] buffer = new byte[1024];
// int ln;
// while ((ln = inputStream.read(buffer)) != -1) {
// out.write(buffer, 0, ln);
// }
// out.flush();
// }
byte[] buffer = new byte[1024]; byte[] buffer = new byte[1024];
int ln; int ln;
while ((ln = inputStream.read(buffer)) != -1) { while ((ln = inputStream.read(buffer)) != -1) {
...@@ -92,6 +127,55 @@ public class TTServiceUtil { ...@@ -92,6 +127,55 @@ public class TTServiceUtil {
} }
} }
public static void buildMp3ResponseForAudio(HttpServletResponse response, String fileName, Boolean xiaoai, String range) {
response.setStatus(200);
try (BufferedInputStream inputStream = new BufferedInputStream(new FileInputStream(fileName));
OutputStream out = new BufferedOutputStream(response.getOutputStream())){
response.reset();
response.setContentType("audio/mp3");
// response.setHeader("Content-Type", "audio/mp3");
response.setHeader("Content-Type", "application/octet-stream");
int length = inputStream.available();
// if (!Boolean.TRUE.equals(xiaoai)) {
// response.setHeader("Content-Length", String.valueOf(length));
// }
response.setHeader("Content-Length", String.valueOf(length));
range = range.substring(range.indexOf("=")+1, range.indexOf("-"));
String contentRange = "bytes "+range+"-"+length+"/"+length;
log.info("Content-Range:"+contentRange);
response.setHeader("Content-Range", contentRange);
response.setHeader("Accept-Ranges", "bytes");
response.setHeader("icy-metaint", "8192");
// response.setHeader("Cache-Control", "max-age=43200, public");
int begin = Integer.valueOf(range);
byte[] buffer = new byte[1024];
int ln;
while ((ln = inputStream.read(buffer)) != -1) {
if (begin > 0) {
begin -= ln;
if (begin < 0) {
out.write(buffer, ln+begin, -begin);
}
} else {
out.write(buffer, 0, ln);
}
}
out.flush();
// byte[] buffer = new byte[1024];
// int ln;
// while ((ln = inputStream.read(buffer)) != -1) {
// out.write(buffer, 0, ln);
// }
// out.flush();
} catch (ClientAbortException e) {
} catch (IOException e) {
log.error("buildMp3Response:写入音频流到HttpServletResponse失败:{}", e.toString());
}
}
/** /**
* 构建tts_ls接口请求的响应信息 * 构建tts_ls接口请求的响应信息
* @param servletResponse HttpServletResponse对象 * @param servletResponse HttpServletResponse对象
......
package ai.qiwu.com.tts_service.common;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.servlet.config.annotation.ResourceHandlerRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurationSupport;
/**
* @author 苗权威
* @dateTime 19-12-26 下午9:02
*/
@Configuration
public class WebMvcConfig extends WebMvcConfigurationSupport {
@Override
protected void addResourceHandlers(ResourceHandlerRegistry registry) {
registry.addResourceHandler("/static/**").addResourceLocations("file:/root/TTS-service/audio/");
}
}
...@@ -3,14 +3,6 @@ package ai.qiwu.com.tts_service.common.sound; ...@@ -3,14 +3,6 @@ package ai.qiwu.com.tts_service.common.sound;
import ai.qiwu.com.tts_service.common.CallPython; import ai.qiwu.com.tts_service.common.CallPython;
import ai.qiwu.com.tts_service.service.TTService; import ai.qiwu.com.tts_service.service.TTService;
import lombok.extern.slf4j.Slf4j; import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.apache.commons.lang3.exception.ExceptionUtils;
import org.jaudiotagger.audio.exceptions.InvalidAudioFrameException;
import org.jaudiotagger.audio.exceptions.ReadOnlyFileException;
import org.jaudiotagger.audio.mp3.MP3AudioHeader;
import org.jaudiotagger.audio.mp3.MP3File;
import org.jaudiotagger.tag.TagException;
import ws.schild.jave.*;
import javax.sound.sampled.*; import javax.sound.sampled.*;
import java.io.File; import java.io.File;
...@@ -38,41 +30,41 @@ public class SampleRateConverter { ...@@ -38,41 +30,41 @@ public class SampleRateConverter {
public static final String SUFFIX_MP3 = "TEMP.mp3"; public static final String SUFFIX_MP3 = "TEMP.mp3";
private static final String WAV_SUFFIX = ".wav"; private static final String WAV_SUFFIX = ".wav";
public static List<String> equalSampleRate(Collection<String> pathList) throws IOException, UnsupportedAudioFileException, InvalidAudioFrameException, TagException, ReadOnlyFileException { public static List<String> equalSampleRate(Collection<String> pathList) throws IOException, UnsupportedAudioFileException{
float mouldSampleRate = 0; float mouldSampleRate = 0;
List<String> changedRateList = new ArrayList<>(); List<String> changedRateList = new ArrayList<>();
boolean first = true; boolean first = true;
for (String path: pathList) { for (String path: pathList) {
if (first) { if (first) {
File file = new File(path); File file = new File(path);
mouldSampleRate = getMp3FileSampleRate(file); // mouldSampleRate = getMp3FileSampleRate(file);
// log.warn("root采样率{}",mouldSampleRate); // log.warn("root采样率{}",mouldSampleRate);
changedRateList.add(path); changedRateList.add(path);
first = false; first = false;
continue; continue;
} }
float num = getMp3FileSampleRate(new File(path)); // float num = getMp3FileSampleRate(new File(path));
// log.warn("{}:采样率:{}", path, num); // log.warn("{}:采样率:{}", path, num);
if (mouldSampleRate != num) { // if (mouldSampleRate != num) {
// log.warn("{} different",path); //// log.warn("{} different",path);
int spot = path.lastIndexOf("."); // int spot = path.lastIndexOf(".");
String prefix = path.substring(0, spot); // String prefix = path.substring(0, spot);
path = prefix+WAV_SUFFIX; // path = prefix+WAV_SUFFIX;
if (!new File(path).exists()) { // if (!new File(path).exists()) {
log.error("{}不存在",path); // log.error("{}不存在",path);
return null; // return null;
} // }
String tempMp3Path = changeSampleRate(new File(path), prefix, mouldSampleRate); // String tempMp3Path = changeSampleRate(new File(path), prefix, mouldSampleRate);
if (StringUtils.isBlank(tempMp3Path)) return null; // if (StringUtils.isBlank(tempMp3Path)) return null;
changedRateList.add(tempMp3Path); // changedRateList.add(tempMp3Path);
} else { // } else {
changedRateList.add(path); // changedRateList.add(path);
} // }
} }
return changedRateList; return changedRateList;
} }
public static List<String> equalWavData(Collection<String> pathList) throws IOException, UnsupportedAudioFileException, InvalidAudioFrameException, TagException, ReadOnlyFileException { public static List<String> equalWavData(Collection<String> pathList) throws IOException, UnsupportedAudioFileException{
int mouldSampleRate = 0; int mouldSampleRate = 0;
int channel = 1; int channel = 1;
List<String> changedRateList = new ArrayList<>(); List<String> changedRateList = new ArrayList<>();
...@@ -80,110 +72,114 @@ public class SampleRateConverter { ...@@ -80,110 +72,114 @@ public class SampleRateConverter {
for (String path: pathList) { for (String path: pathList) {
if (first) { if (first) {
File file = new File(path); File file = new File(path);
mouldSampleRate = getMp3FileSampleRate(file); // mouldSampleRate = getMp3FileSampleRate(file);
channel = getMp3FileChannel(file); // channel = getMp3FileChannel(file);
// log.warn("root采样率{}",mouldSampleRate); // log.warn("root采样率{}",mouldSampleRate);
changedRateList.add(path); changedRateList.add(path);
first = false; first = false;
continue; continue;
} }
// log.warn("{}:采样率:{}", path, num); // log.warn("{}:采样率:{}", path, num);
if (mouldSampleRate != getMp3FileSampleRate(new File(path))) { // if (mouldSampleRate != getMp3FileSampleRate(new File(path))) {
// log.warn("{} different",path); //// log.warn("{} different",path);
int spot = path.lastIndexOf("."); // int spot = path.lastIndexOf(".");
String prefix = path.substring(0, spot); // String prefix = path.substring(0, spot);
path = prefix+WAV_SUFFIX; // path = prefix+WAV_SUFFIX;
String targetWavPath = prefix+SUFFIX_WAV; // String targetWavPath = prefix+SUFFIX_WAV;
if (!new File(path).exists()) { // if (!new File(path).exists()) {
log.error("{}不存在",path); // log.error("{}不存在",path);
return null; // return null;
} // }
AudioConverter.changeWavData(new File(path), targetWavPath, mouldSampleRate, channel); // AudioConverter.changeWavData(new File(path), targetWavPath, mouldSampleRate, channel);
String tempMp3Path = CallPython.wav2Mp3(targetWavPath, prefix+SUFFIX_MP3); // String tempMp3Path = CallPython.wav2Mp3(targetWavPath, prefix+SUFFIX_MP3);
if (tempMp3Path == null) return null; // if (tempMp3Path == null) return null;
changedRateList.add(tempMp3Path); // changedRateList.add(tempMp3Path);
} else { // } else {
changedRateList.add(path); // changedRateList.add(path);
} // }
}
return changedRateList;
}
public static List<String> equalSampleRateUseFfmepg(Collection<String> pathList) throws EncoderException {
int mouldSampleRate = 0;
int channel = 1;
// long bitRate = 0;
List<String> changedRateList = new ArrayList<>();
boolean first = true;
int i = -1;
List<Future> futureList = new ArrayList<>();
for (String path: pathList) {
i++;
final MultimediaObject sourceObject = new MultimediaObject(new File(path));
final AudioInfo audioInfo = sourceObject.getInfo().getAudio();
if (first) {
mouldSampleRate = audioInfo.getSamplingRate();
channel = audioInfo.getChannels();
changedRateList.add(path);
first = false;
continue;
}
if (mouldSampleRate != audioInfo.getSamplingRate()) {
// log.warn("{} different",path);
final Integer index = i;
final Integer sr = mouldSampleRate;
final Integer cl = channel;
Future future = TTService.POOL.submit(() -> {
try {
String tempMp3Path = path.substring(0, path.lastIndexOf("."))+SUFFIX_MP3;
ffmepg(sourceObject, audioInfo, tempMp3Path, sr,cl);
changedRateList.add(index,tempMp3Path);
} catch (Exception e) {
throw new RuntimeException(e);
}
});
futureList.add(future);
} else {
changedRateList.add(i, path);
}
}
for (Future future: futureList) {
try {
future.get(6, TimeUnit.SECONDS);
} catch (InterruptedException | ExecutionException | TimeoutException e) {
log.error("ffmpeg error:{}", ExceptionUtils.getStackTrace(e));
return null;
}
} }
return changedRateList; return changedRateList;
} }
private static void ffmepg(MultimediaObject sourceObject,AudioInfo audioInfo,String target, int sampleRate, int channel) throws EncoderException { // public static List<String> equalSampleRateUseFfmepg(Collection<String> pathList) throws EncoderException {
AudioAttributes audio = new AudioAttributes(); // int mouldSampleRate = 0;
audio.setCodec("libmp3lame"); // int channel = 1;
audio.setBitRate(audioInfo.getBitRate()); // int bitRate = 0;
audio.setChannels(channel); //
audio.setSamplingRate(sampleRate); // List<String> changedRateList = new ArrayList<>();
EncodingAttributes attrs = new EncodingAttributes(); // boolean first = true;
attrs.setFormat("mp3"); // int i = -1;
attrs.setAudioAttributes(audio); // List<Future> futureList = new ArrayList<>();
Encoder encoder = new Encoder(); // for (String path: pathList) {
encoder.encode(sourceObject, new File(target), attrs); // i++;
} // final MultimediaObject sourceObject = new MultimediaObject(new File(path));
// final AudioInfo audioInfo = sourceObject.getInfo().getAudio();
private static int getMp3FileSampleRate(File file) throws ReadOnlyFileException, TagException, InvalidAudioFrameException, IOException { // if (first) {
MP3File mp3File = new MP3File(file); // mouldSampleRate = audioInfo.getSamplingRate();
return mp3File.getMP3AudioHeader().getSampleRateAsNumber(); // channel = audioInfo.getChannels();
} // bitRate = audioInfo.getBitRate();
// changedRateList.add(path);
private static int getMp3FileChannel(File file) throws ReadOnlyFileException, TagException, InvalidAudioFrameException, IOException { // first = false;
MP3File mp3File = new MP3File(file); // continue;
String mode = mp3File.getMP3AudioHeader().getChannels(); // }
if (StringUtils.containsIgnoreCase(mode, "Stereo")) return 2; //
return 1; // if (mouldSampleRate != audioInfo.getSamplingRate() || channel != audioInfo.getChannels() || bitRate != audioInfo.getBitRate()) {
} //// log.warn("{} different",path);
// final Integer index = i;
// final Integer sr = mouldSampleRate;
// final Integer cl = channel;
// final Integer br = bitRate;
// Future future = TTService.POOL.submit(() -> {
// try {
// String tempMp3Path = path.substring(0, path.lastIndexOf("."))+SUFFIX_MP3;
// ffmepg(sourceObject, audioInfo, tempMp3Path, sr,cl,br);
// changedRateList.add(index,tempMp3Path);
// } catch (Exception e) {
// throw new RuntimeException(e);
// }
// });
// futureList.add(future);
// } else {
// changedRateList.add(i, path);
// }
// }
// for (Future future: futureList) {
// try {
// future.get(6, TimeUnit.SECONDS);
// } catch (InterruptedException | ExecutionException | TimeoutException e) {
// log.error("ffmpeg error:{}", ExceptionUtils.getStackTrace(e));
// return null;
// }
// }
// return changedRateList;
// }
//
// private static void ffmepg(MultimediaObject sourceObject,AudioInfo audioInfo,String target, int sampleRate, int channel, int bitrate) throws EncoderException {
// AudioAttributes audio = new AudioAttributes();
// audio.setCodec("libmp3lame");
//// audio.setBitRate(audioInfo.getBitRate());
// System.out.println("bitrate"+bitrate);
// audio.setBitRate(bitrate);
// audio.setChannels(channel);
// audio.setSamplingRate(sampleRate);
// EncodingAttributes attrs = new EncodingAttributes();
// attrs.setFormat("mp3");
// attrs.setAudioAttributes(audio);
// Encoder encoder = new Encoder();
// encoder.encode(sourceObject, new File(target), attrs);
// }
//
// private static int getMp3FileSampleRate(File file) throws ReadOnlyFileException, TagException, InvalidAudioFrameException, IOException {
// MP3File mp3File = new MP3File(file);
// return mp3File.getMP3AudioHeader().getSampleRateAsNumber();
// }
//
// private static int getMp3FileChannel(File file) throws ReadOnlyFileException, TagException, InvalidAudioFrameException, IOException {
// MP3File mp3File = new MP3File(file);
// String mode = mp3File.getMP3AudioHeader().getChannels();
// if (StringUtils.containsIgnoreCase(mode, "Stereo")) return 2;
// return 1;
// }
private static String changeSampleRate(File sourceFile, String targetPath, float fTargetSampleRate) throws IOException, UnsupportedAudioFileException { private static String changeSampleRate(File sourceFile, String targetPath, float fTargetSampleRate) throws IOException, UnsupportedAudioFileException {
AudioFileFormat sourceFileFormat = AudioSystem.getAudioFileFormat(sourceFile); AudioFileFormat sourceFileFormat = AudioSystem.getAudioFileFormat(sourceFile);
......
...@@ -135,8 +135,9 @@ public class TTSController { ...@@ -135,8 +135,9 @@ public class TTSController {
*/ */
@GetMapping("/api/tts/get_audio") @GetMapping("/api/tts/get_audio")
public void mp3(@RequestParam(required = false) String dirs, @RequestParam(required = false) String filename, public void mp3(@RequestParam(required = false) String dirs, @RequestParam(required = false) String filename,
@RequestParam(required = false) String _type, HttpServletResponse response) { @RequestParam(required = false) String _type, @RequestParam(required = false) String xiaoai,
ttService.mp3(dirs, filename, _type, response); HttpServletResponse response) {
ttService.mp3(dirs, filename, _type, response,xiaoai);
} }
// @PostMapping("/api/chatbot") // @PostMapping("/api/chatbot")
...@@ -228,4 +229,14 @@ public class TTSController { ...@@ -228,4 +229,14 @@ public class TTSController {
if ("miao".equals(secret)) lieHuSchedule.scheduleLieHuToken(); if ("miao".equals(secret)) lieHuSchedule.scheduleLieHuToken();
} }
@PostMapping("/api/audio")
public String apiAudio(@RequestBody ApiAudioData data) {
return ttService.apiAudio(data);
}
@GetMapping("/api/audio/get")
public void apiAudioGet(@RequestParam(required = false) String type, @RequestParam String path,
HttpServletResponse response, HttpServletRequest request) {
ttService.apiAudioGet(type, path, response, request);
}
} }
package ai.qiwu.com.tts_service.pojo;
import com.fasterxml.jackson.annotation.JsonIgnoreProperties;
import lombok.Getter;
import lombok.Setter;
import lombok.ToString;
import java.util.List;
/**
* @author 苗权威
* @dateTime 19-12-13 上午11:11
*/
@Getter
@Setter
@ToString
@JsonIgnoreProperties(ignoreUnknown = true)
public class ApiAudioData {
private String aipioneerUsername;
private List<Dialog> dialogs;
}
package ai.qiwu.com.tts_service.pojo;
import lombok.Getter;
import lombok.Setter;
/**
* @author 苗权威
* @dateTime 19-12-13 下午1:08
*/
@Getter
@Setter
public class AudioBoxData {
private volatile long timestamp;
private volatile String path;
}
package ai.qiwu.com.tts_service.pojo;
import lombok.Getter;
import lombok.Setter;
import lombok.ToString;
/**
* @author 苗权威
* @dateTime 19-12-13 上午11:12
*/
@Getter
@Setter
@ToString
public class Dialog {
private String botAccount;
private String npcName;
private String person;
private String text;
private String tone;
private String pitch;
private String speed;
private String volume;
}
...@@ -24,49 +24,49 @@ public class Initialize implements InitializingBean { ...@@ -24,49 +24,49 @@ public class Initialize implements InitializingBean {
/** /**
* 默认person * 默认person
*/ */
private static String init_person = "B05"; private static volatile String init_person = "B05";
/** /**
* 默认情绪 * 默认情绪
*/ */
private String init_tone = "正常"; private volatile String init_tone = "正常";
/** /**
* 默认请求地址 * 默认请求地址
*/ */
private String init_url; // 一定是线上url private volatile String init_url; // 一定是线上url
/** /**
* 线上请求地址列表 * 线上请求地址列表
*/ */
private static final List<String> URL_LS; //线上地址列表 private static volatile List<String> URL_LS; //线上地址列表
/** /**
* 存储数据结构: person -> (name,sex,mood[],third_party) * 存储数据结构: person -> (name,sex,mood[],third_party)
*/ */
private static final Map<String, PersonInfo> PERSON_INFO_ONLINE; //speakers_online private static volatile Map<String, PersonInfo> PERSON_INFO_ONLINE; //speakers_online
/** /**
* 存储数据结构: person_offline -> (name,sex,mood[],third_party) * 存储数据结构: person_offline -> (name,sex,mood[],third_party)
*/ */
private static final Map<String, PersonInfo> PERSON_INFO_OFFLINE; //speakers_offline private static volatile Map<String, PersonInfo> PERSON_INFO_OFFLINE; //speakers_offline
/** /**
* 存储数据结构: * 存储数据结构:
* person -> [mood -> url] * person -> [mood -> url]
* person_offline -> [mood -> url] * person_offline -> [mood -> url]
*/ */
private static final Map<String, Map<String, String>> PERSON_MOODURL; //api private static volatile Map<String, Map<String, String>> PERSON_MOODURL; //api
/** /**
* 存储数据结构: * 存储数据结构:
* person_offline -> [mood -> jumpId] * person_offline -> [mood -> jumpId]
*/ */
private static final Map<String, Map<String, Integer>> OFFLINE_2_ONLINE; private static volatile Map<String, Map<String, Integer>> OFFLINE_2_ONLINE;
/** /**
* 第三方person列表 * 第三方person列表
*/ */
private static final List<String> THIRD_PARTY_TTS; private static volatile List<String> THIRD_PARTY_TTS;
/** /**
* 第三方person及其角色识别标识 * 第三方person及其角色识别标识
...@@ -77,12 +77,12 @@ public class Initialize implements InitializingBean { ...@@ -77,12 +77,12 @@ public class Initialize implements InitializingBean {
* 存储数据结构: * 存储数据结构:
* id -> 线上url * id -> 线上url
*/ */
private static final Map<Integer, String> ONLINE_ID_2_URL; private static volatile Map<Integer, String> ONLINE_ID_2_URL;
/** /**
* 线上url -> (person,mood) * 线上url -> (person,mood)
*/ */
private static final Map<String, List<String>> URL_2_PERSON_TON; private static volatile Map<String, List<String>> URL_2_PERSON_TON;
/** /**
* 服务器标识 * 服务器标识
...@@ -269,6 +269,95 @@ public class Initialize implements InitializingBean { ...@@ -269,6 +269,95 @@ public class Initialize implements InitializingBean {
// log.info("PERSON_MODELURL:{}", PERSON_MOODURL); // log.info("PERSON_MODELURL:{}", PERSON_MOODURL);
} }
void updateCache() {
Map<String, PersonInfo> PERSON_INFO_ONLINE_TEMP = new HashMap<>();
List<String> THIRD_PARTY_TTS_TEMP = new ArrayList<>();
List<String> URL_LS_TEMP = new ArrayList<>();
Map<Integer, String> ONLINE_ID_2_URL_TEMP = new HashMap<>();
Map<String, List<String>> URL_2_PERSON_TON_TEMP = new HashMap<>();
Map<String, Map<String, String>> PERSON_MOODURL_TEMP = new HashMap<>();
Map<String, PersonInfo> PERSON_INFO_OFFLINE_TEMP = new HashMap<>();
Map<String, Map<String, Integer>> OFFLINE_2_ONLINE_TEMP = new HashMap<>();
List<SpeakersInfo> speakerInfos = speakerInfoRepository.findByIsDelete("0");
for (SpeakersInfo speakerInfo: speakerInfos) {
refreshData(speakerInfo, PERSON_INFO_ONLINE_TEMP, THIRD_PARTY_TTS_TEMP, URL_LS_TEMP, ONLINE_ID_2_URL_TEMP,
URL_2_PERSON_TON_TEMP,PERSON_MOODURL_TEMP, PERSON_INFO_OFFLINE_TEMP, OFFLINE_2_ONLINE_TEMP);
}
PERSON_INFO_ONLINE = PERSON_INFO_ONLINE_TEMP;
THIRD_PARTY_TTS = THIRD_PARTY_TTS_TEMP;
URL_LS = URL_LS_TEMP;
ONLINE_ID_2_URL = ONLINE_ID_2_URL_TEMP;
URL_2_PERSON_TON = URL_2_PERSON_TON_TEMP;
PERSON_MOODURL = PERSON_MOODURL_TEMP;
PERSON_INFO_OFFLINE = PERSON_INFO_OFFLINE_TEMP;
OFFLINE_2_ONLINE = OFFLINE_2_ONLINE_TEMP;
// 若B05不在线上,则从线上中选择一person值替代
if (!PERSON_INFO_ONLINE.containsKey(init_person)) {
for (String person : PERSON_INFO_ONLINE.keySet()) {
if (!THIRD_PARTY_TTS.contains(person)) {
init_person = person;
break;
}
}
}
// 若情绪默认值“正常”不在默认person的情绪列表中,则更换;确保init_person 与 init_toon 之间是有联系的
List<String> moodList = PERSON_INFO_ONLINE.get(init_person).getMood();
if (!moodList.contains(init_tone)) {
init_tone = moodList.get(0);
}
// 获取默认请求地址
init_url = PERSON_MOODURL.get(init_person).get(init_tone);
}
private void refreshData(SpeakersInfo speakerInfo,Map<String, PersonInfo> PERSON_INFO_ONLINE, List<String> THIRD_PARTY_TTS,
List<String> URL_LS, Map<Integer, String> ONLINE_ID_2_URL, Map<String, List<String>> URL_2_PERSON_TON,
Map<String, Map<String, String>> PERSON_MOODURL, Map<String, PersonInfo> PERSON_INFO_OFFLINE, Map<String,
Map<String, Integer>> OFFLINE_2_ONLINE) {
final String name = speakerInfo.getName();
final String sex = speakerInfo.getSex();
String mood = speakerInfo.getMood();
Integer jump = speakerInfo.getJump();
Integer withOnLine = speakerInfo.getWithOnline();
String person = speakerInfo.getPerson();
String person_offline = person+"_offline";
// modelname为空则说明是第三方请求,将该条记录信息保存,并标识其为第三方,并加入第三方列表中
if (StringUtils.isBlank(speakerInfo.getModelName())) {
PersonInfo third = PERSON_INFO_ONLINE.computeIfAbsent(person, k -> new PersonInfo(name, sex));
third.setThird_party(true);
third.getMood().add(mood);
THIRD_PARTY_TTS.add(person);
return;
}
// withonline不为0则标识该条记录的wav文件在线上服务器存在
if (withOnLine != null && withOnLine != 0) {
String url = String.format("%s:9%03d/synthesize", Initialize.getOnlineServer(withOnLine), speakerInfo.getId());
URL_LS.add(url);
ONLINE_ID_2_URL.put(speakerInfo.getId(), url);
URL_2_PERSON_TON.put(url, Arrays.asList(person,mood));
PersonInfo personInfo_online = PERSON_INFO_ONLINE.computeIfAbsent(person, k -> new PersonInfo(name, sex));
personInfo_online.getMood().add(mood);
Map<String, String> mood_url = PERSON_MOODURL.computeIfAbsent(person, k -> new HashMap<>());
mood_url.put(mood, url);
}
PersonInfo personInfo_offline = PERSON_INFO_OFFLINE.computeIfAbsent(person_offline, k -> new PersonInfo(name, sex));
personInfo_offline.getMood().add(mood);
if (jump != null && !jump.equals(speakerInfo.getId())) {
Map<String, Integer> mood2jumpUrl = OFFLINE_2_ONLINE.computeIfAbsent(person_offline, k -> new HashMap<>());
mood2jumpUrl.put(mood, jump);
}
Map<String, String> mood_url = PERSON_MOODURL.computeIfAbsent(person_offline, k -> new HashMap<>());
mood_url.putIfAbsent(mood, String.format("%s/synthesize", OFFLINE_SERVER));
}
public static Map<String, PersonInfo> getPersonInfoOnline() { public static Map<String, PersonInfo> getPersonInfoOnline() {
return PERSON_INFO_ONLINE; return PERSON_INFO_ONLINE;
} }
......
...@@ -40,11 +40,12 @@ public class LieHuSchedule { ...@@ -40,11 +40,12 @@ public class LieHuSchedule {
new Thread(() -> { new Thread(() -> {
int count = 0; int count = 0;
boolean success = false; boolean success = false;
String liehuTokenRes = null;
do { do {
try { try {
// String liehuTokenRes = OkHttp3Utils.doGet(TTSConstants.LIE_HU.TOKEN_URL, LIE_HU_TOKEN_PARAMS, // String liehuTokenRes = OkHttp3Utils.doGet(TTSConstants.LIE_HU.TOKEN_URL, LIE_HU_TOKEN_PARAMS,
// LIE_HU_TOKEN_HEADER); // LIE_HU_TOKEN_HEADER);
String liehuTokenRes = OkHttp3Utils.doGet(TTSConstants.LIE_HU.TOKEN_URL, LIE_HU_TOKEN_PARAMS); liehuTokenRes = OkHttp3Utils.doGet(TTSConstants.LIE_HU.TOKEN_URL, LIE_HU_TOKEN_PARAMS);
if (StringUtils.isBlank(liehuTokenRes)) { if (StringUtils.isBlank(liehuTokenRes)) {
log.error("对猎户Token发起的请求出错"); log.error("对猎户Token发起的请求出错");
return; return;
...@@ -56,18 +57,18 @@ public class LieHuSchedule { ...@@ -56,18 +57,18 @@ public class LieHuSchedule {
return; return;
//log.info("成功获取到猎户Token:{}", LIE_HU_TOKEN); //log.info("成功获取到猎户Token:{}", LIE_HU_TOKEN);
}else { }else {
log.error("第次{}尝试请求猎户Token失败:{}", count+1,response.getError()); log.error("第次{}尝试请求猎户Token失败->{}, errorMsg:{}", count+1, liehuTokenRes,response.getError());
} }
} catch (Exception e) { } catch (Exception e) {
log.error("第次{}尝试获取猎户Token异常:{},", count+1,e.toString()); log.error("第次{}尝试获取猎户Token异常,->{} , errorMsg:{},", count+1,liehuTokenRes,e.toString());
} }
count++; count++;
try { try {
Thread.sleep(2*count); Thread.sleep(5*count);
} catch (Exception e) { } catch (Exception e) {
} }
} while (!success && count < 10); } while (!success && count < 15);
}).start(); }).start();
} }
......
...@@ -9,6 +9,7 @@ import ai.qiwu.com.tts_service.service.baidu.ThirdPartyService; ...@@ -9,6 +9,7 @@ import ai.qiwu.com.tts_service.service.baidu.ThirdPartyService;
import com.alibaba.fastjson.JSON; import com.alibaba.fastjson.JSON;
import com.csvreader.CsvReader; import com.csvreader.CsvReader;
import lombok.extern.slf4j.Slf4j; import lombok.extern.slf4j.Slf4j;
import org.apache.catalina.connector.Response;
import org.apache.commons.csv.CSVFormat; import org.apache.commons.csv.CSVFormat;
import org.apache.commons.csv.CSVParser; import org.apache.commons.csv.CSVParser;
import org.apache.commons.csv.CSVRecord; import org.apache.commons.csv.CSVRecord;
...@@ -16,21 +17,32 @@ import org.apache.commons.lang3.RandomStringUtils; ...@@ -16,21 +17,32 @@ import org.apache.commons.lang3.RandomStringUtils;
import org.apache.commons.lang3.StringUtils; import org.apache.commons.lang3.StringUtils;
import org.apache.commons.lang3.exception.ExceptionUtils; import org.apache.commons.lang3.exception.ExceptionUtils;
import org.springframework.beans.factory.annotation.Autowired; import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service; import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;
import org.springframework.web.multipart.MultipartFile; import org.springframework.web.multipart.MultipartFile;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse; import javax.servlet.http.HttpServletResponse;
import java.io.*; import java.io.*;
import java.net.URLDecoder; import java.net.URLDecoder;
import java.net.URLEncoder; import java.net.URLEncoder;
import java.nio.channels.FileLock;
import java.nio.charset.Charset; import java.nio.charset.Charset;
import java.nio.charset.StandardCharsets;
import java.nio.file.Files; import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.*; import java.util.*;
import java.util.concurrent.*; import java.util.concurrent.*;
import java.util.concurrent.atomic.AtomicInteger; import java.util.concurrent.atomic.AtomicInteger;
import java.util.concurrent.locks.ReentrantLock;
import java.util.regex.Matcher; import java.util.regex.Matcher;
import java.util.regex.Pattern; 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;
/** /**
* @author 苗权威 * @author 苗权威
...@@ -61,6 +73,8 @@ public class TTService { ...@@ -61,6 +73,8 @@ public class TTService {
*/ */
private final String offlineService; private final String offlineService;
public static final HashSet<String> XIAOAI_MP3_MARK = new HashSet<>();
/** /**
* 导入初始化类,构建离线地址 * 导入初始化类,构建离线地址
* @param initialize 初始化类 * @param initialize 初始化类
...@@ -71,6 +85,9 @@ public class TTService { ...@@ -71,6 +85,9 @@ public class TTService {
this.offlineService = String.format("%s/synthesize", Initialize.getOfflineServer()); this.offlineService = String.format("%s/synthesize", Initialize.getOfflineServer());
} }
@Value("${audioUrl}")
private String audioUrl;
// /** // /**
// * 退出请求的处理/返回TTS_test.mp3文件的下载链接 // * 退出请求的处理/返回TTS_test.mp3文件的下载链接
// * @param request // * @param request
...@@ -154,6 +171,31 @@ public class TTService { ...@@ -154,6 +171,31 @@ public class TTService {
TTServiceUtil.buildOnlineCacheResponse(response, new TTSResponse(deleteOfflineResCode), deleteOfflineResCode); TTServiceUtil.buildOnlineCacheResponse(response, new TTSResponse(deleteOfflineResCode), deleteOfflineResCode);
} }
// public void mp3(String dirs, String filename, String _type, HttpServletResponse response, String xiaoai, HttpServletRequest request) {
// if (StringUtils.isNotBlank(xiaoai)) {
// try {
// LOCK.lock();
// Enumeration enumeration = request.getHeaderNames();
// while (enumeration.hasMoreElements()) {
// String name = (String) enumeration.nextElement();
// log.warn(name+":"+request.getHeader(name));
// }
// String range = request.getHeader("range").trim();
// if (!xiaoai.equals(xiaoAiRequestId)) {
// log.warn("==========="+xiaoai);
// xiaoAiRequestId = xiaoai;
// range = File.separator;
//// xiaoAiCount.set(0);
// }
// mp3Temp(dirs, filename, _type, response, range);
// } finally {
// LOCK.unlock();
// }
// } else {
// mp3Temp(dirs, filename, _type, response, null);
// }
// }
/** /**
* 参数dirs与filename指向一个mp3音频文件,返回该文件内容数据 * 参数dirs与filename指向一个mp3音频文件,返回该文件内容数据
* @param dirs mp3音频文件路径 * @param dirs mp3音频文件路径
...@@ -161,7 +203,7 @@ public class TTService { ...@@ -161,7 +203,7 @@ public class TTService {
* @param _type 为file则标识用户是下载请求 * @param _type 为file则标识用户是下载请求
* @param response 响应信息 * @param response 响应信息
*/ */
public void mp3(String dirs, String filename, String _type, HttpServletResponse response) { public void mp3(String dirs, String filename, String _type, HttpServletResponse response, String xiaoaiCount) {
// 修正dirs的格式 // 修正dirs的格式
boolean tmp = false; boolean tmp = false;
if (dirs != null) { if (dirs != null) {
...@@ -169,12 +211,12 @@ public class TTService { ...@@ -169,12 +211,12 @@ public class TTService {
dirs = URLDecoder.decode(dirs, "UTF-8"); dirs = URLDecoder.decode(dirs, "UTF-8");
} catch (UnsupportedEncodingException e) { } catch (UnsupportedEncodingException e) {
log.error("url解码出错:请求目录{},请求文件名:{}",dirs,filename); log.error("url解码出错:请求目录{},请求文件名:{}",dirs,filename);
TTServiceUtil.buildMp3Response(response, new MP3Response(400), null, 400, false); TTServiceUtil.buildMp3Response(response, new MP3Response(400), null, 400, false, null);
return; return;
} }
if ("..".equals(dirs) || StringUtils.startsWith(dirs, "/")) { if ("..".equals(dirs) || StringUtils.startsWith(dirs, "/")) {
TTServiceUtil.buildMp3Response(response, new MP3Response(400, "参数设置有误,不能包含..或是以/开头"), TTServiceUtil.buildMp3Response(response, new MP3Response(400, "参数设置有误,不能包含..或是以/开头"),
null, 400, false); null, 400, false, null);
return; return;
} }
if (StringUtils.startsWith(dirs, "[") && StringUtils.endsWith(dirs, "]")) { if (StringUtils.startsWith(dirs, "[") && StringUtils.endsWith(dirs, "]")) {
...@@ -185,7 +227,7 @@ public class TTService { ...@@ -185,7 +227,7 @@ public class TTService {
} }
if (StringUtils.startsWith(dir_ls.get(0), "/")) { if (StringUtils.startsWith(dir_ls.get(0), "/")) {
TTServiceUtil.buildMp3Response(response, new MP3Response(400, "参数设置有误,参数形式如下[/,..]"), TTServiceUtil.buildMp3Response(response, new MP3Response(400, "参数设置有误,参数形式如下[/,..]"),
null, 400, false); null, 400, false, null);
return; return;
} }
tmp = "tmp".equals(dir_ls.get(0)); tmp = "tmp".equals(dir_ls.get(0));
...@@ -204,10 +246,10 @@ public class TTService { ...@@ -204,10 +246,10 @@ public class TTService {
if (TTSUtils.doesFileExist(filepath)) { if (TTSUtils.doesFileExist(filepath)) {
if ("file".equals(_type)) { if ("file".equals(_type)) {
// 请求头中添加 Content-Disposition = attachment 可下载 // 请求头中添加 Content-Disposition = attachment 可下载
TTServiceUtil.buildMp3Response(response, null, filepath, 200, true); TTServiceUtil.buildMp3Response(response, null, filepath, 200, true, null);
return; return;
} }
TTServiceUtil.buildMp3Response(response, null, filepath, 200, false); TTServiceUtil.buildMp3Response(response, null, filepath, 200, false, xiaoaiCount);
if (tmp) { if (tmp) {
POOL.submit(() -> { POOL.submit(() -> {
if (!new File(filepath).delete()) log.info("删除tmp文件失败:{}",filepath); if (!new File(filepath).delete()) log.info("删除tmp文件失败:{}",filepath);
...@@ -216,7 +258,7 @@ public class TTService { ...@@ -216,7 +258,7 @@ public class TTService {
return; return;
} }
} }
TTServiceUtil.buildMp3Response(response, new MP3Response(400), null, 400, false); TTServiceUtil.buildMp3Response(response, new MP3Response(400), null, 400, false, null);
} }
/** /**
...@@ -336,7 +378,12 @@ public class TTService { ...@@ -336,7 +378,12 @@ public class TTService {
data.setNpcName(npcName); data.setNpcName(npcName);
final String path = filepath; final String path = filepath;
final String moodUrl = url; final String moodUrl = url;
Future<ResponseCodeWithData> future = POOL.submit(() -> generalMP3(moodUrl, data, path, "GET",true)); Future<ResponseCodeWithData> future = POOL.submit(() -> {
// Long start = System.currentTimeMillis();
ResponseCodeWithData response1 = generalMP3(moodUrl, data, path, "GET",true);
// log.info("generalMP3耗时:"+(System.currentTimeMillis()-start));
return response1;
});
futures.add(future); futures.add(future);
} }
...@@ -381,7 +428,7 @@ public class TTService { ...@@ -381,7 +428,7 @@ public class TTService {
ResponseCodeWithData data = future.get(); ResponseCodeWithData data = future.get();
if (data.getCode() != 200) { if (data.getCode() != 200) {
if (data.getCode() == 404) { if (data.getCode() == 404) {
log.info("404,音频没有找到"); log.warn("404,音频没有找到");
}else { }else {
log.error("下载音频失败, status:{}", data.getCode()); log.error("下载音频失败, status:{}", data.getCode());
} }
...@@ -413,7 +460,9 @@ public class TTService { ...@@ -413,7 +460,9 @@ public class TTService {
try { try {
if (!TTSUtils.doesFileExist(tmp_audio_name)) { if (!TTSUtils.doesFileExist(tmp_audio_name)) {
TTSUtils.makedir(folder); TTSUtils.makedir(folder);
// long startTime = System.currentTimeMillis();
TTSUtils.combineMp3File(file_ls, tmp_audio_name); TTSUtils.combineMp3File(file_ls, tmp_audio_name);
// log.info("ffmpeg合并耗时:"+(System.currentTimeMillis()-startTime));
//CallPython.combine(file_ls, tmp_audio_name); //CallPython.combine(file_ls, tmp_audio_name);
} }
if (!TTSUtils.doesFileExist(tmp_audio_name)) { if (!TTSUtils.doesFileExist(tmp_audio_name)) {
...@@ -783,19 +832,25 @@ public class TTService { ...@@ -783,19 +832,25 @@ public class TTService {
*/ */
private ResponseCodeWithData generalMP3(String url, GeneralMP3Data data, String filePath, String requestMethod, private ResponseCodeWithData generalMP3(String url, GeneralMP3Data data, String filePath, String requestMethod,
boolean getOnline) { boolean getOnline) {
//long startTime = System.currentTimeMillis(); // long startTime = System.currentTimeMillis();
ResponseCodeWithData res = null; ResponseCodeWithData res = null;
String wavFilename = filePath.substring(0, filePath.length()-4)+".wav"; String wavFilename = filePath.substring(0, filePath.length()-4)+".wav";
//对于请求参数中带有npcName的,首先判断其是否是分段请求,即检查text中是否包含AB符号 //对于请求参数中带有npcName的,首先判断其是否是分段请求,即检查text中是否包含AB符号
if (StringUtils.isNotBlank(data.getNpcName())) { if (StringUtils.isNotBlank(data.getNpcName())) {
//log.info("777"); //log.info("777");
// long startTime = System.currentTimeMillis();
// boolean result = genRecordWithChange(url, data, filePath, requestMethod, getOnline);
// log.info("分段耗时:"+(System.currentTimeMillis()-startTime));
// if (result) return new ResponseCodeWithData(200);
if (genRecordWithChange(url, data, filePath, requestMethod, getOnline)) return new ResponseCodeWithData(200); if (genRecordWithChange(url, data, filePath, requestMethod, getOnline)) return new ResponseCodeWithData(200);
//log.info("11,11,11"); //log.info("11,11,11");
} }
// 若wav不存在则先下载,通过person来区分是否是第三方 // 若wav不存在则先下载,通过person来区分是否是第三方
if (!TTSUtils.doesFileExist(wavFilename)) { if (!TTSUtils.doesFileExist(wavFilename)) {
if (Initialize.getThirdPartyTts().contains(data.getPerson())) { if (Initialize.getThirdPartyTts().contains(data.getPerson())) {
// long startTime = System.currentTimeMillis();
res = dealThirdParty(data.getText().trim(), data.getPerson(), wavFilename); res = dealThirdParty(data.getText().trim(), data.getPerson(), wavFilename);
// log.info("第三方请求耗时:"+(System.currentTimeMillis()-startTime));
if (res.getCode() != 200) { if (res.getCode() != 200) {
return res; return res;
} }
...@@ -828,16 +883,22 @@ public class TTService { ...@@ -828,16 +883,22 @@ public class TTService {
} else if (!fileExist) { } else if (!fileExist) {
if (offlineService.equals(url)) { if (offlineService.equals(url)) {
data.setFormat("mp3"); data.setFormat("mp3");
// long startTime = System.currentTimeMillis();
res = requestTemplate(url , data, filePath, false, getOnline); res = requestTemplate(url , data, filePath, false, getOnline);
// log.info("线下请求mp3耗时:"+(System.currentTimeMillis()-startTime));
if (res == null || res.getCode() != 200) { if (res == null || res.getCode() != 200) {
log.error("线下请求音频文件:{},失败:{}",filePath, res); log.error("线下请求音频文件:{},失败:{}",filePath, res);
} }
// 若是线上下载mp3文件失败,或是下载了个空文件,则wav转mp3 // 若是线上下载mp3文件失败,或是下载了个空文件,则wav转mp3
if (!TTSUtils.doesFileExist(filePath)) { if (!TTSUtils.doesFileExist(filePath)) {
// long startTime2 = System.currentTimeMillis();
res = changeSound(wavFilename, data.getVolume(), data.getSpeed(), data.getPitch(), filePath); res = changeSound(wavFilename, data.getVolume(), data.getSpeed(), data.getPitch(), filePath);
// log.info("调用python代码耗时:"+(System.currentTimeMillis()-startTime2));
} }
}else { }else {
// long startTime2 = System.currentTimeMillis();
res = changeSound(wavFilename, data.getVolume(), data.getSpeed(), data.getPitch(), filePath); res = changeSound(wavFilename, data.getVolume(), data.getSpeed(), data.getPitch(), filePath);
// log.info("调用python代码耗时:"+(System.currentTimeMillis()-startTime2));
// String executeResult = null; // String executeResult = null;
// try { // try {
// //long changeSoundStartTime = System.currentTimeMillis(); // //long changeSoundStartTime = System.currentTimeMillis();
...@@ -918,6 +979,7 @@ public class TTService { ...@@ -918,6 +979,7 @@ public class TTService {
Initialize.getUploadedDir(), data.getNpcName()}, File.separator); Initialize.getUploadedDir(), data.getNpcName()}, File.separator);
// 非变量部分 // 非变量部分
String[] notVariableTextArray = pattern.split(text); String[] notVariableTextArray = pattern.split(text);
// if (notVariableTextArray.length == 0) return false;
//log.info("notVariableTextArray:{}",Arrays.toString(notVariableTextArray)); //log.info("notVariableTextArray:{}",Arrays.toString(notVariableTextArray));
//boolean notVariableLast = text.indexOf(notVariableTextArray[notVariableTextArray.length-1]) > text.indexOf(variableTextList.get(variableTextList.size()-1)); //boolean notVariableLast = text.indexOf(notVariableTextArray[notVariableTextArray.length-1]) > text.indexOf(variableTextList.get(variableTextList.size()-1));
// 遍历所有非变量,若其mp3文件在人工目录下不存在则返回false回到generalMp3方法,整句合成 // 遍历所有非变量,若其mp3文件在人工目录下不存在则返回false回到generalMp3方法,整句合成
...@@ -958,7 +1020,7 @@ public class TTService { ...@@ -958,7 +1020,7 @@ public class TTService {
if (!TTSUtils.doesFileExist(variableTextPath)) { if (!TTSUtils.doesFileExist(variableTextPath)) {
GeneralMP3Data variableData = new GeneralMP3Data(data.getServer(), variableText,data.getPerson(), GeneralMP3Data variableData = new GeneralMP3Data(data.getServer(), variableText,data.getPerson(),
data.getTone(), data.getBotname(), data.getCache(),data.getVolume(),data.getSpeed(),data.getPitch()); data.getTone(), data.getBotname(), data.getCache(),data.getVolume(),data.getSpeed(),data.getPitch());
String variablePathInUsDir = new StringBuilder(usDir).append(variableTextFilename).toString(); String variablePathInUsDir = new StringBuilder(usDir).append(File.separator).append(variableTextFilename).toString();
ResponseCodeWithData response = generalMP3(url, variableData, variablePathInUsDir, requestMethod, getOnline); ResponseCodeWithData response = generalMP3(url, variableData, variablePathInUsDir, requestMethod, getOnline);
if (response.getCode() != 200) return false; if (response.getCode() != 200) return false;
combineMp3Text2FilePath.put(variableText, variablePathInUsDir); combineMp3Text2FilePath.put(variableText, variablePathInUsDir);
...@@ -973,6 +1035,10 @@ public class TTService { ...@@ -973,6 +1035,10 @@ public class TTService {
// StringBuilder combineRecordPath = new StringBuilder( // StringBuilder combineRecordPath = new StringBuilder(
// personToneFilePath.substring(0, personToneFilePath.lastIndexOf(File.separator))); // personToneFilePath.substring(0, personToneFilePath.lastIndexOf(File.separator)));
TTSUtils.combineMp3File(combineMp3Text2FilePath.values(), personToneFilePath); TTSUtils.combineMp3File(combineMp3Text2FilePath.values(), personToneFilePath);
if (!new File(personToneFilePath).exists()) {
log.error("分段合并音频,未找到合并后的文件");
return false;
}
} catch (Exception e) { } catch (Exception e) {
log.error("genRecordWithChange:合成音频失败:{}",e.toString()); log.error("genRecordWithChange:合成音频失败:{}",e.toString());
return false; return false;
...@@ -1148,17 +1214,19 @@ public class TTService { ...@@ -1148,17 +1214,19 @@ public class TTService {
log.error("第{}次失败,原因{}", i+1, e.toString()); log.error("第{}次失败,原因{}", i+1, e.toString());
continue; continue;
} }
// if (res == null) {
// log.error("requestTemplate请求无法获取到结果,该请求信息是:{}", data.toString());
// return new ResponseCodeWithData(402, "requestTemplate请求无法获取到结果,该请求信息是:"+data.toString());
// }
//log.info("resCode:{}, offlineService:{},url:{}", resCode, offlineService, url);
if (res == null) { if (res == null) {
log.error("requestTemplate请求无法获取到结果,该请求信息是:{}", data.toString()); log.error("requestTemplate请求无法获取到结果,该请求信息是:{}", data.toString());
return new ResponseCodeWithData(402, "requestTemplate请求无法获取到结果,该请求信息是:"+data.toString());
} }
int resCode = res.getCode(); else if (res.getCode() == 200) {
//log.info("resCode:{}, offlineService:{},url:{}", resCode, offlineService, url);
if (resCode == 200) {
return res; return res;
} }
else if (resCode == 404 && url.equals(offlineService)) { else if (res.getCode() == 404 && url.equals(offlineService)) {
// 明确指定是线下请求的则直接返回404 // 明确指定是线下请求的则直接返回404
if (!getOnline) return new ResponseCodeWithData(404, "没有找到该文件"); if (!getOnline) return new ResponseCodeWithData(404, "没有找到该文件");
// 根据person,toon获取其线上地址 // 根据person,toon获取其线上地址
String person = data.getPerson(); String person = data.getPerson();
...@@ -1183,19 +1251,80 @@ public class TTService { ...@@ -1183,19 +1251,80 @@ public class TTService {
res = requestLongTimeout(url, dataStr, new File(filePath)); res = requestLongTimeout(url, dataStr, new File(filePath));
//log.info("requestLongTimeout返回结果:{}",res.getCode()); //log.info("requestLongTimeout返回结果:{}",res.getCode());
} catch (Exception e) { } catch (Exception e) {
log.error("线下跳转线上地址请求发生错误:person:{},mood:{}, 错误信息:{}", person, mood, log.error("线下跳转默认线上地址请求发生错误:person:{},mood:{}, 错误信息:{}", person, mood,
ExceptionUtils.getStackTrace(e)); ExceptionUtils.getStackTrace(e));
res = null; res = null;
} }
break; break;
} }
} }
if (res == null) {
log.error("请求无法获取到结果,该请求信息是:{}", data.toString()); // else if (resCode == 404 && url.equals(offlineService)) {
return new ResponseCodeWithData(402, null); // // 明确指定是线下请求的则直接返回404
// if (!getOnline) return new ResponseCodeWithData(404, "没有找到该文件");
// // 根据person,toon获取其线上地址
// String person = data.getPerson();
// String mood = data.getTone();
// try {
// url = "";
// Map<String, Integer> moodJumpId = initialize.getThePersonJumpId(person);
// if (moodJumpId != null) {
// Integer id;
// if ((id = moodJumpId.get(mood)) != null) url = Initialize.getOnlineId2Url().get(id);
// }
// // 若线上url地址列表不能包含该地址,则将该地址置为默认地址
// if (initialize.doesThisMoodUrlWithOnline0(url)) {
// url = initialize.getInit_url();
// //log.info("requestTemplate方法,init_url:{}",url);
// }
// // 修正data中的person与tone
// List<String> personTon = Initialize.getUrl2PersonTon(url);
// data.setPerson(personTon.get(0));
// data.setTone(personTon.get(1));
// dataStr = JSON.toJSONString(data);
// res = requestLongTimeout(url, dataStr, new File(filePath));
// //log.info("requestLongTimeout返回结果:{}",res.getCode());
// } catch (Exception e) {
// log.error("线下跳转线上地址请求发生错误:person:{},mood:{}, 错误信息:{}", person, mood,
// ExceptionUtils.getStackTrace(e));
// res = null;
// }
// break;
// }
if (res == null || res.getCode() != 200) {
log.warn("请求无法获取到结果,该请求信息是:{}", data.toString());
String person = data.getPerson();
String mood = data.getTone();
try {
url = "";
Map<String, Integer> moodJumpId = initialize.getThePersonJumpId(person);
if (moodJumpId != null) {
Integer id;
if ((id = moodJumpId.get(mood)) != null) url = Initialize.getOnlineId2Url().get(id);
}
// 若线上url地址列表不能包含该地址,则将该地址置为默认地址
if (initialize.doesThisMoodUrlWithOnline0(url)) {
url = initialize.getInit_url();
//log.info("requestTemplate方法,init_url:{}",url);
}
// 修正data中的person与tone
List<String> personTon = Initialize.getUrl2PersonTon(url);
data.setPerson(personTon.get(0));
data.setTone(personTon.get(1));
dataStr = JSON.toJSONString(data);
res = requestLongTimeout(url, dataStr, new File(filePath));
//log.info("requestLongTimeout返回结果:{}",res.getCode());
} catch (Exception e) {
log.error("跳转默认地址请求发生错误:person:{},mood:{}, 错误信息:{}", person, mood,
ExceptionUtils.getStackTrace(e));
res = new ResponseCodeWithData(500, null);
}
} }
if (res.getCode() != 200) {
log.info("请求不成功,该请求信息是:{}", data.toString()); if ((res == null || res.getCode() != 200) && !"mp3".equals(data.getFormat())) {
res = dealThirdParty(data.getText(), "Liehu1", filePath);
} }
return res; return res;
} }
...@@ -1253,7 +1382,7 @@ public class TTService { ...@@ -1253,7 +1382,7 @@ public class TTService {
* @throws Exception * @throws Exception
*/ */
public void updateCache() throws Exception { public void updateCache() throws Exception {
initialize.afterPropertiesSet(); initialize.updateCache();
} }
/** /**
...@@ -1867,7 +1996,7 @@ public class TTService { ...@@ -1867,7 +1996,7 @@ public class TTService {
log.info("upload:{}", filePath); log.info("upload:{}", filePath);
try { try {
file.transferTo(new File(filePath)); file.transferTo(new File(filePath));
if (!TTSUtils.unZip(Initialize.getAudioDir(), filePath)) { if (!TTSUtils.UploadCallbackUnzip(Initialize.getAudioDir(), filePath)) {
POOL.submit(() -> new File(filePath).delete()); POOL.submit(() -> new File(filePath).delete());
TTServiceUtil.buildUploadResponse(response, new TTSResponse(555, "压缩包解压失败"), 555); TTServiceUtil.buildUploadResponse(response, new TTSResponse(555, "压缩包解压失败"), 555);
return; return;
...@@ -1878,10 +2007,288 @@ public class TTService { ...@@ -1878,10 +2007,288 @@ public class TTService {
TTServiceUtil.buildUploadResponse(response, new TTSResponse(555, "程序出错"), 555); TTServiceUtil.buildUploadResponse(response, new TTSResponse(555, "程序出错"), 555);
return; return;
} }
log.info("callback unzip success:{}", filePath);
TTServiceUtil.buildUploadResponse(response, new TTSResponse(200), 200); TTServiceUtil.buildUploadResponse(response, new TTSResponse(200), 200);
} }
public static ThreadPoolExecutor getPOOL() { public static ThreadPoolExecutor getPOOL() {
return POOL; return POOL;
} }
// public void apiAudioGet(String type, String id, HttpServletResponse response) {
// AudioBoxData boxData = null;
// switch (type) {
// case XIAOAI : boxData = XIAOAI_MP3_PATH.get(id);break;
// case XIAODU : boxData = XIAODU_MP3_PATH.get(id);break;
// }
// String path;
// if (boxData != null) {
// if ((path = boxData.getPath()) != null) {
// TTServiceUtil.buildMp3Response(response, null, path, 200, false, null);
// boxData.setPath(null);
// } else {
// try {
// Thread.sleep(2000);
// } catch (Exception e) {}
// if ((path = boxData.getPath()) != null) {
// TTServiceUtil.buildMp3Response(response, null, path, 200, false, null);
// boxData.setPath(null);
// } else {
// log.error("等待2s后仍未获取到音箱的音频结果");
// }
// }
// } else {
// try {
// Thread.sleep(2000);
// } catch (Exception e) {}
// switch (type) {
// case XIAOAI : boxData = XIAOAI_MP3_PATH.get(id);break;
// case XIAODU : boxData = XIAODU_MP3_PATH.get(id);break;
// }
// if (boxData != null && (path = boxData.getPath()) != null) {
// TTServiceUtil.buildMp3Response(response, null, path, 200, false, null);
// boxData.setPath(null);
// } else {
// log.error("等待2s后仍未获取到音箱的音频结果");
// }
// }
// }
// public void apiAudio(ApiAudioData data, String userId) {
// if (StringUtils.isBlank(userId)) {
// log.error("请求头里没有userId");
// return;
// }
// String path = apiAudioTtsLs(data);
// if (StringUtils.isBlank(path)) {
// log.warn("出现错误没有获取到音频");
// return;
// }
// String type = userId.substring(0, userId.indexOf("_"));
// AudioBoxData boxData = null;
// switch (type) {
// case XIAOAI : boxData = XIAOAI_MP3_PATH.computeIfAbsent(userId, s -> new AudioBoxData());break;
// case XIAODU : boxData = XIAODU_MP3_PATH.computeIfAbsent(userId, s -> new AudioBoxData());break;
// }
// if (boxData != null) {
// log.info("写入音频地址成功");
// boxData.setPath(path);
// } else {
// log.warn("音箱userId不对");
// }
// }
public void apiAudioGet(String type, String path, HttpServletResponse response, HttpServletRequest request) {
Path pt;
boolean xiaoAi = StringUtils.isNotBlank(type);
if (xiaoAi) {
OkHttp3Utils.backPostAsync(audioUrl+type);
}
Enumeration enumeration = request.getHeaderNames();
while (enumeration.hasMoreElements()) {
String name = (String) enumeration.nextElement();
log.warn(name+":"+request.getHeader(name));
}
String range = request.getHeader("range");
if (Files.exists((pt = Paths.get(path)))) {
while (XIAOAI_MP3_MARK.contains(path)) {
try {
Thread.sleep(500);
} catch (Exception e) {}
}
TTServiceUtil.buildMp3ResponseForAudio(response, path, xiaoAi,range);
} else {
try {
Thread.sleep(1500);
} catch (Exception e) {}
if (Files.exists(pt)) {
while (XIAOAI_MP3_MARK.contains(path)) {
try {
Thread.sleep(300);
} catch (Exception e) {}
}
TTServiceUtil.buildMp3ResponseForAudio(response, path, xiaoAi,range);
} else {
log.error("等待2s后仍未获取到音箱的音频结果");
}
}
}
public String apiAudio(ApiAudioData apiAudioData) {
List<Dialog> dialogs = apiAudioData.getDialogs();
// botname不能为空
String botName = apiAudioData.getAipioneerUsername();
if (botName == null) botName = "中控";
else if (StringUtils.isBlank(botName)) {
return "null";
}
final List<Future<ResponseCodeWithData>> futures = new ArrayList<>();
final List<String> 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.getInit_person();
//log.info("person:{}", 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) {
// person不存在则置为默认person
if (!initialize.getPersonMoodurl().containsKey(person)) person = initialize.getInit_person();
//log.info("person:{}",person);
// 确保tone值为person的某个已有的情绪值
tone = info.getTone() == null ? initialize.getInit_tone() : info.getTone();
//
Map<String, String> moodUrlMap = initialize.getPersonMoodurl().get(person);
if (!moodUrlMap.containsKey(tone)) tone = initialize.getDefault_tone();
if (!moodUrlMap.containsKey(tone)) {
if (person.equals(initialize.getInit_person())) tone = initialize.getInit_tone();
else tone = moodUrlMap.keySet().iterator().next();
}
// 获取该person的mood的url地址
url = moodUrlMap.get(tone);
//log.info("mood->url:{}", url);
}
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) {
//log.info("333");
// 目录为:(audio_dir)/botname/person/tone
String folder = new StringBuilder(rootFolder).append(person).append(File.separator).append(tone).toString();
//String folder = StringUtils.join(new String[]{Initialize.getAudioDir(), botName, person, tone}, File.separator);
boolean createDirRes = TTSUtils.makedir(folder);
if (!createDirRes) {
log.error("tts_ls创建目录:{}失败",folder);
}
// 生成文件名
filepath = new StringBuilder(folder).append(File.separator).append(fileName).toString();
//log.info("tts_ls方法:filepath:{}", filepath);
}
if (!TTSUtils.doesFileExist(filepath)) {
//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);
final String path = filepath;
final String moodUrl = url;
Future<ResponseCodeWithData> future = POOL.submit(() -> {
// Long start = System.currentTimeMillis();
// log.info("generalMP3耗时:"+(System.currentTimeMillis()-start));
return generalMP3(moodUrl, data, path, "GET",true);
});
futures.add(future);
}
// _type为filename的请求都将返回文件名列表
// xiaoai 平台的,返回如下:
// "audio": [
// "..../xxx.mp3",
// "......"
// ]
// 非xiaoai平台的,返回如下:
//"audio": [
// "..../xxx.mp3.b64",
// "......"
// ]
file_ls.add(filepath);
}
// 小爱平台的请求,我们会讲所有mp3文件合在一起,文件路径为(audio_dir)/botname/xiaoai/xxx.mp3,
// 成功则构建请求get_audio接口的请求url,包括参数信息,返回该url
String temp;
if (file_ls.size() == 1) {
final String tmp_audio_name = file_ls.get(0);
POOL.submit(() -> task(futures, tmp_audio_name, file_ls, null));
return URLEncoder.encode(tmp_audio_name);
} else {
temp = TTSUtils.pythonlistToStr(file_ls);
// String dirs = String.format("[%s,xiaoai]", botName);
final String folder = StringUtils.join(new String[]{Initialize.getAudioDir(), botName, "xiaoai"}, File.separator);
final String tmp_audio_name = new StringBuilder(folder).append(File.separator).append(temp).toString();
POOL.submit(() -> task(futures, tmp_audio_name, file_ls, folder));
return tmp_audio_name;
}
}
return "null";
}
private void task(List<Future<ResponseCodeWithData>> futures, String tmp_audio_name,
List<String> file_ls, String folder) {
try {
// 阻塞等待mp3文件生成成功
//log.info("196:file list:{}", file_ls);
for (Future<ResponseCodeWithData> future : futures) {
try {
// ResponseCodeWithData data = future.get(60, TimeUnit.SECONDS);
ResponseCodeWithData data = future.get();
if (data.getCode() != 200) {
if (data.getCode() == 404) {
log.warn("404,音频没有找到");
}else {
log.error("下载音频失败, status:{}", data.getCode());
}
return;
}
} catch (Exception e) {
log.error("tts_ls获取结果出错:{}", ExceptionUtils.getStackTrace(e));
return;
}
}
if (folder != null && !TTSUtils.doesFileExist(tmp_audio_name)) {
TTSUtils.makedir(folder);
XIAOAI_MP3_MARK.add(tmp_audio_name);
TTSUtils.combineMp3File(file_ls, tmp_audio_name);
if (!TTSUtils.doesFileExist(tmp_audio_name)) {
log.error("小爱平台的请求,聚合mp3文件失败");
}
XIAOAI_MP3_MARK.remove(tmp_audio_name);
}
} catch (Exception e) {
log.error("合成多个音频文件出错:{}", e.toString());
}
}
public static void main(String[] args) {
System.out.println(URLEncoder.encode("正常0c60f9484eaa35aa7a9e2879c574e8a3.mp3"));
System.out.println(URLEncoder.encode("正常24f87c9e922d063260634941f5f75be2.mp3"));
System.out.println(URLEncoder.encode("正常d1a75129c54ef3037bd44e25ab6eeb9a.mp3"));
}
} }
...@@ -11,11 +11,6 @@ import com.csvreader.CsvReader; ...@@ -11,11 +11,6 @@ import com.csvreader.CsvReader;
import lombok.extern.slf4j.Slf4j; import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils; import org.apache.commons.lang3.StringUtils;
import org.apache.commons.lang3.exception.ExceptionUtils; import org.apache.commons.lang3.exception.ExceptionUtils;
import org.jaudiotagger.audio.exceptions.InvalidAudioFrameException;
import org.jaudiotagger.audio.exceptions.ReadOnlyFileException;
import org.jaudiotagger.audio.mp3.MP3File;
import org.jaudiotagger.tag.TagException;
import javax.sound.sampled.AudioFormat; import javax.sound.sampled.AudioFormat;
import javax.sound.sampled.AudioInputStream; import javax.sound.sampled.AudioInputStream;
...@@ -264,27 +259,38 @@ public class Test { ...@@ -264,27 +259,38 @@ public class Test {
return "3"; return "3";
} }
private static void convert(File input, File outPut) throws IOException, UnsupportedAudioFileException { private static void test8(String text) {
AudioInputStream stream = AudioSystem.getAudioInputStream(input); List<String> variableTextList = new ArrayList<>();
AudioFormat format = stream.getFormat(); // 获取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地址集合
// 人工上传目录, audio_dir/botname/record/npcname
// 非变量部分
String[] notVariableTextArray = pattern.split(text);
System.out.println("variable:"+variableTextList);
System.out.println("un:"+Arrays.toString(notVariableTextArray));
}
} }
public static void main(String[] args) throws IOException, ParseException, UnsupportedAudioFileException, InvalidAudioFrameException, TagException, ReadOnlyFileException {
Pattern pattern = Pattern.compile(TTSUtils.getAbRegex()); public static void main(String[] args) {
String[] arrr = pattern.split("回答错误,正确答案为 :风吹草地见牛羊。 当前体力值为 \uD83C\uDD7097\uD83C\uDD71");
System.out.println(Arrays.toString(arrr));
Date date = new Date(1572522571234L); Date date = new Date(1572522571234L);
SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
System.out.println(format.format(new Date())); SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
ArrayList<String> list = new ArrayList<>(); System.out.println(TTSUtils.buildMP3Filename("\uD83C\uDD70会数学的杰瑞的类型为:儿童、简单、益智、休闲、教育、学生、免费\uD83C\uDD71"));
list.add("/home/yf01/下载/human1.mp3"); System.out.println(TTSUtils.buildMP3Filename("会数学的杰瑞的类型为:儿童、简单、益智、休闲、教育、学生、免费"));
list.add("/home/yf01/下载/human2.mp3");
list.add("/home/yf01/下载/us1.mp3");
list.add("/home/yf01/下载/us2.mp3");
TTSUtils.combineMp3File(list, "/home/yf01/下载/mqwTest.mp3");
System.out.println(TTSUtils.buildMP3Filename("你当{/dang1/}前{/qian2/}分{/fen1/}数{/shu4/}是")); Pattern pattern = Pattern.compile(TTSUtils.getAbRegex());
System.out.println(TTSUtils.buildMP3Filename("10")); String[] notVariableTextArray = pattern.split("\uD83C\uDD70会数学的杰瑞的类型为:儿童、简单、益智、休闲、教育、学生、免费\uD83C\uDD71");
System.out.println(notVariableTextArray.length);
System.out.println(Arrays.toString(notVariableTextArray));
} }
} }
...@@ -4,7 +4,7 @@ spring: ...@@ -4,7 +4,7 @@ spring:
#password: 3g9^pWQs#ft7 #password: 3g9^pWQs#ft7
password: qiwu@123234aA~ password: qiwu@123234aA~
# driver-class-name: com.mysql.cj.jdbc.Driver # driver-class-name: com.mysql.cj.jdbc.Driver
driver-class-name: com.mysql.jdbc.Driver driver-class-name: com.mysql.cj.jdbc.Driver
# url: jdbc:mysql://aliyun-hz1.chewrobot.com:3306/TTS?useUnicode=true&characterEncoding=utf-8&useSSL=false # url: jdbc:mysql://aliyun-hz1.chewrobot.com:3306/TTS?useUnicode=true&characterEncoding=utf-8&useSSL=false
url: jdbc:mysql://didi-gz1.jiaoyou365.com:3306/TTS?useUnicode=true&characterEncoding=utf-8&useSSL=false url: jdbc:mysql://didi-gz1.jiaoyou365.com:3306/TTS?useUnicode=true&characterEncoding=utf-8&useSSL=false
# username: tts # username: tts
...@@ -37,4 +37,5 @@ server: ...@@ -37,4 +37,5 @@ server:
directory: /home/ubuntu/project/tts/tomcat directory: /home/ubuntu/project/tts/tomcat
max-threads: 1024 max-threads: 1024
# directory: /root/GameEditor/mqw/project/ttsTest/tomcat # directory: /root/GameEditor/mqw/project/ttsTest/tomcat
connection-timeout: 2000
audioUrl: https://didi-gz4.jiaoyou365.com/xiaoai/audio/play?userId=
...@@ -14,10 +14,13 @@ import ai.qiwu.mi.xiaoai.model.response.innerResponse.directive.AudioItem.AudioI ...@@ -14,10 +14,13 @@ import ai.qiwu.mi.xiaoai.model.response.innerResponse.directive.AudioItem.AudioI
import ai.qiwu.mi.xiaoai.model.response.innerResponse.directive.AudioItem.AudioStream; import ai.qiwu.mi.xiaoai.model.response.innerResponse.directive.AudioItem.AudioStream;
import ai.qiwu.mi.xiaoai.model.response.innerResponse.directive.Directive; import ai.qiwu.mi.xiaoai.model.response.innerResponse.directive.Directive;
import ai.qiwu.mi.xiaoai.model.response.innerResponse.toSpeak.ToSpeak; import ai.qiwu.mi.xiaoai.model.response.innerResponse.toSpeak.ToSpeak;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import lombok.extern.slf4j.Slf4j; import lombok.extern.slf4j.Slf4j;
import org.apache.commons.codec.binary.StringUtils; import org.apache.commons.codec.binary.StringUtils;
import org.springframework.stereotype.Service; import org.springframework.stereotype.Service;
import java.io.File;
import java.util.*; import java.util.*;
import java.util.concurrent.*; import java.util.concurrent.*;
...@@ -284,4 +287,15 @@ public class XiaoAiService { ...@@ -284,4 +287,15 @@ public class XiaoAiService {
LAST_OUTTIME_RESULT.put(userId, xiaoAiResponse); LAST_OUTTIME_RESULT.put(userId, xiaoAiResponse);
} }
} }
public static void main(String[] args) {
String s = "{\"mainChatKey\":\"jiaoyou-audio-testXIAODU_173f8ae7434db1b46160d04069e067e0@@@42637886@@@@QMBnsvLlgdydEhKF74Zm\",\"extraChatKey\":\"jiaoyou-audio-testXIAODU_173f8ae7434db1b46160d04069e067e0@@@438574481@@@@CKcTNH015jrkg8xy7yrF\",\"aipioneerUsername\":\"438574481\",\"dialogs\":[{\"botAccount\":\"438574481\",\"npcName\":\"皮皮\",\"person\":\"A20_offline\",\"pitch\":\"1.2\",\"speed\":\"1.4\",\"text\":\"啊!糟糕,时光机怎么自己动起来了!\",\"tone\":\"生气\",\"volume\":\"5.0\"},{\"botAccount\":\"438574481\",\"npcName\":\"旁白\",\"person\":\"A04_offline\",\"pitch\":\"0.0\",\"speed\":\"1.14\",\"text\":\"时空穿梭机似乎出了点问题{/ti2/},你和皮皮穿梭到了动物园,动物园里有老{/lao3/}虎{/hu3/},狮子,大象,还有几只在吃竹子的大熊猫\",\"tone\":\"正常\",\"volume\":\"4.0\"},{\"botAccount\":\"438574481\",\"npcName\":\"皮皮\",\"person\":\"A20_offline\",\"pitch\":\"1.2\",\"speed\":\"1.4\",\"text\":\"呀{/ya4/},我们好像来到动物园了!小朋友你看,那里有熊猫耶,你喜欢熊猫吗?\",\"tone\":\"正常\",\"volume\":\"5.0\"}]}";
JSONObject object = JSONObject.parseObject(s);
JSONArray array = object.getJSONArray("dialogs");
for (Object ob: array) {
String str = ((JSONObject) ob).getString("text");
str = str.replaceAll("\\{/.*?/}", "");
System.out.println(str);
}
}
} }
...@@ -90,7 +90,7 @@ ...@@ -90,7 +90,7 @@
<dependency> <dependency>
<groupId>com.alibaba</groupId> <groupId>com.alibaba</groupId>
<artifactId>fastjson</artifactId> <artifactId>fastjson</artifactId>
<version>1.2.60</version> <version>1.2.62</version>
</dependency> </dependency>
<!-- https://mvnrepository.com/artifact/net.sourceforge.javacsv/javacsv --> <!-- https://mvnrepository.com/artifact/net.sourceforge.javacsv/javacsv -->
<dependency> <dependency>
...@@ -104,6 +104,34 @@ ...@@ -104,6 +104,34 @@
<artifactId>commons-csv</artifactId> <artifactId>commons-csv</artifactId>
<version>1.7</version> <version>1.7</version>
</dependency> </dependency>
<dependency>
<groupId>com.tianmao</groupId>
<artifactId>spirit</artifactId>
<version>1.0.0</version>
<scope>system</scope>
<systemPath>${project.basedir}/src/main/resources/static/aligenie/aliGenie-intent-sematic.jar</systemPath>
</dependency>
<!-- https://mvnrepository.com/artifact/com.google.guava/guava -->
<dependency>
<groupId>com.google.guava</groupId>
<artifactId>guava</artifactId>
<version>28.1-jre</version>
</dependency>
<dependency>
<groupId>com.google.code.gson</groupId>
<artifactId>gson</artifactId>
<version>2.8.5</version>
</dependency>
<!-- https://mvnrepository.com/artifact/org.apache.httpcomponents/httpclient -->
<dependency>
<groupId>org.apache.httpcomponents</groupId>
<artifactId>httpclient</artifactId>
</dependency>
<!-- https://mvnrepository.com/artifact/org.apache.httpcomponents/httpmime -->
<dependency>
<groupId>org.apache.httpcomponents</groupId>
<artifactId>httpmime</artifactId>
</dependency>
</dependencies> </dependencies>
<build> <build>
...@@ -112,6 +140,9 @@ ...@@ -112,6 +140,9 @@
<plugin> <plugin>
<groupId>org.springframework.boot</groupId> <groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-maven-plugin</artifactId> <artifactId>spring-boot-maven-plugin</artifactId>
<configuration>
<includeSystemScope>true</includeSystemScope>
</configuration>
</plugin> </plugin>
</plugins> </plugins>
</build> </build>
......
package ai.qiwu.com.xiaoduhome.common;
import lombok.extern.slf4j.Slf4j;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.client.config.RequestConfig;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.ContentType;
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.HttpClients;
import org.apache.http.impl.conn.PoolingHttpClientConnectionManager;
import org.apache.http.protocol.HTTP;
import org.springframework.util.CollectionUtils;
import java.io.BufferedReader;
import java.io.File;
import java.io.IOException;
import java.io.InputStreamReader;
import java.nio.charset.Charset;
import java.nio.charset.StandardCharsets;
import java.util.Map;
/**
* @author 苗权威
* @dateTime 19-12-4 下午7:59
*/
@Slf4j
public class ApachHttpUtils {
private static CloseableHttpClient httpClient;
static {
PoolingHttpClientConnectionManager cm = new PoolingHttpClientConnectionManager();
cm.setMaxTotal(100);
cm.setDefaultMaxPerRoute(50);
httpClient = HttpClients.custom().setConnectionManager(cm).build();
}
public static String post(String url, String jsonString, Map<String, String> headers) {
String result = null;
HttpPost httpPost = new HttpPost(url);
RequestConfig requestConfig = RequestConfig.custom().setConnectTimeout(30000).setConnectionRequestTimeout(30000).setSocketTimeout(30000).build();
httpPost.setConfig(requestConfig);
if (!CollectionUtils.isEmpty(headers)) headers.forEach(httpPost::setHeader);
else {
httpPost.addHeader("Content-type", "application/json; charset=utf-8");
httpPost.setHeader("Accept", "application/json");
}
httpPost.setEntity(new StringEntity(jsonString, Charset.forName("UTF-8")));
try(CloseableHttpResponse response = httpClient.execute(httpPost);
BufferedReader in = new BufferedReader(new InputStreamReader(response.getEntity().getContent()))) {
StringBuilder sb = new StringBuilder();
String line;
while ((line = in.readLine()) != null) {
sb.append(line);
}
result = sb.toString();
} catch (IOException e) {
log.error("post表单请求出错:"+e);
}
return result;
}
public static String requestByPostParts(Map<String,String> map, Map<String,String> headers, String url, Charset charset, File file) {
try {
HttpPost post = new HttpPost(url);
if (!CollectionUtils.isEmpty(headers)) headers.forEach(post::setHeader);
MultipartEntityBuilder multipartEntityBuilder = MultipartEntityBuilder.create();
multipartEntityBuilder.setMode(HttpMultipartMode.BROWSER_COMPATIBLE);
if(map!=null) {
ContentType contentType = ContentType.create(HTTP.PLAIN_TEXT_TYPE, StandardCharsets.UTF_8);
for (Map.Entry<String, String> stringObjectEntry : map.entrySet()) {
String key = stringObjectEntry.getKey();
String value = stringObjectEntry.getValue();
multipartEntityBuilder.addTextBody(key, value, contentType);
}
}
if (file != null) {
multipartEntityBuilder.addBinaryBody("file", file);
}
post.setEntity(multipartEntityBuilder.build());
HttpResponse resp = httpClient.execute(post);
int ret = resp.getStatusLine().getStatusCode();
if (ret != 200) return null;
HttpEntity entity = resp.getEntity();
try (BufferedReader br = new BufferedReader(new InputStreamReader(entity.getContent(), charset))){
StringBuilder responseString = new StringBuilder();
String result = br.readLine();
while (result != null)
{
responseString.append(result);
result = br.readLine();
}
return responseString.toString();
}
} catch (Exception e)
{
log.error(e.toString());
}
return null;
}
}
...@@ -6,8 +6,12 @@ package ai.qiwu.com.xiaoduhome.common; ...@@ -6,8 +6,12 @@ package ai.qiwu.com.xiaoduhome.common;
*/ */
public interface Constants { public interface Constants {
String QI_WU_INTERFACE = "http://didi-gz4.jiaoyou365.com:8070/api/chat2"; String QI_WU_INTERFACE = "http://didi-gz3.jiaoyou365.com:8070/api/chat2";
String INTERFACE_DI = "http://didi-gz3.jiaoyou365.com:8070/api/chat2"; String INTERFACE_DI = "http://didi-gz3.jiaoyou365.com:8070/api/chat2";
String TTS_DIDI3_GET = "http://didi-gz3.jiaoyou365.com:9663/api/audio/get?path=";
String TTS_DIDI3_GET_XIAOAI = "http://didi-gz3.jiaoyou365.com:9663/api/audio/get?type=";
String TTS_DIDI4_GET_XIAOAI = "http://didi-gz4.jiaoyou365.com:9663/api/audio/get?type=";
String TTS_DIDI4_GET_XIAOAI_STATIC = "http://didi-gz4.jiaoyou365.com:9663/static/";
String SERVICE_NAME = "BAIDU"; String SERVICE_NAME = "BAIDU";
String PRIVATE_KEY = "MIICdwIBADANBgkqhkiG9w0BAQEFAASCAmEwggJdAgEAAoGBANMWIYduiQZt0B7s" + String PRIVATE_KEY = "MIICdwIBADANBgkqhkiG9w0BAQEFAASCAmEwggJdAgEAAoGBANMWIYduiQZt0B7s" +
"IZ6PW15gpcO7Yn+9ZbaMSHwzJqNeDAZzh6HXF7r0ZpQcw3XEWKPAPWyuJ5eqZf46" + "IZ6PW15gpcO7Yn+9ZbaMSHwzJqNeDAZzh6HXF7r0ZpQcw3XEWKPAPWyuJ5eqZf46" +
...@@ -33,6 +37,7 @@ public interface Constants { ...@@ -33,6 +37,7 @@ public interface Constants {
String LOAD_INTRO = "扫描二维码输入手机号获取验证码登录"; String LOAD_INTRO = "扫描二维码输入手机号获取验证码登录";
String REWARD_FLOWER = "请扫码支付"; String REWARD_FLOWER = "请扫码支付";
String UNIT_PRICE = "1"; String UNIT_PRICE = "1";
String PREFIX_USERID = "XIAODU_";
Integer CO_HI_PAGE_SIZE = 4; Integer CO_HI_PAGE_SIZE = 4;
Integer RE_RA_CA_PAGE_SIZE = 12; Integer RE_RA_CA_PAGE_SIZE = 12;
...@@ -55,7 +60,7 @@ public interface Constants { ...@@ -55,7 +60,7 @@ public interface Constants {
String COLLECTED_IMG_URL = "https://didi-gz5.jiaoyou365.com/duai/image/collec.png"; String COLLECTED_IMG_URL = "https://didi-gz5.jiaoyou365.com/duai/image/collec.png";
String UN_COLLECTED_IMG_URL = "https://didi-gz5.jiaoyou365.com/duai/image/uncollec.png"; String UN_COLLECTED_IMG_URL = "https://didi-gz5.jiaoyou365.com/duai/image/uncollec.png";
String DEFAULT_ASIDE_IMG_URL = "http://didi-gz4.jiaoyou365.com/Editor//upload/img/npc/2019/02/19174004213.png"; String DEFAULT_ASIDE_IMG_URL = "http://didi-gz4.jiaoyou365.com/Editor/upload/img/npc/2019/02/19174004213.png";
} }
interface PRODUCT_INTRO { interface PRODUCT_INTRO {
...@@ -96,7 +101,16 @@ public interface Constants { ...@@ -96,7 +101,16 @@ public interface Constants {
} }
interface WelcomeWord { interface WelcomeWord {
String WELCOME = "欢迎来到交游天下,这里有海量的作品在这等您"; String WELCOME = "欢迎来到交游天下,你可以说推荐作品给我";
String SKILL = "交游天下";
String WELCOME_SMART = "小朋友你好,欢迎来到智能故事,你可以对我说有什么好玩的吗";
String SKILL_SMART = "智能故事";
String WELCOME_NOVEL = "欢迎来到智能小说,你可以说推荐作品给我";
String SKILL_NOVEL = "智能小说";
String WELCOME_LITERATURE = "欢迎来到互动文艺,你可以说推荐作品给我";
String SKILL_LITERATURE = "互动文艺";
String WELCOME_STORY = "小朋友你好,欢迎来到交互故事,你可以对我说有什么好玩的吗";
String SKILL_STORY = "交互故事";
String BEGIN_NO_RESPONSE = "咋还没开始就停住了,我们这里可有很多好玩的作品哦"; String BEGIN_NO_RESPONSE = "咋还没开始就停住了,我们这里可有很多好玩的作品哦";
String GUIDE_WORD = "请点击或者直接说出您想要玩的作品名"; String GUIDE_WORD = "请点击或者直接说出您想要玩的作品名";
String FAIL_COLLECT = "好像出了什么问题,请再说一遍吧"; String FAIL_COLLECT = "好像出了什么问题,请再说一遍吧";
...@@ -105,6 +119,8 @@ public interface Constants { ...@@ -105,6 +119,8 @@ public interface Constants {
interface EndMsg { interface EndMsg {
String BYE_BYE = "我们的作品库在不断的扩充,欢迎下次再来玩"; String BYE_BYE = "我们的作品库在不断的扩充,欢迎下次再来玩";
String END_BYE_CHILD = "再见啦小朋友,记得下次再来玩哦";
String END_BYE_Adult = "再见啦,记得下次再来玩哦";
String CAN_NOT_UNDERSTAND = "用户无输入或多次输入无法理解"; String CAN_NOT_UNDERSTAND = "用户无输入或多次输入无法理解";
String USER_SAY_CANCEL = "用户直接说退出"; String USER_SAY_CANCEL = "用户直接说退出";
} }
......
package ai.qiwu.com.xiaoduhome.common; package ai.qiwu.com.xiaoduhome.common;
import ai.qiwu.com.xiaoduhome.pojo.AudioBoxData;
import lombok.extern.slf4j.Slf4j; import lombok.extern.slf4j.Slf4j;
import okhttp3.*; import okhttp3.*;
import org.apache.commons.lang3.exception.ExceptionUtils;
import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.NotNull;
import java.io.File; import java.io.File;
...@@ -68,7 +70,7 @@ public class OkHttp3Utils { ...@@ -68,7 +70,7 @@ public class OkHttp3Utils {
Headers.Builder headBuilder = request.headers().newBuilder(); Headers.Builder headBuilder = request.headers().newBuilder();
headBuilder.add("Content-Type", "application/json;charset=utf-8"); headBuilder.add("Content-Type", "application/json;charset=utf-8");
headBuilder.add("App-Channel-Id", "jiaoyou-audio-test"); // headBuilder.add("App-Channel-Id", "jiaoyou-audio-test");
// Iterator<Map.Entry<String, String>> headIterator = headers.entrySet().iterator(); // Iterator<Map.Entry<String, String>> headIterator = headers.entrySet().iterator();
// headIterator.forEachRemaining(e -> headBuilder.add(e.getKey(), e.getValue())); // headIterator.forEachRemaining(e -> headBuilder.add(e.getKey(), e.getValue()));
...@@ -106,18 +108,50 @@ public class OkHttp3Utils { ...@@ -106,18 +108,50 @@ public class OkHttp3Utils {
return null; return null;
} }
public static void backPostAsync(String url, String requestJsonStr) { public static void asyncPost(String url, String strJson, final AudioBoxData data) {
Request.Builder builder = new Request.Builder(); Request request = new Request.Builder()
// builder.url(url); .url(url)
// builder.addHeader("Content-Type", "application/json;charset=utf-8"); .post(RequestBody.create(MediaType.parse("application/json; charset=utf-8"), strJson))
.build();
client.newCall(request).enqueue(new Callback() {
@Override
public void onFailure(@NotNull Call call, @NotNull IOException e) {
log.info("异步请求失败");
}
Request request = builder.url(url).build(); @Override
Headers.Builder headBuilder = request.headers().newBuilder(); public void onResponse(@NotNull Call call, @NotNull Response response) throws IOException {
headBuilder.add("Content-Type", "application/json;charset=utf-8"); try (ResponseBody body = response.body()){
data.setPath(body.string());
log.info("异步请求成功");
} catch (SocketTimeoutException e) {
log.error("捕获到SocketTimeoutException:{}", e.toString());
client.dispatcher().cancelAll();
client.connectionPool().evictAll();
} catch (Exception e) {
log.error(ExceptionUtils.getStackTrace(e));
}
}
});
}
//RequestBody requestBody = FormBody.create(MediaType.parse("application/json; charset=utf-8"), requestJsonStr); public static void backPostAsync(String url, String requestJsonStr, Integer type) {
builder.post(RequestBody.create(MediaType.parse("application/json; charset=utf-8"), requestJsonStr)); String header = "jiaoyou-audio-test";
client.newCall(builder.build()).enqueue(new Callback() { if (type != null) {
switch (type) {
case 1 :
case 3 : header = "jiaoyou-audio-child-test";break;
case 2 :
case 4 : header = "jiaoyou-audio-adult-test";break;
default: header = "jiaoyou-audio-test";
}
}
Request request = new Request.Builder()
.url(url)
.post(RequestBody.create(MediaType.parse("application/json; charset=utf-8"), requestJsonStr))
.header("App-Channel-Id", header)
.build();
client.newCall(request).enqueue(new Callback() {
@Override @Override
public void onFailure(@NotNull Call call, @NotNull IOException e) { public void onFailure(@NotNull Call call, @NotNull IOException e) {
log.info("退出失败"); log.info("退出失败");
...@@ -125,12 +159,46 @@ public class OkHttp3Utils { ...@@ -125,12 +159,46 @@ public class OkHttp3Utils {
@Override @Override
public void onResponse(@NotNull Call call, @NotNull Response response) throws IOException { public void onResponse(@NotNull Call call, @NotNull Response response) throws IOException {
log.info("退出成功"); try (ResponseBody body = response.body()){
log.info("退出成功:{}", body.string());
} catch (SocketTimeoutException e) {
log.error("捕获到SocketTimeoutException:{}", e.toString());
client.dispatcher().cancelAll();
client.connectionPool().evictAll();
} catch (Exception e) {
log.error(ExceptionUtils.getStackTrace(e));
}
} }
}); });
} }
public static String doPost(String url, Map<String, String> headers, Map<String, String> params, File file) throws IOException { public static void postAsync(String url, String requestJsonStr) {
Request request = new Request.Builder()
.url(url)
.post(RequestBody.create(requestJsonStr,MediaType.parse("application/json; charset=utf-8")))
.build();
client.newCall(request).enqueue(new Callback() {
@Override
public void onFailure(@NotNull Call call, @NotNull IOException e) {
log.info("天猫精灵发送无音频数据失败");
}
@Override
public void onResponse(@NotNull Call call, @NotNull Response response) throws IOException {
try (ResponseBody body = response.body()){
body.string();
} catch (SocketTimeoutException e) {
log.error("捕获到SocketTimeoutException:{}", e.toString());
client.dispatcher().cancelAll();
client.connectionPool().evictAll();
} catch (Exception e) {
log.error(ExceptionUtils.getStackTrace(e));
}
}
});
}
public static String doPost(String url, final Map<String, String> headers, final Map<String, String> params, File file) throws IOException {
Request.Builder builder = new Request.Builder(); Request.Builder builder = new Request.Builder();
Request request = builder.url(url).build(); Request request = builder.url(url).build();
...@@ -140,12 +208,12 @@ public class OkHttp3Utils { ...@@ -140,12 +208,12 @@ public class OkHttp3Utils {
headIterator.forEachRemaining(e -> headBuilder.add(e.getKey(), e.getValue())); headIterator.forEachRemaining(e -> headBuilder.add(e.getKey(), e.getValue()));
MultipartBody.Builder requestBuilder = new MultipartBody.Builder(); MultipartBody.Builder requestBuilder = new MultipartBody.Builder();
Iterator<Map.Entry<String, String>> paramsIterator = params.entrySet().iterator(); System.out.println(params);
paramsIterator.forEachRemaining(e -> requestBuilder.addFormDataPart(e.getKey(), e.getValue())); params.forEach(requestBuilder::addFormDataPart);
if (file != null) { if (file != null) {
requestBuilder.addFormDataPart("uploadFiles", file.getName(), requestBuilder.addFormDataPart("file", file.getName(),
RequestBody.create(MediaType.parse("application/octet-stream"), file)); RequestBody.create(MediaType.parse("audio/mpeg"), file));
} }
builder.headers(headBuilder.build()).post(requestBuilder.build()); builder.headers(headBuilder.build()).post(requestBuilder.build());
Response response = client.newCall(builder.build()).execute(); Response response = client.newCall(builder.build()).execute();
......
package ai.qiwu.com.xiaoduhome.controller;
import lombok.extern.slf4j.Slf4j;
import org.apache.catalina.connector.ClientAbortException;
import org.springframework.web.bind.annotation.RestController;
import javax.servlet.http.HttpServletResponse;
import java.io.*;
/**
* @author 苗权威
* @dateTime 19-12-13 下午4:32
*/
@RestController
@Slf4j
public class AudioGetController {
// @RequestMapping("/audio/get")
// public void audioGet(String id, String mark, HttpServletResponse response) {
// String type = id.substring(0, id.indexOf("_"));
// AudioBoxData data = null;
// switch (type) {
// case "XIAODU": data = DplBotService.XIAODU_MP3_PATH.get(id); break;
// case "XIAOAI": data = XiaoAiServiceTemp.XIAOAI_MP3_PATH.get(id); break;
// }
// if (data != null && mark.equals(data.getMark())) {
// buildMp3Response(response, data.getPath());
// } else {
// try {
// Thread.sleep(2000);
// } catch (Exception e){}
// switch (type) {
// case "XIAODU": data = DplBotService.XIAODU_MP3_PATH.get(id); break;
// case "XIAOAI": data = XiaoAiServiceTemp.XIAOAI_MP3_PATH.get(id); break;
// }
// if (data != null && mark.equals(data.getMark())) {
// buildMp3Response(response, data.getPath());
// } else {
// log.error("没有获取到音频");
// }
// }
// }
private void buildMp3Response(HttpServletResponse response, String fileName) {
response.setStatus(200);
try (BufferedInputStream inputStream = new BufferedInputStream(new FileInputStream(fileName));
OutputStream out = new BufferedOutputStream(response.getOutputStream())){
response.reset();
response.setContentType("audio/mp3");
response.setHeader("Content-Type", "audio/mp3");
byte[] buffer = new byte[1024];
int ln;
while ((ln = inputStream.read(buffer)) != -1) {
out.write(buffer, 0, ln);
}
out.flush();
} catch (ClientAbortException e) {
} catch (IOException e) {
log.error("buildMp3Response:写入音频流到HttpServletResponse失败:{}", e.toString());
}
}
}
...@@ -11,10 +11,7 @@ import org.apache.commons.lang3.StringUtils; ...@@ -11,10 +11,7 @@ import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired; import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller; import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap; import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.GetMapping; import org.springframework.web.bind.annotation.*;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletRequest;
import java.io.IOException; import java.io.IOException;
......
package ai.qiwu.com.xiaoduhome.controller;
import ai.qiwu.com.xiaoduhome.spirit.SpiritService;
import com.alibaba.da.coin.ide.spi.standard.ResultModel;
import com.alibaba.da.coin.ide.spi.standard.TaskQuery;
import com.alibaba.da.coin.ide.spi.standard.TaskResult;
import com.alibaba.da.coin.ide.spi.trans.MetaFormat;
import com.alibaba.fastjson.JSON;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import javax.servlet.http.HttpServletResponse;
/**
* @author 苗权威
* @dateTime 19-12-6 上午10:31
*/
@RestController
@RequestMapping("/spirit")
@Slf4j
public class SpiritController {
private final SpiritService spiritService;
@Autowired
public SpiritController(SpiritService spiritService) {
this.spiritService = spiritService;
}
/**
* 利用天猫精灵打开发包解析请求并从构造响应数据返回
* @param taskQuery 请求的参数信息
* @return 返回响应的JSON数据
*/
@PostMapping(value = "/") //交游天下
public ResultModel<TaskResult> getResponse(@RequestBody String taskQuery) {
log.info("天猫请求信息:{}",taskQuery);
TaskQuery query = MetaFormat.parseToQuery(taskQuery);
// build response
ResultModel<TaskResult> resultModel = new ResultModel<>();
TaskResult taskResult = spiritService.getResponse(query, 1);
resultModel.setReturnCode("0");
resultModel.setReturnValue(taskResult);
log.info("天猫响应信息:"+ JSON.toJSONString(resultModel));
return resultModel;
}
@PostMapping(value = "/story") // 互动故事
public ResultModel<TaskResult> story(@RequestBody String taskQuery) {
// log.info("TaskQuery:{}",taskQuery);
TaskQuery query = MetaFormat.parseToQuery(taskQuery);
// build response
ResultModel<TaskResult> resultModel = new ResultModel<>();
TaskResult taskResult = spiritService.getResponse(query,2);
// logger.info("taskResult:"+taskResult);
resultModel.setReturnCode("0");
resultModel.setReturnValue(taskResult);
return resultModel;
}
@PostMapping(value = "/literature") // 互动文艺
public ResultModel<TaskResult> literature(@RequestBody String taskQuery) {
// log.info("TaskQuery:{}",taskQuery);
TaskQuery query = MetaFormat.parseToQuery(taskQuery);
// build response
ResultModel<TaskResult> resultModel = new ResultModel<>();
TaskResult taskResult = spiritService.getResponse(query,3);
// logger.info("taskResult:"+taskResult);
resultModel.setReturnCode("0");
resultModel.setReturnValue(taskResult);
return resultModel;
}
@PostMapping(value = "/smart") // 智能故事
public ResultModel<TaskResult> smart(@RequestBody String taskQuery) {
// log.info("TaskQuery:{}",taskQuery);
TaskQuery query = MetaFormat.parseToQuery(taskQuery);
// build response
ResultModel<TaskResult> resultModel = new ResultModel<>();
TaskResult taskResult = spiritService.getResponse(query,4);
// logger.info("taskResult:"+taskResult);
resultModel.setReturnCode("0");
resultModel.setReturnValue(taskResult);
return resultModel;
}
@PostMapping(value = "/novel") // 智能小说
public ResultModel<TaskResult> novel(@RequestBody String taskQuery) {
// log.info("TaskQuery:{}",taskQuery);
TaskQuery query = MetaFormat.parseToQuery(taskQuery);
// build response
ResultModel<TaskResult> resultModel = new ResultModel<>();
TaskResult taskResult = spiritService.getResponse(query,5);
// logger.info("taskResult:"+taskResult);
resultModel.setReturnCode("0");
resultModel.setReturnValue(taskResult);
return resultModel;
}
}
package ai.qiwu.com.xiaoduhome.controller; package ai.qiwu.com.xiaoduhome.controller;
import org.springframework.stereotype.Controller; import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping; import org.springframework.web.bind.annotation.*;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile; import org.springframework.web.multipart.MultipartFile;
import javax.servlet.http.HttpServletResponse;
import java.io.File; import java.io.File;
/** /**
* @author 苗权威 * @author 苗权威
* @dateTime 19-9-4 下午2:13 * @dateTime 19-9-4 下午2:13
*/ */
@Controller @RestController
@RequestMapping("/xiaoduhome/img") //@RequestMapping("/xiaoduhome/img")
public class UpLoadImgController { public class UpLoadImgController {
@GetMapping("/up") // @GetMapping("/up")
public String uploadImage() { public String uploadImage() {
return "linPicture"; return "linPicture";
} }
@PostMapping("/up") // @PostMapping("/up")
public @ResponseBody public @ResponseBody
void loadImage(MultipartFile file, String storyName, String imageType) { void loadImage(MultipartFile file, String storyName, String imageType) {
StringBuilder builder = new StringBuilder("/root/GameEditor/mqw/xiaoduhome/image/tmp/"); StringBuilder builder = new StringBuilder("/root/GameEditor/mqw/xiaoduhome/image/tmp/");
...@@ -37,4 +35,8 @@ public class UpLoadImgController { ...@@ -37,4 +35,8 @@ public class UpLoadImgController {
e.printStackTrace(); e.printStackTrace();
} }
} }
public void download(HttpServletResponse response) {
}
} }
...@@ -11,21 +11,6 @@ import org.springframework.web.bind.annotation.*; ...@@ -11,21 +11,6 @@ import org.springframework.web.bind.annotation.*;
@Controller @Controller
public class WebSocketLogController { public class WebSocketLogController {
// @GetMapping("/audio/webSocket/du")
// public String duLog(ModelMap modelMap) {
// return "Log";
// }
//
// @GetMapping("/audio/webSocket/aigz3")
// public String aigz3Log(ModelMap modelMap) {
// return "aigz3";
// }
//
// @GetMapping("/audio/webSocket/aigz4")
// public String aigz4Log(ModelMap modelMap) {
// return "aigz4";
// }
@GetMapping("/audio/index") @GetMapping("/audio/index")
public String logIndexPage(ModelMap modelMap) { public String logIndexPage(ModelMap modelMap) {
return "index.html"; return "index.html";
...@@ -50,4 +35,10 @@ public class WebSocketLogController { ...@@ -50,4 +35,10 @@ public class WebSocketLogController {
public String logdu2Page(ModelMap modelMap) { public String logdu2Page(ModelMap modelMap) {
return "Log4.html"; return "Log4.html";
} }
// eae846c7d1ca51474ebc7230ace47bf2.txt
@GetMapping("/aligenie/{name}")
public String spirit(@PathVariable String name, ModelMap modelMap) {
return name;
}
} }
package ai.qiwu.com.xiaoduhome.controller;
import ai.qiwu.com.xiaoduhome.xiaoai.model.request.XiaoAiRequest;
import ai.qiwu.com.xiaoduhome.xiaoai.model.response.XiaoAiResponse;
import ai.qiwu.com.xiaoduhome.xiaoai.service.XiaoAiService;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
/**
* @author 苗权威
* @dateTime 19-12-6 上午9:54
*/
@RestController
@RequestMapping("/xiaoai")
@Slf4j
public class XiaoAiController {
private final XiaoAiService xiaoAiService;
@Autowired
public XiaoAiController(XiaoAiService xiaoAiService) {
this.xiaoAiService = xiaoAiService;
}
/**
* Controller控制器
* @param request
* @return
*/
@RequestMapping("/")
public XiaoAiResponse xiaoai(@RequestBody XiaoAiRequest request) {
log.info("请求:"+request);
XiaoAiResponse response = xiaoAiService.getResponse(request);
log.info("响应:"+response);
return response;
// return xiaoAiService.getResponse(request);
}
@RequestMapping("/child")
public XiaoAiResponse xiaoaiChild(@RequestBody XiaoAiRequest request) {
//log.info("请求:"+request);
request.setType(1);
XiaoAiResponse response = xiaoAiService.getResponse(request);
// log.info("响应:"+response);
return response;
// return xiaoAiService.getResponse(request);
}
@RequestMapping("/story") //互动故事
public XiaoAiResponse xiaoaiChildStory(@RequestBody XiaoAiRequest request) {
//log.info("请求:"+request);
request.setType(3);
XiaoAiResponse response = xiaoAiService.getResponse(request);
// log.info("响应:"+response);
return response;
// return xiaoAiService.getResponse(request);
}
@RequestMapping("/adult")
public XiaoAiResponse xiaoaiAdult(@RequestBody XiaoAiRequest request) {
//log.info("请求:"+request);
request.setType(2);
XiaoAiResponse response = xiaoAiService.getResponse(request);
// log.info("响应:"+response);
return response;
// return xiaoAiService.getResponse(request);
}
@RequestMapping("/literature") // 互动文艺
public XiaoAiResponse xiaoaiAdultLiterature(@RequestBody XiaoAiRequest request) {
//log.info("请求:"+request);
request.setType(4);
XiaoAiResponse response = xiaoAiService.getResponse(request);
// log.info("响应:"+response);
return response;
// return xiaoAiService.getResponse(request);
}
@GetMapping("/audio/play")
public void xiaoaiPlayed(String userId) {
if (StringUtils.isNotBlank(userId)) {
// log.info("小爱确认音频播放:"+userId);
xiaoAiService.changeAudioPlayMark(userId);
}
else log.error("/xiaoai/audio/play userId is null");
}
}
...@@ -3,9 +3,14 @@ package ai.qiwu.com.xiaoduhome.controller; ...@@ -3,9 +3,14 @@ package ai.qiwu.com.xiaoduhome.controller;
import ai.qiwu.com.xiaoduhome.common.Utils; import ai.qiwu.com.xiaoduhome.common.Utils;
import ai.qiwu.com.xiaoduhome.service.DplBotService; import ai.qiwu.com.xiaoduhome.service.DplBotService;
import ai.qiwu.com.xiaoduhome.service.ResponseEncapsulation; import ai.qiwu.com.xiaoduhome.service.ResponseEncapsulation;
import ai.qiwu.com.xiaoduhome.spirit.SpiritService;
import ai.qiwu.com.xiaoduhome.xiaoai.model.request.XiaoAiRequest; import ai.qiwu.com.xiaoduhome.xiaoai.model.request.XiaoAiRequest;
import ai.qiwu.com.xiaoduhome.xiaoai.model.response.XiaoAiResponse; import ai.qiwu.com.xiaoduhome.xiaoai.model.response.XiaoAiResponse;
import ai.qiwu.com.xiaoduhome.xiaoai.service.XiaoAiService; import ai.qiwu.com.xiaoduhome.xiaoai.service.XiaoAiService;
import com.alibaba.da.coin.ide.spi.standard.ResultModel;
import com.alibaba.da.coin.ide.spi.standard.TaskQuery;
import com.alibaba.da.coin.ide.spi.standard.TaskResult;
import com.alibaba.da.coin.ide.spi.trans.MetaFormat;
import lombok.extern.slf4j.Slf4j; import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils; import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired; import org.springframework.beans.factory.annotation.Autowired;
...@@ -13,6 +18,7 @@ import org.springframework.util.ResourceUtils; ...@@ -13,6 +18,7 @@ import org.springframework.util.ResourceUtils;
import org.springframework.web.bind.annotation.*; import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile; import org.springframework.web.multipart.MultipartFile;
import javax.servlet.http.HttpServletResponse;
import java.io.File; import java.io.File;
import java.util.Map; import java.util.Map;
import java.util.UUID; import java.util.UUID;
...@@ -22,60 +28,97 @@ import java.util.UUID; ...@@ -22,60 +28,97 @@ import java.util.UUID;
* @dateTime 19-7-26 下午9:27 * @dateTime 19-7-26 下午9:27
*/ */
@RestController @RestController
@RequestMapping("/xiaoduhome")
@Slf4j @Slf4j
public class XiaoDuHomeController { public class XiaoDuHomeController {
/** @RequestMapping("/chat") //互动天地
* 功能实现类 public String chat() {
*/ try {
@Autowired //log.info("--------------分界线-------------------");
private XiaoAiService xiaoAiService; DplBotService service = new DplBotService(Utils.getHttpServletRequest(), 5);
// log.info("请求信息中的attributes:{}", service.getRequest().getSession().getAttributes());
log.info(service.getStrRequest());
//service.disableVerify();
service.enableVerify();
String str = service.run();
log.info("响应信息:{}", str);
return str;
} catch (Exception e) {
e.printStackTrace();
//log.error("出现错误 "+e.toString());
}
return null;
}
/** @RequestMapping("/story") //交互故事
* Controller控制器 public String story() {
* @param request try {
* @return //log.info("--------------分界线-------------------");
*/ DplBotService service = new DplBotService(Utils.getHttpServletRequest(), 3);
@RequestMapping("/xiaoai") // log.info("请求信息中的attributes:{}", service.getRequest().getSession().getAttributes());
public XiaoAiResponse xiaoai(@RequestBody XiaoAiRequest request) { // log.info(service.getStrRequest());
//log.info("请求:"+request); //service.disableVerify();
XiaoAiResponse response = xiaoAiService.getResponse(request); service.enableVerify();
// log.info("响应:"+response); String str = service.run();
return response; // log.info("响应信息:{}", str);
// return xiaoAiService.getResponse(request); return str;
} catch (Exception e) {
e.printStackTrace();
//log.error("出现错误 "+e.toString());
}
return null;
} }
@RequestMapping("/xiaoai/child") @RequestMapping("/literature") // 互动文艺
public XiaoAiResponse xiaoaiChild(@RequestBody XiaoAiRequest request) { public String literature() {
//log.info("请求:"+request); try {
request.setType(1); //log.info("--------------分界线-------------------");
XiaoAiResponse response = xiaoAiService.getResponse(request); DplBotService service = new DplBotService(Utils.getHttpServletRequest(),4);
// log.info("响应:"+response); // log.info("请求信息中的attributes:{}", service.getRequest().getSession().getAttributes());
return response; // log.info(service.getStrRequest());
// return xiaoAiService.getResponse(request); //service.disableVerify();
service.enableVerify();
String str = service.run();
// log.info("响应信息:{}", str);
return str;
} catch (Exception e) {
e.printStackTrace();
//log.error("出现错误 "+e.toString());
}
return null;
} }
@RequestMapping("/xiaoai/adult") @RequestMapping("/smart") // 智能故事
public XiaoAiResponse xiaoaiAdult(@RequestBody XiaoAiRequest request) { public String smart() {
//log.info("请求:"+request); try {
request.setType(2); //log.info("--------------分界线-------------------");
XiaoAiResponse response = xiaoAiService.getResponse(request); DplBotService service = new DplBotService(Utils.getHttpServletRequest(), 1);
// log.info("响应:"+response); // log.info("请求信息中的attributes:{}", service.getRequest().getSession().getAttributes());
return response; // log.info(service.getStrRequest());
// return xiaoAiService.getResponse(request); //service.disableVerify();
service.enableVerify();
String str = service.run();
// log.info("响应信息:{}", str);
return str;
} catch (Exception e) {
e.printStackTrace();
//log.error("出现错误 "+e.toString());
}
return null;
} }
@RequestMapping("/xiaoduhome/chat") @RequestMapping("/novel") // 智能小说
public String chat() { public String novel() {
try { try {
//log.info("--------------分界线-------------------"); //log.info("--------------分界线-------------------");
DplBotService service = new DplBotService(Utils.getHttpServletRequest()); DplBotService service = new DplBotService(Utils.getHttpServletRequest(), 2);
// log.info("请求信息中的attributes:{}", service.getRequest().getSession().getAttributes()); // log.info("请求信息中的attributes:{}", service.getRequest().getSession().getAttributes());
// log.info(service.getStrRequest()); // log.info(service.getStrRequest());
//service.disableVerify(); //service.disableVerify();
service.enableVerify(); service.enableVerify();
String str = service.run(); String str = service.run();
//log.info("响应信息:{}", str); // log.info("响应信息:{}", str);
return str; return str;
} catch (Exception e) { } catch (Exception e) {
e.printStackTrace(); e.printStackTrace();
......
package ai.qiwu.com.xiaoduhome.pojo;
import lombok.Getter;
import lombok.Setter;
/**
* @author 苗权威
* @dateTime 19-12-13 下午4:27
*/
@Getter
@Setter
public class AudioBoxData {
// private volatile long timestamp;
// private volatile String mark;
private volatile String path;
}
...@@ -346,7 +346,7 @@ public class TestBuild { ...@@ -346,7 +346,7 @@ public class TestBuild {
} }
static void test7() { static void test7() {
String regex = "{[/].+?[/]}"; String regex = "[/].+?[/]}";
String s = "/home/yf01/下载/xiaorong2.csv"; String s = "/home/yf01/下载/xiaorong2.csv";
Pattern pattern = Pattern.compile(regex); Pattern pattern = Pattern.compile(regex);
CSVFormat format = CSVFormat.DEFAULT.withHeader("内部代号", "句子", "是否已上传音频文件", "音频文件名"); CSVFormat format = CSVFormat.DEFAULT.withHeader("内部代号", "句子", "是否已上传音频文件", "音频文件名");
......
...@@ -15,10 +15,14 @@ import ai.qiwu.com.xiaoduhome.entity.primary.*; ...@@ -15,10 +15,14 @@ import ai.qiwu.com.xiaoduhome.entity.primary.*;
import ai.qiwu.com.xiaoduhome.entity.secondary.XiaoDuOrderTB; import ai.qiwu.com.xiaoduhome.entity.secondary.XiaoDuOrderTB;
import ai.qiwu.com.xiaoduhome.pojo.*; import ai.qiwu.com.xiaoduhome.pojo.*;
import ai.qiwu.com.xiaoduhome.pojo.dpl.MyDocument; import ai.qiwu.com.xiaoduhome.pojo.dpl.MyDocument;
import ai.qiwu.com.xiaoduhome.pojo.playAside.PlayPageData;
import ai.qiwu.com.xiaoduhome.repository.secondary.XiaoDuOrderTbRepository; import ai.qiwu.com.xiaoduhome.repository.secondary.XiaoDuOrderTbRepository;
import ai.qiwu.com.xiaoduhome.spirit.SpiritTerminateRequest;
import ai.qiwu.com.xiaoduhome.xiaoai.common.XiaoAiConstants; import ai.qiwu.com.xiaoduhome.xiaoai.common.XiaoAiConstants;
import ai.qiwu.com.xiaoduhome.xiaoai.service.XiaoAiService; import ai.qiwu.com.xiaoduhome.xiaoai.service.XiaoAiService;
import com.alibaba.fastjson.JSON; import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.baidu.dueros.bot.BaseBot; import com.baidu.dueros.bot.BaseBot;
import com.baidu.dueros.data.request.IntentRequest; import com.baidu.dueros.data.request.IntentRequest;
import com.baidu.dueros.data.request.LaunchRequest; import com.baidu.dueros.data.request.LaunchRequest;
...@@ -31,8 +35,8 @@ import com.baidu.dueros.data.request.audioplayer.event.PlaybackStoppedEvent; ...@@ -31,8 +35,8 @@ import com.baidu.dueros.data.request.audioplayer.event.PlaybackStoppedEvent;
import com.baidu.dueros.data.request.events.LinkAccountSucceededEvent; import com.baidu.dueros.data.request.events.LinkAccountSucceededEvent;
import com.baidu.dueros.data.request.pay.event.ChargeEvent; import com.baidu.dueros.data.request.pay.event.ChargeEvent;
import com.baidu.dueros.data.response.OutputSpeech; import com.baidu.dueros.data.response.OutputSpeech;
import com.baidu.dueros.data.response.card.Card; import com.baidu.dueros.data.response.Reprompt;
import com.baidu.dueros.data.response.card.LinkAccountCard; import com.baidu.dueros.data.response.card.*;
import com.baidu.dueros.data.response.directive.Directive; import com.baidu.dueros.data.response.directive.Directive;
import com.baidu.dueros.data.response.directive.audioplayer.AudioPlayerDirective; import com.baidu.dueros.data.response.directive.audioplayer.AudioPlayerDirective;
import com.baidu.dueros.data.response.directive.audioplayer.Play; import com.baidu.dueros.data.response.directive.audioplayer.Play;
...@@ -46,6 +50,7 @@ import com.baidu.dueros.data.response.directive.pay.Charge; ...@@ -46,6 +50,7 @@ import com.baidu.dueros.data.response.directive.pay.Charge;
import com.baidu.dueros.model.Response; import com.baidu.dueros.model.Response;
import com.baidu.dueros.nlu.Intent; import com.baidu.dueros.nlu.Intent;
import lombok.extern.slf4j.Slf4j; import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.RandomStringUtils;
import org.apache.commons.lang3.RandomUtils; import org.apache.commons.lang3.RandomUtils;
import org.apache.commons.lang3.StringUtils; import org.apache.commons.lang3.StringUtils;
import org.apache.commons.lang3.exception.ExceptionUtils; import org.apache.commons.lang3.exception.ExceptionUtils;
...@@ -66,8 +71,7 @@ import static ai.qiwu.com.xiaoduhome.common.Constants.CATEGORY_IMG_URL.*; ...@@ -66,8 +71,7 @@ import static ai.qiwu.com.xiaoduhome.common.Constants.CATEGORY_IMG_URL.*;
import static ai.qiwu.com.xiaoduhome.common.Constants.DPL_COMPONENT_ID.*; import static ai.qiwu.com.xiaoduhome.common.Constants.DPL_COMPONENT_ID.*;
import static ai.qiwu.com.xiaoduhome.common.Constants.ErrorMsg.*; import static ai.qiwu.com.xiaoduhome.common.Constants.ErrorMsg.*;
import static ai.qiwu.com.xiaoduhome.common.Constants.PRODUCT_INTRO.*; import static ai.qiwu.com.xiaoduhome.common.Constants.PRODUCT_INTRO.*;
import static ai.qiwu.com.xiaoduhome.common.Constants.WelcomeWord.ERROR_SEND_FLOWER; import static ai.qiwu.com.xiaoduhome.common.Constants.WelcomeWord.*;
import static ai.qiwu.com.xiaoduhome.common.Constants.WelcomeWord.FAIL_COLLECT;
import static ai.qiwu.com.xiaoduhome.common.Constants.XIAOWU_API.*; import static ai.qiwu.com.xiaoduhome.common.Constants.XIAOWU_API.*;
import static ai.qiwu.com.xiaoduhome.service.ScheduleService.*; import static ai.qiwu.com.xiaoduhome.service.ScheduleService.*;
import static ai.qiwu.com.xiaoduhome.xiaoai.service.XiaoAiService.LAST_OUTTIME_MARK; import static ai.qiwu.com.xiaoduhome.xiaoai.service.XiaoAiService.LAST_OUTTIME_MARK;
...@@ -85,29 +89,48 @@ public class DplBotService extends BaseBot { ...@@ -85,29 +89,48 @@ public class DplBotService extends BaseBot {
private static volatile RecommandDocument FUNNY_DEFAULT_DOCUMENT; private static volatile RecommandDocument FUNNY_DEFAULT_DOCUMENT;
// private static final ThreadLocal<Integer> CACHE_THREAD_INDEX = new ThreadLocal<>();
// 用来处理短时间内的多次请求 // 用来处理短时间内的多次请求
private static final ConcurrentHashMap<String, List<IntentRequest>> CACHE_XIAODU_REQUEST = new ConcurrentHashMap<>(); private static final ConcurrentHashMap<String, List<IntentRequest>> CACHE_XIAODU_REQUEST = new ConcurrentHashMap<>();
private static final ConcurrentHashMap<String, String> USERID_AUDIO_PATH = new ConcurrentHashMap<>();
static { static {
FIRST_PAGE = JSON.parseObject(DplbotServiceUtil.getDPLTemple("static/json/firstPage.json"), MyDocument.class); FIRST_PAGE = JSON.parseObject(DplbotServiceUtil.getDPLTemple("static/json/firstPage.json"), MyDocument.class);
} }
private static final String DU_DEVICE_ID = "2bf4f1ade0565b09bef2c529b03e163b"; private static final String FIRST_IMAGE = "https://didi-gz4.jiaoyou365.com/duai/image/Loading.png";
private static final String DU_DEVICE_ID = "XIAODU_2bf4f1ade0565b09bef2c529b03e163b";
private final int type;
public DplBotService(HttpServletRequest request) throws IOException { private final static Reprompt WAIT_WORD = new Reprompt(new OutputSpeech(OutputSpeech.SpeechType.PlainText, "晓悟正在等你的回复"));
public DplBotService(HttpServletRequest request, Integer type) throws IOException {
super(request); super(request);
this.type = type;
} }
@Override @Override
public Response onLaunch(LaunchRequest launchRequest) { public Response onLaunch(LaunchRequest launchRequest) {
if (getRequest().getContext().getScreen() == null) { if (getRequest().getContext().getScreen() == null) {
LAST_OUTTIME_MARK.remove(getDeviceId()); String deviceId = PREFIX_USERID+getDeviceId();
LAST_OUTTIME_RESULT.remove(getDeviceId()); LAST_OUTTIME_MARK.remove(deviceId);
OutputSpeech outputSpeech = new OutputSpeech(OutputSpeech.SpeechType.PlainText, WelcomeWord.WELCOME); LAST_OUTTIME_RESULT.remove(deviceId);
return new Response(outputSpeech); USERID_AUDIO_PATH.remove(deviceId);
String welcomeWord;
String skillName;
switch (type) {
case 1 : welcomeWord = WelcomeWord.WELCOME_SMART; skillName = SKILL_SMART; break;
case 2 : welcomeWord = WelcomeWord.WELCOME_NOVEL; skillName = SKILL_NOVEL; break;
case 3 : welcomeWord = WelcomeWord.WELCOME_STORY; skillName = SKILL_STORY; break;
case 4 : welcomeWord = WelcomeWord.WELCOME_LITERATURE; skillName = SKILL_LITERATURE; break;
default: welcomeWord = WelcomeWord.WELCOME; skillName = SKILL; break;
}
StandardCard standardCard = new StandardCard(skillName, welcomeWord);
standardCard.setImage(FIRST_IMAGE);
OutputSpeech outputSpeech = new OutputSpeech(OutputSpeech.SpeechType.PlainText, welcomeWord);
return new Response(outputSpeech, standardCard);
} }
RenderDocument renderDocument = new RenderDocument(FIRST_PAGE); RenderDocument renderDocument = new RenderDocument(FIRST_PAGE);
this.addDirective(renderDocument); this.addDirective(renderDocument);
...@@ -122,31 +145,23 @@ public class DplBotService extends BaseBot { ...@@ -122,31 +145,23 @@ public class DplBotService extends BaseBot {
return new Response(outputSpeech); return new Response(outputSpeech);
} }
@Override @Override
protected Response onInent(IntentRequest intentRequest) { protected Response onInent(IntentRequest intentRequest) {
final String userId = getUserId(); final String userId = getUserId();
if (getRequest().getContext().getScreen() == null) { if (getRequest().getContext().getScreen() == null) {
final String deviceUserId = getDeviceId(); final String deviceUserId = PREFIX_USERID + getDeviceId();
Byte overTimeType; Byte overTimeType;
if ((overTimeType = LAST_OUTTIME_MARK.get(deviceUserId)) != null) { String path;
try { if ((overTimeType = LAST_OUTTIME_MARK.remove(deviceUserId)) != null) {
//log.info("开始等待");
Thread.sleep(2000);
//log.info("等待OVER");
} catch (InterruptedException e) {
log.warn("等待中断");
}
OverTimeDetail lastData = LAST_OUTTIME_RESULT.get(deviceUserId); OverTimeDetail lastData = LAST_OUTTIME_RESULT.get(deviceUserId);
if (lastData != null) { if (lastData != null) {
for (Directive directive : lastData.getDirectives()) { for (Directive directive : lastData.getDirectives()) {
//log.info("上次超时保存的Directive:{}",directive.getClass().getName()); //log.info("上次超时保存的Directive:{}",directive.getClass().getName());
this.addDirective(directive); this.addDirective(directive);
} }
for (String key : lastData.getAttributes().keySet()) { for (Map.Entry<String, String> entry : lastData.getAttributes().entrySet()) {
//log.info("上次超时保存的key:{}",key); //log.info("上次超时保存的key:{}",key);
this.setSessionAttribute(key, lastData.getAttributes().get(key)); this.setSessionAttribute(entry.getKey(), entry.getValue());
} }
LAST_OUTTIME_MARK.remove(deviceUserId); LAST_OUTTIME_MARK.remove(deviceUserId);
LAST_OUTTIME_RESULT.remove(deviceUserId); LAST_OUTTIME_RESULT.remove(deviceUserId);
...@@ -158,10 +173,16 @@ public class DplBotService extends BaseBot { ...@@ -158,10 +173,16 @@ public class DplBotService extends BaseBot {
XiaoAiConstants.TTS.WAIT_WORD_2); XiaoAiConstants.TTS.WAIT_WORD_2);
} }
LAST_OUTTIME_MARK.remove(deviceUserId); LAST_OUTTIME_MARK.remove(deviceUserId);
} else if ((path = USERID_AUDIO_PATH.get(deviceUserId)) != null) {
Directive play = buildNoScreenPlayDirec(dealAudioUrl(path), AudioPlayerDirective.PlayBehaviorType.REPLACE_ALL);
addDirective(play);
log.error("小度音频播放开始事件未被触发:"+path);
dealWithFinishedNoCallEvent(deviceUserId);
return new Response();
} }
try { try {
Future future = DplbotServiceUtil.getPOOL().submit(() -> dealNoScreenIntent(intentRequest, deviceUserId)); Future future = DplbotServiceUtil.getPOOL().submit(() -> dealNoScreenIntentTemp(intentRequest, deviceUserId));
future.get(2500, TimeUnit.MILLISECONDS); future.get(2700, TimeUnit.MILLISECONDS);
} catch (InterruptedException | ExecutionException e) { } catch (InterruptedException | ExecutionException e) {
log.error("获取任务执行结果出错:{}", ExceptionUtils.getStackTrace(e)); log.error("获取任务执行结果出错:{}", ExceptionUtils.getStackTrace(e));
return buildErrorResponse(SORRY_UNCATCH); return buildErrorResponse(SORRY_UNCATCH);
...@@ -213,7 +234,19 @@ public class DplBotService extends BaseBot { ...@@ -213,7 +234,19 @@ public class DplBotService extends BaseBot {
return data.getResponse(); return data.getResponse();
} }
private void dealNoScreenIntent(IntentRequest intentRequest, String userId) { private void dealWithFinishedNoCallEvent(String userId) {
if (userId.equals(DU_DEVICE_ID)) {
DplbotServiceUtil.getPOOL().submit(() -> {
WebSocketLog.sendInfo("警告/小度音频播放开始事件未被触发,请将这一情况告知", "du1");
});
} else {
DplbotServiceUtil.getPOOL().submit(() -> {
WebSocketLog.sendInfo("警告/小度音频播放开始事件未被触发,请将这一情况告知", "du2");
});
}
}
private void dealNoScreenIntentTemp(IntentRequest intentRequest, String userId) {
String intentName = getIntent().getName(); String intentName = getIntent().getName();
OverTimeDetail data = new OverTimeDetail(); OverTimeDetail data = new OverTimeDetail();
LAST_OUTTIME_RESULT.put(userId, data); LAST_OUTTIME_RESULT.put(userId, data);
...@@ -231,7 +264,6 @@ public class DplBotService extends BaseBot { ...@@ -231,7 +264,6 @@ public class DplBotService extends BaseBot {
List<IntentRequest> requestList = CACHE_XIAODU_REQUEST.get(userId); List<IntentRequest> requestList = CACHE_XIAODU_REQUEST.get(userId);
try { try {
if (requestList == null) { if (requestList == null) {
// CACHE_THREAD_INDEX.set(1);
requestList = new ArrayList<>(); requestList = new ArrayList<>();
requestList.add(intentRequest); requestList.add(intentRequest);
CACHE_XIAODU_REQUEST.put(userId, requestList); CACHE_XIAODU_REQUEST.put(userId, requestList);
...@@ -239,8 +271,7 @@ public class DplBotService extends BaseBot { ...@@ -239,8 +271,7 @@ public class DplBotService extends BaseBot {
int i = 1; int i = 1;
int j; int j;
int count = 0; int count = 0;
while (i != (j = CACHE_XIAODU_REQUEST.get(userId).size()) && count < 9) { while (i != (j = CACHE_XIAODU_REQUEST.get(userId).size()) && count < 5) {
// CACHE_THREAD_INDEX.set(i);
i = j; i = j;
Thread.sleep(100); Thread.sleep(100);
++count; ++count;
...@@ -257,43 +288,61 @@ public class DplBotService extends BaseBot { ...@@ -257,43 +288,61 @@ public class DplBotService extends BaseBot {
return; return;
} }
final Query query = intentRequest.getQuery(); final Query query = intentRequest.getQuery();
String userWord = null; final String userWord = query.getOriginal();
if (query != null) userWord = query.getOriginal(); // if (query != null) userWord = query.getOriginal();
if (userWord == null){ if (userWord == null){
log.warn("小度没有传来任何话语"); log.warn("小度没有传来任何话语");
data.setResponse(buildErrorResponse(ErrorMsg.SORRY_UNCATCH)); data.setResponse(buildErrorResponse(ErrorMsg.SORRY_UNCATCH));
return; return;
} }
log.info("小度.用户说的话:{}, requestID:{}",userWord, intentRequest.getRequestId()); log.info("小度.用户说的话:{}, requestID:{}",userWord, intentRequest.getRequestId());
QiWuResponse response; String response = RequestTerminal.requestTerminateTemp(userWord, userId, type);
boolean deviceMark; log.info("小度,小悟返回:{},",response);
if ((deviceMark = DU_DEVICE_ID.equals(getDeviceId()))) { if (StringUtils.isBlank(response)) {
response = RequestTerminal.requestTerminate(userWord, DU_DEVICE_ID); data.setResponse(buildErrorResponse(ErrorMsg.SORRY_UNCATCH));
} else { return;
response = RequestTerminal.requestTerminateDU2(userWord, getDeviceId());
} }
log.info("小度,小悟返回:{}, audioUrl:{}",response.getText(),response.getAudio()); // String mark = RandomStringUtils.randomAlphabetic(3);
if (StringUtils.isBlank(response.getAudio())) { // AudioBoxData pathData = new AudioBoxData();
// OkHttp3Utils.asyncPost(XiaoAiConstants.TTS_DIDI3, response, pathData);
String path = OkHttp3Utils.doPostJsonStr(XiaoAiConstants.TTS_DIDI3, response);
if (StringUtils.isBlank(path)) {
log.error("小度没有获取到音频链接");
data.setResponse(buildErrorResponse(ErrorMsg.SORRY_UNCATCH)); data.setResponse(buildErrorResponse(ErrorMsg.SORRY_UNCATCH));
return; return;
} }
if (!ScheduleService.getExceptBotAccount().contains(response.getAipioneerUsername())) { final JSONObject ob = JSONObject.parseObject(response);
String beforeBotAccount = getSessionAttribute("botAcc"); String botAcc = ob.getString("aipioneerUsername");
if (StringUtils.isBlank(beforeBotAccount) || !beforeBotAccount.equals(response.getAipioneerUsername())) { String beforeBotAccount = getSessionAttribute("botAcc");
setSessionAttribute("botAcc", response.getAipioneerUsername()); if (StringUtils.isBlank(beforeBotAccount) || !beforeBotAccount.equals(botAcc)) {
data.getAttributes().put("botAcc",response.getAipioneerUsername()); setSessionAttribute("botAcc", botAcc);
} data.getAttributes().put("botAcc",botAcc);
} }
Directive directive = buildNoScreenPlayDirec(response.getAudio(), AudioPlayerDirective.PlayBehaviorType.REPLACE_ALL);
addDirective(directive); Directive play = buildNoScreenPlayDirec(dealAudioUrl(path), AudioPlayerDirective.PlayBehaviorType.REPLACE_ALL);
data.getDirectives().add(directive); addDirective(play);
final String word = userWord; data.getDirectives().add(play);
if (deviceMark) { USERID_AUDIO_PATH.put(userId, path);
DplbotServiceUtil.getPOOL().submit(() -> WebSocketLog.sendInfo(new StringBuilder(word).append(File.separator) if (userId.equals(DU_DEVICE_ID)) {
.append(response.getText()).toString(), "du1")); DplbotServiceUtil.getPOOL().submit(() -> {
JSONArray array = ob.getJSONArray("dialogs");
StringBuilder builder = new StringBuilder(userWord).append(File.separator);
for (Object item: array) {
String str = ((JSONObject) item).getString("text");
builder.append(str.replaceAll("\\{/.*?/}", "")).append(";");
}
WebSocketLog.sendInfo(builder.toString(), "du1");
});
} else { } else {
DplbotServiceUtil.getPOOL().submit(() -> WebSocketLog.sendInfo(new StringBuilder(word).append(File.separator) DplbotServiceUtil.getPOOL().submit(() -> {
.append(response.getText()).toString(), "du2")); JSONArray array = ob.getJSONArray("dialogs");
StringBuilder builder = new StringBuilder(userWord).append(File.separator);
for (Object item: array) {
String str = ((JSONObject) item).getString("text");
builder.append(str.replaceAll("\\{/.*?/}", "")).append(";");
}
WebSocketLog.sendInfo(builder.toString(), "du2");
});
} }
} catch (Exception e) { } catch (Exception e) {
log.warn("中控返回结果为空"); log.warn("中控返回结果为空");
...@@ -305,11 +354,14 @@ public class DplBotService extends BaseBot { ...@@ -305,11 +354,14 @@ public class DplBotService extends BaseBot {
requestList.notifyAll(); requestList.notifyAll();
} }
} }
// CACHE_THREAD_INDEX.remove();
CACHE_XIAODU_REQUEST.remove(userId); CACHE_XIAODU_REQUEST.remove(userId);
} }
} }
private String dealAudioUrl(String path) {
return Constants.TTS_DIDI3_GET+path;
}
private void dealNoScreenSendFlowerIntent(String userId, OverTimeDetail data) { private void dealNoScreenSendFlowerIntent(String userId, OverTimeDetail data) {
if (getAccessToken() == null) { if (getAccessToken() == null) {
data.setResponse(buildErrorResponse("该功能需要登录")); data.setResponse(buildErrorResponse("该功能需要登录"));
...@@ -396,7 +448,7 @@ public class DplBotService extends BaseBot { ...@@ -396,7 +448,7 @@ public class DplBotService extends BaseBot {
log.info("进入作品语句:{}", enterProductWord); log.info("进入作品语句:{}", enterProductWord);
QiWuResponse data = null; QiWuResponse data = null;
try { try {
data = RequestTerminal.requestTerminate(enterProductWord, getUserId()); data = RequestTerminal.requestTerminate(enterProductWord, getUserId(), type);
} catch (IOException e) { } catch (IOException e) {
log.error("请求终端接口出错:", e.toString()); log.error("请求终端接口出错:", e.toString());
} }
...@@ -518,7 +570,7 @@ public class DplBotService extends BaseBot { ...@@ -518,7 +570,7 @@ public class DplBotService extends BaseBot {
log.info("进入作品语句:{}", enterProductWord); log.info("进入作品语句:{}", enterProductWord);
QiWuResponse data = null; QiWuResponse data = null;
try { try {
data = RequestTerminal.requestTerminate(enterProductWord, getUserId()); data = RequestTerminal.requestTerminate(enterProductWord, getUserId(), type);
} catch (IOException e) { } catch (IOException e) {
log.error("请求终端接口出错:", e.toString()); log.error("请求终端接口出错:", e.toString());
} }
...@@ -620,14 +672,21 @@ public class DplBotService extends BaseBot { ...@@ -620,14 +672,21 @@ public class DplBotService extends BaseBot {
case EXCEEDED_MAX_REPROMPTS: log.info(EndMsg.CAN_NOT_UNDERSTAND);break; case EXCEEDED_MAX_REPROMPTS: log.info(EndMsg.CAN_NOT_UNDERSTAND);break;
} }
if (getRequest().getContext().getScreen() == null) { if (getRequest().getContext().getScreen() == null) {
LAST_OUTTIME_MARK.remove(getDeviceId()); String deviceId = PREFIX_USERID+getDeviceId();
LAST_OUTTIME_RESULT.remove(getDeviceId()); LAST_OUTTIME_MARK.remove(deviceId);
OutputSpeech outputSpeech = new OutputSpeech(OutputSpeech.SpeechType.PlainText, EndMsg.BYE_BYE); LAST_OUTTIME_RESULT.remove(deviceId);
USERID_AUDIO_PATH.remove(deviceId);
String byeWord = EndMsg.END_BYE_Adult;
switch (type) {
case 1:
case 3: byeWord = EndMsg.END_BYE_CHILD;break;
}
OutputSpeech outputSpeech = new OutputSpeech(OutputSpeech.SpeechType.PlainText, byeWord);
try { try {
if (DU_DEVICE_ID.equals(getDeviceId())) { if (DU_DEVICE_ID.equals(deviceId)) {
RequestTerminal.backRequest(DU_DEVICE_ID); RequestTerminal.backRequest(DU_DEVICE_ID, type);
} else { } else {
RequestTerminal.backRequestDU2(getDeviceId()); RequestTerminal.backRequestDU2(deviceId, type);
} }
} catch (Exception e) { } catch (Exception e) {
log.warn("用户退出向中控发出退出指令出错"); log.warn("用户退出向中控发出退出指令出错");
...@@ -838,6 +897,41 @@ public class DplBotService extends BaseBot { ...@@ -838,6 +897,41 @@ public class DplBotService extends BaseBot {
return new Response(outputSpeech); return new Response(outputSpeech);
} }
private Response buildNoScreenListCardResponse(String content, String botAccount) {
Pattern pattern = Pattern.compile(Utils.getRegexSeperate());
List<String> actors = DplbotServiceUtil.seperateActor(content, pattern);
String[] actorWord = DplbotServiceUtil.seperateActorWord(content, pattern);
int i = 0;
ListCard listCard = new ListCard();
for (String actor: actors) {
StandardCardInfo cardInfo = new StandardCardInfo(actor, actorWord[i++].replaceAll("<br>","\n"));
cardInfo.setImage(ScheduleService.getAsideImgUrl(botAccount, actor));
listCard.getList().add(cardInfo);
}
// content = buildText(content);
return new Response(null, listCard, WAIT_WORD);
}
private Response buildNoScreenTextCardREsponse(String content) {
content = buildText(content);
TextCard textCard = new TextCard(content);
return new Response(null, textCard, WAIT_WORD);
}
private String buildText(String text) {
Pattern pattern = Pattern.compile(Utils.getRegexSeperate());
StringBuilder builder = new StringBuilder();
List<String> actors = DplbotServiceUtil.seperateActor(text, pattern);
String[] word = DplbotServiceUtil.seperateActorWord(text, pattern);
int i = 0;
for (String actor: actors) {
builder.append(actor).append(":").append(word[i].replaceAll("<br>", "\n")).append("\n");
i++;
}
if (builder.length() == 0) builder.append(text);
return builder.toString();
}
private void backToBotIntro(String botAccount, OverTimeDetail detail) { private void backToBotIntro(String botAccount, OverTimeDetail detail) {
OnProductDetail productDetail = ScheduleService.PRODUCT_ID_DETAIL.get(botAccount); OnProductDetail productDetail = ScheduleService.PRODUCT_ID_DETAIL.get(botAccount);
// product picture // product picture
...@@ -907,7 +1001,7 @@ public class DplBotService extends BaseBot { ...@@ -907,7 +1001,7 @@ public class DplBotService extends BaseBot {
// 异步发送“退出”给终端 // 异步发送“退出”给终端
private void sendCancellToTerminate(String userId){ private void sendCancellToTerminate(String userId){
RequestTerminal.backRequest(userId); RequestTerminal.backRequest(userId, type);
} }
class Task implements Runnable{ class Task implements Runnable{
...@@ -1756,7 +1850,7 @@ public class DplBotService extends BaseBot { ...@@ -1756,7 +1850,7 @@ public class DplBotService extends BaseBot {
} }
QiWuResponse data = null; QiWuResponse data = null;
try { try {
data = RequestTerminal.requestTerminate(word, userId); data = RequestTerminal.requestTerminate(word, userId, type);
} catch (Exception e) { } catch (Exception e) {
log.error("请求终端接口出错:", e.toString()); log.error("请求终端接口出错:", e.toString());
} }
...@@ -1948,7 +2042,7 @@ public class DplBotService extends BaseBot { ...@@ -1948,7 +2042,7 @@ public class DplBotService extends BaseBot {
log.info("进入作品语句:{}", enterProductWord); log.info("进入作品语句:{}", enterProductWord);
QiWuResponse data = null; QiWuResponse data = null;
try { try {
data = RequestTerminal.requestTerminate(enterProductWord, getUserId()); data = RequestTerminal.requestTerminate(enterProductWord, getUserId(), type);
} catch (IOException e) { } catch (IOException e) {
log.error("请求终端接口出错:", e.toString()); log.error("请求终端接口出错:", e.toString());
} }
...@@ -2150,6 +2244,7 @@ public class DplBotService extends BaseBot { ...@@ -2150,6 +2244,7 @@ public class DplBotService extends BaseBot {
// log.info("音频播放完毕,开麦"); // log.info("音频播放完毕,开麦");
// setSessionAttribute("botAcc",getSessionAttribute("botAcc")); // setSessionAttribute("botAcc",getSessionAttribute("botAcc"));
this.setExpectSpeech(true); this.setExpectSpeech(true);
log.error("FinishedEvent");
return new Response(); return new Response();
} }
...@@ -2160,11 +2255,10 @@ public class DplBotService extends BaseBot { ...@@ -2160,11 +2255,10 @@ public class DplBotService extends BaseBot {
return new Response(); return new Response();
} }
@Override @Override
protected Response onPlaybackStartedEvent(PlaybackStartedEvent playbackStartedEvent) { protected Response onPlaybackStartedEvent(PlaybackStartedEvent playbackStartedEvent) {
// setSessionAttribute("botAcc",getSessionAttribute("botAcc")); // setSessionAttribute("botAcc",getSessionAttribute("botAcc"));
USERID_AUDIO_PATH.remove(PREFIX_USERID + getDeviceId());
waitAnswer(); waitAnswer();
return new Response(); return new Response();
} }
......
...@@ -629,7 +629,7 @@ public class DplbotServiceUtil { ...@@ -629,7 +629,7 @@ public class DplbotServiceUtil {
return name; return name;
} }
static List<String> seperateActor(String text, Pattern pattern) { public static List<String> seperateActor(String text, Pattern pattern) {
Matcher matcher = pattern.matcher(text); Matcher matcher = pattern.matcher(text);
List<String> actorList = new ArrayList<>(); List<String> actorList = new ArrayList<>();
while (matcher.find()) { while (matcher.find()) {
...@@ -640,7 +640,7 @@ public class DplbotServiceUtil { ...@@ -640,7 +640,7 @@ public class DplbotServiceUtil {
return actorList; return actorList;
} }
static String[] seperateActorWord(String text, Pattern pattern) { public static String[] seperateActorWord(String text, Pattern pattern) {
String[] actorWords = pattern.split(text); String[] actorWords = pattern.split(text);
if (StringUtils.startsWith(text.trim(), "【")) { if (StringUtils.startsWith(text.trim(), "【")) {
actorWords = ArrayUtils.remove(actorWords, 0); actorWords = ArrayUtils.remove(actorWords, 0);
......
...@@ -6,6 +6,7 @@ import ai.qiwu.com.xiaoduhome.common.Utils; ...@@ -6,6 +6,7 @@ import ai.qiwu.com.xiaoduhome.common.Utils;
import ai.qiwu.com.xiaoduhome.pojo.QiWuRequest; import ai.qiwu.com.xiaoduhome.pojo.QiWuRequest;
import ai.qiwu.com.xiaoduhome.pojo.QiWuResponse; import ai.qiwu.com.xiaoduhome.pojo.QiWuResponse;
import ai.qiwu.com.xiaoduhome.pojo.playAside.AsideImageResponse; import ai.qiwu.com.xiaoduhome.pojo.playAside.AsideImageResponse;
import ai.qiwu.com.xiaoduhome.spirit.SpiritTerminateRequest;
import com.alibaba.fastjson.JSON; import com.alibaba.fastjson.JSON;
import lombok.extern.slf4j.Slf4j; import lombok.extern.slf4j.Slf4j;
import org.slf4j.Logger; import org.slf4j.Logger;
...@@ -22,48 +23,84 @@ import java.util.Random; ...@@ -22,48 +23,84 @@ import java.util.Random;
@Slf4j @Slf4j
class RequestTerminal { class RequestTerminal {
static QiWuResponse requestTerminate(String userWord, String userId) throws IOException { static String requestTerminateTemp(String userWord, String userId, int type) throws IOException {
SpiritTerminateRequest requestPojo = new SpiritTerminateRequest();
requestPojo.setUid(userId);
requestPojo.setMsg(userWord);
String requestJsonStr = JSON.toJSONString(requestPojo);
// log.info("向小悟发送的请求信息:{}", requestJsonStr);
HashMap<String, String> headers = new HashMap<>();
headers.put("Content-Type", "application/json;charset=utf-8");
switch (type) {
case 1 :
case 3 : headers.put("App-Channel-Id", "jiaoyou-audio-child-test");break;
case 2 :
case 4 : headers.put("App-Channel-Id", "jiaoyou-audio-adult-test");break;
default: headers.put("App-Channel-Id", "jiaoyou-audio-test");
}
return OkHttp3Utils.doPostJsonStr(Constants.QI_WU_INTERFACE, requestJsonStr, headers);
}
static QiWuResponse requestTerminate(String userWord, String userId, int type) throws IOException {
QiWuRequest requestPojo = new QiWuRequest(); QiWuRequest requestPojo = new QiWuRequest();
requestPojo.setUid(userId); requestPojo.setUid(userId);
// requestPojo.setAccess(Constants.SERVICE_NAME); // requestPojo.setAccess(Constants.SERVICE_NAME);
requestPojo.setMsg(userWord); requestPojo.setMsg(userWord);
String requestJsonStr = JSON.toJSONString(requestPojo); String requestJsonStr = JSON.toJSONString(requestPojo);
// log.info("向小悟发送的请求信息:{}", requestJsonStr); // log.info("向小悟发送的请求信息:{}", requestJsonStr);
String resStr = OkHttp3Utils.doPostJsonStr(Constants.QI_WU_INTERFACE, requestJsonStr); HashMap<String, String> headers = new HashMap<>();
headers.put("Content-Type", "application/json;charset=utf-8");
switch (type) {
case 1 :
case 3 : headers.put("App-Channel-Id", "jiaoyou-audio-child-test");break;
case 2 :
case 4 : headers.put("App-Channel-Id", "jiaoyou-audio-adult-test");break;
default: headers.put("App-Channel-Id", "jiaoyou-audio-test");
}
String resStr = OkHttp3Utils.doPostJsonStr(Constants.QI_WU_INTERFACE, requestJsonStr, headers);
if (resStr == null) return null; if (resStr == null) return null;
// log.info("返回信息:{}", resStr); // log.info("返回信息:{}", resStr);
return JSON.parseObject(resStr, QiWuResponse.class); return JSON.parseObject(resStr, QiWuResponse.class);
} }
static QiWuResponse requestTerminateDU2(String userWord, String userId) throws IOException { static QiWuResponse requestTerminateDU2(String userWord, String userId, int type) throws IOException {
QiWuRequest requestPojo = new QiWuRequest(); QiWuRequest requestPojo = new QiWuRequest();
requestPojo.setUid(userId); requestPojo.setUid(userId);
// requestPojo.setAccess(Constants.SERVICE_NAME); // requestPojo.setAccess(Constants.SERVICE_NAME);
requestPojo.setMsg(userWord); requestPojo.setMsg(userWord);
String requestJsonStr = JSON.toJSONString(requestPojo); String requestJsonStr = JSON.toJSONString(requestPojo);
// log.info("向小悟发送的请求信息:{}", requestJsonStr); // log.info("向小悟发送的请求信息:{}", requestJsonStr);
String resStr = OkHttp3Utils.doPostJsonStr(Constants.INTERFACE_DI, requestJsonStr); HashMap<String, String> headers = new HashMap<>();
headers.put("Content-Type", "application/json;charset=utf-8");
switch (type) {
case 1 :
case 3 : headers.put("App-Channel-Id", "jiaoyou-audio-child-test");break;
case 2 :
case 4 : headers.put("App-Channel-Id", "jiaoyou-audio-adult-test");break;
default: headers.put("App-Channel-Id", "jiaoyou-audio-test");
}
String resStr = OkHttp3Utils.doPostJsonStr(Constants.INTERFACE_DI, requestJsonStr, headers);
if (resStr == null) return null; if (resStr == null) return null;
// log.info("返回信息:{}", resStr); // log.info("返回信息:{}", resStr);
return JSON.parseObject(resStr, QiWuResponse.class); return JSON.parseObject(resStr, QiWuResponse.class);
} }
static void backRequest(String userId) { static void backRequest(String userId, int type) {
QiWuRequest requestPojo = new QiWuRequest(); QiWuRequest requestPojo = new QiWuRequest();
requestPojo.setUid(userId); requestPojo.setUid(userId);
// requestPojo.setAccess(Constants.SERVICE_NAME); // requestPojo.setAccess(Constants.SERVICE_NAME);
requestPojo.setMsg("退出"); requestPojo.setMsg("退出当前作品");
String requestJsonStr = JSON.toJSONString(requestPojo); String requestJsonStr = JSON.toJSONString(requestPojo);
OkHttp3Utils.backPostAsync(Constants.QI_WU_INTERFACE, requestJsonStr); OkHttp3Utils.backPostAsync(Constants.QI_WU_INTERFACE, requestJsonStr, type);
} }
static void backRequestDU2(String userId) { static void backRequestDU2(String userId, int type) {
QiWuRequest requestPojo = new QiWuRequest(); QiWuRequest requestPojo = new QiWuRequest();
requestPojo.setUid(userId); requestPojo.setUid(userId);
// requestPojo.setAccess(Constants.SERVICE_NAME); // requestPojo.setAccess(Constants.SERVICE_NAME);
requestPojo.setMsg("退出"); requestPojo.setMsg("退出当前作品");
String requestJsonStr = JSON.toJSONString(requestPojo); String requestJsonStr = JSON.toJSONString(requestPojo);
OkHttp3Utils.backPostAsync(Constants.INTERFACE_DI, requestJsonStr); OkHttp3Utils.backPostAsync(Constants.INTERFACE_DI, requestJsonStr, type);
} }
public static void main(String[] args) throws IOException { public static void main(String[] args) throws IOException {
......
...@@ -164,7 +164,7 @@ public class ResponseEncapsulation extends AudioPlayer { ...@@ -164,7 +164,7 @@ public class ResponseEncapsulation extends AudioPlayer {
}else { }else {
QiWuResponse data = null; QiWuResponse data = null;
try { try {
data = RequestTerminal.requestTerminate(userId, userWord); data = RequestTerminal.requestTerminate(userId, userWord, 1);
} catch (Exception e) { } catch (Exception e) {
log.error("请求终端接口出错:{}", e.toString()); log.error("请求终端接口出错:{}", e.toString());
} }
......
...@@ -16,8 +16,11 @@ import ai.qiwu.com.xiaoduhome.repository.primary.ProjectLabelRepository; ...@@ -16,8 +16,11 @@ import ai.qiwu.com.xiaoduhome.repository.primary.ProjectLabelRepository;
import ai.qiwu.com.xiaoduhome.repository.secondary.XiaoDuHistoryTBRepository; import ai.qiwu.com.xiaoduhome.repository.secondary.XiaoDuHistoryTBRepository;
import ai.qiwu.com.xiaoduhome.repository.secondary.XiaoDuOrderTbRepository; import ai.qiwu.com.xiaoduhome.repository.secondary.XiaoDuOrderTbRepository;
import com.alibaba.fastjson.JSON; import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import lombok.extern.slf4j.Slf4j; import lombok.extern.slf4j.Slf4j;
import okhttp3.OkHttpClient; import okhttp3.OkHttpClient;
import org.apache.commons.lang3.StringUtils;
import org.apache.commons.lang3.exception.ExceptionUtils; import org.apache.commons.lang3.exception.ExceptionUtils;
import org.springframework.beans.factory.InitializingBean; import org.springframework.beans.factory.InitializingBean;
import org.springframework.beans.factory.annotation.Autowired; import org.springframework.beans.factory.annotation.Autowired;
...@@ -72,6 +75,8 @@ public class ScheduleService implements InitializingBean { ...@@ -72,6 +75,8 @@ public class ScheduleService implements InitializingBean {
static volatile Long curTime = System.currentTimeMillis(); static volatile Long curTime = System.currentTimeMillis();
public static volatile Map<String, String> channelId2RecommendBotAcc = new HashMap<>();
@Autowired @Autowired
public ScheduleService(GameProjectTbRepository gameProjectTbRepository, public ScheduleService(GameProjectTbRepository gameProjectTbRepository,
ProjectLabelRepository projectLabelRepository, ProjectLabelRepository projectLabelRepository,
...@@ -218,6 +223,36 @@ public class ScheduleService implements InitializingBean { ...@@ -218,6 +223,36 @@ public class ScheduleService implements InitializingBean {
}).start(); }).start();
} }
@Scheduled(cron = "0 */30 * * * ?")
public void getAllChannelRecommendBotAccount() {
String response = null;
int count = 1;
Map<String, String> map = new HashMap<>();
do {
try {
Thread.sleep(count*5);
response = OkHttp3Utils.doGet("http://didi-gz4.jiaoyou365.com:8070/api/sdk/botConfig/all");
JSONArray array = JSONObject.parseArray(response);
if (array != null) {
for (Object o: array) {
JSONObject object = (JSONObject) o;
if (Boolean.FALSE.equals(object.getBoolean("auth"))) {
map.put(object.getString("appChannelId"), object.getString("recommendBotAccount"));
}
}
}
} catch (Exception e) {
log.error("getAllChannelRecommendBotAccount:{}",e);
}
if (StringUtils.isBlank(response)) log.warn("第"+count+"次获取channelId失败");
count++;
} while (StringUtils.isBlank(response) && count < 5);
if (map.size() != 0) {
channelId2RecommendBotAcc = map;
log.error("audio channelId list:"+map);
}
}
private void getAsideImg() { private void getAsideImg() {
DplbotServiceUtil.getPOOL().submit(() -> { DplbotServiceUtil.getPOOL().submit(() -> {
List<String> botIds = gameProjectTbRepository.getAllOnTableProductIds(); List<String> botIds = gameProjectTbRepository.getAllOnTableProductIds();
......
package ai.qiwu.com.xiaoduhome.spirit;
import com.fasterxml.jackson.annotation.JsonIgnoreProperties;
import lombok.Getter;
import lombok.Setter;
import lombok.ToString;
/**
* @author 苗权威
* @dateTime 19-12-11 下午3:40
*/
@Getter
@Setter
@ToString
@JsonIgnoreProperties(ignoreUnknown = true)
public class Dialog {
private String botAccount;
private String npcName;
private String person;
private String text;
private String tone;
private String pitch;
private String speed;
private String volume;
}
package ai.qiwu.com.xiaoduhome.spirit;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.csv.CSVFormat;
import org.apache.commons.csv.CSVParser;
import org.apache.commons.csv.CSVRecord;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.InitializingBean;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;
import org.springframework.util.DigestUtils;
import java.io.BufferedReader;
import java.io.File;
import java.io.FileInputStream;
import java.io.InputStreamReader;
import java.nio.charset.Charset;
import java.nio.charset.StandardCharsets;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
/**
* @author 苗权威
* @dateTime 19-12-11 下午4:15
*/
@Component
@Slf4j
public class InitialData implements InitializingBean {
@Value("${csvDic}")
private String csvDic;
private static volatile Map<String, Map<String, Map<String, String>>> recordMap;
private static volatile Map<String, Map<String, Map<String, Map<String, String>>>> audioMap;
static volatile Map<String, Boolean> botAccount2ItsCache;
static {
recordMap = new HashMap<>();
audioMap = new HashMap<>();
botAccount2ItsCache = new HashMap<>();
}
@Override
public void afterPropertiesSet() throws Exception {
try {
File[] csvFiles = new File(csvDic).listFiles((dir, name) -> StringUtils.endsWith(name, ".csv"));
if (csvFiles != null && csvFiles.length != 0) {
CSVParser reader;
for (File file: csvFiles) {
String fileName = file.getName();
int i = fileName.indexOf("_");
String botAccount = fileName.substring(0, i);
boolean record = Integer.valueOf(fileName.substring(i+1, i+2)) == 1;
reader = CSVFormat.EXCEL.parse(new BufferedReader(new InputStreamReader(
new FileInputStream(file), Charset.forName("UTF-8"))));
if (record) {
if (recordMap.containsKey(botAccount)) {
log.error("重复:{}",fileName);
continue;
}
Map<String, Map<String, String>> npcName2nameId = recordMap.computeIfAbsent(botAccount, s -> new HashMap<>());
int j = 0;
// "person", "mood", "md5", "id", "text", "upUrl"
for (CSVRecord line: reader) {
if (j == 0) {
j++;
continue;
}
String npcName = line.get(0);
String md5 = line.get(2);
md5 = md5.substring(0, md5.indexOf("."));
String id = line.get(3);
Map<String, String> mp3Name2Id = npcName2nameId.computeIfAbsent(npcName, s -> new HashMap<>());
mp3Name2Id.put(md5, id);
}
botAccount2ItsCache.put(botAccount, true);
} else {
if (audioMap.containsKey(botAccount)) {
log.error("重复:{}",fileName);
continue;
}
Map<String, Map<String, Map<String, String>>> person2toneMd5Id = audioMap.computeIfAbsent(botAccount, s -> new HashMap<>());
int j = 0;
for (CSVRecord line: reader) {
if (j == 0) {
j++;
continue;
}
String person = line.get(0);
String mood = line.get(1);
String md5 = line.get(2);
if (StringUtils.endsWith(md5, ".wav")) continue;
md5 = md5.substring(0, md5.indexOf("."));
String id = line.get(3);
Map<String, Map<String, String>> tone2Md5Id = person2toneMd5Id.computeIfAbsent(person, s -> new HashMap<>());
Map<String, String> md52Id = tone2Md5Id.computeIfAbsent(mood, s -> new HashMap<>());
md52Id.put(md5, id);
}
botAccount2ItsCache.put(botAccount, false);
}
reader.close();
}
} else {
log.warn("没有数据文件");
}
} catch (Exception e) {
log.error(e.toString());
}
}
static String getRecordId(String botAccount, String npcName, String text) {
Map<String, Map<String, String>> npcName2Md5Id = recordMap.get(botAccount);
if (npcName2Md5Id != null) {
Map<String, String> md52Id = npcName2Md5Id.get(npcName);
if (md52Id != null) {
return md52Id.get(buildMd5Name(text));
}
}
return null;
}
static String getAudioId(String botAccount, String person, String mood, String text) {
Map<String, Map<String, Map<String, String>>> person2MoodMd5Id = audioMap.get(botAccount);
if (person2MoodMd5Id != null) {
Map<String, Map<String, String>> mood2Md5Id = person2MoodMd5Id.get(person);
if (mood2Md5Id != null) {
Map<String, String> md52Id = mood2Md5Id.get(mood);
if (md52Id != null) {
return md52Id.get(buildMd5Name(text));
}
}
}
return null;
}
private static String buildMd5Name(String text) {
return DigestUtils.md5DigestAsHex(text.getBytes(StandardCharsets.UTF_8));
}
public static void main(String[] args) {
System.out.println(new File("/home/yf01/下载/out.mp3").getName());
}
}
package ai.qiwu.com.xiaoduhome.spirit;
import ai.qiwu.com.xiaoduhome.common.OkHttp3Utils;
import ai.qiwu.com.xiaoduhome.common.Utils;
import ai.qiwu.com.xiaoduhome.service.DplbotServiceUtil;
import ai.qiwu.com.xiaoduhome.xiaoai.common.XiaoAiConstants;
import com.alibaba.da.coin.ide.spi.meta.Action;
import com.alibaba.da.coin.ide.spi.meta.AskedInfoMsg;
import com.alibaba.da.coin.ide.spi.meta.ExecuteCode;
import com.alibaba.da.coin.ide.spi.meta.ResultType;
import com.alibaba.da.coin.ide.spi.standard.TaskQuery;
import com.alibaba.da.coin.ide.spi.standard.TaskResult;
import com.alibaba.fastjson.JSON;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.RandomUtils;
import org.apache.commons.lang3.StringUtils;
import org.apache.commons.lang3.exception.ExceptionUtils;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;
import java.io.*;
import java.util.*;
import java.util.concurrent.*;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import java.util.stream.Collectors;
import static ai.qiwu.com.xiaoduhome.spirit.InitialData.botAccount2ItsCache;
import static ai.qiwu.com.xiaoduhome.xiaoai.service.XiaoAiService.LAST_OUTTIME_MARK;
import static ai.qiwu.com.xiaoduhome.xiaoai.service.XiaoAiService.OUTTIME_TYPE_0;
/**
* 解析请求参数,构造向终端接口发送打数据打JSON,之后得到响应数据,提取构造返回给天猫的响应数据
* @author 苗权威
* @dateTime 2019/6/18
*/
@Service
@Slf4j
public class SpiritService {
private static final String AB_REGEX = "\uD83C\uDD70(.*?)\uD83C\uDD71";
private static final ConcurrentHashMap<String, TaskResult> LAST_OUTTIME_RESULT = new ConcurrentHashMap<>();
/**
* 获取返回给天猫的数据
* @param request 请求参数
* @return 返回数据封装在开发包中的TaskResult
*/
public TaskResult getResponse(TaskQuery request, int type) {
return getNeededParam(request, type);
}
/**
* 解析获取需要的参数信息:用户的话,用户的id,意图id
* @param request 请求参数
* @return 返回数据封装在开发包中的TaskResult
*/
private TaskResult getNeededParam(TaskQuery request, int type) {
String userId = getUserId(request);
if (StringUtils.isBlank(userId)) return buildTextTaskResult("不好意思好像出了什么问题,正在抓紧修复中", request.getIntentId());
Long intentId = request.getIntentId();
Byte waitType;
if ((waitType=LAST_OUTTIME_MARK.remove(userId)) != null) {
if (waitType < 2) {
if (LAST_OUTTIME_RESULT.get(userId) == null) {
LAST_OUTTIME_MARK.put(userId, (byte) (waitType+1));
return buildTextTaskResult((RandomUtils.nextInt() & 1) == 1 ? XiaoAiConstants.TTS.WAIT_WORD_1 :
XiaoAiConstants.TTS.WAIT_WORD_2, intentId);
}
return LAST_OUTTIME_RESULT.remove(userId);
}
}
String userWord = request.getUtterance();
log.info("天猫精灵用户说的话:"+userWord);
try {
Future<TaskResult> future = DplbotServiceUtil.getPOOL().submit(() -> requestTerminate(userId, userWord, type, intentId));
return future.get(1700, TimeUnit.MILLISECONDS);
} catch (InterruptedException | ExecutionException e) {
log.error("天猫精灵出现问题:{}", ExceptionUtils.getStackTrace(e));
} catch (TimeoutException e) {
log.warn("超时");
LAST_OUTTIME_MARK.put(userId, OUTTIME_TYPE_0);
return buildTextTaskResult("不好意思晓悟没有听清您刚才说的话,请再重复一遍吧", intentId);
}
return buildTextTaskResult("不好意思请再说一遍吧", intentId);
}
private TaskResult requestTerminate(String userId, String userWord, Integer type, Long intentId) throws IOException {
SpiritTerminateRequest requestPojo = new SpiritTerminateRequest();
requestPojo.setUid(userId);
// requestPojo.setAccess(XiaoAiConstants.DEVICE_NAME);
requestPojo.setMsg(userWord);
String requestJsonStr = JSON.toJSONString(requestPojo);
//log.info("向终端发出请求的参数信息:{}", requestJsonStr);
HashMap<String, String> headers = new HashMap<>();
headers.put("Content-Type", "application/json;charset=utf-8");
String channelId = "jiaoyou-audio-test";
switch (type) {
case 2:
case 4: channelId = "jiaoyou-audio-child-test";break;
case 3:
case 5: channelId= "jiaoyou-audio-adult-test";break;
}
headers.put("App-Channel-Id", channelId);
String resStr= OkHttp3Utils.doPostJsonStr(XiaoAiConstants.QI_WU_TERMINATE_DIDI2, requestJsonStr, headers);;
if (resStr == null) {
return null;
}
log.info("天猫精灵晓悟返回:"+resStr);
TaskResult taskResult = null;
try {
final SpiritTerminateResponse response = JSON.parseObject(resStr, SpiritTerminateResponse.class);
// Boolean recommand = response.getAipioneerUsername().equals(channelId2RecommendBotAcc.get(channelId));
if (CollectionUtils.isEmpty(response.getDialogs())) {
taskResult = buildTextTaskResult("不好意思晓悟没有听清您刚才说的话,请再重复一遍吧", intentId);
LAST_OUTTIME_RESULT.put(userId, taskResult);
return taskResult;
}
List<String> list = dealResponse(response);
if (CollectionUtils.isEmpty(list)) {
// DplbotServiceUtil.getPool().submit(() -> {
// List<Dialog> noAudioDialogs = dealNoAudio(response);
// if (!CollectionUtils.isEmpty(noAudioDialogs)) {
// OkHttp3Utils.postAsync("http://didi-gz2.jiaoyou365.com:8188/spirit/audio/no", JSON.toJSONString(noAudioDialogs));
// }
// });
StringBuilder builder = new StringBuilder();
response.getDialogs().forEach(dialog -> builder.append(buildText(dialog.getText())));
if (builder.length() != 0) taskResult = buildTextTaskResult(builder.toString(), intentId);
} else {
taskResult = buildAudioTaskResult(list, intentId);
}
} catch (Exception e) {
log.error(e.toString());
}
if (taskResult == null) {
taskResult = buildTextTaskResult("不好意思晓悟没有听清您刚才说的话,请再重复一遍吧", intentId);
}
LAST_OUTTIME_RESULT.put(userId, taskResult);
return taskResult;
}
private List<Dialog> dealNoAudio(SpiritTerminateResponse response) {
return response.getDialogs().stream().filter(dialog -> {
String botAccount = dialog.getBotAccount();
Boolean record = botAccount2ItsCache.get(botAccount);
if (record == null) return true;
else if (record) {
return InitialData.getRecordId(botAccount, dialog.getNpcName(), dialog.getText()) == null;
} else {
return InitialData.getAudioId(botAccount, dialog.getPerson(), dialog.getTone(), dialog.getText()) == null;
}
}).collect(Collectors.toList());
}
private List<String> dealResponse(SpiritTerminateResponse response) {
List<String> idList = new ArrayList<>();
List<Dialog> dialogs = response.getDialogs();
String botAccount, npcName, id, person, mood;
for (Dialog dialog: dialogs) {
botAccount = dialog.getBotAccount();
Boolean record = botAccount2ItsCache.get(botAccount);
if (record == null) return null;
else if (record) {
npcName = dialog.getNpcName();
Collection<String> ls = dealWithSep(dialog, true, botAccount, npcName, null);
if (CollectionUtils.isEmpty(ls)) {
id = InitialData.getRecordId(botAccount, npcName, dialog.getText());
if (StringUtils.isNotBlank(id)) idList.add(id);
else return null;
} else {
idList.addAll(ls);
}
} else {
person = dialog.getPerson();
mood = dialog.getTone();
Collection<String> ls = dealWithSep(dialog, false, botAccount, person, mood);
if (CollectionUtils.isEmpty(ls)) {
id = InitialData.getAudioId(botAccount, person, mood, dialog.getText());
if (StringUtils.isNotBlank(id)) idList.add(id);
else return null;
} else {
idList.addAll(ls);
}
}
}
return idList;
}
private Collection<String> dealWithSep(Dialog dialog, Boolean record, String botAccount,
String porn, String mood) {
String text = dialog.getText();
List<String> variableTextList = new ArrayList<>();
// 获取AB之间的变量,为空则忽略
Pattern pattern = Pattern.compile(AB_REGEX);
Matcher matcher = pattern.matcher(text);
while (matcher.find()) {
String variableText = matcher.group(1);
if (StringUtils.isNotBlank(variableText)) variableTextList.add(variableText);
}
if (variableTextList.size() != 0) {
TreeMap<String, String> combineMp3Text2FilePath = new TreeMap<>(Comparator.comparingInt(text::indexOf));
// 非变量部分
String[] notVariableTextArray = pattern.split(text);
int i = 0;
for (String notVariableText: notVariableTextArray) {
if (StringUtils.isBlank(notVariableText)) {
++i;
continue;
}
if (i++ == notVariableTextArray.length-1) {
//log.info("888");
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 id;
if (record) {
id = InitialData.getRecordId(botAccount, porn, notVariableText);
} else {
id = InitialData.getAudioId(botAccount, porn, mood, notVariableText);
}
if (StringUtils.isBlank(id)) return null;
combineMp3Text2FilePath.put(notVariableText, id);
}
for (String variableText: variableTextList) {
String id;
if (record) {
id = InitialData.getRecordId(botAccount, porn, variableText);
} else {
id = InitialData.getAudioId(botAccount, porn, mood, variableText);
}
if (StringUtils.isBlank(id)) return null;
combineMp3Text2FilePath.put(variableText, id);
}
return combineMp3Text2FilePath.values();
}
return null;
}
/**
* 封装返回数据在TaskResult中
* @param text TTS文本内容
* @param intentId 意图id
* @return 返回数据封装在开发包中的TaskResult
*/
private TaskResult buildTextTaskResult(String text, Long intentId) {
TaskResult result = new TaskResult();
result.setReply(buildText(text));
result.setResultType(ResultType.ASK_INF);
result.setExecuteCode(ExecuteCode.SUCCESS);
result.setAskedInfos(Collections.singletonList(new AskedInfoMsg("any", intentId)));
return result;
}
private TaskResult buildAudioTaskResult(List<String> ids, Long intentId) {
TaskResult result = new TaskResult();
result.setReply("叮咚");
result.setResultType(ResultType.ASK_INF);
result.setExecuteCode(ExecuteCode.SUCCESS);
result.setAskedInfos(Collections.singletonList(new AskedInfoMsg("any", intentId)));
List<Action> actions = ids.stream().map(s -> {
Action action = new Action("audioPlayGenieSource");
action.addProperty("audioGenieId", s);
return action;
}).collect(Collectors.toList());
result.setActions(actions);
return result;
}
private String buildText(String text) {
Pattern pattern = Pattern.compile(Utils.getRegexSeperate());
StringBuilder builder = new StringBuilder();
List<String> actors = DplbotServiceUtil.seperateActor(text, pattern);
String[] word = DplbotServiceUtil.seperateActorWord(text, pattern);
int i = 0;
for (String actor: actors) {
builder.append(actor).append("说:").append(word[i].replaceAll("\\p{P}", "")).append("。");
i++;
}
if (builder.length() == 0) builder.append(text);
return builder.toString();
}
private String getUserId(TaskQuery query) {
log.warn("requestData:{}", query.getRequestData());
String userId = query.getRequestData().get("userOpenId");
if (StringUtils.isBlank(userId)) {
userId = query.getRequestData().get("deviceOpenId");
}
if (StringUtils.isBlank(userId)) log.error("天猫精灵无法获取到唯一标识的id");
return userId;
}
public static void main(String[] args) {
// System.out.println(buildText("【小悟@正常】推荐如下作品:《小狗小白》、《妖刀异闻录》、《星球问答》 。你可以说:“打开某作品”"));
// System.out.println(buildText("不好意思请在说一遍吧"));
// System.out.println(buildText("【齐齐@开心】小朋友真聪明。他们循声来到一颗大榕树后的一座木屋旁,<br>见到音乐家捧着一个像笛子一样的乐器正在入神地吹奏着。后来,音乐家很高兴接纳了他们,并在木屋旁边给他们安了新家,<br>四个小伙伴和善良的音乐家开心地住在水心湖边,再也不用担惊受怕了。每天和音乐家一起弹奏唱跳,认识他们的人都亲切地称他们为“水心湖的音乐家”。【齐齐@正常】好了,小朋友,今天的故事就到这里了,谢谢你的耐心听讲,再见!【晓悟@正常】已退出当前作品。【小悟@正常】推荐如下作品:《小神童闯关》、《遇见伽利略》、《会数学的杰瑞》 。你可以说:“打开某作品”"));
// System.out.println(buildText("【皮皮@正常】不好,我们在这里待得太久了,时空机要把我们带到下个地方去了【旁白@正常】随着时光穿梭机的强制转移,你和皮皮来到了动物园,动物园里有老虎,狮子,大象,还有几只大熊猫<br>【皮皮@正常】<br>我们好像被转移到动物园了。。。哇小朋友,你看!那里有熊猫耶,你喜欢熊猫吗? 。"));
}
}
package ai.qiwu.com.xiaoduhome.spirit;
import com.fasterxml.jackson.annotation.JsonIgnoreProperties;
import lombok.Getter;
import lombok.Setter;
import lombok.ToString;
/**
* @author 苗权威
* @dateTime 19-12-11 下午4:06
*/
@Getter
@Setter
@ToString
public class SpiritTerminateRequest {
private String uid;
private String msg;
private Integer resptype = 2;
}
package ai.qiwu.com.xiaoduhome.spirit;
import com.fasterxml.jackson.annotation.JsonIgnoreProperties;
import lombok.Getter;
import lombok.Setter;
import lombok.ToString;
import java.util.List;
/**
* @author 苗权威
* @dateTime 19-12-11 下午4:07
*/
@Getter
@Setter
@ToString
@JsonIgnoreProperties(ignoreUnknown = true)
public class SpiritTerminateResponse {
private String aipioneerUsername;
private List<Dialog> dialogs;
private String extraChatKey;
private String mainChatKey;
}
package ai.qiwu.com.xiaoduhome.xiaoai.common; package ai.qiwu.com.xiaoduhome.xiaoai.common;
import ai.qiwu.com.xiaoduhome.common.OkHttp3Utils; import ai.qiwu.com.xiaoduhome.common.OkHttp3Utils;
import ai.qiwu.com.xiaoduhome.spirit.SpiritTerminateRequest;
import ai.qiwu.com.xiaoduhome.xiaoai.model.QiWuRequest; import ai.qiwu.com.xiaoduhome.xiaoai.model.QiWuRequest;
import ai.qiwu.com.xiaoduhome.xiaoai.model.QiWuResponse; import ai.qiwu.com.xiaoduhome.xiaoai.model.QiWuResponse;
import ai.qiwu.com.xiaoduhome.xiaoai.service.XiaoAiService; import ai.qiwu.com.xiaoduhome.xiaoai.service.XiaoAiService;
...@@ -18,6 +19,22 @@ import java.util.HashMap; ...@@ -18,6 +19,22 @@ import java.util.HashMap;
@Slf4j @Slf4j
public class RequestTerminal { public class RequestTerminal {
private static final HashMap<String, String> ALL_HEADERS;
private static final HashMap<String, String> CHILD_HEADERS;
private static final HashMap<String, String> ADULT_HEADERS;
static {
ALL_HEADERS = new HashMap<>();
ALL_HEADERS.put("Content-Type", "application/json;charset=utf-8");
ALL_HEADERS.put("App-Channel-Id", "jiaoyou-audio-test");
CHILD_HEADERS = new HashMap<>();
CHILD_HEADERS.put("Content-Type", "application/json;charset=utf-8");
CHILD_HEADERS.put("App-Channel-Id", "jiaoyou-audio-child-test");
ADULT_HEADERS = new HashMap<>();
ADULT_HEADERS.put("Content-Type", "application/json;charset=utf-8");
ADULT_HEADERS.put("App-Channel-Id", "jiaoyou-audio-adult-test");
}
/** /**
* 向终端发出请求 * 向终端发出请求
* @param userId 用户id * @param userId 用户id
...@@ -25,27 +42,37 @@ public class RequestTerminal { ...@@ -25,27 +42,37 @@ public class RequestTerminal {
* @return mp3链接及文字描述 * @return mp3链接及文字描述
* @throws IOException * @throws IOException
*/ */
public static QiWuResponse requestTerminate(String userId, String userWord, Integer type) throws IOException { public static String requestTerminate(String userId, String userWord, Integer type) throws IOException {
QiWuRequest requestPojo = new QiWuRequest(); SpiritTerminateRequest requestPojo = new SpiritTerminateRequest();
requestPojo.setUid(userId); requestPojo.setUid(userId);
// requestPojo.setAccess(XiaoAiConstants.DEVICE_NAME);
requestPojo.setMsg(userWord); requestPojo.setMsg(userWord);
String requestJsonStr = JSON.toJSONString(requestPojo); String requestJsonStr = JSON.toJSONString(requestPojo);
//log.info("向终端发出请求的参数信息:{}", requestJsonStr); //log.info("向终端发出请求的参数信息:{}", requestJsonStr);
HashMap<String, String> headers = new HashMap<>(); HashMap<String, String> headers;
headers.put("Content-Type", "application/json;charset=utf-8"); if (type != null) {
if (NumberUtils.INTEGER_ONE.equals(type)) headers.put("App-Channel-Id", "jiaoyou-audio-child-test"); if ((type & 1) == 1) headers = CHILD_HEADERS;
else if (NumberUtils.INTEGER_TWO.equals(type)) headers.put("App-Channel-Id", "jiaoyou-audio-adult-test"); else headers = ADULT_HEADERS;
else headers.put("App-Channel-Id", "jiaoyou-audio-test"); } else {
headers = ALL_HEADERS;
}
String resStr; String resStr;
if (userId.equals(XiaoAiService.deviceId)) { if (userId.equals(XiaoAiService.deviceId)) {
resStr = OkHttp3Utils.doPostJsonStr(XiaoAiConstants.QI_WU_TERMINATE_DIDI, requestJsonStr, headers);
}else {
resStr = OkHttp3Utils.doPostJsonStr(XiaoAiConstants.QI_WU_TERMINATE_nx2, requestJsonStr, headers); resStr = OkHttp3Utils.doPostJsonStr(XiaoAiConstants.QI_WU_TERMINATE_nx2, requestJsonStr, headers);
}else {
resStr = OkHttp3Utils.doPostJsonStr(XiaoAiConstants.QI_WU_TERMINATE_DIDI, requestJsonStr, headers);
} }
if (resStr == null) { return resStr;
return null; }
public static void backBotRequest(String userId, Integer type) {
SpiritTerminateRequest requestPojo = new SpiritTerminateRequest();
requestPojo.setUid(userId);
requestPojo.setMsg(XiaoAiConstants.TTS.END_WORD);
String requestJsonStr = JSON.toJSONString(requestPojo);
if (userId.equals(XiaoAiService.deviceId)) {
OkHttp3Utils.backPostAsync(XiaoAiConstants.QI_WU_TERMINATE_DIDI, requestJsonStr, type);
}else {
OkHttp3Utils.backPostAsync(XiaoAiConstants.QI_WU_TERMINATE_nx2, requestJsonStr, type);
} }
return JSON.parseObject(resStr, QiWuResponse.class);
} }
} }
...@@ -7,10 +7,14 @@ package ai.qiwu.com.xiaoduhome.xiaoai.common; ...@@ -7,10 +7,14 @@ package ai.qiwu.com.xiaoduhome.xiaoai.common;
*/ */
public interface XiaoAiConstants { public interface XiaoAiConstants {
String QI_WU_TERMINATE_DIDI = "http://didi-gz3.jiaoyou365.com:8070/api/chat2"; String QI_WU_TERMINATE_DIDI = "http://didi-gz3.jiaoyou365.com:8070/api/chat2";
String QI_WU_TERMINATE_DIDI2 = "http://didi-gz2.jiaoyou365.com:8070/api/chat2";
String QI_WU_TERMINATE_nx2 = "http://didi-gz4.jiaoyou365.com:8070/api/chat2"; String QI_WU_TERMINATE_nx2 = "http://didi-gz4.jiaoyou365.com:8070/api/chat2";
String TTS_DIDI3 = "http://didi-gz3.jiaoyou365.com:9663/api/audio";
String TTS_DIDI4 = "http://didi-gz4.jiaoyou365.com:9663/api/audio";
String DEVICE_NAME = "XIAOAI"; String DEVICE_NAME = "XIAOAI";
String CONTENT_TYPE = "application/json;charset=utf-8"; String CONTENT_TYPE = "application/json;charset=utf-8";
String PLAYBACK_NEARLY_FINISHED = "mediaplayer.playbacknearlyfinished"; String PLAYBACK_NEARLY_FINISHED = "mediaplayer.playbacknearlyfinished";
String PREFIX_USERID="XIAOAI_";
interface ERROR_MSG { interface ERROR_MSG {
...@@ -21,9 +25,11 @@ public interface XiaoAiConstants { ...@@ -21,9 +25,11 @@ public interface XiaoAiConstants {
} }
interface TTS { interface TTS {
String WELCOME_WORD = "欢迎来到交游天下,海量的作品在这等您"; String WELCOME_WORD = "欢迎来到交游天下,海量的作品在这等您,你可以说推荐作品给我";
String WELCOME_WORD_CHILD = "小朋友你好,欢迎来到智能故事"; String WELCOME_WORD_CHILD = "小朋友你好,欢迎来到智能故事,你可以说推荐作品给我";
String WELCOME_WORD_Adult = "你好,欢迎来到智能小说"; String WELCOME_WORD_CHILD_STORY = "小朋友你好,欢迎来到互动故事,你可以说推荐作品给我";
String WELCOME_WORD_Adult = "你好,欢迎来到智能小说,你可以说推荐作品给我";
String WELCOME_WORD_Adult_literature = "你好,欢迎来到互动文艺,你可以说推荐作品给我";
String END_BYE = "我们的作品库在不断扩充,欢迎再来玩"; String END_BYE = "我们的作品库在不断扩充,欢迎再来玩";
String END_BYE_CHILD = "再见啦小朋友,记得下次再来玩哦"; String END_BYE_CHILD = "再见啦小朋友,记得下次再来玩哦";
String END_BYE_Adult = "再见啦,记得下次再来玩哦"; String END_BYE_Adult = "再见啦,记得下次再来玩哦";
......
...@@ -12,4 +12,6 @@ import lombok.ToString; ...@@ -12,4 +12,6 @@ import lombok.ToString;
public class QiWuResponse { public class QiWuResponse {
private String audio; private String audio;
private String text; private String text;
private String extraChatKey;
private String mainChatKey;
} }
...@@ -12,5 +12,9 @@ import lombok.ToString; ...@@ -12,5 +12,9 @@ import lombok.ToString;
@Setter @Setter
@ToString @ToString
public class RegisterEvent { public class RegisterEvent {
public RegisterEvent(String event_name) {
this.event_name = event_name;
}
private String event_name; private String event_name;
} }
package ai.qiwu.com.xiaoduhome.xiaoai.service; package ai.qiwu.com.xiaoduhome.xiaoai.service;
import ai.qiwu.com.xiaoduhome.common.OkHttp3Utils;
import ai.qiwu.com.xiaoduhome.controller.WebSocketLog; import ai.qiwu.com.xiaoduhome.controller.WebSocketLog;
import ai.qiwu.com.xiaoduhome.service.DplbotServiceUtil; import ai.qiwu.com.xiaoduhome.service.DplbotServiceUtil;
import ai.qiwu.com.xiaoduhome.xiaoai.common.*; import ai.qiwu.com.xiaoduhome.xiaoai.common.*;
import ai.qiwu.com.xiaoduhome.xiaoai.model.QiWuResponse;
import ai.qiwu.com.xiaoduhome.xiaoai.model.request.XiaoAiRequest; import ai.qiwu.com.xiaoduhome.xiaoai.model.request.XiaoAiRequest;
import ai.qiwu.com.xiaoduhome.xiaoai.model.response.XiaoAiResponse; import ai.qiwu.com.xiaoduhome.xiaoai.model.response.XiaoAiResponse;
import ai.qiwu.com.xiaoduhome.xiaoai.model.response.innerResponse.Response; import ai.qiwu.com.xiaoduhome.xiaoai.model.response.innerResponse.Response;
import ai.qiwu.com.xiaoduhome.xiaoai.model.response.innerResponse.directive.AudioItem.AudioItem; import ai.qiwu.com.xiaoduhome.xiaoai.model.response.innerResponse.directive.AudioItem.AudioItem;
import ai.qiwu.com.xiaoduhome.xiaoai.model.response.innerResponse.directive.AudioItem.AudioStream; import ai.qiwu.com.xiaoduhome.xiaoai.model.response.innerResponse.directive.AudioItem.AudioStream;
import ai.qiwu.com.xiaoduhome.xiaoai.model.response.innerResponse.directive.Directive; import ai.qiwu.com.xiaoduhome.xiaoai.model.response.innerResponse.directive.Directive;
import ai.qiwu.com.xiaoduhome.xiaoai.model.response.innerResponse.toDisplay.ToDisplay;
import ai.qiwu.com.xiaoduhome.xiaoai.model.response.innerResponse.toSpeak.ToSpeak; import ai.qiwu.com.xiaoduhome.xiaoai.model.response.innerResponse.toSpeak.ToSpeak;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import lombok.extern.slf4j.Slf4j; import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.RandomUtils; import org.apache.commons.lang3.RandomUtils;
import org.apache.commons.lang3.StringUtils; import org.apache.commons.lang3.StringUtils;
import org.apache.commons.lang3.math.NumberUtils;
import org.springframework.stereotype.Service; import org.springframework.stereotype.Service;
import java.io.File; import java.io.File;
import java.util.ArrayList; import java.util.*;
import java.util.List;
import java.util.Random;
import java.util.concurrent.*; import java.util.concurrent.*;
import static ai.qiwu.com.xiaoduhome.common.Constants.*;
import static ai.qiwu.com.xiaoduhome.xiaoai.common.XiaoAiConstants.ERROR_MSG.SORRY_REPEAT; import static ai.qiwu.com.xiaoduhome.xiaoai.common.XiaoAiConstants.ERROR_MSG.SORRY_REPEAT;
import static ai.qiwu.com.xiaoduhome.xiaoai.common.XiaoAiConstants.PREFIX_USERID;
import static ai.qiwu.com.xiaoduhome.xiaoai.common.XiaoAiConstants.TTS.WAIT_WORD_3; import static ai.qiwu.com.xiaoduhome.xiaoai.common.XiaoAiConstants.TTS.WAIT_WORD_3;
/** /**
...@@ -47,11 +49,13 @@ public class XiaoAiService { ...@@ -47,11 +49,13 @@ public class XiaoAiService {
*/ */
private static final ConcurrentHashMap<String, XiaoAiResponse> LAST_OUTTIME_RESULT = new ConcurrentHashMap<>(); private static final ConcurrentHashMap<String, XiaoAiResponse> LAST_OUTTIME_RESULT = new ConcurrentHashMap<>();
public static final ConcurrentHashMap<String, Byte> LAST_OUTTIME_MARK = new ConcurrentHashMap<>(); public static final ConcurrentHashMap<String, Byte> LAST_OUTTIME_MARK = new ConcurrentHashMap<>();
private static final ConcurrentHashMap<String, String> LAST_AUDIO_PLAY = new ConcurrentHashMap<>();
public static final Byte OUTTIME_TYPE_0 = 0; public static final Byte OUTTIME_TYPE_0 = 0;
public static final Byte OUTTIME_TYPE_1 = 1; private static final Byte OUTTIME_TYPE_1 = 1;
private static final Byte OUTTIME_TYPE_2 = 2;
public static final String deviceId = "oIOWfYEFbZGFHB5DzoMA=="; public static final String deviceId = "XIAOAI_nbNGwoZIS8AmRGVqHog==";//XIAOAI_nbNGwoZIS8AmRGVqHog==,XIAOAI_oIOWfYEFbZGFHB5DzoMA==
/** /**
* 处理不同意图,type为0则说明是启动,为1则说明是会话进行中,为2则说明用户退出 * 处理不同意图,type为0则说明是启动,为1则说明是会话进行中,为2则说明用户退出
...@@ -150,6 +154,29 @@ public class XiaoAiService { ...@@ -150,6 +154,29 @@ public class XiaoAiService {
return response; return response;
} }
private XiaoAiResponse buildAudioTextResponse(String audioUrl, String text) {
XiaoAiResponse response = buildResponse();
Response responseInfo = response.getResponse();
Directive directive = new Directive();
directive.setType("audio");
AudioItem audioItem = new AudioItem();
AudioStream audioStream = new AudioStream();
audioStream.setUrl(audioUrl);
audioItem.setStream(audioStream);
directive.setAudio_item(audioItem);
List<Directive> directives = new ArrayList<>();
directives.add(directive);
responseInfo.setDirectives(directives);
ToDisplay display = new ToDisplay();
display.setType(0);
display.setText(text);
responseInfo.setTo_display(display);
return response;
}
/** /**
* 构建文字返回信息 * 构建文字返回信息
* @param text 文字 * @param text 文字
...@@ -179,8 +206,16 @@ public class XiaoAiService { ...@@ -179,8 +206,16 @@ public class XiaoAiService {
// } // }
LAST_OUTTIME_RESULT.remove(getUserId(request)); LAST_OUTTIME_RESULT.remove(getUserId(request));
LAST_OUTTIME_MARK.remove(getUserId(request)); LAST_OUTTIME_MARK.remove(getUserId(request));
if (NumberUtils.INTEGER_ONE.equals(request.getType())) return buildTextResponse(XiaoAiConstants.TTS.WELCOME_WORD_CHILD); LAST_AUDIO_PLAY.remove(getUserId(request));
else if (NumberUtils.INTEGER_TWO.equals(request.getType())) return buildTextResponse(XiaoAiConstants.TTS.WELCOME_WORD_Adult); Integer type;
if ((type = request.getType()) != null) {
switch (type) {
case 1: return buildTextResponse(XiaoAiConstants.TTS.WELCOME_WORD_CHILD);
case 2: return buildTextResponse(XiaoAiConstants.TTS.WELCOME_WORD_Adult);
case 3: return buildTextResponse(XiaoAiConstants.TTS.WELCOME_WORD_CHILD_STORY);
case 4: return buildTextResponse(XiaoAiConstants.TTS.WELCOME_WORD_Adult_literature);
}
}
return buildTextResponse(XiaoAiConstants.TTS.WELCOME_WORD); return buildTextResponse(XiaoAiConstants.TTS.WELCOME_WORD);
} }
...@@ -194,15 +229,8 @@ public class XiaoAiService { ...@@ -194,15 +229,8 @@ public class XiaoAiService {
private XiaoAiResponse dealWithIntentRequest(XiaoAiRequest request, String userId) { private XiaoAiResponse dealWithIntentRequest(XiaoAiRequest request, String userId) {
Boolean idle = request.getRequest().getNo_response(); Boolean idle = request.getRequest().getNo_response();
Byte waitType; Byte waitType;
if ((waitType=LAST_OUTTIME_MARK.get(userId)) != null) { if ((waitType=LAST_OUTTIME_MARK.remove(userId)) != null) {
boolean firstTime = waitType == 0; boolean firstTime = waitType == 0;
try {
//log.info("开始等待");
Thread.sleep(1600);
//log.info("等待OVER");
} catch (InterruptedException e) {
log.warn("等待中断");
}
if (LAST_OUTTIME_RESULT.get(userId) == null) { if (LAST_OUTTIME_RESULT.get(userId) == null) {
if (Boolean.TRUE.equals(idle)) { if (Boolean.TRUE.equals(idle)) {
if (firstTime) { if (firstTime) {
...@@ -210,6 +238,7 @@ public class XiaoAiService { ...@@ -210,6 +238,7 @@ public class XiaoAiService {
return buildTextResponse((RandomUtils.nextInt() & 1) == 1 ? XiaoAiConstants.TTS.WAIT_WORD_1 : return buildTextResponse((RandomUtils.nextInt() & 1) == 1 ? XiaoAiConstants.TTS.WAIT_WORD_1 :
XiaoAiConstants.TTS.WAIT_WORD_2); XiaoAiConstants.TTS.WAIT_WORD_2);
} else { } else {
LAST_OUTTIME_MARK.put(userId, OUTTIME_TYPE_2);
return buildTextResponse(WAIT_WORD_3); return buildTextResponse(WAIT_WORD_3);
} }
} }
...@@ -217,13 +246,12 @@ public class XiaoAiService { ...@@ -217,13 +246,12 @@ public class XiaoAiService {
return buildTextResponse((RandomUtils.nextInt() & 1) == 1 ? XiaoAiConstants.TTS.WAIT_WORD_1 : return buildTextResponse((RandomUtils.nextInt() & 1) == 1 ? XiaoAiConstants.TTS.WAIT_WORD_1 :
XiaoAiConstants.TTS.WAIT_WORD_2); XiaoAiConstants.TTS.WAIT_WORD_2);
} }
LAST_OUTTIME_MARK.remove(userId);
return LAST_OUTTIME_RESULT.remove(userId); return LAST_OUTTIME_RESULT.remove(userId);
} }
if (idle != null && idle) { if (Boolean.TRUE.equals(idle)) {
try { try {
//log.info("开始等待"); //log.info("开始等待");
Thread.sleep(1900); Thread.sleep(2000);
//log.info("等待OVER"); //log.info("等待OVER");
} catch (InterruptedException e) { } catch (InterruptedException e) {
log.warn("等待中断"); log.warn("等待中断");
...@@ -235,11 +263,15 @@ public class XiaoAiService { ...@@ -235,11 +263,15 @@ public class XiaoAiService {
return buildTextResponse((RandomUtils.nextInt() & 1) == 1 ? XiaoAiConstants.TTS.USER_IDLE : return buildTextResponse((RandomUtils.nextInt() & 1) == 1 ? XiaoAiConstants.TTS.USER_IDLE :
XiaoAiConstants.TTS.ANOTHER_USER_IDLE); XiaoAiConstants.TTS.ANOTHER_USER_IDLE);
} }
String path;
if ((path = LAST_AUDIO_PLAY.get(userId)) != null) {
return buildAudioResponse(changeAudioUrl(path, userId));
}
// XiaoAiResponse response = getLastResult(userId); // XiaoAiResponse response = getLastResult(userId);
// if (response != null) return response; // if (response != null) return response;
try { try {
Future future = DplbotServiceUtil.getPool().submit(new Task(userId, request.getQuery(), request.getType())); Future future = DplbotServiceUtil.getPool().submit(new Task(userId, request.getQuery(), request.getType()));
future.get(2100, TimeUnit.MILLISECONDS); future.get(2250, TimeUnit.MILLISECONDS);
} catch (InterruptedException | ExecutionException e) { } catch (InterruptedException | ExecutionException e) {
log.error("获取任务执行结果出错:{}", e.toString()); log.error("获取任务执行结果出错:{}", e.toString());
return buildTextResponse(SORRY_REPEAT); return buildTextResponse(SORRY_REPEAT);
...@@ -260,17 +292,21 @@ public class XiaoAiService { ...@@ -260,17 +292,21 @@ public class XiaoAiService {
* @return 返回信息 * @return 返回信息
*/ */
private XiaoAiResponse dealWithEndRequest(String userId, Integer type) { private XiaoAiResponse dealWithEndRequest(String userId, Integer type) {
DplbotServiceUtil.getPool().submit(() -> { // DplbotServiceUtil.getPool().submit(() -> {
try { // try {
RequestTerminal.requestTerminate(userId, XiaoAiConstants.TTS.END_WORD, type); // RequestTerminal.backBotRequest(userId, type);
} catch (Exception e) { // } catch (Exception e) {
log.error("向终端发出的退出请求失败:{}", e.toString()); // log.error("向终端发出的退出请求失败:{}", e.toString());
} // }
}); // });
RequestTerminal.backBotRequest(userId, type);
LAST_OUTTIME_MARK.remove(userId); LAST_OUTTIME_MARK.remove(userId);
LAST_OUTTIME_RESULT.remove(userId); LAST_OUTTIME_RESULT.remove(userId);
if (NumberUtils.INTEGER_ONE.equals(type)) return buildTextResponse(XiaoAiConstants.TTS.END_BYE_CHILD); LAST_AUDIO_PLAY.remove(userId);
else if (NumberUtils.INTEGER_TWO.equals(type)) return buildTextResponse(XiaoAiConstants.TTS.END_BYE_Adult); if (type != null) {
if ((type & 1) == 1) return buildTextResponse(XiaoAiConstants.TTS.END_BYE_CHILD);
else return buildTextResponse(XiaoAiConstants.TTS.END_BYE_Adult);
}
return buildTextResponse(XiaoAiConstants.TTS.END_BYE); return buildTextResponse(XiaoAiConstants.TTS.END_BYE);
} }
...@@ -287,6 +323,7 @@ public class XiaoAiService { ...@@ -287,6 +323,7 @@ public class XiaoAiService {
if (userId == null) { if (userId == null) {
userId = Utils.useIPAsItsID(); userId = Utils.useIPAsItsID();
} }
userId = PREFIX_USERID+userId;
return Utils.modifyDeviceId(userId); return Utils.modifyDeviceId(userId);
} }
...@@ -316,32 +353,98 @@ public class XiaoAiService { ...@@ -316,32 +353,98 @@ public class XiaoAiService {
throw new RequestWordNullException("user word can not be null"); throw new RequestWordNullException("user word can not be null");
} }
log.info("小爱,用户说的话:{}", userWord); log.info("小爱,用户说的话:{}", userWord);
QiWuResponse response; String response;
try { try {
response = RequestTerminal.requestTerminate(userId, userWord, type); response = RequestTerminal.requestTerminate(userId, userWord, type);
log.info("小爱,小悟返回:{}", response);
} catch (Exception e) { } catch (Exception e) {
log.error("向终端发出的请求信息失败:{}", e.toString()); log.error("向终端发出的请求信息失败:{}", e.toString());
throw new RequestTerminateFail(e.toString()); xiaoAiResponse = buildTextResponse(SORRY_REPEAT);
LAST_OUTTIME_RESULT.put(userId, xiaoAiResponse);
return;
} }
if (response == null || StringUtils.isBlank(response.getAudio())) { if (StringUtils.isBlank(response)) {
log.error("中控返回结果或是url链接为空"); log.error("中控返回结果为空");
xiaoAiResponse = buildTextResponse(SORRY_REPEAT); xiaoAiResponse = buildTextResponse(SORRY_REPEAT);
} else { } else {
log.info("小爱,小悟返回:{}, audio:{}", response.getText(),response.getAudio()); String path;
final String audioUrl = response.getAudio(); try {
xiaoAiResponse = buildAudioResponse(audioUrl); boolean one;
final String word = userWord; if ((one=userId.equals(deviceId))) {
DplbotServiceUtil.getPOOL().submit(() -> { path = OkHttp3Utils.doPostJsonStr(XiaoAiConstants.TTS_DIDI4, response);
if (deviceId.equals(userId)) { } else {
WebSocketLog.sendInfo(new StringBuilder(word).append(File.separator) path = OkHttp3Utils.doPostJsonStr(XiaoAiConstants.TTS_DIDI3, response);
.append(response.getText()).toString(), "ai1"); }
if (StringUtils.isBlank(path) || path.equals("null")) {
log.error("没有获取到TTS返回的路径path");
LAST_OUTTIME_RESULT.put(userId, buildTextResponse(SORRY_REPEAT));
return;
}
if (one) {
xiaoAiResponse = buildAudioResponse(changeAudioUrlTemp(path, userId));
} else {
xiaoAiResponse = buildAudioResponse(changeAudioUrl(path, userId));
}
LAST_AUDIO_PLAY.put(userId, path);
if (userId.equals(deviceId)) {
DplbotServiceUtil.getPool().submit(() -> {
JSONObject ob = JSONObject.parseObject(response);
JSONArray array = ob.getJSONArray("dialogs");
StringBuilder builder = new StringBuilder(userWord).append(File.separator);
for (Object item: array) {
String str = ((JSONObject) item).getString("text");
builder.append(str.replaceAll("\\{/.*?/}", "")).append(";");
}
WebSocketLog.sendInfo(builder.toString(), "ai1");
});
} else { } else {
WebSocketLog.sendInfo(new StringBuilder(word).append(File.separator) DplbotServiceUtil.getPool().submit(() -> {
.append(response.getText()).toString(), "ai2"); JSONObject ob = JSONObject.parseObject(response);
JSONArray array = ob.getJSONArray("dialogs");
StringBuilder builder = new StringBuilder(userWord).append(File.separator);
for (Object item: array) {
String str = ((JSONObject) item).getString("text");
builder.append(str.replaceAll("\\{/.*?/}", "")).append(";");
}
WebSocketLog.sendInfo(builder.toString(), "ai2");
});
} }
}); } catch (Exception e) {
log.error("没有获取到TTS返回的路径path");
xiaoAiResponse = buildTextResponse(SORRY_REPEAT);
}
// final String word = userWord;
// DplbotServiceUtil.getPOOL().submit(() -> {
// if (deviceId.equals(userId)) {
// WebSocketLog.sendInfo(new StringBuilder(word).append(File.separator)
// .append(response.getText()).toString(), "ai1");
// } else {
// WebSocketLog.sendInfo(new StringBuilder(word).append(File.separator)
// .append(response.getText()).toString(), "ai2");
// }
// });
} }
LAST_OUTTIME_RESULT.put(userId, xiaoAiResponse); LAST_OUTTIME_RESULT.put(userId, xiaoAiResponse);
} }
} }
private String changeAudioUrl(String path, String userId) {
return new StringBuilder(TTS_DIDI3_GET_XIAOAI).append(userId).append("&path=").append(path).toString();
}
private String changeAudioUrlTemp(String path, String userId) {
path = path.replaceAll("%2F", "/");
// return new StringBuilder(TTS_DIDI4_GET_XIAOAI_STATIC).append(path.substring(path.indexOf("audio")+6)).toString();
return new StringBuilder(TTS_DIDI4_GET_XIAOAI).append(userId).append("&path=").append(path).toString();
}
public void changeAudioPlayMark(String userId) {
LAST_AUDIO_PLAY.remove(userId);
}
public static void main(String[] args) {
System.out.println(Utils.modifyDeviceId("XIAOAI_nbNGwo/tZIS8A/mRGVqHog=="));
// oIOWfYEFbZGFHB5DzoMA==;
// oItOWfYEFbtZGFHB5DzoMA==
}
} }
...@@ -7,12 +7,17 @@ spring: ...@@ -7,12 +7,17 @@ spring:
jdbc-url: jdbc:mysql://localhost:3306/game_editor_db?useUnicode=true&characterEncoding=utf-8&serverTimezone=Hongkong&useSSL=false jdbc-url: jdbc:mysql://localhost:3306/game_editor_db?useUnicode=true&characterEncoding=utf-8&serverTimezone=Hongkong&useSSL=false
username: root username: root
password: 38A0O1jEPOE password: 38A0O1jEPOE
driver-class-name: com.mysql.jdbc.Driver driver-class-name: com.mysql.cj.jdbc.Driver
secondary: secondary:
jdbc-url: jdbc:mysql://localhost:3306/audiobox?useUnicode=true&characterEncoding=utf-8&serverTimezone=Hongkong&useSSL=false jdbc-url: jdbc:mysql://localhost:3306/audiobox?useUnicode=true&characterEncoding=utf-8&serverTimezone=Hongkong&useSSL=false
username: root username: root
password: 38A0O1jEPOE password: 38A0O1jEPOE
driver-class-name: com.mysql.jdbc.Driver driver-class-name: com.mysql.cj.jdbc.Driver
analysis:
jdbc-url: jdbc:mysql://localhost:3306/analysis?useUnicode=true&characterEncoding=utf-8&serverTimezone=Hongkong&useSSL=false
username: root
password: 38A0O1jEPOE
driver-class-name: com.mysql.cj.jdbc.Driver
jpa: jpa:
database: mysql database: mysql
#控制台显示SQL #控制台显示SQL
...@@ -27,4 +32,6 @@ logging: ...@@ -27,4 +32,6 @@ logging:
level: level:
root: info root: info
okhttp3: okhttp3:
OkHttpClient: FINE OkHttpClient: FINE
\ No newline at end of file
csvDic: /home/dc2-user/projects/audiobox/duai/csv/
\ No newline at end of file
Jfc4Z4Ur15JwUBuvUQD5wg7Nu8+l+HscqYlfofbyJdYGH+f3XrduI0FLgVW7gXyV
\ No newline at end of file
Jfc4Z4Ur15JwUBuvUQD5wg7Nu8+l+HscqYlfofbyJdYGH+f3XrduI0FLgVW7gXyV
\ No newline at end of file
Jfc4Z4Ur15JwUBuvUQD5wg7Nu8+l+HscqYlfofbyJdaEr7275aEMVjPWxwUQXYKO
\ No newline at end of file
Jfc4Z4Ur15JwUBuvUQD5wg7Nu8+l+HscqYlfofbyJdbWemsw1KjF/K5sTmFtefcK
\ No newline at end of file
Jfc4Z4Ur15JwUBuvUQD5wg7Nu8+l+HscqYlfofbyJdYl1WV0wUh0suAg2swzr9op
\ No newline at end of file
Jfc4Z4Ur15JwUBuvUQD5wg7Nu8+l+HscqYlfofbyJdYHaA0JQeSQDRWj5Va+HtGy
\ No newline at end of file
Jfc4Z4Ur15JwUBuvUQD5wg7Nu8+l+HscqYlfofbyJdabUWNw9gpRzUrkhpgKK2YY
\ No newline at end of file
Jfc4Z4Ur15JwUBuvUQD5wg7Nu8+l+HscqYlfofbyJdaEZbglH1ruVqu+Lzfq0fGo
\ No newline at end of file
...@@ -9,10 +9,10 @@ ...@@ -9,10 +9,10 @@
</head> </head>
<body> <body>
<div class="mainbox"> <div class="mainbox">
<button type="button" class="layui-btn button " id="one">小度1号 (gz4)</button> <button type="button" class="layui-btn button " id="one">小度1号 (gz3)</button>
<button type="button" class="layui-btn button " id="four">小度2号 (gz3)</button> <button type="button" class="layui-btn button " id="four">小度2号 (gz3)</button>
<button type="button" class="layui-btn button " id="tow">小爱1号(gz3)</button> <button type="button" class="layui-btn button " id="tow">小爱1号(gz3)</button>
<button type="button" class="layui-btn button " id="therr">小爱2号(gz4)</button> <button type="button" class="layui-btn button " id="therr">小爱2号(gz3)</button>
</div> </div>
</body> </body>
<style> <style>
...@@ -53,7 +53,6 @@ ...@@ -53,7 +53,6 @@
four.onclick = function(){ four.onclick = function(){
console.log("点击事件"); console.log("点击事件");
window.open("./Log4.html","_blank"); window.open("./Log4.html","_blank");
} }
</script> </script>
......
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