Commit 42683448 by 苗权威

8.17

parent cd7a7e18
<?xml version="1.0" encoding="UTF-8"?>
<project version="4">
<component name="dataSourceStorageLocal">
<data-source name="xiaoduHomeSql" uuid="eca35561-cff4-46e2-adf3-8f0830701325">
<database-info product="" version="" jdbc-version="" driver-name="" driver-version="" dbms="MYSQL" exact-version="0" />
<secret-storage>master_key</secret-storage>
<user-name>root</user-name>
</data-source>
</component>
</project>
\ No newline at end of file
<?xml version="1.0" encoding="UTF-8"?>
<project version="4">
<component name="DataSourceManagerImpl" format="xml" multifile-model="true">
<data-source source="LOCAL" name="xiaoduHomeSql" uuid="eca35561-cff4-46e2-adf3-8f0830701325">
<driver-ref>mysql</driver-ref>
<synchronize>true</synchronize>
<jdbc-driver>com.mysql.jdbc.Driver</jdbc-driver>
<jdbc-url>jdbc:mysql://localhost:3306/TTS</jdbc-url>
<driver-properties>
<property name="autoReconnect" value="true" />
<property name="zeroDateTimeBehavior" value="convertToNull" />
<property name="tinyInt1isBit" value="false" />
<property name="characterEncoding" value="utf8" />
<property name="characterSetResults" value="utf8" />
<property name="yearIsDateType" value="false" />
</driver-properties>
</data-source>
</component>
</project>
\ No newline at end of file
<?xml version="1.0" encoding="UTF-8"?>
<project version="4">
<component name="SqlDialectMappings">
<file url="PROJECT" dialect="MySQL" />
</component>
</project>
\ No newline at end of file
This source diff could not be displayed because it is too large. You can view the blob instead.
...@@ -24,7 +24,7 @@ public class OfflineController { ...@@ -24,7 +24,7 @@ public class OfflineController {
} }
@GetMapping("/synthesize") @GetMapping("/synthesize")
public void speakers_api(@RequestParam(required = false) String person, @RequestParam(required = false) String tone, public void speakers_get(@RequestParam(required = false) String person, @RequestParam(required = false) String tone,
@RequestParam(required = false) String server, @RequestParam(required = false) String text, @RequestParam(required = false) String server, @RequestParam(required = false) String text,
@RequestParam(required = false) String botname, @RequestParam(required = false)String volume, @RequestParam(required = false) String botname, @RequestParam(required = false)String volume,
@RequestParam(required = false) String pitch, @RequestParam(required = false) String speed, @RequestParam(required = false) String pitch, @RequestParam(required = false) String speed,
...@@ -36,12 +36,12 @@ public class OfflineController { ...@@ -36,12 +36,12 @@ public class OfflineController {
} }
@PostMapping("/synthesize") @PostMapping("/synthesize")
public void speakers_api(@RequestBody SpeakersApi api, HttpServletResponse response) { public void speakers_post(@RequestBody SpeakersApi api, HttpServletResponse response) {
offlineService.speakers_api(api, response, "POST"); offlineService.speakers_api(api, response, "POST");
} }
@PutMapping("/synthesize") @PutMapping("/synthesize")
public void speakers(@RequestBody SpeakersApi api, HttpServletResponse response) { public void speakers_put(@RequestBody SpeakersApi api, HttpServletResponse response) {
offlineService.speakers_api(api, response, "PUT"); offlineService.speakers_api(api, response, "PUT");
} }
......
...@@ -65,6 +65,18 @@ ...@@ -65,6 +65,18 @@
<artifactId>commons-lang3</artifactId> <artifactId>commons-lang3</artifactId>
<version>3.9</version> <version>3.9</version>
</dependency> </dependency>
<!-- https://mvnrepository.com/artifact/com.baidu.aip/java-sdk -->
<dependency>
<groupId>com.baidu.aip</groupId>
<artifactId>java-sdk</artifactId>
<exclusions>
<exclusion>
<groupId>org.slf4j</groupId>
<artifactId>slf4j-log4j12</artifactId>
</exclusion>
</exclusions>
<version>4.11.3</version>
</dependency>
<!--&lt;!&ndash; https://mvnrepository.com/artifact/org.python/jython-standalone &ndash;&gt;--> <!--&lt;!&ndash; https://mvnrepository.com/artifact/org.python/jython-standalone &ndash;&gt;-->
<!--<dependency>--> <!--<dependency>-->
<!--<groupId>org.python</groupId>--> <!--<groupId>org.python</groupId>-->
......
...@@ -4,10 +4,12 @@ import org.springframework.boot.SpringApplication; ...@@ -4,10 +4,12 @@ import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication; import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.boot.autoconfigure.domain.EntityScan; import org.springframework.boot.autoconfigure.domain.EntityScan;
import org.springframework.data.jpa.repository.config.EnableJpaRepositories; import org.springframework.data.jpa.repository.config.EnableJpaRepositories;
import org.springframework.scheduling.annotation.EnableScheduling;
@SpringBootApplication @SpringBootApplication
@EntityScan(basePackages = {"ai.qiwu.com.tts_service.entity"}) @EntityScan(basePackages = {"ai.qiwu.com.tts_service.entity"})
@EnableJpaRepositories(basePackages = {"ai.qiwu.com.tts_service.repository"}) @EnableJpaRepositories(basePackages = {"ai.qiwu.com.tts_service.repository"})
@EnableScheduling
public class TtsServiceApplication { public class TtsServiceApplication {
public static void main(String[] args) { public static void main(String[] args) {
......
...@@ -9,7 +9,11 @@ import lombok.Setter; ...@@ -9,7 +9,11 @@ import lombok.Setter;
*/ */
public enum ErrorMsgEnum { public enum ErrorMsgEnum {
FAIL_DEL_OFFLINE_BOT(1001, "删除offline地址的bot请求出错"), FAIL_DEL_OFFLINE_BOT(1001, "删除offline地址的bot请求出错"),
FAIL_IN_CREATE_DIR(1002, "创建文件失败"); FAIL_IN_CREATE_DIR(1002, "创建文件失败"),
BAI_DU_NOT_SUPPORT(500, "不支持的输入"),
BAI_DU_PARAMS_NOT_RIGHT(501, "输入参数不正确"),
BAI_DU_TOKEN_FAIL(502, "token验证失败"),
BAI_DU_SYNTHESIS(503, "合成后端错误");
private int code; private int code;
private String msg; private String msg;
......
...@@ -8,6 +8,7 @@ import okio.Okio; ...@@ -8,6 +8,7 @@ import okio.Okio;
import java.io.File; import java.io.File;
import java.io.IOException; import java.io.IOException;
import java.net.SocketTimeoutException;
import java.util.HashMap; import java.util.HashMap;
import java.util.Iterator; import java.util.Iterator;
import java.util.Map; import java.util.Map;
...@@ -20,9 +21,17 @@ import java.util.concurrent.TimeUnit; ...@@ -20,9 +21,17 @@ import java.util.concurrent.TimeUnit;
*/ */
@Slf4j @Slf4j
public class OkHttp3Utils { public class OkHttp3Utils {
private static final OkHttpClient client = new OkHttpClient.Builder().connectTimeout(12, TimeUnit.SECONDS).build(); private static final OkHttpClient client = new OkHttpClient.Builder()
.connectTimeout(15, TimeUnit.SECONDS)
private static final OkHttpClient ShortTimeoutClient = new OkHttpClient.Builder().connectTimeout(3, TimeUnit.SECONDS).build(); .readTimeout(15, TimeUnit.SECONDS)
.writeTimeout(20, TimeUnit.SECONDS)
.build();
private static final OkHttpClient ShortTimeoutClient = new OkHttpClient.Builder()
.connectTimeout(8, TimeUnit.SECONDS)
.readTimeout(8, TimeUnit.SECONDS)
.writeTimeout(10, TimeUnit.SECONDS)
.build();
public static String doGet(String url) throws IOException { public static String doGet(String url) throws IOException {
return doGet(url, new HashMap<>()); return doGet(url, new HashMap<>());
...@@ -50,6 +59,34 @@ public class OkHttp3Utils { ...@@ -50,6 +59,34 @@ public class OkHttp3Utils {
} }
} }
public static byte[] lieHudoGet(String url, Map<String, String> params, Map<String, String> header) throws IOException {
Request.Builder builder = new Request.Builder();
Request request = builder.url(url).build();
HttpUrl.Builder urlBuild = request.url().newBuilder();
Headers.Builder headerBuilder = request.headers().newBuilder();
Iterator<Map.Entry<String, String>> headIterator = header.entrySet().iterator();
headIterator.forEachRemaining(e -> headerBuilder.add(e.getKey(), e.getValue()));
Iterator<Map.Entry<String, String>> paramsIterator = params.entrySet().iterator();
paramsIterator.forEachRemaining(e -> urlBuild.addQueryParameter(e.getKey(), e.getValue()));
builder.url(urlBuild.build()).headers(headerBuilder.build());
try (Response response = client.newCall(builder.build()).execute()){
String contentType = response.header("Content-Type");
if ("audio/pcm".equals(contentType)) {
return response.body().bytes();
}else {
log.error("猎狐返回的response中Content-Type不是audio/pcm,是{}, json数据:{}", contentType, response.body().string());
}
}catch (SocketTimeoutException e) {
log.error("捕获到SocketTimeoutException:{}", e.toString());
client.dispatcher().cancelAll();
client.connectionPool().evictAll();
}
return null;
}
public static String doPost(String url, Map<String, String> params) throws IOException { public static String doPost(String url, Map<String, String> params) throws IOException {
return doPost(url, new HashMap<>(), params,null); return doPost(url, new HashMap<>(), params,null);
} }
...@@ -110,7 +147,12 @@ public class OkHttp3Utils { ...@@ -110,7 +147,12 @@ public class OkHttp3Utils {
} }
} }
return codeWithData; return codeWithData;
}catch (SocketTimeoutException e) {
log.error("捕获到SocketTimeoutException:{}", e.toString());
client.dispatcher().cancelAll();
client.connectionPool().evictAll();
} }
return null;
} }
public static String doPost(String url, Map<String, String> headers, Map<String, String> params, File file) throws IOException { public static String doPost(String url, Map<String, String> headers, Map<String, String> params, File file) throws IOException {
...@@ -204,6 +246,11 @@ public class OkHttp3Utils { ...@@ -204,6 +246,11 @@ public class OkHttp3Utils {
builder.headers(headBuilder.build()).delete(RequestBody.create(MediaType.parse("application/json; charset=utf-8"), jsonStr)); builder.headers(headBuilder.build()).delete(RequestBody.create(MediaType.parse("application/json; charset=utf-8"), jsonStr));
try (Response response = client.newCall(builder.build()).execute()){ try (Response response = client.newCall(builder.build()).execute()){
return response.code(); return response.code();
}catch (SocketTimeoutException e) {
log.error("捕获到SocketTimeoutException:{}", e.toString());
client.dispatcher().cancelAll();
client.connectionPool().evictAll();
} }
return 555;
} }
} }
...@@ -12,11 +12,27 @@ public interface TTSConstants { ...@@ -12,11 +12,27 @@ public interface TTSConstants {
String ONLINE_SERVER = "http://dev01.centaurstech.com"; String ONLINE_SERVER = "http://dev01.centaurstech.com";
String OFFLINE_SERVER ="http://aliyun-hz1.chewrobot.com:9001"; String OFFLINE_SERVER ="http://aliyun-hz1.chewrobot.com:9001";
String SERVER_NAME = "hz1"; String SERVER_NAME = "hz1";
// String AUDIO_DIR = "/root/GameEditor/mqw/tts/audio"; String AUDIO_DIR = "/root/GameEditor/mqw/tts/audio";
String AUDIO_DIR = "/usr/GameEditor/mqw/tts/audio"; //String AUDIO_DIR = "/usr/GameEditor/mqw/tts/audio";
String SERVER_URL= "aliyun-hz1.chewrobot.com:9663"; String SERVER_URL= "aliyun-hz1.chewrobot.com:9663";
String THIRD_PARTY_TTS_TEXT = "third_party_tts"; String THIRD_PARTY_TTS_TEXT = "third_party_tts";
String DELETE_SUCCESS = "删除文件成功"; String DELETE_SUCCESS = "删除文件成功";
String DELETE_FAIL = "删除文件失败"; String DELETE_FAIL = "删除文件失败";
String DELETE_OFFLINE_FAIL = "对线下测试服务器的删除指令调用失败"; String DELETE_OFFLINE_FAIL = "对线下测试服务器的删除指令调用失败";
interface BAI_DU {
String APP_ID = "16998411";
String API_KEY = "bHlKRYe9d5o7Ad2z2D5aGiVw";
String SECRET_KEY = "f5bGP0PapVqSdl8gAOKGawHGlsSnHulB";
}
interface LIE_HU {
String CLIENT_ID = "orion.asrtts.1558690632399";
String CLIENT_SECRET = "7a40f0e6fd05d527c1dc94b6974612a2";
String PDT = "7234";
String URL_HOST = "speech.ainirobot.com";
String TOKEN_URL = "https://speech.ainirobot.com/asr-auth/token/apply";
String URL = "https://speech.ainirobot.com/tts/v1/text2audio";
String AUTHORIZATION = "Bearer ";
}
} }
...@@ -44,7 +44,7 @@ public class TTSUtils { ...@@ -44,7 +44,7 @@ public class TTSUtils {
public static boolean createFile(String path) throws IOException { public static boolean createFile(String path) throws IOException {
File file = new File(path); File file = new File(path);
boolean createResult = false; boolean createResult = true;
if (!file.exists() || file.isDirectory()) { if (!file.exists() || file.isDirectory()) {
createResult = file.createNewFile(); createResult = file.createNewFile();
} }
...@@ -59,12 +59,12 @@ public class TTSUtils { ...@@ -59,12 +59,12 @@ public class TTSUtils {
return file; return file;
} }
public static boolean createFile(String dir, String fileName) { public static String createFile(String dir, String fileName) {
try { try {
makedir(dir); makedir(dir);
} catch (Exception e) { } catch (Exception e) {
log.error("创建目录:{}失败", dir); log.error("创建目录:{}失败", dir);
return false; return null;
} }
String file = buildMP3Filename(fileName); String file = buildMP3Filename(fileName);
String filePath = StringUtils.join(new String[]{dir, file}, File.separator); String filePath = StringUtils.join(new String[]{dir, file}, File.separator);
...@@ -73,17 +73,18 @@ public class TTSUtils { ...@@ -73,17 +73,18 @@ public class TTSUtils {
createFileResult = createFile(filePath); createFileResult = createFile(filePath);
} catch (Exception e) { } catch (Exception e) {
log.error("创建文件:{}出错:{}", fileName,e.toString()); log.error("创建文件:{}出错:{}", fileName,e.toString());
return false; return null;
} }
if (!createFileResult) { if (!createFileResult) {
log.error("创建文件:{}失败", fileName); log.error("创建文件:{}失败", fileName);
return null;
} }
return createFileResult; return filePath;
} }
public static String buildMP3Filename(String filename) { public static String buildMP3Filename(String filename) {
String file = DigestUtils.md5DigestAsHex(filename.getBytes(StandardCharsets.UTF_8)); String file = DigestUtils.md5DigestAsHex(filename.getBytes(StandardCharsets.UTF_8));
file = StringUtils.join(new String[]{file, "mp3"}, "."); file = file+".mp3";
return file; return file;
} }
...@@ -261,17 +262,4 @@ public class TTSUtils { ...@@ -261,17 +262,4 @@ public class TTSUtils {
return result; return result;
} }
} }
public static void main(String[] args) {
String s = "python -u a.py -a A -b B -o test";
String s2 = " python -u a.py -a A -b B -o test ";
String s3 = " python -u a.py -a A -b B -o test ";
String s4 = " ";
String s5 = " b ";
shlexSplit(s, new ArrayList<>());
shlexSplit(s2, new ArrayList<>());
shlexSplit(s3, new ArrayList<>());
shlexSplit(s4, new ArrayList<>());
shlexSplit(s5, new ArrayList<>());
}
} }
package ai.qiwu.com.tts_service.common.pcm;
import java.nio.ByteBuffer;
import java.util.Arrays;
/**
* @author 苗权威
* @dateTime 19-8-14 下午2:21
*/
public class ByteUtils {
/**
* short[] 转 byte[]
*/
public static byte[] toBytes(short[] src) {
int count = src.length;
byte[] dest = new byte[count << 1];
for (int i = 0; i < count; i++) {
dest[i * 2] = (byte) (src[i]);
dest[i * 2 + 1] = (byte) (src[i] >> 8);
}
return dest;
}
/**
* short[] 转 byte[]
*/
public static byte[] toBytes(short src) {
byte[] dest = new byte[2];
dest[0] = (byte) (src);
dest[1] = (byte) (src >> 8);
return dest;
}
/**
* int 转 byte[]
*/
public static byte[] toBytes(int i) {
byte[] b = new byte[4];
b[0] = (byte) (i & 0xff);
b[1] = (byte) ((i >> 8) & 0xff);
b[2] = (byte) ((i >> 16) & 0xff);
b[3] = (byte) ((i >> 24) & 0xff);
return b;
}
/**
* String 转 byte[]
*/
public static byte[] toBytes(String str) {
return str.getBytes();
}
/**
* long类型转成byte数组
*/
public static byte[] toBytes(long number) {
ByteBuffer buffer = ByteBuffer.allocate(8);
buffer.putLong(0, number);
return buffer.array();
}
public static int toInt(byte[] src, int offset) {
return ((src[offset] & 0xFF)
| ((src[offset + 1] & 0xFF) << 8)
| ((src[offset + 2] & 0xFF) << 16)
| ((src[offset + 3] & 0xFF) << 24));
}
public static int toInt(byte[] src) {
return toInt(src, 0);
}
/**
* 字节数组到long的转换.
*/
public static long toLong(byte[] b) {
ByteBuffer buffer = ByteBuffer.allocate(8);
buffer.put(b, 0, b.length);
return buffer.getLong();
}
/**
* byte[] 转 short[]
* short: 2字节
*/
public static short[] toShorts(byte[] src) {
int count = src.length >> 1;
short[] dest = new short[count];
for (int i = 0; i < count; i++) {
dest[i] = (short) ((src[i * 2] & 0xff) | ((src[2 * i + 1] & 0xff) << 8));
}
return dest;
}
public static byte[] merger(byte[] bt1, byte[] bt2) {
byte[] bt3 = new byte[bt1.length + bt2.length];
System.arraycopy(bt1, 0, bt3, 0, bt1.length);
System.arraycopy(bt2, 0, bt3, bt1.length, bt2.length);
return bt3;
}
public static String toString(byte[] b) {
return Arrays.toString(b);
}
}
package ai.qiwu.com.tts_service.common.pcm;
import ai.qiwu.com.tts_service.service.baidu.ThirdPartyService;
import lombok.extern.slf4j.Slf4j;
import javax.sound.sampled.AudioFileFormat;
import javax.sound.sampled.AudioFormat;
import javax.sound.sampled.AudioInputStream;
import javax.sound.sampled.AudioSystem;
import java.io.*;
/**
* @author 苗权威
* @dateTime 19-8-14 下午12:15
*/
@Slf4j
public class Pcm2Wav {
public static void pcm2Wav(byte[] data, String dest) {
// float sampleRate = 16000;
// int sampleSizeInBits = 16;
// int channels = 1;
// boolean signed = true;
// boolean bigEndian = false;
AudioFormat audioFormat = new AudioFormat(AudioFormat.Encoding.PCM_SIGNED,16000, 16, 1, 1, 16000, false);
try (FileOutputStream out = new FileOutputStream(new File(dest));
ByteArrayInputStream byteInput = new ByteArrayInputStream(data);
AudioInputStream audioInputStream = new AudioInputStream(byteInput, audioFormat, data.length)){
AudioSystem.write(audioInputStream, AudioFileFormat.Type.WAVE, out);
out.flush();
} catch (IOException e) {
log.error("pcm转换成wav出错:{}", e.toString());
}
}
public static void main(String[] args) {
// ThirdPartyService.lieHuTTS("绿洲有美丽的风景,好吃的食物,湛蓝的天空,蔚蓝的海洋", "1", "/home/yf01/testPcm.wav");
}
}
package ai.qiwu.com.tts_service.common.pcm;
/**
* @author 苗权威
* @dateTime 19-8-14 下午2:20
*/
public class WavFileHeader {
/**
* RIFF数据块
*/
final String riffChunkId = "RIFF";
int riffChunkSize;
final String riffType = "WAVE";
/**
* FORMAT 数据块
*/
final String formatChunkId = "fmt ";
final int formatChunkSize = 16;
final short audioFormat = 1;
short channels;
int sampleRate;
int byteRate;
short blockAlign;
short sampleBits;
/**
* FORMAT 数据块
*/
final String dataChunkId = "data";
int dataChunkSize;
WavFileHeader(int totalAudioLen, int sampleRate, short channels, short sampleBits) {
this.riffChunkSize = totalAudioLen;
this.channels = channels;
this.sampleRate = sampleRate;
this.byteRate = sampleRate * sampleBits / 8 * channels;
this.blockAlign = (short) (channels * sampleBits / 8);
this.sampleBits = sampleBits;
this.dataChunkSize = totalAudioLen - 44;
}
public byte[] getHeader() {
byte[] result;
result = ByteUtils.merger(ByteUtils.toBytes(riffChunkId), ByteUtils.toBytes(riffChunkSize));
result = ByteUtils.merger(result, ByteUtils.toBytes(riffType));
result = ByteUtils.merger(result, ByteUtils.toBytes(formatChunkId));
result = ByteUtils.merger(result, ByteUtils.toBytes(formatChunkSize));
result = ByteUtils.merger(result, ByteUtils.toBytes(audioFormat));
result = ByteUtils.merger(result, ByteUtils.toBytes(channels));
result = ByteUtils.merger(result, ByteUtils.toBytes(sampleRate));
result = ByteUtils.merger(result, ByteUtils.toBytes(byteRate));
result = ByteUtils.merger(result, ByteUtils.toBytes(blockAlign));
result = ByteUtils.merger(result, ByteUtils.toBytes(sampleBits));
result = ByteUtils.merger(result, ByteUtils.toBytes(dataChunkId));
result = ByteUtils.merger(result, ByteUtils.toBytes(dataChunkSize));
return result;
}
}
package ai.qiwu.com.tts_service.common.pcm;
import lombok.Setter;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
/**
* @author 苗权威
* @dateTime 19-8-14 下午12:16
*/
@Setter
public class WavHeader {
private final char fileID[] = {'R', 'I', 'F', 'F'};
private int fileLength;
private char wavTag[] = {'W', 'A', 'V', 'E'};;
private char FmtHdrID[] = {'f', 'm', 't', ' '};
private int FmtHdrLeth;
private short FormatTag;
private short Channels;
private int SamplesPerSec;
private int AvgBytesPerSec;
private short BlockAlign;
private short BitsPerSample;
private char DataHdrID[] = {'d','a','t','a'};
private int DataHdrLeth;
public WavHeader() {
}
public WavHeader(int fileLength, int fmtHdrLeth, short formatTag, short channels,
int samplesPerSec, int avgBytesPerSec, short blockAlign, short bitsPerSample, int dataHdrLeth) {
this.fileLength = fileLength;
FmtHdrLeth = fmtHdrLeth;
FormatTag = formatTag;
Channels = channels;
SamplesPerSec = samplesPerSec;
AvgBytesPerSec = avgBytesPerSec;
BlockAlign = blockAlign;
BitsPerSample = bitsPerSample;
DataHdrLeth = dataHdrLeth;
}
public byte[] getHeader() throws IOException {
ByteArrayOutputStream bos = new ByteArrayOutputStream();
WriteChar(bos, fileID);
WriteInt(bos, fileLength);
WriteChar(bos, wavTag);
WriteChar(bos, FmtHdrID);
WriteInt(bos,FmtHdrLeth);
WriteShort(bos,FormatTag);
WriteShort(bos,Channels);
WriteInt(bos,SamplesPerSec);
WriteInt(bos,AvgBytesPerSec);
WriteShort(bos,BlockAlign);
WriteShort(bos,BitsPerSample);
WriteChar(bos,DataHdrID);
WriteInt(bos,DataHdrLeth);
bos.flush();
byte[] r = bos.toByteArray();
bos.close();
return r;
}
private void WriteShort(ByteArrayOutputStream bos, int s) throws IOException {
byte[] mybyte = new byte[2];
mybyte[1] =(byte)( (s << 16) >> 24 );
mybyte[0] =(byte)( (s << 24) >> 24 );
bos.write(mybyte);
}
private void WriteInt(ByteArrayOutputStream bos, int n) throws IOException {
byte[] buf = new byte[4];
buf[3] =(byte)( n >> 24 );
buf[2] =(byte)( (n << 8) >> 24 );
buf[1] =(byte)( (n << 16) >> 24 );
buf[0] =(byte)( (n << 24) >> 24 );
bos.write(buf);
}
private void WriteChar(ByteArrayOutputStream bos, char[] id) {
for (char c : id) {
bos.write(c);
}
}
}
package ai.qiwu.com.tts_service.common.pcm;
import lombok.extern.slf4j.Slf4j;
import java.io.File;
import java.io.RandomAccessFile;
/**
* @author 苗权威
* @dateTime 19-8-14 下午2:23
*/
@Slf4j
public class WavUtils {
private static final String TAG = WavUtils.class.getSimpleName();
/**
* 生成wav格式的Header
* wave是RIFF文件结构,每一部分为一个chunk,其中有RIFF WAVE chunk,
* FMT Chunk,Fact chunk(可选),Data chunk
*
* @param totalAudioLen 不包括header的音频数据总长度
* @param sampleRate 采样率,也就是录制时使用的频率
* @param channels audioRecord的频道数量
* @param sampleBits 位宽
*/
public static byte[] generateWavFileHeader(int totalAudioLen, int sampleRate, int channels, int sampleBits) {
WavFileHeader wavHeader = new WavFileHeader(totalAudioLen, sampleRate, (short) channels, (short) sampleBits);
return wavHeader.getHeader();
}
/**
* 将header写入到pcm文件中 不修改文件名
*
* @param file 写入的pcm文件
* @param header wav头数据
*/
public static void writeHeader(File file, byte[] header) {
if (!file.isFile()) {
return;
}
try (RandomAccessFile wavRaf = new RandomAccessFile(file, "rw")) {
wavRaf.seek(0);
wavRaf.write(header);
} catch (Exception e) {
log.error("{},pcm转换成wav出错,{}", TAG, e.toString());
}
}
}
...@@ -37,7 +37,7 @@ public class TTSController { ...@@ -37,7 +37,7 @@ public class TTSController {
} }
@GetMapping("/api/tts") @GetMapping("/api/tts")
public void tts(@RequestParam(required = false) String person, @RequestParam(required = false) String tone, public void tts_get(@RequestParam(required = false) String person, @RequestParam(required = false) String tone,
@RequestParam(required = false) String text, @RequestParam(required = false) String botname, @RequestParam(required = false) String text, @RequestParam(required = false) String botname,
@RequestParam(required = false) String _type, @RequestParam(required = false) String volume, @RequestParam(required = false) String _type, @RequestParam(required = false) String volume,
@RequestParam(required = false) String pitch, @RequestParam(required = false) String speed, @RequestParam(required = false) String pitch, @RequestParam(required = false) String speed,
...@@ -47,7 +47,7 @@ public class TTSController { ...@@ -47,7 +47,7 @@ public class TTSController {
} }
@PostMapping("/api/tts") @PostMapping("/api/tts")
public void tts(@RequestBody TTSRequest ttsRequest, HttpServletResponse response) { public void tts_post(@RequestBody TTSRequest ttsRequest, HttpServletResponse response) {
ttService.tts(ttsRequest, "POST", response); ttService.tts(ttsRequest, "POST", response);
} }
......
...@@ -21,4 +21,5 @@ public class TTSLSRequest { ...@@ -21,4 +21,5 @@ public class TTSLSRequest {
private List<TextInfo> text_info_ls; private List<TextInfo> text_info_ls;
private String botname; private String botname;
private String person; private String person;
private Integer gen3rd;
} }
package ai.qiwu.com.tts_service.pojo.third;
import lombok.Getter;
import lombok.Setter;
import lombok.ToString;
/**
* @author 苗权威
* @dateTime 19-8-14 上午10:04
*/
@Getter
@Setter
@ToString
public class LieHuCombineSoundResponse {
private Integer err_no;
private String err_msg;
private Integer idx;
private Integer percent;
private String phonemes;
private String sn;
}
package ai.qiwu.com.tts_service.pojo.third;
import lombok.Getter;
import lombok.Setter;
import lombok.ToString;
/**
* @author 苗权威
* @dateTime 19-8-13 下午8:50
*/
@Getter
@Setter
@ToString
public class LieHuSpeech {
private String tex;
private String sn;
private Integer pdt;
private Integer per;
private Integer aue;
private String token;
public LieHuSpeech() {
}
public LieHuSpeech(String tex, String sn, Integer pdt, Integer per, Integer aue, String token) {
this.tex = tex;
this.sn = sn;
this.pdt = pdt;
this.per = per;
this.aue = aue;
this.token = token;
}
}
package ai.qiwu.baidu.xiaodu.pojo.dpl; package ai.qiwu.com.tts_service.pojo.third;
import lombok.Getter; import lombok.Getter;
import lombok.Setter; import lombok.Setter;
...@@ -6,11 +6,15 @@ import lombok.ToString; ...@@ -6,11 +6,15 @@ import lombok.ToString;
/** /**
* @author 苗权威 * @author 苗权威
* @dateTime 19-8-6 下午9:26 * @dateTime 19-8-13 下午9:08
*/ */
@Getter @Getter
@Setter @Setter
@ToString @ToString
public class Event { public class LieHuTokenResponse {
private String type; private String token;
private String code;
private String error;
private String expire;
private String expire_duration;
} }
...@@ -12,10 +12,7 @@ import org.springframework.beans.factory.InitializingBean; ...@@ -12,10 +12,7 @@ import org.springframework.beans.factory.InitializingBean;
import org.springframework.beans.factory.annotation.Autowired; import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component; import org.springframework.stereotype.Component;
import java.util.ArrayList; import java.util.*;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
/** /**
* @author 苗权威 * @author 苗权威
...@@ -24,7 +21,7 @@ import java.util.Map; ...@@ -24,7 +21,7 @@ import java.util.Map;
@Component @Component
@Slf4j @Slf4j
public class Initialize implements InitializingBean { public class Initialize implements InitializingBean {
private String init_person = "B05"; private static String init_person = "B05";
private String init_tone = "正常"; private String init_tone = "正常";
private String init_url; private String init_url;
...@@ -34,6 +31,7 @@ public class Initialize implements InitializingBean { ...@@ -34,6 +31,7 @@ public class Initialize implements InitializingBean {
private static final Map<String, Map<String, String>> PERSON_MOODURL; //api private static final Map<String, Map<String, String>> PERSON_MOODURL; //api
private static final Map<String, Map<String, String>> OFFLINE_2_ONLINE; private static final Map<String, Map<String, String>> OFFLINE_2_ONLINE;
private static final List<String> THIRD_PARTY_TTS; private static final List<String> THIRD_PARTY_TTS;
private static final Map<String, String> THIRD_PARTY_WITH_ITS_PER = new HashMap<>();
private static final String SERVER_NAME; private static final String SERVER_NAME;
private static final String SERVER_URL; private static final String SERVER_URL;
...@@ -59,6 +57,19 @@ public class Initialize implements InitializingBean { ...@@ -59,6 +57,19 @@ public class Initialize implements InitializingBean {
OFFLINE_SERVER = Config.getProperty("offline_server"); OFFLINE_SERVER = Config.getProperty("offline_server");
THIRD_PARTY = Config.getProperty("third_party_tts_text"); THIRD_PARTY = Config.getProperty("third_party_tts_text");
CHANGE_SOUND = Config.getProperty("change_sound_path"); CHANGE_SOUND = Config.getProperty("change_sound_path");
THIRD_PARTY_WITH_ITS_PER.put("Baidu1", "1"); //度小宇(普通男)
THIRD_PARTY_WITH_ITS_PER.put("Baidu4", "0"); //度小美(普通女)
THIRD_PARTY_WITH_ITS_PER.put("Baidu2", "3"); //度逍遥(情感男)
THIRD_PARTY_WITH_ITS_PER.put("Baidu5", "4"); //度丫丫(情感女)
THIRD_PARTY_WITH_ITS_PER.put("Baidu3", "106"); //度博文(情感男)
THIRD_PARTY_WITH_ITS_PER.put("Baidu8", "110"); //度小童(童声)
THIRD_PARTY_WITH_ITS_PER.put("Baidu9", "111"); //度小萌(情感女)
THIRD_PARTY_WITH_ITS_PER.put("Baidu6", "103"); //度米朵(童声)
THIRD_PARTY_WITH_ITS_PER.put("Baidu7", "5"); //度小娇(情感女)
THIRD_PARTY_WITH_ITS_PER.put("Liehu1", "1"); //猎户采采
// THIRD_PARTY_WITH_ITS_PER.put("Liehu0", "0"); //猎户小雅
// THIRD_PARTY_WITH_ITS_PER.put("Liehu20", "20"); //猎户童音
} }
@Autowired @Autowired
...@@ -98,7 +109,7 @@ public class Initialize implements InitializingBean { ...@@ -98,7 +109,7 @@ public class Initialize implements InitializingBean {
PersonInfo personInfo_offline = PERSON_INFO_OFFLINE.computeIfAbsent(person_offline, k -> new PersonInfo(name, sex)); PersonInfo personInfo_offline = PERSON_INFO_OFFLINE.computeIfAbsent(person_offline, k -> new PersonInfo(name, sex));
personInfo_offline.getMood().add(mood); personInfo_offline.getMood().add(mood);
if (jump != null) { if (jump != null && !jump.equals(speakerInfo.getId())) {
Map<String, String> mood2jumpUrl = OFFLINE_2_ONLINE.computeIfAbsent(person_offline, k -> new HashMap<>()); Map<String, String> mood2jumpUrl = OFFLINE_2_ONLINE.computeIfAbsent(person_offline, k -> new HashMap<>());
mood2jumpUrl.put(mood, String.format("%s:9%03d/synthesize", ONLINE_SERVER, jump)); mood2jumpUrl.put(mood, String.format("%s:9%03d/synthesize", ONLINE_SERVER, jump));
} }
...@@ -115,7 +126,12 @@ public class Initialize implements InitializingBean { ...@@ -115,7 +126,12 @@ public class Initialize implements InitializingBean {
} }
//CallPython.getPythonInterpreter(); //CallPython.getPythonInterpreter();
if (!PERSON_INFO_ONLINE.containsKey(init_person)) { if (!PERSON_INFO_ONLINE.containsKey(init_person)) {
init_person = PERSON_INFO_ONLINE.keySet().iterator().next(); for (String person : PERSON_INFO_ONLINE.keySet()) {
if (!THIRD_PARTY_TTS.contains(person)) {
init_person = person;
break;
}
}
} }
List<String> moodList = PERSON_INFO_ONLINE.get(init_person).getMood(); List<String> moodList = PERSON_INFO_ONLINE.get(init_person).getMood();
if (!moodList.contains(init_tone)) { if (!moodList.contains(init_tone)) {
...@@ -200,4 +216,8 @@ public class Initialize implements InitializingBean { ...@@ -200,4 +216,8 @@ public class Initialize implements InitializingBean {
public static String getChangeSound() { public static String getChangeSound() {
return CHANGE_SOUND; return CHANGE_SOUND;
} }
public static String theThirdPartysPer(String person) {
return THIRD_PARTY_WITH_ITS_PER.get(person);
}
} }
package ai.qiwu.com.tts_service.service;
import ai.qiwu.com.tts_service.common.OkHttp3Utils;
import ai.qiwu.com.tts_service.common.TTSConstants;
import ai.qiwu.com.tts_service.pojo.third.LieHuTokenResponse;
import com.alibaba.fastjson.JSON;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;
import java.util.HashMap;
/**
* @author 苗权威
* @dateTime 19-8-13 下午8:55
*/
@Slf4j
@Component
public class LieHuSchedule {
public static final HashMap<String, String> LIE_HU_TOKEN_PARAMS;
private static String LIE_HU_TOKEN;
static {
LIE_HU_TOKEN_PARAMS = new HashMap<>();
LIE_HU_TOKEN_PARAMS.put("client_id", TTSConstants.LIE_HU.CLIENT_ID);
LIE_HU_TOKEN_PARAMS.put("client_secret", TTSConstants.LIE_HU.CLIENT_SECRET);
}
@Scheduled(fixedDelay = 6600000)
public void scheduleLieHuToken() {
new Thread(() -> {
try {
String liehuTokenRes = OkHttp3Utils.doGet(TTSConstants.LIE_HU.TOKEN_URL, LIE_HU_TOKEN_PARAMS);
if (StringUtils.isBlank(liehuTokenRes)) {
log.error("对猎户Token发起的请求出错");
return;
}
LieHuTokenResponse response = JSON.parseObject(liehuTokenRes, LieHuTokenResponse.class);
if ("success".equals(response.getCode())) {
LIE_HU_TOKEN = response.getToken();
log.info("成功获取到猎户Token:{}", LIE_HU_TOKEN);
}else {
log.error("请求猎户Token失败:{}", response.getError());
}
} catch (Exception e) {
log.error("获取猎户Token失败:{}", e.toString());
}
}).start();
}
public static String getLieHuToken() {
return LIE_HU_TOKEN;
}
}
package ai.qiwu.com.tts_service.service.baidu;
import ai.qiwu.com.tts_service.common.ErrorMsgEnum;
import ai.qiwu.com.tts_service.common.OkHttp3Utils;
import ai.qiwu.com.tts_service.common.pcm.Pcm2Wav;
import ai.qiwu.com.tts_service.common.TTSConstants;
import ai.qiwu.com.tts_service.common.TTSConstants.BAI_DU;
import ai.qiwu.com.tts_service.service.LieHuSchedule;
import com.baidu.aip.speech.AipSpeech;
import com.baidu.aip.speech.TtsResponse;
import lombok.extern.slf4j.Slf4j;
import java.io.*;
import java.util.HashMap;
import java.util.UUID;
/**
* @author 苗权威
* @dateTime 19-8-12 下午8:10
*/
@Slf4j
public class ThirdPartyService {
private static final AipSpeech CLIENT = new AipSpeech(BAI_DU.APP_ID, BAI_DU.API_KEY, BAI_DU.SECRET_KEY);
public static boolean thirdPartyCall(String text, String per, String filepath, String person) {
person = person.substring(0, 5);
if ("Baidu".equals(person)) {
return synthesis(text, Integer.parseInt(per), filepath);
}else if ("Liehu".equals(person)) {
return lieHuTTS(text, per, filepath);
} else {
log.info("不支持该第三方平台:{}", person);
}
return false;
}
public static boolean synthesis(String text, int per, String filepath) {
HashMap<String, Object> options = new HashMap<>();
// options.put("spd", correctSoundParams(speed, false));
// options.put("pit", correctSoundParams(pitch, true));
// options.put("vol", correctSoundParams(volume, false));
options.put("aue", 6);
options.put("per", per);
TtsResponse res = CLIENT.synthesis(text, "zh", 1, options);
if (res.getResult() == null) {
try (FileOutputStream output = new FileOutputStream(new File(filepath))){
output.write(res.getData());
return true;
} catch (IOException e) {
log.error("写入mp3数据信息失败:{}", e.toString());
}
} else {
String errorCode = (String) res.getResult().get("error_code");
if ("SDK108".equals(errorCode)) {
log.error("错误码:SDK108,错误信息:{}", "连接超时或读取数据超时");
}else {
log.error("错误码:{},错误信息:{}", errorCode, ErrorMsgEnum.findMsgByCode(Integer.parseInt(errorCode)));
}
}
return false;
}
public static boolean lieHuTTS(String text, String per, String filepath) {
// LieHuSpeech lieHuSpeech = new LieHuSpeech(text, UUID.randomUUID().toString(), TTSConstants.LIE_HU.PDT,
// per, 4, LieHuSchedule.getLieHuToken());
// String requestJson = JSON.toJSONString(lieHuSpeech);
HashMap<String, String> headers = new HashMap<>();
//headers.put("Content-Type", "application/x-www-form-urlencoded");
headers.put("Authorization", TTSConstants.LIE_HU.AUTHORIZATION+LieHuSchedule.getLieHuToken());
HashMap<String, String> params = new HashMap<>();
params.put("tex", text);
params.put("sn", UUID.randomUUID().toString());
params.put("pdt", TTSConstants.LIE_HU.PDT);
params.put("per", per);
params.put("aue", "4");
params.put("token", LieHuSchedule.getLieHuToken());
byte[] data;
try {
data = OkHttp3Utils.lieHudoGet(TTSConstants.LIE_HU.URL, params, headers);
if (data == null || data.length == 0) {
log.error("对猎户发起的语音合成请求出错,没有获取到任何返回结果");
return false;
}
// LieHuCombineSoundResponse response = JSON.parseObject(responseStr, LieHuCombineSoundResponse.class);
// if (response.getErr_no() != 0) {
// log.error("对猎户发起的语音合成请求出错:返回信息{},错误信息{}", response,response.getErr_msg());
// return false;
// }
Pcm2Wav.pcm2Wav(data, filepath);
} catch (Exception e) {
log.error("对猎户发起的语音合成请求出错,错误信息{}",e.toString());
return false;
}
return true;
}
private static double correctSoundParams(String param, boolean doesPitch) {
int point = param.indexOf(".");
String after = "";
if (doesPitch) {
int pitch = (int) Double.parseDouble(param)+100;
if (pitch >= 195) return 15;
if (point != -1) {
after = param.substring(point);
}
return Double.parseDouble(pitch/13+after);
}else {
int vors = (int) Double.parseDouble(param);
if (vors >= 90) return 15;
if (point != -1) {
after = param.substring(point);
}
return Double.parseDouble(vors/6+after);
}
}
public static void main(String[] args) {
System.out.println(correctSoundParams("73.436", false));
}
}
server_name=hz1 server_name=hz1
#server_name=aws-nx2
server_url=http://aliyun-hz1.chewrobot.com:9663 server_url=http://aliyun-hz1.chewrobot.com:9663
audio_dir=/root/GameEditor/mqw/project/tts/audio audio_dir=/root/GameEditor/mqw/project/tts/audio
#audio_dir=/usr/GameEditor/mqw/tts/audio #audio_dir=/usr/GameEditor/mqw/tts/audio
......
...@@ -20,10 +20,10 @@ public class TtsServiceApplicationTests { ...@@ -20,10 +20,10 @@ public class TtsServiceApplicationTests {
@Test @Test
public void createFileTest() { public void createFileTest() {
String fileName = DigestUtils.md5DigestAsHex("text".getBytes(StandardCharsets.UTF_8)); // String fileName = DigestUtils.md5DigestAsHex("text".getBytes(StandardCharsets.UTF_8));
fileName = StringUtils.join(new String[]{fileName, "mp3"}, "."); // fileName = StringUtils.join(new String[]{fileName, "mp3"}, ".");
boolean result = TTSUtils.createFile("/usr/springbootdemo/优美/A307/女声高兴", fileName); // boolean result = TTSUtils.createFile("/usr/springbootdemo/优美/A307/女声高兴", fileName);
System.out.println(result); // System.out.println(result);
} }
} }
package ai.qiwu.mi.xiaoai.commons; package ai.qiwu.mi.xiaoai.commons;
import lombok.extern.slf4j.Slf4j;
import okhttp3.*; import okhttp3.*;
import java.io.File; import java.io.File;
import java.io.IOException; import java.io.IOException;
import java.net.SocketTimeoutException;
import java.util.HashMap; import java.util.HashMap;
import java.util.Iterator; import java.util.Iterator;
import java.util.Map; import java.util.Map;
import java.util.concurrent.TimeUnit;
/** /**
* @author 苗权威 * @author 苗权威
* @dateTime 19-7-18 上午10:54 * @dateTime 19-7-18 上午10:54
*/ */
@Slf4j
public class OkHttp3Utils { public class OkHttp3Utils {
private static OkHttpClient client = new OkHttpClient(); private static OkHttpClient client = new OkHttpClient.Builder()
.connectTimeout(10, TimeUnit.SECONDS)
.readTimeout(12, TimeUnit.SECONDS)
.build();
public static String doGet(String url) throws IOException { public static String doGet(String url) throws IOException {
return doGet(url, new HashMap<>()); return doGet(url, new HashMap<>());
...@@ -65,7 +72,12 @@ public class OkHttp3Utils { ...@@ -65,7 +72,12 @@ public class OkHttp3Utils {
builder.headers(headBuilder.build()).post(RequestBody.create(MediaType.parse("application/json; charset=utf-8"), requestJsonStr)); builder.headers(headBuilder.build()).post(RequestBody.create(MediaType.parse("application/json; charset=utf-8"), requestJsonStr));
try (Response response = client.newCall(builder.build()).execute()){ try (Response response = client.newCall(builder.build()).execute()){
return response.body().string(); return response.body().string();
}catch (SocketTimeoutException e) {
log.error("捕获到SocketTimeoutException:{}", e.toString());
client.dispatcher().cancelAll();
client.connectionPool().evictAll();
} }
return null;
} }
public static String doPost(String url, Map<String, String> headers, Map<String, String> params, File file) throws IOException { public static String doPost(String url, Map<String, String> headers, Map<String, String> params, File file) throws IOException {
...@@ -89,7 +101,12 @@ public class OkHttp3Utils { ...@@ -89,7 +101,12 @@ public class OkHttp3Utils {
try (Response response = client.newCall(builder.build()).execute()){ try (Response response = client.newCall(builder.build()).execute()){
return response.body().string(); return response.body().string();
}catch (SocketTimeoutException e) {
log.error("捕获到SocketTimeoutException:{}", e.toString());
client.dispatcher().cancelAll();
client.connectionPool().evictAll();
} }
return null;
} }
public static String doPost(String url, Map<String, String> headers, Map<String, String> params, public static String doPost(String url, Map<String, String> headers, Map<String, String> params,
......
...@@ -3,6 +3,7 @@ package ai.qiwu.mi.xiaoai.commons; ...@@ -3,6 +3,7 @@ package ai.qiwu.mi.xiaoai.commons;
import ai.qiwu.mi.xiaoai.model.QiWuRequest; import ai.qiwu.mi.xiaoai.model.QiWuRequest;
import ai.qiwu.mi.xiaoai.model.QiWuResponse; import ai.qiwu.mi.xiaoai.model.QiWuResponse;
import com.alibaba.fastjson.JSON; import com.alibaba.fastjson.JSON;
import lombok.extern.slf4j.Slf4j;
import java.io.IOException; import java.io.IOException;
import java.util.HashMap; import java.util.HashMap;
...@@ -11,6 +12,7 @@ import java.util.HashMap; ...@@ -11,6 +12,7 @@ import java.util.HashMap;
* @author 苗权威 * @author 苗权威
* @dateTime 19-6-29 下午3:49 * @dateTime 19-6-29 下午3:49
*/ */
@Slf4j
public class RequestTerminal { public class RequestTerminal {
public static QiWuResponse requestTerminate(String userId, String userWord) throws IOException { public static QiWuResponse requestTerminate(String userId, String userWord) throws IOException {
...@@ -19,9 +21,13 @@ public class RequestTerminal { ...@@ -19,9 +21,13 @@ public class RequestTerminal {
requestPojo.setAccess(XiaoAiConstants.DEVICE_NAME); requestPojo.setAccess(XiaoAiConstants.DEVICE_NAME);
requestPojo.setText(userWord); requestPojo.setText(userWord);
String requestJsonStr = JSON.toJSONString(requestPojo); String requestJsonStr = JSON.toJSONString(requestPojo);
//log.info("向终端发出请求的参数信息:{}", requestJsonStr);
HashMap<String, String> headers = new HashMap<>(); HashMap<String, String> headers = new HashMap<>();
headers.put("Content-Type", "application/json;charset=utf-8"); headers.put("Content-Type", "application/json;charset=utf-8");
String resStr = OkHttp3Utils.doPostJsonStr(XiaoAiConstants.QI_WU_TERMINATE, headers, requestJsonStr); String resStr = OkHttp3Utils.doPostJsonStr(XiaoAiConstants.QI_WU_TERMINATE, headers, requestJsonStr);
if (resStr == null) {
return null;
}
return JSON.parseObject(resStr, QiWuResponse.class); return JSON.parseObject(resStr, QiWuResponse.class);
} }
} }
package ai.qiwu.mi.xiaoai.commons;
/**
* @author 苗权威
* @dateTime 19-8-10 下午3:11
*/
public class RequestTerminateFail extends RuntimeException {
private int errorCode;
private String errorMsg;
public RequestTerminateFail(String message, int errorCode) {
super(message);
this.errorCode = errorCode;
}
public RequestTerminateFail(String message) {
super(message);
this.errorMsg = errorMsg;
}
public int getErrorCode() {
return errorCode;
}
public String getErrorMsg() {
return errorMsg;
}
}
package ai.qiwu.mi.xiaoai.commons;
/**
* @author 苗权威
* @dateTime 19-8-10 下午3:15
*/
public class RequestWordNullException extends RuntimeException {
private int errorCode;
private String errorMsg;
public RequestWordNullException(String message, int errorCode) {
super(message);
this.errorCode = errorCode;
}
public RequestWordNullException(String message) {
super(message);
this.errorMsg = errorMsg;
}
public int getErrorCode() {
return errorCode;
}
public String getErrorMsg() {
return errorMsg;
}
}
...@@ -4,6 +4,7 @@ import org.springframework.web.context.request.RequestContextHolder; ...@@ -4,6 +4,7 @@ import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes; import org.springframework.web.context.request.ServletRequestAttributes;
import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletRequest;
import java.util.Arrays;
import java.util.Objects; import java.util.Objects;
/** /**
...@@ -12,6 +13,8 @@ import java.util.Objects; ...@@ -12,6 +13,8 @@ import java.util.Objects;
*/ */
public class Utils { public class Utils {
private static final String STRIP = " /'\"\\t";
public static HttpServletRequest getHttpServletRequest() { public static HttpServletRequest getHttpServletRequest() {
return ((ServletRequestAttributes) Objects.requireNonNull(RequestContextHolder return ((ServletRequestAttributes) Objects.requireNonNull(RequestContextHolder
.getRequestAttributes())).getRequest(); .getRequestAttributes())).getRequest();
...@@ -31,4 +34,14 @@ public class Utils { ...@@ -31,4 +34,14 @@ public class Utils {
} }
return ip; return ip;
} }
public static String modifyDeviceId(String deviceId) {
char[] arr = deviceId.toCharArray();
StringBuilder builder = new StringBuilder();
for (char c : arr) {
if (STRIP.contains(c+"")) continue;
builder.append(c);
}
return builder.toString();
}
} }
...@@ -5,22 +5,25 @@ package ai.qiwu.mi.xiaoai.commons; ...@@ -5,22 +5,25 @@ package ai.qiwu.mi.xiaoai.commons;
* @dateTime 19-7-5 下午8:56 * @dateTime 19-7-5 下午8:56
*/ */
public interface XiaoAiConstants { public interface XiaoAiConstants {
String QI_WU_TERMINATE = "http://aws-nx2.chewrobot.com:8070/api/chat2"; String QI_WU_TERMINATE = "http://didi-gz2.jiaoyou365.com:8070/api/chat2";
//String QI_WU_TERMINATE = "http://aws-nx2.chewrobot.com:8070/api/chat2";
String DEVICE_NAME = "XIAOAI"; String DEVICE_NAME = "XIAOAI";
String CONTENT_TYPE = "application/json;charset=utf-8"; String CONTENT_TYPE = "application/json;charset=utf-8";
String PLAYBACK_NEARLY_FINISHED = "mediaplayer.playbacknearlyfinished"; String PLAYBACK_NEARLY_FINISHED = "mediaplayer.playbacknearlyfinished";
interface ERROR_MSG { interface ERROR_MSG {
String SORRY_REPEAT = "不好意思,请再说一边吧"; String SORRY_REPEAT = "不好意思,请再说一遍吧";
String TIME_OUT = "请稍等";
String TERMINATE_IO_EXCEPTION = "请求终端接口时发生IO错误"; String TERMINATE_IO_EXCEPTION = "请求终端接口时发生IO错误";
String HTTP_CONNECTION_CLOSE_EXCEPTION = "关闭与终端接口链接时出错"; String HTTP_CONNECTION_CLOSE_EXCEPTION = "关闭与终端接口链接时出错";
} }
interface TTS { interface TTS {
String WELCOME_WORD = "欢迎来到互动天地,请说推荐作品"; String WELCOME_WORD = "欢迎来到交游天下,海量的作品在这等您";
String END_BYE = "我们的作品库在不断扩充,下次会有更大的惊喜哦"; String END_BYE = "我们的作品库在不断扩充,欢迎再来玩";
String END_WORD = "退出"; String END_WORD = "退出";
String USER_IDLE = "小悟在等你的回复哦"; String USER_IDLE = "小悟在等你的回复哦";
String ANOTHER_USER_IDLE = "再不回复我,那我可退出喽";
} }
} }
...@@ -25,9 +25,9 @@ public class XiaoAiController { ...@@ -25,9 +25,9 @@ public class XiaoAiController {
@RequestMapping("/xiaoai") @RequestMapping("/xiaoai")
public @ResponseBody XiaoAiResponse xiaoai(@RequestBody XiaoAiRequest request) { public @ResponseBody XiaoAiResponse xiaoai(@RequestBody XiaoAiRequest request) {
//log.info("请求:"+request); log.info("请求:"+request);
XiaoAiResponse response = xiaoAiService.getResponse(request); XiaoAiResponse response = xiaoAiService.getResponse(request);
log.info("响应:"+response); //log.info("响应:"+response);
return response; return response;
// return xiaoAiService.getResponse(request); // return xiaoAiService.getResponse(request);
} }
......
package ai.qiwu.mi.xiaoai.model; package ai.qiwu.mi.xiaoai.model;
import com.fasterxml.jackson.annotation.JsonIgnoreProperties;
import lombok.Getter; import lombok.Getter;
import lombok.Setter; import lombok.Setter;
import lombok.ToString; import lombok.ToString;
...@@ -7,6 +8,7 @@ import lombok.ToString; ...@@ -7,6 +8,7 @@ import lombok.ToString;
@Getter @Getter
@Setter @Setter
@ToString @ToString
@JsonIgnoreProperties(ignoreUnknown = true)
public class QiWuResponse { public class QiWuResponse {
private String audio; private String audio;
private String text; private String text;
......
package ai.qiwu.mi.xiaoai.service; package ai.qiwu.mi.xiaoai.service;
import ai.qiwu.mi.xiaoai.commons.RequestTerminal; import ai.qiwu.mi.xiaoai.commons.RequestTerminal;
import ai.qiwu.mi.xiaoai.commons.RequestTerminateFail;
import ai.qiwu.mi.xiaoai.commons.RequestWordNullException;
import ai.qiwu.mi.xiaoai.commons.Utils; import ai.qiwu.mi.xiaoai.commons.Utils;
import ai.qiwu.mi.xiaoai.commons.XiaoAiConstants.TTS; import ai.qiwu.mi.xiaoai.commons.XiaoAiConstants.TTS;
import ai.qiwu.mi.xiaoai.commons.XiaoAiConstants.ERROR_MSG; import ai.qiwu.mi.xiaoai.commons.XiaoAiConstants.ERROR_MSG;
...@@ -13,10 +15,13 @@ import ai.qiwu.mi.xiaoai.model.response.innerResponse.directive.AudioItem.AudioS ...@@ -13,10 +15,13 @@ import ai.qiwu.mi.xiaoai.model.response.innerResponse.directive.AudioItem.AudioS
import ai.qiwu.mi.xiaoai.model.response.innerResponse.directive.Directive; import ai.qiwu.mi.xiaoai.model.response.innerResponse.directive.Directive;
import ai.qiwu.mi.xiaoai.model.response.innerResponse.toSpeak.ToSpeak; import ai.qiwu.mi.xiaoai.model.response.innerResponse.toSpeak.ToSpeak;
import lombok.extern.slf4j.Slf4j; import lombok.extern.slf4j.Slf4j;
import org.apache.commons.codec.binary.StringUtils;
import org.springframework.stereotype.Service; import org.springframework.stereotype.Service;
import java.util.ArrayList; import java.util.*;
import java.util.List; import java.util.concurrent.*;
import static ai.qiwu.mi.xiaoai.commons.XiaoAiConstants.ERROR_MSG.SORRY_REPEAT;
/** /**
* @author 苗权威 * @author 苗权威
...@@ -26,14 +31,19 @@ import java.util.List; ...@@ -26,14 +31,19 @@ import java.util.List;
@Slf4j @Slf4j
public class XiaoAiService { public class XiaoAiService {
private static final int CORE = Runtime.getRuntime().availableProcessors();
private static final ThreadPoolExecutor POOL = new ThreadPoolExecutor(CORE+1, 1500,
2500, TimeUnit.MILLISECONDS, new ArrayBlockingQueue<>(CORE), new ThreadPoolExecutor.CallerRunsPolicy());
private static final ConcurrentHashMap<String, XiaoAiResponse> LAST_OUTTIME_RESULT = new ConcurrentHashMap<>();
public XiaoAiResponse getResponse(XiaoAiRequest request) { public XiaoAiResponse getResponse(XiaoAiRequest request) {
String userId = getUserId(request); String userId = getUserId(request);
int type = request.getRequest().getType(); int type = request.getRequest().getType();
switch (type) { switch (type) {
case 0 : return dealWithLaunchRequest(request); case 0 : return dealWithLaunchRequest();
case 1 : return dealWithIntentRequest(request, userId); case 1 : return dealWithIntentRequest(request, userId);
case 2 : return dealWithEndRequest(userId); case 2 : return dealWithEndRequest(userId);
default: return buildTextResponse(ERROR_MSG.SORRY_REPEAT); default: return buildTextResponse(SORRY_REPEAT);
} }
} }
...@@ -120,46 +130,99 @@ public class XiaoAiService { ...@@ -120,46 +130,99 @@ public class XiaoAiService {
return response; return response;
} }
private XiaoAiResponse dealWithLaunchRequest(XiaoAiRequest request) { private XiaoAiResponse dealWithLaunchRequest() {
return buildTextResponse(TTS.WELCOME_WORD); return buildTextResponse(TTS.WELCOME_WORD);
} }
private XiaoAiResponse dealWithIntentRequest(XiaoAiRequest request, String userId) { private XiaoAiResponse dealWithIntentRequest(XiaoAiRequest request, String userId) {
Boolean idle = request.getRequest().getNo_response(); Boolean idle = request.getRequest().getNo_response();
if (idle != null && idle) { if (idle != null && idle) {
return buildTextResponse(TTS.USER_IDLE); XiaoAiResponse response = getLastResult(userId);
} if (response != null) return response;
String userWord = request.getQuery(); //log.info("用户没说话");
if (userWord == null) { //return buildTextResponse(".");
return buildTextResponse(ERROR_MSG.SORRY_REPEAT); return buildTextResponse((new Random(47).nextInt(666) & 1) == 1 ? TTS.USER_IDLE : TTS.ANOTHER_USER_IDLE);
} }
QiWuResponse response = null; XiaoAiResponse response = getLastResult(userId);
if (response != null) return response;
try { try {
response = RequestTerminal.requestTerminate(userId, userWord); Future future = POOL.submit(new Task(userId, request.getQuery()));
} catch (Exception e) { future.get(2100, TimeUnit.MILLISECONDS);
log.error("向终端发出的请求信息失败:{}", e.toString()); } catch (InterruptedException | ExecutionException e) {
return buildTextResponse(ERROR_MSG.SORRY_REPEAT); log.error("获取任务执行结果出错:{}", e.toString());
return buildTextResponse(SORRY_REPEAT);
} catch (TimeoutException e) {
log.info("超时,让用户再说一遍:{}",e.toString());
return buildTextResponse(ERROR_MSG.TIME_OUT);
} catch (Exception all) {
log.error("任务执行发生了错误:{}", all.toString());
return buildTextResponse(SORRY_REPEAT);
} }
return buildAudioResponse(response.getAudio()); return LAST_OUTTIME_RESULT.remove(userId);
} }
private XiaoAiResponse dealWithEndRequest(String userId) { private XiaoAiResponse dealWithEndRequest(String userId) {
POOL.submit(() -> {
try { try {
RequestTerminal.requestTerminate(userId, TTS.END_WORD); RequestTerminal.requestTerminate(userId, TTS.END_WORD);
} catch (Exception e) { } catch (Exception e) {
log.error("向终端发出的退出请求失败:{}", e.toString()); log.error("向终端发出的退出请求失败:{}", e.toString());
} }
});
LAST_OUTTIME_RESULT.remove(userId);
return buildTextResponse(TTS.END_BYE); return buildTextResponse(TTS.END_BYE);
} }
private String getUserId(XiaoAiRequest request) { private String getUserId(XiaoAiRequest request) {
String userId = request.getSession().getUser().getUser_id(); String userId = request.getContext().getDevice_id();
if (userId == null) { if (userId == null) {
userId = request.getContext().getDevice_id(); userId = request.getSession().getUser().getUser_id();
} }
if (userId == null) { if (userId == null) {
userId = Utils.useIPAsItsID(); userId = Utils.useIPAsItsID();
} }
return userId; return Utils.modifyDeviceId(userId);
}
public XiaoAiResponse getLastResult(String userId) {
XiaoAiResponse response;
if ((response = LAST_OUTTIME_RESULT.get(userId)) != null) {
LAST_OUTTIME_RESULT.remove(userId);
}
return response;
}
class Task implements Runnable {
private String userId;
private String userWord;
Task(String userId, String userWord) {
this.userId = userId;
this.userWord = userWord;
}
@Override
public void run() {
XiaoAiResponse xiaoAiResponse;
if (userWord == null) {
log.info("请求中没有带有用户的话");
throw new RequestWordNullException("user word can not be null");
}
log.info("用户说的话:{}", userWord);
QiWuResponse response;
try {
response = RequestTerminal.requestTerminate(userId, userWord);
} catch (Exception e) {
log.error("向终端发出的请求信息失败:{}", e.toString());
throw new RequestTerminateFail(e.toString());
}
if (response == null) {
xiaoAiResponse = buildTextResponse(SORRY_REPEAT);
} else {
log.info("小悟返回:{}", response);
xiaoAiResponse = buildAudioResponse(response.getAudio());
}
LAST_OUTTIME_RESULT.put(userId, xiaoAiResponse);
}
} }
} }
...@@ -6,7 +6,7 @@ package ai.qiwu.baidu.xiaodu.common; ...@@ -6,7 +6,7 @@ package ai.qiwu.baidu.xiaodu.common;
*/ */
public interface Constants { public interface Constants {
String QI_WU_INTERFACE = "http://aliyun-hz1.chewrobot.com:8070/api/chat"; String QI_WU_INTERFACE = "http://didi-gz2.jiaoyou365.com:8070/api/chat2";
String SERVICE_NAME = "BAIDU"; String SERVICE_NAME = "BAIDU";
String PRIVATE_KEY = "MIICdwIBADANBgkqhkiG9w0BAQEFAASCAmEwggJdAgEAAoGBANMWIYduiQZt0B7s" + String PRIVATE_KEY = "MIICdwIBADANBgkqhkiG9w0BAQEFAASCAmEwggJdAgEAAoGBANMWIYduiQZt0B7s" +
"IZ6PW15gpcO7Yn+9ZbaMSHwzJqNeDAZzh6HXF7r0ZpQcw3XEWKPAPWyuJ5eqZf46" + "IZ6PW15gpcO7Yn+9ZbaMSHwzJqNeDAZzh6HXF7r0ZpQcw3XEWKPAPWyuJ5eqZf46" +
......
package ai.qiwu.baidu.xiaodu.controller; package ai.qiwu.baidu.xiaodu.controller;
import ai.qiwu.baidu.xiaodu.common.Utils; import ai.qiwu.baidu.xiaodu.common.Utils;
import ai.qiwu.baidu.xiaodu.service.DplBotService;
import ai.qiwu.baidu.xiaodu.service.ResponseEncapsulation; import ai.qiwu.baidu.xiaodu.service.ResponseEncapsulation;
import lombok.extern.slf4j.Slf4j; import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestMapping;
......
package ai.qiwu.baidu.xiaodu.pojo.dpl;
import com.fasterxml.jackson.annotation.JsonIgnoreProperties;
import com.fasterxml.jackson.annotation.JsonProperty;
import com.fasterxml.jackson.databind.annotation.JsonSerialize;
import lombok.Getter;
import lombok.Setter;
import lombok.ToString;
import java.util.List;
/**
* @author 苗权威
* @dateTime 19-8-6 下午9:14
*/
@Getter
@Setter
@ToString
@JsonIgnoreProperties(ignoreUnknown = true)
@JsonSerialize(include = JsonSerialize.Inclusion.NON_NULL)
public class Item {
private String type;
private String width;
private String height;
private String src;
@JsonProperty("scale-type")
private String scaleType;
@JsonProperty("border-bottom-right-radius")
private String borderBrr;
private Double opacity;
private String text;
@JsonProperty("line-height")
private String lineHeight;
@JsonProperty("letter-spacing")
private String LetterSpace;
private String color;
@JsonProperty("padding-left")
private String paddingLeft;
@JsonProperty("margin-left")
private String marginLeft;
private Boolean looping;
private Boolean autoPlay;
private String audioType;
private List<Event> onEnd;
private List<Item> items;
}
package ai.qiwu.baidu.xiaodu.pojo.dpl;
import com.baidu.dueros.data.response.directive.dpl.Document;
import lombok.Getter;
import lombok.Setter;
import lombok.ToString;
/**
* @author 苗权威
* @dateTime 19-8-7 上午9:50
*/
@Getter
@Setter
@ToString
public class MyDocument extends Document {
private final String type = "DPL";
private String version;
private long duration;
private Object resources;
private Object styles;
private Object dataSource;
private Object layouts;
private MyMainTemplate mainTemplate;
}
package ai.qiwu.baidu.xiaodu.service;
import ai.qiwu.baidu.xiaodu.common.Constants;
import ai.qiwu.baidu.xiaodu.common.Utils;
import ai.qiwu.baidu.xiaodu.pojo.AudioUrlAndText;
import ai.qiwu.baidu.xiaodu.pojo.dpl.Item;
import ai.qiwu.baidu.xiaodu.pojo.dpl.MyDocument;
import com.alibaba.fastjson.JSON;
import com.baidu.dueros.bot.BaseBot;
import com.baidu.dueros.data.request.IntentRequest;
import com.baidu.dueros.data.request.Query;
import com.baidu.dueros.data.response.OutputSpeech;
import com.baidu.dueros.data.response.directive.dpl.RenderDocument;
import com.baidu.dueros.data.response.directive.dpl.event.UserEvent;
import com.baidu.dueros.model.Request;
import com.baidu.dueros.model.Response;
import lombok.extern.slf4j.Slf4j;
import javax.servlet.http.HttpServletRequest;
import java.io.*;
import java.nio.charset.Charset;
import java.nio.charset.StandardCharsets;
/**
* @author 苗权威
* @dateTime 19-8-6 下午8:06
*/
@Slf4j
public class DplBotService extends BaseBot {
private static String jsonStr;
public DplBotService(HttpServletRequest request) throws IOException {
super(request);
}
@Override
protected Response onInent(IntentRequest intentRequest) {
String userId = getCustomerId();
Query query = intentRequest.getQuery();
String userWord = null;
if (query != null) userWord = query.getOriginal();
if (userWord == null){
log.info("小度没有传来任何话语");
return buildErrorResponse(Constants.ErrorMsg.SORRY_UNCATCH);
}
MyDocument document = JSON.parseObject(testJsonStr(), MyDocument.class);
AudioUrlAndText data = null;
try {
data = RequestTerminal.requestTerminate(userWord, userId);
} catch (IOException e) {
log.error("请求终端接口出错:", e.toString());
}
if (data == null) {
return buildErrorResponse(Constants.ErrorMsg.SORRY_UNCATCH);
}
Item container = document.getMainTemplate().getItems().get(0);
for (Item item : container.getItems()) {
String type = item.getType();
if (type.equals("Text")) {
item.setText(data.getText());
}else if (type.equals("Audio")) {
item.setSrc(data.getAudio());
}
}
RenderDocument render = new RenderDocument();
render.setDocument(document);
this.addDirective(render);
return new Response();
}
private String testJsonStr() {
if (jsonStr == null) {
try {
jsonStr = getJsonFromName("demo01.json");
} catch (IOException e) {
log.error("没有获取到json字符串:{}", e.toString());
}
}
return jsonStr;
}
@Override
protected Response onUserEvent(UserEvent userEvent) {
log.info("onUserEvent333333333");
setExpectSpeech(true);
return null;
}
private Response buildErrorResponse(String errorMsg) {
OutputSpeech outputSpeech = new OutputSpeech(OutputSpeech.SpeechType.PlainText, errorMsg);
return new Response(outputSpeech);
}
private String getCustomerId() {
String userId;
try {
userId = getUserId();
} catch (NullPointerException e) {
userId = Utils.useIPAsItsID();
}
return userId;
}
private String getJsonFromName(String filename) throws IOException {
InputStreamReader reader = new InputStreamReader(DplBotService.class.getClassLoader().getResourceAsStream(filename), StandardCharsets.UTF_8);
char[] buffer = new char[512];
int ln;
StringBuilder builder = new StringBuilder();
while ((ln = reader.read(buffer)) != -1) {
builder.append(buffer, 0, ln);
}
return builder.toString();
}
private String getJsonFromPath(String path) throws IOException {
try (BufferedReader reader = new BufferedReader(new FileReader(new File(path)))){
StringBuilder build = new StringBuilder();
String str;
while ((str = reader.readLine()) != null) build.append(str);
return build.toString();
}
}
public static void main(String[] args) {
StringBuilder absolutePath = new StringBuilder(System.getProperty("user.dir")).append(File.separator);
absolutePath.append("xiaodu/src/main/resources/static/json/demo01.json");
String path = absolutePath.toString();
// try {
// String jsonStr = getJsonFromPath(path);
// MyDocument document = JSON.parseObject(jsonStr, MyDocument.class);
// log.info("Document:{}", document);
// } catch (IOException e) {
// e.printStackTrace();
// }
}
}
...@@ -221,9 +221,9 @@ public class ResponseEncapsulation extends AudioPlayer { ...@@ -221,9 +221,9 @@ public class ResponseEncapsulation extends AudioPlayer {
} }
logger.info("请求终端接口:"+data); logger.info("请求终端接口:"+data);
String audioUrl = data.getAudio(); String audioUrl = data.getAudio();
String screenToken = getRequest().getContext().getScreen().getToken(); Screen screen = getRequest().getContext().getScreen();
logger.info("screen token:{}", screenToken); //logger.info("screen token:{}", screenToken);
if (screenToken == null) { if (screen == null) {
addDirective(buildNoScreenPlayDirec(audioUrl, AudioPlayerDirective.PlayBehaviorType.REPLACE_ALL)); addDirective(buildNoScreenPlayDirec(audioUrl, AudioPlayerDirective.PlayBehaviorType.REPLACE_ALL));
}else { }else {
addDirective(buildPlayDirective(audioUrl, data.getText(), AudioPlayerDirective.PlayBehaviorType.REPLACE_ALL)); addDirective(buildPlayDirective(audioUrl, data.getText(), AudioPlayerDirective.PlayBehaviorType.REPLACE_ALL));
......
...@@ -23,6 +23,15 @@ ...@@ -23,6 +23,15 @@
<groupId>org.springframework.boot</groupId> <groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId> <artifactId>spring-boot-starter-web</artifactId>
</dependency> </dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-jpa</artifactId>
</dependency>
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<scope>runtime</scope>
</dependency>
<dependency> <dependency>
<groupId>org.springframework.boot</groupId> <groupId>org.springframework.boot</groupId>
......
...@@ -2,8 +2,14 @@ package ai.qiwu.com.xiaoduhome; ...@@ -2,8 +2,14 @@ package ai.qiwu.com.xiaoduhome;
import org.springframework.boot.SpringApplication; import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication; import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.boot.autoconfigure.domain.EntityScan;
import org.springframework.data.jpa.repository.config.EnableJpaRepositories;
import org.springframework.scheduling.annotation.EnableScheduling;
@SpringBootApplication @SpringBootApplication
@EntityScan(basePackages = {"ai.qiwu.com.xiaoduhome.entity"})
@EnableJpaRepositories(basePackages = {"ai.qiwu.com.xiaoduhome.repository"})
@EnableScheduling
public class XiaoduhomeApplication { public class XiaoduhomeApplication {
public static void main(String[] args) { public static void main(String[] args) {
......
...@@ -6,7 +6,7 @@ package ai.qiwu.com.xiaoduhome.common; ...@@ -6,7 +6,7 @@ package ai.qiwu.com.xiaoduhome.common;
*/ */
public interface Constants { public interface Constants {
String QI_WU_INTERFACE = "http://aliyun-hz1.chewrobot.com:8070/api/chat"; String QI_WU_INTERFACE = "http://aws-nx2.chewrobot.com:8070/api/chat2";
String SERVICE_NAME = "BAIDU"; String SERVICE_NAME = "BAIDU";
String PRIVATE_KEY = "MIICdwIBADANBgkqhkiG9w0BAQEFAASCAmEwggJdAgEAAoGBANMWIYduiQZt0B7s" + String PRIVATE_KEY = "MIICdwIBADANBgkqhkiG9w0BAQEFAASCAmEwggJdAgEAAoGBANMWIYduiQZt0B7s" +
"IZ6PW15gpcO7Yn+9ZbaMSHwzJqNeDAZzh6HXF7r0ZpQcw3XEWKPAPWyuJ5eqZf46" + "IZ6PW15gpcO7Yn+9ZbaMSHwzJqNeDAZzh6HXF7r0ZpQcw3XEWKPAPWyuJ5eqZf46" +
...@@ -23,6 +23,17 @@ public interface Constants { ...@@ -23,6 +23,17 @@ public interface Constants {
"CvwfHTyEgphcWrWDzB7bEqUDWiEjfO8sf+lwj9I0yU6fO/+aUtwU9xwkij1PscUF" + "CvwfHTyEgphcWrWDzB7bEqUDWiEjfO8sf+lwj9I0yU6fO/+aUtwU9xwkij1PscUF" +
"9AWUhbas+LG9mds="; "9AWUhbas+LG9mds=";
Integer GET_PRODUCT_TOKEN_FAIL_STATUS = 10086; Integer GET_PRODUCT_TOKEN_FAIL_STATUS = 10086;
String IMG_PREFIX = "https://aliyun-hz1.chewrobot.com";
String PRE_PRODUCT_IMG = "prod:";
String PRE_ENTER_PRODUCT = "enter";
String PRE_PRODUCT_PLAY = "我要玩";
interface PRODUCT_INTRO {
String CREATE_TIME = "发表时间: ";
String AUTHOR = "作者: ";
String LABEL = "相关标签: ";
String SPACE = " ";
}
interface SKILL_SECURITY { interface SKILL_SECURITY {
String REDIRECT_URI = "https://xiaodu.baidu.com/saiya/auth/3428011e7f55ec4c10b2da1b00a1675b"; String REDIRECT_URI = "https://xiaodu.baidu.com/saiya/auth/3428011e7f55ec4c10b2da1b00a1675b";
...@@ -32,8 +43,9 @@ public interface Constants { ...@@ -32,8 +43,9 @@ public interface Constants {
} }
interface WelcomeWord { interface WelcomeWord {
String WELCOME = "在这里你就是主角,开始你的星辰大海吧,请说推荐作品"; String WELCOME = "欢迎来到互动天地,这里有海量的作品在这等您";
String BEGIN_NO_RESPONSE = "咋还没开始就停住了,我们这里可有很多好玩的作品哦"; String BEGIN_NO_RESPONSE = "咋还没开始就停住了,我们这里可有很多好玩的作品哦";
String GUIDE_WORD = "请点击或者直接说出您想要玩的作品名";
} }
interface EndMsg { interface EndMsg {
......
...@@ -21,8 +21,9 @@ public class XiaoDuHomeController { ...@@ -21,8 +21,9 @@ public class XiaoDuHomeController {
public String chat() { public String chat() {
try { try {
DplBotService service = new DplBotService(Utils.getHttpServletRequest()); DplBotService service = new DplBotService(Utils.getHttpServletRequest());
log.info("请求信息:{}", service.getStrRequest()); //log.info("请求信息:{}", service.getStrRequest());
service.disableVerify(); //service.disableVerify();
service.enableVerify();
String str = service.run(); String str = service.run();
log.info("响应信息:{}", str); log.info("响应信息:{}", str);
return str; return str;
......
package ai.qiwu.com.xiaoduhome.entity;
import lombok.Getter;
import lombok.Setter;
import lombok.ToString;
import javax.persistence.*;
import java.util.Date;
/**
* @author 苗权威
* @dateTime 19-8-14 下午8:29
*/
@Entity
@Table(name = "game_project_tb")
@Getter
@Setter
@ToString
public class GameProjectTb {
@Id
@GeneratedValue
private Integer id;
@Column
private String intro;
@Column
private String name;
@Column
private Long watch;
@Column(name = "banner_img_url")
private String bannerImgUrl;
@Column(name = "apply_status")
private Integer applyStatus;
}
package ai.qiwu.com.xiaoduhome.entity;
import lombok.Getter;
import lombok.Setter;
import lombok.ToString;
import javax.persistence.*;
import java.util.Date;
import java.util.List;
/**
* @author 苗权威
* @dateTime 19-8-16 下午6:26
*/
@Entity
@Table(name = "game_project_tb")
@Getter
@Setter
@ToString
public class OnProductDetail {
@Id
@GeneratedValue
private Integer id;
@Column
private String intro;
@Column
private String name;
@Column
private Long watch;
@Column(name = "banner_img_url")
private String bannerImgUrl;
@Column(name = "apply_status")
private Integer applyStatus;
@Column(name = "gmt_create")
private Date createTime;
@Column(name = "user_nickname")
private String authorName;
@Transient
private List<String> labels;
}
package ai.qiwu.com.xiaoduhome.entity;
import lombok.Getter;
import lombok.Setter;
import lombok.ToString;
import javax.persistence.*;
/**
* @author 苗权威
* @dateTime 19-8-15 下午3:55
*/
@Entity
@Table(name = "game_project_label_tb")
@Getter
@Setter
@ToString
public class ProjectLabel {
@Id
@GeneratedValue
private Integer id;
@Column
private String name;
@Column(name = "project_id")
private String productId;
}
package ai.qiwu.com.xiaoduhome.pojo;
import com.baidu.dueros.data.response.directive.dpl.ExecuteCommands;
import com.baidu.dueros.data.response.directive.dpl.commands.BaseCommand;
import com.fasterxml.jackson.annotation.JsonIgnoreProperties;
import lombok.Getter;
import lombok.Setter;
import java.util.ArrayList;
import java.util.List;
/**
* @author 苗权威
* @dateTime 19-8-10 下午6:24
*/
@JsonIgnoreProperties(
ignoreUnknown = true
)
@Getter
@Setter
public class MyParallelCommand extends BaseCommand {
private long delayInMilliseconds;
private List<BaseCommand> commands = new ArrayList<>();
public MyParallelCommand() {
super("Parallel");
}
public MyParallelCommand addCommand(BaseCommand command) {
this.commands.add(command);
return this;
}
}
package ai.qiwu.baidu.xiaodu.pojo.dpl; package ai.qiwu.com.xiaoduhome.pojo;
import lombok.Getter; import lombok.Getter;
import lombok.Setter; import lombok.Setter;
import lombok.ToString; import lombok.ToString;
import java.util.ArrayList;
import java.util.List; import java.util.List;
/** /**
* @author 苗权威 * @author 苗权威
* @dateTime 19-8-7 上午9:37 * @dateTime 19-8-16 下午8:15
*/ */
@Getter @Getter
@Setter @Setter
@ToString @ToString
public class MyMainTemplate { public class ProjectLabels {
private List<String> parameters = new ArrayList<>(); private String projectName;
private List<Item> items; private List<String> labels;
public MyMainTemplate() { public ProjectLabels(String projectName, List<String> labels) {
this.parameters.add("payload"); this.projectName = projectName;
this.items = new ArrayList<>(); this.labels = labels;
} }
} }
package ai.qiwu.com.xiaoduhome.pojo; package ai.qiwu.com.xiaoduhome.pojo;
import com.fasterxml.jackson.annotation.JsonIgnoreProperties;
import lombok.Getter; import lombok.Getter;
import lombok.Setter; import lombok.Setter;
import lombok.ToString; import lombok.ToString;
...@@ -7,7 +8,9 @@ import lombok.ToString; ...@@ -7,7 +8,9 @@ import lombok.ToString;
@Getter @Getter
@Setter @Setter
@ToString @ToString
@JsonIgnoreProperties(ignoreUnknown = true)
public class QiWuResponse { public class QiWuResponse {
private String audio; private String audio;
private String text; private String text;
private String length;
} }
package ai.qiwu.com.xiaoduhome.pojo.dpl;
import lombok.Getter;
import lombok.Setter;
import lombok.ToString;
/**
* @author 苗权威
* @dateTime 19-8-15 下午6:20
*/
@Getter
@Setter
@ToString
public class Data {
private String imageSrc;
private String imageName;
private String imageId;
public Data() {
}
public Data(String imageSrc, String imageName, String imageId) {
this.imageSrc = imageSrc;
this.imageName = imageName;
this.imageId = imageId;
}
}
package ai.qiwu.com.xiaoduhome.pojo.dpl; package ai.qiwu.com.xiaoduhome.pojo.dpl;
import com.fasterxml.jackson.databind.annotation.JsonSerialize;
import lombok.Getter; import lombok.Getter;
import lombok.Setter; import lombok.Setter;
import lombok.ToString; import lombok.ToString;
...@@ -11,7 +12,9 @@ import lombok.ToString; ...@@ -11,7 +12,9 @@ import lombok.ToString;
@Getter @Getter
@Setter @Setter
@ToString @ToString
@JsonSerialize(include = JsonSerialize.Inclusion.NON_NULL)
public class Event { public class Event {
private String type; private String type;
private String componentId; private String componentId;
private Integer durationInMillisecond;
} }
...@@ -19,6 +19,7 @@ import java.util.List; ...@@ -19,6 +19,7 @@ import java.util.List;
@JsonIgnoreProperties(ignoreUnknown = true) @JsonIgnoreProperties(ignoreUnknown = true)
@JsonSerialize(include = JsonSerialize.Inclusion.NON_NULL) @JsonSerialize(include = JsonSerialize.Inclusion.NON_NULL)
public class Item { public class Item {
private Integer duration;
private String type; private String type;
private String width; private String width;
private String height; private String height;
...@@ -44,6 +45,7 @@ public class Item { ...@@ -44,6 +45,7 @@ public class Item {
private Boolean autoPlay; private Boolean autoPlay;
private String audioType; private String audioType;
private List<Event> onClick;
private List<Event> onEnd; private List<Event> onEnd;
private List<Event> onPrepared; private List<Event> onPrepared;
private List<Event> onLoaded; private List<Event> onLoaded;
...@@ -61,6 +63,18 @@ public class Item { ...@@ -61,6 +63,18 @@ public class Item {
private String flexDirection; private String flexDirection;
@JsonProperty("font-size") @JsonProperty("font-size")
private String fontSize; private String fontSize;
@JsonProperty("font-style")
private String fontStyle;
private List<String> hints; private List<String> hints;
private String componentId; private String componentId;
private String direction;
@JsonProperty("border-radius")
private String borderRadius;
private List<Data> data;
private String headerTitle;
private Boolean hasBackIcon;
private String initialPage;
} }
package ai.qiwu.com.xiaoduhome.repository;
import ai.qiwu.com.xiaoduhome.entity.OnProductDetail;
import org.springframework.data.jpa.repository.JpaRepository;
import java.util.List;
/**
* @author 苗权威
* @dateTime 19-8-16 下午6:26
*/
public interface AllOnProductInfoRepository extends JpaRepository<OnProductDetail, Integer> {
List<OnProductDetail> findAllByApplyStatus(Integer applyStatus);
}
package ai.qiwu.com.xiaoduhome.repository;
import ai.qiwu.com.xiaoduhome.entity.GameProjectTb;
import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.data.jpa.repository.Query;
import org.springframework.data.repository.query.Param;
import java.util.List;
/**
* @author 苗权威
* @dateTime 19-8-14 下午9:05
*/
public interface GameProjectTbRepository extends JpaRepository<GameProjectTb, Integer> {
List<GameProjectTb> findFirst15ByApplyStatusOrderByWatchDesc(Integer applyStatus);
@Query(value = "select id,intro,name,watch,banner_img_url,apply_status from game_project_tb where apply_status = 1 and id >= (select floor(RAND()*(select MAX(id) from game_project_tb))) order by id limit 10", nativeQuery = true)
List<GameProjectTb> recommendList();
@Query(value = "select p.id,p.intro,p.name,p.watch,p.banner_img_url,p.apply_status from game_project_tb as p,game_project_label_tb as l where l.name= :category and p.id = l.project_id and p.apply_status=1", nativeQuery = true)
List<GameProjectTb> categoryProject(@Param("category") String category);
}
package ai.qiwu.com.xiaoduhome.repository;
import ai.qiwu.com.xiaoduhome.entity.ProjectLabel;
import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.data.jpa.repository.Query;
import org.springframework.data.repository.query.Param;
import java.util.List;
/**
* @author 苗权威
* @dateTime 19-8-15 下午4:03
*/
public interface ProjectLabelRepository extends JpaRepository<ProjectLabel, Integer> {
@Query(value = "SELECT name FROM game_project_label_tb WHERE project_id = :productId", nativeQuery = true)
List<String> productLabels(@Param("productId") Integer productId);
}
...@@ -5,6 +5,7 @@ import ai.qiwu.com.xiaoduhome.common.OkHttp3Utils; ...@@ -5,6 +5,7 @@ import ai.qiwu.com.xiaoduhome.common.OkHttp3Utils;
import ai.qiwu.com.xiaoduhome.pojo.QiWuRequest; import ai.qiwu.com.xiaoduhome.pojo.QiWuRequest;
import ai.qiwu.com.xiaoduhome.pojo.QiWuResponse; import ai.qiwu.com.xiaoduhome.pojo.QiWuResponse;
import com.alibaba.fastjson.JSON; import com.alibaba.fastjson.JSON;
import lombok.extern.slf4j.Slf4j;
import org.slf4j.Logger; import org.slf4j.Logger;
import org.slf4j.LoggerFactory; import org.slf4j.LoggerFactory;
...@@ -15,9 +16,10 @@ import java.util.HashMap; ...@@ -15,9 +16,10 @@ import java.util.HashMap;
* @author 苗权威 * @author 苗权威
* @dateTime 19-6-29 下午3:49 * @dateTime 19-6-29 下午3:49
*/ */
@Slf4j
class RequestTerminal { class RequestTerminal {
static QiWuResponse requestTerminate(String userId, String userWord) throws IOException { static QiWuResponse requestTerminate(String userWord, String userId) throws IOException {
QiWuRequest requestPojo = new QiWuRequest(); QiWuRequest requestPojo = new QiWuRequest();
requestPojo.setUser_id(userId); requestPojo.setUser_id(userId);
requestPojo.setAccess(Constants.SERVICE_NAME); requestPojo.setAccess(Constants.SERVICE_NAME);
...@@ -25,6 +27,7 @@ class RequestTerminal { ...@@ -25,6 +27,7 @@ class RequestTerminal {
String requestJsonStr = JSON.toJSONString(requestPojo); String requestJsonStr = JSON.toJSONString(requestPojo);
HashMap<String, String> headers = new HashMap<>(); HashMap<String, String> headers = new HashMap<>();
headers.put("Content-Type", "application/json;charset=utf-8"); headers.put("Content-Type", "application/json;charset=utf-8");
log.info("向小悟发送的请求信息:{}", requestJsonStr);
String resStr = OkHttp3Utils.doPostJsonStr(Constants.QI_WU_INTERFACE, headers, requestJsonStr); String resStr = OkHttp3Utils.doPostJsonStr(Constants.QI_WU_INTERFACE, headers, requestJsonStr);
return JSON.parseObject(resStr, QiWuResponse.class); return JSON.parseObject(resStr, QiWuResponse.class);
} }
......
package ai.qiwu.com.xiaoduhome.service;
import ai.qiwu.com.xiaoduhome.entity.GameProjectTb;
import ai.qiwu.com.xiaoduhome.entity.OnProductDetail;
import ai.qiwu.com.xiaoduhome.repository.AllOnProductInfoRepository;
import ai.qiwu.com.xiaoduhome.repository.GameProjectTbRepository;
import ai.qiwu.com.xiaoduhome.repository.ProjectLabelRepository;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.InitializingBean;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.concurrent.ConcurrentHashMap;
/**
* @author 苗权威
* @dateTime 19-8-14 下午8:56
*/
@Slf4j
@Component
public class ScheduleService implements InitializingBean {
static volatile List<GameProjectTb> RANKING_LIST = new ArrayList<>();
static volatile List<GameProjectTb> RECOMMEND_LIST = new ArrayList<>();
static volatile List<OnProductDetail> ALL_ON_PRODUCT = new ArrayList<>();
static final HashMap<String, OnProductDetail> PRODUCT_NAME_DETAIL = new HashMap<>();
//static final Map<String, List<String>> PRODUCT_LABELS = new HashMap<>();
private static final String[] CATEGORY = {"古风", "科幻", "占星", "恋爱", "灾难", "架空", "儿童", "经营", "冒险", "武侠"};
private static final ConcurrentHashMap<String, List<GameProjectTb>> CATEGORY_PRODUCT_LIST = new ConcurrentHashMap<>();
private final GameProjectTbRepository gameProjectTbRepository;
private final ProjectLabelRepository projectLabelRepository;
private final AllOnProductInfoRepository allOnProductInfoRepository;
@Autowired
public ScheduleService(GameProjectTbRepository gameProjectTbRepository,
ProjectLabelRepository projectLabelRepository, AllOnProductInfoRepository allOnProductInfoRepository) {
this.gameProjectTbRepository = gameProjectTbRepository;
this.projectLabelRepository = projectLabelRepository;
this.allOnProductInfoRepository = allOnProductInfoRepository;
}
@Scheduled(cron = "0 0 19 * * ?")
public void getRankingList() {
try {
new Thread(() -> {
RANKING_LIST = gameProjectTbRepository.findFirst15ByApplyStatusOrderByWatchDesc(1);
//log.info("排行榜:{}", RANKING_LIST);
}).start();
} catch (Exception e) {
log.error("更新排行榜出错:{}", e.getMessage());
}
}
@Scheduled(cron = "0 0 18 * * ?")
public void getRecommendList() {
try {
new Thread(() -> {
RECOMMEND_LIST = gameProjectTbRepository.recommendList();
//log.info("推荐:{}", RECOMMEND_LIST);
}).start();
} catch (Exception e) {
log.error("更新推荐页出错:{}", e.getMessage());
}
}
@Scheduled(cron = "0 0 17 * * ?")
public void getAllOnTableProductInfo() {
try {
new Thread(() -> {
ALL_ON_PRODUCT = allOnProductInfoRepository.findAllByApplyStatus(1);
for (OnProductDetail item : ALL_ON_PRODUCT) {
String productName = item.getName();
List<String> labels = projectLabelRepository.productLabels(item.getId());
//PRODUCT_LABELS.put(productName, labels);
item.setLabels(labels);
PRODUCT_NAME_DETAIL.put(productName, item);
}
//log.info("作品详细信息:{}", PRODUCT_NAME_DETAIL);
}).start();
} catch (Exception e) {
log.error("更新推荐页出错:{}", e.getMessage());
}
}
@Scheduled(cron = "0 0 1 ? * 7")
public void getProductList() {
try {
new Thread(() -> {
for (String category: CATEGORY) {
List<GameProjectTb> list = gameProjectTbRepository.categoryProject(category);
CATEGORY_PRODUCT_LIST.put(category, list);
log.info("分类{},作品列表{}", category, list);
}
}).start();
} catch (Exception e) {
log.error("更新分类作品列表出错:{}", e.getMessage());
}
}
@Override
public void afterPropertiesSet() throws Exception {
getAllOnTableProductInfo();
getRecommendList();
getRankingList();
getProductList();
}
}
server:
port: 8088
spring:
datasource:
username: root
password: 3g9^pWQs#ft7
driver-class-name: com.mysql.cj.jdbc.Driver
url: jdbc:mysql://localhost:3306/game_editor_db?characterEncoding=utf-8
# username: root
# password: mysql
# driver-class-name: com.mysql.cj.jdbc.Driver
# url: jdbc:mysql://localhost:3306/TTS
jpa:
database: mysql
#控制台显示SQL
show-sql: true
hibernate:
ddl-auto: none
output:
ansi:
enabled: detect
\ No newline at end of file
...@@ -11,8 +11,27 @@ ...@@ -11,8 +11,27 @@
"width": "100%", "width": "100%",
"height": "100%", "height": "100%",
"componentId": "whole", "componentId": "whole",
"onLoaded": [
{
"type": "SendEvent",
"componentId": "whole"
}
],
"items": [ "items": [
{ {
"type": "Audio",
"componentId": "audio",
"looping": "false",
"autoplay": "false",
"onEnd": [
{
"type": "ControlMedia",
"componentId": "audio",
"command": "end"
}
]
},
{
"type": "Image", "type": "Image",
"position": "absolute", "position": "absolute",
"top": "0dp", "top": "0dp",
...@@ -22,18 +41,6 @@ ...@@ -22,18 +41,6 @@
"src": "https://duerstatic.bj.bcebos.com/dbp-image%2FDPLMaterial%2Fimage2019-6-24_19-8-392.jpg" "src": "https://duerstatic.bj.bcebos.com/dbp-image%2FDPLMaterial%2Fimage2019-6-24_19-8-392.jpg"
}, },
{ {
"type": "Audio",
"componentId": "audio",
"looping": "false",
"autoplay": "true",
"onEnd":[
{
"type":"SendEvent",
"componentId": "audio"
}
]
},
{
"type": "Container", "type": "Container",
"width": "100%", "width": "100%",
"height": "100%", "height": "100%",
......
{
"type": "DPL",
"version": "1.0",
"mainTemplate": {
"parameters": [
"payload"
],
"items": [
{
"type": "Image",
"position": "absolute",
"left": "0dp",
"top": "0dp",
"src": "https://aliyun-hz1.chewrobot.com/xiaoduhome/image/Loading.png",
"height": "100%",
"width": "100%"
},
{
"type": "Header",
"headerImage": "https://aliyun-hz1.chewrobot.com/xiaodu/image/5b2d0a11/lvzhou/15640330891628686.jpg",
"headerTitle": "交游天下"
},
{
"type": "Container",
"height": "100%",
"width": "100%",
"margin-top": "65dp",
"componentId": "whole",
"items": [
{
"type": "List",
"height": "100%",
"width": "100%",
"direction": "horizontal",
"items": [
{
"type": "Container",
"margin-left": "30dp",
"items": [
{
"type": "Image",
"componentId": "${data.imageId}",
"width": "260dp",
"height": "260dp",
"border-radius": "5%",
"src": "${data.imageSrc}",
"onClick": [
{
"type": "SendEvent",
"componentId": "${data.imageId}"
}
]
},
{
"type": "Text",
"font-size": "30dp",
"letter-spacing": "3dp",
"margin-top": "10dp",
"text": "${data.imageName}"
}
]
}
]
}
]
}
]
}
}
\ No newline at end of file
...@@ -7,81 +7,86 @@ ...@@ -7,81 +7,86 @@
], ],
"items": [ "items": [
{ {
"type": "Container", "type": "Pager",
"width": "100%", "direction": "horizontal",
"height": "100%", "height": "100%",
"width": "100%",
"initialPage":"0",
"componentId": "whole", "componentId": "whole",
"items": [ "items": [
{ {
"type": "Image", "type": "Image",
"componentId": "load",
"position": "absolute", "position": "absolute",
"top": "0dp", "top": "0dp",
"left": "0dp", "left": "0dp",
"src": "https://aliyun-hz1.chewrobot.com/xiaoduhome/image/Loading.png",
"height": "100%", "height": "100%",
"width": "100%", "width": "100%"
"src": "https://duerstatic.bj.bcebos.com/dbp-image%2FDPLMaterial%2Fimage2019-6-24_19-8-392.jpg"
}, },
{ {
"type": "Container", "type": "Container",
"width": "100%",
"height": "100%", "height": "100%",
"width": "100%",
"componentId": "second",
"items": [ "items": [
{ {
"type": "Image",
"position": "absolute",
"left": "0dp",
"opacity": "0.5",
"top": "0dp",
"src": "https://aliyun-hz1.chewrobot.com/xiaoduhome/image/backend.jpg",
"height": "100%",
"width": "100%"
},
{
"type": "Header", "type": "Header",
"headerImage": "https://aliyun-hz1.chewrobot.com/xiaodu/image/5b2d0a11/lvzhou/15640330891628686.jpg" "headerImage": "https://aliyun-hz1.chewrobot.com/xiaodu/image/5b2d0a11/lvzhou/15640330891628686.jpg",
"headerTitle": "交游天下"
}, },
{ {
"type": "Container", "type": "Container",
"flex-direction": "row", "height": "100%",
"width": "100%", "width": "100%",
"margin-top": "65dp",
"items": [
{
"type": "List",
"height": "100%", "height": "100%",
"width": "100%",
"direction": "horizontal",
"items": [ "items": [
{ {
"type": "Container", "type": "Container",
"width": "65%", "margin-left": "30dp",
"height": "100%",
"items": [ "items": [
{ {
"type": "Text", "type": "Image",
"text": "互动天地", "componentId": "onLunchImageClick",
"color": "blue", "width": "220dp",
"font-size": "35dp", "height": "220dp",
"letter-spacing": "30dp", "border-radius": "10dp",
"margin-top": "30dp", "src": "${data.imageSrc}",
"margin-left": "10%" "scale-type": "fitXY",
}, "onClick": [
{ {
"type": "Text", "type": "SendEvent",
"text": "有声互动小说", "componentId": "${data.imageId}"
"font-size": "25dp", }
"letter-spacing": "30dp", ]
"margin-top": "20dp",
"margin-left": "10%"
}, },
{ {
"type": "Text", "type": "Text",
"text": "欢迎来到互动天地",
"font-size": "30dp", "font-size": "30dp",
"letter-spacing": "30dp", "letter-spacing": "3dp",
"margin-top": "20dp", "margin-top": "10dp",
"margin-left": "10%" "text": "${data.imageName}"
} }
] ]
},
{
"type": "Image",
"height": "400dp",
"width": "280dp",
"margin-left": "10dp",
"margin-top": "30dp",
"src": "https://aliyun-hz1.chewrobot.com/xiaoduhome/image/cat.jpg"
} }
] ]
}, }
{
"type": "Footer",
"hints": [
"有什么好玩的码?","推荐作品","我要玩绿洲"
] ]
} }
] ]
......
{
"type": "DPL",
"version": "1.0",
"mainTemplate": {
"parameters": [
"payload"
],
"items": [
{
"type": "Container",
"height": "100%",
"width": "100%",
"componentId": "whole",
"items": [
{
"type": "Image",
"position": "absolute",
"top": "0dp",
"left": "0dp",
"opacity":"0.4",
"src": "https://aliyun-hz1.chewrobot.com/xiaoduhome/image/backend.jpg",
"height": "100%",
"width": "100%"
},
{
"type": "Container",
"width": "100%",
"height": "100%",
"items": [
{
"type": "Header",
"headerTitle": "交游天下",
"headerImage": "https://aliyun-hz1.chewrobot.com/xiaodu/image/5b2d0a11/lvzhou/15640330891628686.jpg",
"hasBackIcon": true
},
{
"type": "Container",
"height": "80%",
"width": "90%",
"margin-left": "5%",
"margin-top": "5%",
"items": [
{
"type": "Text",
"font-size": "45dp",
"font-style": "normal",
"letter-spacing": "3dp"
}
]
}
]
},
{
"type": "Audio",
"componentId": "audio",
"looping": "false",
"autoplay": "true",
"onPrepared": [
{
"type": "SendEvent",
"componentId": "audio"
}
]
}
]
}
]
}
}
\ No newline at end of file
{
"type": "DPL",
"version": "1.0",
"mainTemplate": {
"parameters": [
"payload"
],
"items": [
{
"type": "Container",
"width": "100%",
"height": "100%",
"componentId": "whole",
"onClick": [
{
"type": "SendEvent"
}
],
"items": [
{
"type": "Image",
"height": "100%",
"width": "100%",
"opacity":"0.4",
"position": "absolute",
"left": "0dp",
"top": "0dp",
"src": "https://aliyun-hz1.chewrobot.com/xiaoduhome/image/backend.jpg"
},
{
"type": "Container",
"width": "100%",
"height": "100%",
"items": [
{
"type": "Header",
"headerImage": "https://skillstore.cdn.bcebos.com/icon/23/fc7581b7-b505-1f44-ab52-3d9f5e567dfd.png"
},
{
"type": "Container",
"flex-direction": "row",
"width": "100%",
"height": "100%",
"items": [
{
"type": "Image",
"margin-top": "5%",
"height": "400dp",
"width": "380dp",
"scale-type": "fitCenter",
"margin-left": "35dp"
},
{
"type": "Container",
"margin-top": "7%",
"width": "65%",
"height": "100%",
"items": [
{
"type": "Text",
"font-size": "30dp",
"letter-spacing": "10dp",
"margin-left": "7%"
},
{
"type": "Container",
"padding-top": "2%",
"flex-direction":"row",
"items":[
{
"type": "Text",
"text": "发表时间:2019.5.8",
"font-size": "22dp",
"letter-spacing": "4dp",
"margin-left": "7%"
},
{
"type": "Text",
"text": "作者:小艾",
"font-size": "22dp",
"letter-spacing": "4dp",
"margin-left": "7%"
}
]
},
{
"type": "Container",
"padding-top": "2%",
"flex-direction":"row",
"items":[
{
"type": "Text",
"text": "相关标签: 都市 社会 生活",
"font-size": "26dp",
"letter-spacing": "4dp",
"margin-left": "7%"
}
]
},
{
"type": "Text",
"font-size": "25dp",
"letter-spacing": "4dp",
"margin-top": "30dp",
"margin-left": "7%"
},
{
"type": "Container",
"flex-direction": "row",
"width": "100%",
"height": "100%",
"items": [
{
"type": "Container",
"items": [
{
"type": "Image",
"height": "30dp",
"width": "30dp",
"src": "https://aliyun-hz1.chewrobot.com/xiaoduhome/image/feel.png",
"scale-type": "fitCenter"
},
{
"type": "Text",
"text": "开始体验",
"font-size": "10dp",
"letter-spacing": "2dp"
}
]
},
{
"type": "Container",
"items": [
{
"type": "Image",
"height": "30dp",
"width": "30dp",
"src": "https://aliyun-hz1.chewrobot.com/xiaoduhome/image/flower.png",
"scale-type": "fitCenter"
},
{
"type": "Text",
"text": "打赏鲜花",
"font-size": "10dp",
"letter-spacing": "2dp"
}
]
},
{
"type": "Container",
"items": [
{
"type": "Image",
"height": "30dp",
"width": "30dp",
"src": "https://aliyun-hz1.chewrobot.com/xiaoduhome/image/share.png",
"scale-type": "fitCenter"
},
{
"type": "Text",
"text": "分享",
"font-size": "10dp",
"letter-spacing": "2dp"
}
]
}
]
}
]
}
]
},
{
"type": "Footer"
}
]
}
]
}
]
}
}
\ 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