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 @@
<groupId>ai.qiwu.tmall</groupId>
<artifactId>spirit</artifactId>
<version>0.0.1-SNAPSHOT</version>
<packaging>war</packaging>
<!--<packaging>war</packaging>-->
<name>spirit</name>
<description>Tmall spirit project</description>
......@@ -23,12 +23,6 @@
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
<exclusions>
<exclusion>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-tomcat</artifactId>
</exclusion>
</exclusions>
</dependency>
<dependency>
......@@ -36,7 +30,10 @@
<artifactId>spring-boot-starter-test</artifactId>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-jpa</artifactId>
</dependency>
<dependency>
<groupId>com.tmall.spirit</groupId>
<artifactId>tmall-sdk</artifactId>
......@@ -44,39 +41,79 @@
<scope>system</scope>
<systemPath>${project.basedir}/src/main/resources/lib/aliGenie-intent-sematic.jar</systemPath>
</dependency>
<!-- https://mvnrepository.com/artifact/org.apache.httpcomponents/httpclient -->
<dependency>
<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>
<groupId>org.apache.httpcomponents</groupId>
<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>
<groupId>com.alibaba</groupId>
<artifactId>fastjson</artifactId>
<version>1.2.60</version>
<version>1.2.62</version>
</dependency>
<dependency>
<groupId>com.google.guava</groupId>
<artifactId>guava</artifactId>
<version>18.0</version>
<groupId>org.projectlombok</groupId>
<artifactId>lombok</artifactId>
<version>1.18.8</version>
<scope>provided</scope>
</dependency>
<dependency>
<groupId>com.google.code.gson</groupId>
<artifactId>gson</artifactId>
<version>2.8.5</version>
<groupId>org.apache.commons</groupId>
<artifactId>commons-lang3</artifactId>
<version>3.9</version>
</dependency>
<!--添加servlet-api的依赖,用来打war包 -->
<dependency>
<groupId>javax.servlet</groupId>
<artifactId>javax.servlet-api</artifactId>
<version>LATEST</version>
<scope>provided</scope>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<scope>runtime</scope>
</dependency>
<dependency>
<groupId>org.apache.commons</groupId>
<artifactId>commons-csv</artifactId>
<version>1.7</version>
</dependency>
</dependencies>
<build>
<finalName>Spirit</finalName>
<finalName>spirit</finalName>
<plugins>
<plugin>
<groupId>org.springframework.boot</groupId>
......@@ -96,19 +133,19 @@
</compilerArguments>
</configuration>
</plugin>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-war-plugin</artifactId>
<version>3.2.3</version>
<configuration>
<webResources>
<resource>
<directory>${project.basedir}/src/main/resources/lib</directory>
<targetPath>WEB-INF/lib</targetPath>
</resource>
</webResources>
</configuration>
</plugin>
<!--<plugin>-->
<!--<groupId>org.apache.maven.plugins</groupId>-->
<!--<artifactId>maven-war-plugin</artifactId>-->
<!--<version>3.2.3</version>-->
<!--<configuration>-->
<!--<webResources>-->
<!--<resource>-->
<!--<directory>${project.basedir}/src/main/resources/lib</directory>-->
<!--<targetPath>WEB-INF/lib</targetPath>-->
<!--</resource>-->
<!--</webResources>-->
<!--</configuration>-->
<!--</plugin>-->
</plugins>
</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;
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.TaskQuery;
import com.alibaba.da.coin.ide.spi.standard.TaskResult;
import com.alibaba.da.coin.ide.spi.trans.MetaFormat;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import com.alibaba.fastjson.JSON;
import org.apache.catalina.connector.ClientAbortException;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.*;
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 苗权威
* @dateTime 2019/6/18
* @dateTime 19-12-6 上午10:31
*/
@RestController
@RequestMapping("/spirit")
public class SpiritController {
private final SpiritService spiritService;
private final SpiritAudioUpload spiritAudioUpload;
/**
* slf4j打印日志信息
*/
private static final Logger logger = LoggerFactory.getLogger(SpiritController.class);
@Value("${csvDic}")
private String csvDic;
/**
* 解析请求信息的实现类
*/
@Autowired
private SpiritService spiritService;
public SpiritController(SpiritService spiritService, SpiritAudioUpload spiritAudioUpload) {
this.spiritService = spiritService;
this.spiritAudioUpload = spiritAudioUpload;
}
/**
* 利用天猫精灵打开发包解析请求并从构造响应数据返回
* @param taskQuery 请求的参数信息
* @return 返回响应的JSON数据
*/
@RequestMapping(value = "/spirit")
public @ResponseBody ResultModel<TaskResult> getResponse(@RequestBody String taskQuery) {
logger.info("TaskQuery:{}",taskQuery);
@PostMapping(value = "/") //交游天下
public ResultModel<TaskResult> getResponse(@RequestBody String 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);
// build response
ResultModel<TaskResult> resultModel = new ResultModel<>();
TaskResult taskResult = spiritService.getResponse(query);
logger.info("taskResult:"+taskResult);
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;
}
@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.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;
}
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 @@
<scope>system</scope>
<systemPath>${project.basedir}/src/main/resources/static/bot-sdk-1.2.0.jar</systemPath>
</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>
<build>
<finalName>testTool</finalName>
<finalName>useTool</finalName>
<plugins>
<plugin>
<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 @@
<!--<artifactId>java-getopt</artifactId>-->
<!--<version>1.0.13</version>-->
<!--</dependency>-->
<!-- https://mvnrepository.com/artifact/ws.schild/jave-all-deps -->
<dependency>
<groupId>ws.schild</groupId>
<artifactId>jave-all-deps</artifactId>
<version>2.7.1</version>
</dependency>
<!-- https://mvnrepository.com/artifact/org/jaudiotagger -->
<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>-->
<!--<groupId>ws.schild</groupId>-->
<!--<artifactId>jave-all-deps</artifactId>-->
<!--<version>2.7.1</version>-->
<!--</dependency>-->
<!--https://mvnrepository.com/artifact/ws.schild/jave-core-->
<!--<dependency>-->
<!--<groupId>ws.schild</groupId>-->
<!--<artifactId>jave-core</artifactId>-->
<!--<version>2.7.1</version>-->
<!--</dependency>-->
<!--&lt;!&ndash; https://mvnrepository.com/artifact/ws.schild/jave-native-linux64 &ndash;&gt;-->
<!--<dependency>-->
<!--<groupId>ws.schild</groupId>-->
<!--<artifactId>jave-native-linux64</artifactId>-->
<!--<version>2.4.6</version>-->
<!--</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>-->
<!--<groupId>org.tritonus.share</groupId>-->
<!--<artifactId>tritonus</artifactId>-->
......
......@@ -122,6 +122,43 @@ public class CallPython {
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) {
ProcessBuilder processBuilder = new ProcessBuilder(args);
processBuilder.redirectErrorStream(true); //错误输出流合并到标准输出流中
......
......@@ -5,6 +5,8 @@ import lombok.extern.slf4j.Slf4j;
import okhttp3.*;
import okio.BufferedSink;
import okio.Okio;
import org.apache.commons.lang3.exception.ExceptionUtils;
import org.jetbrains.annotations.NotNull;
import java.io.File;
import java.io.IOException;
......@@ -444,4 +446,30 @@ public class OkHttp3Utils {
}
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 {
String URL = "https://speech.ainirobot.com/tts/v1/text2audio";
String AUTHORIZATION = "Bearer ";
}
interface Audio {
String XIAOAI = "XIAOAI";
String XIAODU = "XIAODU";
}
}
......@@ -16,12 +16,18 @@ import javax.sound.sampled.AudioInputStream;
import javax.sound.sampled.AudioSystem;
import javax.sound.sampled.UnsupportedAudioFileException;
import java.io.*;
import java.nio.channels.FileLock;
import java.nio.charset.Charset;
import java.nio.charset.StandardCharsets;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.nio.file.StandardOpenOption;
import java.text.Normalizer;
import java.util.*;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import java.util.stream.Collectors;
import java.util.zip.ZipEntry;
import java.util.zip.ZipFile;
......@@ -177,6 +183,37 @@ public class TTSUtils {
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 文件路径
......@@ -485,19 +522,29 @@ public class TTSUtils {
*/
public static void combineMp3File(Collection<String> filePathList, String targetFilepath)
throws IOException {
try {
// List<String> filePaths = SampleRateConverter.equalSampleRate(filePathList);
// List<String> filePaths = SampleRateConverter.equalWavData(filePathList);
List<String> filePaths = SampleRateConverter.equalSampleRateUseFfmepg(filePathList);
if (!CollectionUtils.isEmpty(filePaths)) filePathList = filePaths;
} catch (Exception e) {
log.error("转换采样率出现错误:{}",e);
}
// try {
//// List<String> filePaths = SampleRateConverter.equalSampleRate(filePathList);
//// List<String> filePaths = SampleRateConverter.equalWavData(filePathList);
// List<String> filePaths = SampleRateConverter.equalSampleRateUseFfmepg(filePathList);
// if (!CollectionUtils.isEmpty(filePaths)) filePathList = filePaths;
// } catch (Exception 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, " ");
filePathList.add(targetFilepath);
CallPython.execute("sox "+ StringUtils.join(filePathList, " "));
List<String> str = filePathList.stream().map(s -> "-i "+s).collect(Collectors.toList());
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))){
// AudioEnumeration<InputStream> audioEnumeration = new AudioEnumeration<>();
......@@ -517,16 +564,16 @@ public class TTSUtils {
// outputStream.flush();
// sequenceInputStream.close();
// }
final List<String> check = new ArrayList<>(filePathList);
TTService.POOL.submit(() -> {
for (String path: check) {
if (StringUtils.endsWith(path, SampleRateConverter.SUFFIX_MP3)) {
if (!new File(path).delete()) log.error("删除采样率mp3出错:{}",path);
// String wavTempPath = path.substring(0, path.length()-8)+SampleRateConverter.SUFFIX_WAV;
// if (!new File(wavTempPath).delete()) log.error("删除采样率wav出错:{}",wavTempPath);
}
}
});
// final List<String> check = new ArrayList<>(filePathList);
// TTService.POOL.submit(() -> {
// for (String path: check) {
// if (StringUtils.endsWith(path, SampleRateConverter.SUFFIX_MP3)) {
// if (!new File(path).delete()) log.error("删除采样率mp3出错:{}",path);
//// String wavTempPath = path.substring(0, path.length()-8)+SampleRateConverter.SUFFIX_WAV;
//// if (!new File(wavTempPath).delete()) log.error("删除采样率wav出错:{}",wavTempPath);
// }
// }
// });
}
/**
......@@ -609,12 +656,6 @@ public class TTSUtils {
}
public static void main(String[] args) throws IOException, UnsupportedAudioFileException {
List<String> list = new ArrayList<>();
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());
UploadCallbackUnzip("/home/yf01/下载/tts/testzip","/home/yf01/下载/testUnzip.zip");
}
}
......@@ -12,7 +12,10 @@ import org.apache.commons.lang3.exception.ExceptionUtils;
import javax.servlet.http.HttpServletResponse;
import java.io.*;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;
import java.util.concurrent.atomic.AtomicInteger;
/**
* 响应构建类
......@@ -22,6 +25,8 @@ import java.util.List;
@Slf4j
public class TTServiceUtil {
private static final Integer MP3_BOUND = 50*1024;
/**
* 构建删除缓存接口的响应信息
* @param response HttpServletResponse对象
......@@ -50,7 +55,7 @@ public class TTServiceUtil {
* @param fileType 是否下载
*/
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);
if (mp3Response != null) {
String ttsResJsonStr = JSON.toJSONString(mp3Response);
......@@ -68,8 +73,11 @@ public class TTServiceUtil {
response.reset();
response.setContentType("audio/mp3");
response.setHeader("Content-Type", "audio/mp3");
response.setHeader("Content-Length", String.valueOf(inputStream.available()));
response.setHeader("Cache-Control", "max-age=43200, public");
int length = inputStream.available();
if (StringUtils.isBlank(xiaoaiCount)) {
response.setHeader("Content-Length", String.valueOf(length));
response.setHeader("Cache-Control", "max-age=43200, public");
}
if (fileType) {
String loadName = fileName.substring(fileName.lastIndexOf("/")+1).trim();
if (StringUtils.isBlank(loadName)) {
......@@ -78,6 +86,33 @@ public class TTServiceUtil {
String value = String.format("attachment;filename=\"%s\"", loadName);
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];
int ln;
while ((ln = inputStream.read(buffer)) != -1) {
......@@ -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接口请求的响应信息
* @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/");
}
}
......@@ -135,8 +135,9 @@ public class TTSController {
*/
@GetMapping("/api/tts/get_audio")
public void mp3(@RequestParam(required = false) String dirs, @RequestParam(required = false) String filename,
@RequestParam(required = false) String _type, HttpServletResponse response) {
ttService.mp3(dirs, filename, _type, response);
@RequestParam(required = false) String _type, @RequestParam(required = false) String xiaoai,
HttpServletResponse response) {
ttService.mp3(dirs, filename, _type, response,xiaoai);
}
// @PostMapping("/api/chatbot")
......@@ -228,4 +229,14 @@ public class TTSController {
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 {
/**
* 默认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)
*/
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)
*/
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_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]
*/
private static final Map<String, Map<String, Integer>> OFFLINE_2_ONLINE;
private static volatile Map<String, Map<String, Integer>> OFFLINE_2_ONLINE;
/**
* 第三方person列表
*/
private static final List<String> THIRD_PARTY_TTS;
private static volatile List<String> THIRD_PARTY_TTS;
/**
* 第三方person及其角色识别标识
......@@ -77,12 +77,12 @@ public class Initialize implements InitializingBean {
* 存储数据结构:
* 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)
*/
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 {
// 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() {
return PERSON_INFO_ONLINE;
}
......
......@@ -40,11 +40,12 @@ public class LieHuSchedule {
new Thread(() -> {
int count = 0;
boolean success = false;
String liehuTokenRes = null;
do {
try {
// String liehuTokenRes = OkHttp3Utils.doGet(TTSConstants.LIE_HU.TOKEN_URL, LIE_HU_TOKEN_PARAMS,
// 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)) {
log.error("对猎户Token发起的请求出错");
return;
......@@ -56,18 +57,18 @@ public class LieHuSchedule {
return;
//log.info("成功获取到猎户Token:{}", LIE_HU_TOKEN);
}else {
log.error("第次{}尝试请求猎户Token失败:{}", count+1,response.getError());
log.error("第次{}尝试请求猎户Token失败->{}, errorMsg:{}", count+1, liehuTokenRes,response.getError());
}
} catch (Exception e) {
log.error("第次{}尝试获取猎户Token异常:{},", count+1,e.toString());
log.error("第次{}尝试获取猎户Token异常,->{} , errorMsg:{},", count+1,liehuTokenRes,e.toString());
}
count++;
try {
Thread.sleep(2*count);
Thread.sleep(5*count);
} catch (Exception e) {
}
} while (!success && count < 10);
} while (!success && count < 15);
}).start();
}
......
......@@ -11,11 +11,6 @@ import com.csvreader.CsvReader;
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.MP3File;
import org.jaudiotagger.tag.TagException;
import javax.sound.sampled.AudioFormat;
import javax.sound.sampled.AudioInputStream;
......@@ -264,27 +259,38 @@ public class Test {
return "3";
}
private static void convert(File input, File outPut) throws IOException, UnsupportedAudioFileException {
AudioInputStream stream = AudioSystem.getAudioInputStream(input);
AudioFormat format = stream.getFormat();
private static void test8(String text) {
List<String> variableTextList = new ArrayList<>();
// 获取AB之间的变量,为空则忽略
Pattern pattern = Pattern.compile(TTSUtils.getAbRegex());
Matcher matcher = pattern.matcher(text);
while (matcher.find()) {
String variableText = matcher.group(1);
if (StringUtils.isNotBlank(variableText)) variableTextList.add(variableText);
}
//log.info("variableTextList:{}",variableTextList);
//不是分段语句则返回false,回到generalMP3方法整体处理
if (variableTextList.size() != 0) {
// 要合并的mp3地址集合
// 人工上传目录, 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());
String[] arrr = pattern.split("回答错误,正确答案为 :风吹草地见牛羊。 当前体力值为 \uD83C\uDD7097\uD83C\uDD71");
System.out.println(Arrays.toString(arrr));
public static void main(String[] args) {
Date date = new Date(1572522571234L);
SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
System.out.println(format.format(new Date()));
ArrayList<String> list = new ArrayList<>();
list.add("/home/yf01/下载/human1.mp3");
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");
SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
System.out.println(TTSUtils.buildMP3Filename("\uD83C\uDD70会数学的杰瑞的类型为:儿童、简单、益智、休闲、教育、学生、免费\uD83C\uDD71"));
System.out.println(TTSUtils.buildMP3Filename("会数学的杰瑞的类型为:儿童、简单、益智、休闲、教育、学生、免费"));
System.out.println(TTSUtils.buildMP3Filename("你当{/dang1/}前{/qian2/}分{/fen1/}数{/shu4/}是"));
System.out.println(TTSUtils.buildMP3Filename("10"));
Pattern pattern = Pattern.compile(TTSUtils.getAbRegex());
String[] notVariableTextArray = pattern.split("\uD83C\uDD70会数学的杰瑞的类型为:儿童、简单、益智、休闲、教育、学生、免费\uD83C\uDD71");
System.out.println(notVariableTextArray.length);
System.out.println(Arrays.toString(notVariableTextArray));
}
}
......@@ -4,7 +4,7 @@ spring:
#password: 3g9^pWQs#ft7
password: qiwu@123234aA~
# 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://didi-gz1.jiaoyou365.com:3306/TTS?useUnicode=true&characterEncoding=utf-8&useSSL=false
# username: tts
......@@ -37,4 +37,5 @@ server:
directory: /home/ubuntu/project/tts/tomcat
max-threads: 1024
# 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
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.toSpeak.ToSpeak;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.codec.binary.StringUtils;
import org.springframework.stereotype.Service;
import java.io.File;
import java.util.*;
import java.util.concurrent.*;
......@@ -284,4 +287,15 @@ public class XiaoAiService {
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 @@
<dependency>
<groupId>com.alibaba</groupId>
<artifactId>fastjson</artifactId>
<version>1.2.60</version>
<version>1.2.62</version>
</dependency>
<!-- https://mvnrepository.com/artifact/net.sourceforge.javacsv/javacsv -->
<dependency>
......@@ -104,6 +104,34 @@
<artifactId>commons-csv</artifactId>
<version>1.7</version>
</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>
<build>
......@@ -112,6 +140,9 @@
<plugin>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-maven-plugin</artifactId>
<configuration>
<includeSystemScope>true</includeSystemScope>
</configuration>
</plugin>
</plugins>
</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;
*/
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 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 PRIVATE_KEY = "MIICdwIBADANBgkqhkiG9w0BAQEFAASCAmEwggJdAgEAAoGBANMWIYduiQZt0B7s" +
"IZ6PW15gpcO7Yn+9ZbaMSHwzJqNeDAZzh6HXF7r0ZpQcw3XEWKPAPWyuJ5eqZf46" +
......@@ -33,6 +37,7 @@ public interface Constants {
String LOAD_INTRO = "扫描二维码输入手机号获取验证码登录";
String REWARD_FLOWER = "请扫码支付";
String UNIT_PRICE = "1";
String PREFIX_USERID = "XIAODU_";
Integer CO_HI_PAGE_SIZE = 4;
Integer RE_RA_CA_PAGE_SIZE = 12;
......@@ -55,7 +60,7 @@ public interface Constants {
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 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 {
......@@ -96,7 +101,16 @@ public interface Constants {
}
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 GUIDE_WORD = "请点击或者直接说出您想要玩的作品名";
String FAIL_COLLECT = "好像出了什么问题,请再说一遍吧";
......@@ -105,6 +119,8 @@ public interface Constants {
interface EndMsg {
String BYE_BYE = "我们的作品库在不断的扩充,欢迎下次再来玩";
String END_BYE_CHILD = "再见啦小朋友,记得下次再来玩哦";
String END_BYE_Adult = "再见啦,记得下次再来玩哦";
String CAN_NOT_UNDERSTAND = "用户无输入或多次输入无法理解";
String USER_SAY_CANCEL = "用户直接说退出";
}
......
package ai.qiwu.com.xiaoduhome.common;
import ai.qiwu.com.xiaoduhome.pojo.AudioBoxData;
import lombok.extern.slf4j.Slf4j;
import okhttp3.*;
import org.apache.commons.lang3.exception.ExceptionUtils;
import org.jetbrains.annotations.NotNull;
import java.io.File;
......@@ -68,7 +70,7 @@ public class OkHttp3Utils {
Headers.Builder headBuilder = request.headers().newBuilder();
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();
// headIterator.forEachRemaining(e -> headBuilder.add(e.getKey(), e.getValue()));
......@@ -106,18 +108,50 @@ public class OkHttp3Utils {
return null;
}
public static void backPostAsync(String url, String requestJsonStr) {
Request.Builder builder = new Request.Builder();
// builder.url(url);
// builder.addHeader("Content-Type", "application/json;charset=utf-8");
public static void asyncPost(String url, String strJson, final AudioBoxData data) {
Request request = new Request.Builder()
.url(url)
.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();
Headers.Builder headBuilder = request.headers().newBuilder();
headBuilder.add("Content-Type", "application/json;charset=utf-8");
@Override
public void onResponse(@NotNull Call call, @NotNull Response response) throws IOException {
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);
builder.post(RequestBody.create(MediaType.parse("application/json; charset=utf-8"), requestJsonStr));
client.newCall(builder.build()).enqueue(new Callback() {
public static void backPostAsync(String url, String requestJsonStr, Integer type) {
String header = "jiaoyou-audio-test";
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
public void onFailure(@NotNull Call call, @NotNull IOException e) {
log.info("退出失败");
......@@ -125,12 +159,46 @@ public class OkHttp3Utils {
@Override
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 request = builder.url(url).build();
......@@ -140,12 +208,12 @@ public class OkHttp3Utils {
headIterator.forEachRemaining(e -> headBuilder.add(e.getKey(), e.getValue()));
MultipartBody.Builder requestBuilder = new MultipartBody.Builder();
Iterator<Map.Entry<String, String>> paramsIterator = params.entrySet().iterator();
paramsIterator.forEachRemaining(e -> requestBuilder.addFormDataPart(e.getKey(), e.getValue()));
System.out.println(params);
params.forEach(requestBuilder::addFormDataPart);
if (file != null) {
requestBuilder.addFormDataPart("uploadFiles", file.getName(),
RequestBody.create(MediaType.parse("application/octet-stream"), file));
requestBuilder.addFormDataPart("file", file.getName(),
RequestBody.create(MediaType.parse("audio/mpeg"), file));
}
builder.headers(headBuilder.build()).post(requestBuilder.build());
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;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.*;
import javax.servlet.http.HttpServletRequest;
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;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
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.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;
import javax.servlet.http.HttpServletResponse;
import java.io.File;
/**
* @author 苗权威
* @dateTime 19-9-4 下午2:13
*/
@Controller
@RequestMapping("/xiaoduhome/img")
@RestController
//@RequestMapping("/xiaoduhome/img")
public class UpLoadImgController {
@GetMapping("/up")
// @GetMapping("/up")
public String uploadImage() {
return "linPicture";
}
@PostMapping("/up")
// @PostMapping("/up")
public @ResponseBody
void loadImage(MultipartFile file, String storyName, String imageType) {
StringBuilder builder = new StringBuilder("/root/GameEditor/mqw/xiaoduhome/image/tmp/");
......@@ -37,4 +35,8 @@ public class UpLoadImgController {
e.printStackTrace();
}
}
public void download(HttpServletResponse response) {
}
}
......@@ -11,21 +11,6 @@ import org.springframework.web.bind.annotation.*;
@Controller
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")
public String logIndexPage(ModelMap modelMap) {
return "index.html";
......@@ -50,4 +35,10 @@ public class WebSocketLogController {
public String logdu2Page(ModelMap modelMap) {
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;
import ai.qiwu.com.xiaoduhome.common.Utils;
import ai.qiwu.com.xiaoduhome.service.DplBotService;
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.response.XiaoAiResponse;
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 org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
......@@ -13,6 +18,7 @@ import org.springframework.util.ResourceUtils;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;
import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.util.Map;
import java.util.UUID;
......@@ -22,60 +28,97 @@ import java.util.UUID;
* @dateTime 19-7-26 下午9:27
*/
@RestController
@RequestMapping("/xiaoduhome")
@Slf4j
public class XiaoDuHomeController {
/**
* 功能实现类
*/
@Autowired
private XiaoAiService xiaoAiService;
@RequestMapping("/chat") //互动天地
public String chat() {
try {
//log.info("--------------分界线-------------------");
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;
}
/**
* Controller控制器
* @param request
* @return
*/
@RequestMapping("/xiaoai")
public XiaoAiResponse xiaoai(@RequestBody XiaoAiRequest request) {
//log.info("请求:"+request);
XiaoAiResponse response = xiaoAiService.getResponse(request);
// log.info("响应:"+response);
return response;
// return xiaoAiService.getResponse(request);
@RequestMapping("/story") //交互故事
public String story() {
try {
//log.info("--------------分界线-------------------");
DplBotService service = new DplBotService(Utils.getHttpServletRequest(), 3);
// 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("/xiaoai/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("/literature") // 互动文艺
public String literature() {
try {
//log.info("--------------分界线-------------------");
DplBotService service = new DplBotService(Utils.getHttpServletRequest(),4);
// 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("/xiaoai/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("/smart") // 智能故事
public String smart() {
try {
//log.info("--------------分界线-------------------");
DplBotService service = new DplBotService(Utils.getHttpServletRequest(), 1);
// 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("/xiaoduhome/chat")
public String chat() {
@RequestMapping("/novel") // 智能小说
public String novel() {
try {
//log.info("--------------分界线-------------------");
DplBotService service = new DplBotService(Utils.getHttpServletRequest());
DplBotService service = new DplBotService(Utils.getHttpServletRequest(), 2);
// log.info("请求信息中的attributes:{}", service.getRequest().getSession().getAttributes());
// log.info(service.getStrRequest());
//service.disableVerify();
service.enableVerify();
String str = service.run();
//log.info("响应信息:{}", str);
// log.info("响应信息:{}", str);
return str;
} catch (Exception e) {
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 {
}
static void test7() {
String regex = "{[/].+?[/]}";
String regex = "[/].+?[/]}";
String s = "/home/yf01/下载/xiaorong2.csv";
Pattern pattern = Pattern.compile(regex);
CSVFormat format = CSVFormat.DEFAULT.withHeader("内部代号", "句子", "是否已上传音频文件", "音频文件名");
......
......@@ -629,7 +629,7 @@ public class DplbotServiceUtil {
return name;
}
static List<String> seperateActor(String text, Pattern pattern) {
public static List<String> seperateActor(String text, Pattern pattern) {
Matcher matcher = pattern.matcher(text);
List<String> actorList = new ArrayList<>();
while (matcher.find()) {
......@@ -640,7 +640,7 @@ public class DplbotServiceUtil {
return actorList;
}
static String[] seperateActorWord(String text, Pattern pattern) {
public static String[] seperateActorWord(String text, Pattern pattern) {
String[] actorWords = pattern.split(text);
if (StringUtils.startsWith(text.trim(), "【")) {
actorWords = ArrayUtils.remove(actorWords, 0);
......
......@@ -6,6 +6,7 @@ import ai.qiwu.com.xiaoduhome.common.Utils;
import ai.qiwu.com.xiaoduhome.pojo.QiWuRequest;
import ai.qiwu.com.xiaoduhome.pojo.QiWuResponse;
import ai.qiwu.com.xiaoduhome.pojo.playAside.AsideImageResponse;
import ai.qiwu.com.xiaoduhome.spirit.SpiritTerminateRequest;
import com.alibaba.fastjson.JSON;
import lombok.extern.slf4j.Slf4j;
import org.slf4j.Logger;
......@@ -22,48 +23,84 @@ import java.util.Random;
@Slf4j
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();
requestPojo.setUid(userId);
// requestPojo.setAccess(Constants.SERVICE_NAME);
requestPojo.setMsg(userWord);
String requestJsonStr = JSON.toJSONString(requestPojo);
// 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;
// log.info("返回信息:{}", resStr);
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();
requestPojo.setUid(userId);
// requestPojo.setAccess(Constants.SERVICE_NAME);
requestPojo.setMsg(userWord);
String requestJsonStr = JSON.toJSONString(requestPojo);
// 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;
// log.info("返回信息:{}", resStr);
return JSON.parseObject(resStr, QiWuResponse.class);
}
static void backRequest(String userId) {
static void backRequest(String userId, int type) {
QiWuRequest requestPojo = new QiWuRequest();
requestPojo.setUid(userId);
// requestPojo.setAccess(Constants.SERVICE_NAME);
requestPojo.setMsg("退出");
requestPojo.setMsg("退出当前作品");
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();
requestPojo.setUid(userId);
// requestPojo.setAccess(Constants.SERVICE_NAME);
requestPojo.setMsg("退出");
requestPojo.setMsg("退出当前作品");
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 {
......
......@@ -164,7 +164,7 @@ public class ResponseEncapsulation extends AudioPlayer {
}else {
QiWuResponse data = null;
try {
data = RequestTerminal.requestTerminate(userId, userWord);
data = RequestTerminal.requestTerminate(userId, userWord, 1);
} catch (Exception e) {
log.error("请求终端接口出错:{}", e.toString());
}
......
......@@ -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.XiaoDuOrderTbRepository;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import lombok.extern.slf4j.Slf4j;
import okhttp3.OkHttpClient;
import org.apache.commons.lang3.StringUtils;
import org.apache.commons.lang3.exception.ExceptionUtils;
import org.springframework.beans.factory.InitializingBean;
import org.springframework.beans.factory.annotation.Autowired;
......@@ -72,6 +75,8 @@ public class ScheduleService implements InitializingBean {
static volatile Long curTime = System.currentTimeMillis();
public static volatile Map<String, String> channelId2RecommendBotAcc = new HashMap<>();
@Autowired
public ScheduleService(GameProjectTbRepository gameProjectTbRepository,
ProjectLabelRepository projectLabelRepository,
......@@ -218,6 +223,36 @@ public class ScheduleService implements InitializingBean {
}).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() {
DplbotServiceUtil.getPOOL().submit(() -> {
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 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;
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.QiWuResponse;
import ai.qiwu.com.xiaoduhome.xiaoai.service.XiaoAiService;
......@@ -18,6 +19,22 @@ import java.util.HashMap;
@Slf4j
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
......@@ -25,27 +42,37 @@ public class RequestTerminal {
* @return mp3链接及文字描述
* @throws IOException
*/
public static QiWuResponse requestTerminate(String userId, String userWord, Integer type) throws IOException {
QiWuRequest requestPojo = new QiWuRequest();
public static String requestTerminate(String userId, String userWord, Integer type) 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");
if (NumberUtils.INTEGER_ONE.equals(type)) headers.put("App-Channel-Id", "jiaoyou-audio-child-test");
else if (NumberUtils.INTEGER_TWO.equals(type)) headers.put("App-Channel-Id", "jiaoyou-audio-adult-test");
else headers.put("App-Channel-Id", "jiaoyou-audio-test");
HashMap<String, String> headers;
if (type != null) {
if ((type & 1) == 1) headers = CHILD_HEADERS;
else headers = ADULT_HEADERS;
} else {
headers = ALL_HEADERS;
}
String resStr;
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);
}else {
resStr = OkHttp3Utils.doPostJsonStr(XiaoAiConstants.QI_WU_TERMINATE_DIDI, requestJsonStr, headers);
}
if (resStr == null) {
return null;
return resStr;
}
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;
*/
public interface XiaoAiConstants {
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 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 CONTENT_TYPE = "application/json;charset=utf-8";
String PLAYBACK_NEARLY_FINISHED = "mediaplayer.playbacknearlyfinished";
String PREFIX_USERID="XIAOAI_";
interface ERROR_MSG {
......@@ -21,9 +25,11 @@ public interface XiaoAiConstants {
}
interface TTS {
String WELCOME_WORD = "欢迎来到交游天下,海量的作品在这等您";
String WELCOME_WORD_CHILD = "小朋友你好,欢迎来到智能故事";
String WELCOME_WORD_Adult = "你好,欢迎来到智能小说";
String WELCOME_WORD = "欢迎来到交游天下,海量的作品在这等您,你可以说推荐作品给我";
String WELCOME_WORD_CHILD = "小朋友你好,欢迎来到智能故事,你可以说推荐作品给我";
String WELCOME_WORD_CHILD_STORY = "小朋友你好,欢迎来到互动故事,你可以说推荐作品给我";
String WELCOME_WORD_Adult = "你好,欢迎来到智能小说,你可以说推荐作品给我";
String WELCOME_WORD_Adult_literature = "你好,欢迎来到互动文艺,你可以说推荐作品给我";
String END_BYE = "我们的作品库在不断扩充,欢迎再来玩";
String END_BYE_CHILD = "再见啦小朋友,记得下次再来玩哦";
String END_BYE_Adult = "再见啦,记得下次再来玩哦";
......
......@@ -12,4 +12,6 @@ import lombok.ToString;
public class QiWuResponse {
private String audio;
private String text;
private String extraChatKey;
private String mainChatKey;
}
......@@ -12,5 +12,9 @@ import lombok.ToString;
@Setter
@ToString
public class RegisterEvent {
public RegisterEvent(String event_name) {
this.event_name = event_name;
}
private String event_name;
}
......@@ -7,12 +7,17 @@ spring:
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.jdbc.Driver
driver-class-name: com.mysql.cj.jdbc.Driver
secondary:
jdbc-url: jdbc:mysql://localhost:3306/audiobox?useUnicode=true&characterEncoding=utf-8&serverTimezone=Hongkong&useSSL=false
username: root
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:
database: mysql
#控制台显示SQL
......@@ -27,4 +32,6 @@ logging:
level:
root: info
okhttp3:
OkHttpClient: FINE
\ No newline at end of file
OkHttpClient: FINE
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
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